@bigduu/lotus 2026.5.1 → 2026.5.4

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 (66) hide show
  1. package/dist/assets/App-CIBUzKFV.js +254 -0
  2. package/dist/assets/{App-B5iMQtsl.css → App-DJeBpzcc.css} +1 -1
  3. package/dist/assets/{_baseUniq-JxvxITJ4.js → _baseUniq-C-LHgpwK.js} +1 -1
  4. package/dist/assets/{architectureDiagram-Q4EWVU46-BtLEHHTC.js → architectureDiagram-Q4EWVU46-knT7SmxI.js} +1 -1
  5. package/dist/assets/{blockDiagram-DXYQGD6D-VCIl5oVL.js → blockDiagram-DXYQGD6D-B9y1uS9R.js} +1 -1
  6. package/dist/assets/{c4Diagram-AHTNJAMY-sxcrRtSC.js → c4Diagram-AHTNJAMY-BRoJcx0b.js} +1 -1
  7. package/dist/assets/{chunk-4BX2VUAB-cdpbCefI.js → chunk-4BX2VUAB-Dg65rhkh.js} +1 -1
  8. package/dist/assets/{chunk-4TB4RGXK-6y4jkX8O.js → chunk-4TB4RGXK-D95yqR9H.js} +1 -1
  9. package/dist/assets/{chunk-55IACEB6-zGTUbgou.js → chunk-55IACEB6-CUbVVgja.js} +1 -1
  10. package/dist/assets/{chunk-EDXVE4YY-CPKsbfnW.js → chunk-EDXVE4YY-B_pb0EHW.js} +1 -1
  11. package/dist/assets/{chunk-FMBD7UC4-u1fsHgLk.js → chunk-FMBD7UC4-B0r7CE0W.js} +1 -1
  12. package/dist/assets/{chunk-OYMX7WX6-B_juGEzU.js → chunk-OYMX7WX6-2_Im5UU8.js} +1 -1
  13. package/dist/assets/{chunk-QZHKN3VN-Cziuusiz.js → chunk-QZHKN3VN-DbGqS_ab.js} +1 -1
  14. package/dist/assets/{chunk-YZCP3GAM-SnPgbijx.js → chunk-YZCP3GAM-DdAJ9t55.js} +1 -1
  15. package/dist/assets/classDiagram-6PBFFD2Q-hQqJj1FL.js +1 -0
  16. package/dist/assets/classDiagram-v2-HSJHXN6E-hQqJj1FL.js +1 -0
  17. package/dist/assets/clone-BnNFRj9O.js +1 -0
  18. package/dist/assets/{cose-bilkent-S5V4N54A-DP12PpvR.js → cose-bilkent-S5V4N54A-BDxVvsWm.js} +1 -1
  19. package/dist/assets/{dagre-KV5264BT-BWrJEOJE.js → dagre-KV5264BT-vzGZtZ_w.js} +1 -1
  20. package/dist/assets/{diagram-5BDNPKRD-B3Ag_nwx.js → diagram-5BDNPKRD-CGYBSS7a.js} +1 -1
  21. package/dist/assets/{diagram-G4DWMVQ6-CU5AAMtk.js → diagram-G4DWMVQ6-DBeNrz6n.js} +1 -1
  22. package/dist/assets/{diagram-MMDJMWI5-0jeeksm5.js → diagram-MMDJMWI5-CCt9wdnx.js} +1 -1
  23. package/dist/assets/{diagram-TYMM5635-B8Te0NTK.js → diagram-TYMM5635-B-q2z4os.js} +1 -1
  24. package/dist/assets/{erDiagram-SMLLAGMA-DgZehpcF.js → erDiagram-SMLLAGMA-DFjajcpE.js} +1 -1
  25. package/dist/assets/{flowDiagram-DWJPFMVM-DME4sy3r.js → flowDiagram-DWJPFMVM-CmdYRxD2.js} +1 -1
  26. package/dist/assets/{ganttDiagram-T4ZO3ILL-4VUoDKDN.js → ganttDiagram-T4ZO3ILL-BdeV_JQv.js} +1 -1
  27. package/dist/assets/{gitGraphDiagram-UUTBAWPF-M9eA0knu.js → gitGraphDiagram-UUTBAWPF-Bv1bpmVh.js} +1 -1
  28. package/dist/assets/{graph-Dl52eM4Z.js → graph-BZhdALnM.js} +1 -1
  29. package/dist/assets/{index-D839lRZb.js → index-8MhLoQym.js} +1 -1
  30. package/dist/assets/{index-BrpQmT5J.js → index-BR-Jz13T.js} +1 -1
  31. package/dist/assets/{index-BNcuFl0J.js → index-Byt6VrzO.js} +1 -1
  32. package/dist/assets/{index-BAibvIVz.js → index-CTVpEC_u.js} +1 -1
  33. package/dist/assets/{index-DjUMzvjR.js → index-jIgpBMFj.js} +1 -1
  34. package/dist/assets/{index.es-DYgOq-7b.js → index.es-Cn1_mau_.js} +1 -1
  35. package/dist/assets/{infoDiagram-42DDH7IO-DSE-8cVU.js → infoDiagram-42DDH7IO-COrckp6q.js} +1 -1
  36. package/dist/assets/{ishikawaDiagram-UXIWVN3A-CZdup7Ia.js → ishikawaDiagram-UXIWVN3A-mjLLHcYj.js} +1 -1
  37. package/dist/assets/{journeyDiagram-VCZTEJTY-DApltPSo.js → journeyDiagram-VCZTEJTY-DKAns2QR.js} +1 -1
  38. package/dist/assets/{kanban-definition-6JOO6SKY-ClF33MZ9.js → kanban-definition-6JOO6SKY-_8RYarrG.js} +1 -1
  39. package/dist/assets/{layout-Cc6oxhrd.js → layout-BJQnEdOR.js} +1 -1
  40. package/dist/assets/{main-tzCacohH.js → main-_fs1sZGu.js} +5 -5
  41. package/dist/assets/{min-CRXMcNks.js → min-CEPPgGqS.js} +1 -1
  42. package/dist/assets/{mindmap-definition-QFDTVHPH-Cp5dCq5F.js → mindmap-definition-QFDTVHPH-B8Fqmn2S.js} +1 -1
  43. package/dist/assets/{pieDiagram-DEJITSTG-xwiGZjCh.js → pieDiagram-DEJITSTG-BCklzk2d.js} +1 -1
  44. package/dist/assets/{quadrantDiagram-34T5L4WZ-DYFzLdJ_.js → quadrantDiagram-34T5L4WZ-ea-ItGVk.js} +1 -1
  45. package/dist/assets/{requirementDiagram-MS252O5E-CcTppyOC.js → requirementDiagram-MS252O5E-DoJ6ZjPU.js} +1 -1
  46. package/dist/assets/{sankeyDiagram-XADWPNL6-BidnGUTn.js → sankeyDiagram-XADWPNL6-CtYEK_8E.js} +1 -1
  47. package/dist/assets/{sequenceDiagram-FGHM5R23-BGNLJ-kB.js → sequenceDiagram-FGHM5R23-CnFMNFdv.js} +1 -1
  48. package/dist/assets/{stateDiagram-FHFEXIEX-DaT9haW6.js → stateDiagram-FHFEXIEX-B_kOGWb-.js} +1 -1
  49. package/dist/assets/stateDiagram-v2-QKLJ7IA2-DL6DUSmq.js +1 -0
  50. package/dist/assets/{timeline-definition-GMOUNBTQ-B7UYx32z.js → timeline-definition-GMOUNBTQ-Dgx0wfE4.js} +1 -1
  51. package/dist/assets/{vendor-antd-Dvkx9eba.js → vendor-antd-BpW-8RO2.js} +1 -1
  52. package/dist/assets/{vendor-charts-DHCOhRb3.js → vendor-charts-fIPNnfk-.js} +1 -1
  53. package/dist/assets/{vendor-markdown-DrUBuQ-c.js → vendor-markdown-yOmFo5hK.js} +1 -1
  54. package/dist/assets/{vendor-mermaid-BAz0MwVj.js → vendor-mermaid-DA4JIJaA.js} +4 -4
  55. package/dist/assets/{vendor-pdf-wx1tMujY.js → vendor-pdf-xt0MLWhy.js} +4 -4
  56. package/dist/assets/{vennDiagram-DHZGUBPP-DbgCCrwc.js → vennDiagram-DHZGUBPP-DcJGrLhu.js} +1 -1
  57. package/dist/assets/{wardley-RL74JXVD-BeMJefeY.js → wardley-RL74JXVD-DIGH9Gor.js} +1 -1
  58. package/dist/assets/{wardleyDiagram-NUSXRM2D-CfibirQl.js → wardleyDiagram-NUSXRM2D-CMAuUksM.js} +1 -1
  59. package/dist/assets/{xychartDiagram-5P7HB3ND-OkJekxIp.js → xychartDiagram-5P7HB3ND-B4_9m2II.js} +1 -1
  60. package/dist/index.html +3 -3
  61. package/package.json +3 -1
  62. package/dist/assets/App-rmb4U246.js +0 -248
  63. package/dist/assets/classDiagram-6PBFFD2Q-8WbR2T8d.js +0 -1
  64. package/dist/assets/classDiagram-v2-HSJHXN6E-8WbR2T8d.js +0 -1
  65. package/dist/assets/clone-BzHXtWgJ.js +0 -1
  66. package/dist/assets/stateDiagram-v2-QKLJ7IA2-CIjRWULt.js +0 -1
@@ -0,0 +1,254 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-8MhLoQym.js","./vendor-markdown-yOmFo5hK.js","./vendor-i18n-BNURlJ23.js","./vendor-antd-BpW-8RO2.js","./main-_fs1sZGu.js","./main-B6snAd4S.css","./vendor-charts-fIPNnfk-.js","./vendor-mermaid-DA4JIJaA.js","./index-CTVpEC_u.js","./index-jIgpBMFj.js","./index-Bi-vGirQ.css","./index-BR-Jz13T.js","./index-Byt6VrzO.js","./index-BmjFP0ha.js","./core-Cfh-QHsP.js","./index-_XI0Qq6F.js","./vendor-pdf-xt0MLWhy.js"])))=>i.map(i=>d[i]);
2
+ var Lw=Object.defineProperty;var Fw=(e,t,n)=>t in e?Lw(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var jt=(e,t,n)=>Fw(e,typeof t!="symbol"?t+"":t,n);import{j as o,M as Es,r as Fc,h as Bo,_ as Bn,S as gn,a as pb,t as gb,p as yb,b as Nw,c as Cm,d as zw,m as bb,s as Bw,y as xb,e as vb,f as Mm,g as Pm,i as Sb}from"./vendor-markdown-yOmFo5hK.js";import{a as f,R as pn,i as bs,c as Ww,g as po,u as Ae}from"./vendor-i18n-BNURlJ23.js";import{r as qw,A as Uw}from"./main-_fs1sZGu.js";import{S as he,B as de,C as Ce,m as Ke,L as Qt,Y as xs,T as Ne,Z as Hw,$ as Nc,a0 as vs,a1 as Cr,M as Xn,E as Mn,a2 as Ui,t as Qe,a3 as Eu,a4 as Em,j as Hi,O as io,a5 as wb,a6 as Kw,k as Mr,H as Yw,o as Ho,a7 as lo,a8 as Vw,I as et,K as ve,a9 as Gn,aa as Vs,i as or,ab as Ki,n as bt,ac as Xw,ad as Gw,A as en,ae as _b,af as $i,ag as Jw,ah as zc,p as Ht,F as Pe,v as Rs,ai as Di,aj as St,ak as ln,al as fs,am as Et,an as Kn,ao as Zt,ap as Qw,V as zn,aq as lr,ar as Zw,as as Rm,P as fc,at as Yi,au as kb,av as Bc,aw as cf,ax as ar,u as cr,ay as e_,az as Wc,aA as Ru,aB as Fn,aC as t_,aD as dr,aE as sn,aF as Am,aG as df,Q as ir,aH as As,aI as pc,aJ as kl,aK as n_,aL as s_,G as r_,aM as so,aN as Tb,aO as uf,aP as Wo,aQ as o_,aR as a_,l as qo,aS as Im,U as Om,aT as i_,aU as l_,aV as jb,aW as $m,aX as Cb,aY as c_,aZ as d_,a_ as u_,a$ as m_,b0 as h_,b1 as f_,b2 as p_,b3 as Mb,b4 as Pb,x as Eb,q as gc,b5 as Dm,b6 as Rb,w as g_,b7 as y_,b8 as b_,N as x_,b9 as v_,ba as S_,bb as w_,bc as __,bd as Ab,be as k_,bf as T_,bg as j_,bh as Lm,bi as C_,bj as M_,bk as yc,bl as mf,bm as Ib,bn as hf,bo as P_,bp as E_,bq as R_,br as A_,bs as Ob,bt as I_,bu as O_,bv as ff,bw as pf}from"./vendor-antd-BpW-8RO2.js";import{Z as Ko,_ as Fm,$ as Vi,a0 as Xi,a1 as Gi,a2 as Yo,a3 as Nm,a4 as bc,a5 as $b,a6 as Lo,a7 as $_,a8 as D_,a9 as L_}from"./vendor-charts-fIPNnfk-.js";import{bc as zm}from"./vendor-mermaid-DA4JIJaA.js";function Db(e){const[t,n]=f.useState(()=>typeof window<"u"?window.matchMedia(e).matches:!1);return f.useEffect(()=>{if(typeof window>"u")return;const s=window.matchMedia(e);n(s.matches);const r=a=>{n(a.matches)};return s.addEventListener?s.addEventListener("change",r):s.addListener(r),()=>{s.removeEventListener?s.removeEventListener("change",r):s.removeListener(r)}},[e]),t}function Bm(){return Db("(max-width: 768px)")}const F_=({buttons:e,className:t,style:n,size:s="middle",align:r="right"})=>{const a={className:t,style:{width:"100%",justifyContent:r==="left"?"flex-start":r==="center"?"center":"flex-end",...n}};return o.jsx(he,{...a,children:e.map(i=>o.jsx(de,{type:i.type||"default",disabled:i.disabled,loading:i.loading,danger:i.danger,onClick:i.onClick,size:s,icon:i.icon,children:i.text},i.key))})},N_=(e,t)=>({key:"cancel",text:t||"Cancel",type:"default",onClick:e}),z_=(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}),gf=e=>{let t;const n=new Set,s=(u,m)=>{const p=typeof u=="function"?u(t):u;if(!Object.is(p,t)){const g=t;t=m??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(b=>b(t,g))}},r=()=>t,l={setState:s,getState:r,getInitialState:()=>c,subscribe:u=>(n.add(u),()=>n.delete(u))},c=t=e(s,r,l);return l},B_=e=>e?gf(e):gf,W_=e=>e;function q_(e,t=W_){const n=pn.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return pn.useDebugValue(n),n}const yf=e=>{const t=B_(e),n=s=>q_(t,s);return Object.assign(n,t),n},Pr=e=>e?yf(e):yf,bf={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},Li=new Map,Tl=e=>{const t=Li.get(e);return t?Object.fromEntries(Object.entries(t.stores).map(([n,s])=>[n,s.getState()])):{}},U_=(e,t,n)=>{if(e===void 0)return{type:"untracked",connection:t.connect(n)};const s=Li.get(n.name);if(s)return{type:"tracked",store:e,...s};const r={connection:t.connect(n),stores:{}};return Li.set(n.name,r),{type:"tracked",store:e,...r}},H_=(e,t)=>{if(t===void 0)return;const n=Li.get(e);n&&(delete n.stores[t],Object.keys(n.stores).length===0&&Li.delete(e))},K_=e=>{var t,n;if(!e)return;const s=e.split(`
3
+ `),r=s.findIndex(i=>i.includes("api.setState"));if(r<0)return;const a=((t=s[r+1])==null?void 0:t.trim())||"";return(n=/.+ (.+) .+/.exec(a))==null?void 0:n[1]},Y_=(e,t={})=>(n,s,r)=>{const{enabled:a,anonymousActionType:i,store:l,...c}=t;let u;try{u=(a??(bf?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!u)return e(n,s,r);const{connection:m,...p}=U_(l,u,c);let g=!0;r.setState=(x,k,j)=>{const w=n(x,k);if(!g)return w;const M=j===void 0?{type:i||K_(new Error().stack)||"anonymous"}:typeof j=="string"?{type:j}:j;return l===void 0?(m==null||m.send(M,s()),w):(m==null||m.send({...M,type:`${l}/${M.type}`},{...Tl(c.name),[l]:r.getState()}),w)},r.devtools={cleanup:()=>{m&&typeof m.unsubscribe=="function"&&m.unsubscribe(),H_(c.name,l)}};const b=(...x)=>{const k=g;g=!1,n(...x),g=k},S=e(r.setState,s,r);if(p.type==="untracked"?m==null||m.init(S):(p.stores[p.store]=r,m==null||m.init(Object.fromEntries(Object.entries(p.stores).map(([x,k])=>[x,x===p.store?S:k.getState()])))),r.dispatchFromDevtools&&typeof r.dispatch=="function"){let x=!1;const k=r.dispatch;r.dispatch=(...j)=>{(bf?"production":void 0)!=="production"&&j[0].type==="__setState"&&!x&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),x=!0),k(...j)}}return m.subscribe(x=>{var k;switch(x.type){case"ACTION":if(typeof x.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return Pd(x.payload,j=>{if(j.type==="__setState"){if(l===void 0){b(j.state);return}Object.keys(j.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 w=j.state[l];if(w==null)return;JSON.stringify(r.getState())!==JSON.stringify(w)&&b(w);return}r.dispatchFromDevtools&&typeof r.dispatch=="function"&&r.dispatch(j)});case"DISPATCH":switch(x.payload.type){case"RESET":return b(S),l===void 0?m==null?void 0:m.init(r.getState()):m==null?void 0:m.init(Tl(c.name));case"COMMIT":if(l===void 0){m==null||m.init(r.getState());return}return m==null?void 0:m.init(Tl(c.name));case"ROLLBACK":return Pd(x.state,j=>{if(l===void 0){b(j),m==null||m.init(r.getState());return}b(j[l]),m==null||m.init(Tl(c.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return Pd(x.state,j=>{if(l===void 0){b(j);return}JSON.stringify(r.getState())!==JSON.stringify(j[l])&&b(j[l])});case"IMPORT_STATE":{const{nextLiftedState:j}=x.payload,w=(k=j.computedStates.slice(-1)[0])==null?void 0:k.state;if(!w)return;b(l===void 0?w:w[l]),m==null||m.send(null,j);return}case"PAUSE_RECORDING":return g=!g}return}}),S},V_=Y_,Pd=(e,t)=>{let n;try{n=JSON.parse(e)}catch(s){console.error("[zustand devtools middleware] Could not parse the received json",s)}n!==void 0&&t(n)},X_=e=>(t,n,s)=>{const r=s.subscribe;return s.subscribe=(i,l,c)=>{let u=i;if(l){const m=(c==null?void 0:c.equalityFn)||Object.is;let p=i(s.getState());u=g=>{const b=i(g);if(!m(p,b)){const S=p;l(p=b,S)}},c!=null&&c.fireImmediately&&l(p,p)}return r(u)},e(t,n,s)},G_=X_;function J_(e,t){let n;try{n=e()}catch{return}return{getItem:r=>{var a;const i=c=>c===null?null:JSON.parse(c,void 0),l=(a=n.getItem(r))!=null?a:null;return l instanceof Promise?l.then(i):i(l)},setItem:(r,a)=>n.setItem(r,JSON.stringify(a,void 0)),removeItem:r=>n.removeItem(r)}}const Au=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(s){return Au(s)(n)},catch(s){return this}}}catch(n){return{then(s){return this},catch(s){return Au(s)(n)}}}},Q_=(e,t)=>(n,s,r)=>{let a={storage:J_(()=>localStorage),partialize:x=>x,version:0,merge:(x,k)=>({...k,...x}),...t},i=!1;const l=new Set,c=new Set;let u=a.storage;if(!u)return e((...x)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),n(...x)},s,r);const m=()=>{const x=a.partialize({...s()});return u.setItem(a.name,{state:x,version:a.version})},p=r.setState;r.setState=(x,k)=>{p(x,k),m()};const g=e((...x)=>{n(...x),m()},s,r);r.getInitialState=()=>g;let b;const S=()=>{var x,k;if(!u)return;i=!1,l.forEach(w=>{var M;return w((M=s())!=null?M:g)});const j=((k=a.onRehydrateStorage)==null?void 0:k.call(a,(x=s())!=null?x:g))||void 0;return Au(u.getItem.bind(u))(a.name).then(w=>{if(w)if(typeof w.version=="number"&&w.version!==a.version){if(a.migrate){const M=a.migrate(w.state,w.version);return M instanceof Promise?M.then(_=>[!0,_]):[!0,M]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,w.state];return[!1,void 0]}).then(w=>{var M;const[_,C]=w;if(b=a.merge(C,(M=s())!=null?M:g),n(b,!0),_)return m()}).then(()=>{j==null||j(b,void 0),b=s(),i=!0,c.forEach(w=>w(b))}).catch(w=>{j==null||j(void 0,w)})};return r.persist={setOptions:x=>{a={...a,...x},x.storage&&(u=x.storage)},clearStorage:()=>{u==null||u.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>S(),hasHydrated:()=>i,onHydrate:x=>(l.add(x),()=>{l.delete(x)}),onFinishHydration:x=>(c.add(x),()=>{c.delete(x)})},a.skipHydration||S(),b||g},Z_=Q_,Lb=()=>!1,Fb=e=>{if(!Lb())return!1;try{return localStorage.getItem(e)==="1"}catch{return!1}},e0=()=>Fb("bodhi_debug_ui_layout"),ps=(e,t)=>{e0()&&console.log(`[ui-layout] ${e}`,t??"")},Jt=(e,t,...n)=>{Lb()&&Fb("bodhi_debug_verbose")&&console.log(`${e} ${t}`,...n)};var Ed={};const Rd="copilot_backend_base_url",Nb="http://127.0.0.1:9562/v1",t0=9562,co=e=>e.trim().replace(/\/+$/,""),n0=()=>{const t=Ed==null?void 0:Ed.VITE_BACKEND_BASE_URL;return t?co(t):null},Ji=()=>{const e=globalThis.location;if(!e)return null;const t=typeof e.protocol=="string"?e.protocol:"",n=typeof e.hostname=="string"?e.hostname:"";return!t||!n?null:{protocol:t,hostname:n}},Wm=e=>{const t=e.trim().toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="::1"},s0=(e=Ji())=>(e==null?void 0:e.protocol.toLowerCase())==="https:",r0=e=>{try{return new URL(co(e)).protocol.toLowerCase()==="http:"}catch{return!1}},o0=e=>{try{const t=new URL(co(e));return Wm(t.hostname)}catch{return!1}},a0=(e=Ji())=>{if(!e)return null;const t=e.protocol.toLowerCase(),n=e.hostname.trim();return n?t==="https:"?co(`https://${n}/v1`):t==="http:"?co(`http://${n}/v1`):null:null},i0=(e,t=Ji())=>{if(!t)return!1;const n=t.hostname.trim();return n?s0(t)&&r0(e)?!0:Wm(n)?!1:o0(e):!1},l0=(e=Ji())=>{if(!e)return null;const t=e.protocol.toLowerCase();if(t!=="http:"&&t!=="https:")return null;const n=e.hostname.trim();return n?t==="https:"?a0(e):Wm(n)?Nb:co(`http://${n}:${t0}/v1`):null},c0=()=>{const e=n0();return e||(l0()??Nb)},Vo=()=>{const e=Ji(),t=localStorage.getItem(Rd);if(t){const n=co(t);if(i0(n,e))console.warn("Ignoring stored backend override because it is incompatible with the current page origin:",n),localStorage.removeItem(Rd);else try{return new URL(n),n}catch{console.warn("Invalid stored backend URL, using default:",n),localStorage.removeItem(Rd)}}return c0()};class uo extends Error{constructor(t,n,s,r){super(t),this.status=n,this.statusText=s,this.body=r,this.name="ApiError"}}function d0(e){return e instanceof uo}class qm{constructor(t={}){jt(this,"baseUrl");jt(this,"defaultHeaders");this.baseUrl=t.baseUrl??this.resolveBaseUrl(),this.defaultHeaders=t.defaultHeaders??{"Content-Type":"application/json"}}resolveBaseUrl(){const t=Vo().trim().replace(/\/+$/,"");return t.endsWith("/v1")?t:`${t}/v1`}buildUrl(t){const n=t.replace(/^\/+/,"");return`${this.baseUrl}/${n}`}async handleResponse(t){var s,r,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"?(s=c.error)==null?void 0:s.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 uo(l,t.status,t.statusText,i)}return t.status===204?void 0:(((a=(r=t.headers)==null?void 0:r.get)==null?void 0:a.call(r,"content-type"))||"").includes("application/json")?t.json():typeof t.text=="function"?await t.text():t.json()}delay(t){return new Promise(n=>setTimeout(n,t))}async fetchWithRetry(t,n,s=3){let r=null;for(let a=0;a<s;a++)try{const i=await fetch(t,n);if(i.status>=500&&a<s-1){const l=1e3*Math.pow(2,a);console.warn(`Request failed with ${i.status}, retrying in ${l}ms (attempt ${a+1}/${s})`),await this.delay(l);continue}return i}catch(i){if(r=i,a<s-1){const l=1e3*Math.pow(2,a);console.warn(`Network error: ${r.message}, retrying in ${l}ms (attempt ${a+1}/${s})`),await this.delay(l)}}throw r||new Error("Max retries exceeded")}async get(t,n){const s=this.buildUrl(t),r=new AbortController,a=setTimeout(()=>r.abort(),3e4);try{const i=await this.fetchWithRetry(s,{...n,method:"GET",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",signal:r.signal},3);return this.handleResponse(i)}finally{clearTimeout(a)}}async post(t,n,s){const r=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(r,{...s,method:"POST",headers:{...this.defaultHeaders,...s==null?void 0:s.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async put(t,n,s){const r=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(r,{...s,method:"PUT",headers:{...this.defaultHeaders,...s==null?void 0:s.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async patch(t,n,s){const r=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(r,{...s,method:"PATCH",headers:{...this.defaultHeaders,...s==null?void 0:s.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async delete(t,n){const s=this.buildUrl(t),r=new AbortController,a=setTimeout(()=>r.abort(),3e4);try{const i=await this.fetchWithRetry(s,{...n,method:"DELETE",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",signal:r.signal},3);return this.handleResponse(i)}finally{clearTimeout(a)}}async request(t,n,s){const r=this.buildUrl(n),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(r,{...s,method:t,headers:{...this.defaultHeaders,...s==null?void 0:s.headers},credentials:"include",signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async fetchRaw(t,n){const s=this.buildUrl(t),r=await fetch(s,{...n,headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include"});if(!r.ok)throw new uo(`API request failed: ${r.statusText}`,r.status,r.statusText);return r}}const at=new qm,nt=new qm({baseUrl:(()=>{let e=Vo().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`})()});function u0(e){return e instanceof uo}const Gr=class Gr{static getInstance(){return Gr.instance||(Gr.instance=new Gr),Gr.instance}async sendMessage(t){return nt.post("chat",t)}async execute(t,n,s,r,a){const i={};return n&&(i.model=n),s&&(i.reasoning_effort=s),r&&(i.client_sync=r),a&&(i.model_ref=a,i.provider=a.provider),nt.post(`execute/${t}`,i)}async listSessions(){return nt.get("sessions")}async getTaskList(t){const n=encodeURIComponent(t),s=await nt.get(`task/${n}`);if(!(typeof s.title=="string"||s.items.length>0))return null;const a=new Date().toISOString();return{session_id:s.session_id,title:s.title??"Task List",items:s.items,created_at:a,updated_at:a}}async createSession(t){return nt.post("sessions",t)}async patchSession(t,n){const s=encodeURIComponent(t);await nt.patch(`sessions/${s}`,n)}async getSessionSystemPrompt(t){const n=encodeURIComponent(t);return nt.get(`sessions/${n}/system-prompt`)}async clearSession(t){const n=encodeURIComponent(t);await nt.post(`sessions/${n}/clear`)}async runProjectDream(t){const n=encodeURIComponent(t);return nt.post(`sessions/${n}/project-dream/run`)}async truncateSessionMessages(t,n){const s=encodeURIComponent(t);return nt.post(`sessions/${s}/messages/truncate`,n)}async restoreSessionState(t,n){const s=encodeURIComponent(t);return nt.post(`sessions/${s}/restore`,n)}async patchSessionMessage(t,n,s){const r=encodeURIComponent(t),a=encodeURIComponent(n);await nt.patch(`sessions/${r}/messages/${a}`,s)}async deleteSessionMessage(t,n){const s=encodeURIComponent(t),r=encodeURIComponent(n);await nt.delete(`sessions/${s}/messages/${r}`)}async cleanupSessions(t,n){await nt.post("sessions/cleanup",{mode:t,keep_pinned:n})}async devResetSessions(){await nt.post("dev/reset")}async getRunningSessions(){return nt.get("runs/active")}async listSchedules(){return nt.get("schedules")}async createSchedule(t){return nt.post("schedules",t)}async patchSchedule(t,n){const s=encodeURIComponent(t);return nt.patch(`schedules/${s}`,n)}async deleteSchedule(t){const n=encodeURIComponent(t);await nt.delete(`schedules/${n}`)}async runScheduleNow(t){const n=encodeURIComponent(t);await nt.post(`schedules/${n}/run`)}async listScheduleSessions(t){const n=encodeURIComponent(t);return nt.get(`schedules/${n}/sessions`)}async listScheduleRuns(t){const n=encodeURIComponent(t);return nt.get(`schedules/${n}/runs`)}async subscribeToEvents(t,n,s){var a;const r=s==null?void 0:s.signal;Jt("[AgentClient]","[AgentClient] Subscribing to events for session:",t);try{const i=await nt.fetchRaw(`events/${t}`,{signal:r});if(Jt("[AgentClient]","[AgentClient] Events subscription response:",i.status,i.statusText,"Content-Type:",i.headers.get("content-type")),!i.ok){let m=`Failed to subscribe to events: ${i.statusText}`;try{const p=await i.text();if(p)try{const g=JSON.parse(p);m=g.error||g.message||g.detail||m}catch{m=p||m}}catch(p){console.error("Failed to parse error response:",p)}throw new Error(m)}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(;!(r!=null&&r.aborted);){const{done:m,value:p}=await l.read();if(m)break;u+=c.decode(p,{stream:!0});const g=u.split(`
8
+ `);u=g.pop()||"";for(const b of g)if(b.startsWith("data: ")){const S=b.slice(6);if(S==="[DONE]")return;try{const x=JSON.parse(S);this.handleEvent(x,n)}catch(x){console.warn("Failed to parse event:",S,x)}}}}finally{l.releaseLock()}}catch(i){if(r!=null&&r.aborted){Jt("[AgentClient]","Events subscription aborted for session:",t);return}throw console.error("[AgentClient] Events subscription error:",i),i}}handleEvent(t,n){var s,r,a,i,l,c,u,m,p,g,b,S,x,k,j,w,M,_,C,D,A,B,F,O,R;switch(t.type){case"token":(s=n.onToken)==null||s.call(n,t.content||"");break;case"reasoning_token":(r=n.onReasoningToken)==null||r.call(n,t.content||"");break;case"tool_token":(a=n.onToolToken)==null||a.call(n,t.tool_call_id||"",t.content||"");break;case"tool_start":(i=n.onToolStart)==null||i.call(n,t.tool_call_id||"",t.tool_name||"",t.arguments||{});break;case"tool_complete":t.result&&((l=n.onToolComplete)==null||l.call(n,t.tool_call_id||"",t.result));break;case"tool_error":(c=n.onToolError)==null||c.call(n,t.tool_call_id||"",t.error||"");break;case"task_list_updated":t.task_list&&((u=n.onTaskListUpdated)==null||u.call(n,t.task_list));break;case"task_list_item_progress":if(t.session_id&&t.item_id&&t.status&&t.tool_calls_count!==void 0&&t.version!==void 0){const I=t.status;if(!(I==="pending"||I==="in_progress"||I==="completed"||I==="blocked"))break;(m=n.onTaskListItemProgress)==null||m.call(n,{session_id:t.session_id,item_id:t.item_id,status:I,tool_calls_count:t.tool_calls_count,version:t.version})}break;case"task_list_completed":t.session_id&&t.total_rounds!==void 0&&t.total_tool_calls!==void 0&&((p=n.onTaskListCompleted)==null||p.call(n,t.session_id,t.total_rounds,t.total_tool_calls));break;case"task_evaluation_started":t.session_id&&t.items_count!==void 0&&((g=n.onTaskEvaluationStarted)==null||g.call(n,t.session_id,t.items_count));break;case"task_evaluation_completed":t.session_id&&t.updates_count!==void 0&&t.reasoning&&((b=n.onTaskEvaluationCompleted)==null||b.call(n,t.session_id,t.updates_count,t.reasoning));break;case"token_budget_updated":t.usage&&"system_tokens"in t.usage&&((S=n.onTokenBudgetUpdated)==null||S.call(n,t.usage));break;case"context_compression_status":typeof t.phase=="string"&&typeof t.status=="string"&&((x=n.onContextCompressionStatus)==null||x.call(n,t.phase,t.status));break;case"tool_lifecycle":(k=n.onToolLifecycle)==null||k.call(n,t.tool_call_id||"",t.tool_name||"",t.phase||"",t.elapsed_ms,t.is_mutating,t.auto_approved,t.summary,t.error);break;case"context_summarized":t.summary_info&&((j=n.onContextSummarized)==null||j.call(n,t.summary_info));break;case"context_pressure_notification":typeof t.percent=="number"&&typeof t.level=="string"&&((w=n.onContextPressureNotification)==null||w.call(n,t.percent,t.level,t.message||""));break;case"sub_session_started":t.parent_session_id&&t.child_session_id&&((M=n.onSubSessionStarted)==null||M.call(n,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&&((_=n.onSubSessionEvent)==null||_.call(n,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&&((C=n.onSubSessionHeartbeat)==null||C.call(n,t.parent_session_id,t.child_session_id,t.timestamp));break;case"sub_session_completed":t.parent_session_id&&t.child_session_id&&((D=n.onSubSessionCompleted)==null||D.call(n,t.parent_session_id,t.child_session_id,typeof t.status=="string"?t.status:"completed",t.error));break;case"execution_started":(A=n.onExecutionStarted)==null||A.call(n,t.run_id||"",t.started_at);break;case"runner_progress":t.session_id&&typeof t.round_count=="number"&&((B=n.onRunnerProgress)==null||B.call(n,t.session_id,t.round_count));break;case"need_clarification":(F=n.onNeedClarification)==null||F.call(n,t);break;case"complete":(O=n.onComplete)==null||O.call(n,t.usage);break;case"error":(R=n.onError)==null||R.call(n,t.message||t.error||"Unknown error");break;default:console.warn("Unknown event type:",t)}}async stopGeneration(t){await nt.post(`stop/${t}`)}async deleteSession(t){const n=encodeURIComponent(t);await nt.delete(`sessions/${n}`)}async getHistory(t){return nt.get(`history/${t}`)}async healthCheck(){try{return await nt.get("health"),!0}catch{return!1}}};jt(Gr,"instance");let os=Gr;const Fo=os.getInstance(),m0=()=>({id:"general_assistant",name:"Bodhi",description:bs.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}),xc=()=>[m0()];class h0{async getProviderConfig(){return at.get("/bamboo/settings/provider")}async saveProviderConfig(t){return at.post("/bamboo/settings/provider",t)}async reloadConfig(){return at.post("/bamboo/settings/reload")}async getCopilotAuthStatus(){return at.post("/bamboo/copilot/auth/status")}async startCopilotAuth(){return at.post("/bamboo/copilot/auth/start")}async completeCopilotAuth(t){return at.post("/bamboo/copilot/auth/complete",t)}async authenticateCopilot(){return at.post("/bamboo/copilot/authenticate")}async logoutCopilot(){return at.post("/bamboo/copilot/logout")}async fetchProviderModels(t){return(await at.post("/bamboo/settings/provider/models",{provider:t})).models}async getProviderCatalog(){return at.get("/bamboo/provider-catalog")}async fetchCatalogModels(t){const n=t?{provider:t}:{};return at.post("/bamboo/provider-catalog/fetch-models",n)}async getEnvVars(){return at.get("/bamboo/env-vars")}async upsertEnvVar(t){return at.post("/bamboo/env-vars",t)}async deleteEnvVar(t){return at.delete(`/bamboo/env-vars/${encodeURIComponent(t)}`)}async replaceEnvVars(t){return at.post("/bamboo/env-vars/replace",{entries:t})}}const Yn=new h0,Ct=Pr((e,t)=>({currentProvider:"copilot",providerConfig:{provider:"copilot",defaults:void 0,providers:{}},isLoading:!1,error:null,selectedModelRef:null,catalog:null,isCatalogFetching:!1,loadProviderConfig:async()=>{var n,s;e({isLoading:!0,error:null});try{const r=await Yn.getProviderConfig();if(!((s=(n=r.defaults)==null?void 0:n.chat)!=null&&s.model)&&r.provider&&r.providers){const a=r.provider,i=r.providers[a],l=i==null?void 0:i.model;l&&(r.defaults={chat:{provider:a,model:l}})}e({providerConfig:r,currentProvider:r.provider,isLoading:!1})}catch(r){console.error("Failed to load provider config:",r),e({error:r instanceof Error?r.message:"Failed to load provider config",isLoading:!1})}},setCurrentProvider:n=>{e({currentProvider:n})},updateProviderConfig:n=>{e(s=>({providerConfig:{...s.providerConfig,...n}}))},getActiveModel:()=>{var r,a,i;return((i=(a=(r=t().providerConfig.defaults)==null?void 0:r.chat)==null?void 0:a.model)==null?void 0:i.trim())||void 0},getFastModel:()=>{var r,a,i;const n=t();return((i=(a=(r=n.providerConfig.defaults)==null?void 0:r.fast)==null?void 0:a.model)==null?void 0:i.trim())||n.getActiveModel()},getVisionModel:()=>{var r,a,i;const n=t();return((i=(a=(r=n.providerConfig.defaults)==null?void 0:r.vision)==null?void 0:a.model)==null?void 0:i.trim())||n.getActiveModel()},isProviderModelRefEnabled:()=>!0,setSelectedModelRef:n=>{e({selectedModelRef:n})},loadCatalog:async()=>{try{const n=await Yn.getProviderCatalog();e({catalog:n})}catch{}},fetchCatalogModels:async n=>{e({isCatalogFetching:!0});try{await Yn.fetchCatalogModels(n),await t().loadCatalog()}catch{}finally{e({isCatalogFetching:!1})}},getFastModelRef:()=>{var a,i,l,c;const n=t(),s=(a=n.providerConfig.defaults)==null?void 0:a.fast;if((i=s==null?void 0:s.model)!=null&&i.trim())return s;const r=(l=n.providerConfig.defaults)==null?void 0:l.chat;return(c=r==null?void 0:r.model)!=null&&c.trim()?r:null},getVisionModelRef:()=>{var a,i,l,c;const n=t(),s=(a=n.providerConfig.defaults)==null?void 0:a.vision;if((i=s==null?void 0:s.model)!=null&&i.trim())return s;const r=(l=n.providerConfig.defaults)==null?void 0:l.chat;return(c=r==null?void 0:r.model)!=null&&c.trim()?r:null},getModelsForProvider:n=>{const{catalog:s}=t();return s!=null&&s.models?s.models.filter(r=>r.reference.provider===n):[]}})),f0=Object.freeze(Object.defineProperty({__proto__:null,useProviderStore:Ct},Symbol.toStringTag,{value:"Module"})),p0=5e3,xf=80,g0=16,Um=e=>e!==void 0&&e!=="idle"&&e!=="completed"&&e!=="error"&&e!=="cancelled",y0=e=>e==="starting"||e==="running"||e==="streaming"||e==="running_tools"||e==="running_children"||e==="settling",b0=e=>e==="starting"||e==="running"||e==="streaming"||e==="running_tools"||e==="running_children",zb=e=>({sessionId:e,phase:"idle",confidence:"optimistic",activeReasons:[],generation:0,backendRunId:null,stream:{hasTokens:!1,tokenCount:0,activeToolCalls:[],lastStatusHint:null},backend:{isRunning:!1,lastRunStatus:null,lastRunError:null,syncedAt:null,hasPendingQuestion:null,runningChildCount:null},interaction:{pendingQuestion:null,respondMode:null},children:{byId:{},runningCount:0},timestamps:{optimisticAt:null,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},error:null}),Dn=(e,t)=>e[t]??zb(t),Bt=(e,t)=>[...e.length>=g0?e.slice(-15):e,t],x0=e=>e.length<=xf?e:e.slice(e.length-xf),qc=new Set(["idle","completed","error","cancelled","settling","waiting_user_answer"]),Xo=e=>qc.has(e.phase)?e:e.children.runningCount>0?e.phase==="running_children"?e:{...e,phase:"running_children"}:e.stream.activeToolCalls.length>0?e.phase==="running_tools"?e:{...e,phase:"running_tools"}:e.stream.hasTokens?e.phase==="streaming"?e:{...e,phase:"streaming"}:e.phase==="running"?e:{...e,phase:"running"},mn=(e,t,n)=>({...e,[t]:n}),v0=(e,t)=>{if(!(t in e))return e;const n={...e};return delete n[t],n},vf=(e,t,n)=>{const s=e.timestamps.firstTokenAt??n(),r={...e,confidence:"live",stream:{...e.stream,hasTokens:!0,tokenCount:e.stream.tokenCount+1},timestamps:{...e.timestamps,firstTokenAt:s},activeReasons:Bt(e.activeReasons,t)};return Xo(r)},S0=(e,t,n,s)=>{const a=e.stream.activeToolCalls.findIndex(l=>l.toolCallId===t)>=0?e.stream.activeToolCalls:[...e.stream.activeToolCalls,{toolCallId:t,toolName:n,startedAt:s}],i={...e,confidence:"live",stream:{...e.stream,activeToolCalls:a},activeReasons:Bt(e.activeReasons,"sse:tool_start")};return Xo(i)},w0=(e,t,n)=>{const s=e.stream.activeToolCalls.findIndex(u=>u.toolCallId===t);if(s<0)return e;const r=e.stream.activeToolCalls[s],a=r.preview??"",i=x0(a+n),l={...r,preview:i},c=[...e.stream.activeToolCalls];return c[s]=l,{...e,stream:{...e.stream,activeToolCalls:c}}},_0=(e,t,n)=>{const s=e.stream.activeToolCalls.filter(a=>a.toolCallId!==t);if(s.length===e.stream.activeToolCalls.length)return e;const r={...e,stream:{...e.stream,activeToolCalls:s},activeReasons:Bt(e.activeReasons,n)};return r.timestamps.terminalAt&&r.children.runningCount===0&&r.stream.activeToolCalls.length===0&&!qc.has(r.phase)?{...r,phase:"settling",timestamps:{...r.timestamps,settlingStartedAt:r.timestamps.settlingStartedAt??r.timestamps.terminalAt}}:Xo(r)},Bb=(e,t,n)=>{const s=e.children.byId[t],r=s!==void 0&&(s.status===void 0||s.status==="running"),a={...s,...n,status:n.status??(s==null?void 0:s.status)??"running"},l=(a.status===void 0||a.status==="running"?1:0)-(r?1:0),c={...e,confidence:"live",children:{byId:{...e.children.byId,[t]:a},runningCount:Math.max(0,e.children.runningCount+l)},activeReasons:Bt(e.activeReasons,"sse:sub_session_started")};return Xo(c)},Iu=(e,t,n)=>{const s=e.children.byId[t],r=s===void 0||s.status===void 0||s.status==="running",a={...s,...n},i=a.status===void 0||a.status==="running";let l=0;s!==void 0&&(l=(i?1:0)-(r?1:0));const c=Math.max(0,e.children.runningCount+l),u={...e,children:{byId:{...e.children.byId,[t]:a},runningCount:c}};return u.timestamps.terminalAt&&u.children.runningCount===0&&u.stream.activeToolCalls.length===0&&!qc.has(u.phase)?{...u,phase:"settling",timestamps:{...u.timestamps,settlingStartedAt:u.timestamps.settlingStartedAt??u.timestamps.terminalAt},activeReasons:Bt(u.activeReasons,"sse:sub_session_completed")}:Xo(u)},k0=(e,t)=>{if(!(t in e.children.byId))return e;const n=e.children.byId[t],s=n.status===void 0||n.status==="running",r={...e.children.byId};delete r[t];const a={...e,children:{byId:r,runningCount:Math.max(0,e.children.runningCount-(s?1:0))}};return a.timestamps.terminalAt&&a.children.runningCount===0&&a.stream.activeToolCalls.length===0&&!qc.has(a.phase)?{...a,phase:"settling",timestamps:{...a.timestamps,settlingStartedAt:a.timestamps.settlingStartedAt??a.timestamps.terminalAt}}:Xo(a)},Sf=(e,t,n)=>{switch(t.type){case"token":return vf(e,"sse:token",n);case"reasoning_token":return vf(e,"sse:token",n);case"tool_start":{const s=t.tool_call_id??"",r=t.tool_name??"";return s?S0(e,s,r,n()):e}case"tool_token":{const s=t.tool_call_id??"";return s?w0(e,s,t.content??""):e}case"tool_complete":case"tool_error":{const s=t.tool_call_id??"";return s?_0(e,s,"sse:tool_complete"):e}case"tool_lifecycle":return e;case"sub_session_started":{const s=t.child_session_id??"";return s?Bb(e,s,{title:t.title,status:"running"}):e}case"sub_session_event":case"sub_session_heartbeat":{const s=t.child_session_id??"";if(!s)return e;const r={lastEventAt:t.timestamp??n()};return t.type==="sub_session_heartbeat"&&(r.lastHeartbeatAt=t.timestamp??n()),Iu(e,s,r)}case"sub_session_completed":{const s=t.child_session_id??"";if(!s)return e;const r=typeof t.status=="string"?t.status:"completed";return Iu(e,s,{status:r,error:t.error})}case"need_clarification":{const s={question:t.question??"",options:t.options??[],allowCustom:t.allow_custom??!1,toolCallId:t.tool_call_id??null},r=n();return{...e,phase:"waiting_user_answer",confidence:"live",interaction:{...e.interaction,pendingQuestion:{...s,receivedAt:r},respondMode:{...s,sessionId:e.sessionId}},activeReasons:Bt(e.activeReasons,"sse:need_clarification")}}case"execution_started":{const s=t.run_id;return s?e.phase!=="starting"?{...e,backendRunId:s,confidence:"live",activeReasons:Bt(e.activeReasons,"sse:execution_started")}:{...e,phase:"running",confidence:"live",backendRunId:s,timestamps:{...e.timestamps,confirmedAt:n()},activeReasons:Bt(e.activeReasons,"sse:execution_started")}:e}case"complete":{const s=n();return{...e,phase:"settling",timestamps:{...e.timestamps,terminalAt:s,settlingStartedAt:e.timestamps.settlingStartedAt??s},activeReasons:Bt(e.activeReasons,"sse:complete")}}case"error":{const s=n();return{...e,phase:"error",confidence:"terminal",timestamps:{...e.timestamps,terminalAt:s},error:{message:t.message??t.error??"Unknown error",source:"sse",occurredAt:s},activeReasons:Bt(e.activeReasons,"sse:error")}}case"task_list_updated":case"task_list_item_progress":case"task_list_completed":case"task_evaluation_started":case"task_evaluation_completed":case"token_budget_updated":case"context_compression_status":case"context_summarized":case"context_pressure_notification":return e;default:return e}},T0=e=>e==="completed"||e==="error"||e==="cancelled",j0=(e,t,n)=>{const s=t.last_run_status,r=T0(s)?s:null,a=n(),i=t.has_pending_question===void 0?null:t.has_pending_question,l=t.running_child_count===void 0?null:t.running_child_count,c={...e,backend:{...e.backend,isRunning:t.is_running,lastRunStatus:r,lastRunError:t.last_run_error??null,syncedAt:a,hasPendingQuestion:i,runningChildCount:l},backendRunId:e.backendRunId};if(t.is_running)return e.phase==="idle"||e.phase==="completed"||e.phase==="error"||e.phase==="cancelled"?{...c,phase:"running",confidence:"summary",activeReasons:Bt(c.activeReasons,"summary:is_running")}:e.phase==="starting"?{...c,phase:"running",confidence:"summary",timestamps:{...c.timestamps,confirmedAt:a},activeReasons:Bt(c.activeReasons,"summary:is_running")}:c;if(new Set(["starting","running","streaming","running_tools","running_children","settling"]).has(e.phase)){if(r==="completed")return{...c,phase:"completed",confidence:"terminal",timestamps:{...c.timestamps,settledAt:a},activeReasons:Bt(c.activeReasons,"summary:terminal")};if(r==="error")return{...c,phase:"error",confidence:"terminal",timestamps:{...c.timestamps,settledAt:a},error:{message:t.last_run_error??"Backend reported error",source:"summary",occurredAt:a},activeReasons:Bt(c.activeReasons,"summary:terminal")};if(r==="cancelled")return{...c,phase:"cancelled",confidence:"terminal",timestamps:{...c.timestamps,settledAt:a},activeReasons:Bt(c.activeReasons,"summary:terminal")};if(e.timestamps.optimisticAt){const m=Date.parse(a)-Date.parse(e.timestamps.optimisticAt);if(Number.isFinite(m)&&m<p0)return c}return{...c,phase:"idle",confidence:"summary",activeReasons:Bt(c.activeReasons,"summary:terminal")}}return c},C0=()=>new Date().toISOString(),nn=(e,t,n=C0)=>{switch(t.type){case"ensureSession":return t.sessionId in e?e:mn(e,t.sessionId,zb(t.sessionId));case"markOptimisticStart":{const s=Dn(e,t.sessionId),r=n(),a={...s,phase:"starting",confidence:"optimistic",generation:s.generation+1,stream:{hasTokens:!1,tokenCount:0,activeToolCalls:[],lastStatusHint:null},interaction:{...s.interaction,respondMode:null},error:null,timestamps:{optimisticAt:r,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},activeReasons:Bt(s.activeReasons,"optimistic:send")};return mn(e,t.sessionId,a)}case"markRespondStart":{const s=Dn(e,t.sessionId),r=n(),a={...s,phase:"starting",confidence:"optimistic",generation:s.generation+1,stream:{hasTokens:!1,tokenCount:0,activeToolCalls:[],lastStatusHint:null},interaction:{...s.interaction,pendingQuestion:null,respondMode:null},error:null,timestamps:{...s.timestamps,optimisticAt:r,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},activeReasons:Bt(s.activeReasons,"optimistic:respond")};return mn(e,t.sessionId,a)}case"markRetryStart":{const s=Dn(e,t.sessionId),r=n(),a={...s,phase:"starting",confidence:"optimistic",generation:s.generation+1,stream:{hasTokens:!1,tokenCount:0,activeToolCalls:[],lastStatusHint:null},error:null,timestamps:{...s.timestamps,optimisticAt:r,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},activeReasons:Bt(s.activeReasons,"optimistic:retry")};return mn(e,t.sessionId,a)}case"markForceSubscribe":{const s=Dn(e,t.sessionId);if(Um(s.phase))return e;const r={...s,phase:"running",confidence:"optimistic",generation:s.generation+1,error:null,activeReasons:Bt(s.activeReasons,"optimistic:openSession.forceSubscribe")};return mn(e,t.sessionId,r)}case"markCancel":{const s=Dn(e,t.sessionId),r=n(),a={...s,phase:"cancelled",confidence:"terminal",timestamps:{...s.timestamps,settledAt:r},activeReasons:Bt(s.activeReasons,"user:cancel")};return mn(e,t.sessionId,a)}case"markSettleTimeout":{const s=Dn(e,t.sessionId);if(s.phase!=="starting"&&s.phase!=="settling")return e;const r={...s,phase:"idle",confidence:"optimistic",timestamps:{...s.timestamps,settledAt:n()},activeReasons:Bt(s.activeReasons,"settle:timeout")};return mn(e,t.sessionId,r)}case"applyAgentEvent":{const s=Dn(e,t.sessionId);if(t.generation!==s.generation)return e;const r=Sf(s,t.event,n);return r===s?e:mn(e,t.sessionId,r)}case"applyExecutionStarted":{const s=Dn(e,t.sessionId);if(t.generation!==s.generation)return e;if(s.phase!=="starting")return mn(e,t.sessionId,{...s,backendRunId:t.runId,confidence:"live",activeReasons:Bt(s.activeReasons,"sse:execution_started")});const r={...s,phase:"running",confidence:"live",backendRunId:t.runId,timestamps:{...s.timestamps,confirmedAt:n()},activeReasons:Bt(s.activeReasons,"sse:execution_started")};return mn(e,t.sessionId,r)}case"applySessionSummary":{const s=Dn(e,t.sessionId),r=j0(s,t.summary,n);return r===s?e:mn(e,t.sessionId,r)}case"applyOneShotTerminal":{const s=Dn(e,t.sessionId);if(t.generation!==s.generation||s.phase!=="idle"&&s.phase!=="starting")return e;const r=n();return t.payload.status==="completed"?mn(e,t.sessionId,{...s,phase:"completed",confidence:"terminal",timestamps:{...s.timestamps,terminalAt:r,settledAt:r},activeReasons:Bt(s.activeReasons,"sse:terminal_one_shot")}):mn(e,t.sessionId,{...s,phase:"error",confidence:"terminal",timestamps:{...s.timestamps,terminalAt:r,settledAt:r},error:{message:t.payload.message??"Unknown error",source:"sse",occurredAt:r},activeReasons:Bt(s.activeReasons,"sse:terminal_one_shot")})}case"beginSettle":{const s=Dn(e,t.sessionId);if(t.generation!==s.generation||s.phase!=="running"&&s.phase!=="streaming"&&s.phase!=="running_tools"&&s.phase!=="running_children")return e;const r=n();return mn(e,t.sessionId,{...s,phase:"settling",timestamps:{...s.timestamps,settlingStartedAt:r,terminalAt:s.timestamps.terminalAt??r}})}case"applyChildProgress":{const s=Dn(e,t.sessionId),a=!(t.childId in s.children.byId)?Bb(s,t.childId,t.patch):Iu(s,t.childId,t.patch);return a===s?e:mn(e,t.sessionId,a)}case"clearChildProgress":{const s=Dn(e,t.sessionId),r=k0(s,t.childId);return r===s?e:mn(e,t.sessionId,r)}case"setPendingQuestion":{const s=Dn(e,t.sessionId),r=n(),a={...s,phase:"waiting_user_answer",confidence:"live",interaction:{...s.interaction,pendingQuestion:{...t.payload,receivedAt:r},respondMode:{...t.payload,sessionId:t.sessionId}},activeReasons:Bt(s.activeReasons,"sse:need_clarification")};return mn(e,t.sessionId,a)}case"clearPendingQuestion":{const s=Dn(e,t.sessionId);if(s.interaction.pendingQuestion===null&&s.interaction.respondMode===null)return e;const r={...s,interaction:{...s.interaction,pendingQuestion:null,respondMode:null}};return mn(e,t.sessionId,r)}case"resetSession":return v0(e,t.sessionId);case"applyRunningSnapshot":{let s=e;for(const r of t.sessions){const a=Dn(s,r.sessionId),i=a.generation+1;let l={...a,generation:i,backendRunId:r.runId,phase:"running",confidence:"live",timestamps:{...a.timestamps,confirmedAt:n()},activeReasons:Bt(a.activeReasons,"sse:execution_started")};for(const c of r.criticalEvents)c.type!=="execution_started"&&(l=Sf(l,c,n));s=mn(s,r.sessionId,l)}return s}default:return e}},xn=()=>new Date().toISOString(),M0=e=>({executionBySession:{},ensureSession:t=>{e(n=>{const s=nn(n.executionBySession,{type:"ensureSession",sessionId:t},xn);return s===n.executionBySession?{}:{executionBySession:s}})},markOptimisticStart:t=>{e(n=>{const s=nn(n.executionBySession,{type:"markOptimisticStart",sessionId:t},xn);return s===n.executionBySession?{}:{executionBySession:s}})},markRespondStart:(t,n)=>{e(s=>{const r=nn(s.executionBySession,{type:"markRespondStart",sessionId:t},xn);return r===s.executionBySession?{}:{executionBySession:r}})},markRetryStart:t=>{e(n=>{const s=nn(n.executionBySession,{type:"markRetryStart",sessionId:t},xn);return s===n.executionBySession?{}:{executionBySession:s}})},markForceSubscribe:t=>{e(n=>{const s=nn(n.executionBySession,{type:"markForceSubscribe",sessionId:t},xn);return s===n.executionBySession?{}:{executionBySession:s}})},markCancel:t=>{e(n=>{const s=nn(n.executionBySession,{type:"markCancel",sessionId:t},xn);return s===n.executionBySession?{}:{executionBySession:s}})},markSettleTimeout:t=>{e(n=>{const s=nn(n.executionBySession,{type:"markSettleTimeout",sessionId:t},xn);return s===n.executionBySession?{}:{executionBySession:s}})},applyAgentEvent:(t,n,s)=>{e(r=>{const a=nn(r.executionBySession,{type:"applyAgentEvent",sessionId:t,event:n,generation:s},xn);return a===r.executionBySession?{}:{executionBySession:a}})},applyExecutionStarted:(t,n,s)=>{e(r=>{const a=nn(r.executionBySession,{type:"applyExecutionStarted",sessionId:t,runId:n,generation:s},xn);return a===r.executionBySession?{}:{executionBySession:a}})},applySessionSummary:(t,n)=>{e(s=>{const r=nn(s.executionBySession,{type:"applySessionSummary",sessionId:t,summary:n},xn);return r===s.executionBySession?{}:{executionBySession:r}})},applyOneShotTerminal:(t,n,s)=>{e(r=>{const a=nn(r.executionBySession,{type:"applyOneShotTerminal",sessionId:t,generation:n,payload:s},xn);return a===r.executionBySession?{}:{executionBySession:a}})},beginSettle:(t,n)=>{e(s=>{const r=nn(s.executionBySession,{type:"beginSettle",sessionId:t,generation:n},xn);return r===s.executionBySession?{}:{executionBySession:r}})},applyChildProgress:(t,n,s)=>{e(r=>{const a=nn(r.executionBySession,{type:"applyChildProgress",sessionId:t,childId:n,patch:s},xn);return a===r.executionBySession?{}:{executionBySession:a}})},clearChildProgress:(t,n)=>{e(s=>{const r=nn(s.executionBySession,{type:"clearChildProgress",sessionId:t,childId:n},xn);return r===s.executionBySession?{}:{executionBySession:r}})},setPendingQuestion:(t,n)=>{e(s=>{const r=nn(s.executionBySession,{type:"setPendingQuestion",sessionId:t,payload:n},xn);return r===s.executionBySession?{}:{executionBySession:r}})},clearPendingQuestion:t=>{e(n=>{const s=nn(n.executionBySession,{type:"clearPendingQuestion",sessionId:t},xn);return s===n.executionBySession?{}:{executionBySession:s}})},resetSession:t=>{e(n=>{const s=nn(n.executionBySession,{type:"resetSession",sessionId:t},xn);return s===n.executionBySession?{}:{executionBySession:s}})},applyRunningSnapshot:t=>{e(n=>{const s=nn(n.executionBySession,{type:"applyRunningSnapshot",sessions:t},xn);return s===n.executionBySession?{}:{executionBySession:s}})}}),wf="copilot_auto_generate_titles",Ws=os.getInstance(),No=xc()[0],P0=(No==null?void 0:No.id)||"general_assistant";var fb;const Wb=((fb=No==null?void 0:No.content)==null?void 0:fb.trim())||"",Ad="tool",_f=e=>{if(typeof e!="string"||!e.trim())return null;const t=Date.parse(e);return Number.isFinite(t)?t:null},E0=()=>{try{const e=globalThis.crypto;if(e!=null&&e.randomUUID)return e.randomUUID()}catch{}return`id_${Date.now()}_${Math.random().toString(16).slice(2)}`},R0=()=>{let e=Vo().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`},qb=e=>{const t=e.trim();if(!t.startsWith("bamboo-attachment://"))return null;const n=t.slice(20),[s,r]=n.split("/",2);return!s||!r?null:{sessionId:s,attachmentId:r}},A0=e=>{const t=qb(e);return t?`${R0()}/sessions/${encodeURIComponent(t.sessionId)}/attachments/${encodeURIComponent(t.attachmentId)}`:e},Yr=e=>{if(typeof e!="string")return;const t=e.trim();if(t&&t.toLowerCase()!=="unknown")return t},I0=e=>{const t=(e||"").trim();if(!t)return;const n=t.match(/tool policy blocked ['"`]([^'"`]+)['"`]/i);if(n!=null&&n[1])return Yr(n[1]);try{const s=JSON.parse(t);if(typeof(s==null?void 0:s.tool_name)=="string")return Yr(s.tool_name)}catch{}},Ou=e=>{var s,r;const t=Number.isFinite(Date.parse(e.created_at))?Date.parse(e.created_at):Date.now(),n=e.token_usage?{systemTokens:e.token_usage.system_tokens,summaryTokens:e.token_usage.summary_tokens,windowTokens:e.token_usage.window_tokens,totalTokens:e.token_usage.total_tokens,budgetLimit:e.token_usage.budget_limit,...typeof e.token_usage.max_context_tokens=="number"&&e.token_usage.max_context_tokens>0?{maxContextTokens:e.token_usage.max_context_tokens}:{},...typeof e.token_usage.prompt_cached_tool_outputs=="number"&&e.token_usage.prompt_cached_tool_outputs>0?{promptCachedToolOutputs:e.token_usage.prompt_cached_tool_outputs}:{}}: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||bs.t("chat.session.defaultTitle"),createdAt:t,pinned:e.pinned,messages:[],config:{systemPromptId:P0,baseSystemPrompt:Wb,lastUsedEnhancedPrompt:null,model:e.model,model_ref:e.model_ref??null,reasoningEffort:e.reasoning_effort??null,tokenUsage:n,truncationOccurred:(s=e.token_usage)==null?void 0:s.truncation_occurred,segmentsRemoved:(r=e.token_usage)==null?void 0:r.segments_removed,compressionEvents:[]}}},O0=(e,t)=>{var a,i,l,c,u;const n=new Map,s=new Map;for(const m of t)m.role==="tool"&&m.tool_call_id&&m.metadata&&s.set(m.tool_call_id,m.metadata);const r=[];for(const m of t){const p=m.created_at||new Date().toISOString();if(m.role==="system"){const g={role:"system",id:m.id,createdAt:p,content:m.content||"",isCompressed:!!m.compressed,compressedEventId:m.compressed_by_event_id};r.push(g);continue}if(m.role==="user"){const g=new Map;for(const x of m.image_ocr||[]){const k=(a=x.image_url)==null?void 0:a.trim();if(!k)continue;const w=(x.lines||[]).map(M=>((M==null?void 0:M.text)||"").trim()).filter(Boolean);g.set(k,{ocrText:w.length?w.join(`
12
+ `):void 0,ocrError:x.error?String(x.error):void 0})}const b=[];for(const x of m.content_parts||[]){if(x.type!=="image_url")continue;const k=((i=x.image_url)==null?void 0:i.url)||"";if(!k)continue;const j=A0(k),w=qb(k),M=g.get(k.trim());b.push({id:E0(),url:j,ocrText:M==null?void 0:M.ocrText,ocrError:M==null?void 0:M.ocrError,name:w?`attachment-${w.attachmentId}`:"image",size:0,type:"image/*"})}const S={role:"user",id:m.id,createdAt:p,content:m.content||"",images:b.length?b:void 0,isCompressed:!!m.compressed,compressedEventId:m.compressed_by_event_id};r.push(S);continue}if(m.role==="assistant"){const g=m.tool_calls||[];if(g.length>0){const x=(m.content||"").trim(),k=typeof m.reasoning=="string"&&m.reasoning.trim().length>0;if(x||k){const _=k?{reasoning:m.reasoning,backendMessageId:m.id}:{backendMessageId:m.id},C={role:"assistant",type:"text",id:`${m.id}_text`,createdAt:p,content:m.content||"",metadata:_,isCompressed:!!m.compressed,compressedEventId:m.compressed_by_event_id};r.push(C)}for(const _ of g)_.id&&n.set(_.id,Yr((l=_.function)==null?void 0:l.name)||Ad);const j=(c=g[0])==null?void 0:c.id,w=j?s.get(j):void 0,M={role:"assistant",type:"tool_call",id:m.id,createdAt:p,toolCalls:g.map(_=>{var C;return{toolCallId:_.id,toolName:Yr((C=_.function)==null?void 0:C.name)||Ad,parameters:(()=>{var D,A;try{return JSON.parse(((D=_.function)==null?void 0:D.arguments)||"{}")}catch{return{raw:((A=_.function)==null?void 0:A.arguments)||""}}})(),streamingOutput:""}}),...w?{metadata:w}:{},isCompressed:!!m.compressed,compressedEventId:m.compressed_by_event_id};r.push(M);continue}const b=typeof m.reasoning=="string"&&m.reasoning.trim().length>0?{reasoning:m.reasoning}:{},S={role:"assistant",type:"text",id:m.id,createdAt:p,content:m.content||"",metadata:b,isCompressed:!!m.compressed,compressedEventId:m.compressed_by_event_id};r.push(S);continue}if(m.role==="tool"){const g=((u=m.tool_call_id)==null?void 0:u.trim())||`orphan-tool-call:${m.id}`,b=Yr(n.get(g))||Yr(m.tool_name)||Yr(m.name)||I0(m.content)||Ad,S=m.tool_success===!1||m.tool_success==null&&typeof m.content=="string"&&m.content.trimStart().startsWith("Error:"),x={role:"assistant",type:"tool_result",id:m.id,createdAt:p,toolName:b,toolCallId:g,result:{tool_name:b,result:m.content||"",display_preference:"Default"},isError:S,isCompressed:!!m.compressed,compressedEventId:m.compressed_by_event_id};r.push(x);continue}}return r},$0=750,Ot={inFlight:null,forcedPromise:null,timer:null,trailingPromise:null,trailingResolve:null,trailingReject:null};function Ub(){const e={resolve:Ot.trailingResolve,reject:Ot.trailingReject};return Ot.trailingPromise=null,Ot.trailingResolve=null,Ot.trailingReject=null,e}function kf(e,t){!t.resolve&&!t.reject||e.then(()=>{var n;return(n=t.resolve)==null?void 0:n.call(t)},n=>{var s;return(s=t.reject)==null?void 0:s.call(t,n)})}function D0(){return Ot.timer&&(clearTimeout(Ot.timer),Ot.timer=null),Ub()}function L0(e,t){const n=e.map(Ou);t(s=>{let r=s.executionBySession;for(const l of e)r=nn(r,{type:"applySessionSummary",sessionId:l.id,summary:l});const a=new Map(s.chats.map(l=>[l.id,l])),i=n.map(l=>{var w,M,_,C;const c=a.get(l.id);if(!c)return l;const u=_f(c.updatedAt),m=_f(l.updatedAt),p=u!==null&&m!==null&&u>m,g=c.config||{},b=l.config||{},S=Object.prototype.hasOwnProperty.call(g,"model"),x=Object.prototype.hasOwnProperty.call(g,"model_ref"),k=Object.prototype.hasOwnProperty.call(g,"reasoningEffort"),j=Math.max(c.messageCount??0,l.messageCount??0);return{...l,title:p?c.title:l.title,pinned:p?c.pinned:l.pinned,updatedAt:p?c.updatedAt:l.updatedAt,messages:c.messages,messageCount:j,config:{...g,...b,model:p&&S?g.model:b.model,model_ref:p&&x?g.model_ref:b.model_ref,reasoningEffort:p&&k?g.reasoningEffort:b.reasoningEffort,compressionEvents:((w=c.config)==null?void 0:w.compressionEvents)??((M=l.config)==null?void 0:M.compressionEvents),syncCursor:((_=c.config)==null?void 0:_.syncCursor)??((C=l.config)==null?void 0:C.syncCursor)}}});return{...s,chats:i,executionBySession:r}})}async function Gl(e){return Ot.inFlight||(Ot.inFlight=(async()=>{try{const t=await Ws.listSessions();L0(t.sessions,e)}catch(t){throw console.error("[ChatSlice] Failed to refresh sessions:",t),t}})().finally(()=>{Ot.inFlight=null})),Ot.inFlight}function F0(e){return Ot.forcedPromise||(Ot.forcedPromise=(async()=>{Ot.inFlight&&await Ot.inFlight,await Gl(e)})().finally(()=>{Ot.forcedPromise=null})),Ot.forcedPromise}const N0=(e,t)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,autoGenerateTitles:!0,isUpdatingAutoTitlePreference:!1,addChat:async n=>{var g,b,S,x,k,j,w,M,_,C,D,A;const s=(n.title||bs.t("chat.sidebar.newSession")).trim(),r=((b=(g=n.config)==null?void 0:g.baseSystemPrompt)==null?void 0:b.trim())||"",a=(S=Ct.getState().getActiveModel())==null?void 0:S.trim(),i=((k=(x=n.config)==null?void 0:x.model)==null?void 0:k.trim())||a||void 0,l=((j=n.config)==null?void 0:j.reasoningEffort)??void 0;let c,u;if(Ct.getState().isProviderModelRefEnabled()){const B=(w=n.config)==null?void 0:w.model_ref;if((M=B==null?void 0:B.provider)!=null&&M.trim()&&((_=B==null?void 0:B.model)!=null&&_.trim()))c=B,u=B.provider;else{const F=(C=Ct.getState().providerConfig.defaults)==null?void 0:C.chat;if((D=F==null?void 0:F.provider)!=null&&D.trim()&&((A=F==null?void 0:F.model)!=null&&A.trim()))c=F,u=F.provider;else{const O=Ct.getState().getActiveModel();O&&(c={provider:Ct.getState().currentProvider,model:O},u=Ct.getState().currentProvider)}}}const m=await Ws.createSession({title:s,system_prompt:r||void 0,model:i,model_ref:c,provider:u,reasoning_effort:l||void 0}),p={...Ou(m.session),title:s,config:{...n.config,model:m.session.model,model_ref:m.session.model_ref??null,reasoningEffort:m.session.reasoning_effort??null,baseSystemPrompt:r||Wb},messages:[]};return e(B=>{const F=[p,...B.chats.filter(O=>O.id!==p.id)];return{...B,chats:F,currentSessionId:p.id,latestActiveSessionId:p.id}}),p.id},selectSession:n=>{const s=t();s.currentSessionId===n&&s.latestActiveSessionId===n||e({currentSessionId:n,latestActiveSessionId:n})},deleteSession:async n=>{try{await Ws.deleteSession(n)}catch(s){console.error(`[ChatSlice] Failed to delete backend session ${n}:`,s)}e(s=>{var c;const r=new Set;for(const u of s.chats)u.id===n&&r.add(u.id),u.rootSessionId===n&&r.add(u.id);const a=s.chats.filter(u=>!r.has(u.id)),i=s.currentSessionId&&r.has(s.currentSessionId)?null:s.currentSessionId,l=s.latestActiveSessionId&&r.has(s.latestActiveSessionId)?((c=a[0])==null?void 0:c.id)??null:s.latestActiveSessionId;return{...s,chats:a,currentSessionId:i,latestActiveSessionId:l}})},deleteSessions:async n=>{for(const s of n)await t().deleteSession(s)},updateSession:(n,s)=>{const r=!!s.config&&(Object.prototype.hasOwnProperty.call(s.config,"model")||Object.prototype.hasOwnProperty.call(s.config,"reasoningEffort")),a=typeof s.title=="string"||typeof s.pinned=="boolean",l=r||a?new Date().toISOString():void 0;e(u=>{const m=u.chats.map(p=>p.id===n?{...p,...s,...l?{updatedAt:l}:{}}:p);return{...u,chats:m}});const c={};if(typeof s.title=="string"&&(c.title=s.title),typeof s.pinned=="boolean"&&(c.pinned=s.pinned),s.config&&Object.prototype.hasOwnProperty.call(s.config,"model")&&(c.model=s.config.model??null),s.config&&Object.prototype.hasOwnProperty.call(s.config,"model_ref")&&Ct.getState().isProviderModelRefEnabled()&&(c.model_ref=s.config.model_ref??null,s.config.model_ref&&(c.provider=s.config.model_ref.provider)),s.config&&Object.prototype.hasOwnProperty.call(s.config,"reasoningEffort")){const u=s.config.reasoningEffort;u?c.reasoning_effort=u:c.clear_reasoning_effort=!0}Object.keys(c).length>0&&Ws.patchSession(n,c).catch(u=>{console.warn(`[ChatSlice] Failed to patch session ${n}:`,u)})},persistSessionTitle:async(n,s)=>{var a;const r=(a=t().chats.find(i=>i.id===n))==null?void 0:a.title;e(i=>({...i,chats:i.chats.map(l=>l.id===n?{...l,title:s,updatedAt:new Date().toISOString()}:l)}));try{await Ws.patchSession(n,{title:s})}catch(i){throw typeof r=="string"&&e(l=>({...l,chats:l.chats.map(c=>c.id===n?{...c,title:r}:c)})),console.warn(`[ChatSlice] persistSessionTitle failed for ${n}:`,i),i}},pinSession:n=>{t().updateSession(n,{pinned:!0})},unpinSession:n=>{t().updateSession(n,{pinned:!1})},setMessages:(n,s)=>{t().chats.find(a=>a.id===n)&&t().updateSession(n,{messages:s})},addMessage:async(n,s)=>{const r=t().chats.find(i=>i.id===n);if(!r)return;const a=[...r.messages,s];t().updateSession(n,{messages:a})},updateMessage:(n,s,r)=>{const a=t().chats.find(l=>l.id===n);if(!a)return;const i=a.messages.map(l=>{if(l.id!==s)return l;const c={...l};return Object.keys(r).forEach(u=>{Object.prototype.hasOwnProperty.call(c,u)&&(c[u]=r[u])}),c});t().updateSession(n,{messages:i})},deleteMessage:async(n,s)=>{const r=t().chats.find(a=>a.id===n);if(!r)return{success:!1,sessionId:n,messageId:s,reason:"session_not_found"};if(!r.messages.some(a=>a.id===s))return{success:!1,sessionId:n,messageId:s,reason:"message_not_found"};try{await Ws.deleteSessionMessage(n,s)}catch(a){return console.warn(`[ChatSlice] Failed to delete message ${s} from session ${n}:`,a),a instanceof uo?a.status===404?{success:!1,sessionId:n,messageId:s,reason:"backend_not_found",statusCode:a.status,errorMessage:a.message}:a.status===409?{success:!1,sessionId:n,messageId:s,reason:"session_running",statusCode:a.status,errorMessage:a.message}:{success:!1,sessionId:n,messageId:s,reason:"backend_error",statusCode:a.status,errorMessage:a.message}:{success:!1,sessionId:n,messageId:s,reason:"backend_error",errorMessage:a instanceof Error?a.message:void 0}}return e(a=>({...a,chats:a.chats.map(i=>i.id===n?{...i,messages:i.messages.filter(l=>l.id!==s)}:i)})),{success:!0,sessionId:n,messageId:s}},refreshChats:async()=>Ot.inFlight?Ot.inFlight:Ot.timer?(Ot.trailingPromise||(Ot.trailingPromise=new Promise((n,s)=>{Ot.trailingResolve=n,Ot.trailingReject=s})),Ot.trailingPromise):(Ot.timer=setTimeout(()=>{if(Ot.timer=null,Ot.trailingPromise){const n=Ub();kf(Gl(e),n)}},$0),Gl(e)),refreshChatsNow:async()=>{const n=D0(),s=Ot.inFlight?F0(e):Gl(e);return kf(s,n),s},loadChats:async()=>{var c,u,m;const n=localStorage.getItem(wf),s=n===null?t().autoGenerateTitles:n==="true";let r=await Ws.listSessions();if(!r.sessions||r.sessions.length===0){const p=(c=Ct.getState().getActiveModel())==null?void 0:c.trim(),g=(u=Ct.getState().providerConfig.defaults)==null?void 0:u.chat;r={sessions:[(await Ws.createSession({title:bs.t("chat.sidebar.newSession"),model:p,model_ref:g,provider:g==null?void 0:g.provider})).session]}}const a=r.sessions.map(Ou),i=((m=a[0])==null?void 0:m.id)??null;let l=t().executionBySession;for(const p of r.sessions)l=nn(l,{type:"applySessionSummary",sessionId:p.id,summary:p});try{const p=await Ws.getRunningSessions();p.sessions.length>0&&(l=nn(l,{type:"applyRunningSnapshot",sessions:p.sessions.map(g=>({sessionId:g.session_id,runId:g.run_id,criticalEvents:g.last_critical_events}))},()=>new Date().toISOString()))}catch{}e({chats:a,latestActiveSessionId:i,currentSessionId:i,executionBySession:l,autoGenerateTitles:s}),i&&await t().loadChatHistory(i)},loadChatHistory:async(n,s)=>{var l,c,u,m,p,g,b,S,x,k,j,w,M;const r=(s==null?void 0:s.mode)??"replace",a=Math.max(0,(s==null?void 0:s.retries)??0),i=Math.max(0,(s==null?void 0:s.retryDelayMs)??0);for(let _=0;_<=a;_+=1)try{const C=t().chats.find(F=>F.id===n);if(!C)return;const D=await Ws.getHistory(n),A=(l=D.messages[D.messages.length-1])==null?void 0:l.role;if(s!=null&&s.waitForAssistant&&A==="user"&&_<a){const F=i>0?i*(_+1):200*(_+1);await new Promise(O=>setTimeout(O,F));continue}const B=O0(n,D.messages);if(r==="monotonic"){const F=C.messages||[],O=F.length,R=B.length,I=(c=B[B.length-1])==null?void 0:c.role,L=(u=F[F.length-1])==null?void 0:u.role,U=F[F.length-1],q=B[B.length-1],H=U==null?void 0:U.id,P=q==null?void 0:q.id;let W=!1;if(R>O?W=!0:R===O&&(W=L==="user"&&I!=="user"||typeof H=="string"&&typeof P=="string"&&H!==P),!W){t().updateSession(n,{messageCount:Math.max(C.messageCount??0,D.messages.length)});return}}t().updateSession(n,{messages:B,messageCount:D.messages.length,config:{...C.config||{},compressionEvents:(D.compression_events||[]).map(F=>({id:F.id,createdAt:F.created_at,messagesCompressed:F.messages_compressed,segmentsRemoved:F.segments_removed})),syncCursor:{messageCount:D.messages.length,lastMessageId:((m=D.messages[D.messages.length-1])==null?void 0:m.id)??null,hasPendingQuestion:((b=(g=(p=t().executionBySession)==null?void 0:p[n])==null?void 0:g.interaction.respondMode)==null?void 0:b.sessionId)===n,pendingQuestionToolCallId:((k=(x=(S=t().executionBySession)==null?void 0:S[n])==null?void 0:x.interaction.respondMode)==null?void 0:k.sessionId)===n?((M=(w=(j=t().executionBySession)==null?void 0:j[n])==null?void 0:w.interaction.respondMode)==null?void 0:M.toolCallId)??null:null}}});return}catch(C){if(_>=a){console.warn(`[ChatSlice] Failed to load history for ${n}:`,C);return}const D=i>0?i*(_+1):200*(_+1);await new Promise(A=>setTimeout(A,D))}},setAutoGenerateTitlesPreference:async n=>{const s=t().autoGenerateTitles;e({autoGenerateTitles:n,isUpdatingAutoTitlePreference:!0});try{localStorage.setItem(wf,String(n))}catch(r){throw console.warn("[ChatSlice] Failed to update auto-title preference:",r),e({autoGenerateTitles:s}),r}finally{e({isUpdatingAutoTitlePreference:!1})}}});class $u extends Error{constructor(n="Proxy authentication required"){super(n);jt(this,"code","proxy_auth_required");this.name="ProxyAuthRequiredError"}}const Jr=class Jr{constructor(){}static getInstance(){return Jr.instance||(Jr.instance=new Jr),Jr.instance}resolveOpenAICompatBaseUrl(){const t=Vo().trim().replace(/\/+$/,"");return t.endsWith("/openai/v1")?t:`${t.endsWith("/v1")?t.slice(0,-3):t}/openai/v1`}async getModels(){var t,n;try{return(await new qm({baseUrl:this.resolveOpenAICompatBaseUrl()}).get("models")).data.map(a=>a.id)}catch(s){if(console.error("Failed to fetch models from HTTP API:",s),s instanceof uo){if(s.status===428)throw new $u(s.message);let r;if(s.body)try{r=JSON.parse(s.body)}catch{}if(r&&typeof r=="object"&&"error"in r&&((t=r.error)==null?void 0:t.code)==="proxy_auth_required")throw new $u(((n=r.error)==null?void 0:n.message)||s.message)}throw s}}};jt(Jr,"instance");let Du=Jr;const Hb=Du.getInstance(),z0=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)},B0=e=>{if(typeof document>"u")throw new Error("document is unavailable");const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","true"),t.style.position="fixed",t.style.top="-9999px",t.style.left="-9999px",t.style.opacity="0",document.body.appendChild(t),t.focus(),t.select();const n=document.execCommand("copy");if(document.body.removeChild(t),!n)throw new Error("document.execCommand('copy') returned false")},Ss=async e=>{try{await z0(e);return}catch(t){try{B0(e);return}catch(n){const s=t instanceof Error?t.message:String(t),r=n instanceof Error?n.message:String(n);throw new Error(`Clipboard copy failed: navigator(${s}); fallback(${r})`)}}};class W0{async copyToClipboard(t){await Ss(t)}async getBambooConfig(){try{return await at.get("bamboo/config")}catch(t){return console.error("Failed to fetch Bamboo config:",t),{}}}async getBambooTools(){try{return await at.get("bamboo/tools")}catch(t){return console.error("Failed to fetch Bamboo tools:",t),{tools:[]}}}async getModelLimitDefaults(){try{return await at.get("bamboo/model-limits/defaults")}catch(t){return console.error("Failed to fetch model limit defaults:",t),{model_limits:[]}}}async setBambooConfig(t){return at.post("bamboo/config",t)}async validateBambooConfigPatch(t){return at.post("bamboo/config/validate",t)}async setProxyAuth(t){return at.post("bamboo/proxy-auth",t)}async getProxyAuthStatus(){try{return await at.get("bamboo/proxy-auth/status")}catch(t){return console.error("Failed to fetch proxy auth status:",t),{configured:!1,username:null}}}async clearProxyAuth(){return at.post("bamboo/proxy-auth",{username:"",password:""})}async resetBambooConfig(){return at.post("bamboo/config/reset",{})}async saveWorkflow(t,n){return at.post("bamboo/workflows",{name:t,content:n})}async deleteWorkflow(t){return at.delete(`bamboo/workflows/${encodeURIComponent(t)}`)}async getKeywordMaskingConfig(){try{return await at.get("bamboo/keyword-masking")}catch(t){return console.error("Failed to fetch keyword masking config:",t),{entries:[]}}}async updateKeywordMaskingConfig(t){return at.post("bamboo/keyword-masking",t)}async validateKeywordEntries(t){return at.post("bamboo/keyword-masking/validate",t)}async getSetupStatus(){return await at.get("bamboo/setup/status")}async markSetupComplete(){return at.post("bamboo/setup/complete",{})}async resetSetupStatus(){await at.post("bamboo/setup/incomplete",{})}async getAccessStatus(){return at.get("bamboo/access/status")}async verifyAccessPassword(t){return at.post("bamboo/access/verify",{password:t})}async updateAccessPassword(t){return at.post("bamboo/access/password",t)}}const Qr=class Qr{constructor(){jt(this,"httpUtilityService",new W0)}static getInstance(){return Qr.instance||(Qr.instance=new Qr),Qr.instance}getUtilityService(){return{copyToClipboard:t=>this.httpUtilityService.copyToClipboard(t),getBambooConfig:()=>this.httpUtilityService.getBambooConfig(),getBambooTools:()=>this.httpUtilityService.getBambooTools(),getModelLimitDefaults:()=>this.httpUtilityService.getModelLimitDefaults(),setBambooConfig:t=>this.httpUtilityService.setBambooConfig(t),validateBambooConfigPatch:t=>this.httpUtilityService.validateBambooConfigPatch(t),setProxyAuth:t=>this.httpUtilityService.setProxyAuth(t),getProxyAuthStatus:()=>this.httpUtilityService.getProxyAuthStatus(),clearProxyAuth:()=>this.httpUtilityService.clearProxyAuth(),resetBambooConfig:()=>this.httpUtilityService.resetBambooConfig(),resetSetupStatus:()=>this.httpUtilityService.resetSetupStatus(),saveWorkflow:(t,n)=>this.httpUtilityService.saveWorkflow(t,n),deleteWorkflow:t=>this.httpUtilityService.deleteWorkflow(t),getKeywordMaskingConfig:()=>this.httpUtilityService.getKeywordMaskingConfig(),updateKeywordMaskingConfig:t=>this.httpUtilityService.updateKeywordMaskingConfig(t),validateKeywordEntries:t=>this.httpUtilityService.validateKeywordEntries(t),getSetupStatus:()=>this.httpUtilityService.getSetupStatus(),markSetupComplete:()=>this.httpUtilityService.markSetupComplete(),getAccessStatus:()=>this.httpUtilityService.getAccessStatus(),verifyAccessPassword:t=>this.httpUtilityService.verifyAccessPassword(t),updateAccessPassword:t=>this.httpUtilityService.updateAccessPassword(t)}}async copyToClipboard(t){return this.getUtilityService().copyToClipboard(t)}async getBambooConfig(){return this.getUtilityService().getBambooConfig()}async getBambooTools(){return this.getUtilityService().getBambooTools()}async getModelLimitDefaults(){return this.getUtilityService().getModelLimitDefaults()}async setBambooConfig(t){return this.getUtilityService().setBambooConfig(t)}async validateBambooConfigPatch(t){return this.getUtilityService().validateBambooConfigPatch(t)}async setProxyAuth(t){return this.getUtilityService().setProxyAuth(t)}async getProxyAuthStatus(){return this.getUtilityService().getProxyAuthStatus()}async clearProxyAuth(){return this.getUtilityService().clearProxyAuth()}async resetBambooConfig(){return this.getUtilityService().resetBambooConfig()}async resetSetupStatus(){return this.getUtilityService().resetSetupStatus()}async saveWorkflow(t,n){return this.getUtilityService().saveWorkflow(t,n)}async deleteWorkflow(t){return this.getUtilityService().deleteWorkflow(t)}async getKeywordMaskingConfig(){return this.getUtilityService().getKeywordMaskingConfig()}async updateKeywordMaskingConfig(t){return this.getUtilityService().updateKeywordMaskingConfig(t)}async validateKeywordEntries(t){return this.getUtilityService().validateKeywordEntries(t)}async getSetupStatus(){return this.getUtilityService().getSetupStatus()}async markSetupComplete(){return this.getUtilityService().markSetupComplete()}async getAccessStatus(){return this.getUtilityService().getAccessStatus()}async verifyAccessPassword(t){return this.getUtilityService().verifyAccessPassword(t)}async updateAccessPassword(t){return this.getUtilityService().updateAccessPassword(t)}};jt(Qr,"instance");let Is=Qr;const Vt=Is.getInstance();let ua=null,ma=null;const Id=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,Ps=Pr((e,t)=>({config:null,proxyAuthStatus:null,isLoadingConfig:!1,isLoadingProxyAuthStatus:!1,lastLoadedAt:null,error:null,loadConfig:async({force:n=!1}={})=>{const s=t().config;if(!n&&s)return s;if(ua)return ua;ua=(async()=>{e({isLoadingConfig:!0,error:null});try{const r=await Vt.getBambooConfig()??{};return e({config:r,lastLoadedAt:Date.now(),error:null}),r}catch(r){const a=Id(r,"Failed to load Bamboo config");throw e({error:a}),r}finally{e({isLoadingConfig:!1})}})();try{return await ua}finally{ua=null}},saveConfig:async n=>{e({isLoadingConfig:!0,error:null,config:n});try{const s=await Vt.setBambooConfig(n);return e({config:s,lastLoadedAt:Date.now(),error:null}),s}catch(s){const r=Id(s,"Failed to save Bamboo config");throw e({error:r}),s}finally{e({isLoadingConfig:!1})}},patchConfig:async n=>{const r={...await t().loadConfig()??{},...n??{}};return t().saveConfig(r)},loadProxyAuthStatus:async({force:n=!1}={})=>{const s=t().proxyAuthStatus;if(!n&&s)return s;if(ma)return ma;ma=(async()=>{e({isLoadingProxyAuthStatus:!0,error:null});try{const r=await Vt.getProxyAuthStatus();return e({proxyAuthStatus:r,error:null}),r}catch(r){const a=Id(r,"Failed to load proxy auth status");throw e({error:a}),r}finally{e({isLoadingProxyAuthStatus:!1})}})();try{return await ma}finally{ma=null}},applyProxyAuth:async n=>{await Vt.setProxyAuth(n),await t().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await Vt.clearProxyAuth(),await t().loadProxyAuthStatus({force:!0})}}));let ha=null;const q0=(e,t)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:n=>{e({selectedModel:n})},loadConfigModel:async()=>{try{const n=await Ps.getState().loadConfig(),s=typeof(n==null?void 0:n.model)=="string"?n.model:void 0;s&&e({configModel:s})}catch(n){console.error("Failed to load model from config:",n)}},fetchModels:async()=>{if(ha)return ha;ha=(async()=>{e({isLoadingModels:!0,modelsError:null});try{try{if(!(await Vt.getSetupStatus()).is_complete){Jt("[ModelSlice]","Setup not complete, skipping model fetch"),e({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:"Complete setup to access all models"});return}}catch(s){console.error("Failed to check setup status:",s)}const n=await Hb.getModels();e(s=>{const r=s.selectedModel;let a=s.selectedModel;return r&&n.includes(r)||(n.length>0?a=n[0]:a=void 0),{...s,models:n,selectedModel:a,modelsError:n.length>0?null:"No available model options"}}),t().models.length===0&&console.warn("No models available from service")}catch(n){const s=n instanceof Error?n.message:String(n);if(console.error("Failed to fetch models:",n),n instanceof $u){e(r=>({...r,models:r.models,selectedModel:r.selectedModel,modelsError:s||"Proxy authentication required. Please configure proxy auth."}));return}e(r=>({...r,models:[],selectedModel:r.selectedModel,modelsError:s}))}finally{e({isLoadingModels:!1})}})();try{await ha}finally{ha=null}}}),U0=["system_prompt","system_prompt_selected_id"],Od=e=>({id:e.id,name:e.name||e.id,content:e.content||"",description:e.description,isDefault:!!e.is_default}),wr=class wr{constructor(){jt(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return wr.instance||(wr.instance=new wr),wr.instance.cleanupDeprecatedPromptStorageKeys(),wr.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const t of U0)localStorage.removeItem(t)}catch(t){console.warn("[SystemPromptService] Failed to cleanup deprecated prompt storage keys:",t)}}}async getSystemPromptPresets(){try{const t=await nt.get("prompt-presets"),s=(Array.isArray(t==null?void 0:t.prompts)?t.prompts:[]).filter(r=>r.id&&r.id.trim().length>0).map(Od);if(s.length>0)return s}catch(t){console.error("Failed to load prompt presets from backend:",t)}return xc()}async createSystemPromptPreset(t){var r;const n={name:t.name,content:t.content};(r=t.id)!=null&&r.trim()&&(n.id=t.id.trim()),t.description!==void 0&&(n.description=t.description);const s=await nt.post("prompt-presets",n);if(!(s!=null&&s.prompt))throw new Error("Backend did not return created prompt preset");return Od(s.prompt)}async updateSystemPromptPreset(t){const n=encodeURIComponent(t.id),s={name:t.name,content:t.content,description:t.description},r=await nt.patch(`prompt-presets/${n}`,s);if(!(r!=null&&r.prompt))throw new Error("Backend did not return updated prompt preset");return Od(r.prompt)}async deleteSystemPromptPreset(t){const n=encodeURIComponent(t);await nt.delete(`prompt-presets/${n}`)}async findPresetById(t){return(await this.getSystemPromptPresets()).find(s=>s.id===t)}async getCurrentSystemPromptContent(t){const n=await this.findPresetById(t);if(n)return n.content;const s=await this.getSystemPromptPresets(),r=s.find(a=>a.isDefault)||s[0];return(r==null?void 0:r.content)||""}};jt(wr,"instance");let vc=wr;const Tf="copilot_last_selected_prompt_id",Kb="copilot_custom_system_prompts_v2",Yb="copilot_custom_system_prompts_v2_migrated_to_backend",Vb="general_assistant",Hm=80,$o=vc.getInstance();let jl=null;function Km(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,Hm)}function Xb(e){if(typeof e!="string")return null;const t=e.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return t?t.slice(0,Hm):null}function Gb(e,t){if(!t.has(e))return e;let n=2;for(;;){const s=`_${n}`,a=`${e.slice(0,Math.max(0,Hm-s.length))}${s}`;if(!t.has(a))return a;n+=1}}function Jb(){try{const e=localStorage.getItem(Kb);if(!e)return[];const t=JSON.parse(e);if(!Array.isArray(t))return[];const n=new Set,s=[];for(const r of t){const a=typeof(r==null?void 0:r.name)=="string"?r.name.trim():"",i=typeof(r==null?void 0:r.content)=="string"?r.content.trim():"";if(!a||!i)continue;const c=Xb(r==null?void 0:r.id)||Km(a),u=Gb(c,n);u!==Vb&&(n.add(u),s.push({id:u,name:a,content:i,description:typeof(r==null?void 0:r.description)=="string"&&r.description.trim()||void 0,isDefault:!!(r!=null&&r.isDefault)}))}return s}catch(e){return console.error("[promptSlice] Failed to read legacy custom prompts:",e),[]}}function Qb(){try{return localStorage.getItem(Yb)==="1"}catch(e){return console.error("[promptSlice] Failed to read migration marker:",e),!1}}function jf(){try{localStorage.setItem(Yb,"1")}catch(e){console.error("[promptSlice] Failed to write migration marker:",e)}}function Cf(){try{localStorage.removeItem(Kb)}catch(e){console.error("[promptSlice] Failed to clear legacy custom prompts:",e)}}async function H0(){var r,a;if(Qb())return;const e=Jb();if(e.length===0){Cf(),jf();return}const t=await $o.getSystemPromptPresets(),n=new Set(t.map(i=>i.id));let s=!1;for(const i of e){const l=(r=i.name)==null?void 0:r.trim(),c=(a=i.content)==null?void 0:a.trim();if(!l||!c||i.id===Vb||i.isDefault)continue;const u=Xb(i.id)||Km(l),m=Gb(u,n);try{const p=await $o.createSystemPromptPreset({id:m,name:l,content:c,description:i.description});n.add(p.id)}catch(p){s=!0,console.error(`[promptSlice] Failed to migrate legacy prompt '${l}' to backend:`,p)}}s||(Cf(),jf())}async function K0(){jl||(jl=H0().finally(()=>{jl=null})),await jl}const Y0=(e,t)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(Tf)||null,loadSystemPrompts:async()=>{try{await K0()}catch(r){console.warn("[promptSlice] Legacy prompt migration skipped:",r)}let n=[];try{n=await $o.getSystemPromptPresets()}catch(r){console.error("Failed to load system prompts from backend:",r)}let s=n.length?n:xc();if(!Qb()){const r=Jb();s=V0(s,r)}s.length===0&&(s=xc()),e({systemPrompts:s})},addSystemPrompt:async n=>{try{await $o.createSystemPromptPreset({id:Km(n.name),name:n.name,content:n.content,description:n.description}),await t().loadSystemPrompts()}catch(s){throw console.error("Failed to add system prompt:",s),s}},updateSystemPrompt:async n=>{try{await $o.updateSystemPromptPreset(n),await t().loadSystemPrompts()}catch(s){throw console.error("Failed to update system prompt:",s),s}},deleteSystemPrompt:async n=>{try{await $o.deleteSystemPromptPreset(n),await t().loadSystemPrompts()}catch(s){throw console.error("Failed to delete system prompt:",s),s}},setLastSelectedPromptId:n=>{e({lastSelectedPromptId:n});try{localStorage.setItem(Tf,n)}catch(s){console.error("Failed to save last selected prompt ID to localStorage:",s)}}}),V0=(e,t)=>{const n=new Map;return e.forEach(s=>{n.set(s.id,s)}),t.forEach(s=>{n.set(s.id,s)}),Array.from(n.values())},X0=()=>({});class G0{async listSkills(t,n){const s=new URLSearchParams;t!=null&&t.search&&s.append("search",t.search),t!=null&&t.includeDisabled&&s.append("include_disabled","true"),n&&s.append("refresh","true");const r=s.toString(),a=r?`skills?${r}`:"skills";return at.get(a)}async getSkill(t){return at.get(`skills/${t}`)}async getFilteredTools(t){const n=t?`?session_id=${encodeURIComponent(t)}`:"";return(await at.get(`skills/filtered-tools${n}`)).tools??[]}}const Lu=new G0,J0=(e,t)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(n,s)=>{e({isLoadingSkills:!0,skillsError:null});try{const r=await Lu.listSkills(n,s);e({skills:r.skills,isLoadingSkills:!1})}catch(r){e({skillsError:r instanceof Error?r.message:bs.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async n=>{e({isLoadingSkills:!0,skillsError:null});try{const s=await Lu.getSkill(n),r=t().skills,i=r.findIndex(l=>l.id===s.id)>=0?r.map(l=>l.id===s.id?s:l):[...r,s];e({skills:i,isLoadingSkills:!1})}catch(s){e({skillsError:s instanceof Error?s.message:bs.t("components.skillManager.getFailed"),isLoadingSkills:!1})}},clearSkillsError:()=>{e({skillsError:null})}}),Q0=e=>({tokenUsages:{},truncationOccurred:{},segmentsRemoved:{},updateTokenUsage:(t,n)=>e(s=>({tokenUsages:{...s.tokenUsages,[t]:n}})),setTruncationInfo:(t,n,s)=>e(r=>({truncationOccurred:{...r.truncationOccurred,[t]:n},segmentsRemoved:{...r.segmentsRemoved,[t]:s}})),clearTokenUsage:t=>e(n=>{const{[t]:s,...r}=n.tokenUsages,{[t]:a,...i}=n.truncationOccurred,{[t]:l,...c}=n.segmentsRemoved;return{tokenUsages:r,truncationOccurred:i,segmentsRemoved:c}})}),Z0=os.getInstance(),ek=(e,t)=>({taskLists:{},taskListVersions:{},activeItems:{},evaluationStates:{},setTaskList:(n,s)=>e(r=>({taskLists:{...r.taskLists,[n]:s},taskListVersions:{...r.taskListVersions,[n]:s.version||0}})),loadTaskList:async n=>{const s=await Z0.getTaskList(n);return s?(t().setTaskList(s.session_id||n,s),s):null},updateTaskListDelta:(n,s)=>e(r=>{const a=r.taskListVersions[n]||0;if(s.version<=a)return r;const i=r.taskLists[n];if(!i)return r;const l=i.items.map(c=>c.id===s.item_id?{...c,status:s.status,tool_calls_count:s.tool_calls_count}:c);return{taskLists:{...r.taskLists,[n]:{...i,items:l,updated_at:new Date().toISOString()}},taskListVersions:{...r.taskListVersions,[n]:s.version},activeItems:{...r.activeItems,[n]:s.status==="in_progress"?s.item_id:null}}}),clearTaskList:n=>e(s=>{const{[n]:r,...a}=s.taskLists,{[n]:i,...l}=s.taskListVersions,{[n]:c,...u}=s.activeItems,{[n]:m,...p}=s.evaluationStates;return{taskLists:a,taskListVersions:l,activeItems:u,evaluationStates:p}}),getTaskListVersion:n=>t().taskListVersions[n]||0,setEvaluationState:(n,s)=>e(r=>({evaluationStates:{...r.evaluationStates,[n]:s}})),clearEvaluationState:n=>e(s=>{const{[n]:r,...a}=s.evaluationStates;return{evaluationStates:a}})});var Jl={exports:{}},tk=Jl.exports,Mf;function nk(){return Mf||(Mf=1,function(e,t){((n,s)=>{e.exports=s()})(tk,function(){var n=function(d,h){return(n=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(y,v){y.__proto__=v}:function(y,v){for(var T in v)Object.prototype.hasOwnProperty.call(v,T)&&(y[T]=v[T])}))(d,h)},s=function(){return(s=Object.assign||function(d){for(var h,y=1,v=arguments.length;y<v;y++)for(var T in h=arguments[y])Object.prototype.hasOwnProperty.call(h,T)&&(d[T]=h[T]);return d}).apply(this,arguments)};function r(d,h,y){for(var v,T=0,E=h.length;T<E;T++)!v&&T in h||((v=v||Array.prototype.slice.call(h,0,T))[T]=h[T]);return d.concat(v||Array.prototype.slice.call(h))}var a=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:Ww,i=Object.keys,l=Array.isArray;function c(d,h){return typeof h=="object"&&i(h).forEach(function(y){d[y]=h[y]}),d}typeof Promise>"u"||a.Promise||(a.Promise=Promise);var u=Object.getPrototypeOf,m={}.hasOwnProperty;function p(d,h){return m.call(d,h)}function g(d,h){typeof h=="function"&&(h=h(u(d))),(typeof Reflect>"u"?i:Reflect.ownKeys)(h).forEach(function(y){S(d,y,h[y])})}var b=Object.defineProperty;function S(d,h,y,v){b(d,h,c(y&&p(y,"get")&&typeof y.get=="function"?{get:y.get,set:y.set,configurable:!0}:{value:y,configurable:!0,writable:!0},v))}function x(d){return{from:function(h){return d.prototype=Object.create(h.prototype),S(d.prototype,"constructor",d),{extend:g.bind(null,d.prototype)}}}}var k=Object.getOwnPropertyDescriptor,j=[].slice;function w(d,h,y){return j.call(d,h,y)}function M(d,h){return h(d)}function _(d){if(!d)throw new Error("Assertion Failed")}function C(d){a.setImmediate?setImmediate(d):setTimeout(d,0)}function D(d,h){if(typeof h=="string"&&p(d,h))return d[h];if(!h)return d;if(typeof h!="string"){for(var y=[],v=0,T=h.length;v<T;++v){var E=D(d,h[v]);y.push(E)}return y}var $,z=h.indexOf(".");return z===-1||($=d[h.substr(0,z)])==null?void 0:D($,h.substr(z+1))}function A(d,h,y){if(d&&h!==void 0&&!("isFrozen"in Object&&Object.isFrozen(d)))if(typeof h!="string"&&"length"in h){_(typeof y!="string"&&"length"in y);for(var v=0,T=h.length;v<T;++v)A(d,h[v],y[v])}else{var E,$,z=h.indexOf(".");z!==-1?(E=h.substr(0,z),(z=h.substr(z+1))===""?y===void 0?l(d)&&!isNaN(parseInt(E))?d.splice(E,1):delete d[E]:d[E]=y:A($=($=d[E])&&p(d,E)?$:d[E]={},z,y)):y===void 0?l(d)&&!isNaN(parseInt(h))?d.splice(h,1):delete d[h]:d[h]=y}}function B(d){var h,y={};for(h in d)p(d,h)&&(y[h]=d[h]);return y}var F=[].concat;function O(d){return F.apply([],d)}var se="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(O([8,16,32,64].map(function(d){return["Int","Uint","Float"].map(function(h){return h+d+"Array"})}))).filter(function(d){return a[d]}),R=new Set(se.map(function(d){return a[d]})),I=null;function L(d){return I=new WeakMap,d=function h(y){if(!y||typeof y!="object")return y;var v=I.get(y);if(v)return v;if(l(y)){v=[],I.set(y,v);for(var T=0,E=y.length;T<E;++T)v.push(h(y[T]))}else if(R.has(y.constructor))v=y;else{var $,z=u(y);for($ in v=z===Object.prototype?{}:Object.create(z),I.set(y,v),y)p(y,$)&&(v[$]=h(y[$]))}return v}(d),I=null,d}var U={}.toString;function q(d){return U.call(d).slice(8,-1)}var H=typeof Symbol<"u"?Symbol.iterator:"@@iterator",P=typeof H=="symbol"?function(d){var h;return d!=null&&(h=d[H])&&h.apply(d)}:function(){return null};function W(d,h){h=d.indexOf(h),0<=h&&d.splice(h,1)}var ne={};function K(d){var h,y,v,T;if(arguments.length===1){if(l(d))return d.slice();if(this===ne&&typeof d=="string")return[d];if(T=P(d))for(y=[];!(v=T.next()).done;)y.push(v.value);else{if(d==null)return[d];if(typeof(h=d.length)!="number")return[d];for(y=new Array(h);h--;)y[h]=d[h]}}else for(h=arguments.length,y=new Array(h);h--;)y[h]=arguments[h];return y}var xe=typeof Symbol<"u"?function(d){return d[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},se=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],ae=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(se),fe={VersionChanged:"Database version changed by other database connection",DatabaseClosed:"Database has been closed",Abort:"Transaction aborted",TransactionInactive:"Transaction has already completed or failed",MissingAPI:"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb"};function Se(d,h){this.name=d,this.message=h}function me(d,h){return d+". Errors: "+Object.keys(h).map(function(y){return h[y].toString()}).filter(function(y,v,T){return T.indexOf(y)===v}).join(`
13
+ `)}function ze(d,h,y,v){this.failures=h,this.failedKeys=v,this.successCount=y,this.message=me(d,h)}function st(d,h){this.name="BulkError",this.failures=Object.keys(h).map(function(y){return h[y]}),this.failuresByPos=h,this.message=me(d,this.failures)}x(Se).from(Error).extend({toString:function(){return this.name+": "+this.message}}),x(ze).from(Se),x(st).from(Se);var pt=ae.reduce(function(d,h){return d[h]=h+"Error",d},{}),Kt=Se,Oe=ae.reduce(function(d,h){var y=h+"Error";function v(T,E){this.name=y,T?typeof T=="string"?(this.message="".concat(T).concat(E?`
14
+ `+E:""),this.inner=E||null):typeof T=="object"&&(this.message="".concat(T.name," ").concat(T.message),this.inner=T):(this.message=fe[h]||y,this.inner=null)}return x(v).from(Kt),d[h]=v,d},{}),Wt=(Oe.Syntax=SyntaxError,Oe.Type=TypeError,Oe.Range=RangeError,se.reduce(function(d,h){return d[h+"Error"]=Oe[h],d},{}));se=ae.reduce(function(d,h){return["Syntax","Type","Range"].indexOf(h)===-1&&(d[h+"Error"]=Oe[h]),d},{});function Xe(){}function _e(d){return d}function Ye(d,h){return d==null||d===_e?h:function(y){return h(d(y))}}function ot(d,h){return function(){d.apply(this,arguments),h.apply(this,arguments)}}function Lt(d,h){return d===Xe?h:function(){var y=d.apply(this,arguments),v=(y!==void 0&&(arguments[0]=y),this.onsuccess),T=this.onerror,E=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return v&&(this.onsuccess=this.onsuccess?ot(v,this.onsuccess):v),T&&(this.onerror=this.onerror?ot(T,this.onerror):T),E!==void 0?E:y}}function N(d,h){return d===Xe?h:function(){d.apply(this,arguments);var y=this.onsuccess,v=this.onerror;this.onsuccess=this.onerror=null,h.apply(this,arguments),y&&(this.onsuccess=this.onsuccess?ot(y,this.onsuccess):y),v&&(this.onerror=this.onerror?ot(v,this.onerror):v)}}function le(d,h){return d===Xe?h:function(T){var v=d.apply(this,arguments),T=(c(T,v),this.onsuccess),E=this.onerror,$=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return T&&(this.onsuccess=this.onsuccess?ot(T,this.onsuccess):T),E&&(this.onerror=this.onerror?ot(E,this.onerror):E),v===void 0?$===void 0?void 0:$:c(v,$)}}function be(d,h){return d===Xe?h:function(){return h.apply(this,arguments)!==!1&&d.apply(this,arguments)}}function De(d,h){return d===Xe?h:function(){var y=d.apply(this,arguments);if(y&&typeof y.then=="function"){for(var v=this,T=arguments.length,E=new Array(T);T--;)E[T]=arguments[T];return y.then(function(){return h.apply(v,E)})}return h.apply(this,arguments)}}se.ModifyError=ze,se.DexieError=Se,se.BulkError=st;var Le=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function ue(d){Le=d}var ye={},qe=100,He=typeof Promise>"u"?[]:(ae=Promise.resolve(),typeof crypto<"u"&&crypto.subtle?[He=crypto.subtle.digest("SHA-512",new Uint8Array([0])),u(He),ae]:[ae,u(ae),ae]),ae=He[0],vo=He[1],vo=vo&&vo.then,ke=ae&&ae.constructor,pe=!!He[2],Re=function(d,h){rn.push([d,h]),gt&&(queueMicrotask(mr),gt=!1)},Je=!0,gt=!0,Mt=[],xt=[],Ft=_e,Dt={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:Xe,pgp:!1,env:{},finalize:Xe},Ue=Dt,rn=[],dn=0,on=[];function Be(d){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var h=this._PSD=Ue;if(typeof d!="function"){if(d!==ye)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&En(this,this._value)}else this._state=null,this._value=null,++h.ref,function y(v,T){try{T(function(E){if(v._state===null){if(E===v)throw new TypeError("A promise cannot be resolved with itself.");var $=v._lib&&is();E&&typeof E.then=="function"?y(v,function(z,V){E instanceof Be?E._then(z,V):E.then(z,V)}):(v._state=!0,v._value=E,$s(v)),$&&ws()}},En.bind(null,v))}catch(E){En(v,E)}}(this,d)}var Ar={get:function(){var d=Ue,h=Rn;function y(v,T){var E=this,$=!d.global&&(d!==Ue||h!==Rn),z=$&&!Ds(),V=new Be(function(re,J){Jn(E,new as(Gt(v,d,$,z),Gt(T,d,$,z),re,J,d))});return this._consoleTask&&(V._consoleTask=this._consoleTask),V}return y.prototype=ye,y},set:function(d){S(this,"then",d&&d.prototype===ye?Ar:{get:function(){return d},set:Ar.set})}};function as(d,h,y,v,T){this.onFulfilled=typeof d=="function"?d:null,this.onRejected=typeof h=="function"?h:null,this.resolve=y,this.reject=v,this.psd=T}function En(d,h){var y,v;xt.push(h),d._state===null&&(y=d._lib&&is(),h=Ft(h),d._state=!1,d._value=h,v=d,Mt.some(function(T){return T._value===v._value})||Mt.push(v),$s(d),y)&&ws()}function $s(d){var h=d._listeners;d._listeners=[];for(var y=0,v=h.length;y<v;++y)Jn(d,h[y]);var T=d._PSD;--T.ref||T.finalize(),dn===0&&(++dn,Re(function(){--dn==0&&Fe()},[]))}function Jn(d,h){if(d._state===null)d._listeners.push(h);else{var y=d._state?h.onFulfilled:h.onRejected;if(y===null)return(d._state?h.resolve:h.reject)(d._value);++h.psd.ref,++dn,Re(Xs,[y,d,h])}}function Xs(d,h,y){try{var v,T=h._value;!h._state&&xt.length&&(xt=[]),v=Le&&h._consoleTask?h._consoleTask.run(function(){return d(T)}):d(T),h._state||xt.indexOf(T)!==-1||(E=>{for(var $=Mt.length;$;)if(Mt[--$]._value===E._value)return Mt.splice($,1)})(h),y.resolve(v)}catch(E){y.reject(E)}finally{--dn==0&&Fe(),--y.psd.ref||y.psd.finalize()}}function mr(){Nt(Dt,function(){is()&&ws()})}function is(){var d=Je;return gt=Je=!1,d}function ws(){var d,h,y;do for(;0<rn.length;)for(d=rn,rn=[],y=d.length,h=0;h<y;++h){var v=d[h];v[0].apply(null,v[1])}while(0<rn.length);gt=Je=!0}function Fe(){for(var d=Mt,h=(Mt=[],d.forEach(function(v){v._PSD.onunhandled.call(null,v._value,v)}),on.slice(0)),y=h.length;y;)h[--y]()}function yt(d){return new Be(ye,!1,d)}function tt(d,h){var y=Ue;return function(){var v=is(),T=Ue;try{return we(y,!0),d.apply(this,arguments)}catch(E){h&&h(E)}finally{we(T,!1),v&&ws()}}}g(Be.prototype,{then:Ar,_then:function(d,h){Jn(this,new as(null,null,d,h,Ue))},catch:function(d){var h,y;return arguments.length===1?this.then(null,d):(h=d,y=arguments[1],typeof h=="function"?this.then(null,function(v){return(v instanceof h?y:yt)(v)}):this.then(null,function(v){return(v&&v.name===h?y:yt)(v)}))},finally:function(d){return this.then(function(h){return Be.resolve(d()).then(function(){return h})},function(h){return Be.resolve(d()).then(function(){return yt(h)})})},timeout:function(d,h){var y=this;return d<1/0?new Be(function(v,T){var E=setTimeout(function(){return T(new Oe.Timeout(h))},d);y.then(v,T).finally(clearTimeout.bind(null,E))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&S(Be.prototype,Symbol.toStringTag,"Dexie.Promise"),Dt.env=$t(),g(Be,{all:function(){var d=K.apply(null,arguments).map(Ir);return new Be(function(h,y){d.length===0&&h([]);var v=d.length;d.forEach(function(T,E){return Be.resolve(T).then(function($){d[E]=$,--v||h(d)},y)})})},resolve:function(d){return d instanceof Be?d:d&&typeof d.then=="function"?new Be(function(h,y){d.then(h,y)}):new Be(ye,!0,d)},reject:yt,race:function(){var d=K.apply(null,arguments).map(Ir);return new Be(function(h,y){d.map(function(v){return Be.resolve(v).then(h,y)})})},PSD:{get:function(){return Ue},set:function(d){return Ue=d}},totalEchoes:{get:function(){return Rn}},newPSD:yn,usePSD:Nt,scheduler:{get:function(){return Re},set:function(d){Re=d}},rejectionMapper:{get:function(){return Ft},set:function(d){Ft=d}},follow:function(d,h){return new Be(function(y,v){return yn(function(T,E){var $=Ue;$.unhandleds=[],$.onunhandled=E,$.finalize=ot(function(){var z,V=this;z=function(){V.unhandleds.length===0?T():E(V.unhandleds[0])},on.push(function re(){z(),on.splice(on.indexOf(re),1)}),++dn,Re(function(){--dn==0&&Fe()},[])},$.finalize),d()},h,y,v)})}}),ke&&(ke.allSettled&&S(Be,"allSettled",function(){var d=K.apply(null,arguments).map(Ir);return new Be(function(h){d.length===0&&h([]);var y=d.length,v=new Array(y);d.forEach(function(T,E){return Be.resolve(T).then(function($){return v[E]={status:"fulfilled",value:$}},function($){return v[E]={status:"rejected",reason:$}}).then(function(){return--y||h(v)})})})}),ke.any&&typeof AggregateError<"u"&&S(Be,"any",function(){var d=K.apply(null,arguments).map(Ir);return new Be(function(h,y){d.length===0&&y(new AggregateError([]));var v=d.length,T=new Array(v);d.forEach(function(E,$){return Be.resolve(E).then(function(z){return h(z)},function(z){T[$]=z,--v||y(new AggregateError(T))})})})}),ke.withResolvers)&&(Be.withResolvers=ke.withResolvers);var mt={awaits:0,echoes:0,id:0},_n=0,Un=[],Hn=0,Rn=0,ls=0;function yn(d,$,y,v){var T=Ue,E=Object.create(T),$=(E.parent=T,E.ref=0,E.global=!1,E.id=++ls,Dt.env,E.env=pe?{Promise:Be,PromiseProp:{value:Be,configurable:!0,writable:!0},all:Be.all,race:Be.race,allSettled:Be.allSettled,any:Be.any,resolve:Be.resolve,reject:Be.reject}:{},$&&c(E,$),++T.ref,E.finalize=function(){--this.parent.ref||this.parent.finalize()},Nt(E,d,y,v));return E.ref===0&&E.finalize(),$}function An(){return mt.id||(mt.id=++_n),++mt.awaits,mt.echoes+=qe,mt.id}function Ds(){return!!mt.awaits&&(--mt.awaits==0&&(mt.id=0),mt.echoes=mt.awaits*qe,!0)}function Ir(d){return mt.echoes&&d&&d.constructor===ke?(An(),d.then(function(h){return Ds(),h},function(h){return Ds(),Pt(h)})):d}function al(){var d=Un[Un.length-1];Un.pop(),we(d,!1)}function we(d,h){var y,v,T=Ue;(h?!mt.echoes||Hn++&&d===Ue:!Hn||--Hn&&d===Ue)||queueMicrotask(h?(function(E){++Rn,mt.echoes&&--mt.echoes!=0||(mt.echoes=mt.awaits=mt.id=0),Un.push(Ue),we(E,!0)}).bind(null,d):al),d!==Ue&&(Ue=d,T===Dt&&(Dt.env=$t()),pe)&&(y=Dt.env.Promise,v=d.env,T.global||d.global)&&(Object.defineProperty(a,"Promise",v.PromiseProp),y.all=v.all,y.race=v.race,y.resolve=v.resolve,y.reject=v.reject,v.allSettled&&(y.allSettled=v.allSettled),v.any)&&(y.any=v.any)}function $t(){var d=a.Promise;return pe?{Promise:d,PromiseProp:Object.getOwnPropertyDescriptor(a,"Promise"),all:d.all,race:d.race,allSettled:d.allSettled,any:d.any,resolve:d.resolve,reject:d.reject}:{}}function Nt(d,h,y,v,T){var E=Ue;try{return we(d,!0),h(y,v,T)}finally{we(E,!1)}}function Gt(d,h,y,v){return typeof d!="function"?d:function(){var T=Ue;y&&An(),we(h,!0);try{return d.apply(this,arguments)}finally{we(T,!1),v&&queueMicrotask(Ds)}}}function kt(d){Promise===ke&&mt.echoes===0?Hn===0?d():enqueueNativeMicroTask(d):setTimeout(d,0)}(""+vo).indexOf("[native code]")===-1&&(An=Ds=Xe);var Pt=Be.reject,un="￿",an="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",ea="String expected.",_s="__dbnames",ks="readonly",go="readwrite";function Or(d,h){return d?h?function(){return d.apply(this,arguments)&&h.apply(this,arguments)}:d:h}var Oh={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function il(d){return typeof d!="string"||/\./.test(d)?function(h){return h}:function(h){return h[d]===void 0&&d in h&&delete(h=L(h))[d],h}}function $h(){throw Oe.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function Tt(d,h){try{var y=Dh(d),v=Dh(h);if(y!==v)return y==="Array"?1:v==="Array"?-1:y==="binary"?1:v==="binary"?-1:y==="string"?1:v==="string"?-1:y==="Date"?1:v!=="Date"?NaN:-1;switch(y){case"number":case"Date":case"string":return h<d?1:d<h?-1:0;case"binary":for(var T=Lh(d),E=Lh(h),$=T.length,z=E.length,V=$<z?$:z,re=0;re<V;++re)if(T[re]!==E[re])return T[re]<E[re]?-1:1;return $===z?0:$<z?-1:1;case"Array":for(var J=d,Y=h,X=J.length,te=Y.length,Q=X<te?X:te,Z=0;Z<Q;++Z){var ee=Tt(J[Z],Y[Z]);if(ee!==0)return ee}return X===te?0:X<te?-1:1}}catch{}return NaN}function Dh(d){var h=typeof d;return h=="object"&&(ArrayBuffer.isView(d)||(h=q(d))==="ArrayBuffer")?"binary":h}function Lh(d){return d instanceof Uint8Array?d:ArrayBuffer.isView(d)?new Uint8Array(d.buffer,d.byteOffset,d.byteLength):new Uint8Array(d)}function ll(d,h,y){var v=d.schema.yProps;return v?(h&&0<y.numFailures&&(h=h.filter(function(T,E){return!y.failures[E]})),Promise.all(v.map(function(T){return T=T.updatesTable,h?d.db.table(T).where("k").anyOf(h).delete():d.db.table(T).clear()})).then(function(){return y})):y}Fh.prototype.execute=function(d){var h=this["@@propmod"];if(h.add!==void 0){var y=h.add;if(l(y))return r(r([],l(d)?d:[],!0),y).sort();if(typeof y=="number")return(Number(d)||0)+y;if(typeof y=="bigint")try{return BigInt(d)+y}catch{return BigInt(0)+y}throw new TypeError("Invalid term ".concat(y))}if(h.remove!==void 0){var v=h.remove;if(l(v))return l(d)?d.filter(function(T){return!v.includes(T)}).sort():[];if(typeof v=="number")return Number(d)-v;if(typeof v=="bigint")try{return BigInt(d)-v}catch{return BigInt(0)-v}throw new TypeError("Invalid subtrahend ".concat(v))}return y=(y=h.replacePrefix)==null?void 0:y[0],y&&typeof d=="string"&&d.startsWith(y)?h.replacePrefix[1]+d.substring(y.length):d};var ta=Fh;function Fh(d){this["@@propmod"]=d}function Nh(d,h){for(var y=i(h),v=y.length,T=!1,E=0;E<v;++E){var $=y[E],z=h[$],V=D(d,$);z instanceof ta?(A(d,$,z.execute(V)),T=!0):V!==z&&(A(d,$,z),T=!0)}return T}qt.prototype._trans=function(d,h,y){var v=this._tx||Ue.trans,T=this.name,E=Le&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(d==="readonly"?"read":"write"," ").concat(this.name));function $(re,J,Y){if(Y.schema[T])return h(Y.idbtrans,Y);throw new Oe.NotFound("Table "+T+" not part of transaction")}var z=is();try{var V=v&&v.db._novip===this.db._novip?v===Ue.trans?v._promise(d,$,y):yn(function(){return v._promise(d,$,y)},{trans:v,transless:Ue.transless||Ue}):function re(J,Y,X,te){if(J.idbdb&&(J._state.openComplete||Ue.letThrough||J._vip)){var Q=J._createTransaction(Y,X,J._dbSchema);try{Q.create(),J._state.PR1398_maxLoop=3}catch(Z){return Z.name===pt.InvalidState&&J.isOpen()&&0<--J._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),J.close({disableAutoOpen:!1}),J.open().then(function(){return re(J,Y,X,te)})):Pt(Z)}return Q._promise(Y,function(Z,ee){return yn(function(){return Ue.trans=Q,te(Z,ee,Q)})}).then(function(Z){if(Y==="readwrite")try{Q.idbtrans.commit()}catch{}return Y==="readonly"?Z:Q._completion.then(function(){return Z})})}if(J._state.openComplete)return Pt(new Oe.DatabaseClosed(J._state.dbOpenError));if(!J._state.isBeingOpened){if(!J._state.autoOpen)return Pt(new Oe.DatabaseClosed);J.open().catch(Xe)}return J._state.dbReadyPromise.then(function(){return re(J,Y,X,te)})}(this.db,d,[this.name],$);return E&&(V._consoleTask=E,V=V.catch(function(re){return console.trace(re),Pt(re)})),V}finally{z&&ws()}},qt.prototype.get=function(d,h){var y=this;return d&&d.constructor===Object?this.where(d).first(h):d==null?Pt(new Oe.Type("Invalid argument to Table.get()")):this._trans("readonly",function(v){return y.core.get({trans:v,key:d}).then(function(T){return y.hook.reading.fire(T)})}).then(h)},qt.prototype.where=function(d){if(typeof d=="string")return new this.db.WhereClause(this,d);if(l(d))return new this.db.WhereClause(this,"[".concat(d.join("+"),"]"));var h=i(d);if(h.length===1)return this.where(h[0]).equals(d[h[0]]);var y=this.schema.indexes.concat(this.schema.primKey).filter(function(z){if(z.compound&&h.every(function(re){return 0<=z.keyPath.indexOf(re)})){for(var V=0;V<h.length;++V)if(h.indexOf(z.keyPath[V])===-1)return!1;return!0}return!1}).sort(function(z,V){return z.keyPath.length-V.keyPath.length})[0];if(y&&this.db._maxKey!==un)return $=y.keyPath.slice(0,h.length),this.where($).equals($.map(function(z){return d[z]}));!y&&Le&&console.warn("The query ".concat(JSON.stringify(d)," on ").concat(this.name," would benefit from a ")+"compound index [".concat(h.join("+"),"]"));var v=this.schema.idxByName;function T(z,V){return Tt(z,V)===0}var $=h.reduce(function(J,V){var re=J[0],J=J[1],Y=v[V],X=d[V];return[re||Y,re||!Y?Or(J,Y&&Y.multi?function(te){return te=D(te,V),l(te)&&te.some(function(Q){return T(X,Q)})}:function(te){return T(X,D(te,V))}):J]},[null,null]),E=$[0],$=$[1];return E?this.where(E.name).equals(d[E.keyPath]).filter($):y?this.filter($):this.where(h).equals("")},qt.prototype.filter=function(d){return this.toCollection().and(d)},qt.prototype.count=function(d){return this.toCollection().count(d)},qt.prototype.offset=function(d){return this.toCollection().offset(d)},qt.prototype.limit=function(d){return this.toCollection().limit(d)},qt.prototype.each=function(d){return this.toCollection().each(d)},qt.prototype.toArray=function(d){return this.toCollection().toArray(d)},qt.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},qt.prototype.orderBy=function(d){return new this.db.Collection(new this.db.WhereClause(this,l(d)?"[".concat(d.join("+"),"]"):d))},qt.prototype.reverse=function(){return this.toCollection().reverse()},qt.prototype.mapToClass=function(d){for(var h=this.db,y=this.name,v=((this.schema.mappedClass=d).prototype instanceof $h&&(d=($=>{var z=J,V=$;if(typeof V!="function"&&V!==null)throw new TypeError("Class extends value "+String(V)+" is not a constructor or null");function re(){this.constructor=z}function J(){return $!==null&&$.apply(this,arguments)||this}return n(z,V),z.prototype=V===null?Object.create(V):(re.prototype=V.prototype,new re),Object.defineProperty(J.prototype,"db",{get:function(){return h},enumerable:!1,configurable:!0}),J.prototype.table=function(){return y},J})(d)),new Set),T=d.prototype;T;T=u(T))Object.getOwnPropertyNames(T).forEach(function($){return v.add($)});function E($){if(!$)return $;var z,V=Object.create(d.prototype);for(z in $)if(!v.has(z))try{V[z]=$[z]}catch{}return V}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=E,this.hook("reading",E),d},qt.prototype.defineClass=function(){return this.mapToClass(function(d){c(this,d)})},qt.prototype.add=function(d,h){var y=this,v=this.schema.primKey,T=v.auto,E=v.keyPath,$=d;return E&&T&&($=il(E)(d)),this._trans("readwrite",function(z){return y.core.mutate({trans:z,type:"add",keys:h!=null?[h]:null,values:[$]})}).then(function(z){return z.numFailures?Be.reject(z.failures[0]):z.lastResult}).then(function(z){if(E)try{A(d,E,z)}catch{}return z})},qt.prototype.upsert=function(d,h){var y=this,v=this.schema.primKey.keyPath;return this._trans("readwrite",function(T){return y.core.get({trans:T,key:d}).then(function(E){var $=E??{};return Nh($,h),v&&A($,v,d),y.core.mutate({trans:T,type:"put",values:[$],keys:[d],upsert:!0,updates:{keys:[d],changeSpecs:[h]}}).then(function(z){return z.numFailures?Be.reject(z.failures[0]):!!E})})})},qt.prototype.update=function(d,h){return typeof d!="object"||l(d)?this.where(":id").equals(d).modify(h):(d=D(d,this.schema.primKey.keyPath))===void 0?Pt(new Oe.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(d).modify(h)},qt.prototype.put=function(d,h){var y=this,v=this.schema.primKey,T=v.auto,E=v.keyPath,$=d;return E&&T&&($=il(E)(d)),this._trans("readwrite",function(z){return y.core.mutate({trans:z,type:"put",values:[$],keys:h!=null?[h]:null})}).then(function(z){return z.numFailures?Be.reject(z.failures[0]):z.lastResult}).then(function(z){if(E)try{A(d,E,z)}catch{}return z})},qt.prototype.delete=function(d){var h=this;return this._trans("readwrite",function(y){return h.core.mutate({trans:y,type:"delete",keys:[d]}).then(function(v){return ll(h,[d],v)}).then(function(v){return v.numFailures?Be.reject(v.failures[0]):void 0})})},qt.prototype.clear=function(){var d=this;return this._trans("readwrite",function(h){return d.core.mutate({trans:h,type:"deleteRange",range:Oh}).then(function(y){return ll(d,null,y)})}).then(function(h){return h.numFailures?Be.reject(h.failures[0]):void 0})},qt.prototype.bulkGet=function(d){var h=this;return this._trans("readonly",function(y){return h.core.getMany({keys:d,trans:y}).then(function(v){return v.map(function(T){return h.hook.reading.fire(T)})})})},qt.prototype.bulkAdd=function(d,h,y){var v=this,T=Array.isArray(h)?h:void 0,E=(y=y||(T?void 0:h))?y.allKeys:void 0;return this._trans("readwrite",function($){var z=v.schema.primKey,re=z.auto,z=z.keyPath;if(z&&T)throw new Oe.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(T&&T.length!==d.length)throw new Oe.InvalidArgument("Arguments objects and keys must have the same length");var V=d.length,re=z&&re?d.map(il(z)):d;return v.core.mutate({trans:$,type:"add",keys:T,values:re,wantResults:E}).then(function(J){var Y=J.numFailures,X=J.failures;if(Y===0)return E?J.results:J.lastResult;throw new st("".concat(v.name,".bulkAdd(): ").concat(Y," of ").concat(V," operations failed"),X)})})},qt.prototype.bulkPut=function(d,h,y){var v=this,T=Array.isArray(h)?h:void 0,E=(y=y||(T?void 0:h))?y.allKeys:void 0;return this._trans("readwrite",function($){var z=v.schema.primKey,re=z.auto,z=z.keyPath;if(z&&T)throw new Oe.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(T&&T.length!==d.length)throw new Oe.InvalidArgument("Arguments objects and keys must have the same length");var V=d.length,re=z&&re?d.map(il(z)):d;return v.core.mutate({trans:$,type:"put",keys:T,values:re,wantResults:E}).then(function(J){var Y=J.numFailures,X=J.failures;if(Y===0)return E?J.results:J.lastResult;throw new st("".concat(v.name,".bulkPut(): ").concat(Y," of ").concat(V," operations failed"),X)})})},qt.prototype.bulkUpdate=function(d){var h=this,y=this.core,v=d.map(function($){return $.key}),T=d.map(function($){return $.changes}),E=[];return this._trans("readwrite",function($){return y.getMany({trans:$,keys:v,cache:"clone"}).then(function(z){var V=[],re=[],J=(d.forEach(function(Y,X){var te=Y.key,Q=Y.changes,Z=z[X];if(Z){for(var ee=0,ce=Object.keys(Q);ee<ce.length;ee++){var oe=ce[ee],ge=Q[oe];if(oe===h.schema.primKey.keyPath){if(Tt(ge,te)!==0)throw new Oe.Constraint("Cannot update primary key in bulkUpdate()")}else A(Z,oe,ge)}E.push(X),V.push(te),re.push(Z)}}),V.length);return y.mutate({trans:$,type:"put",keys:V,values:re,updates:{keys:v,changeSpecs:T}}).then(function(Y){var X=Y.numFailures,te=Y.failures;if(X===0)return J;for(var Q=0,Z=Object.keys(te);Q<Z.length;Q++){var ee,ce=Z[Q],oe=E[Number(ce)];oe!=null&&(ee=te[ce],delete te[ce],te[oe]=ee)}throw new st("".concat(h.name,".bulkUpdate(): ").concat(X," of ").concat(J," operations failed"),te)})})})},qt.prototype.bulkDelete=function(d){var h=this,y=d.length;return this._trans("readwrite",function(v){return h.core.mutate({trans:v,type:"delete",keys:d}).then(function(T){return ll(h,d,T)})}).then(function(v){var T=v.numFailures,E=v.failures;if(T===0)return v.lastResult;throw new st("".concat(h.name,".bulkDelete(): ").concat(T," of ").concat(y," operations failed"),E)})};var zh=qt;function qt(){}function na(d){function h($,z){if(z){for(var V=arguments.length,re=new Array(V-1);--V;)re[V-1]=arguments[V];return y[$].subscribe.apply(null,re),d}if(typeof $=="string")return y[$]}var y={};h.addEventType=E;for(var v=1,T=arguments.length;v<T;++v)E(arguments[v]);return h;function E($,z,V){var re,J;if(typeof $!="object")return z=z||be,J={subscribers:[],fire:V=V||Xe,subscribe:function(Y){J.subscribers.indexOf(Y)===-1&&(J.subscribers.push(Y),J.fire=z(J.fire,Y))},unsubscribe:function(Y){J.subscribers=J.subscribers.filter(function(X){return X!==Y}),J.fire=J.subscribers.reduce(z,V)}},y[$]=h[$]=J;i(re=$).forEach(function(Y){var X=re[Y];if(l(X))E(Y,re[Y][0],re[Y][1]);else{if(X!=="asap")throw new Oe.InvalidArgument("Invalid event config");var te=E(Y,_e,function(){for(var Q=arguments.length,Z=new Array(Q);Q--;)Z[Q]=arguments[Q];te.subscribers.forEach(function(ee){C(function(){ee.apply(null,Z)})})})}})}}function sa(d,h){return x(h).from({prototype:d}),h}function yo(d,h){return!(d.filter||d.algorithm||d.or)&&(h?d.justLimit:!d.replayFilter)}function od(d,h){d.filter=Or(d.filter,h)}function ad(d,h,y){var v=d.replayFilter;d.replayFilter=v?function(){return Or(v(),h())}:h,d.justLimit=y&&!v}function cl(d,h){if(d.isPrimKey)return h.primaryKey;var y=h.getIndexByKeyPath(d.index);if(y)return y;throw new Oe.Schema("KeyPath "+d.index+" on object store "+h.name+" is not indexed")}function Bh(d,h,y){var v=cl(d,h.schema);return h.openCursor({trans:y,values:!d.keysOnly,reverse:d.dir==="prev",unique:!!d.unique,query:{index:v,range:d.range}})}function dl(d,h,y,v){var T,E,$=d.replayFilter?Or(d.filter,d.replayFilter()):d.filter;return d.or?(T={},E=function(z,V,re){var J,Y;$&&!$(V,re,function(X){return V.stop(X)},function(X){return V.fail(X)})||((Y=""+(J=V.primaryKey))=="[object ArrayBuffer]"&&(Y=""+new Uint8Array(J)),p(T,Y))||(T[Y]=!0,h(z,V,re))},Promise.all([d.or._iterate(E,y),Wh(Bh(d,v,y),d.algorithm,E,!d.keysOnly&&d.valueMapper)])):Wh(Bh(d,v,y),Or(d.algorithm,$),h,!d.keysOnly&&d.valueMapper)}function Wh(d,h,y,v){var T=tt(v?function(E,$,z){return y(v(E),$,z)}:y);return d.then(function(E){if(E)return E.start(function(){var $=function(){return E.continue()};h&&!h(E,function(z){return $=z},function(z){E.stop(z),$=Xe},function(z){E.fail(z),$=Xe})||T(E.value,E,function(z){return $=z}),$()})})}Rt.prototype._read=function(d,h){var y=this._ctx;return y.error?y.table._trans(null,Pt.bind(null,y.error)):y.table._trans("readonly",d).then(h)},Rt.prototype._write=function(d){var h=this._ctx;return h.error?h.table._trans(null,Pt.bind(null,h.error)):h.table._trans("readwrite",d,"locked")},Rt.prototype._addAlgorithm=function(d){var h=this._ctx;h.algorithm=Or(h.algorithm,d)},Rt.prototype._iterate=function(d,h){return dl(this._ctx,d,h,this._ctx.table.core)},Rt.prototype.clone=function(d){var h=Object.create(this.constructor.prototype),y=Object.create(this._ctx);return d&&c(y,d),h._ctx=y,h},Rt.prototype.raw=function(){return this._ctx.valueMapper=null,this},Rt.prototype.each=function(d){var h=this._ctx;return this._read(function(y){return dl(h,d,y,h.table.core)})},Rt.prototype.count=function(d){var h=this;return this._read(function(y){var v,T=h._ctx,E=T.table.core;return yo(T,!0)?E.count({trans:y,query:{index:cl(T,E.schema),range:T.range}}).then(function($){return Math.min($,T.limit)}):(v=0,dl(T,function(){return++v,!1},y,E).then(function(){return v}))}).then(d)},Rt.prototype.sortBy=function(d,h){var y=d.split(".").reverse(),v=y[0],T=y.length-1;function E(V,re){return re?E(V[y[re]],re-1):V[v]}var $=this._ctx.dir==="next"?1:-1;function z(V,re){return Tt(E(V,T),E(re,T))*$}return this.toArray(function(V){return V.sort(z)}).then(h)},Rt.prototype.toArray=function(d){var h=this;return this._read(function(y){var v,T,E,$=h._ctx;return yo($,!0)&&0<$.limit?(v=$.valueMapper,T=cl($,$.table.core.schema),$.table.core.query({trans:y,limit:$.limit,values:!0,direction:$.dir==="prev"?"prev":void 0,query:{index:T,range:$.range}}).then(function(z){return z=z.result,v?z.map(v):z})):(E=[],dl($,function(z){return E.push(z)},y,$.table.core).then(function(){return E}))},d)},Rt.prototype.offset=function(d){var h=this._ctx;return d<=0||(h.offset+=d,yo(h)?ad(h,function(){var y=d;return function(v,T){return y===0||(y===1?--y:T(function(){v.advance(y),y=0}),!1)}}):ad(h,function(){var y=d;return function(){return--y<0}})),this},Rt.prototype.limit=function(d){return this._ctx.limit=Math.min(this._ctx.limit,d),ad(this._ctx,function(){var h=d;return function(y,v,T){return--h<=0&&v(T),0<=h}},!0),this},Rt.prototype.until=function(d,h){return od(this._ctx,function(y,v,T){return!d(y.value)||(v(T),h)}),this},Rt.prototype.first=function(d){return this.limit(1).toArray(function(h){return h[0]}).then(d)},Rt.prototype.last=function(d){return this.reverse().first(d)},Rt.prototype.filter=function(d){var h;return od(this._ctx,function(y){return d(y.value)}),(h=this._ctx).isMatch=Or(h.isMatch,d),this},Rt.prototype.and=function(d){return this.filter(d)},Rt.prototype.or=function(d){return new this.db.WhereClause(this._ctx.table,d,this)},Rt.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},Rt.prototype.desc=function(){return this.reverse()},Rt.prototype.eachKey=function(d){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(y,v){d(v.key,v)})},Rt.prototype.eachUniqueKey=function(d){return this._ctx.unique="unique",this.eachKey(d)},Rt.prototype.eachPrimaryKey=function(d){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(y,v){d(v.primaryKey,v)})},Rt.prototype.keys=function(d){var h=this._ctx,y=(h.keysOnly=!h.isMatch,[]);return this.each(function(v,T){y.push(T.key)}).then(function(){return y}).then(d)},Rt.prototype.primaryKeys=function(d){var h=this._ctx;if(yo(h,!0)&&0<h.limit)return this._read(function(v){var T=cl(h,h.table.core.schema);return h.table.core.query({trans:v,values:!1,limit:h.limit,direction:h.dir==="prev"?"prev":void 0,query:{index:T,range:h.range}})}).then(function(v){return v.result}).then(d);h.keysOnly=!h.isMatch;var y=[];return this.each(function(v,T){y.push(T.primaryKey)}).then(function(){return y}).then(d)},Rt.prototype.uniqueKeys=function(d){return this._ctx.unique="unique",this.keys(d)},Rt.prototype.firstKey=function(d){return this.limit(1).keys(function(h){return h[0]}).then(d)},Rt.prototype.lastKey=function(d){return this.reverse().firstKey(d)},Rt.prototype.distinct=function(){var d,h=this._ctx,h=h.index&&h.table.schema.idxByName[h.index];return h&&h.multi&&(d={},od(this._ctx,function(v){var v=v.primaryKey.toString(),T=p(d,v);return d[v]=!0,!T})),this},Rt.prototype.modify=function(d){var h=this,y=this._ctx;return this._write(function(v){function T(Z,ee){var ce=ee.failures;X+=Z-ee.numFailures;for(var oe=0,ge=i(ce);oe<ge.length;oe++){var Te=ge[oe];Y.push(ce[Te])}}var E=typeof d=="function"?d:function(Z){return Nh(Z,d)},$=y.table.core,J=$.schema.primaryKey,z=J.outbound,V=J.extractKey,re=200,J=h.db._options.modifyChunkSize,Y=(J&&(re=typeof J=="object"?J[$.name]||J["*"]||200:J),[]),X=0,te=[],Q=d===qh;return h.clone().primaryKeys().then(function(Z){function ee(oe){var ge=Math.min(re,Z.length-oe),Te=Z.slice(oe,oe+ge);return(Q?Promise.resolve([]):$.getMany({trans:v,keys:Te,cache:"immutable"})).then(function(Me){var $e=[],Ee=[],Ve=z?[]:null,Ie=Q?Te:[];if(!Q)for(var Ge=0;Ge<ge;++Ge){var je=Me[Ge],ct={value:L(je),primKey:Z[oe+Ge]};E.call(ct,ct.value,ct)!==!1&&(ct.value==null?Ie.push(Z[oe+Ge]):z||Tt(V(je),V(ct.value))===0?(Ee.push(ct.value),z&&Ve.push(Z[oe+Ge])):(Ie.push(Z[oe+Ge]),$e.push(ct.value)))}return Promise.resolve(0<$e.length&&$.mutate({trans:v,type:"add",values:$e}).then(function(dt){for(var ft in dt.failures)Ie.splice(parseInt(ft),1);T($e.length,dt)})).then(function(){return(0<Ee.length||ce&&typeof d=="object")&&$.mutate({trans:v,type:"put",keys:Ve,values:Ee,criteria:ce,changeSpec:typeof d!="function"&&d,isAdditionalChunk:0<oe}).then(function(dt){return T(Ee.length,dt)})}).then(function(){return(0<Ie.length||ce&&Q)&&$.mutate({trans:v,type:"delete",keys:Ie,criteria:ce,isAdditionalChunk:0<oe}).then(function(dt){return ll(y.table,Ie,dt)}).then(function(dt){return T(Ie.length,dt)})}).then(function(){return Z.length>oe+ge&&ee(oe+re)})})}var ce=yo(y)&&y.limit===1/0&&(typeof d!="function"||Q)&&{index:y.index,range:y.range};return ee(0).then(function(){if(0<Y.length)throw new ze("Error modifying one or more objects",Y,X,te);return Z.length})})})},Rt.prototype.delete=function(){var d=this._ctx,h=d.range;return!yo(d)||d.table.schema.yProps||!d.isPrimKey&&h.type!==3?this.modify(qh):this._write(function(y){var v=d.table.core.schema.primaryKey,T=h;return d.table.core.count({trans:y,query:{index:v,range:T}}).then(function(E){return d.table.core.mutate({trans:y,type:"deleteRange",range:T}).then(function(V){var z=V.failures,V=V.numFailures;if(V)throw new ze("Could not delete some values",Object.keys(z).map(function(re){return z[re]}),E-V);return E-V})})})};var yw=Rt;function Rt(){}var qh=function(d,h){return h.value=null};function bw(d,h){return d<h?-1:d===h?0:1}function xw(d,h){return h<d?-1:d===h?0:1}function Qn(d,h,y){return d=d instanceof Hh?new d.Collection(d):d,d._ctx.error=new(y||TypeError)(h),d}function bo(d){return new d.Collection(d,function(){return Uh("")}).limit(0)}function ul(te,h,y,v){var T,E,$,z,V,re,J,Y=y.length;if(!y.every(function(Z){return typeof Z=="string"}))return Qn(te,ea);function X(Z){T=Z==="next"?function(ce){return ce.toUpperCase()}:function(ce){return ce.toLowerCase()},E=Z==="next"?function(ce){return ce.toLowerCase()}:function(ce){return ce.toUpperCase()},$=Z==="next"?bw:xw;var ee=y.map(function(ce){return{lower:E(ce),upper:T(ce)}}).sort(function(ce,oe){return $(ce.lower,oe.lower)});z=ee.map(function(ce){return ce.upper}),V=ee.map(function(ce){return ce.lower}),J=(re=Z)==="next"?"":v}X("next");var te=new te.Collection(te,function(){return hr(z[0],V[Y-1]+v)}),Q=(te._ondirectionchange=function(Z){X(Z)},0);return te._addAlgorithm(function(Z,ee,ce){var oe=Z.key;if(typeof oe=="string"){var ge=E(oe);if(h(ge,V,Q))return!0;for(var Te=null,Me=Q;Me<Y;++Me){var $e=((Ee,Ve,Ie,Ge,je,ct)=>{for(var dt=Math.min(Ee.length,Ge.length),ft=-1,_t=0;_t<dt;++_t){var Zn=Ve[_t];if(Zn!==Ge[_t])return je(Ee[_t],Ie[_t])<0?Ee.substr(0,_t)+Ie[_t]+Ie.substr(_t+1):je(Ee[_t],Ge[_t])<0?Ee.substr(0,_t)+Ge[_t]+Ie.substr(_t+1):0<=ft?Ee.substr(0,ft)+Ve[ft]+Ie.substr(ft+1):null;je(Ee[_t],Zn)<0&&(ft=_t)}return dt<Ge.length&&ct==="next"?Ee+Ie.substr(Ee.length):dt<Ee.length&&ct==="prev"?Ee.substr(0,Ie.length):ft<0?null:Ee.substr(0,ft)+Ge[ft]+Ie.substr(ft+1)})(oe,ge,z[Me],V[Me],$,re);$e===null&&Te===null?Q=Me+1:(Te===null||0<$(Te,$e))&&(Te=$e)}ee(Te!==null?function(){Z.continue(Te+J)}:ce)}return!1}),te}function hr(d,h,y,v){return{type:2,lower:d,upper:h,lowerOpen:y,upperOpen:v}}function Uh(d){return{type:1,lower:d,upper:d}}Object.defineProperty(bn.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),bn.prototype.between=function(d,h,y,v){y=y!==!1,v=v===!0;try{return 0<this._cmp(d,h)||this._cmp(d,h)===0&&(y||v)&&(!y||!v)?bo(this):new this.Collection(this,function(){return hr(d,h,!y,!v)})}catch{return Qn(this,an)}},bn.prototype.equals=function(d){return d==null?Qn(this,an):new this.Collection(this,function(){return Uh(d)})},bn.prototype.above=function(d){return d==null?Qn(this,an):new this.Collection(this,function(){return hr(d,void 0,!0)})},bn.prototype.aboveOrEqual=function(d){return d==null?Qn(this,an):new this.Collection(this,function(){return hr(d,void 0,!1)})},bn.prototype.below=function(d){return d==null?Qn(this,an):new this.Collection(this,function(){return hr(void 0,d,!1,!0)})},bn.prototype.belowOrEqual=function(d){return d==null?Qn(this,an):new this.Collection(this,function(){return hr(void 0,d)})},bn.prototype.startsWith=function(d){return typeof d!="string"?Qn(this,ea):this.between(d,d+un,!0,!0)},bn.prototype.startsWithIgnoreCase=function(d){return d===""?this.startsWith(d):ul(this,function(h,y){return h.indexOf(y[0])===0},[d],un)},bn.prototype.equalsIgnoreCase=function(d){return ul(this,function(h,y){return h===y[0]},[d],"")},bn.prototype.anyOfIgnoreCase=function(){var d=K.apply(ne,arguments);return d.length===0?bo(this):ul(this,function(h,y){return y.indexOf(h)!==-1},d,"")},bn.prototype.startsWithAnyOfIgnoreCase=function(){var d=K.apply(ne,arguments);return d.length===0?bo(this):ul(this,function(h,y){return y.some(function(v){return h.indexOf(v)===0})},d,un)},bn.prototype.anyOf=function(){var d,h,y=this,v=K.apply(ne,arguments),T=this._cmp;try{v.sort(T)}catch{return Qn(this,an)}return v.length===0?bo(this):((d=new this.Collection(this,function(){return hr(v[0],v[v.length-1])}))._ondirectionchange=function(E){T=E==="next"?y._ascending:y._descending,v.sort(T)},h=0,d._addAlgorithm(function(E,$,z){for(var V=E.key;0<T(V,v[h]);)if(++h===v.length)return $(z),!1;return T(V,v[h])===0||($(function(){E.continue(v[h])}),!1)}),d)},bn.prototype.notEqual=function(d){return this.inAnyRange([[-1/0,d],[d,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},bn.prototype.noneOf=function(){var d=K.apply(ne,arguments);if(d.length===0)return new this.Collection(this);try{d.sort(this._ascending)}catch{return Qn(this,an)}var h=d.reduce(function(y,v){return y?y.concat([[y[y.length-1][1],v]]):[[-1/0,v]]},null);return h.push([d[d.length-1],this.db._maxKey]),this.inAnyRange(h,{includeLowers:!1,includeUppers:!1})},bn.prototype.inAnyRange=function(d,ce){var y=this,v=this._cmp,T=this._ascending,E=this._descending,$=this._min,z=this._max;if(d.length===0)return bo(this);if(!d.every(function(oe){return oe[0]!==void 0&&oe[1]!==void 0&&T(oe[0],oe[1])<=0}))return Qn(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",Oe.InvalidArgument);var V=!ce||ce.includeLowers!==!1,re=ce&&ce.includeUppers===!0,J,Y=T;function X(oe,ge){return Y(oe[0],ge[0])}try{(J=d.reduce(function(oe,ge){for(var Te=0,Me=oe.length;Te<Me;++Te){var $e=oe[Te];if(v(ge[0],$e[1])<0&&0<v(ge[1],$e[0])){$e[0]=$($e[0],ge[0]),$e[1]=z($e[1],ge[1]);break}}return Te===Me&&oe.push(ge),oe},[])).sort(X)}catch{return Qn(this,an)}var te=0,Q=re?function(oe){return 0<T(oe,J[te][1])}:function(oe){return 0<=T(oe,J[te][1])},Z=V?function(oe){return 0<E(oe,J[te][0])}:function(oe){return 0<=E(oe,J[te][0])},ee=Q,ce=new this.Collection(this,function(){return hr(J[0][0],J[J.length-1][1],!V,!re)});return ce._ondirectionchange=function(oe){Y=oe==="next"?(ee=Q,T):(ee=Z,E),J.sort(X)},ce._addAlgorithm(function(oe,ge,Te){for(var Me,$e=oe.key;ee($e);)if(++te===J.length)return ge(Te),!1;return!Q(Me=$e)&&!Z(Me)||(y._cmp($e,J[te][1])===0||y._cmp($e,J[te][0])===0||ge(function(){Y===T?oe.continue(J[te][0]):oe.continue(J[te][1])}),!1)}),ce},bn.prototype.startsWithAnyOf=function(){var d=K.apply(ne,arguments);return d.every(function(h){return typeof h=="string"})?d.length===0?bo(this):this.inAnyRange(d.map(function(h){return[h,h+un]})):Qn(this,"startsWithAnyOf() only works with strings")};var Hh=bn;function bn(){}function Ts(d){return tt(function(h){return ra(h),d(h.target.error),!1})}function ra(d){d.stopPropagation&&d.stopPropagation(),d.preventDefault&&d.preventDefault()}var oa="storagemutated",id="x-storagemutated-1",fr=na(null,oa),vw=(Ls.prototype._lock=function(){return _(!Ue.global),++this._reculock,this._reculock!==1||Ue.global||(Ue.lockOwnerFor=this),this},Ls.prototype._unlock=function(){if(_(!Ue.global),--this._reculock==0)for(Ue.global||(Ue.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var d=this._blockedFuncs.shift();try{Nt(d[1],d[0])}catch{}}return this},Ls.prototype._locked=function(){return this._reculock&&Ue.lockOwnerFor!==this},Ls.prototype.create=function(d){var h=this;if(this.mode){var y=this.db.idbdb,v=this.db._state.dbOpenError;if(_(!this.idbtrans),!d&&!y)switch(v&&v.name){case"DatabaseClosedError":throw new Oe.DatabaseClosed(v);case"MissingAPIError":throw new Oe.MissingAPI(v.message,v);default:throw new Oe.OpenFailed(v)}if(!this.active)throw new Oe.TransactionInactive;_(this._completion._state===null),(d=this.idbtrans=d||(this.db.core||y).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=tt(function(T){ra(T),h._reject(d.error)}),d.onabort=tt(function(T){ra(T),h.active&&h._reject(new Oe.Abort(d.error)),h.active=!1,h.on("abort").fire(T)}),d.oncomplete=tt(function(){h.active=!1,h._resolve(),"mutatedParts"in d&&fr.storagemutated.fire(d.mutatedParts)})}return this},Ls.prototype._promise=function(d,h,y){var v,T=this;return d==="readwrite"&&this.mode!=="readwrite"?Pt(new Oe.ReadOnly("Transaction is readonly")):this.active?this._locked()?new Be(function(E,$){T._blockedFuncs.push([function(){T._promise(d,h,y).then(E,$)},Ue])}):y?yn(function(){var E=new Be(function($,z){T._lock();var V=h($,z,T);V&&V.then&&V.then($,z)});return E.finally(function(){return T._unlock()}),E._lib=!0,E}):((v=new Be(function(E,$){var z=h(E,$,T);z&&z.then&&z.then(E,$)}))._lib=!0,v):Pt(new Oe.TransactionInactive)},Ls.prototype._root=function(){return this.parent?this.parent._root():this},Ls.prototype.waitFor=function(d){var h,y=this._root(),v=Be.resolve(d),T=(y._waitingFor?y._waitingFor=y._waitingFor.then(function(){return v}):(y._waitingFor=v,y._waitingQueue=[],h=y.idbtrans.objectStore(y.storeNames[0]),function E(){for(++y._spinCount;y._waitingQueue.length;)y._waitingQueue.shift()();y._waitingFor&&(h.get(-1/0).onsuccess=E)}()),y._waitingFor);return new Be(function(E,$){v.then(function(z){return y._waitingQueue.push(tt(E.bind(null,z)))},function(z){return y._waitingQueue.push(tt($.bind(null,z)))}).finally(function(){y._waitingFor===T&&(y._waitingFor=null)})})},Ls.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new Oe.Abort))},Ls.prototype.table=function(d){var h=this._memoizedTables||(this._memoizedTables={});if(p(h,d))return h[d];var y=this.schema[d];if(y)return(y=new this.db.Table(d,y,this)).core=this.db.core.table(d),h[d]=y;throw new Oe.NotFound("Table "+d+" not part of transaction")},Ls);function Ls(){}function ld(d,h,y,v,T,E,$,z){return{name:d,keyPath:h,unique:y,multi:v,auto:T,compound:E,src:(y&&!$?"&":"")+(v?"*":"")+(T?"++":"")+Kh(h),type:z}}function Kh(d){return typeof d=="string"?d:d?"["+[].join.call(d,"+")+"]":""}function cd(d,h,y){return{name:d,primKey:h,indexes:y,mappedClass:null,idxByName:(v=function(T){return[T.name,T]},y.reduce(function(T,E,$){return E=v(E,$),E&&(T[E[0]]=E[1]),T},{}))};var v}var aa=function(d){try{return d.only([[]]),aa=function(){return[[]]},[[]]}catch{return aa=function(){return un},un}};function dd(d){return d==null?function(){}:typeof d=="string"?(h=d).split(".").length===1?function(y){return y[h]}:function(y){return D(y,h)}:function(y){return D(y,d)};var h}function Yh(d){return[].slice.call(d)}var Sw=0;function ia(d){return d==null?":id":typeof d=="string"?d:"[".concat(d.join("+"),"]")}function ww(d,h,$){function v(ee){if(ee.type===3)return null;if(ee.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var te=ee.lower,Q=ee.upper,Z=ee.lowerOpen,ee=ee.upperOpen;return te===void 0?Q===void 0?null:h.upperBound(Q,!!ee):Q===void 0?h.lowerBound(te,!!Z):h.bound(te,Q,!!Z,!!ee)}function T(X){var te,Q,Z=X.name;return{name:Z,schema:X,mutate:function(ee){var ce=ee.trans,oe=ee.type,ge=ee.keys,Te=ee.values,Me=ee.range;return new Promise(function($e,Ee){$e=tt($e);var Ve=ce.objectStore(Z),Ie=Ve.keyPath==null,Ge=oe==="put"||oe==="add";if(!Ge&&oe!=="delete"&&oe!=="deleteRange")throw new Error("Invalid operation type: "+oe);var je,ct=(ge||Te||{length:1}).length;if(ge&&Te&&ge.length!==Te.length)throw new Error("Given keys array must have same length as given values array.");if(ct===0)return $e({numFailures:0,failures:{},results:[],lastResult:void 0});function dt(Ln){++Zn,ra(Ln)}var ft=[],_t=[],Zn=0;if(oe==="deleteRange"){if(Me.type===4)return $e({numFailures:Zn,failures:_t,results:[],lastResult:void 0});Me.type===3?ft.push(je=Ve.clear()):ft.push(je=Ve.delete(v(Me)))}else{var Ie=Ge?Ie?[Te,ge]:[Te,null]:[ge,null],ht=Ie[0],On=Ie[1];if(Ge)for(var $n=0;$n<ct;++$n)ft.push(je=On&&On[$n]!==void 0?Ve[oe](ht[$n],On[$n]):Ve[oe](ht[$n])),je.onerror=dt;else for($n=0;$n<ct;++$n)ft.push(je=Ve[oe](ht[$n])),je.onerror=dt}function _l(Ln){Ln=Ln.target.result,ft.forEach(function(Lr,Md){return Lr.error!=null&&(_t[Md]=Lr.error)}),$e({numFailures:Zn,failures:_t,results:oe==="delete"?ge:ft.map(function(Lr){return Lr.result}),lastResult:Ln})}je.onerror=function(Ln){dt(Ln),_l(Ln)},je.onsuccess=_l})},getMany:function(ee){var ce=ee.trans,oe=ee.keys;return new Promise(function(ge,Te){ge=tt(ge);for(var Me,$e=ce.objectStore(Z),Ee=oe.length,Ve=new Array(Ee),Ie=0,Ge=0,je=function(ft){ft=ft.target,Ve[ft._pos]=ft.result,++Ge===Ie&&ge(Ve)},ct=Ts(Te),dt=0;dt<Ee;++dt)oe[dt]!=null&&((Me=$e.get(oe[dt]))._pos=dt,Me.onsuccess=je,Me.onerror=ct,++Ie);Ie===0&&ge(Ve)})},get:function(ee){var ce=ee.trans,oe=ee.key;return new Promise(function(ge,Te){ge=tt(ge);var Me=ce.objectStore(Z).get(oe);Me.onsuccess=function($e){return ge($e.target.result)},Me.onerror=Ts(Te)})},query:(te=V,Q=re,function(ee){return new Promise(function(ce,oe){ce=tt(ce);var ge,Te,Me,$e,ct=ee.trans,Ee=ee.values,Ve=ee.limit,je=ee.query,Ie=(Ie=ee.direction)!=null?Ie:"next",Ge=Ve===1/0?void 0:Ve,dt=je.index,je=je.range,ct=ct.objectStore(Z),ct=dt.isPrimaryKey?ct:ct.index(dt.name),dt=v(je);if(Ve===0)return ce({result:[]});Q?(je={query:dt,count:Ge,direction:Ie},(ge=Ee?ct.getAll(je):ct.getAllKeys(je)).onsuccess=function(ft){return ce({result:ft.target.result})},ge.onerror=Ts(oe)):te&&Ie==="next"?((ge=Ee?ct.getAll(dt,Ge):ct.getAllKeys(dt,Ge)).onsuccess=function(ft){return ce({result:ft.target.result})},ge.onerror=Ts(oe)):(Te=0,Me=!Ee&&"openKeyCursor"in ct?ct.openKeyCursor(dt,Ie):ct.openCursor(dt,Ie),$e=[],Me.onsuccess=function(){var ft=Me.result;return!ft||($e.push(Ee?ft.value:ft.primaryKey),++Te===Ve)?ce({result:$e}):void ft.continue()},Me.onerror=Ts(oe))})}),openCursor:function(ee){var ce=ee.trans,oe=ee.values,ge=ee.query,Te=ee.reverse,Me=ee.unique;return new Promise(function($e,Ee){$e=tt($e);var Ge=ge.index,Ve=ge.range,Ie=ce.objectStore(Z),Ie=Ge.isPrimaryKey?Ie:Ie.index(Ge.name),Ge=Te?Me?"prevunique":"prev":Me?"nextunique":"next",je=!oe&&"openKeyCursor"in Ie?Ie.openKeyCursor(v(Ve),Ge):Ie.openCursor(v(Ve),Ge);je.onerror=Ts(Ee),je.onsuccess=tt(function(ct){var dt,ft,_t,Zn,ht=je.result;ht?(ht.___id=++Sw,ht.done=!1,dt=ht.continue.bind(ht),ft=(ft=ht.continuePrimaryKey)&&ft.bind(ht),_t=ht.advance.bind(ht),Zn=function(){throw new Error("Cursor not stopped")},ht.trans=ce,ht.stop=ht.continue=ht.continuePrimaryKey=ht.advance=function(){throw new Error("Cursor not started")},ht.fail=tt(Ee),ht.next=function(){var On=this,$n=1;return this.start(function(){return $n--?On.continue():On.stop()}).then(function(){return On})},ht.start=function(On){function $n(){if(je.result)try{On()}catch(Ln){ht.fail(Ln)}else ht.done=!0,ht.start=function(){throw new Error("Cursor behind last entry")},ht.stop()}var _l=new Promise(function(Ln,Lr){Ln=tt(Ln),je.onerror=Ts(Lr),ht.fail=Lr,ht.stop=function(Md){ht.stop=ht.continue=ht.continuePrimaryKey=ht.advance=Zn,Ln(Md)}});return je.onsuccess=tt(function(Ln){je.onsuccess=$n,$n()}),ht.continue=dt,ht.continuePrimaryKey=ft,ht.advance=_t,$n(),_l},$e(ht)):$e(null)},Ee)})},count:function(ee){var ce=ee.query,oe=ee.trans,ge=ce.index,Te=ce.range;return new Promise(function(Me,$e){var Ee=oe.objectStore(Z),Ee=ge.isPrimaryKey?Ee:Ee.index(ge.name),Ve=v(Te),Ve=Ve?Ee.count(Ve):Ee.count();Ve.onsuccess=tt(function(Ie){return Me(Ie.target.result)}),Ve.onerror=Ts($e)})}}}E=$,z=Yh(($=d).objectStoreNames),J=0<z.length?E.objectStore(z[0]):{};var E,$={schema:{name:$.name,tables:z.map(function(X){return E.objectStore(X)}).map(function(X){var te=X.keyPath,Q=X.autoIncrement,ee=l(te),Z={},ee={name:X.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:te==null,compound:ee,keyPath:te,autoIncrement:Q,unique:!0,extractKey:dd(te)},indexes:Yh(X.indexNames).map(function(ce){return X.index(ce)}).map(function(Te){var Me=Te.name,oe=Te.unique,ge=Te.multiEntry,Te=Te.keyPath,Me={name:Me,compound:l(Te),keyPath:Te,unique:oe,multiEntry:ge,extractKey:dd(Te)};return Z[ia(Te)]=Me}),getIndexByKeyPath:function(ce){return Z[ia(ce)]}};return Z[":id"]=ee.primaryKey,te!=null&&(Z[ia(te)]=ee.primaryKey),ee})},hasGetAll:0<z.length&&"getAll"in J&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604),hasIdb3Features:"getAllRecords"in J},z=$.schema,V=$.hasGetAll,re=$.hasIdb3Features,J=z.tables.map(T),Y={};return J.forEach(function(X){return Y[X.name]=X}),{stack:"dbcore",transaction:d.transaction.bind(d),table:function(X){if(Y[X])return Y[X];throw new Error("Table '".concat(X,"' not found"))},MIN_KEY:-1/0,MAX_KEY:aa(h),schema:z}}function _w(d,h,y,v){return y=y.IDBKeyRange,h=ww(h,y,v),{dbcore:d.dbcore.reduce(function(T,E){return E=E.create,s(s({},T),E(T))},h)}}function ml(d,h){var y=h.db,y=_w(d._middlewares,y,d._deps,h);d.core=y.dbcore,d.tables.forEach(function(v){var T=v.name;d.core.schema.tables.some(function(E){return E.name===T})&&(v.core=d.core.table(T),d[T]instanceof d.Table)&&(d[T].core=v.core)})}function hl(d,h,y,v){y.forEach(function(T){var E=v[T];h.forEach(function($){var z=function V(re,J){return k(re,J)||(re=u(re))&&V(re,J)}($,T);(!z||"value"in z&&z.value===void 0)&&($===d.Transaction.prototype||$ instanceof d.Transaction?S($,T,{get:function(){return this.table(T)},set:function(V){b(this,T,{value:V,writable:!0,configurable:!0,enumerable:!0})}}):$[T]=new d.Table(T,E))})})}function ud(d,h){h.forEach(function(y){for(var v in y)y[v]instanceof d.Table&&delete y[v]})}function kw(d,h){return d._cfg.version-h._cfg.version}function Tw(d,h,y,v){var T=d._dbSchema,E=(y.objectStoreNames.contains("$meta")&&!T.$meta&&(T.$meta=cd("$meta",Xh("")[0],[]),d._storeNames.push("$meta")),d._createTransaction("readwrite",d._storeNames,T)),$=(E.create(y),E._completion.catch(v),E._reject.bind(E)),z=Ue.transless||Ue;yn(function(){if(Ue.trans=E,Ue.transless=z,h!==0)return ml(d,y),re=h,((V=E).storeNames.includes("$meta")?V.table("$meta").get("version").then(function(J){return J??re}):Be.resolve(re)).then(function(ee){var Y=d,X=ee,te=E,Q=y,Z=[],ee=Y._versions,ce=Y._dbSchema=pl(0,Y.idbdb,Q);return(ee=ee.filter(function(oe){return oe._cfg.version>=X})).length===0?Be.resolve():(ee.forEach(function(oe){Z.push(function(){var ge,Te,Me,$e=ce,Ee=oe._cfg.dbschema,Ve=(gl(Y,$e,Q),gl(Y,Ee,Q),ce=Y._dbSchema=Ee,md($e,Ee)),Ie=(Ve.add.forEach(function(Ge){hd(Q,Ge[0],Ge[1].primKey,Ge[1].indexes)}),Ve.change.forEach(function(Ge){if(Ge.recreate)throw new Oe.Upgrade("Not yet support for changing primary key");var je=Q.objectStore(Ge.name);Ge.add.forEach(function(ct){return fl(je,ct)}),Ge.change.forEach(function(ct){je.deleteIndex(ct.name),fl(je,ct)}),Ge.del.forEach(function(ct){return je.deleteIndex(ct)})}),oe._cfg.contentUpgrade);if(Ie&&oe._cfg.version>X)return ml(Y,Q),te._memoizedTables={},ge=B(Ee),Ve.del.forEach(function(Ge){ge[Ge]=$e[Ge]}),ud(Y,[Y.Transaction.prototype]),hl(Y,[Y.Transaction.prototype],i(ge),ge),te.schema=ge,(Te=xe(Ie))&&An(),Ee=Be.follow(function(){var Ge;(Me=Ie(te))&&Te&&(Ge=Ds.bind(null,null),Me.then(Ge,Ge))}),Me&&typeof Me.then=="function"?Be.resolve(Me):Ee.then(function(){return Me})}),Z.push(function(ge){var Te,Me,$e=oe._cfg.dbschema;Te=$e,Me=ge,[].slice.call(Me.db.objectStoreNames).forEach(function(Ee){return Te[Ee]==null&&Me.db.deleteObjectStore(Ee)}),ud(Y,[Y.Transaction.prototype]),hl(Y,[Y.Transaction.prototype],Y._storeNames,Y._dbSchema),te.schema=Y._dbSchema}),Z.push(function(ge){Y.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(Y.idbdb.version/10)===oe._cfg.version?(Y.idbdb.deleteObjectStore("$meta"),delete Y._dbSchema.$meta,Y._storeNames=Y._storeNames.filter(function(Te){return Te!=="$meta"})):ge.objectStore("$meta").put(oe._cfg.version,"version"))})}),function oe(){return Z.length?Be.resolve(Z.shift()(te.idbtrans)).then(oe):Be.resolve()}().then(function(){Vh(ce,Q)}))}).catch($);var V,re;i(T).forEach(function(J){hd(y,J,T[J].primKey,T[J].indexes)}),ml(d,y),Be.follow(function(){return d.on.populate.fire(E)}).catch($)})}function jw(d,h){Vh(d._dbSchema,h),h.db.version%10!=0||h.objectStoreNames.contains("$meta")||h.db.createObjectStore("$meta").add(Math.ceil(h.db.version/10-1),"version");var y=pl(0,d.idbdb,h);gl(d,d._dbSchema,h);for(var v=0,T=md(y,d._dbSchema).change;v<T.length;v++){var E=($=>{if($.change.length||$.recreate)return console.warn("Unable to patch indexes of table ".concat($.name," because it has changes on the type of index or primary key.")),{value:void 0};var z=h.objectStore($.name);$.add.forEach(function(V){Le&&console.debug("Dexie upgrade patch: Creating missing index ".concat($.name,".").concat(V.src)),fl(z,V)})})(T[v]);if(typeof E=="object")return E.value}}function md(d,h){var y,v={del:[],add:[],change:[]};for(y in d)h[y]||v.del.push(y);for(y in h){var T=d[y],E=h[y];if(T){var $={name:y,def:E,recreate:!1,del:[],add:[],change:[]};if(""+(T.primKey.keyPath||"")!=""+(E.primKey.keyPath||"")||T.primKey.auto!==E.primKey.auto)$.recreate=!0,v.change.push($);else{var z=T.idxByName,V=E.idxByName,re=void 0;for(re in z)V[re]||$.del.push(re);for(re in V){var J=z[re],Y=V[re];J?J.src!==Y.src&&$.change.push(Y):$.add.push(Y)}(0<$.del.length||0<$.add.length||0<$.change.length)&&v.change.push($)}}else v.add.push([y,E])}return v}function hd(d,h,y,v){var T=d.db.createObjectStore(h,y.keyPath?{keyPath:y.keyPath,autoIncrement:y.auto}:{autoIncrement:y.auto});v.forEach(function(E){return fl(T,E)})}function Vh(d,h){i(d).forEach(function(y){h.db.objectStoreNames.contains(y)||(Le&&console.debug("Dexie: Creating missing table",y),hd(h,y,d[y].primKey,d[y].indexes))})}function fl(d,h){d.createIndex(h.name,h.keyPath,{unique:h.unique,multiEntry:h.multi})}function pl(d,h,y){var v={};return w(h.objectStoreNames,0).forEach(function(T){for(var E=y.objectStore(T),$=ld(Kh(re=E.keyPath),re||"",!0,!1,!!E.autoIncrement,re&&typeof re!="string",!0),z=[],V=0;V<E.indexNames.length;++V){var J=E.index(E.indexNames[V]),re=J.keyPath,J=ld(J.name,re,!!J.unique,!!J.multiEntry,!1,re&&typeof re!="string",!1);z.push(J)}v[T]=cd(T,$,z)}),v}function gl(d,h,y){for(var v=y.db.objectStoreNames,T=0;T<v.length;++T){var E=v[T],$=y.objectStore(E);d._hasGetAll="getAll"in $;for(var z=0;z<$.indexNames.length;++z){var V,re=$.indexNames[z],J=$.index(re).keyPath,J=typeof J=="string"?J:"["+w(J).join("+")+"]";h[E]&&(V=h[E].idxByName[J])&&(V.name=re,delete h[E].idxByName[J],h[E].idxByName[re]=V)}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&a.WorkerGlobalScope&&a instanceof a.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(d._hasGetAll=!1)}function Xh(d){return d.split(",").map(function(h,y){var T=h.split(":"),v=(v=T[1])==null?void 0:v.trim(),T=(h=T[0].trim()).replace(/([&*]|\+\+)/g,""),E=/^\[/.test(T)?T.match(/^\[(.*)\]$/)[1].split("+"):T;return ld(T,E||null,/\&/.test(h),/\*/.test(h),/\+\+/.test(h),l(E),y===0,v)})}xo.prototype._createTableSchema=cd,xo.prototype._parseIndexSyntax=Xh,xo.prototype._parseStoresSpec=function(d,h){var y=this;i(d).forEach(function(v){if(d[v]!==null){var T=y._parseIndexSyntax(d[v]),E=T.shift();if(!E)throw new Oe.Schema("Invalid schema for table "+v+": "+d[v]);if(E.unique=!0,E.multi)throw new Oe.Schema("Primary key cannot be multiEntry*");T.forEach(function($){if($.auto)throw new Oe.Schema("Only primary key can be marked as autoIncrement (++)");if(!$.keyPath)throw new Oe.Schema("Index must have a name and cannot be an empty string")}),E=y._createTableSchema(v,E,T),h[v]=E}})},xo.prototype.stores=function(y){var h=this.db,y=(this._cfg.storesSource=this._cfg.storesSource?c(this._cfg.storesSource,y):y,h._versions),v={},T={};return y.forEach(function(E){c(v,E._cfg.storesSource),T=E._cfg.dbschema={},E._parseStoresSpec(v,T)}),h._dbSchema=T,ud(h,[h._allTables,h,h.Transaction.prototype]),hl(h,[h._allTables,h,h.Transaction.prototype,this._cfg.tables],i(T),T),h._storeNames=i(T),this},xo.prototype.upgrade=function(d){return this._cfg.contentUpgrade=De(this._cfg.contentUpgrade||Xe,d),this};var Cw=xo;function xo(){}var la=(()=>{var d,h,y;return typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"?(d=new Set,h=new FinalizationRegistry(function(v){d.delete(v)}),{toArray:function(){return Array.from(d).map(function(v){return v.deref()}).filter(function(v){return v!==void 0})},add:function(v){var T=new WeakRef(v._novip);d.add(T),h.register(v._novip,T,T),d.size>v._options.maxConnections&&(T=d.values().next().value,d.delete(T),h.unregister(T))},remove:function(v){if(v)for(var T=d.values(),E=T.next();!E.done;){var $=E.value;if($.deref()===v._novip)return d.delete($),void h.unregister($);E=T.next()}}}):(y=[],{toArray:function(){return y},add:function(v){y.push(v._novip)},remove:function(v){v&&(v=y.indexOf(v._novip))!==-1&&y.splice(v,1)}})})();function fd(d,h){var y=d._dbNamesDB;return y||(y=d._dbNamesDB=new Gs(_s,{addons:[],indexedDB:d,IDBKeyRange:h})).version(1).stores({dbnames:"name"}),y.table("dbnames")}function pd(d){return d&&typeof d.databases=="function"}function gd(d){return yn(function(){return Ue.letThrough=!0,d()})}function yd(d){return!("from"in d)}var In=function(d,h){var y;if(!this)return y=new In,d&&"d"in d&&c(y,d),y;c(this,arguments.length?{d:1,from:d,to:1<arguments.length?h:d}:{d:0})};function ca(d,h,y){var v=Tt(h,y);if(!isNaN(v)){if(0<v)throw RangeError();if(yd(d))return c(d,{from:h,to:y,d:1});var v=d.l,T=d.r;if(Tt(y,d.from)<0)return v?ca(v,h,y):d.l={from:h,to:y,d:1,l:null,r:null},Jh(d);if(0<Tt(h,d.to))return T?ca(T,h,y):d.r={from:h,to:y,d:1,l:null,r:null},Jh(d);Tt(h,d.from)<0&&(d.from=h,d.l=null,d.d=T?T.d+1:1),0<Tt(y,d.to)&&(d.to=y,d.r=null,d.d=d.l?d.l.d+1:1),h=!d.r,v&&!d.l&&da(d,v),T&&h&&da(d,T)}}function da(d,h){yd(h)||function y(v,T){var E=T.from,$=T.l,z=T.r;ca(v,E,T.to),$&&y(v,$),z&&y(v,z)}(d,h)}function Gh(d,h){var y=yl(h),v=y.next();if(!v.done)for(var T=v.value,E=yl(d),$=E.next(T.from),z=$.value;!v.done&&!$.done;){if(Tt(z.from,T.to)<=0&&0<=Tt(z.to,T.from))return!0;Tt(T.from,z.from)<0?T=(v=y.next(z.from)).value:z=($=E.next(T.from)).value}return!1}function yl(d){var h=yd(d)?null:{s:0,n:d};return{next:function(y){for(var v=0<arguments.length;h;)switch(h.s){case 0:if(h.s=1,v)for(;h.n.l&&Tt(y,h.n.from)<0;)h={up:h,n:h.n.l,s:1};else for(;h.n.l;)h={up:h,n:h.n.l,s:1};case 1:if(h.s=2,!v||Tt(y,h.n.to)<=0)return{value:h.n,done:!1};case 2:if(h.n.r){h.s=3,h={up:h,n:h.n.r,s:0};continue}case 3:h=h.up}return{done:!0}}}}function Jh(d){var h,y,v,T=(((T=d.r)==null?void 0:T.d)||0)-(((T=d.l)==null?void 0:T.d)||0),T=1<T?"r":T<-1?"l":"";T&&(h=T=="r"?"l":"r",y=s({},d),v=d[T],d.from=v.from,d.to=v.to,d[T]=v[T],y[T]=v[h],(d[h]=y).d=Qh(y)),d.d=Qh(d)}function Qh(y){var h=y.r,y=y.l;return(h?y?Math.max(h.d,y.d):h.d:y?y.d:0)+1}function bl(d,h){return i(h).forEach(function(y){d[y]?da(d[y],h[y]):d[y]=function v(T){var E,$,z={};for(E in T)p(T,E)&&($=T[E],z[E]=!$||typeof $!="object"||R.has($.constructor)?$:v($));return z}(h[y])}),d}function bd(d,h){return d.all||h.all||Object.keys(d).some(function(y){return h[y]&&Gh(h[y],d[y])})}g(In.prototype,((ae={add:function(d){return da(this,d),this},addKey:function(d){return ca(this,d,d),this},addKeys:function(d){var h=this;return d.forEach(function(y){return ca(h,y,y)}),this},hasKey:function(d){var h=yl(this).next(d).value;return h&&Tt(h.from,d)<=0&&0<=Tt(h.to,d)}})[H]=function(){return yl(this)},ae));var $r={},xd={},vd=!1;function xl(d){bl(xd,d),vd||(vd=!0,setTimeout(function(){vd=!1,Sd(xd,!(xd={}))},0))}function Sd(d,h){h===void 0&&(h=!1);var y=new Set;if(d.all)for(var v=0,T=Object.values($r);v<T.length;v++)Zh(z=T[v],d,y,h);else for(var E in d){var $,z,E=/^idb\:\/\/(.*)\/(.*)\//.exec(E);E&&($=E[1],E=E[2],z=$r["idb://".concat($,"/").concat(E)])&&Zh(z,d,y,h)}y.forEach(function(V){return V()})}function Zh(d,h,y,v){for(var T=[],E=0,$=Object.entries(d.queries.query);E<$.length;E++){for(var z=$[E],V=z[0],re=[],J=0,Y=z[1];J<Y.length;J++){var X=Y[J];bd(h,X.obsSet)?X.subscribers.forEach(function(ee){return y.add(ee)}):v&&re.push(X)}v&&T.push([V,re])}if(v)for(var te=0,Q=T;te<Q.length;te++){var Z=Q[te],V=Z[0],re=Z[1];d.queries.query[V]=re}}function Mw(d){var h=d._state,y=d._deps.indexedDB;if(h.isBeingOpened||d.idbdb)return h.dbReadyPromise.then(function(){return h.dbOpenError?Pt(h.dbOpenError):d});h.isBeingOpened=!0,h.dbOpenError=null,h.openComplete=!1;var v=h.openCanceller,T=Math.round(10*d.verno),E=!1;function $(){if(h.openCanceller!==v)throw new Oe.DatabaseClosed("db.open() was cancelled")}function z(){return new Be(function(X,te){if($(),!y)throw new Oe.MissingAPI;var Q=d.name,Z=h.autoSchema||!T?y.open(Q):y.open(Q,T);if(!Z)throw new Oe.MissingAPI;Z.onerror=Ts(te),Z.onblocked=tt(d._fireOnBlocked),Z.onupgradeneeded=tt(function(ee){var ce;J=Z.transaction,h.autoSchema&&!d._options.allowEmptyDB?(Z.onerror=ra,J.abort(),Z.result.close(),(ce=y.deleteDatabase(Q)).onsuccess=ce.onerror=tt(function(){te(new Oe.NoSuchDatabase("Database ".concat(Q," doesnt exist")))})):(J.onerror=Ts(te),ce=ee.oldVersion>Math.pow(2,62)?0:ee.oldVersion,Y=ce<1,d.idbdb=Z.result,E&&jw(d,J),Tw(d,ce/10,J,te))},te),Z.onsuccess=tt(function(){J=null;var ee,ce,oe,ge,Te,Me,$e=d.idbdb=Z.result,Ee=w($e.objectStoreNames);if(0<Ee.length)try{var Ve=$e.transaction((Te=Ee).length===1?Te[0]:Te,"readonly");if(h.autoSchema)Me=$e,ge=Ve,(oe=d).verno=Me.version/10,ge=oe._dbSchema=pl(0,Me,ge),oe._storeNames=w(Me.objectStoreNames,0),hl(oe,[oe._allTables],i(ge),ge);else if(gl(d,d._dbSchema,Ve),ce=Ve,((ce=md(pl(0,(ee=d).idbdb,ce),ee._dbSchema)).add.length||ce.change.some(function(Ie){return Ie.add.length||Ie.change.length}))&&!E)return console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this."),$e.close(),T=$e.version+1,E=!0,X(z());ml(d,Ve)}catch{}la.add(d),$e.onversionchange=tt(function(Ie){h.vcFired=!0,d.on("versionchange").fire(Ie)}),$e.onclose=tt(function(){d.close({disableAutoOpen:!1})}),Y&&(Ee=d._deps,Te=Q,pd(Me=Ee.indexedDB)||Te===_s||fd(Me,Ee.IDBKeyRange).put({name:Te}).catch(Xe)),X()},te)}).catch(function(X){switch(X==null?void 0:X.name){case"UnknownError":if(0<h.PR1398_maxLoop)return h.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),z();break;case"VersionError":if(0<T)return T=0,z()}return Be.reject(X)})}var V,re=h.dbReadyResolve,J=null,Y=!1;return Be.race([v,(typeof navigator>"u"?Be.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(X){function te(){return indexedDB.databases().finally(X)}V=setInterval(te,100),te()}).finally(function(){return clearInterval(V)}):Promise.resolve()).then(z)]).then(function(){return $(),h.onReadyBeingFired=[],Be.resolve(gd(function(){return d.on.ready.fire(d.vip)})).then(function X(){var te;if(0<h.onReadyBeingFired.length)return te=h.onReadyBeingFired.reduce(De,Xe),h.onReadyBeingFired=[],Be.resolve(gd(function(){return te(d.vip)})).then(X)})}).finally(function(){h.openCanceller===v&&(h.onReadyBeingFired=null,h.isBeingOpened=!1)}).catch(function(X){h.dbOpenError=X;try{J&&J.abort()}catch{}return v===h.openCanceller&&d._close(),Pt(X)}).finally(function(){h.openComplete=!0,re()}).then(function(){var X;return Y&&(X={},d.tables.forEach(function(te){te.schema.indexes.forEach(function(Q){Q.name&&(X["idb://".concat(d.name,"/").concat(te.name,"/").concat(Q.name)]=new In(-1/0,[[[]]]))}),X["idb://".concat(d.name,"/").concat(te.name,"/")]=X["idb://".concat(d.name,"/").concat(te.name,"/:dels")]=new In(-1/0,[[[]]])}),fr(oa).fire(X),Sd(X,!0)),d})}function wd(d){function h(E){return d.next(E)}var y=T(h),v=T(function(E){return d.throw(E)});function T(E){return function(z){var z=E(z),V=z.value;return z.done?V:V&&typeof V.then=="function"?V.then(y,v):l(V)?Promise.all(V).then(y,v):y(V)}}return T(h)()}function vl(d,h,y){for(var v=l(d)?d.slice():[d],T=0;T<y;++T)v.push(h);return v}var Pw={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(d){return s(s({},d),{table:function(v){var y=d.table(v),v=y.schema,T={},E=[];function $(X,te,Q){var oe=ia(X),Z=T[oe]=T[oe]||[],ee=X==null?0:typeof X=="string"?1:X.length,ce=0<te,oe=s(s({},Q),{name:ce?"".concat(oe,"(virtual-from:").concat(Q.name,")"):Q.name,lowLevelIndex:Q,isVirtual:ce,keyTail:te,keyLength:ee,extractKey:dd(X),unique:!ce&&Q.unique});return Z.push(oe),oe.isPrimaryKey||E.push(oe),1<ee&&$(ee===2?X[0]:X.slice(0,ee-1),te+1,Q),Z.sort(function(ge,Te){return ge.keyTail-Te.keyTail}),oe}var z=$(v.primaryKey.keyPath,0,v.primaryKey);T[":id"]=[z];for(var V=0,re=v.indexes;V<re.length;V++){var J=re[V];$(J.keyPath,0,J)}function Y(X){var te,Q=X.query.index;return Q.isVirtual?s(s({},X),{query:{index:Q.lowLevelIndex,range:(te=X.query.range,Q=Q.keyTail,{type:te.type===1?2:te.type,lower:vl(te.lower,te.lowerOpen?d.MAX_KEY:d.MIN_KEY,Q),lowerOpen:!0,upper:vl(te.upper,te.upperOpen?d.MIN_KEY:d.MAX_KEY,Q),upperOpen:!0})}}):X}return s(s({},y),{schema:s(s({},v),{primaryKey:z,indexes:E,getIndexByKeyPath:function(X){return(X=T[ia(X)])&&X[0]}}),count:function(X){return y.count(Y(X))},query:function(X){return y.query(Y(X))},openCursor:function(X){var te=X.query.index,Q=te.keyTail,Z=te.keyLength;return te.isVirtual?y.openCursor(Y(X)).then(function(ce){return ce&&ee(ce)}):y.openCursor(X);function ee(ce){return Object.create(ce,{continue:{value:function(oe){oe!=null?ce.continue(vl(oe,X.reverse?d.MAX_KEY:d.MIN_KEY,Q)):X.unique?ce.continue(ce.key.slice(0,Z).concat(X.reverse?d.MIN_KEY:d.MAX_KEY,Q)):ce.continue()}},continuePrimaryKey:{value:function(oe,ge){ce.continuePrimaryKey(vl(oe,d.MAX_KEY,Q),ge)}},primaryKey:{get:function(){return ce.primaryKey}},key:{get:function(){var oe=ce.key;return Z===1?oe[0]:oe.slice(0,Z)}},value:{get:function(){return ce.value}}})}}})}})}};function _d(d,h,y,v){return y=y||{},v=v||"",i(d).forEach(function(T){var E,$,z;p(h,T)?(E=d[T],$=h[T],typeof E=="object"&&typeof $=="object"&&E&&$?(z=q(E))!==q($)?y[v+T]=h[T]:z==="Object"?_d(E,$,y,v+T+"."):E!==$&&(y[v+T]=h[T]):E!==$&&(y[v+T]=h[T])):y[v+T]=void 0}),i(h).forEach(function(T){p(d,T)||(y[v+T]=h[T])}),y}function kd(d,h){return h.type==="delete"?h.keys:h.keys||h.values.map(d.extractKey)}var Ew={stack:"dbcore",name:"HooksMiddleware",level:2,create:function(d){return s(s({},d),{table:function(h){var y=d.table(h),v=y.schema.primaryKey;return s(s({},y),{mutate:function(T){var E=Ue.trans,$=E.table(h).hook,z=$.deleting,V=$.creating,re=$.updating;switch(T.type){case"add":if(V.fire===Xe)break;return E._promise("readwrite",function(){return J(T)},!0);case"put":if(V.fire===Xe&&re.fire===Xe)break;return E._promise("readwrite",function(){return J(T)},!0);case"delete":if(z.fire===Xe)break;return E._promise("readwrite",function(){return J(T)},!0);case"deleteRange":if(z.fire===Xe)break;return E._promise("readwrite",function(){return function Y(X,te,Q){return y.query({trans:X,values:!1,query:{index:v,range:te},limit:Q}).then(function(Z){var ee=Z.result;return J({type:"delete",keys:ee,trans:X}).then(function(ce){return 0<ce.numFailures?Promise.reject(ce.failures[0]):ee.length<Q?{failures:[],numFailures:0,lastResult:void 0}:Y(X,s(s({},te),{lower:ee[ee.length-1],lowerOpen:!0}),Q)})})}(T.trans,T.range,1e4)},!0)}return y.mutate(T);function J(Y){var X,te,Q,Z=Ue.trans,ee=Y.keys||kd(v,Y);if(ee)return(Y=Y.type==="add"||Y.type==="put"?s(s({},Y),{keys:ee}):s({},Y)).type!=="delete"&&(Y.values=r([],Y.values)),Y.keys&&(Y.keys=r([],Y.keys)),X=y,Q=ee,((te=Y).type==="add"?Promise.resolve([]):X.getMany({trans:te.trans,keys:Q,cache:"immutable"})).then(function(ce){var oe=ee.map(function(ge,Te){var Me,$e,Ee,Ve=ce[Te],Ie={onerror:null,onsuccess:null};return Y.type==="delete"?z.fire.call(Ie,ge,Ve,Z):Y.type==="add"||Ve===void 0?(Me=V.fire.call(Ie,ge,Y.values[Te],Z),ge==null&&Me!=null&&(Y.keys[Te]=ge=Me,v.outbound||A(Y.values[Te],v.keyPath,ge))):(Me=_d(Ve,Y.values[Te]),($e=re.fire.call(Ie,Me,ge,Ve,Z))&&(Ee=Y.values[Te],Object.keys($e).forEach(function(Ge){p(Ee,Ge)?Ee[Ge]=$e[Ge]:A(Ee,Ge,$e[Ge])}))),Ie});return y.mutate(Y).then(function(ge){for(var Te=ge.failures,Me=ge.results,$e=ge.numFailures,ge=ge.lastResult,Ee=0;Ee<ee.length;++Ee){var Ve=(Me||ee)[Ee],Ie=oe[Ee];Ve==null?Ie.onerror&&Ie.onerror(Te[Ee]):Ie.onsuccess&&Ie.onsuccess(Y.type==="put"&&ce[Ee]?Y.values[Ee]:Ve)}return{failures:Te,results:Me,numFailures:$e,lastResult:ge}}).catch(function(ge){return oe.forEach(function(Te){return Te.onerror&&Te.onerror(ge)}),Promise.reject(ge)})});throw new Error("Keys missing")}}})}})}};function ef(d,h,y){try{if(!h||h.keys.length<d.length)return null;for(var v=[],T=0,E=0;T<h.keys.length&&E<d.length;++T)Tt(h.keys[T],d[E])===0&&(v.push(y?L(h.values[T]):h.values[T]),++E);return v.length===d.length?v:null}catch{return null}}var Rw={stack:"dbcore",level:-1,create:function(d){return{table:function(h){var y=d.table(h);return s(s({},y),{getMany:function(v){var T;return v.cache?(T=ef(v.keys,v.trans._cache,v.cache==="clone"))?Be.resolve(T):y.getMany(v).then(function(E){return v.trans._cache={keys:v.keys,values:v.cache==="clone"?L(E):E},E}):y.getMany(v)},mutate:function(v){return v.type!=="add"&&(v.trans._cache=null),y.mutate(v)}})}}}};function tf(d,h){return d.trans.mode==="readonly"&&!!d.subscr&&!d.trans.explicit&&d.trans.db._options.cache!=="disabled"&&!h.schema.primaryKey.outbound}function nf(d,h){switch(d){case"query":return h.values&&!h.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var Aw={stack:"dbcore",level:0,name:"Observability",create:function(d){var h=d.schema.name,y=new In(d.MIN_KEY,d.MAX_KEY);return s(s({},d),{transaction:function(v,T,E){if(Ue.subscr&&T!=="readonly")throw new Oe.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(Ue.querier));return d.transaction(v,T,E)},table:function(v){function T(ee){var Z,ee=ee.query;return[Z=ee.index,new In((Z=(ee=ee.range).lower)!=null?Z:d.MIN_KEY,(Z=ee.upper)!=null?Z:d.MAX_KEY)]}var E=d.table(v),$=E.schema,z=$.primaryKey,V=$.indexes,re=z.extractKey,J=z.outbound,Y=z.autoIncrement&&V.filter(function(Q){return Q.compound&&Q.keyPath.includes(z.keyPath)}),X=s(s({},E),{mutate:function(Q){function Z(je){return je="idb://".concat(h,"/").concat(v,"/").concat(je),Te[je]||(Te[je]=new In)}var ee,ce,oe,ge=Q.trans,Te=Q.mutatedParts||(Q.mutatedParts={}),Me=Z(""),$e=Z(":dels"),Ee=Q.type,Ie=Q.type==="deleteRange"?[Q.range]:Q.type==="delete"?[Q.keys]:Q.values.length<50?[kd(z,Q).filter(function(je){return je}),Q.values]:[],Ve=Ie[0],Ie=Ie[1],Ge=Q.trans._cache;return l(Ve)?(Me.addKeys(Ve),(Ee=Ee==="delete"||Ve.length===Ie.length?ef(Ve,Ge):null)||$e.addKeys(Ve),(Ee||Ie)&&(ee=Z,ce=Ee,oe=Ie,$.indexes.forEach(function(je){var ct=ee(je.name||"");function dt(_t){return _t!=null?je.extractKey(_t):null}function ft(_t){je.multiEntry&&l(_t)?_t.forEach(function(Zn){return ct.addKey(Zn)}):ct.addKey(_t)}(ce||oe).forEach(function(_t,On){var ht=ce&&dt(ce[On]),On=oe&&dt(oe[On]);Tt(ht,On)!==0&&(ht!=null&&ft(ht),On!=null)&&ft(On)})}))):Ve?(Ie={from:(Ge=Ve.lower)!=null?Ge:d.MIN_KEY,to:(Ee=Ve.upper)!=null?Ee:d.MAX_KEY},$e.add(Ie),Me.add(Ie)):(Me.add(y),$e.add(y),$.indexes.forEach(function(je){return Z(je.name).add(y)})),E.mutate(Q).then(function(je){return!Ve||Q.type!=="add"&&Q.type!=="put"||(Me.addKeys(je.results),Y&&Y.forEach(function(ct){for(var dt=Q.values.map(function(ht){return ct.extractKey(ht)}),ft=ct.keyPath.findIndex(function(ht){return ht===z.keyPath}),_t=0,Zn=je.results.length;_t<Zn;++_t)dt[_t][ft]=je.results[_t];Z(ct.name).addKeys(dt)})),ge.mutatedParts=bl(ge.mutatedParts||{},Te),je})}}),te={get:function(Q){return[z,new In(Q.key)]},getMany:function(Q){return[z,new In().addKeys(Q.keys)]},count:T,query:T,openCursor:T};return i(te).forEach(function(Q){X[Q]=function(Z){var ee=Ue.subscr,ce=!!ee,oe=tf(Ue,E)&&nf(Q,Z)?Z.obsSet={}:ee;if(ce){var ge,ee=function(Ie){return Ie="idb://".concat(h,"/").concat(v,"/").concat(Ie),oe[Ie]||(oe[Ie]=new In)},Te=ee(""),Me=ee(":dels"),ce=te[Q](Z),$e=ce[0],ce=ce[1];if((Q==="query"&&$e.isPrimaryKey&&!Z.values?Me:ee($e.name||"")).add(ce),!$e.isPrimaryKey){if(Q!=="count")return ge=Q==="query"&&J&&Z.values&&E.query(s(s({},Z),{values:!1})),E[Q].apply(this,arguments).then(function(Ie){if(Q==="query"){if(J&&Z.values)return ge.then(function(dt){return dt=dt.result,Te.addKeys(dt),Ie});var Ge=Z.values?Ie.result.map(re):Ie.result;(Z.values?Te:Me).addKeys(Ge)}else{var je,ct;if(Q==="openCursor")return ct=Z.values,(je=Ie)&&Object.create(je,{key:{get:function(){return Me.addKey(je.primaryKey),je.key}},primaryKey:{get:function(){var dt=je.primaryKey;return Me.addKey(dt),dt}},value:{get:function(){return ct&&Te.addKey(je.primaryKey),je.value}}})}return Ie});Me.add(y)}}return E[Q].apply(this,arguments)}}),X}})}};function sf(d,h,y){var v;return y.numFailures===0?h:h.type==="deleteRange"||(v=h.keys?h.keys.length:"values"in h&&h.values?h.values.length:1,y.numFailures===v)?null:(v=s({},h),l(v.keys)&&(v.keys=v.keys.filter(function(T,E){return!(E in y.failures)})),"values"in v&&l(v.values)&&(v.values=v.values.filter(function(T,E){return!(E in y.failures)})),v)}function Td(d,h){return y=d,((v=h).lower===void 0||(v.lowerOpen?0<Tt(y,v.lower):0<=Tt(y,v.lower)))&&(y=d,(v=h).upper===void 0||(v.upperOpen?Tt(y,v.upper)<0:Tt(y,v.upper)<=0));var y,v}function rf(d,h,y,v,T,E){var $,z,V,re,J,Y,X;return!y||y.length===0||($=h.query.index,z=$.multiEntry,V=h.query.range,re=v.schema.primaryKey.extractKey,J=$.extractKey,Y=($.lowLevelIndex||$).extractKey,(v=y.reduce(function(te,Q){var Z=te,ee=[];if(Q.type==="add"||Q.type==="put")for(var ce=new In,oe=Q.values.length-1;0<=oe;--oe){var ge,Te=Q.values[oe],Me=re(Te);!ce.hasKey(Me)&&(ge=J(Te),z&&l(ge)?ge.some(function(Ge){return Td(Ge,V)}):Td(ge,V))&&(ce.addKey(Me),ee.push(Te))}switch(Q.type){case"add":var $e=new In().addKeys(h.values?te.map(function(je){return re(je)}):te),Z=te.concat(h.values?ee.filter(function(je){return je=re(je),!$e.hasKey(je)&&($e.addKey(je),!0)}):ee.map(function(je){return re(je)}).filter(function(je){return!$e.hasKey(je)&&($e.addKey(je),!0)}));break;case"put":var Ee=new In().addKeys(Q.values.map(function(je){return re(je)}));Z=te.filter(function(je){return!Ee.hasKey(h.values?re(je):je)}).concat(h.values?ee:ee.map(function(je){return re(je)}));break;case"delete":var Ve=new In().addKeys(Q.keys);Z=te.filter(function(je){return!Ve.hasKey(h.values?re(je):je)});break;case"deleteRange":var Ie=Q.range;Z=te.filter(function(je){return!Td(re(je),Ie)})}return Z},d))===d)?d:(X=function(te,Q){return Tt(Y(te),Y(Q))||Tt(re(te),re(Q))},v.sort(h.direction==="prev"||h.direction==="prevunique"?function(te,Q){return X(Q,te)}:X),h.limit&&h.limit<1/0&&(v.length>h.limit?v.length=h.limit:d.length===h.limit&&v.length<h.limit&&(T.dirty=!0)),E?Object.freeze(v):v)}function of(d,h){return Tt(d.lower,h.lower)===0&&Tt(d.upper,h.upper)===0&&!!d.lowerOpen==!!h.lowerOpen&&!!d.upperOpen==!!h.upperOpen}function Iw(d,h){return((y,v,T,E)=>{if(y===void 0)return v!==void 0?-1:0;if(v===void 0)return 1;if((y=Tt(y,v))===0){if(T&&E)return 0;if(T)return 1;if(E)return-1}return y})(d.lower,h.lower,d.lowerOpen,h.lowerOpen)<=0&&0<=((y,v,T,E)=>{if(y===void 0)return v!==void 0?1:0;if(v===void 0)return-1;if((y=Tt(y,v))===0){if(T&&E)return 0;if(T)return-1;if(E)return 1}return y})(d.upper,h.upper,d.upperOpen,h.upperOpen)}function Ow(d,h,y,v){d.subscribers.add(y),v.addEventListener("abort",function(){var T,E;d.subscribers.delete(y),d.subscribers.size===0&&(T=d,E=h,setTimeout(function(){T.subscribers.size===0&&W(E,T)},3e3))})}var $w={stack:"dbcore",level:0,name:"Cache",create:function(d){var h=d.schema.name;return s(s({},d),{transaction:function(y,v,T){var E,$,z=d.transaction(y,v,T);return v==="readwrite"&&(T=(E=new AbortController).signal,z.addEventListener("abort",($=function(V){return function(){if(E.abort(),v==="readwrite"){for(var re=new Set,J=0,Y=y;J<Y.length;J++){var X=Y[J],te=$r["idb://".concat(h,"/").concat(X)];if(te){var Q=d.table(X),Z=te.optimisticOps.filter(function(je){return je.trans===z});if(z._explicit&&V&&z.mutatedParts)for(var ee=0,ce=Object.values(te.queries.query);ee<ce.length;ee++)for(var oe=0,ge=($e=ce[ee]).slice();oe<ge.length;oe++)bd((Ee=ge[oe]).obsSet,z.mutatedParts)&&(W($e,Ee),Ee.subscribers.forEach(function(je){return re.add(je)}));else if(0<Z.length){te.optimisticOps=te.optimisticOps.filter(function(je){return je.trans!==z});for(var Te=0,Me=Object.values(te.queries.query);Te<Me.length;Te++)for(var $e,Ee,Ve,Ie=0,Ge=($e=Me[Te]).slice();Ie<Ge.length;Ie++)(Ee=Ge[Ie]).res!=null&&z.mutatedParts&&(V&&!Ee.dirty?(Ve=Object.isFrozen(Ee.res),Ve=rf(Ee.res,Ee.req,Z,Q,Ee,Ve),Ee.dirty?(W($e,Ee),Ee.subscribers.forEach(function(je){return re.add(je)})):Ve!==Ee.res&&(Ee.res=Ve,Ee.promise=Be.resolve({result:Ve}))):(Ee.dirty&&W($e,Ee),Ee.subscribers.forEach(function(je){return re.add(je)})))}}}re.forEach(function(je){return je()})}}})(!1),{signal:T}),z.addEventListener("error",$(!1),{signal:T}),z.addEventListener("complete",$(!0),{signal:T})),z},table:function(y){var v=d.table(y),T=v.schema.primaryKey;return s(s({},v),{mutate:function(E){var $,z=Ue.trans;return!T.outbound&&z.db._options.cache!=="disabled"&&!z.explicit&&z.idbtrans.mode==="readwrite"&&($=$r["idb://".concat(h,"/").concat(y)])?(z=v.mutate(E),E.type!=="add"&&E.type!=="put"||!(50<=E.values.length||kd(T,E).some(function(V){return V==null}))?($.optimisticOps.push(E),E.mutatedParts&&xl(E.mutatedParts),z.then(function(V){0<V.numFailures&&(W($.optimisticOps,E),(V=sf(0,E,V))&&$.optimisticOps.push(V),E.mutatedParts)&&xl(E.mutatedParts)}),z.catch(function(){W($.optimisticOps,E),E.mutatedParts&&xl(E.mutatedParts)})):z.then(function(V){var re=sf(0,s(s({},E),{values:E.values.map(function(J,Y){var X;return V.failures[Y]?J:(A(X=(X=T.keyPath)!=null&&X.includes(".")?L(J):s({},J),T.keyPath,V.results[Y]),X)})}),V);$.optimisticOps.push(re),queueMicrotask(function(){return E.mutatedParts&&xl(E.mutatedParts)})}),z):v.mutate(E)},query:function(E){var $,z,V,re,J,Y,X;return tf(Ue,v)&&nf("query",E)?($=((V=Ue.trans)==null?void 0:V.db._options.cache)==="immutable",z=(V=Ue).requery,V=V.signal,Y=((te,Q,Z,ee)=>{var ce=$r["idb://".concat(te,"/").concat(Q)];if(!ce)return[];if(!(te=ce.queries[Z]))return[null,!1,ce,null];var oe=te[(ee.query?ee.query.index.name:null)||""];if(!oe)return[null,!1,ce,null];switch(Z){case"query":var ge=(Te=ee.direction)!=null?Te:"next",Te=oe.find(function(Me){var $e;return Me.req.limit===ee.limit&&Me.req.values===ee.values&&(($e=Me.req.direction)!=null?$e:"next")===ge&&of(Me.req.query.range,ee.query.range)});return Te?[Te,!0,ce,oe]:[oe.find(function(Me){var $e;return("limit"in Me.req?Me.req.limit:1/0)>=ee.limit&&(($e=Me.req.direction)!=null?$e:"next")===ge&&(!ee.values||Me.req.values)&&Iw(Me.req.query.range,ee.query.range)}),!1,ce,oe];case"count":return Te=oe.find(function(Me){return of(Me.req.query.range,ee.query.range)}),[Te,!!Te,ce,oe]}})(h,y,"query",E),X=Y[0],re=Y[2],J=Y[3],X&&Y[1]?X.obsSet=E.obsSet:(Y=v.query(E).then(function(te){var Q=te.result;if(X&&(X.res=Q),$){for(var Z=0,ee=Q.length;Z<ee;++Z)Object.freeze(Q[Z]);Object.freeze(Q)}else te.result=L(Q);return te}).catch(function(te){return J&&X&&W(J,X),Promise.reject(te)}),X={obsSet:E.obsSet,promise:Y,subscribers:new Set,type:"query",req:E,dirty:!1},J?J.push(X):(J=[X],(re=re||($r["idb://".concat(h,"/").concat(y)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[E.query.index.name||""]=J)),Ow(X,J,z,V),X.promise.then(function(te){return{result:rf(te.result,E,re==null?void 0:re.optimisticOps,v,X,$)}})):v.query(E)}})}})}};function Sl(d,h){return new Proxy(d,{get:function(y,v,T){return v==="db"?h:Reflect.get(y,v,T)}})}tn.prototype.version=function(d){if(isNaN(d)||d<.1)throw new Oe.Type("Given version is not a positive number");if(d=Math.round(10*d)/10,this.idbdb||this._state.isBeingOpened)throw new Oe.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,d);var h=this._versions,y=h.filter(function(v){return v._cfg.version===d})[0];return y||(y=new this.Version(d),h.push(y),h.sort(kw),y.stores({}),this._state.autoSchema=!1),y},tn.prototype._whenReady=function(d){var h=this;return this.idbdb&&(this._state.openComplete||Ue.letThrough||this._vip)?d():new Be(function(y,v){if(h._state.openComplete)return v(new Oe.DatabaseClosed(h._state.dbOpenError));if(!h._state.isBeingOpened){if(!h._state.autoOpen)return void v(new Oe.DatabaseClosed);h.open().catch(Xe)}h._state.dbReadyPromise.then(y,v)}).then(d)},tn.prototype.use=function(T){var h=T.stack,y=T.create,v=T.level,T=T.name,E=(T&&this.unuse({stack:h,name:T}),this._middlewares[h]||(this._middlewares[h]=[]));return E.push({stack:h,create:y,level:v??10,name:T}),E.sort(function($,z){return $.level-z.level}),this},tn.prototype.unuse=function(d){var h=d.stack,y=d.name,v=d.create;return h&&this._middlewares[h]&&(this._middlewares[h]=this._middlewares[h].filter(function(T){return v?T.create!==v:!!y&&T.name!==y})),this},tn.prototype.open=function(){var d=this;return Nt(Dt,function(){return Mw(d)})},tn.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var d=this._state;if(la.remove(this),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}d.isBeingOpened||(d.dbReadyPromise=new Be(function(h){d.dbReadyResolve=h}),d.openCanceller=new Be(function(h,y){d.cancelOpen=y}))},tn.prototype.close=function(h){var h=(h===void 0?{disableAutoOpen:!0}:h).disableAutoOpen,y=this._state;h?(y.isBeingOpened&&y.cancelOpen(new Oe.DatabaseClosed),this._close(),y.autoOpen=!1,y.dbOpenError=new Oe.DatabaseClosed):(this._close(),y.autoOpen=this._options.autoOpen||y.isBeingOpened,y.openComplete=!1,y.dbOpenError=null)},tn.prototype.delete=function(d){var h=this,y=(d===void 0&&(d={disableAutoOpen:!0}),0<arguments.length&&typeof arguments[0]!="object"),v=this._state;return new Be(function(T,E){function $(){h.close(d);var z=h._deps.indexedDB.deleteDatabase(h.name);z.onsuccess=tt(function(){var V,re,J;V=h._deps,re=h.name,pd(J=V.indexedDB)||re===_s||fd(J,V.IDBKeyRange).delete(re).catch(Xe),T()}),z.onerror=Ts(E),z.onblocked=h._fireOnBlocked}if(y)throw new Oe.InvalidArgument("Invalid closeOptions argument to db.delete()");v.isBeingOpened?v.dbReadyPromise.then($):$()})},tn.prototype.backendDB=function(){return this.idbdb},tn.prototype.isOpen=function(){return this.idbdb!==null},tn.prototype.hasBeenClosed=function(){var d=this._state.dbOpenError;return d&&d.name==="DatabaseClosed"},tn.prototype.hasFailed=function(){return this._state.dbOpenError!==null},tn.prototype.dynamicallyOpened=function(){return this._state.autoSchema},Object.defineProperty(tn.prototype,"tables",{get:function(){var d=this;return i(this._allTables).map(function(h){return d._allTables[h]})},enumerable:!1,configurable:!0}),tn.prototype.transaction=function(){var d=(function(h,y,v){var T=arguments.length;if(T<2)throw new Oe.InvalidArgument("Too few arguments");for(var E=new Array(T-1);--T;)E[T-1]=arguments[T];return v=E.pop(),[h,O(E),v]}).apply(this,arguments);return this._transaction.apply(this,d)},tn.prototype._transaction=function(d,h,y){var v,T,E=this,$=Ue.trans,z=($&&$.db===this&&d.indexOf("!")===-1||($=null),d.indexOf("?")!==-1);d=d.replace("!","").replace("?","");try{if(T=h.map(function(re){if(re=re instanceof E.Table?re.name:re,typeof re!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return re}),d=="r"||d===ks)v=ks;else{if(d!="rw"&&d!=go)throw new Oe.InvalidArgument("Invalid transaction mode: "+d);v=go}if($){if($.mode===ks&&v===go){if(!z)throw new Oe.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");$=null}$&&T.forEach(function(re){if($&&$.storeNames.indexOf(re)===-1){if(!z)throw new Oe.SubTransaction("Table "+re+" not included in parent transaction.");$=null}}),z&&$&&!$.active&&($=null)}}catch(re){return $?$._promise(null,function(J,Y){Y(re)}):Pt(re)}var V=(function re(J,Y,X,te,Q){return Be.resolve().then(function(){var oe=Ue.transless||Ue,Z=J._createTransaction(Y,X,J._dbSchema,te),oe=(Z.explicit=!0,{trans:Z,transless:oe});if(te)Z.idbtrans=te.idbtrans;else try{Z.create(),Z.idbtrans._explicit=!0,J._state.PR1398_maxLoop=3}catch(ge){return ge.name===pt.InvalidState&&J.isOpen()&&0<--J._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),J.close({disableAutoOpen:!1}),J.open().then(function(){return re(J,Y,X,null,Q)})):Pt(ge)}var ee,ce=xe(Q),oe=(ce&&An(),Be.follow(function(){var ge;(ee=Q.call(Z,Z))&&(ce?(ge=Ds.bind(null,null),ee.then(ge,ge)):typeof ee.next=="function"&&typeof ee.throw=="function"&&(ee=wd(ee)))},oe));return(ee&&typeof ee.then=="function"?Be.resolve(ee).then(function(ge){return Z.active?ge:Pt(new Oe.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):oe.then(function(){return ee})).then(function(ge){return te&&Z._resolve(),Z._completion.then(function(){return ge})}).catch(function(ge){return Z._reject(ge),Pt(ge)})})}).bind(null,this,v,T,$,y);return $?$._promise(v,V,"lock"):Ue.trans?Nt(Ue.transless,function(){return E._whenReady(V)}):this._whenReady(V)},tn.prototype.table=function(d){if(p(this._allTables,d))return this._allTables[d];throw new Oe.InvalidTable("Table ".concat(d," does not exist"))};var Gs=tn;function tn(d,h){var y,v,T,E,$,z=this,V=(this._middlewares={},this.verno=0,tn.dependencies),V=(this._options=h=s({addons:tn.addons,autoOpen:!0,indexedDB:V.indexedDB,IDBKeyRange:V.IDBKeyRange,cache:"cloned",maxConnections:1e3},h),this._deps={indexedDB:h.indexedDB,IDBKeyRange:h.IDBKeyRange},h.addons),re=(this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this,{dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:Xe,dbReadyPromise:null,cancelOpen:Xe,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:h.autoOpen}),J=(re.dbReadyPromise=new Be(function(Y){re.dbReadyResolve=Y}),re.openCanceller=new Be(function(Y,X){re.cancelOpen=X}),this._state=re,this.name=d,this.on=na(this,"populate","blocked","versionchange","close",{ready:[De,Xe]}),this.once=function(Y,X){var te=function(){for(var Q=[],Z=0;Z<arguments.length;Z++)Q[Z]=arguments[Z];z.on(Y).unsubscribe(te),X.apply(z,Q)};return z.on(Y,te)},this.on.ready.subscribe=M(this.on.ready.subscribe,function(Y){return function(X,te){tn.vip(function(){var Q,Z=z._state;Z.openComplete?(Z.dbOpenError||Be.resolve().then(X),te&&Y(X)):Z.onReadyBeingFired?(Z.onReadyBeingFired.push(X),te&&Y(X)):(Y(X),Q=z,te||Y(function ee(){Q.on.ready.unsubscribe(X),Q.on.ready.unsubscribe(ee)}))})}}),this.Collection=(y=this,sa(yw.prototype,function(ee,Z){this.db=y;var te=Oh,Q=null;if(Z)try{te=Z()}catch(oe){Q=oe}var Z=ee._ctx,ee=Z.table,ce=ee.hook.reading.fire;this._ctx={table:ee,index:Z.index,isPrimKey:!Z.index||ee.schema.primKey.keyPath&&Z.index===ee.schema.primKey.name,range:te,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:Q,or:Z.or,valueMapper:ce!==_e?ce:null}})),this.Table=(v=this,sa(zh.prototype,function(Y,X,te){this.db=v,this._tx=te,this.name=Y,this.schema=X,this.hook=v._allTables[Y]?v._allTables[Y].hook:na(null,{creating:[Lt,Xe],reading:[Ye,_e],updating:[le,Xe],deleting:[N,Xe]})})),this.Transaction=(T=this,sa(vw.prototype,function(Y,X,te,Q,Z){var ee=this;Y!=="readonly"&&X.forEach(function(ce){ce=(ce=te[ce])==null?void 0:ce.yProps,ce&&(X=X.concat(ce.map(function(oe){return oe.updatesTable})))}),this.db=T,this.mode=Y,this.storeNames=X,this.schema=te,this.chromeTransactionDurability=Q,this.idbtrans=null,this.on=na(this,"complete","error","abort"),this.parent=Z||null,this.active=!0,this._reculock=0,this._blockedFuncs=[],this._resolve=null,this._reject=null,this._waitingFor=null,this._waitingQueue=null,this._spinCount=0,this._completion=new Be(function(ce,oe){ee._resolve=ce,ee._reject=oe}),this._completion.then(function(){ee.active=!1,ee.on.complete.fire()},function(ce){var oe=ee.active;return ee.active=!1,ee.on.error.fire(ce),ee.parent?ee.parent._reject(ce):oe&&ee.idbtrans&&ee.idbtrans.abort(),Pt(ce)})})),this.Version=(E=this,sa(Cw.prototype,function(Y){this.db=E,this._cfg={version:Y,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=($=this,sa(Hh.prototype,function(Y,X,te){if(this.db=$,this._ctx={table:Y,index:X===":id"?null:X,or:te},this._cmp=this._ascending=Tt,this._descending=function(Q,Z){return Tt(Z,Q)},this._max=function(Q,Z){return 0<Tt(Q,Z)?Q:Z},this._min=function(Q,Z){return Tt(Q,Z)<0?Q:Z},this._IDBKeyRange=$._deps.IDBKeyRange,!this._IDBKeyRange)throw new Oe.MissingAPI})),this.on("versionchange",function(Y){0<Y.newVersion?console.warn("Another connection wants to upgrade database '".concat(z.name,"'. Closing db now to resume the upgrade.")):console.warn("Another connection wants to delete database '".concat(z.name,"'. Closing db now to resume the delete request.")),z.close({disableAutoOpen:!1})}),this.on("blocked",function(Y){!Y.newVersion||Y.newVersion<Y.oldVersion?console.warn("Dexie.delete('".concat(z.name,"') was blocked")):console.warn("Upgrade '".concat(z.name,"' blocked by other connection holding version ").concat(Y.oldVersion/10))}),this._maxKey=aa(h.IDBKeyRange),this._createTransaction=function(Y,X,te,Q){return new z.Transaction(Y,X,te,z._options.chromeTransactionDurability,Q)},this._fireOnBlocked=function(Y){z.on("blocked").fire(Y),la.toArray().filter(function(X){return X.name===z.name&&X!==z&&!X._state.vcFired}).map(function(X){return X.on("versionchange").fire(Y)})},this.use(Rw),this.use($w),this.use(Aw),this.use(Pw),this.use(Ew),new Proxy(this,{get:function(Y,X,te){var Q;return X==="_vip"||(X==="table"?function(Z){return Sl(z.table(Z),J)}:(Q=Reflect.get(Y,X,te))instanceof zh?Sl(Q,J):X==="tables"?Q.map(function(Z){return Sl(Z,J)}):X==="_createTransaction"?function(){return Sl(Q.apply(this,arguments),J)}:Q)}}));this.vip=J,V.forEach(function(Y){return Y(z)})}var wl,vo=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",Dw=(jd.prototype.subscribe=function(d,h,y){return this._subscribe(d&&typeof d!="function"?d:{next:d,error:h,complete:y})},jd.prototype[vo]=function(){return this},jd);function jd(d){this._subscribe=d}try{wl={indexedDB:a.indexedDB||a.mozIndexedDB||a.webkitIndexedDB||a.msIndexedDB,IDBKeyRange:a.IDBKeyRange||a.webkitIDBKeyRange}}catch{wl={indexedDB:null,IDBKeyRange:null}}function af(d){var h,y=!1,v=new Dw(function(T){var E=xe(d),$,z=!1,V={},re={},J={get closed(){return z},unsubscribe:function(){z||(z=!0,$&&$.abort(),Y&&fr.storagemutated.unsubscribe(Q))}},Y=(T.start&&T.start(J),!1),X=function(){return kt(Z)};function te(){return bd(re,V)}var Q=function(ee){bl(V,ee),te()&&X()},Z=function(){var ee,ce,oe;!z&&wl.indexedDB&&(V={},ee={},$&&$.abort(),$=new AbortController,oe=(ge=>{var Te=is();try{E&&An();var Me=yn(d,ge);return Me=E?Me.finally(Ds):Me}finally{Te&&ws()}})(ce={subscr:ee,signal:$.signal,requery:X,querier:d,trans:null}),Y||(fr(oa,Q),Y=!0),Promise.resolve(oe).then(function(ge){y=!0,h=ge,z||ce.signal.aborted||(te()||(re=ee,te())?X():(V={},kt(function(){return!z&&T.next&&T.next(ge)})))},function(ge){y=!1,["DatabaseClosedError","AbortError"].includes(ge==null?void 0:ge.name)||z||kt(function(){z||T.error&&T.error(ge)})}))};return setTimeout(X,0),J});return v.hasValue=function(){return y},v.getValue=function(){return h},v}var Dr=Gs;function Cd(d){var h=pr;try{pr=!0,fr.storagemutated.fire(d),Sd(d,!0)}finally{pr=h}}g(Dr,s(s({},se),{delete:function(d){return new Dr(d,{addons:[]}).delete()},exists:function(d){return new Dr(d,{addons:[]}).open().then(function(h){return h.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(d){try{return h=Dr.dependencies,y=h.indexedDB,h=h.IDBKeyRange,(pd(y)?Promise.resolve(y.databases()).then(function(v){return v.map(function(T){return T.name}).filter(function(T){return T!==_s})}):fd(y,h).toCollection().primaryKeys()).then(d)}catch{return Pt(new Oe.MissingAPI)}var h,y},defineClass:function(){return function(d){c(this,d)}},ignoreTransaction:function(d){return Ue.trans?Nt(Ue.transless||Dt,d):d()},vip:gd,async:function(d){return function(){try{var h=wd(d.apply(this,arguments));return h&&typeof h.then=="function"?h:Be.resolve(h)}catch(y){return Pt(y)}}},spawn:function(d,h,y){try{var v=wd(d.apply(y,h||[]));return v&&typeof v.then=="function"?v:Be.resolve(v)}catch(T){return Pt(T)}},currentTransaction:{get:function(){return Ue.trans||null}},waitFor:function(d,h){return d=Be.resolve(typeof d=="function"?Dr.ignoreTransaction(d):d).timeout(h||6e4),Ue.trans?Ue.trans.waitFor(d):d},Promise:Be,debug:{get:function(){return Le},set:function(d){ue(d)}},derive:x,extend:c,props:g,override:M,Events:na,on:fr,liveQuery:af,extendObservabilitySet:bl,getByKeyPath:D,setByKeyPath:A,delByKeyPath:function(d,h){typeof h=="string"?A(d,h,void 0):"length"in h&&[].map.call(h,function(y){A(d,y,void 0)})},shallowClone:B,deepClone:L,getObjectDiff:_d,cmp:Tt,asap:C,minKey:-1/0,addons:[],connections:{get:la.toArray},errnames:pt,dependencies:wl,cache:$r,semVer:"4.4.2",version:"4.4.2".split(".").map(function(d){return parseInt(d)}).reduce(function(d,h,y){return d+h/Math.pow(10,2*y)})})),Dr.maxKey=aa(Dr.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(fr(oa,function(d){pr||(d=new CustomEvent(id,{detail:d}),pr=!0,dispatchEvent(d),pr=!1)}),addEventListener(id,function(d){d=d.detail,pr||Cd(d)}));var So,pr=!1,lf=function(){};return typeof BroadcastChannel<"u"&&((lf=function(){(So=new BroadcastChannel(id)).onmessage=function(d){return d.data&&Cd(d.data)}})(),typeof So.unref=="function"&&So.unref(),fr(oa,function(d){pr||So.postMessage(d)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(d){if(!Gs.disableBfCache&&d.persisted){Le&&console.debug("Dexie: handling persisted pagehide"),So!=null&&So.close();for(var h=0,y=la.toArray();h<y.length;h++)y[h].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(d){!Gs.disableBfCache&&d.persisted&&(Le&&console.debug("Dexie: handling persisted pageshow"),lf(),Cd({all:new In(-1/0,[[]])}))})),Be.rejectionMapper=function(d,h){return!d||d instanceof Se||d instanceof TypeError||d instanceof SyntaxError||!d.name||!Wt[d.name]?d:(h=new Wt[d.name](h||d.message,d),"stack"in d&&S(h,"stack",{get:function(){return this.inner.stack}}),h)},ue(Le),s(Gs,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:Gs,Entity:$h,PropModification:ta,RangeSet:In,add:function(d){return new ta({add:d})},cmp:Tt,default:Gs,liveQuery:af,mergeRanges:da,rangesOverlap:Gh,remove:function(d){return new ta({remove:d})},replacePrefix:function(d,h){return new ta({replacePrefix:[d,h]})}}),{default:Gs}),Gs})}(Jl)),Jl.exports}var sk=nk();const Fu=po(sk),Pf=Symbol.for("Dexie"),Sc=globalThis[Pf]||(globalThis[Pf]=Fu);if(Fu.semVer!==Sc.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${Fu.semVer} and ${Sc.semVer}`);const{liveQuery:aF,mergeRanges:iF,rangesOverlap:lF,RangeSet:cF,cmp:dF,Entity:uF,PropModification:mF,replacePrefix:hF,add:fF,remove:pF,DexieYProvider:gF}=Sc;class rk extends Sc{constructor(){super("LotusStorage");jt(this,"scrollAnchors");jt(this,"toolSessionCollapses");jt(this,"diffCollapses");jt(this,"inputStates");jt(this,"modelOptionsCaches");this.version(1).stores({scrollAnchors:"sessionId, ts",toolSessionCollapses:"id, sessionId, updatedAt",diffCollapses:"sessionId, updatedAt",inputStates:"sessionId, updatedAt",modelOptionsCaches:"provider, timestamp"})}}const ok=new rk,Zr=class Zr{constructor(){jt(this,"db",ok)}static getInstance(){return Zr.instance||(Zr.instance=new Zr),Zr.instance}async saveScrollAnchor(t,n){try{await this.db.scrollAnchors.put({sessionId:t,anchorId:n.anchorId,offsetPx:n.offsetPx,ts:n.ts,indexHint:n.indexHint,createdAt:n.createdAt})}catch(s){console.warn("[StorageManager] IndexedDB save failed, falling back to localStorage",s);try{localStorage.setItem(`chat_scroll_anchor_v2:${t}`,JSON.stringify(n))}catch{}}}async loadScrollAnchor(t){try{const n=await this.db.scrollAnchors.get(t);return n?{v:1,anchorId:n.anchorId,offsetPx:n.offsetPx,ts:n.ts,indexHint:n.indexHint,createdAt:n.createdAt}:null}catch{try{const n=localStorage.getItem(`chat_scroll_anchor_v2:${t}`);if(!n)return null;const s=JSON.parse(n);if(s&&s.v===1&&typeof s.anchorId=="string")return s}catch{}return null}}async clearScrollAnchor(t){try{await this.db.scrollAnchors.delete(t)}catch{}try{localStorage.removeItem(`chat_scroll_anchor_v2:${t}`)}catch{}}async saveToolSessionCollapse(t,n,s){try{await this.db.toolSessionCollapses.put({id:`${t}:${n}`,sessionId:t,toolSessionId:n,isExpanded:s.isExpanded,expandedTools:s.expandedTools,updatedAt:Date.now()})}catch(r){console.warn("[StorageManager] saveToolSessionCollapse failed",r);try{localStorage.setItem(`chat-session-tool-collapse:${t}:${n}`,JSON.stringify(s))}catch{}}}async loadToolSessionCollapse(t,n){try{const s=await this.db.toolSessionCollapses.get(`${t}:${n}`);return s?{isExpanded:s.isExpanded,expandedTools:s.expandedTools}:null}catch{try{const s=localStorage.getItem(`chat-session-tool-collapse:${t}:${n}`);if(!s)return null;const r=JSON.parse(s);if(r&&typeof r.isExpanded=="boolean")return r}catch{}return null}}async saveDiffCollapse(t,n){try{await this.db.diffCollapses.put({sessionId:t,isExpanded:n.isExpanded,expandedFiles:n.expandedFiles,updatedAt:Date.now()})}catch(s){console.warn("[StorageManager] saveDiffCollapse failed",s);try{localStorage.setItem(`chat-session-diff-collapse:${t}`,JSON.stringify(n))}catch{}}}async loadDiffCollapse(t){try{const n=await this.db.diffCollapses.get(t);return n?{isExpanded:n.isExpanded,expandedFiles:n.expandedFiles}:null}catch{try{const n=localStorage.getItem(`chat-session-diff-collapse:${t}`);if(!n)return null;const s=JSON.parse(n);if(s&&typeof s.isExpanded=="boolean")return s}catch{}return null}}async saveInputReasoning(t,n){try{const s=await this.db.inputStates.get(t);await this.db.inputStates.put({sessionId:t,reasoningEffort:n,content:s==null?void 0:s.content,referenceText:s==null?void 0:s.referenceText,updatedAt:Date.now()})}catch(s){console.warn("[StorageManager] saveInputReasoning failed",s);try{const r=localStorage.getItem("chat_input_reasoning_by_session_v1"),a=r?JSON.parse(r):{};a[t]=n,localStorage.setItem("chat_input_reasoning_by_session_v1",JSON.stringify(a))}catch{}}}async loadInputReasoning(t){try{const n=await this.db.inputStates.get(t);return(n==null?void 0:n.reasoningEffort)??null}catch{try{const n=localStorage.getItem("chat_input_reasoning_by_session_v1");return n?JSON.parse(n)[t]??null:null}catch{return null}}}async saveLastUsedReasoningEffort(t){try{await this.db.inputStates.put({sessionId:"__last_used__",reasoningEffort:t,updatedAt:Date.now()})}catch{try{localStorage.setItem("chat_input_reasoning_last_used_v1",t)}catch{}}}async loadLastUsedReasoningEffort(){try{const t=await this.db.inputStates.get("__last_used__");return(t==null?void 0:t.reasoningEffort)??null}catch{try{return localStorage.getItem("chat_input_reasoning_last_used_v1")}catch{return null}}}async saveModelOptionsCache(t,n,s){try{await this.db.modelOptionsCaches.put({provider:t,options:n,timestamp:s})}catch(r){console.warn("[StorageManager] saveModelOptionsCache failed",r);try{localStorage.setItem(`chat-model-options-cache-v1:${t}`,JSON.stringify({timestamp:s,options:n}))}catch{}}}async loadModelOptionsCache(t){try{const n=await this.db.modelOptionsCaches.get(t);return n?{options:n.options,timestamp:n.timestamp}:null}catch{try{const n=localStorage.getItem(`chat-model-options-cache-v1:${t}`);if(!n)return null;const s=JSON.parse(n);if(s&&Array.isArray(s.options))return{options:s.options,timestamp:s.timestamp}}catch{}return null}}async clearSessionData(t){try{await Promise.all([this.db.scrollAnchors.delete(t),this.db.diffCollapses.delete(t),this.db.toolSessionCollapses.where("sessionId").equals(t).delete(),this.db.inputStates.delete(t)])}catch{}}async cleanupStaleData(t=30){const n=Date.now()-t*24*60*60*1e3;try{await Promise.all([this.db.scrollAnchors.where("ts").below(n).delete(),this.db.toolSessionCollapses.where("updatedAt").below(n).delete(),this.db.diffCollapses.where("updatedAt").below(n).delete(),this.db.inputStates.where("updatedAt").below(n).delete(),this.db.modelOptionsCaches.where("timestamp").below(n).delete()])}catch{}}async getStats(){try{const[t,n,s,r,a]=await Promise.all([this.db.scrollAnchors.count(),this.db.toolSessionCollapses.count(),this.db.diffCollapses.count(),this.db.inputStates.count(),this.db.modelOptionsCaches.count()]);return{scrollAnchors:t,toolSessionCollapses:n,diffCollapses:s,inputStates:r,modelOptionsCaches:a}}catch{return{scrollAnchors:0,toolSessionCollapses:0,diffCollapses:0,inputStates:0,modelOptionsCaches:0}}}};jt(Zr,"instance");let Wn=Zr;const Zb="chat_input_reasoning_by_session_v1",ex="chat_input_reasoning_last_used_v1",Ef={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},Ym=e=>e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",tx=()=>{if(typeof window>"u")return{};try{const e=localStorage.getItem(Zb);if(!e)return{};const t=JSON.parse(e),n={};for(const[s,r]of Object.entries(t||{}))Ym(r)&&(n[s]=r);return n}catch{return{}}},ak=e=>{if(!(typeof window>"u"))try{localStorage.setItem(Zb,JSON.stringify(e))}catch{}},ik=()=>{if(!(typeof window>"u"))try{const e=localStorage.getItem(ex);return Ym(e)?e:void 0}catch{return}},lk=e=>{if(!(typeof window>"u"))try{localStorage.setItem(ex,e)}catch{}},Vm=e=>{const t=tx();return Ym(t[e])?t[e]:ik()},fa=e=>({...Ef,reasoningEffort:Vm(e)??Ef.reasoningEffort}),ck=(e,t)=>({inputStates:{},setInputContent:(n,s)=>e(r=>({inputStates:{...r.inputStates,[n]:{...r.inputStates[n]||fa(n),content:s}}})),setReferenceText:(n,s)=>e(r=>({inputStates:{...r.inputStates,[n]:{...r.inputStates[n]||fa(n),referenceText:s}}})),setAttachments:(n,s)=>e(r=>({inputStates:{...r.inputStates,[n]:{...r.inputStates[n]||fa(n),attachments:s}}})),setInputReasoningEffort:(n,s)=>{e(i=>({inputStates:{...i.inputStates,[n]:{...i.inputStates[n]||fa(n),reasoningEffort:s}}}));const r=tx();r[n]=s,ak(r),lk(s);const a=Wn.getInstance();a.saveInputReasoning(n,s).catch(()=>{}),a.saveLastUsedReasoningEffort(s).catch(()=>{})},clearInputState:n=>e(s=>{const{[n]:r,...a}=s.inputStates;return{inputStates:a}}),getInputState:n=>t().inputStates[n]||fa(n)}),dk="bamboo_proxy_auth",uk=()=>{try{const e=localStorage.getItem(dk);if(!e)return null;const t=JSON.parse(e);if(!t||typeof t!="object")return null;const n=typeof t.username=="string"?t.username.trim():"",s=typeof t.password=="string"?t.password:"";return n?{username:n,password:s}:null}catch{return null}},nx={byId:{},runningCount:0},mk=[],qn=(e,t)=>t?e.executionBySession[t]??null:null,sx=e=>t=>qn(t,e),hk=e=>t=>{const n=qn(t,e);return(n==null?void 0:n.phase)??"idle"},ur=e=>t=>{const n=qn(t,e);return Um(n==null?void 0:n.phase)},fk=e=>t=>{const n=qn(t,e);return n?n.phase==="streaming"?!0:n.phase==="running_tools"&&n.stream.hasTokens:!1},pk=e=>t=>{const n=qn(t,e);return n?n.phase==="waiting_user_answer"||n.interaction.pendingQuestion!==null||n.backend.hasPendingQuestion===!0:!1},rx=e=>t=>{const n=qn(t,e);return y0(n==null?void 0:n.phase)},ox=e=>t=>{const n=qn(t,e);return b0(n==null?void 0:n.phase)},qr=e=>t=>{const n=qn(t,e);return Um(n==null?void 0:n.phase)},gk=e=>t=>{const n=qn(t,e);return(n==null?void 0:n.stream.activeToolCalls)??mk},Ci=e=>t=>{const n=qn(t,e);return(n==null?void 0:n.interaction.respondMode)??null},Fi=e=>t=>{const n=qn(t,e);return(n==null?void 0:n.children.byId)??nx.byId},yk=e=>t=>{const n=qn(t,e);return(n==null?void 0:n.children)??nx},wc=e=>t=>{const n=qn(t,e);return(n==null?void 0:n.generation)??0},bk=Object.freeze({state:"idle",activeToolCalls:[],runningChildCount:0,hasQuestion:!1,hasError:!1,errorMessage:null,tokenCount:0,hasTokens:!1,generation:0}),xk=e=>t=>{var s;const n=qn(t,e);return n?{state:n.phase,activeToolCalls:n.stream.activeToolCalls,runningChildCount:n.children.runningCount,hasQuestion:n.interaction.pendingQuestion!==null,hasError:n.error!==null,errorMessage:((s=n.error)==null?void 0:s.message)??null,tokenCount:n.stream.tokenCount,hasTokens:n.stream.hasTokens,generation:n.generation}:bk},vk=e=>t=>e.map(n=>({sessionId:n??"",entry:qn(t,n)})),Sk="auto",wk="required",_k=1e4,kk=15e3,Tk=os.getInstance();let Rf=null,pa=null,Af=null,ga=null;const If=new WeakMap,G=Pr()(V_(G_((e,t,n)=>({...N0(e,t),...q0(e,t),...Y0(e,t),...X0(),...J0(e,t),...Q0(e),...ek(e,t),...ck(e,t),...M0(e),agentAvailability:null,setAgentAvailability:s=>{e({agentAvailability:s})},checkAgentAvailability:async()=>{if(pa)return pa;pa=(async()=>{const s=await Tk.healthCheck();return t().agentAvailability!==s&&e({agentAvailability:s}),s})();try{return await pa}finally{pa=null}},startAgentHealthCheck:()=>{Rf||(t().checkAgentAvailability(),Rf=setInterval(()=>{t().checkAgentAvailability()},_k))},refreshSessionsIndex:async()=>{if(ga)return ga;ga=(async()=>{try{await t().refreshChats()}catch(s){console.warn("[AppStore] refreshChats failed:",s)}})();try{return await ga}finally{ga=null}},startSessionsIndexSync:()=>{Af||(t().refreshSessionsIndex(),Af=setInterval(()=>{t().refreshSessionsIndex()},kk))}})),{name:"AppStore"})),ax=e=>{const t=If.get(e);if(t)return t;const n=new Map(e.map(s=>[s.id,s]));return If.set(e,n),n},Er=e=>t=>e?ax(t.chats).get(e)??null:null,Xm=e=>e.currentSessionId?ax(e.chats).get(e.currentSessionId)??null:null,jk=e=>{var t;return((t=Xm(e))==null?void 0:t.messages)??[]},Of=async()=>{const e=uk();if(!e)return!1;try{return await Vt.setProxyAuth(e),!0}catch(t){return console.error("Failed to apply stored proxy auth during startup:",t),!1}},Ck=async()=>{try{const e=await Ps.getState().loadConfig();if((typeof(e==null?void 0:e.proxy_auth_mode)=="string"?e.proxy_auth_mode:Sk)!==wk)return await Of(),!1;const n=await Ps.getState().loadProxyAuthStatus({force:!0});return n!=null&&n.configured||await Of()?!1:(G.setState(r=>({...r,models:[],selectedModel:void 0,modelsError:"Proxy auth mode is set to required. Please configure proxy username/password and apply it.",isLoadingModels:!1})),!0)}catch(e){return console.error("Failed to evaluate startup proxy auth mode:",e),!1}};let $f=!1;const ix=async(e=!1)=>{if($f&&!e)return;$f=!0,G.getState().startAgentHealthCheck(),G.getState().startSessionsIndexSync(),await Ct.getState().loadProviderConfig(),await G.getState().loadChats(),await Ck()||await G.getState().fetchModels(),await G.getState().loadSystemPrompts()},Mk=Object.freeze(Object.defineProperty({__proto__:null,initializeStore:ix,selectActiveToolCalls:gk,selectCanCancel:ox,selectChildren:Fi,selectChildrenSnapshot:yk,selectCurrentChat:Xm,selectCurrentMessages:jk,selectExecutionByPane:vk,selectExecutionPhase:hk,selectExecutionState:sx,selectGeneration:wc,selectIsAwaitingUser:pk,selectIsBusy:ur,selectIsInputLocked:rx,selectIsStreaming:fk,selectRailModel:xk,selectRespondMode:Ci,selectSessionById:Er,selectShouldObserve:qr,useAppStore:G},Symbol.toStringTag,{value:"Module"})),mo={'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:Df,Paragraph:Pk}=Ke,Ek=({content:e,token:t,showGradient:n,onClick:s})=>o.jsx(Ce,{size:"small",style:{marginLeft:t.marginLG,marginTop:t.marginXS,backgroundColor:t.colorBgLayout,borderColor:t.colorBorderSecondary},styles:{body:{padding:t.paddingMD}},onClick:s,children:o.jsxs("div",{style:{maxHeight:"60vh",overflowY:"auto",position:"relative",paddingRight:t.paddingXS},children:[o.jsx(Es,{remarkPlugins:[Fc],components:{p:({children:r})=>o.jsx(Pk,{style:{marginBottom:t.marginSM},children:r}),ol:({children:r})=>o.jsx("ol",{style:{marginBottom:t.marginSM,paddingLeft:t.paddingLG},children:r}),ul:({children:r})=>o.jsx("ul",{style:{marginBottom:t.marginSM,paddingLeft:t.paddingLG},children:r}),li:({children:r})=>o.jsx("li",{style:{marginBottom:t.marginXS},children:r}),h1:({children:r})=>o.jsx(Df,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block"},children:r}),h2:({children:r})=>o.jsx(Df,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block"},children:r}),code:({inline:r,className:a,children:i,...l})=>{const c=/language-(\w+)/.exec(a||"");return r?o.jsx("code",{className:a,style:{backgroundColor:t.colorFillTertiary,padding:"0 4px",borderRadius:t.borderRadiusSM,fontSize:t.fontSizeSM},...l,children:i}):o.jsx(Bo,{style:mo,language:(c==null?void 0:c[1])||"text",PreTag:"div",wrapLongLines:!0,children:String(i).replace(/\n$/,"")})}},children:e||"No content available."}),n?o.jsx("div",{style:{position:"sticky",bottom:0,height:48,background:`linear-gradient(180deg, transparent, ${t.colorBgLayout})`,pointerEvents:"none",marginTop:-48}}):null]})}),{Text:$d,Paragraph:Rk}=Ke,Ak=({prompt:e,token:t,isSelected:n,isExpanded:s,onSelect:r,onToggleExpand:a,onCopy:i})=>{const{t:l}=Ae(),c=e.content||"",{nonEmptyLineCount:u,wordCount:m,characterCount:p,showGradient:g}=f.useMemo(()=>{const S=(c?c.split(/\r?\n/):[]).filter(j=>j.trim().length>0).length,x=c.trim()?c.trim().split(/\s+/).filter(Boolean).length:0,k=c.length;return{nonEmptyLineCount:S,wordCount:x,characterCount:k,showGradient:!s&&k>600}},[c,s]);return o.jsx(Qt.Item,{style:{cursor:"pointer",padding:t.paddingMD,borderRadius:t.borderRadius,border:n?`2px solid ${t.colorPrimary}`:`1px solid ${t.colorBorderSecondary}`,marginBottom:t.marginXS,backgroundColor:n?t.colorPrimaryBg:t.colorBgContainer,transition:"all 0.2s ease"},onClick:()=>r(e.id),children:o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:t.marginSM,children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",width:"100%",gap:t.marginSM},children:[o.jsxs(he,{align:"start",children:[o.jsx(xs,{checked:n,onChange:()=>r(e.id),onClick:b=>b.stopPropagation()}),o.jsxs("div",{children:[o.jsx($d,{strong:!0,children:e.name||e.id}),o.jsx("div",{children:o.jsx($d,{code:!0,style:{fontSize:t.fontSizeSM,color:t.colorTextSecondary},children:e.id})})]}),e.isDefault?o.jsx(Ne,{color:"warning",children:l("chat.systemPromptSelector.defaultTag")}):null]}),o.jsxs(he,{size:"small",children:[o.jsx(de,{type:"text",size:"small",icon:s?o.jsx(Hw,{}):o.jsx(Nc,{}),onClick:b=>{b.stopPropagation(),a(e.id)},children:l(s?"chat.systemPromptSelector.hide":"chat.systemPromptSelector.preview")}),o.jsx(de,{type:"text",size:"small",icon:o.jsx(vs,{}),onClick:b=>i(b,e),children:l("chat.systemPromptSelector.copy")})]})]}),e.description?o.jsx($d,{type:"secondary",style:{marginLeft:t.marginLG,fontSize:t.fontSizeSM},children:e.description}):null,o.jsxs(he,{size:"small",wrap:!0,style:{marginLeft:t.marginLG},children:[o.jsx(Ne,{color:"processing",children:l("chat.systemPromptSelector.lines",{count:u})}),o.jsx(Ne,{color:"purple",children:l("chat.systemPromptSelector.words",{count:m})}),o.jsx(Ne,{color:"success",children:l("chat.systemPromptSelector.chars",{count:p})})]}),s?o.jsx(Ek,{content:c,token:t,showGradient:g,onClick:b=>b.stopPropagation()}):o.jsx(Rk,{type:"secondary",ellipsis:{rows:3},style:{marginLeft:t.marginLG,marginBottom:0,color:t.colorTextSecondary},children:c||l("chat.systemPromptSelector.noContent")})]})},e.id)},{Text:Ik}=Ke,{useToken:Ok}=Qe,$k=({open:e,onClose:t,onSelect:n,prompts:s,title:r,showCancelButton:a=!0})=>{const{t:i}=Ae(),{token:l}=Ok(),[c,u]=Cr.useMessage(),m=G(C=>C.lastSelectedPromptId),p=G(C=>C.setLastSelectedPromptId),[g,b]=f.useState(null),[S,x]=f.useState(null),k=f.useMemo(()=>s.filter(C=>C.id&&C.id.trim()!==""),[s]),j=async(C,D)=>{C.stopPropagation();const A=D.content??"";try{await Ss(A),c.success(i("success.promptCopied",{name:D.name}))}catch(B){console.error("[SystemPromptSelector] Failed to copy prompt:",B),c.error(i("error.copyPromptFailed"))}},w=r??i("chat.prompt.selectorTitle");f.useEffect(()=>{if(e){const C=k.find(A=>A.isDefault),D=m||(C==null?void 0:C.id)||(k.length>0?k[0].id:null);b(D)}},[e,m,k.length]);const M=C=>{b(C.id),p(C.id),n(C),t()},_=()=>{t()};return o.jsxs(o.Fragment,{children:[u,o.jsxs(Xn,{title:o.jsxs(he,{children:[o.jsx(Ui,{}),w]}),open:e,onCancel:_,width:700,footer:o.jsx(F_,{buttons:[...a?[N_(_)]:[],z_(()=>{const C=k.find(D=>D.id===g);C&&M(C)},{text:i("chat.prompt.createButton"),disabled:!g})]}),styles:{body:{maxHeight:"70vh",overflowY:"auto",padding:l.paddingMD}},children:[o.jsx("div",{style:{marginBottom:l.marginMD},children:o.jsx(Ik,{type:"secondary",style:{fontSize:l.fontSizeSM},children:i("chat.prompt.helperText")})}),k.length===0?o.jsx(Mn,{description:i("chat.prompt.emptyDescription"),style:{margin:l.marginLG}}):o.jsx("div",{children:k.map(C=>o.jsx(Ak,{prompt:C,token:l,isSelected:g===C.id,isExpanded:S===C.id,onSelect:D=>b(D),onToggleExpand:D=>x(S===D?null:D),onCopy:j},C.id))})]})]})},Dk=({chat:e,isSelected:t,onSelect:n,onDelete:s,onPin:r,onUnpin:a,onEdit:i,onGenerateTitle:l,onRunProjectDream:c,isGeneratingTitle:u,isRunningProjectDream:m,titleGenerationError:p})=>{const{t:g}=Ae(),[b,S]=f.useState(!1),[x,k]=f.useState(e.title),[j,w]=f.useState(!1),[M,_]=f.useState(!1),{token:C}=Qe.useToken(),D=f.useCallback(L=>{L.stopPropagation(),i&&x.trim()&&i(e.id,x.trim()),S(!1)},[e.id,x,i]),A=f.useCallback(L=>{L.stopPropagation(),k(e.title),S(!1)},[e.title]),B=[{key:"pin",icon:e.pinned?o.jsx(Eu,{style:{color:C.colorWarning}}):o.jsx(Em,{}),label:e.pinned?g("chat.actions.unpin"):g("chat.actions.pin"),onClick:({domEvent:L})=>{L.stopPropagation(),e.pinned?a(e.id):r(e.id)}},{key:"edit",icon:o.jsx(Hi,{}),label:g("chat.chatItem.edit"),onClick:({domEvent:L})=>{L.stopPropagation(),S(!0)}},...l?[{key:"generate-title",icon:u?o.jsx(io,{}):o.jsx(wb,{style:p?{color:C.colorError}:void 0}),label:p||g("chat.actions.generateTitle"),disabled:u,onClick:({domEvent:L})=>{L.stopPropagation(),l(e.id)}}]:[],...c?[{key:"run-project-dream",icon:m?o.jsx(io,{}):o.jsx(Kw,{}),label:g("chat.actions.runProjectDream"),disabled:m,onClick:({domEvent:L})=>{L.stopPropagation(),c(e.id)}}]:[],{type:"divider"},{key:"delete",icon:o.jsx(Mr,{}),label:g("common.delete"),danger:!0,onClick:({domEvent:L})=>{L.stopPropagation(),s(e.id)}}],F={padding:"8px 12px",borderRadius:C.borderRadiusSM,marginBottom:C.marginXXS,cursor:"pointer",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)",backgroundColor:t?"var(--lotus-primary-soft)":j||M?"var(--lotus-item-hover-bg)":"transparent",border:"1px solid transparent",borderColor:t?"var(--lotus-tool-card-border)":j||M?C.colorBorderSecondary:"transparent",position:"relative",overflow:"visible",boxShadow:t?"var(--lotus-tool-card-shadow)":"none",transform:j&&!t?"translateX(2px)":"none"},O={flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontSize:13,fontWeight:t?600:500,color:t?"var(--lotus-primary)":C.colorText},R={flex:1,fontSize:C.fontSizeSM,marginRight:C.marginSM},I=b?[o.jsx(de,{type:"text",size:"small",icon:o.jsx(Yw,{style:{color:C.colorSuccess}}),onClick:D,"aria-label":g("common.save")},"save"),o.jsx(de,{type:"text",size:"small",icon:o.jsx(Ho,{style:{color:C.colorError}}),onClick:A,"aria-label":g("common.cancel")},"cancel")]:j||M?[o.jsx(lo,{menu:{items:B,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:M,onOpenChange:L=>_(L),children:o.jsx(de,{type:"text",size:"small",icon:o.jsx(Vw,{}),"aria-label":g("common.moreActions","More actions"),onClick:L=>L.stopPropagation(),style:{color:C.colorTextSecondary,borderRadius:C.borderRadiusSM,background:C.colorFillTertiary,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return o.jsx(Qt.Item,{style:F,tabIndex:0,onClick:()=>!b&&n(e.id),onKeyDown:L=>{L.key==="Enter"&&!b?(L.preventDefault(),n(e.id)):(L.key==="Delete"||L.key==="Backspace")&&!b&&L.metaKey&&(L.preventDefault(),s(e.id))},onMouseEnter:()=>w(!0),onMouseLeave:()=>{M||w(!1)},onFocus:()=>w(!0),onBlur:()=>{M||w(!1)},actions:I,"data-testid":"chat-item",role:"option","aria-selected":t,"aria-label":e.title||g("chat.sidebar.untitledChat"),children:o.jsx(Qt.Item.Meta,{title:b?o.jsx(et,{value:x,onChange:L=>k(L.target.value),onClick:L=>L.stopPropagation(),onPressEnter:L=>{L.preventDefault(),D(L)},autoFocus:!0,style:R,variant:"borderless",size:"small"}):o.jsxs("div",{style:{...O,display:"flex",alignItems:"center",gap:C.marginXS,minWidth:0},children:[e.pinned&&o.jsx(Eu,{style:{color:C.colorWarning,fontSize:11,flexShrink:0}}),o.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.title}),e.kind==="child"?o.jsx(Ne,{color:"processing",style:{marginInlineEnd:0,flex:"0 0 auto"},children:g("chat.chatItem.childTag")}):null]})})})},Lk=(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,Nu=f.memo(Dk,Lk);Nu.displayName="ChatItem";const Lf=e=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[e]??4,Fk=e=>{const t={},n=e.filter(r=>r.pinned);n.length>0&&(t.Pinned=n.sort((r,a)=>a.createdAt-r.createdAt));const s=e.filter(r=>!r.pinned&&!!r.createdByScheduleId);return s.length>0&&(t.Scheduled=s.sort((r,a)=>a.createdAt-r.createdAt)),e.filter(r=>!r.pinned&&!r.createdByScheduleId).forEach(r=>{const i=new Date(r.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});t[i]||(t[i]=[]),t[i].push(r)}),Object.keys(t).forEach(r=>{t[r].sort((a,i)=>i.createdAt-a.createdAt)}),t},Nk=e=>{const t=n=>Array.isArray(n)?n.reduce((s,r)=>Math.max(s,r.createdAt),0):Object.values(n).reduce((s,r)=>{const a=r.reduce((i,l)=>Math.max(i,l.createdAt),0);return Math.max(s,a)},0);return Object.keys(e).sort((n,s)=>{if(n==="Pinned")return-1;if(s==="Pinned")return 1;if(n==="Scheduled")return-1;if(s==="Scheduled")return 1;const r=e[n],a=e[s];if(!r||!a)return 0;const i=t(r),l=t(a);return i!==l?l-i:Lf(n)-Lf(s)})},zk=(e,t)=>e[t]?e[t].map(n=>n.id):[],lx=(e,t)=>e[t]?e[t].length:0,Ff=e=>e.pinned?"Pinned":e.createdByScheduleId?"Scheduled":new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),Nf=(e,t)=>{const s={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 s?t(s):e},Bk=({groupedChatsByDate:e,childrenByRoot:t,expandedRootIds:n,onToggleRootExpanded:s,sortedDateKeys:r,expandedKeys:a,onCollapseChange:i,currentSessionId:l,onSelectChat:c,onDeleteChat:u,onDeleteByDate:m,onPinChat:p,onUnpinChat:g,onEditTitle:b,onGenerateTitle:S,onRunProjectDream:x,titleGenerationState:k,projectDreamState:j,token:w,hasActiveFilters:M})=>{const{t:_}=Ae(),C=f.useMemo(()=>r.length?r.map(A=>{const B=e[A],F=lx(e,A);return{dateKey:A,dateGroup:B,totalChatsInDate:F}}):[],[e,r]);if(!r.length)return o.jsx(Mn,{image:Mn.PRESENTED_IMAGE_SIMPLE,description:o.jsxs(he,{direction:"vertical",size:4,align:"center",children:[o.jsx("span",{style:{color:w.colorTextSecondary},children:M?_("chat.sidebar.empty.noMatches","No matching sessions"):_("chat.sidebar.empty.noSessions")}),o.jsx("span",{style:{color:w.colorTextSecondary,fontSize:12},children:M?_("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):_("chat.sidebar.empty.hint")}),M&&o.jsx(de,{size:"small",type:"link",onClick:()=>{var B;const A=document.querySelector('[data-testid="sidebar-search-input"] input, .lotus-sidebar-search input');if(A){const F=(B=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value"))==null?void 0:B.set;F==null||F.call(A,""),A.dispatchEvent(new Event("input",{bubbles:!0}))}},children:_("chat.sidebar.empty.clearFilters","Clear filters")})]})});const D=new Set(a);return o.jsx(he,{direction:"vertical",size:"small",style:{width:"100%"},children:C.map(({dateKey:A,dateGroup:B,totalChatsInDate:F})=>{const O=D.has(A);return o.jsxs("div",{style:{borderRadius:w.borderRadiusSM,background:O?w.colorFillTertiary:"transparent",padding:4},children:[o.jsxs(ve,{align:"center",justify:"space-between",style:{cursor:"pointer",padding:"8px 12px",borderRadius:w.borderRadiusSM,transition:"all 0.2s ease",border:"1px solid transparent"},role:"button",tabIndex:0,"aria-expanded":O,"aria-label":`${Nf(A,_)} (${F})`,onKeyDown:R=>{if(R.key==="Enter"||R.key===" "){R.preventDefault();const I=new Set(D);I.has(A)?I.delete(A):I.add(A),i(Array.from(I))}},onMouseEnter:R=>{R.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.92))",R.currentTarget.style.borderColor="var(--lotus-sidebar-item-hover-border, rgba(13, 148, 136, 0.28))";const I=R.currentTarget.querySelector(".chat-sidebar-date-group-delete");I&&(I.style.opacity="1")},onMouseLeave:R=>{R.currentTarget.style.background="transparent",R.currentTarget.style.borderColor="transparent";const I=R.currentTarget.querySelector(".chat-sidebar-date-group-delete");I&&(I.style.opacity="0")},onClick:()=>{const R=new Set(D);R.has(A)?R.delete(A):R.add(A),i(Array.from(R))},className:"chat-sidebar-date-group-header",children:[o.jsxs(ve,{align:"center",gap:"small",style:{minWidth:0},children:[O?o.jsx(Gn,{style:{fontSize:12,opacity:.6}}):o.jsx(Vs,{style:{fontSize:12,opacity:.6}}),o.jsxs("span",{style:{fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:A==="Today"?"var(--lotus-primary)":w.colorTextSecondary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[Nf(A,_)," (",F,")"]})]}),o.jsx(de,{type:"text",size:"small",icon:o.jsx(Mr,{}),className:"chat-sidebar-date-group-delete",style:{color:w.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:R=>{R.stopPropagation(),m(A)}})]}),O?o.jsx("div",{style:{marginTop:4},children:o.jsx(Qt,{itemLayout:"horizontal",dataSource:B,split:!1,renderItem:R=>{var I,L,U,q,H,P;return o.jsxs("div",{children:[o.jsxs(ve,{align:"center",gap:6,children:[(I=t[R.id])!=null&&I.length?o.jsx(de,{size:"small",type:"text",style:{padding:0,width:22},"aria-label":n.has(R.id)?_("chat.sidebar.actions.collapseChildren"):_("chat.sidebar.actions.expandChildren"),onClick:W=>{W.preventDefault(),W.stopPropagation(),s(R.id)},children:n.has(R.id)?o.jsx(Gn,{}):o.jsx(Vs,{})}):o.jsx("div",{style:{width:22}}),o.jsx("div",{style:{flex:1,minWidth:0},children:o.jsx(Nu,{chat:R,isSelected:R.id===l,onSelect:c,onDelete:u,onPin:p,onUnpin:g,onEdit:b,onGenerateTitle:S,onRunProjectDream:x,isGeneratingTitle:((L=k[R.id])==null?void 0:L.status)==="loading",isRunningProjectDream:((U=j[R.id])==null?void 0:U.status)==="loading",titleGenerationError:((q=k[R.id])==null?void 0:q.status)==="error"?(H=k[R.id])==null?void 0:H.error:void 0})})]}),n.has(R.id)&&(((P=t[R.id])==null?void 0:P.length)??0)>0?o.jsx("div",{style:{marginLeft:22,marginTop:2},children:o.jsx(Qt,{itemLayout:"horizontal",dataSource:t[R.id],split:!1,renderItem:W=>{var ne,K,xe,se;return o.jsx("div",{style:{paddingLeft:12},children:o.jsx(Nu,{chat:W,isSelected:W.id===l,onSelect:c,onDelete:u,onPin:p,onUnpin:g,onEdit:b,onGenerateTitle:S,onRunProjectDream:x,isGeneratingTitle:((ne=k[W.id])==null?void 0:ne.status)==="loading",isRunningProjectDream:((K=j[W.id])==null?void 0:K.status)==="loading",titleGenerationError:((xe=k[W.id])==null?void 0:xe.status)==="error"?(se=k[W.id])==null?void 0:se.error:void 0})},W.id)}})}):null]},R.id)}})}):null]},A)})})},Wk="copilot_ui_theme_v1";function qk(){var e;try{const t=localStorage.getItem(Wk);if(t==="light"||t==="dark")return t}catch{}return(e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const ho=Pr(e=>({themeMode:qk(),setThemeMode:t=>e({themeMode:t}),toggleTheme:()=>e(t=>({themeMode:t.themeMode==="dark"?"light":"dark"}))})),Uk="2026.5.4",Hk={version:Uk},Gm=Hk.version,{Text:Kk}=Ke,Yk=({collapsed:e,onNewChat:t,onOpenSettings:n,screens:s,token:r})=>{const{t:a}=Ae(),i=ho(p=>p.themeMode),l=ho(p=>p.toggleTheme),c=a("chat.sidebar.newSession"),u=a("settings.page.title"),m=i==="dark"?a("settings.app.lightMode","Light mode"):a("settings.app.darkMode","Dark mode");return o.jsxs(ve,{vertical:!0,gap:e?"small":"middle",style:{padding:e?10:16,background:"transparent",borderTop:`1px solid ${r.colorBorderSecondary}`},children:[o.jsx(de,{"data-testid":"new-chat","data-tour-id":"new-session",type:"primary",icon:o.jsx(or,{}),onClick:t,block:!e,shape:"default",size:e?"large":s.xs?"small":"middle",title:c,"aria-label":c,className:"lotus-primary-cta",style:{...e?{width:"44px",height:"44px",margin:"0 auto"}:{},borderRadius:r.borderRadiusLG,minHeight:e?44:46,fontWeight:600},children:!e&&c}),o.jsxs(ve,{gap:8,align:"center",children:[o.jsx(de,{"data-testid":"open-settings","data-tour-id":"open-settings",icon:o.jsx(Ki,{}),onClick:n,block:!e,shape:"default",size:e?"large":s.xs?"small":"middle",title:u,"aria-label":u,className:"lotus-secondary-button",style:{...e?{width:"44px",height:"44px",margin:"0 auto"}:{},borderRadius:r.borderRadiusLG,minHeight:44,flex:e?void 0:1},children:!e&&u}),!e&&o.jsx(bt,{title:m,placement:"top",children:o.jsx(de,{"data-testid":"toggle-theme",type:"text",icon:i==="dark"?o.jsx(Xw,{}):o.jsx(Gw,{}),onClick:l,"aria-label":m,className:"lotus-toolbar-icon",style:{width:44,height:44,borderRadius:r.borderRadiusLG,flexShrink:0}})})]}),!e&&o.jsxs(Kk,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:r.fontSizeSM,textAlign:"center",userSelect:"text"},children:[a("settings.appTab.runningVersion","Running version"),": v",Gm]})]})},zf="provider",rr=Pr(e=>({isOpen:!1,origin:"chat",activeTabKey:zf,open:(t,n=zf)=>e({isOpen:!0,origin:t,activeTabKey:n}),close:()=>e({isOpen:!1}),setActiveTabKey:t=>e({activeTabKey:t})}));function it(e,t,n,s,r){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}function ie(e,t,n,s){if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?s:n==="a"?s.call(e):s?s.value:t.get(e)}let cx=function(){const{crypto:e}=globalThis;if(e!=null&&e.randomUUID)return cx=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^n()&15>>+s/4).toString(16))};function zu(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const Bu=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 lt extends Error{}class Pn extends lt{constructor(t,n,s,r){super(`${Pn.makeMessage(t,n,s)}`),this.status=t,this.headers=r,this.requestID=r==null?void 0:r.get("x-request-id"),this.error=n;const a=n;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,n,s){const r=n!=null&&n.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):s;return t&&r?`${t} ${r}`:t?`${t} status code (no body)`:r||"(no status code or body)"}static generate(t,n,s,r){if(!t||!r)return new Uc({message:s,cause:Bu(n)});const a=n==null?void 0:n.error;return t===400?new dx(t,a,s,r):t===401?new ux(t,a,s,r):t===403?new mx(t,a,s,r):t===404?new hx(t,a,s,r):t===409?new fx(t,a,s,r):t===422?new px(t,a,s,r):t===429?new gx(t,a,s,r):t>=500?new yx(t,a,s,r):new Pn(t,a,s,r)}}class gs extends Pn{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class Uc extends Pn{constructor({message:t,cause:n}){super(void 0,void 0,t||"Connection error.",void 0),n&&(this.cause=n)}}class Jm extends Uc{constructor({message:t}={}){super({message:t??"Request timed out."})}}class dx extends Pn{}class ux extends Pn{}class mx extends Pn{}class hx extends Pn{}class fx extends Pn{}class px extends Pn{}class gx extends Pn{}class yx extends Pn{}class bx extends lt{constructor(){super("Could not parse response content as the length limit was reached")}}class xx extends lt{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class fi extends Error{constructor(t){super(t)}}const Vk=/^[a-z][a-z0-9+.-]*:/i,Xk=e=>Vk.test(e);let Vn=e=>(Vn=Array.isArray,Vn(e)),Bf=Vn;function Gk(e){return typeof e!="object"?{}:e??{}}function Jk(e){if(!e)return!0;for(const t in e)return!1;return!0}function Qk(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Dd(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}const Zk=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new lt(`${e} must be an integer`);if(t<0)throw new lt(`${e} must be a positive integer`);return t},eT=e=>{try{return JSON.parse(e)}catch{return}},Qi=e=>new Promise(t=>setTimeout(t,e)),Ao="5.10.2",tT=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function nT(){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 sT=()=>{var n;const e=nT();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ao,"X-Stainless-OS":qf(Deno.build.os),"X-Stainless-Arch":Wf(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((n=Deno.version)==null?void 0:n.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ao,"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":Ao,"X-Stainless-OS":qf(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Wf(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=rT();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ao,"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":Ao,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function rT(){if(typeof navigator>"u"||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:n}of e){const s=n.exec(navigator.userAgent);if(s){const r=s[1]||0,a=s[2]||0,i=s[3]||0;return{browser:t,version:`${r}.${a}.${i}`}}}return null}const Wf=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",qf=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 Uf;const oT=()=>Uf??(Uf=sT());function aT(){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 vx(...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 Sx(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return vx({start(){},async pull(n){const{done:s,value:r}=await t.next();s?n.close():n.enqueue(r)},async cancel(){var n;await((n=t.return)==null?void 0:n.call(t))}})}function wx(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const n=await t.read();return n!=null&&n.done&&t.releaseLock(),n}catch(n){throw t.releaseLock(),n}},async return(){const n=t.cancel();return t.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function iT(e){var s,r;if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await((r=(s=e[Symbol.asyncIterator]()).return)==null?void 0:r.call(s));return}const t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const lT=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),_x="RFC3986",kx=e=>String(e),Hf={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:kx},cT="RFC1738";let Wu=(e,t)=>(Wu=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Wu(e,t));const Fs=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),Ld=1024,dT=(e,t,n,s,r)=>{if(e.length===0)return e;let a=e;if(typeof e=="symbol"?a=Symbol.prototype.toString.call(e):typeof e!="string"&&(a=String(e)),n==="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+=Ld){const c=a.length>=Ld?a.slice(l,l+Ld):a,u=[];for(let m=0;m<c.length;++m){let p=c.charCodeAt(m);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||r===cT&&(p===40||p===41)){u[u.length]=c.charAt(m);continue}if(p<128){u[u.length]=Fs[p];continue}if(p<2048){u[u.length]=Fs[192|p>>6]+Fs[128|p&63];continue}if(p<55296||p>=57344){u[u.length]=Fs[224|p>>12]+Fs[128|p>>6&63]+Fs[128|p&63];continue}m+=1,p=65536+((p&1023)<<10|c.charCodeAt(m)&1023),u[u.length]=Fs[240|p>>18]+Fs[128|p>>12&63]+Fs[128|p>>6&63]+Fs[128|p&63]}i+=u.join("")}return i};function uT(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Kf(e,t){if(Vn(e)){const n=[];for(let s=0;s<e.length;s+=1)n.push(t(e[s]));return n}return t(e)}const Tx={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},jx=function(e,t){Array.prototype.push.apply(e,Vn(t)?t:[t])};let Yf;const fn={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:dT,encodeValuesOnly:!1,format:_x,formatter:kx,indices:!1,serializeDate(e){return(Yf??(Yf=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function mT(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}const Fd={};function Cx(e,t,n,s,r,a,i,l,c,u,m,p,g,b,S,x,k,j){let w=e,M=j,_=0,C=!1;for(;(M=M.get(Fd))!==void 0&&!C;){const O=M.get(e);if(_+=1,typeof O<"u"){if(O===_)throw new RangeError("Cyclic object value");C=!0}typeof M.get(Fd)>"u"&&(_=0)}if(typeof u=="function"?w=u(t,w):w instanceof Date?w=g==null?void 0:g(w):n==="comma"&&Vn(w)&&(w=Kf(w,function(O){return O instanceof Date?g==null?void 0:g(O):O})),w===null){if(a)return c&&!x?c(t,fn.encoder,k,"key",b):t;w=""}if(mT(w)||uT(w)){if(c){const O=x?t:c(t,fn.encoder,k,"key",b);return[(S==null?void 0:S(O))+"="+(S==null?void 0:S(c(w,fn.encoder,k,"value",b)))]}return[(S==null?void 0:S(t))+"="+(S==null?void 0:S(String(w)))]}const D=[];if(typeof w>"u")return D;let A;if(n==="comma"&&Vn(w))x&&c&&(w=Kf(w,c)),A=[{value:w.length>0?w.join(",")||null:void 0}];else if(Vn(u))A=u;else{const O=Object.keys(w);A=m?O.sort(m):O}const B=l?String(t).replace(/\./g,"%2E"):String(t),F=s&&Vn(w)&&w.length===1?B+"[]":B;if(r&&Vn(w)&&w.length===0)return F+"[]";for(let O=0;O<A.length;++O){const R=A[O],I=typeof R=="object"&&typeof R.value<"u"?R.value:w[R];if(i&&I===null)continue;const L=p&&l?R.replace(/\./g,"%2E"):R,U=Vn(w)?typeof n=="function"?n(F,L):F:F+(p?"."+L:"["+L+"]");j.set(e,_);const q=new WeakMap;q.set(Fd,j),jx(D,Cx(I,U,n,s,r,a,i,l,n==="comma"&&x&&Vn(w)?null:c,u,m,p,g,b,S,x,k,q))}return D}function hT(e=fn){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||fn.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=_x;if(typeof e.format<"u"){if(!Wu(Hf,e.format))throw new TypeError("Unknown format option provided.");n=e.format}const s=Hf[n];let r=fn.filter;(typeof e.filter=="function"||Vn(e.filter))&&(r=e.filter);let a;if(e.arrayFormat&&e.arrayFormat in Tx?a=e.arrayFormat:"indices"in e?a=e.indices?"indices":"repeat":a=fn.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:fn.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:fn.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:fn.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:fn.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?fn.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:fn.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:fn.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:fn.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:fn.encodeValuesOnly,filter:r,format:n,formatter:s,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:fn.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:fn.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:fn.strictNullHandling}}function fT(e,t={}){let n=e;const s=hT(t);let r,a;typeof s.filter=="function"?(a=s.filter,n=a("",n)):Vn(s.filter)&&(a=s.filter,r=a);const i=[];if(typeof n!="object"||n===null)return"";const l=Tx[s.arrayFormat],c=l==="comma"&&s.commaRoundTrip;r||(r=Object.keys(n)),s.sort&&r.sort(s.sort);const u=new WeakMap;for(let g=0;g<r.length;++g){const b=r[g];s.skipNulls&&n[b]===null||jx(i,Cx(n[b],b,l,c,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,u))}const m=i.join(s.delimiter);let p=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),m.length>0?p+m:""}function pT(e){let t=0;for(const r of e)t+=r.length;const n=new Uint8Array(t);let s=0;for(const r of e)n.set(r,s),s+=r.length;return n}let Vf;function Qm(e){let t;return(Vf??(t=new globalThis.TextEncoder,Vf=t.encode.bind(t)))(e)}let Xf;function Gf(e){let t;return(Xf??(t=new globalThis.TextDecoder,Xf=t.decode.bind(t)))(e)}var es,ts;class Hc{constructor(){es.set(this,void 0),ts.set(this,void 0),it(this,es,new Uint8Array),it(this,ts,null)}decode(t){if(t==null)return[];const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Qm(t):t;it(this,es,pT([ie(this,es,"f"),n]));const s=[];let r;for(;(r=gT(ie(this,es,"f"),ie(this,ts,"f")))!=null;){if(r.carriage&&ie(this,ts,"f")==null){it(this,ts,r.index);continue}if(ie(this,ts,"f")!=null&&(r.index!==ie(this,ts,"f")+1||r.carriage)){s.push(Gf(ie(this,es,"f").subarray(0,ie(this,ts,"f")-1))),it(this,es,ie(this,es,"f").subarray(ie(this,ts,"f"))),it(this,ts,null);continue}const a=ie(this,ts,"f")!==null?r.preceding-1:r.preceding,i=Gf(ie(this,es,"f").subarray(0,a));s.push(i),it(this,es,ie(this,es,"f").subarray(r.index)),it(this,ts,null)}return s}flush(){return ie(this,es,"f").length?this.decode(`
15
+ `):[]}}es=new WeakMap,ts=new WeakMap;Hc.NEWLINE_CHARS=new Set([`
16
+ `,"\r"]);Hc.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function gT(e,t){for(let r=t??0;r<e.length;r++){if(e[r]===10)return{preceding:r,index:r+1,carriage:!1};if(e[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function yT(e){for(let s=0;s<e.length-1;s++){if(e[s]===10&&e[s+1]===10||e[s]===13&&e[s+1]===13)return s+2;if(e[s]===13&&e[s+1]===10&&s+3<e.length&&e[s+2]===13&&e[s+3]===10)return s+4}return-1}const _c={off:0,error:200,warn:300,info:400,debug:500},Jf=(e,t,n)=>{if(e){if(Qk(_c,e))return e;jn(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(_c))}`)}};function pi(){}function Cl(e,t,n){return!t||_c[e]>_c[n]?pi:t[e].bind(t)}const bT={error:pi,warn:pi,info:pi,debug:pi};let Qf=new WeakMap;function jn(e){const t=e.logger,n=e.logLevel??"off";if(!t)return bT;const s=Qf.get(t);if(s&&s[0]===n)return s[1];const r={error:Cl("error",t,n),warn:Cl("warn",t,n),info:Cl("info",t,n),debug:Cl("debug",t,n)};return Qf.set(t,[n,r]),r}const Ur=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,n])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var ya;class Ys{constructor(t,n,s){this.iterator=t,ya.set(this,void 0),this.controller=n,it(this,ya,s)}static fromSSEResponse(t,n,s){let r=!1;const a=s?jn(s):console;async function*i(){if(r)throw new lt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let l=!1;try{for await(const c of xT(t,n))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(m){throw a.error("Could not parse message into JSON:",c.data),a.error("From chunk:",c.raw),m}if(u&&u.error)throw new Pn(void 0,u.error,void 0,t.headers);yield u}else{let u;try{u=JSON.parse(c.data)}catch(m){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),m}if(c.event=="error")throw new Pn(void 0,u.error,u.message,void 0);yield{event:c.event,data:u}}}l=!0}catch(c){if(zu(c))return;throw c}finally{l||n.abort()}}return new Ys(i,n,s)}static fromReadableStream(t,n,s){let r=!1;async function*a(){const l=new Hc,c=wx(t);for await(const u of c)for(const m of l.decode(u))yield m;for(const u of l.flush())yield u}async function*i(){if(r)throw new lt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let l=!1;try{for await(const c of a())l||c&&(yield JSON.parse(c));l=!0}catch(c){if(zu(c))return;throw c}finally{l||n.abort()}}return new Ys(i,n,s)}[(ya=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const t=[],n=[],s=this.iterator(),r=a=>({next:()=>{if(a.length===0){const i=s.next();t.push(i),n.push(i)}return a.shift()}});return[new Ys(()=>r(t),this.controller,ie(this,ya,"f")),new Ys(()=>r(n),this.controller,ie(this,ya,"f"))]}toReadableStream(){const t=this;let n;return vx({async start(){n=t[Symbol.asyncIterator]()},async pull(s){try{const{value:r,done:a}=await n.next();if(a)return s.close();const i=Qm(JSON.stringify(r)+`
17
+ `);s.enqueue(i)}catch(r){s.error(r)}},async cancel(){var s;await((s=n.return)==null?void 0:s.call(n))}})}}async function*xT(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new lt("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 lt("Attempted to iterate over a response with no body");const n=new ST,s=new Hc,r=wx(e.body);for await(const a of vT(r))for(const i of s.decode(a)){const l=n.decode(i);l&&(yield l)}for(const a of s.flush()){const i=n.decode(a);i&&(yield i)}}async function*vT(e){let t=new Uint8Array;for await(const n of e){if(n==null)continue;const s=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?Qm(n):n;let r=new Uint8Array(t.length+s.length);r.set(t),r.set(s,t.length),t=r;let a;for(;(a=yT(t))!==-1;)yield t.slice(0,a),t=t.slice(a)}t.length>0&&(yield t)}class ST{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(`
18
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(t),t.startsWith(":"))return null;let[n,s,r]=wT(t,":");return r.startsWith(" ")&&(r=r.substring(1)),n==="event"?this.event=r:n==="data"&&this.data.push(r),null}}function wT(e,t){const n=e.indexOf(t);return n!==-1?[e.substring(0,n),t,e.substring(n+t.length)]:[e,"",""]}async function Mx(e,t){const{response:n,requestLogID:s,retryOfRequestLogID:r,startTime:a}=t,i=await(async()=>{var p;if(t.options.stream)return jn(e).debug("response",n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e):Ys.fromSSEResponse(n,t.controller,e);if(n.status===204)return null;if(t.options.__binaryResponse)return n;const l=n.headers.get("content-type"),c=(p=l==null?void 0:l.split(";")[0])==null?void 0:p.trim();if((c==null?void 0:c.includes("application/json"))||(c==null?void 0:c.endsWith("+json"))){const g=await n.json();return Px(g,n)}return await n.text()})();return jn(e).debug(`[${s}] response parsed`,Ur({retryOfRequestLogID:r,url:n.url,status:n.status,body:i,durationMs:Date.now()-a})),i}function Px(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 gi;class Kc extends Promise{constructor(t,n,s=Mx){super(r=>{r(null)}),this.responsePromise=n,this.parseResponse=s,gi.set(this,void 0),it(this,gi,t)}_thenUnwrap(t){return new Kc(ie(this,gi,"f"),this.responsePromise,async(n,s)=>Px(t(await this.parseResponse(n,s),s),s.response))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){const[t,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:n,request_id:n.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(ie(this,gi,"f"),t))),this.parsedPromise}then(t,n){return this.parse().then(t,n)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}}gi=new WeakMap;var Ml;class Ex{constructor(t,n,s,r){Ml.set(this,void 0),it(this,Ml,t),this.options=r,this.response=n,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const t=this.nextPageRequestOptions();if(!t)throw new lt("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await ie(this,Ml,"f").requestAPIList(this.constructor,t)}async*iterPages(){let t=this;for(yield t;t.hasNextPage();)t=await t.getNextPage(),yield t}async*[(Ml=new WeakMap,Symbol.asyncIterator)](){for await(const t of this.iterPages())for(const n of t.getPaginatedItems())yield n}}class _T extends Kc{constructor(t,n,s){super(t,n,async(r,a)=>new s(r,a.response,await Mx(r,a),a.options))}async*[Symbol.asyncIterator](){const t=await this;for await(const n of t)yield n}}class Yc extends Ex{constructor(t,n,s,r){super(t,n,s,r),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class cn extends Ex{constructor(t,n,s,r){super(t,n,s,r),this.data=s.data||[],this.has_more=s.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var s;const t=this.getPaginatedItems(),n=(s=t[t.length-1])==null?void 0:s.id;return n?{...this.options,query:{...Gk(this.options.query),after:n}}:null}}const Rx=()=>{var e;if(typeof File>"u"){const{process:t}=globalThis,n=typeof((e=t==null?void 0:t.versions)==null?void 0:e.node)=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Mi(e,t,n){return Rx(),new File(e,t??"unknown_file",n)}function Ql(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 Ax=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",fo=async(e,t)=>({...e,body:await TT(e.body,t)}),Zf=new WeakMap;function kT(e){const t=typeof e=="function"?e:e.fetch,n=Zf.get(t);if(n)return n;const s=(async()=>{try{const r="Response"in t?t.Response:(await t("data:,")).constructor,a=new FormData;return a.toString()!==await new r(a).text()}catch{return!0}})();return Zf.set(t,s),s}const TT=async(e,t)=>{if(!await kT(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const n=new FormData;return await Promise.all(Object.entries(e||{}).map(([s,r])=>qu(n,s,r))),n},jT=e=>e instanceof Blob&&"name"in e,qu=async(e,t,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")e.append(t,String(n));else if(n instanceof Response)e.append(t,Mi([await n.blob()],Ql(n)));else if(Ax(n))e.append(t,Mi([await new Response(Sx(n)).blob()],Ql(n)));else if(jT(n))e.append(t,n,Ql(n));else if(Array.isArray(n))await Promise.all(n.map(s=>qu(e,t+"[]",s)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([s,r])=>qu(e,`${t}[${s}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},Ix=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",CT=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&Ix(e),MT=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function PT(e,t,n){if(Rx(),e=await e,CT(e))return e instanceof File?e:Mi([await e.arrayBuffer()],e.name);if(MT(e)){const r=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Mi(await Uu(r),t,n)}const s=await Uu(e);if(t||(t=Ql(e)),!(n!=null&&n.type)){const r=s.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof r=="string"&&(n={...n,type:r})}return Mi(s,t,n)}async function Uu(e){var n;let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Ix(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Ax(e))for await(const s of e)t.push(...await Uu(s));else{const s=(n=e==null?void 0:e.constructor)==null?void 0:n.name;throw new Error(`Unexpected data type: ${typeof e}${s?`; constructor: ${s}`:""}${ET(e)}`)}return t}function ET(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(n=>`"${n}"`).join(", ")}]`}class ut{constructor(t){this._client=t}}function Ox(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const ep=Object.freeze(Object.create(null)),RT=(e=Ox)=>function(n,...s){if(n.length===1)return n[0];let r=!1;const a=[],i=n.reduce((m,p,g)=>{var x;/[?#]/.test(p)&&(r=!0);const b=s[g];let S=(r?encodeURIComponent:e)(""+b);return g!==s.length&&(b==null||typeof b=="object"&&b.toString===((x=Object.getPrototypeOf(Object.getPrototypeOf(b.hasOwnProperty??ep)??ep))==null?void 0:x.toString))&&(S=b+"",a.push({start:m.length+p.length,length:S.length,error:`Value of type ${Object.prototype.toString.call(b).slice(8,-1)} is not a valid path parameter`})),m+p+(g===s.length?"":S)},""),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((m,p)=>m.start-p.start),a.length>0){let m=0;const p=a.reduce((g,b)=>{const S=" ".repeat(b.start-m),x="^".repeat(b.length);return m=b.start+b.length,g+S+x},"");throw new lt(`Path parameters result in path with invalid segments:
19
+ ${a.map(g=>g.error).join(`
20
+ `)}
21
+ ${i}
22
+ ${p}`)}return i},We=RT(Ox);let $x=class extends ut{list(t,n={},s){return this._client.getAPIList(We`/chat/completions/${t}/messages`,cn,{query:n,...s})}};function AT(e){return typeof e.parse=="function"}const kc=e=>(e==null?void 0:e.role)==="assistant",Dx=e=>(e==null?void 0:e.role)==="tool";var Hu,Zl,ec,yi,bi,tc,xi,nr,vi,Tc,jc,Io,Lx;class Zm{constructor(){Hu.add(this),this.controller=new AbortController,Zl.set(this,void 0),ec.set(this,()=>{}),yi.set(this,()=>{}),bi.set(this,void 0),tc.set(this,()=>{}),xi.set(this,()=>{}),nr.set(this,{}),vi.set(this,!1),Tc.set(this,!1),jc.set(this,!1),Io.set(this,!1),it(this,Zl,new Promise((t,n)=>{it(this,ec,t,"f"),it(this,yi,n,"f")})),it(this,bi,new Promise((t,n)=>{it(this,tc,t,"f"),it(this,xi,n,"f")})),ie(this,Zl,"f").catch(()=>{}),ie(this,bi,"f").catch(()=>{})}_run(t){setTimeout(()=>{t().then(()=>{this._emitFinal(),this._emit("end")},ie(this,Hu,"m",Lx).bind(this))},0)}_connected(){this.ended||(ie(this,ec,"f").call(this),this._emit("connect"))}get ended(){return ie(this,vi,"f")}get errored(){return ie(this,Tc,"f")}get aborted(){return ie(this,jc,"f")}abort(){this.controller.abort()}on(t,n){return(ie(this,nr,"f")[t]||(ie(this,nr,"f")[t]=[])).push({listener:n}),this}off(t,n){const s=ie(this,nr,"f")[t];if(!s)return this;const r=s.findIndex(a=>a.listener===n);return r>=0&&s.splice(r,1),this}once(t,n){return(ie(this,nr,"f")[t]||(ie(this,nr,"f")[t]=[])).push({listener:n,once:!0}),this}emitted(t){return new Promise((n,s)=>{it(this,Io,!0),t!=="error"&&this.once("error",s),this.once(t,n)})}async done(){it(this,Io,!0),await ie(this,bi,"f")}_emit(t,...n){if(ie(this,vi,"f"))return;t==="end"&&(it(this,vi,!0),ie(this,tc,"f").call(this));const s=ie(this,nr,"f")[t];if(s&&(ie(this,nr,"f")[t]=s.filter(r=>!r.once),s.forEach(({listener:r})=>r(...n))),t==="abort"){const r=n[0];!ie(this,Io,"f")&&!(s!=null&&s.length)&&Promise.reject(r),ie(this,yi,"f").call(this,r),ie(this,xi,"f").call(this,r),this._emit("end");return}if(t==="error"){const r=n[0];!ie(this,Io,"f")&&!(s!=null&&s.length)&&Promise.reject(r),ie(this,yi,"f").call(this,r),ie(this,xi,"f").call(this,r),this._emit("end")}}_emitFinal(){}}Zl=new WeakMap,ec=new WeakMap,yi=new WeakMap,bi=new WeakMap,tc=new WeakMap,xi=new WeakMap,nr=new WeakMap,vi=new WeakMap,Tc=new WeakMap,jc=new WeakMap,Io=new WeakMap,Hu=new WeakSet,Lx=function(t){if(it(this,Tc,!0),t instanceof Error&&t.name==="AbortError"&&(t=new gs),t instanceof gs)return it(this,jc,!0),this._emit("abort",t);if(t instanceof lt)return this._emit("error",t);if(t instanceof Error){const n=new lt(t.message);return n.cause=t,this._emit("error",n)}return this._emit("error",new lt(String(t)))};function eh(e){return(e==null?void 0:e.$brand)==="auto-parseable-response-format"}function Zi(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function IT(e,t){return!t||!Fx(t)?{...e,choices:e.choices.map(n=>({...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:th(e,t)}function th(e,t){const n=e.choices.map(s=>{var r;if(s.finish_reason==="length")throw new bx;if(s.finish_reason==="content_filter")throw new xx;return{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:((r=s.message.tool_calls)==null?void 0:r.map(a=>$T(t,a)))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?OT(t,s.message.content):null}}});return{...e,choices:n}}function OT(e,t){var n,s;return((n=e.response_format)==null?void 0:n.type)!=="json_schema"?null:((s=e.response_format)==null?void 0:s.type)==="json_schema"?"$parseRaw"in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function $T(e,t){var s;const n=(s=e.tools)==null?void 0:s.find(r=>{var a;return((a=r.function)==null?void 0:a.name)===t.function.name});return{...t,function:{...t.function,parsed_arguments:Zi(n)?n.$parseRaw(t.function.arguments):n!=null&&n.function.strict?JSON.parse(t.function.arguments):null}}}function DT(e,t){var s;if(!e)return!1;const n=(s=e.tools)==null?void 0:s.find(r=>{var a;return((a=r.function)==null?void 0:a.name)===t.function.name});return Zi(n)||(n==null?void 0:n.function.strict)||!1}function Fx(e){var t;return eh(e.response_format)?!0:((t=e.tools)==null?void 0:t.some(n=>Zi(n)||n.type==="function"&&n.function.strict===!0))??!1}function LT(e){for(const t of e??[]){if(t.type!=="function")throw new lt(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new lt(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Nn,Ku,Cc,Yu,Vu,Xu,Nx,zx;const FT=10;class Bx extends Zm{constructor(){super(...arguments),Nn.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(t){var s;this._chatCompletions.push(t),this._emit("chatCompletion",t);const n=(s=t.choices[0])==null?void 0:s.message;return n&&this._addMessage(n),t}_addMessage(t,n=!0){if("content"in t||(t.content=null),this.messages.push(t),n){if(this._emit("message",t),Dx(t)&&t.content)this._emit("functionToolCallResult",t.content);else if(kc(t)&&t.tool_calls)for(const s of t.tool_calls)s.type==="function"&&this._emit("functionToolCall",s.function)}}async finalChatCompletion(){await this.done();const t=this._chatCompletions[this._chatCompletions.length-1];if(!t)throw new lt("stream ended without producing a ChatCompletion");return t}async finalContent(){return await this.done(),ie(this,Nn,"m",Ku).call(this)}async finalMessage(){return await this.done(),ie(this,Nn,"m",Cc).call(this)}async finalFunctionToolCall(){return await this.done(),ie(this,Nn,"m",Yu).call(this)}async finalFunctionToolCallResult(){return await this.done(),ie(this,Nn,"m",Vu).call(this)}async totalUsage(){return await this.done(),ie(this,Nn,"m",Xu).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const t=this._chatCompletions[this._chatCompletions.length-1];t&&this._emit("finalChatCompletion",t);const n=ie(this,Nn,"m",Cc).call(this);n&&this._emit("finalMessage",n);const s=ie(this,Nn,"m",Ku).call(this);s&&this._emit("finalContent",s);const r=ie(this,Nn,"m",Yu).call(this);r&&this._emit("finalFunctionToolCall",r);const a=ie(this,Nn,"m",Vu).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",ie(this,Nn,"m",Xu).call(this))}async _createChatCompletion(t,n,s){const r=s==null?void 0:s.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),ie(this,Nn,"m",Nx).call(this,n);const a=await t.chat.completions.create({...n,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(th(a,n))}async _runChatCompletion(t,n,s){for(const r of n.messages)this._addMessage(r,!1);return await this._createChatCompletion(t,n,s)}async _runTools(t,n,s){var b,S,x;const r="tool",{tool_choice:a="auto",stream:i,...l}=n,c=typeof a!="string"&&((b=a==null?void 0:a.function)==null?void 0:b.name),{maxChatCompletions:u=FT}=s||{},m=n.tools.map(k=>{if(Zi(k)){if(!k.$callback)throw new lt("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:k.$callback,name:k.function.name,description:k.function.description||"",parameters:k.function.parameters,parse:k.$parseRaw,strict:!0}}}return k}),p={};for(const k of m)k.type==="function"&&(p[k.function.name||k.function.function.name]=k.function);const g="tools"in n?m.map(k=>k.type==="function"?{type:"function",function:{name:k.function.name||k.function.function.name,parameters:k.function.parameters,description:k.function.description,strict:k.function.strict}}:k):void 0;for(const k of n.messages)this._addMessage(k,!1);for(let k=0;k<u;++k){const w=(S=(await this._createChatCompletion(t,{...l,tool_choice:a,tools:g,messages:[...this.messages]},s)).choices[0])==null?void 0:S.message;if(!w)throw new lt("missing message in ChatCompletion response");if(!((x=w.tool_calls)!=null&&x.length))return;for(const M of w.tool_calls){if(M.type!=="function")continue;const _=M.id,{name:C,arguments:D}=M.function,A=p[C];if(A){if(c&&c!==C){const R=`Invalid tool_call: ${JSON.stringify(C)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:r,tool_call_id:_,content:R});continue}}else{const R=`Invalid tool_call: ${JSON.stringify(C)}. Available options are: ${Object.keys(p).map(I=>JSON.stringify(I)).join(", ")}. Please try again`;this._addMessage({role:r,tool_call_id:_,content:R});continue}let B;try{B=AT(A)?await A.parse(D):D}catch(R){const I=R instanceof Error?R.message:String(R);this._addMessage({role:r,tool_call_id:_,content:I});continue}const F=await A.function(B,this),O=ie(this,Nn,"m",zx).call(this,F);if(this._addMessage({role:r,tool_call_id:_,content:O}),c)return}}}}Nn=new WeakSet,Ku=function(){return ie(this,Nn,"m",Cc).call(this).content??null},Cc=function(){let t=this.messages.length;for(;t-- >0;){const n=this.messages[t];if(kc(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new lt("stream ended without producing a ChatCompletionMessage with role=assistant")},Yu=function(){var t,n;for(let s=this.messages.length-1;s>=0;s--){const r=this.messages[s];if(kc(r)&&((t=r==null?void 0:r.tool_calls)!=null&&t.length))return(n=r.tool_calls.at(-1))==null?void 0:n.function}},Vu=function(){for(let t=this.messages.length-1;t>=0;t--){const n=this.messages[t];if(Dx(n)&&n.content!=null&&typeof n.content=="string"&&this.messages.some(s=>{var r;return s.role==="assistant"&&((r=s.tool_calls)==null?void 0:r.some(a=>a.type==="function"&&a.id===n.tool_call_id))}))return n.content}},Xu=function(){const t={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:n}of this._chatCompletions)n&&(t.completion_tokens+=n.completion_tokens,t.prompt_tokens+=n.prompt_tokens,t.total_tokens+=n.total_tokens);return t},Nx=function(t){if(t.n!=null&&t.n>1)throw new lt("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},zx=function(t){return typeof t=="string"?t:t===void 0?"undefined":JSON.stringify(t)};class nh extends Bx{static runTools(t,n,s){const r=new nh,a={...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(t,n,a)),r}_addMessage(t,n=!0){super._addMessage(t,n),kc(t)&&t.content&&this._emit("content",t.content)}}const Wx=1,qx=2,Ux=4,Hx=8,Kx=16,Yx=32,Vx=64,Xx=128,Gx=256,Jx=Xx|Gx,Qx=Kx|Yx|Jx|Vx,Zx=Wx|qx|Qx,ev=Ux|Hx,NT=Zx|ev,Sn={STR:Wx,NUM:qx,ARR:Ux,OBJ:Hx,NULL:Kx,BOOL:Yx,NAN:Vx,INFINITY:Xx,MINUS_INFINITY:Gx,INF:Jx,SPECIAL:Qx,ATOM:Zx,COLLECTION:ev,ALL:NT};class zT extends Error{}class BT extends Error{}function WT(e,t=Sn.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return qT(e.trim(),t)}const qT=(e,t)=>{const n=e.length;let s=0;const r=g=>{throw new zT(`${g} at position ${s}`)},a=g=>{throw new BT(`${g} at position ${s}`)},i=()=>(p(),s>=n&&r("Unexpected end of input"),e[s]==='"'?l():e[s]==="{"?c():e[s]==="["?u():e.substring(s,s+4)==="null"||Sn.NULL&t&&n-s<4&&"null".startsWith(e.substring(s))?(s+=4,null):e.substring(s,s+4)==="true"||Sn.BOOL&t&&n-s<4&&"true".startsWith(e.substring(s))?(s+=4,!0):e.substring(s,s+5)==="false"||Sn.BOOL&t&&n-s<5&&"false".startsWith(e.substring(s))?(s+=5,!1):e.substring(s,s+8)==="Infinity"||Sn.INFINITY&t&&n-s<8&&"Infinity".startsWith(e.substring(s))?(s+=8,1/0):e.substring(s,s+9)==="-Infinity"||Sn.MINUS_INFINITY&t&&1<n-s&&n-s<9&&"-Infinity".startsWith(e.substring(s))?(s+=9,-1/0):e.substring(s,s+3)==="NaN"||Sn.NAN&t&&n-s<3&&"NaN".startsWith(e.substring(s))?(s+=3,NaN):m()),l=()=>{const g=s;let b=!1;for(s++;s<n&&(e[s]!=='"'||b&&e[s-1]==="\\");)b=e[s]==="\\"?!b:!1,s++;if(e.charAt(s)=='"')try{return JSON.parse(e.substring(g,++s-Number(b)))}catch(S){a(String(S))}else if(Sn.STR&t)try{return JSON.parse(e.substring(g,s-Number(b))+'"')}catch{return JSON.parse(e.substring(g,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},c=()=>{s++,p();const g={};try{for(;e[s]!=="}";){if(p(),s>=n&&Sn.OBJ&t)return g;const b=l();p(),s++;try{const S=i();Object.defineProperty(g,b,{value:S,writable:!0,enumerable:!0,configurable:!0})}catch(S){if(Sn.OBJ&t)return g;throw S}p(),e[s]===","&&s++}}catch{if(Sn.OBJ&t)return g;r("Expected '}' at end of object")}return s++,g},u=()=>{s++;const g=[];try{for(;e[s]!=="]";)g.push(i()),p(),e[s]===","&&s++}catch{if(Sn.ARR&t)return g;r("Expected ']' at end of array")}return s++,g},m=()=>{if(s===0){e==="-"&&Sn.NUM&t&&r("Not sure what '-' is");try{return JSON.parse(e)}catch(b){if(Sn.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(b))}}const g=s;for(e[s]==="-"&&s++;e[s]&&!",]}".includes(e[s]);)s++;s==n&&!(Sn.NUM&t)&&r("Unterminated number literal");try{return JSON.parse(e.substring(g,s))}catch{e.substring(g,s)==="-"&&Sn.NUM&t&&r("Not sure what '-' is");try{return JSON.parse(e.substring(g,e.lastIndexOf("e")))}catch(S){a(String(S))}}},p=()=>{for(;s<n&&`
23
+ \r `.includes(e[s]);)s++};return i()},tp=e=>WT(e,Sn.ALL^Sn.NUM);var hn,Js,wo,gr,Nd,Pl,zd,Bd,Wd,El,qd,np;class Ni extends Bx{constructor(t){super(),hn.add(this),Js.set(this,void 0),wo.set(this,void 0),gr.set(this,void 0),it(this,Js,t),it(this,wo,[])}get currentChatCompletionSnapshot(){return ie(this,gr,"f")}static fromReadableStream(t){const n=new Ni(null);return n._run(()=>n._fromReadableStream(t)),n}static createChatCompletion(t,n,s){const r=new Ni(n);return r._run(()=>r._runChatCompletion(t,{...n,stream:!0},{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(t,n,s){var i;super._createChatCompletion;const r=s==null?void 0:s.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),ie(this,hn,"m",Nd).call(this);const a=await t.chat.completions.create({...n,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(const l of a)ie(this,hn,"m",zd).call(this,l);if((i=a.controller.signal)!=null&&i.aborted)throw new gs;return this._addChatCompletion(ie(this,hn,"m",El).call(this))}async _fromReadableStream(t,n){var i;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),ie(this,hn,"m",Nd).call(this),this._connected();const r=Ys.fromReadableStream(t,this.controller);let a;for await(const l of r)a&&a!==l.id&&this._addChatCompletion(ie(this,hn,"m",El).call(this)),ie(this,hn,"m",zd).call(this,l),a=l.id;if((i=r.controller.signal)!=null&&i.aborted)throw new gs;return this._addChatCompletion(ie(this,hn,"m",El).call(this))}[(Js=new WeakMap,wo=new WeakMap,gr=new WeakMap,hn=new WeakSet,Nd=function(){this.ended||it(this,gr,void 0)},Pl=function(n){let s=ie(this,wo,"f")[n.index];return s||(s={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},ie(this,wo,"f")[n.index]=s,s)},zd=function(n){var r,a,i,l,c,u,m,p,g,b,S,x,k,j,w;if(this.ended)return;const s=ie(this,hn,"m",np).call(this,n);this._emit("chunk",n,s);for(const M of n.choices){const _=s.choices[M.index];M.delta.content!=null&&((r=_.message)==null?void 0:r.role)==="assistant"&&((a=_.message)!=null&&a.content)&&(this._emit("content",M.delta.content,_.message.content),this._emit("content.delta",{delta:M.delta.content,snapshot:_.message.content,parsed:_.message.parsed})),M.delta.refusal!=null&&((i=_.message)==null?void 0:i.role)==="assistant"&&((l=_.message)!=null&&l.refusal)&&this._emit("refusal.delta",{delta:M.delta.refusal,snapshot:_.message.refusal}),((c=M.logprobs)==null?void 0:c.content)!=null&&((u=_.message)==null?void 0:u.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(m=M.logprobs)==null?void 0:m.content,snapshot:((p=_.logprobs)==null?void 0:p.content)??[]}),((g=M.logprobs)==null?void 0:g.refusal)!=null&&((b=_.message)==null?void 0:b.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(S=M.logprobs)==null?void 0:S.refusal,snapshot:((x=_.logprobs)==null?void 0:x.refusal)??[]});const C=ie(this,hn,"m",Pl).call(this,_);_.finish_reason&&(ie(this,hn,"m",Wd).call(this,_),C.current_tool_call_index!=null&&ie(this,hn,"m",Bd).call(this,_,C.current_tool_call_index));for(const D of M.delta.tool_calls??[])C.current_tool_call_index!==D.index&&(ie(this,hn,"m",Wd).call(this,_),C.current_tool_call_index!=null&&ie(this,hn,"m",Bd).call(this,_,C.current_tool_call_index)),C.current_tool_call_index=D.index;for(const D of M.delta.tool_calls??[]){const A=(k=_.message.tool_calls)==null?void 0:k[D.index];A!=null&&A.type&&((A==null?void 0:A.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(j=A.function)==null?void 0:j.name,index:D.index,arguments:A.function.arguments,parsed_arguments:A.function.parsed_arguments,arguments_delta:((w=D.function)==null?void 0:w.arguments)??""}):(A==null||A.type,void 0))}}},Bd=function(n,s){var i,l,c;if(ie(this,hn,"m",Pl).call(this,n).done_tool_calls.has(s))return;const a=(i=n.message.tool_calls)==null?void 0:i[s];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=ie(this,Js,"f"))==null?void 0:l.tools)==null?void 0:c.find(m=>m.type==="function"&&m.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:s,arguments:a.function.arguments,parsed_arguments:Zi(u)?u.$parseRaw(a.function.arguments):u!=null&&u.function.strict?JSON.parse(a.function.arguments):null})}else a.type},Wd=function(n){var r,a;const s=ie(this,hn,"m",Pl).call(this,n);if(n.message.content&&!s.content_done){s.content_done=!0;const i=ie(this,hn,"m",qd).call(this);this._emit("content.done",{content:n.message.content,parsed:i?i.$parseRaw(n.message.content):null})}n.message.refusal&&!s.refusal_done&&(s.refusal_done=!0,this._emit("refusal.done",{refusal:n.message.refusal})),(r=n.logprobs)!=null&&r.content&&!s.logprobs_content_done&&(s.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:n.logprobs.content})),(a=n.logprobs)!=null&&a.refusal&&!s.logprobs_refusal_done&&(s.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:n.logprobs.refusal}))},El=function(){if(this.ended)throw new lt("stream has ended, this shouldn't happen");const n=ie(this,gr,"f");if(!n)throw new lt("request ended without sending any chunks");return it(this,gr,void 0),it(this,wo,[]),UT(n,ie(this,Js,"f"))},qd=function(){var s;const n=(s=ie(this,Js,"f"))==null?void 0:s.response_format;return eh(n)?n:null},np=function(n){var s,r,a,i;let l=ie(this,gr,"f");const{choices:c,...u}=n;l?Object.assign(l,u):l=it(this,gr,{...u,choices:[]});for(const{delta:m,finish_reason:p,index:g,logprobs:b=null,...S}of n.choices){let x=l.choices[g];if(x||(x=l.choices[g]={finish_reason:p,index:g,message:{},logprobs:b,...S}),b)if(!x.logprobs)x.logprobs=Object.assign({},b);else{const{content:D,refusal:A,...B}=b;Object.assign(x.logprobs,B),D&&((s=x.logprobs).content??(s.content=[]),x.logprobs.content.push(...D)),A&&((r=x.logprobs).refusal??(r.refusal=[]),x.logprobs.refusal.push(...A))}if(p&&(x.finish_reason=p,ie(this,Js,"f")&&Fx(ie(this,Js,"f")))){if(p==="length")throw new bx;if(p==="content_filter")throw new xx}if(Object.assign(x,S),!m)continue;const{content:k,refusal:j,function_call:w,role:M,tool_calls:_,...C}=m;if(Object.assign(x.message,C),j&&(x.message.refusal=(x.message.refusal||"")+j),M&&(x.message.role=M),w&&(x.message.function_call?(w.name&&(x.message.function_call.name=w.name),w.arguments&&((a=x.message.function_call).arguments??(a.arguments=""),x.message.function_call.arguments+=w.arguments)):x.message.function_call=w),k&&(x.message.content=(x.message.content||"")+k,!x.message.refusal&&ie(this,hn,"m",qd).call(this)&&(x.message.parsed=tp(x.message.content))),_){x.message.tool_calls||(x.message.tool_calls=[]);for(const{index:D,id:A,type:B,function:F,...O}of _){const R=(i=x.message.tool_calls)[D]??(i[D]={});Object.assign(R,O),A&&(R.id=A),B&&(R.type=B),F&&(R.function??(R.function={name:F.name??"",arguments:""})),F!=null&&F.name&&(R.function.name=F.name),F!=null&&F.arguments&&(R.function.arguments+=F.arguments,DT(ie(this,Js,"f"),R)&&(R.function.parsed_arguments=tp(R.function.arguments)))}}}return l},Symbol.asyncIterator)](){const t=[],n=[];let s=!1;return this.on("chunk",r=>{const a=n.shift();a?a.resolve(r):t.push(r)}),this.on("end",()=>{s=!0;for(const r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),this.on("error",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((a,i)=>n.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 Ys(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function UT(e,t){const{id:n,choices:s,created:r,model:a,system_fingerprint:i,...l}=e,c={...l,id:n,choices:s.map(({message:u,finish_reason:m,index:p,logprobs:g,...b})=>{if(!m)throw new lt(`missing finish_reason for choice ${p}`);const{content:S=null,function_call:x,tool_calls:k,...j}=u,w=u.role;if(!w)throw new lt(`missing role for choice ${p}`);if(x){const{arguments:M,name:_}=x;if(M==null)throw new lt(`missing function_call.arguments for choice ${p}`);if(!_)throw new lt(`missing function_call.name for choice ${p}`);return{...b,message:{content:S,function_call:{arguments:M,name:_},role:w,refusal:u.refusal??null},finish_reason:m,index:p,logprobs:g}}return k?{...b,index:p,finish_reason:m,logprobs:g,message:{...j,role:w,content:S,refusal:u.refusal??null,tool_calls:k.map((M,_)=>{const{function:C,type:D,id:A,...B}=M,{arguments:F,name:O,...R}=C||{};if(A==null)throw new lt(`missing choices[${p}].tool_calls[${_}].id
24
+ ${Rl(e)}`);if(D==null)throw new lt(`missing choices[${p}].tool_calls[${_}].type
25
+ ${Rl(e)}`);if(O==null)throw new lt(`missing choices[${p}].tool_calls[${_}].function.name
26
+ ${Rl(e)}`);if(F==null)throw new lt(`missing choices[${p}].tool_calls[${_}].function.arguments
27
+ ${Rl(e)}`);return{...B,id:A,type:D,function:{...R,name:O,arguments:F}}})}}:{...b,message:{...j,content:S,role:w,refusal:u.refusal??null},finish_reason:m,index:p,logprobs:g}}),created:r,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return IT(c,t)}function Rl(e){return JSON.stringify(e)}class Mc extends Ni{static fromReadableStream(t){const n=new Mc(null);return n._run(()=>n._fromReadableStream(t)),n}static runTools(t,n,s){const r=new Mc(n),a={...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(t,n,a)),r}}let sh=class extends ut{constructor(){super(...arguments),this.messages=new $x(this._client)}create(t,n){return this._client.post("/chat/completions",{body:t,...n,stream:t.stream??!1})}retrieve(t,n){return this._client.get(We`/chat/completions/${t}`,n)}update(t,n,s){return this._client.post(We`/chat/completions/${t}`,{body:n,...s})}list(t={},n){return this._client.getAPIList("/chat/completions",cn,{query:t,...n})}delete(t,n){return this._client.delete(We`/chat/completions/${t}`,n)}parse(t,n){return LT(t.tools),this._client.chat.completions.create(t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(s=>th(s,t))}runTools(t,n){return t.stream?Mc.runTools(this._client,t,n):nh.runTools(this._client,t,n)}stream(t,n){return Ni.createChatCompletion(this._client,t,n)}};sh.Messages=$x;class rh extends ut{constructor(){super(...arguments),this.completions=new sh(this._client)}}rh.Completions=sh;const tv=Symbol("brand.privateNullableHeaders");function*HT(e){if(!e)return;if(tv in e){const{values:s,nulls:r}=e;yield*s.entries();for(const a of r)yield[a,null];return}let t=!1,n;e instanceof Headers?n=e.entries():Bf(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let s of n){const r=s[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const a=Bf(s[1])?s[1]:[s[1]];let i=!1;for(const l of a)l!==void 0&&(t&&!i&&(i=!0,yield[r,null]),yield[r,l])}}const rt=e=>{const t=new Headers,n=new Set;for(const s of e){const r=new Set;for(const[a,i]of HT(s)){const l=a.toLowerCase();r.has(l)||(t.delete(a),r.add(l)),i===null?(t.delete(a),n.add(l)):(t.append(a,i),n.delete(l))}}return{[tv]:!0,values:t,nulls:n}};class nv extends ut{create(t,n){return this._client.post("/audio/speech",{body:t,...n,headers:rt([{Accept:"application/octet-stream"},n==null?void 0:n.headers]),__binaryResponse:!0})}}class sv extends ut{create(t,n){return this._client.post("/audio/transcriptions",fo({body:t,...n,stream:t.stream??!1,__metadata:{model:t.model}},this._client))}}class rv extends ut{create(t,n){return this._client.post("/audio/translations",fo({body:t,...n,__metadata:{model:t.model}},this._client))}}class el extends ut{constructor(){super(...arguments),this.transcriptions=new sv(this._client),this.translations=new rv(this._client),this.speech=new nv(this._client)}}el.Transcriptions=sv;el.Translations=rv;el.Speech=nv;class ov extends ut{create(t,n){return this._client.post("/batches",{body:t,...n})}retrieve(t,n){return this._client.get(We`/batches/${t}`,n)}list(t={},n){return this._client.getAPIList("/batches",cn,{query:t,...n})}cancel(t,n){return this._client.post(We`/batches/${t}/cancel`,n)}}class av extends ut{create(t,n){return this._client.post("/assistants",{body:t,...n,headers:rt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(We`/assistants/${t}`,{...n,headers:rt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,n,s){return this._client.post(We`/assistants/${t}`,{body:n,...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}list(t={},n){return this._client.getAPIList("/assistants",cn,{query:t,...n,headers:rt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,n){return this._client.delete(We`/assistants/${t}`,{...n,headers:rt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class iv extends ut{create(t,n){return this._client.post("/realtime/sessions",{body:t,...n,headers:rt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class lv extends ut{create(t,n){return this._client.post("/realtime/transcription_sessions",{body:t,...n,headers:rt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class Vc extends ut{constructor(){super(...arguments),this.sessions=new iv(this._client),this.transcriptionSessions=new lv(this._client)}}Vc.Sessions=iv;Vc.TranscriptionSessions=lv;class cv extends ut{create(t,n,s){return this._client.post(We`/threads/${t}/messages`,{body:n,...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,n,s){const{thread_id:r}=n;return this._client.get(We`/threads/${r}/messages/${t}`,{...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,n,s){const{thread_id:r,...a}=n;return this._client.post(We`/threads/${r}/messages/${t}`,{body:a,...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}list(t,n={},s){return this._client.getAPIList(We`/threads/${t}/messages`,cn,{query:n,...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}delete(t,n,s){const{thread_id:r}=n;return this._client.delete(We`/threads/${r}/messages/${t}`,{...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class dv extends ut{retrieve(t,n,s){const{thread_id:r,run_id:a,...i}=n;return this._client.get(We`/threads/${r}/runs/${a}/steps/${t}`,{query:i,...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}list(t,n,s){const{thread_id:r,...a}=n;return this._client.getAPIList(We`/threads/${r}/runs/${t}/steps`,cn,{query:a,...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}const KT=e=>{if(typeof Buffer<"u"){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{const t=atob(e),n=t.length,s=new Uint8Array(n);for(let r=0;r<n;r++)s[r]=t.charCodeAt(r);return Array.from(new Float32Array(s.buffer))}};var Ud={};const _o=e=>{var t,n,s,r;if(typeof globalThis.process<"u")return((t=Ud==null?void 0:Ud[e])==null?void 0:t.trim())??void 0;if(typeof globalThis.Deno<"u")return(r=(s=(n=globalThis.Deno.env)==null?void 0:n.get)==null?void 0:s.call(n,e))==null?void 0:r.trim()};var Cn,ro,Gu,qs,nc,Cs,oo,Do,Vr,Pc,ns,sc,rc,Pi,Si,wi,sp,rp,op,ap,ip,lp,cp;class Ei extends Zm{constructor(){super(...arguments),Cn.add(this),Gu.set(this,[]),qs.set(this,{}),nc.set(this,{}),Cs.set(this,void 0),oo.set(this,void 0),Do.set(this,void 0),Vr.set(this,void 0),Pc.set(this,void 0),ns.set(this,void 0),sc.set(this,void 0),rc.set(this,void 0),Pi.set(this,void 0)}[(Gu=new WeakMap,qs=new WeakMap,nc=new WeakMap,Cs=new WeakMap,oo=new WeakMap,Do=new WeakMap,Vr=new WeakMap,Pc=new WeakMap,ns=new WeakMap,sc=new WeakMap,rc=new WeakMap,Pi=new WeakMap,Cn=new WeakSet,Symbol.asyncIterator)](){const t=[],n=[];let s=!1;return this.on("event",r=>{const a=n.shift();a?a.resolve(r):t.push(r)}),this.on("end",()=>{s=!0;for(const r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),this.on("error",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((a,i)=>n.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 n=new ro;return n._run(()=>n._fromReadableStream(t)),n}async _fromReadableStream(t,n){var a;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),this._connected();const r=Ys.fromReadableStream(t,this.controller);for await(const i of r)ie(this,Cn,"m",Si).call(this,i);if((a=r.controller.signal)!=null&&a.aborted)throw new gs;return this._addRun(ie(this,Cn,"m",wi).call(this))}toReadableStream(){return new Ys(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,n,s,r){const a=new ro;return a._run(()=>a._runToolAssistantStream(t,n,s,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(t,n,s,r){var c;const a=r==null?void 0:r.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...s,stream:!0},l=await t.submitToolOutputs(n,i,{...r,signal:this.controller.signal});this._connected();for await(const u of l)ie(this,Cn,"m",Si).call(this,u);if((c=l.controller.signal)!=null&&c.aborted)throw new gs;return this._addRun(ie(this,Cn,"m",wi).call(this))}static createThreadAssistantStream(t,n,s){const r=new ro;return r._run(()=>r._threadAssistantStream(t,n,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),r}static createAssistantStream(t,n,s,r){const a=new ro;return a._run(()=>a._runAssistantStream(t,n,s,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return ie(this,sc,"f")}currentRun(){return ie(this,rc,"f")}currentMessageSnapshot(){return ie(this,Cs,"f")}currentRunStepSnapshot(){return ie(this,Pi,"f")}async finalRunSteps(){return await this.done(),Object.values(ie(this,qs,"f"))}async finalMessages(){return await this.done(),Object.values(ie(this,nc,"f"))}async finalRun(){if(await this.done(),!ie(this,oo,"f"))throw Error("Final run was not received.");return ie(this,oo,"f")}async _createThreadAssistantStream(t,n,s){var l;const r=s==null?void 0:s.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const a={...n,stream:!0},i=await t.createAndRun(a,{...s,signal:this.controller.signal});this._connected();for await(const c of i)ie(this,Cn,"m",Si).call(this,c);if((l=i.controller.signal)!=null&&l.aborted)throw new gs;return this._addRun(ie(this,Cn,"m",wi).call(this))}async _createAssistantStream(t,n,s,r){var c;const a=r==null?void 0:r.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...s,stream:!0},l=await t.create(n,i,{...r,signal:this.controller.signal});this._connected();for await(const u of l)ie(this,Cn,"m",Si).call(this,u);if((c=l.controller.signal)!=null&&c.aborted)throw new gs;return this._addRun(ie(this,Cn,"m",wi).call(this))}static accumulateDelta(t,n){for(const[s,r]of Object.entries(n)){if(!t.hasOwnProperty(s)){t[s]=r;continue}let a=t[s];if(a==null){t[s]=r;continue}if(s==="index"||s==="type"){t[s]=r;continue}if(typeof a=="string"&&typeof r=="string")a+=r;else if(typeof a=="number"&&typeof r=="number")a+=r;else if(Dd(a)&&Dd(r))a=this.accumulateDelta(a,r);else if(Array.isArray(a)&&Array.isArray(r)){if(a.every(i=>typeof i=="string"||typeof i=="number")){a.push(...r);continue}for(const i of r){if(!Dd(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: ${s}, deltaValue: ${r}, accValue: ${a}`);t[s]=a}return t}_addRun(t){return t}async _threadAssistantStream(t,n,s){return await this._createThreadAssistantStream(n,t,s)}async _runAssistantStream(t,n,s,r){return await this._createAssistantStream(n,t,s,r)}async _runToolAssistantStream(t,n,s,r){return await this._createToolAssistantStream(n,t,s,r)}}ro=Ei,Si=function(t){if(!this.ended)switch(it(this,sc,t),ie(this,Cn,"m",op).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":ie(this,Cn,"m",cp).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":ie(this,Cn,"m",rp).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":ie(this,Cn,"m",sp).call(this,t);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},wi=function(){if(this.ended)throw new lt("stream has ended, this shouldn't happen");if(!ie(this,oo,"f"))throw Error("Final run has not been received");return ie(this,oo,"f")},sp=function(t){const[n,s]=ie(this,Cn,"m",ip).call(this,t,ie(this,Cs,"f"));it(this,Cs,n),ie(this,nc,"f")[n.id]=n;for(const r of s){const a=n.content[r.index];(a==null?void 0:a.type)=="text"&&this._emit("textCreated",a.text)}switch(t.event){case"thread.message.created":this._emit("messageCreated",t.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",t.data.delta,n),t.data.delta.content)for(const r of t.data.delta.content){if(r.type=="text"&&r.text){let a=r.text,i=n.content[r.index];if(i&&i.type=="text")this._emit("textDelta",a,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(r.index!=ie(this,Do,"f")){if(ie(this,Vr,"f"))switch(ie(this,Vr,"f").type){case"text":this._emit("textDone",ie(this,Vr,"f").text,ie(this,Cs,"f"));break;case"image_file":this._emit("imageFileDone",ie(this,Vr,"f").image_file,ie(this,Cs,"f"));break}it(this,Do,r.index)}it(this,Vr,n.content[r.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(ie(this,Do,"f")!==void 0){const r=t.data.content[ie(this,Do,"f")];if(r)switch(r.type){case"image_file":this._emit("imageFileDone",r.image_file,ie(this,Cs,"f"));break;case"text":this._emit("textDone",r.text,ie(this,Cs,"f"));break}}ie(this,Cs,"f")&&this._emit("messageDone",t.data),it(this,Cs,void 0)}},rp=function(t){const n=ie(this,Cn,"m",ap).call(this,t);switch(it(this,Pi,n),t.event){case"thread.run.step.created":this._emit("runStepCreated",t.data);break;case"thread.run.step.delta":const s=t.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&n.step_details.type=="tool_calls")for(const a of s.step_details.tool_calls)a.index==ie(this,Pc,"f")?this._emit("toolCallDelta",a,n.step_details.tool_calls[a.index]):(ie(this,ns,"f")&&this._emit("toolCallDone",ie(this,ns,"f")),it(this,Pc,a.index),it(this,ns,n.step_details.tool_calls[a.index]),ie(this,ns,"f")&&this._emit("toolCallCreated",ie(this,ns,"f")));this._emit("runStepDelta",t.data.delta,n);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":it(this,Pi,void 0),t.data.step_details.type=="tool_calls"&&ie(this,ns,"f")&&(this._emit("toolCallDone",ie(this,ns,"f")),it(this,ns,void 0)),this._emit("runStepDone",t.data,n);break}},op=function(t){ie(this,Gu,"f").push(t),this._emit("event",t)},ap=function(t){switch(t.event){case"thread.run.step.created":return ie(this,qs,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let n=ie(this,qs,"f")[t.data.id];if(!n)throw Error("Received a RunStepDelta before creation of a snapshot");let s=t.data;if(s.delta){const r=ro.accumulateDelta(n,s.delta);ie(this,qs,"f")[t.data.id]=r}return ie(this,qs,"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":ie(this,qs,"f")[t.data.id]=t.data;break}if(ie(this,qs,"f")[t.data.id])return ie(this,qs,"f")[t.data.id];throw new Error("No snapshot available")},ip=function(t,n){let s=[];switch(t.event){case"thread.message.created":return[t.data,s];case"thread.message.delta":if(!n)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let r=t.data;if(r.delta.content)for(const a of r.delta.content)if(a.index in n.content){let i=n.content[a.index];n.content[a.index]=ie(this,Cn,"m",lp).call(this,a,i)}else n.content[a.index]=a,s.push(a);return[n,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(n)return[n,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},lp=function(t,n){return ro.accumulateDelta(n,t)},cp=function(t){switch(it(this,rc,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":it(this,oo,t.data),ie(this,ns,"f")&&(this._emit("toolCallDone",ie(this,ns,"f")),it(this,ns,void 0));break}};let oh=class extends ut{constructor(){super(...arguments),this.steps=new dv(this._client)}create(t,n,s){const{include:r,...a}=n;return this._client.post(We`/threads/${t}/runs`,{query:{include:r},body:a,...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers]),stream:n.stream??!1})}retrieve(t,n,s){const{thread_id:r}=n;return this._client.get(We`/threads/${r}/runs/${t}`,{...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,n,s){const{thread_id:r,...a}=n;return this._client.post(We`/threads/${r}/runs/${t}`,{body:a,...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}list(t,n={},s){return this._client.getAPIList(We`/threads/${t}/runs`,cn,{query:n,...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}cancel(t,n,s){const{thread_id:r}=n;return this._client.post(We`/threads/${r}/runs/${t}/cancel`,{...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}async createAndPoll(t,n,s){const r=await this.create(t,n,s);return await this.poll(r.id,{thread_id:t},s)}createAndStream(t,n,s){return Ei.createAssistantStream(t,this._client.beta.threads.runs,n,s)}async poll(t,n,s){var a;const r=rt([s==null?void 0:s.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=s==null?void 0:s.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const{data:i,response:l}=await this.retrieve(t,n,{...s,headers:{...s==null?void 0:s.headers,...r}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let c=5e3;if(s!=null&&s.pollIntervalMs)c=s.pollIntervalMs;else{const u=l.headers.get("openai-poll-after-ms");if(u){const m=parseInt(u);isNaN(m)||(c=m)}}await Qi(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(t,n,s){return Ei.createAssistantStream(t,this._client.beta.threads.runs,n,s)}submitToolOutputs(t,n,s){const{thread_id:r,...a}=n;return this._client.post(We`/threads/${r}/runs/${t}/submit_tool_outputs`,{body:a,...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers]),stream:n.stream??!1})}async submitToolOutputsAndPoll(t,n,s){const r=await this.submitToolOutputs(t,n,s);return await this.poll(r.id,n,s)}submitToolOutputsStream(t,n,s){return Ei.createToolAssistantStream(t,this._client.beta.threads.runs,n,s)}};oh.Steps=dv;class Xc extends ut{constructor(){super(...arguments),this.runs=new oh(this._client),this.messages=new cv(this._client)}create(t={},n){return this._client.post("/threads",{body:t,...n,headers:rt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(We`/threads/${t}`,{...n,headers:rt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,n,s){return this._client.post(We`/threads/${t}`,{body:n,...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}delete(t,n){return this._client.delete(We`/threads/${t}`,{...n,headers:rt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}createAndRun(t,n){return this._client.post("/threads/runs",{body:t,...n,headers:rt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:t.stream??!1})}async createAndRunPoll(t,n){const s=await this.createAndRun(t,n);return await this.runs.poll(s.id,{thread_id:s.thread_id},n)}createAndRunStream(t,n){return Ei.createThreadAssistantStream(t,this._client.beta.threads,n)}}Xc.Runs=oh;Xc.Messages=cv;class tl extends ut{constructor(){super(...arguments),this.realtime=new Vc(this._client),this.assistants=new av(this._client),this.threads=new Xc(this._client)}}tl.Realtime=Vc;tl.Assistants=av;tl.Threads=Xc;class uv extends ut{create(t,n){return this._client.post("/completions",{body:t,...n,stream:t.stream??!1})}}let mv=class extends ut{retrieve(t,n,s){const{container_id:r}=n;return this._client.get(We`/containers/${r}/files/${t}/content`,{...s,headers:rt([{Accept:"application/binary"},s==null?void 0:s.headers]),__binaryResponse:!0})}},ah=class extends ut{constructor(){super(...arguments),this.content=new mv(this._client)}create(t,n,s){return this._client.post(We`/containers/${t}/files`,fo({body:n,...s},this._client))}retrieve(t,n,s){const{container_id:r}=n;return this._client.get(We`/containers/${r}/files/${t}`,s)}list(t,n={},s){return this._client.getAPIList(We`/containers/${t}/files`,cn,{query:n,...s})}delete(t,n,s){const{container_id:r}=n;return this._client.delete(We`/containers/${r}/files/${t}`,{...s,headers:rt([{Accept:"*/*"},s==null?void 0:s.headers])})}};ah.Content=mv;class ih extends ut{constructor(){super(...arguments),this.files=new ah(this._client)}create(t,n){return this._client.post("/containers",{body:t,...n})}retrieve(t,n){return this._client.get(We`/containers/${t}`,n)}list(t={},n){return this._client.getAPIList("/containers",cn,{query:t,...n})}delete(t,n){return this._client.delete(We`/containers/${t}`,{...n,headers:rt([{Accept:"*/*"},n==null?void 0:n.headers])})}}ih.Files=ah;class hv extends ut{create(t,n){const s=!!t.encoding_format;let r=s?t.encoding_format:"base64";s&&jn(this._client).debug("embeddings/user defined encoding_format:",t.encoding_format);const a=this._client.post("/embeddings",{body:{...t,encoding_format:r},...n});return s?a:(jn(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=KT(c)}),i)))}}class fv extends ut{retrieve(t,n,s){const{eval_id:r,run_id:a}=n;return this._client.get(We`/evals/${r}/runs/${a}/output_items/${t}`,s)}list(t,n,s){const{eval_id:r,...a}=n;return this._client.getAPIList(We`/evals/${r}/runs/${t}/output_items`,cn,{query:a,...s})}}class lh extends ut{constructor(){super(...arguments),this.outputItems=new fv(this._client)}create(t,n,s){return this._client.post(We`/evals/${t}/runs`,{body:n,...s})}retrieve(t,n,s){const{eval_id:r}=n;return this._client.get(We`/evals/${r}/runs/${t}`,s)}list(t,n={},s){return this._client.getAPIList(We`/evals/${t}/runs`,cn,{query:n,...s})}delete(t,n,s){const{eval_id:r}=n;return this._client.delete(We`/evals/${r}/runs/${t}`,s)}cancel(t,n,s){const{eval_id:r}=n;return this._client.post(We`/evals/${r}/runs/${t}`,s)}}lh.OutputItems=fv;class ch extends ut{constructor(){super(...arguments),this.runs=new lh(this._client)}create(t,n){return this._client.post("/evals",{body:t,...n})}retrieve(t,n){return this._client.get(We`/evals/${t}`,n)}update(t,n,s){return this._client.post(We`/evals/${t}`,{body:n,...s})}list(t={},n){return this._client.getAPIList("/evals",cn,{query:t,...n})}delete(t,n){return this._client.delete(We`/evals/${t}`,n)}}ch.Runs=lh;let pv=class extends ut{create(t,n){return this._client.post("/files",fo({body:t,...n},this._client))}retrieve(t,n){return this._client.get(We`/files/${t}`,n)}list(t={},n){return this._client.getAPIList("/files",cn,{query:t,...n})}delete(t,n){return this._client.delete(We`/files/${t}`,n)}content(t,n){return this._client.get(We`/files/${t}/content`,{...n,headers:rt([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}async waitForProcessing(t,{pollInterval:n=5e3,maxWait:s=30*60*1e3}={}){const r=new Set(["processed","error","deleted"]),a=Date.now();let i=await this.retrieve(t);for(;!i.status||!r.has(i.status);)if(await Qi(n),i=await this.retrieve(t),Date.now()-a>s)throw new Jm({message:`Giving up on waiting for file ${t} to finish processing after ${s} milliseconds.`});return i}};class gv extends ut{}let yv=class extends ut{run(t,n){return this._client.post("/fine_tuning/alpha/graders/run",{body:t,...n})}validate(t,n){return this._client.post("/fine_tuning/alpha/graders/validate",{body:t,...n})}};class dh extends ut{constructor(){super(...arguments),this.graders=new yv(this._client)}}dh.Graders=yv;class bv extends ut{create(t,n,s){return this._client.getAPIList(We`/fine_tuning/checkpoints/${t}/permissions`,Yc,{body:n,method:"post",...s})}retrieve(t,n={},s){return this._client.get(We`/fine_tuning/checkpoints/${t}/permissions`,{query:n,...s})}delete(t,n,s){const{fine_tuned_model_checkpoint:r}=n;return this._client.delete(We`/fine_tuning/checkpoints/${r}/permissions/${t}`,s)}}let uh=class extends ut{constructor(){super(...arguments),this.permissions=new bv(this._client)}};uh.Permissions=bv;class xv extends ut{list(t,n={},s){return this._client.getAPIList(We`/fine_tuning/jobs/${t}/checkpoints`,cn,{query:n,...s})}}class mh extends ut{constructor(){super(...arguments),this.checkpoints=new xv(this._client)}create(t,n){return this._client.post("/fine_tuning/jobs",{body:t,...n})}retrieve(t,n){return this._client.get(We`/fine_tuning/jobs/${t}`,n)}list(t={},n){return this._client.getAPIList("/fine_tuning/jobs",cn,{query:t,...n})}cancel(t,n){return this._client.post(We`/fine_tuning/jobs/${t}/cancel`,n)}listEvents(t,n={},s){return this._client.getAPIList(We`/fine_tuning/jobs/${t}/events`,cn,{query:n,...s})}pause(t,n){return this._client.post(We`/fine_tuning/jobs/${t}/pause`,n)}resume(t,n){return this._client.post(We`/fine_tuning/jobs/${t}/resume`,n)}}mh.Checkpoints=xv;class Go extends ut{constructor(){super(...arguments),this.methods=new gv(this._client),this.jobs=new mh(this._client),this.checkpoints=new uh(this._client),this.alpha=new dh(this._client)}}Go.Methods=gv;Go.Jobs=mh;Go.Checkpoints=uh;Go.Alpha=dh;class vv extends ut{}class hh extends ut{constructor(){super(...arguments),this.graderModels=new vv(this._client)}}hh.GraderModels=vv;class Sv extends ut{createVariation(t,n){return this._client.post("/images/variations",fo({body:t,...n},this._client))}edit(t,n){return this._client.post("/images/edits",fo({body:t,...n,stream:t.stream??!1},this._client))}generate(t,n){return this._client.post("/images/generations",{body:t,...n,stream:t.stream??!1})}}class wv extends ut{retrieve(t,n){return this._client.get(We`/models/${t}`,n)}list(t){return this._client.getAPIList("/models",Yc,t)}delete(t,n){return this._client.delete(We`/models/${t}`,n)}}class _v extends ut{create(t,n){return this._client.post("/moderations",{body:t,...n})}}function YT(e,t){return!t||!XT(t)?{...e,output_parsed:null,output:e.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(s=>({...s,parsed:null}))}:n)}:kv(e,t)}function kv(e,t){const n=e.output.map(r=>{if(r.type==="function_call")return{...r,parsed_arguments:QT(t,r)};if(r.type==="message"){const a=r.content.map(i=>i.type==="output_text"?{...i,parsed:VT(t,i.text)}:i);return{...r,content:a}}return r}),s=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,"output_text")||Ju(s),Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(const r of s.output)if(r.type==="message"){for(const a of r.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),s}function VT(e,t){var n,s,r,a;return((s=(n=e.text)==null?void 0:n.format)==null?void 0:s.type)!=="json_schema"?null:"$parseRaw"in((r=e.text)==null?void 0:r.format)?((a=e.text)==null?void 0:a.format).$parseRaw(t):JSON.parse(t)}function XT(e){var t;return!!eh((t=e.text)==null?void 0:t.format)}function GT(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function JT(e,t){return e.find(n=>n.type==="function"&&n.name===t)}function QT(e,t){const n=JT(e.tools??[],t.name);return{...t,...t,parsed_arguments:GT(n)?n.$parseRaw(t.arguments):n!=null&&n.strict?JSON.parse(t.arguments):null}}function Ju(e){const t=[];for(const n of e.output)if(n.type==="message")for(const s of n.content)s.type==="output_text"&&t.push(s.text);e.output_text=t.join("")}var ko,Al,yr,Il,dp,up,mp,hp;class fh extends Zm{constructor(t){super(),ko.add(this),Al.set(this,void 0),yr.set(this,void 0),Il.set(this,void 0),it(this,Al,t)}static createResponse(t,n,s){const r=new fh(n);return r._run(()=>r._createOrRetrieveResponse(t,n,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createOrRetrieveResponse(t,n,s){var l;const r=s==null?void 0:s.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),ie(this,ko,"m",dp).call(this);let a,i=null;"response_id"in n?(a=await t.responses.retrieve(n.response_id,{stream:!0},{...s,signal:this.controller.signal,stream:!0}),i=n.starting_after??null):a=await t.responses.create({...n,stream:!0},{...s,signal:this.controller.signal}),this._connected();for await(const c of a)ie(this,ko,"m",up).call(this,c,i);if((l=a.controller.signal)!=null&&l.aborted)throw new gs;return ie(this,ko,"m",mp).call(this)}[(Al=new WeakMap,yr=new WeakMap,Il=new WeakMap,ko=new WeakSet,dp=function(){this.ended||it(this,yr,void 0)},up=function(n,s){if(this.ended)return;const r=(i,l)=>{(s==null||l.sequence_number>s)&&this._emit(i,l)},a=ie(this,ko,"m",hp).call(this,n);switch(r("event",n),n.type){case"response.output_text.delta":{const i=a.output[n.output_index];if(!i)throw new lt(`missing output at index ${n.output_index}`);if(i.type==="message"){const l=i.content[n.content_index];if(!l)throw new lt(`missing content at index ${n.content_index}`);if(l.type!=="output_text")throw new lt(`expected content to be 'output_text', got ${l.type}`);r("response.output_text.delta",{...n,snapshot:l.text})}break}case"response.function_call_arguments.delta":{const i=a.output[n.output_index];if(!i)throw new lt(`missing output at index ${n.output_index}`);i.type==="function_call"&&r("response.function_call_arguments.delta",{...n,snapshot:i.arguments});break}default:r(n.type,n);break}},mp=function(){if(this.ended)throw new lt("stream has ended, this shouldn't happen");const n=ie(this,yr,"f");if(!n)throw new lt("request ended without sending any events");it(this,yr,void 0);const s=ZT(n,ie(this,Al,"f"));return it(this,Il,s),s},hp=function(n){let s=ie(this,yr,"f");if(!s){if(n.type!=="response.created")throw new lt(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return s=it(this,yr,n.response),s}switch(n.type){case"response.output_item.added":{s.output.push(n.item);break}case"response.content_part.added":{const r=s.output[n.output_index];if(!r)throw new lt(`missing output at index ${n.output_index}`);r.type==="message"&&r.content.push(n.part);break}case"response.output_text.delta":{const r=s.output[n.output_index];if(!r)throw new lt(`missing output at index ${n.output_index}`);if(r.type==="message"){const a=r.content[n.content_index];if(!a)throw new lt(`missing content at index ${n.content_index}`);if(a.type!=="output_text")throw new lt(`expected content to be 'output_text', got ${a.type}`);a.text+=n.delta}break}case"response.function_call_arguments.delta":{const r=s.output[n.output_index];if(!r)throw new lt(`missing output at index ${n.output_index}`);r.type==="function_call"&&(r.arguments+=n.delta);break}case"response.completed":{it(this,yr,n.response);break}}return s},Symbol.asyncIterator)](){const t=[],n=[];let s=!1;return this.on("event",r=>{const a=n.shift();a?a.resolve(r):t.push(r)}),this.on("end",()=>{s=!0;for(const r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),this.on("error",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((a,i)=>n.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=ie(this,Il,"f");if(!t)throw new lt("stream ended without producing a ChatCompletion");return t}}function ZT(e,t){return YT(e,t)}class Tv extends ut{list(t,n={},s){return this._client.getAPIList(We`/responses/${t}/input_items`,cn,{query:n,...s})}}class ph extends ut{constructor(){super(...arguments),this.inputItems=new Tv(this._client)}create(t,n){return this._client.post("/responses",{body:t,...n,stream:t.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Ju(s),s))}retrieve(t,n={},s){return this._client.get(We`/responses/${t}`,{query:n,...s,stream:(n==null?void 0:n.stream)??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Ju(r),r))}delete(t,n){return this._client.delete(We`/responses/${t}`,{...n,headers:rt([{Accept:"*/*"},n==null?void 0:n.headers])})}parse(t,n){return this._client.responses.create(t,n)._thenUnwrap(s=>kv(s,t))}stream(t,n){return fh.createResponse(this._client,t,n)}cancel(t,n){return this._client.post(We`/responses/${t}/cancel`,n)}}ph.InputItems=Tv;class jv extends ut{create(t,n,s){return this._client.post(We`/uploads/${t}/parts`,fo({body:n,...s},this._client))}}class gh extends ut{constructor(){super(...arguments),this.parts=new jv(this._client)}create(t,n){return this._client.post("/uploads",{body:t,...n})}cancel(t,n){return this._client.post(We`/uploads/${t}/cancel`,n)}complete(t,n,s){return this._client.post(We`/uploads/${t}/complete`,{body:n,...s})}}gh.Parts=jv;const ej=async e=>{const t=await Promise.allSettled(e),n=t.filter(r=>r.status==="rejected");if(n.length){for(const r of n)console.error(r.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const s=[];for(const r of t)r.status==="fulfilled"&&s.push(r.value);return s};class Cv extends ut{create(t,n,s){return this._client.post(We`/vector_stores/${t}/file_batches`,{body:n,...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,n,s){const{vector_store_id:r}=n;return this._client.get(We`/vector_stores/${r}/file_batches/${t}`,{...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}cancel(t,n,s){const{vector_store_id:r}=n;return this._client.post(We`/vector_stores/${r}/file_batches/${t}/cancel`,{...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}async createAndPoll(t,n,s){const r=await this.create(t,n);return await this.poll(t,r.id,s)}listFiles(t,n,s){const{vector_store_id:r,...a}=n;return this._client.getAPIList(We`/vector_stores/${r}/file_batches/${t}/files`,cn,{query:a,...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}async poll(t,n,s){var a;const r=rt([s==null?void 0:s.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=s==null?void 0:s.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const{data:i,response:l}=await this.retrieve(n,{vector_store_id:t},{...s,headers:r}).withResponse();switch(i.status){case"in_progress":let c=5e3;if(s!=null&&s.pollIntervalMs)c=s.pollIntervalMs;else{const u=l.headers.get("openai-poll-after-ms");if(u){const m=parseInt(u);isNaN(m)||(c=m)}}await Qi(c);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(t,{files:n,fileIds:s=[]},r){if(n==null||n.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const a=(r==null?void 0:r.maxConcurrency)??5,i=Math.min(a,n.length),l=this._client,c=n.values(),u=[...s];async function m(g){for(let b of g){const S=await l.files.create({file:b,purpose:"assistants"},r);u.push(S.id)}}const p=Array(i).fill(c).map(m);return await ej(p),await this.createAndPoll(t,{file_ids:u})}}class Mv extends ut{create(t,n,s){return this._client.post(We`/vector_stores/${t}/files`,{body:n,...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,n,s){const{vector_store_id:r}=n;return this._client.get(We`/vector_stores/${r}/files/${t}`,{...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,n,s){const{vector_store_id:r,...a}=n;return this._client.post(We`/vector_stores/${r}/files/${t}`,{body:a,...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}list(t,n={},s){return this._client.getAPIList(We`/vector_stores/${t}/files`,cn,{query:n,...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}delete(t,n,s){const{vector_store_id:r}=n;return this._client.delete(We`/vector_stores/${r}/files/${t}`,{...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}async createAndPoll(t,n,s){const r=await this.create(t,n,s);return await this.poll(t,r.id,s)}async poll(t,n,s){var a;const r=rt([s==null?void 0:s.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=s==null?void 0:s.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const i=await this.retrieve(n,{vector_store_id:t},{...s,headers:r}).withResponse(),l=i.data;switch(l.status){case"in_progress":let c=5e3;if(s!=null&&s.pollIntervalMs)c=s.pollIntervalMs;else{const u=i.response.headers.get("openai-poll-after-ms");if(u){const m=parseInt(u);isNaN(m)||(c=m)}}await Qi(c);break;case"failed":case"completed":return l}}}async upload(t,n,s){const r=await this._client.files.create({file:n,purpose:"assistants"},s);return this.create(t,{file_id:r.id},s)}async uploadAndPoll(t,n,s){const r=await this.upload(t,n,s);return await this.poll(t,r.id,s)}content(t,n,s){const{vector_store_id:r}=n;return this._client.getAPIList(We`/vector_stores/${r}/files/${t}/content`,Yc,{...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class Gc extends ut{constructor(){super(...arguments),this.files=new Mv(this._client),this.fileBatches=new Cv(this._client)}create(t,n){return this._client.post("/vector_stores",{body:t,...n,headers:rt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(We`/vector_stores/${t}`,{...n,headers:rt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,n,s){return this._client.post(We`/vector_stores/${t}`,{body:n,...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}list(t={},n){return this._client.getAPIList("/vector_stores",cn,{query:t,...n,headers:rt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,n){return this._client.delete(We`/vector_stores/${t}`,{...n,headers:rt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}search(t,n,s){return this._client.getAPIList(We`/vector_stores/${t}/search`,Yc,{body:n,method:"post",...s,headers:rt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}Gc.Files=Mv;Gc.FileBatches=Cv;var Oo,Pv,oc;class Ev extends ut{constructor(){super(...arguments),Oo.add(this)}async unwrap(t,n,s=this._client.webhookSecret,r=300){return await this.verifySignature(t,n,s,r),JSON.parse(t)}async verifySignature(t,n,s=this._client.webhookSecret,r=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");ie(this,Oo,"m",Pv).call(this,s);const a=rt([n]).values,i=ie(this,Oo,"m",oc).call(this,a,"webhook-signature"),l=ie(this,Oo,"m",oc).call(this,a,"webhook-timestamp"),c=ie(this,Oo,"m",oc).call(this,a,"webhook-id"),u=parseInt(l,10);if(isNaN(u))throw new fi("Invalid webhook timestamp format");const m=Math.floor(Date.now()/1e3);if(m-u>r)throw new fi("Webhook timestamp is too old");if(u>m+r)throw new fi("Webhook timestamp is too new");const p=i.split(" ").map(x=>x.startsWith("v1,")?x.substring(3):x),g=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),b=c?`${c}.${l}.${t}`:`${l}.${t}`,S=await crypto.subtle.importKey("raw",g,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const x of p)try{const k=Buffer.from(x,"base64");if(await crypto.subtle.verify("HMAC",S,k,new TextEncoder().encode(b)))return}catch{continue}throw new fi("The given webhook signature does not match the expected signature")}}Oo=new WeakSet,Pv=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")},oc=function(t,n){if(!t)throw new Error("Headers are required");const s=t.get(n);if(s==null)throw new Error(`Missing required header: ${n}`);return s};var Qu,yh,ac,Rv;class vt{constructor({baseURL:t=_o("OPENAI_BASE_URL"),apiKey:n=_o("OPENAI_API_KEY"),organization:s=_o("OPENAI_ORG_ID")??null,project:r=_o("OPENAI_PROJECT_ID")??null,webhookSecret:a=_o("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(Qu.add(this),ac.set(this,void 0),this.completions=new uv(this),this.chat=new rh(this),this.embeddings=new hv(this),this.files=new pv(this),this.images=new Sv(this),this.audio=new el(this),this.moderations=new _v(this),this.models=new wv(this),this.fineTuning=new Go(this),this.graders=new hh(this),this.vectorStores=new Gc(this),this.webhooks=new Ev(this),this.beta=new tl(this),this.batches=new ov(this),this.uploads=new gh(this),this.responses=new ph(this),this.evals=new ch(this),this.containers=new ih(this),n===void 0)throw new lt("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const l={apiKey:n,organization:s,project:r,webhookSecret:a,...i,baseURL:t||"https://api.openai.com/v1"};if(!l.dangerouslyAllowBrowser&&tT())throw new lt(`It looks like you're running in a browser-like environment.
28
+
29
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
30
+ If you understand the risks and have appropriate mitigations in place,
31
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
32
+
33
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
34
+
35
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
36
+ `);this.baseURL=l.baseURL,this.timeout=l.timeout??yh.DEFAULT_TIMEOUT,this.logger=l.logger??console;const c="warn";this.logLevel=c,this.logLevel=Jf(l.logLevel,"ClientOptions.logLevel",this)??Jf(_o("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??aT(),it(this,ac,lT),this._options=l,this.apiKey=n,this.organization=s,this.project=r,this.webhookSecret=a}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...t})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:n}){}async authHeaders(t){return rt([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return fT(t,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Ao}`}defaultIdempotencyKey(){return`stainless-node-retry-${cx()}`}makeStatusError(t,n,s,r){return Pn.generate(t,n,s,r)}buildURL(t,n,s){const r=!ie(this,Qu,"m",Rv).call(this)&&s||this.baseURL,a=Xk(t)?new URL(t):new URL(r+(r.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),i=this.defaultQuery();return Jk(i)||(n={...i,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(a.search=this.stringifyQuery(n)),a.toString()}async prepareOptions(t){}async prepareRequest(t,{url:n,options:s}){}get(t,n){return this.methodRequest("get",t,n)}post(t,n){return this.methodRequest("post",t,n)}patch(t,n){return this.methodRequest("patch",t,n)}put(t,n){return this.methodRequest("put",t,n)}delete(t,n){return this.methodRequest("delete",t,n)}methodRequest(t,n,s){return this.request(Promise.resolve(s).then(r=>({method:t,path:n,...r})))}request(t,n=null){return new Kc(this,this.makeRequest(t,n,void 0))}async makeRequest(t,n,s){var j,w;const r=await t,a=r.maxRetries??this.maxRetries;n==null&&(n=a),await this.prepareOptions(r);const{req:i,url:l,timeout:c}=await this.buildRequest(r,{retryCount:a-n});await this.prepareRequest(i,{url:l,options:r});const u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=s===void 0?"":`, retryOf: ${s}`,p=Date.now();if(jn(this).debug(`[${u}] sending request`,Ur({retryOfRequestLogID:s,method:r.method,url:l,options:r,headers:i.headers})),(j=r.signal)!=null&&j.aborted)throw new gs;const g=new AbortController,b=await this.fetchWithTimeout(l,i,c,g).catch(Bu),S=Date.now();if(b instanceof Error){const M=`retrying, ${n} attempts remaining`;if((w=r.signal)!=null&&w.aborted)throw new gs;const _=zu(b)||/timed? ?out/i.test(String(b)+("cause"in b?String(b.cause):""));if(n)return jn(this).info(`[${u}] connection ${_?"timed out":"failed"} - ${M}`),jn(this).debug(`[${u}] connection ${_?"timed out":"failed"} (${M})`,Ur({retryOfRequestLogID:s,url:l,durationMs:S-p,message:b.message})),this.retryRequest(r,n,s??u);throw jn(this).info(`[${u}] connection ${_?"timed out":"failed"} - error; no more retries left`),jn(this).debug(`[${u}] connection ${_?"timed out":"failed"} (error; no more retries left)`,Ur({retryOfRequestLogID:s,url:l,durationMs:S-p,message:b.message})),_?new Jm:new Uc({cause:b})}const x=[...b.headers.entries()].filter(([M])=>M==="x-request-id").map(([M,_])=>", "+M+": "+JSON.stringify(_)).join(""),k=`[${u}${m}${x}] ${i.method} ${l} ${b.ok?"succeeded":"failed"} with status ${b.status} in ${S-p}ms`;if(!b.ok){const M=await this.shouldRetry(b);if(n&&M){const F=`retrying, ${n} attempts remaining`;return await iT(b.body),jn(this).info(`${k} - ${F}`),jn(this).debug(`[${u}] response error (${F})`,Ur({retryOfRequestLogID:s,url:b.url,status:b.status,headers:b.headers,durationMs:S-p})),this.retryRequest(r,n,s??u,b.headers)}const _=M?"error; no more retries left":"error; not retryable";jn(this).info(`${k} - ${_}`);const C=await b.text().catch(F=>Bu(F).message),D=eT(C),A=D?void 0:C;throw jn(this).debug(`[${u}] response error (${_})`,Ur({retryOfRequestLogID:s,url:b.url,status:b.status,headers:b.headers,message:A,durationMs:Date.now()-p})),this.makeStatusError(b.status,D,A,b.headers)}return jn(this).info(k),jn(this).debug(`[${u}] response start`,Ur({retryOfRequestLogID:s,url:b.url,status:b.status,headers:b.headers,durationMs:S-p})),{response:b,options:r,controller:g,requestLogID:u,retryOfRequestLogID:s,startTime:p}}getAPIList(t,n,s){return this.requestAPIList(n,{method:"get",path:t,...s})}requestAPIList(t,n){const s=this.makeRequest(n,null,void 0);return new _T(this,s,t)}async fetchWithTimeout(t,n,s,r){const{signal:a,method:i,...l}=n||{};a&&a.addEventListener("abort",()=>r.abort());const c=setTimeout(()=>r.abort(),s),u=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,m={signal:r.signal,...u?{duplex:"half"}:{},method:"GET",...l};i&&(m.method=i.toUpperCase());try{return await this.fetch.call(void 0,t,m)}finally{clearTimeout(c)}}async shouldRetry(t){const n=t.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,n,s,r){let a;const i=r==null?void 0:r.get("retry-after-ms");if(i){const c=parseFloat(i);Number.isNaN(c)||(a=c)}const l=r==null?void 0:r.get("retry-after");if(l&&!a){const c=parseFloat(l);Number.isNaN(c)?a=Date.parse(l)-Date.now():a=c*1e3}if(!(a&&0<=a&&a<60*1e3)){const c=t.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(n,c)}return await Qi(a),this.makeRequest(t,n-1,s)}calculateDefaultRetryTimeoutMillis(t,n){const a=n-t,i=Math.min(.5*Math.pow(2,a),8),l=1-Math.random()*.25;return i*l*1e3}async buildRequest(t,{retryCount:n=0}={}){const s={...t},{method:r,path:a,query:i,defaultBaseURL:l}=s,c=this.buildURL(a,i,l);"timeout"in s&&Zk("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:u,body:m}=this.buildBody({options:s}),p=await this.buildHeaders({options:t,method:r,bodyHeaders:u,retryCount:n});return{req:{method:r,headers:p,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"},...m&&{body:m},...this.fetchOptions??{},...s.fetchOptions??{}},url:c,timeout:s.timeout}}async buildHeaders({options:t,method:n,bodyHeaders:s,retryCount:r}){let a={};this.idempotencyHeader&&n!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=t.idempotencyKey);const i=rt([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...oT(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(t),this._options.defaultHeaders,s,t.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:t,headers:n}}){if(!t)return{bodyHeaders:void 0,body:void 0};const s=rt([n]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&s.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:Sx(t)}:ie(this,ac,"f").call(this,{body:t,headers:s})}}yh=vt,ac=new WeakMap,Qu=new WeakSet,Rv=function(){return this.baseURL!=="https://api.openai.com/v1"};vt.OpenAI=yh;vt.DEFAULT_TIMEOUT=6e5;vt.OpenAIError=lt;vt.APIError=Pn;vt.APIConnectionError=Uc;vt.APIConnectionTimeoutError=Jm;vt.APIUserAbortError=gs;vt.NotFoundError=hx;vt.ConflictError=fx;vt.RateLimitError=gx;vt.BadRequestError=dx;vt.AuthenticationError=ux;vt.InternalServerError=yx;vt.PermissionDeniedError=mx;vt.UnprocessableEntityError=px;vt.InvalidWebhookSignatureError=fi;vt.toFile=PT;vt.Completions=uv;vt.Chat=rh;vt.Embeddings=hv;vt.Files=pv;vt.Images=Sv;vt.Audio=el;vt.Moderations=_v;vt.Models=wv;vt.FineTuning=Go;vt.Graders=hh;vt.VectorStores=Gc;vt.Webhooks=Ev;vt.Beta=tl;vt.Batches=ov;vt.Uploads=gh;vt.Responses=ph;vt.Evals=ch;vt.Containers=ih;let Ol=null,Hd=null;const tj=()=>{const e=Vo().trim().replace(/\/+$/,"");if(e.endsWith("/openai/v1"))return e;const t="/v1";return`${e.endsWith(t)?e.slice(0,-t.length):e}/openai/v1`},Av=()=>{const e=tj();return Ol?Hd!==e&&(Ol=new vt({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),Hd=e):(Ol=new vt({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),Hd=e),Ol};function Jc(e){const t=Ct(r=>r.providerConfig),n=G(Er(e??null));return f.useMemo(()=>{var c,u,m,p,g,b,S;const r=e?(c=n==null?void 0:n.config)==null?void 0:c.model_ref:void 0,a=(u=r==null?void 0:r.model)==null?void 0:u.trim();if(a)return a;const i=e?(p=(m=n==null?void 0:n.config)==null?void 0:m.model)==null?void 0:p.trim():void 0;return i&&i!=="unknown"?i:((S=(b=(g=t.defaults)==null?void 0:g.chat)==null?void 0:b.model)==null?void 0:S.trim())||void 0},[n,t,e])}function Iv(e){const t=Jc(e),n=Ct(s=>s.providerConfig);return f.useMemo(()=>{var r,a,i;return((i=(a=(r=n.defaults)==null?void 0:r.fast)==null?void 0:a.model)==null?void 0:i.trim())||t},[n,t])}function bh(e){const t=Ct(r=>r.isProviderModelRefEnabled),n=Ct(r=>r.selectedModelRef),s=Ct(r=>r.providerConfig.defaults);return f.useMemo(()=>{var r,a;return t()?e||n||((a=(r=s==null?void 0:s.chat)==null?void 0:r.model)!=null&&a.trim()?s.chat:null):null},[e,n,s,t])}function Ov(){const e=Ct(t=>t.getFastModelRef);return f.useMemo(()=>e(),[e])}const Kd="__BODHI_PROMPT_TITLE__",ic=e=>e.trim().toLowerCase(),nj=(e,t)=>{let n=e;for(const s of t){if(!n||typeof n!="object"||!(s in n))return;n=n[s]}return typeof n=="string"?n:void 0},Yd=e=>{const t=new Set,n=bs.options.resources;return!n||typeof n!="object"?[]:(Object.values(n).forEach(s=>{if(!s||typeof s!="object")return;const r="translation"in s&&s.translation&&typeof s.translation=="object"?s.translation:s,a=nj(r,e);if(!a)return;const i=ic(a);i&&t.add(i)}),Array.from(t))},sj=e=>{const t=new Set(["new session","new chat","main"]),n=new Set(["new session","new chat"]),s=[],r=i=>{const l=ic(i);l&&(t.add(l),n.add(l))},a=i=>{const l=ic(i);if(l){if(l.includes("{{prompt}}")){const[c,u]=l.split("{{prompt}}",2);s.push({prefix:c,suffix:u});return}if(l.includes(Kd.toLowerCase())){const[c,u]=l.split(Kd.toLowerCase(),2);s.push({prefix:c,suffix:u});return}n.add(l)}};return Yd(["chat","sidebar","newSession"]).forEach(r),Yd(["chat","session","defaultTitle"]).forEach(r),Yd(["chat","sidebar","newSessionWithPrompt"]).forEach(a),r(e("chat.sidebar.newSession")),r(e("chat.session.defaultTitle")),a(e("chat.sidebar.newSessionWithPrompt",{prompt:Kd})),i=>{if(!i)return!0;const l=ic(i);if(!l||t.has(l))return!0;for(const c of n)if(c&&(l.startsWith(`${c} -`)||l.startsWith(`${c}-`)||l.startsWith(`${c}:`)||l.startsWith(`${c}:`)))return!0;for(const{prefix:c,suffix:u}of s){if(!l.startsWith(c)||!l.endsWith(u))continue;if(l.slice(c.length,l.length-u.length).trim().length>0)return!0}return!1}},xh=e=>{var t,n,s,r,a,i;if("content"in e&&typeof e.content=="string"){const l=e.content.trim();if(l)return l}if("displayText"in e&&typeof e.displayText=="string"){const l=e.displayText.trim();if(l)return l}if(e.role==="assistant"&&"type"in e){if(e.type==="tool_result"&&"result"in e){const l=(t=e.result)==null?void 0:t.result;if(typeof l=="string"&&l.trim())return l.trim()}if(e.type==="task_list"&&"taskList"in e){const l=((s=(n=e.taskList)==null?void 0:n.title)==null?void 0:s.trim())||"",c=(a=(r=e.taskList)==null?void 0:r.items)==null?void 0:a.find(p=>{var g;return(g=p==null?void 0:p.description)==null?void 0:g.trim()}),u=((i=c==null?void 0:c.description)==null?void 0:i.trim())||"",m=[l,u].filter(Boolean).join(" - ");if(m)return m}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""},fp=e=>e.filter(t=>t.role!=="user"&&t.role!=="assistant"?!1:xh(t).length>0);function vh(e){const{message:t}=en.useApp(),{t:n}=Ae(),s=G(k=>k.autoGenerateTitles),r=Iv(),a=Ov(),i=Jc(),l=G(k=>k.setAutoGenerateTitlesPreference),c=G(k=>k.isUpdatingAutoTitlePreference),u=f.useRef(new Set),m=f.useRef(new Set),[p,g]=f.useState({}),b=f.useMemo(()=>sj((k,j)=>n(k,j)),[n]),S=f.useCallback(k=>b(k),[b]),x=f.useCallback(async(k,j)=>{var D,A;let w=e.chats.find(B=>B.id===k);if(!w)return!1;let M=fp(w.messages);if(j!=null&&j.force&&M.length===0){await G.getState().loadChatHistory(k,{mode:"replace"});const B=G.getState().chats.find(F=>F.id===k);B&&(w=B,M=fp(B.messages))}const _=!(j!=null&&j.force);if(_&&!s||_&&(m.current.has(k)||u.current.has(k)||!S(w.title)||M.length===0||M.length>6))return!1;m.current.add(k),g(B=>({...B,[k]:{status:"loading"}}));try{const B=(a==null?void 0:a.model)??r,F=(B==null?void 0:B.trim())||"",O=(i==null?void 0:i.trim())||"";let R,I="";if(F)try{I=await gp(M,F)}catch(L){R=L}if(!I&&O&&O!==F)try{I=await gp(M,O)}catch(L){R||(R=L)}if(I||(I=ij(M)),!I){if(_)return g(L=>({...L,[k]:{status:"idle"}})),!1;throw R instanceof Error?R:new Error(n("chat.title.generateFailed"))}return await e.persistSessionTitle(k,I),(!_||I.toLowerCase()!=="new chat")&&u.current.add(k),g(L=>({...L,[k]:{status:"idle"}})),j!=null&&j.force&&((D=t==null?void 0:t.success)==null||D.call(t,n("chat.title.updated"))),!0}catch(B){const F=B instanceof Error?B.message:n("chat.title.generateFailed");throw g(O=>({...O,[k]:{status:"error",error:F}})),j!=null&&j.force?(A=t==null?void 0:t.error)==null||A.call(t,F):console.warn("[ChatTitleGeneration] Auto title generation failed:",F),B instanceof Error?B:new Error(F)}finally{m.current.delete(k)}},[t,s,S,r,a,i,e,n]);return{titleGenerationState:p,autoGenerateTitles:s,isUpdatingAutoTitlePreference:c,generateChatTitle:x,setAutoGenerateTitlesPreference:l,isDefaultTitle:S}}const Zu=60,rj=20,oj=8,pp=220,aj=e=>e.slice(0,oj).map(s=>{const r=s.role==="user"?"User":"Assistant",a=xh(s);if(!a)return"";const i=a.length>pp?`${a.slice(0,pp-3)}...`:a;return`${r}: ${i}`}).filter(s=>s.length>0).join(`
37
+ `),ij=e=>{const t=[...e.filter(n=>n.role==="user"),...e.filter(n=>n.role!=="user")];for(const n of t){const s=xh(n).replace(/\s+/g," ").trim();if(!s)continue;const r=$v(s);if(r)return r}return""},$v=e=>{var s;const n=(((s=e.split(/\r?\n/)[0])==null?void 0:s.trim())??"").replace(/^["']+|["']+$/g,"");return n.length<=Zu?n:`${n.slice(0,Zu-3)}...`},lj=e=>{if(!e||typeof e!="object")return"";const t=e,n=t.content;return typeof n=="string"?n:Array.isArray(n)?n.map(r=>{if(typeof r=="string")return r;if(!r||typeof r!="object")return"";const a=r;if(typeof a.text=="string")return a.text;if(a.text&&typeof a.text=="object"){const i=a.text;if(typeof i.value=="string")return i.value}return typeof a.content=="string"?a.content:""}).filter(r=>r.trim().length>0).join(`
38
+ `):typeof t.refusal=="string"?t.refusal:""},gp=async(e,t)=>{var l,c;const n=aj(e);if(!n)return"";const s=t==null?void 0:t.trim();if(!s)throw new Error("No model configured. Please select a default model in Provider Settings.");const a=await Av().chat.completions.create({model:s,temperature:.2,max_tokens:rj,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 ${Zu} characters) for this chat:
39
+
40
+ ${n}`}]}),i=lj((c=(l=a.choices)==null?void 0:l[0])==null?void 0:c.message).trim();return $v(i)},$l={THEME:"copilot_ui_theme_v1",LAYOUT:"copilot_ui_layout_v1"};class cj{getTheme(){try{return localStorage.getItem($l.THEME)}catch(t){return console.error("Failed to get theme:",t),null}}setTheme(t){try{localStorage.setItem($l.THEME,t)}catch(n){console.error("Failed to set theme:",n)}}getLayout(){try{return localStorage.getItem($l.LAYOUT)}catch(t){return console.error("Failed to get layout:",t),null}}setLayout(t){try{localStorage.setItem($l.LAYOUT,t)}catch(n){console.error("Failed to set layout:",n)}}getStorageStats(){let t=0;for(let n=0;n<localStorage.length;n++){const s=localStorage.key(n);if(s&&s.startsWith("copilot_ui_")){const r=localStorage.getItem(s);t+=(s.length+((r==null?void 0:r.length)||0))*2}}return{estimatedSize:`${(t/1024).toFixed(1)} KB`}}}const Dv=new cj,Sh={collapsed:!1,widthPx:260,collapsedWidthPx:72,minWidthPx:180,maxWidthPx:520},Lv={v:2,sidebar:Sh,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:null},splitSizesPx:{}},yp=e=>{const t=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return`${e}-${t}`},rs=e=>e.type==="leaf"?[e.id]:[...rs(e.children[0]),...rs(e.children[1])],zi=e=>e.type==="leaf"?[]:[e.id,...zi(e.children[0]),...zi(e.children[1])],dj=(e,t)=>{for(const[n,s]of Object.entries(e))if(s===t)return n;return null},uj=(e,t)=>{const n={},s=new Set;return e.forEach(r=>{const a=t[r]??null;if(!a||s.has(a)){n[r]=null;return}s.add(a),n[r]=a}),n},em=(e,t,n,s,r)=>e.type==="leaf"?e.id!==t?e:{type:"split",id:s,layout:n,children:[e,{type:"leaf",id:r}]}:{...e,children:[em(e.children[0],t,n,s,r),em(e.children[1],t,n,s,r)]},tm=(e,t)=>{if(e.type==="leaf")return e.id===t?{node:null,removed:!0}:{node:e,removed:!1};const n=tm(e.children[0],t);if(n.removed)return n.node?{node:{...e,children:[n.node,e.children[1]]},removed:!0}:{node:e.children[1],removed:!0};const s=tm(e.children[1],t);return s.removed?s.node?{node:{...e,children:[e.children[0],s.node]},removed:!0}:{node:e.children[0],removed:!0}:{node:e,removed:!1}},mj=e=>({v:2,sidebar:e.sidebar,tree:e.tree,activeLeafId:e.activeLeafId,leafSessionIds:e.leafSessionIds,splitSizesPx:e.splitSizesPx}),hj=e=>{try{Dv.setLayout(JSON.stringify(e))}catch(t){console.warn("[uiLayoutStore] Failed to persist layout:",t)}},Qs=e=>{const t=mj(e);return hj(t),t},fj=e=>{var g,b,S,x,k,j,w,M,_,C,D;const t={...Sh,...e.sidebar||{}},n=((g=e.view)==null?void 0:g.mode)??"single",s=((b=e.view)==null?void 0:b.twoDirection)??"horizontal",r={...((S=e.panes)==null?void 0:S.sessionIds)||{}},a=((x=e.panes)==null?void 0:x.activePaneId)??"lt",i={};if(n==="single")return{v:2,sidebar:t,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:r.lt??null},splitSizesPx:{}};if(n==="two"){const A="split-root",B=s,F=B==="horizontal"?{type:"split",id:A,layout:B,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"rt"}]}:{type:"split",id:A,layout:B,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},O=B==="horizontal"?((k=e.split)==null?void 0:k.twoHorizontalPx)||((j=e.split)==null?void 0:j.columnsPx)||null:((w=e.split)==null?void 0:w.twoVerticalPx)||((M=e.split)==null?void 0:M.leftRowsPx)||null;O&&(i[A]=O);const R=rs(F);return{v:2,sidebar:t,tree:F,activeLeafId:R.includes(a)?a:R[0],leafSessionIds:Object.fromEntries(R.map(I=>[I,r[I]??null])),splitSizesPx:i}}const l="split-root",c="split-left",u="split-right",m={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),(C=e.split)!=null&&C.leftRowsPx&&(i[c]=e.split.leftRowsPx),(D=e.split)!=null&&D.rightRowsPx&&(i[u]=e.split.rightRowsPx);const p=rs(m);return{v:2,sidebar:t,tree:m,activeLeafId:p.includes(a)?a:p[0],leafSessionIds:Object.fromEntries(p.map(A=>[A,r[A]??null])),splitSizesPx:i}},pj=e=>{if(!e)return null;try{const t=JSON.parse(e);if(!t||typeof t!="object")return null;if(t.v===2){const n={...Sh,...t.sidebar||{}},s=t.tree||Lv.tree,r=rs(s),a=zi(s),i={};r.forEach(m=>{var p;i[m]=typeof((p=t.leafSessionIds)==null?void 0:p[m])=="string"?t.leafSessionIds[m]:null});const l={};a.forEach(m=>{var g;const p=(g=t.splitSizesPx)==null?void 0:g[m];Array.isArray(p)&&p.length>=2&&(l[m]=[Number(p[0]),Number(p[1])])});const c=typeof t.activeLeafId=="string"&&r.includes(t.activeLeafId)?t.activeLeafId:r[0],u=uj(r,i);return{v:2,sidebar:n,tree:s,activeLeafId:c,leafSessionIds:u,splitSizesPx:l}}return t.v===1?fj(t):null}catch{return null}},gj=()=>pj(Dv.getLayout())??Lv,wt=Pr(e=>({...gj(),setSidebarCollapsed:t=>{e(n=>n.sidebar.collapsed===t?n:Qs({sidebar:{...n.sidebar,collapsed:t},tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx}))},setSidebarWidthPx:t=>{e(n=>{const s=Math.max(n.sidebar.minWidthPx,Math.min(n.sidebar.maxWidthPx,t));return n.sidebar.widthPx===s?n:Qs({sidebar:{...n.sidebar,widthPx:s},tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})})},setActiveLeafId:t=>{e(n=>n.activeLeafId===t||!rs(n.tree).includes(t)?n:(ps("setActiveLeafId",{from:n.activeLeafId,to:t}),Qs({sidebar:n.sidebar,tree:n.tree,activeLeafId:t,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})))},setLeafSessionId:(t,n)=>{e(s=>{const r=rs(s.tree);if(!r.includes(t)||(s.leafSessionIds[t]??null)===n)return s;const a=[];ps("setLeafSessionId",{leafId:t,fromSessionId:s.leafSessionIds[t]??null,toSessionId:n,mode:"unique_session_per_leaf"});const i={...s.leafSessionIds,[t]:n};if(n)for(const l of r)l!==t&&i[l]===n&&(i[l]=null,a.push(l));return a.length>0&&ps("setLeafSessionId dedupe",{sessionId:n,clearedLeafIds:a,assignedLeafId:t}),r.forEach(l=>{l in i||(i[l]=null)}),Qs({sidebar:s.sidebar,tree:s.tree,activeLeafId:s.activeLeafId,leafSessionIds:i,splitSizesPx:s.splitSizesPx})})},clearSessionFromAllLeaves:t=>{e(n=>{const s={...n.leafSessionIds};let r=!1;for(const[a,i]of Object.entries(s))i===t&&(s[a]=null,r=!0);return r?Qs({sidebar:n.sidebar,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:s,splitSizesPx:n.splitSizesPx}):n})},splitLeaf:(t,n)=>{e(s=>{const r=rs(s.tree);if(!r.includes(t)||r.length>=4)return s;const a=yp("split"),i=yp("pane"),l=em(s.tree,t,n,a,i),c={...s.leafSessionIds,[i]:null};return Qs({sidebar:s.sidebar,tree:l,activeLeafId:i,leafSessionIds:c,splitSizesPx:s.splitSizesPx})})},closeLeaf:t=>{e(n=>{const s=rs(n.tree);if(!s.includes(t)||s.length<=1)return n;const r=tm(n.tree,t);if(!r.removed||!r.node)return n;const a=r.node,i=rs(a),l=zi(a),c={};i.forEach(p=>{c[p]=n.leafSessionIds[p]??null});const u={};l.forEach(p=>{const g=n.splitSizesPx[p];g&&(u[p]=g)});const m=n.activeLeafId===t?i[0]:i.includes(n.activeLeafId)?n.activeLeafId:i[0];return Qs({sidebar:n.sidebar,tree:a,activeLeafId:m,leafSessionIds:c,splitSizesPx:u})})},setSplitSizesPx:(t,n)=>{e(s=>{const r=s.splitSizesPx[t];return r&&r[0]===n[0]&&r[1]===n[1]?s:Qs({sidebar:s.sidebar,tree:s.tree,activeLeafId:s.activeLeafId,leafSessionIds:s.leafSessionIds,splitSizesPx:{...s.splitSizesPx,[t]:n}})})},pruneSplitSizes:()=>{e(t=>{const n=new Set(zi(t.tree)),s={};for(const[i,l]of Object.entries(t.splitSizesPx))n.has(i)&&(s[i]=l);const r=Object.keys(t.splitSizesPx),a=Object.keys(s);return r.length===a.length&&r.every(i=>i in s)?t:Qs({sidebar:t.sidebar,tree:t.tree,activeLeafId:t.activeLeafId,leafSessionIds:t.leafSessionIds,splitSizesPx:s})})}})),yj=async(e,t)=>{var i;const n=G.getState(),s=!n.chats.some(l=>l.id===e);if(t!=null&&t.forceRefreshIndex||s)try{await n.refreshChats()}catch(l){console.warn("[openSession] refreshChats failed:",l)}const r=G.getState().chats.find(l=>l.id===e);if(!r)return;if(t!=null&&t.forceLoadHistory||s||(((i=r.messages)==null?void 0:i.length)||0)===0&&(r.messageCount||0)>0)try{await n.loadChatHistory(e)}catch(l){console.warn("[openSession] loadChatHistory failed:",l)}if(t!=null&&t.forceSubscribe){n.markForceSubscribe(e);return}((t==null?void 0:t.subscribeIfRunning)??!0)&&r.isRunning&&n.markForceSubscribe(e)},Qc=(e,t)=>{const{activeLeafId:n,leafSessionIds:s,setLeafSessionId:r,setActiveLeafId:a}=wt.getState(),i=dj(s,e),l=s[n]??null;ps("openSession (input)",{activeLeafId:n,activeLeafSessionId:l,sessionId:e,existingLeafId:i}),i?i===n?ps("openSession (decision)",{action:"noop_already_active",leafId:n,sessionId:e}):(a(i),ps("openSession (decision)",{action:"focus_existing_leaf",leafId:i,sessionId:e})):(r(n,e),ps("openSession (decision)",{action:"assign_to_active_leaf",leafId:n,sessionId:e})),G.getState().selectSession(e),yj(e,t)},Vd=(e,t)=>{if(!t)return!0;const n=[e.title,e.id,e.kind||"root",e.config.workspacePath||"",e.config.systemPromptId||"",e.updatedAt||"",e.createdByScheduleId||"",e.lastRunStatus||"",e.lastRunError||"",...e.messages.filter(r=>r.role==="user"&&"content"in r).slice(0,3).map(r=>"content"in r?r.content:"")].join(" ").toLowerCase();return t.split(/\s+/).filter(Boolean).every(r=>n.includes(r))},Xd=(e,t,n)=>{switch(t){case"pinned":return!!e.pinned;case"running":return n(e.id);case"child":return e.kind==="child";case"all":default:return!0}},bj=()=>{const{t:e}=Ae(),{message:t}=en.useApp(),n=G(ae=>ae.chats),s=G(ae=>ae.currentSessionId),r=G(ae=>ae.deleteSession),a=G(ae=>ae.deleteSessions),i=G(ae=>ae.pinSession),l=G(ae=>ae.unpinSession),c=G(ae=>ae.updateSession),u=G(ae=>ae.persistSessionTitle),m=G(ae=>ae.addChat),p=G(ae=>ae.refreshChats),g=G(ae=>ae.lastSelectedPromptId),b=G(ae=>ae.systemPrompts),S=f.useCallback(ae=>ur(ae)(G.getState()),[]),x=wt(ae=>ae.sidebar.collapsed),k=wt(ae=>ae.setSidebarCollapsed),j=wt(ae=>ae.clearSessionFromAllLeaves),{generateChatTitle:w,titleGenerationState:M}=vh({chats:n,updateSession:c,persistSessionTitle:u}),_=f.useCallback(async(ae,ke)=>{var xt,Ft;const pe=b.find(Dt=>Dt.id===g),Re=(pe==null?void 0:pe.id)||(b.length>0?((xt=b.find(Dt=>Dt.id==="general_assistant"))==null?void 0:xt.id)||b[0].id:""),Je={title:ae||e("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:Re,baseSystemPrompt:(pe==null?void 0:pe.content)||(b.length>0?((Ft=b.find(Dt=>Dt.id==="general_assistant"))==null?void 0:Ft.content)||b[0].content:""),lastUsedEnhancedPrompt:null},...ke},gt=await m(Je),{activeLeafId:Mt}=wt.getState();wt.getState().setLeafSessionId(Mt,gt),wt.getState().setActiveLeafId(Mt)},[m,g,b,e]),[C,D]=f.useState(!1),[A,B]=f.useState(new Set(["Today"])),[F,O]=f.useState(""),[R,I]=f.useState("all"),[L,U]=f.useState({}),q=G(Er(s)),H=f.useMemo(()=>q?Ff(q):null,[q]),P=f.useMemo(()=>{const ae=new Set(A);return H&&ae.add(H),Array.from(ae)},[H,A]),W=ae=>{const ke=new Set(Array.isArray(ae)?ae:[ae]);B(pe=>{if(pe.size!==ke.size)return ke;for(const Re of ke)if(!pe.has(Re))return ke;return pe})},ne=F.trim().toLowerCase(),K=ne.length>0||R!=="all",xe=f.useMemo(()=>n.filter(ae=>ae.kind!=="child"),[n]),se=f.useMemo(()=>{const ae={};for(const ke of n){if(ke.kind!=="child")continue;const pe=ke.parentSessionId||ke.rootSessionId;pe&&(ae[pe]||(ae[pe]=[]),ae[pe].push(ke))}return Object.keys(ae).forEach(ke=>{ae[ke].sort((pe,Re)=>{if(pe.pinned!==Re.pinned)return pe.pinned?-1:1;const Je=Date.parse(pe.updatedAt||"")||pe.createdAt||0;return(Date.parse(Re.updatedAt||"")||Re.createdAt||0)-Je})}),ae},[n]),fe=f.useMemo(()=>K?xe.filter(ae=>Vd(ae,ne)&&Xd(ae,R,S)?!0:(se[ae.id]||[]).some(Re=>Vd(Re,ne)&&Xd(Re,R,S))):xe,[se,K,S,ne,xe,R]),Se=f.useMemo(()=>{if(!K)return se;const ae={};for(const ke of fe){const pe=se[ke.id]||[];ae[ke.id]=pe.filter(Re=>Vd(Re,ne)&&Xd(Re,R,S))}return ae},[se,fe,K,S,ne,R]),me=Fk(fe),ze=Nk(me),st=f.useCallback(ae=>{i(ae),B(ke=>{if(ke.has("Pinned"))return ke;const pe=new Set(ke);return pe.add("Pinned"),pe})},[i]),pt=f.useCallback(ae=>{const ke=n.find(Re=>Re.id===ae),pe=ke?Ff({...ke,pinned:!1}):null;l(ae),pe&&B(Re=>{if(Re.has(pe))return Re;const Je=new Set(Re);return Je.add(pe),Je})},[n,l]),Kt=ae=>{Xn.confirm({title:e("chat.sidebar.delete.title"),content:e("chat.sidebar.delete.confirm"),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{j(ae),r(ae)}})},Oe=rr(ae=>ae.open),Wt=()=>{Oe("chat")},Xe=f.useCallback(ae=>{O(ae)},[]),_e=f.useCallback(ae=>{I(ae)},[]),Ye=(ae,ke)=>{c(ae,{title:ke})},ot=async ae=>{try{await w(ae,{force:!0})}catch(ke){console.error("Failed to generate title:",ke)}},Lt=f.useCallback(async ae=>{var pe;if(((pe=L[ae])==null?void 0:pe.status)==="loading")return;U(Re=>({...Re,[ae]:{status:"loading"}}));const ke=t.loading(e("chat.actions.runProjectDreamRunning"),0);try{const Re=await os.getInstance().runProjectDream(ae);ke(),Re.dream_generated?t.success(e("chat.actions.runProjectDreamSuccess")):t.info(Re.message||e("chat.actions.runProjectDreamNoChange"));try{await p()}catch(Je){console.warn("Failed to refresh chats after project dream run:",Je)}}catch(Re){ke();const Je=Re instanceof Error&&Re.message?Re.message:e("chat.actions.runProjectDreamFailed");t.error(Je),console.error("Failed to run project dream:",Re)}finally{U(Re=>({...Re,[ae]:{status:"idle"}}))}},[t,L,p,e]),N=ae=>{const ke=zk(me,ae),pe=lx(me,ae);Xn.confirm({title:e("chat.sidebar.deleteByDate.title",{date:ae}),content:e("chat.sidebar.deleteByDate.confirm",{count:pe,date:ae}),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{ke.forEach(Re=>j(Re)),a(ke)}})},le=()=>{D(!0)},be=()=>{D(!1)},De=async ae=>{try{await _(e("chat.sidebar.newSessionWithPrompt",{prompt:ae.name}),{config:{systemPromptId:ae.id,baseSystemPrompt:ae.content,lastUsedEnhancedPrompt:null}}),D(!1)}catch(ke){console.error("Failed to create chat:",ke),Xn.error({title:e("chat.sidebar.createFailedTitle"),content:ke instanceof Error?ke.message:e("chat.sidebar.createFailedUnknown")})}},Le=f.useCallback(ae=>Qc(ae),[]),[ue,ye]=f.useState(new Set),qe=f.useMemo(()=>{var pe;const ae=new Set(ue),ke=n.find(Re=>Re.id===s);if(ke){const Re=ke.kind==="child"?ke.parentSessionId||ke.rootSessionId:ke.id;Re&&ae.add(Re)}for(const Re of n)if(Re.kind==="child"&&Re.pinned){const Je=Re.parentSessionId||Re.rootSessionId;Je&&ae.add(Je)}if(K)for(const Re of fe)(((pe=Se[Re.id])==null?void 0:pe.length)??0)>0&&ae.add(Re.id);return ae},[n,Se,s,ue,fe,K]),He=f.useCallback(ae=>{ye(ke=>{const pe=new Set(ke);return pe.has(ae)?pe.delete(ae):pe.add(ae),pe})},[]);return{chats:fe,childrenByRoot:Se,expandedRootIds:qe,toggleRootExpanded:He,collapsed:x,currentSessionId:s,expandedKeys:P,groupedChatsByDate:me,hasActiveFilters:K,handleCollapseChange:W,handleDelete:Kt,handleDeleteByDate:N,handleEditTitle:Ye,handleGenerateTitle:ot,handleNewChat:le,handleNewChatSelectorClose:be,handleOpenSettings:Wt,handleRunProjectDream:Lt,handleSearchQueryChange:Xe,handleStatusFilterChange:_e,handleSystemPromptSelect:De,isNewChatSelectorOpen:C,pinSession:st,projectDreamState:L,searchQuery:F,selectSession:Le,setCollapsed:k,sortedDateKeys:ze,statusFilter:R,systemPrompts:b,titleGenerationState:M,unpinSession:pt}},{useBreakpoint:xj}=zc,{useToken:vj}=Qe,bp=()=>{const{token:e}=vj(),{t}=Ae(),n=xj(),{childrenByRoot:s,expandedRootIds:r,toggleRootExpanded:a,collapsed:i,currentSessionId:l,expandedKeys:c,groupedChatsByDate:u,handleCollapseChange:m,handleDelete:p,handleDeleteByDate:g,handleEditTitle:b,handleGenerateTitle:S,handleNewChat:x,handleNewChatSelectorClose:k,handleOpenSettings:j,handleRunProjectDream:w,handleSearchQueryChange:M,handleStatusFilterChange:_,handleSystemPromptSelect:C,hasActiveFilters:D,isNewChatSelectorOpen:A,pinSession:B,projectDreamState:F,searchQuery:O,selectSession:R,setCollapsed:I,sortedDateKeys:L,statusFilter:U,systemPrompts:q,titleGenerationState:H,unpinSession:P}=bj(),{xs:W,sm:ne}=n;return f.useEffect(()=>{typeof W!="boolean"||typeof ne!="boolean"||W===!1&&ne===!1&&I(!0)},[ne,W,I]),i?null:o.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:[o.jsx(ve,{justify:"flex-end",style:{flexShrink:0,padding:"10px 12px 2px 12px",minHeight:40},children:o.jsx(de,{type:"text",icon:o.jsx(_b,{}),onClick:()=>I(!0),size:n.xs?"small":"middle",className:"lotus-toolbar-icon","aria-label":t("chat.sidebar.collapse","Collapse sidebar")})}),o.jsxs(ve,{vertical:!0,gap:"small",style:{flexShrink:0,padding:"10px 12px 8px 12px"},children:[o.jsx(et,{allowClear:!0,value:O,onChange:K=>M(K.target.value),prefix:o.jsx($i,{style:{color:e.colorTextTertiary}}),placeholder:t("chat.sidebar.searchPlaceholder","Search sessions"),"aria-label":t("chat.sidebar.searchPlaceholder","Search sessions"),size:n.xs?"middle":"large",style:{borderRadius:e.borderRadiusLG}}),o.jsx(Jw,{block:!0,size:n.xs?"middle":"small",value:U,onChange:K=>_(K),options:[{label:t("chat.sidebar.filters.all","All"),value:"all"},{label:t("chat.sidebar.filters.pinned","Pinned"),value:"pinned"},{label:t("chat.sidebar.filters.running","Running"),value:"running"},{label:t("chat.sidebar.filters.child","Child"),value:"child"}]})]}),o.jsx(ve,{vertical:!0,role:"list","aria-label":t("chat.sidebar.chatList","Chat list"),style:{flex:1,minHeight:0,overflowY:"auto",padding:"0 12px 0 12px"},children:o.jsx(Bk,{groupedChatsByDate:u,childrenByRoot:s,expandedRootIds:r,onToggleRootExpanded:a,sortedDateKeys:L,expandedKeys:c,onCollapseChange:m,currentSessionId:l,onSelectChat:R,onDeleteChat:p,onDeleteByDate:g,onPinChat:B,onUnpinChat:P,onEditTitle:b,onGenerateTitle:S,onRunProjectDream:w,titleGenerationState:H,projectDreamState:F,token:e,hasActiveFilters:D})}),o.jsx(Yk,{collapsed:!1,onNewChat:x,onOpenSettings:j,screens:n,token:e}),o.jsx($k,{open:A,onClose:k,onSelect:C,prompts:q,title:t("chat.prompt.newSessionSelectorTitle"),showCancelButton:!0})]})},xp=e=>Symbol.iterator in e,vp=e=>"entries"in e,Sp=(e,t)=>{const n=e instanceof Map?e:new Map(e.entries()),s=t instanceof Map?t:new Map(t.entries());if(n.size!==s.size)return!1;for(const[r,a]of n)if(!Object.is(a,s.get(r)))return!1;return!0},Sj=(e,t)=>{const n=e[Symbol.iterator](),s=t[Symbol.iterator]();let r=n.next(),a=s.next();for(;!r.done&&!a.done;){if(!Object.is(r.value,a.value))return!1;r=n.next(),a=s.next()}return!!r.done&&!!a.done};function wj(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:xp(e)&&xp(t)?vp(e)&&vp(t)?Sp(e,t):Sj(e,t):Sp({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function _j(e){const t=pn.useRef(void 0);return n=>{const s=e(n);return wj(t.current,s)?t.current:t.current=s}}function kj(){const{chats:e,currentSessionId:t,currentChat:n,addMessage:s,selectSession:r,deleteSession:a,deleteSessions:i,deleteMessage:l,updateSession:c,persistSessionTitle:u,pinSession:m,unpinSession:p,loadChats:g}=G(_j(w=>({chats:w.chats,currentSessionId:w.currentSessionId,currentChat:Xm(w),addMessage:w.addMessage,selectSession:w.selectSession,deleteSession:w.deleteSession,deleteSessions:w.deleteSessions,deleteMessage:w.deleteMessage,updateSession:w.updateSession,persistSessionTitle:w.persistSessionTitle,pinSession:w.pinSession,unpinSession:w.unpinSession,loadChats:w.loadChats}))),b=G(ur(t)),S=f.useMemo(()=>(n==null?void 0:n.messages)||[],[n]),x=f.useMemo(()=>e.filter(w=>w.pinned),[e]),k=f.useMemo(()=>e.filter(w=>!w.pinned),[e]),j=e.length;return{chats:e,currentSessionId:t,currentChat:n,isProcessing:b,baseMessages:S,pinnedChats:x,unpinnedChats:k,chatCount:j,addMessage:s,deleteMessage:l,selectSession:r,deleteSession:a,deleteSessions:i,pinSession:m,unpinSession:p,updateSession:c,persistSessionTitle:u,loadChats:g}}function Tj(e){const t=G(g=>g.addChat),n=G(g=>g.lastSelectedPromptId),s=G(g=>g.systemPrompts),r=os.getInstance(),a=f.useCallback(async(g,b)=>{var j,w;const S=s.find(M=>M.id===n),x=(S==null?void 0:S.id)||(s.length>0?((j=s.find(M=>M.id==="general_assistant"))==null?void 0:j.id)||s[0].id:""),k={title:g||"New Session",createdAt:Date.now(),messages:[],config:{systemPromptId:x,baseSystemPrompt:(S==null?void 0:S.content)||(s.length>0?((w=s.find(M=>M.id==="general_assistant"))==null?void 0:w.content)||s[0].content:""),lastUsedEnhancedPrompt:null,...Ct.getState().isProviderModelRefEnabled()?{model_ref:Ct.getState().selectedModelRef}:{}},...b};await t(k)},[t,n,s]),i=f.useCallback(async g=>{Jt("[ChatOps]","[useChatOperations] createChatWithSystemPrompt started with prompt:",g);const b={title:`New Session - ${g.name}`,createdAt:Date.now(),messages:[],config:{systemPromptId:g.id,baseSystemPrompt:g.content,lastUsedEnhancedPrompt:null}};Jt("[ChatOps]","[useChatOperations] Calling addChat with newChatData.config:",b.config),await t(b)},[t]),l=f.useCallback(g=>{const b=e.chats.find(S=>S.id===g);b&&(b.pinned?e.unpinSession(g):e.pinSession(g))},[e]),c=f.useCallback((g,b)=>{e.updateSession(g,{title:b})},[e]),u=f.useCallback(async()=>{await r.cleanupSessions("empty",!0),await G.getState().loadChats()},[r]),m=f.useCallback(async()=>{await r.cleanupSessions("all",!0),await G.getState().loadChats()},[r]),p=f.useCallback(async()=>{await r.cleanupSessions("all",!1),await G.getState().loadChats()},[r]);return{createNewChat:a,createChatWithSystemPrompt:i,toggleChatPin:l,updateChatTitle:c,deleteEmptyChats:u,deleteAllUnpinnedChats:m,deleteAllChats:p}}const _i=new Map,lc=new Set,To=new Map,Ri=new Map;let ki=null;const Fv=(e,t)=>{const n=_i.get(e);n&&n.forEach(s=>s(t))},wp=()=>{if(ki=null,Ri.size===0)return;const e=Array.from(Ri.values());Ri.clear(),e.forEach(t=>{Fv(t.messageId,t.content),lc.forEach(n=>n(t))})},It={getLatest(e){return To.get(e)??null},subscribeMessage(e,t){let n=_i.get(e);return n||(n=new Set,_i.set(e,n)),n.add(t),To.has(e)&&t(To.get(e)??null),()=>{const s=_i.get(e);s&&(s.delete(t),s.size===0&&_i.delete(e))}},subscribe(e){return lc.add(e),()=>{lc.delete(e)}},publish(e){e.content===null?To.delete(e.messageId):To.set(e.messageId,e.content),Ri.set(e.messageId,e),ki===null&&(ki=requestAnimationFrame(wp))},clear(e,t){To.delete(t),Ri.delete(t),Fv(t,null),lc.forEach(n=>n({sessionId:e,messageId:t,content:null}))},forceFlush(){ki!==null&&(cancelAnimationFrame(ki),wp())}},Nv="mermaid_enhancement_enabled",nm=()=>localStorage.getItem(Nv)!=="false",jj=e=>{localStorage.setItem(Nv,e.toString())},Cj=()=>`
41
+
42
+ ## 📊 Visual Representation Guidelines
43
+
44
+ When explaining concepts, processes, relationships, or data structures, use Mermaid diagrams to enhance understanding. Choose appropriate diagram types:
45
+
46
+ - **Flowcharts** (graph TD/LR) - processes, workflows, decision trees
47
+ - **Sequence Diagrams** - API interactions, communication flows
48
+ - **Class Diagrams** - object relationships, data models
49
+ - **State Diagrams** - state machines, status flows
50
+ - **Gantt Charts** - project timelines
51
+ - **ER Diagrams** - database schemas
52
+ - **Git Graphs** - version control workflows
53
+
54
+ **Syntax Notes:**
55
+ - Mermaid diagram definitions MUST be inside a fenced code block (never inline). Example:
56
+ \`\`\`mermaid
57
+ graph TD
58
+ A --> B
59
+ \`\`\`
60
+ - Avoid nested brackets: use \`A[Text]\` or \`A(Text)\`, NOT \`A[Text()]\`
61
+ - Use HTML entities for special chars: &#35; for #, &#59; for ;, &#34; for quotes
62
+ - Keep participant names simple (no spaces): \`participant UserService\`
63
+ - Arrow syntax: \`-->\` (solid), \`-.->\` (dotted), \`==>\` (thick), \`-->|label|\` (labeled)
64
+
65
+ Include relevant diagrams when discussing architecture, workflows, data flow, or relationships.`,sm="task_enhancement_enabled",_p="todo_enhancement_enabled",Mj=e=>e==="false",rm=()=>{let e=localStorage.getItem(sm);if(e===null){const t=localStorage.getItem(_p);t!==null&&(e=t,localStorage.setItem(sm,t),localStorage.removeItem(_p))}return!Mj(e)},Pj=e=>{localStorage.setItem(sm,e.toString())},Ej=()=>`
66
+
67
+ ## Task Management Rules
68
+
69
+ Use the Task tool for non-trivial or multi-step tasks.
70
+ Task updates are shared across the current root session and all child sessions.
71
+ Keep exactly one item in \`in_progress\` state whenever possible.
72
+ Update Task immediately when a step starts or completes; do not batch status updates.
73
+ When marking a task as completed, always fill in the \`summary\` field with a concise description of what was accomplished.
74
+ Do not use Markdown checkbox lists as a substitute for Task.
75
+ Skip Task only for simple one-step requests.
76
+ Use SubSession only when the user explicitly requests delegated/parallel sub-session work.
77
+ `,zv=()=>{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"},Rj=e=>{switch(e){case"windows":return"Windows";case"macos":return"macOS";case"linux":return"Linux";default:return"Unknown OS"}},Aj=()=>{const e=zv(),n=`## 🖥️ Operating System Information
78
+
79
+ You are running on **${Rj(e)}**.`;return e==="windows"?n+`
80
+
81
+ ### Windows-Specific Notes:
82
+
83
+ - **Configuration Directory**: Application configuration and data are stored in the user's home directory at \`.bamboo\` (e.g., \`C:\\Users\\[Username]\\.bamboo\`)
84
+ - Note: When accessing this directory programmatically, use the expanded path rather than the ~ shorthand
85
+
86
+ - **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.
87
+ - Example: \`~/Documents/file.txt\` should be expanded to \`C:\\Users\\[Username]\\Documents\\file.txt\`
88
+ - Use tools to get the actual home directory path when needed
89
+ - Note: This applies to leading tilde only. Windows short paths like \`C:\\PROGRA~1\\\` are valid and should NOT be modified
90
+ - Some Windows shells (PowerShell, Git Bash, WSL) may support ~ in specific contexts, but Windows-native paths/APIs generally do not
91
+
92
+ - **Path Separators**: Windows uses backslashes (\\) as path separators, but forward slashes (/) are also accepted in most contexts
93
+ - **Case Insensitivity**: Windows file paths are case-insensitive (file.txt and FILE.TXT refer to the same file)
94
+ - **Drive Letters**: Windows paths typically start with a drive letter (C:\\, D:\\, etc.)`:e==="macos"?n+`
95
+
96
+ ### macOS-Specific Notes:
97
+
98
+ - **Configuration Directory**: Application configuration and data are stored in \`~/.bamboo\` (expands to \`/Users/[Username]/.bamboo\`)
99
+
100
+ - **File Paths**: macOS uses Unix-style paths with forward slashes (/)
101
+ - **Home Directory**: The tilde (~) expands to /Users/[Username]
102
+ - **Case Sensitivity**: macOS file system may be case-sensitive or case-insensitive depending on format (APFS is case-insensitive by default)`:e==="linux"?n+`
103
+
104
+ ### Linux-Specific Notes:
105
+
106
+ - **Configuration Directory**: Application configuration and data are stored in \`~/.bamboo\` (expands to \`/home/[username]/.bamboo\`)
107
+
108
+ - **File Paths**: Linux uses Unix-style paths with forward slashes (/)
109
+ - **Home Directory**: The tilde (~) expands to /home/[username]
110
+ - **Case Sensitivity**: Linux file systems are case-sensitive (File.txt and file.txt are different files)`:n},Bv="copilot_conclusion_with_options_enhancement_enabled",Ec=()=>localStorage.getItem(Bv)==="true",Ij=e=>{try{localStorage.setItem(Bv,e.toString())}catch(t){console.error("[copilotConclusionWithOptionsEnhancement] Failed to persist setting:",t)}},Oj=()=>"\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",$j=()=>["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(" "),Wv="bamboo_system_prompt_enhancement",Dj=()=>["## 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(`
111
+ `),Lj=e=>e.map(n=>n.trim()).filter(n=>n.length>0).join(`
112
+
113
+ `),qv=()=>{try{return localStorage.getItem(Wv)??""}catch(e){return console.error("Failed to load system prompt enhancement:",e),""}},Fj=e=>{try{const t=e.trim()?e:"";localStorage.setItem(Wv,t)}catch(t){console.error("Failed to save system prompt enhancement:",t)}},Nj=e=>{const t=[];t.push(Aj().trim()),t.push(Dj().trim());const n=qv().trim();return n&&t.push(n),nm()&&t.push(Cj().trim()),rm()&&t.push(Ej().trim()),(e??"").trim().toLowerCase()==="copilot"&&Ec()&&t.push(Oj().trim()),t},zj=e=>Lj(Nj(e)),om=e=>{const t=(e??"").trim().toLowerCase();return t.includes("completion policy violation")&&t.includes("conclusion_with_options")},am=e=>{const t=(e??"").trim(),n=t?`
114
+
115
+ Raw error: ${t}`:"";return["Bamboo stopped this completion because Copilot conclusion_with_options confirmation is enabled for this session.","The assistant tried to finish with plain text instead of calling conclusion_with_options.","Next steps: retry the request, shorten or clarify the prompt, or temporarily disable the Copilot conclusion_with_options enhancement for this session if you do not want enforced confirmation."].join(" ")+n};function Uv(e){var H;const{sessionId:t,addMessage:n,updateSession:s}=e,{modal:r,message:a}=en.useApp(),{t:i}=Ae(),l=f.useRef(null),c=f.useRef(null),u=f.useRef(""),m=f.useRef(new os),p=G(P=>P.agentAvailability),g=G(P=>P.setAgentAvailability),b=G(P=>P.checkAgentAvailability),S=G(P=>P.startAgentHealthCheck),x=G(P=>P.markOptimisticStart),k=G(P=>P.markRetryStart),j=G(P=>P.markSettleTimeout),w=G(P=>P.applyExecutionStarted),M=Jc(t),_=Ct(P=>P.currentProvider),C=G(P=>t&&P.chats.find(W=>W.id===t)||null),D=bh((H=C==null?void 0:C.config)==null?void 0:H.model_ref);f.useEffect(()=>{S()},[S]);const A=f.useCallback(()=>{var W;(W=l.current)==null||W.abort();const P=C==null?void 0:C.id;P&&m.current.stopGeneration(P).catch(ne=>{console.error("[useMessageStreaming] Failed to stop generation:",ne)})},[C==null?void 0:C.id]),B=f.useCallback(P=>{var ze;const W=G.getState(),K=(Array.isArray(W.chats)?W.chats:[]).find(st=>st.id===P),xe=Ci(P)(W),se=(xe==null?void 0:xe.sessionId)===P?xe:null,fe=(ze=K==null?void 0:K.config)==null?void 0:ze.syncCursor,Se=!!se||!!(fe!=null&&fe.hasPendingQuestion),me=(se==null?void 0:se.toolCallId)??(fe==null?void 0:fe.pendingQuestionToolCallId)??null;return{client_message_count:(fe==null?void 0:fe.messageCount)??(K==null?void 0:K.messageCount)??0,client_last_message_id:(fe==null?void 0:fe.lastMessageId)??null,client_has_pending_question:Se,client_pending_question_tool_call_id:me}},[]),F=f.useCallback((P,W)=>{const ne=W.sync;if(!ne)return;const K=G.getState(),se=(Array.isArray(K.chats)?K.chats:[]).find(fe=>fe.id===P);se&&s(P,{messageCount:ne.server_message_count,config:{...se.config||{},syncCursor:{messageCount:ne.server_message_count,lastMessageId:ne.server_last_message_id??null,hasPendingQuestion:ne.has_pending_question,pendingQuestionToolCallId:ne.pending_question_tool_call_id??null}}})},[s]),O=f.useCallback(async P=>{try{return await nt.get(`respond/${P}/pending`)}catch(W){return console.warn(`[useMessageStreaming] Failed to fetch pending question for ${P}:`,W),{has_pending_question:!1}}},[]),R=f.useCallback(async(P,W,ne)=>{var me,ze;j(P),await G.getState().loadChatHistory(P,{mode:"replace"});const K=await O(P),xe=G.getState().setPendingQuestion,se=G.getState().clearPendingQuestion;if(K.has_pending_question){xe(P,{question:K.question||"",options:K.options||[],allowCustom:K.allow_custom??!0,toolCallId:K.tool_call_id??null});const st=G.getState().chats.find(pt=>pt.id===P);return st&&s(P,{config:{...st.config||{},syncCursor:{messageCount:st.messageCount??st.messages.length,lastMessageId:((ze=(me=st.config)==null?void 0:me.syncCursor)==null?void 0:ze.lastMessageId)??null,hasPendingQuestion:!0,pendingQuestionToolCallId:K.tool_call_id??null}}}),null}if(se(P),!((W==null?void 0:W.has_pending_user_message)??!1))return null;x(P),await new Promise(st=>setTimeout(st,0));const Se=ne?await m.current.execute(P,void 0,ne,B(P),D??void 0):await m.current.execute(P,void 0,void 0,B(P),D??void 0);return F(P,Se),Se},[D,F,B,O,x,j,s]),I=f.useCallback(async(P,W,ne)=>{var fe,Se;let K=W;F(P,K);const xe=2;let se=0;for(;(fe=K.sync)!=null&&fe.need_sync&&se<xe;){const me=await R(P,K.sync,ne);if(se+=1,!me){j(P);return}K=me,F(P,K)}if((Se=K.sync)!=null&&Se.need_sync){console.warn(`[useMessageStreaming] Execute remains out-of-sync after ${xe} recovery attempt(s) for session ${P}.`,K.sync),j(P);return}if(["started","already_running"].includes(K.status)){if(K.run_id){const me=wc(P)(G.getState());w(P,K.run_id,me)}return}if(K.status==="completed"){Jt("[Streaming]","[Agent] Session already completed"),j(P);return}throw console.error("[Agent] Execute failed:",K.status),j(P),new Error(`Execute failed: ${K.status}`)},[F,R,j,w]),L=f.useCallback(async(P,W,ne,K,xe)=>{var fe,Se;if(!M)throw new Error(i("chat.model.noModelSelected"));const se=new AbortController;l.current=se;try{const me=zj(_).trim(),ze=(_??"").trim().toLowerCase()==="copilot"&&Ec(),pt=(((fe=C==null?void 0:C.config)==null?void 0:fe.workspacePath)||"").trim().replace(/\/+$/,"").replace(/\\+$/,""),Kt=await m.current.sendMessage({message:P,session_id:W,enhance_prompt:me||void 0,copilot_conclusion_with_options_enhancement_enabled:ze,workspace_path:pt||void 0,selected_skill_ids:xe&&xe.length>0?xe:void 0,images:(Se=ne.images)==null?void 0:Se.filter(Xe=>!!Xe.base64).map(Xe=>({base64:Xe.base64,name:Xe.name,size:Xe.size,type:Xe.type})),model:M,...D?{model_ref:D,provider:D.provider}:{}}),{session_id:Oe}=Kt;Oe!==W&&console.warn(`[useMessageStreaming] Backend returned unexpected session_id=${Oe} for sessionId=${W}`),await G.getState().loadChatHistory(W,{mode:"replace"});const Wt=K?await m.current.execute(W,void 0,K,B(W),D??void 0):await m.current.execute(W,void 0,void 0,B(W),D??void 0);Jt("[Streaming]","[Agent] Execute status:",Wt.status),await I(W,Wt,K)}catch(me){throw me}},[M,D,B,C,_,t,I,i]),U=f.useCallback(async(P,W,ne,K)=>{if(!C){r.info({title:i("chat.streaming.noActiveChatTitle"),content:i("chat.streaming.noActiveChatSendContent")});return}if(!t){r.info({title:i("chat.streaming.noChatIdTitle"),content:i("chat.streaming.noChatIdSendContent")});return}if(!M){r.error({title:i("chat.model.noModelSelected"),content:i("chat.model.selectModelBeforeSend")});return}let xe=p;if(xe===null&&(xe=await b()),!xe){a.error(i("chat.streaming.agentUnavailable"));return}if(!M){a.error(i("chat.streaming.modelConfigNotLoaded"));return}const se=t,fe=(W==null?void 0:W.map(me=>({id:me.id,base64:me.base64,name:me.name,size:me.size,type:me.type})))||[],Se={role:"user",content:P,id:crypto.randomUUID(),createdAt:new Date().toISOString(),images:fe};await n(se,Se),x(se),await new Promise(me=>setTimeout(me,0));try{Jt("[Streaming]","[useChatStreaming] Using Agent Server"),await L(P,se,Se,ne,K)}catch(me){if(c.current&&It.clear(se,c.current),c.current=null,u.current="",me instanceof Error&&me.name==="AbortError")a.info(i("chat.streaming.requestCancelled"));else{console.error("[useChatStreaming] Failed to send message:",me);const ze=me instanceof Error?me.message:String(me??"");om(ze)?a.error(am(ze)):(a.error(i("chat.streaming.sendFailed")),g(!1))}j(se)}finally{l.current=null,c.current&&It.clear(se,c.current),c.current=null,u.current=""}},[p,a,b,C,t,n,r,L,g,M,i,x,j]),q=f.useCallback(async(P,W="regenerate")=>{if(!C){r.info({title:i("chat.streaming.noActiveChatTitle"),content:i("chat.streaming.noActiveChatRetryContent")});return}if(!t){r.info({title:i("chat.streaming.noChatIdTitle"),content:i("chat.streaming.noChatIdRetryContent")});return}if(!M){r.error({title:i("chat.model.noModelSelected"),content:i("chat.model.selectModelBeforeRetry")});return}let ne=p;if(ne===null&&(ne=await b()),!ne){a.error(i("chat.streaming.agentUnavailable"));return}const K=t;c.current&&It.clear(K,c.current),c.current=null,u.current="";try{const xe=W==="error_retry"?"error_retry":"after_last_user",se=await m.current.truncateSessionMessages(K,{mode:xe});(W==="regenerate"||(se.messages_removed??0)>0)&&await G.getState().loadChatHistory(K,{mode:"replace"}),k(K);const fe=P?await m.current.execute(K,void 0,P,B(K),D??void 0):await m.current.execute(K,void 0,void 0,B(K),D??void 0);await I(K,fe,P)}catch(xe){console.error("[useMessageStreaming] Retry failed:",xe);const se=xe instanceof Error?xe.message:String(xe??"");om(se)?a.error(am(se)):a.error(i("chat.streaming.retryFailed")),j(K)}finally{l.current=null}},[M,D,p,a,B,b,C,t,I,r,i,k,j]);return{sendMessage:U,retryLastTurn:q,cancel:A,agentAvailable:p}}function Bj(e,t){const n=f.useMemo(()=>e.baseMessages,[e.baseMessages]),s=f.useCallback(async()=>{var u;if(!e.currentSessionId||!e.currentChat)return;const r=[...e.baseMessages];if(r.length===0)return;const a=r[r.length-1];let i=r;if((a==null?void 0:a.role)==="assistant"){if(!(await e.deleteMessage(e.currentSessionId,a.id)).success)return;i=r.slice(0,-1)}const l=[...i].reverse().find(m=>m.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:n,retryLastMessage:s}}const Wj=()=>{const e=kj(),t=vh(e),n=Tj(e),s=Uv({sessionId:e.currentSessionId,addMessage:e.addMessage,updateSession:e.updateSession}),r=Bj(e,{onRetry:s.sendMessage});return{chats:e.chats,currentSessionId:e.currentSessionId,currentChat:e.currentChat,pinnedChats:e.pinnedChats,unpinnedChats:e.unpinnedChats,chatCount:e.chatCount,currentMessages:r.currentMessages,agentAvailable:s.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:n.createNewChat,createChatWithSystemPrompt:n.createChatWithSystemPrompt,toggleChatPin:n.toggleChatPin,updateChatTitle:n.updateChatTitle,deleteEmptyChats:n.deleteEmptyChats,deleteAllUnpinnedChats:n.deleteAllUnpinnedChats,deleteAllChats:n.deleteAllChats,retryLastMessage:r.retryLastMessage,sendMessage:s.sendMessage,cancelMessage:s.cancel}},Hv="lotus_vdi_safe_mode",Rc=()=>{try{return localStorage.getItem(Hv)==="true"}catch{return!1}},qj=e=>{try{localStorage.setItem(Hv,e.toString())}catch(t){console.error("[vdiSafeMode] Failed to persist setting:",t)}},{Text:Dl}=Ke,{useToken:Uj}=Qe,Hj=({httpProxy:e,httpsProxy:t,onHttpProxyChange:n,onHttpsProxyChange:s,onReload:r,onSave:a,isLoading:i})=>{const{t:l}=Ae(),{token:c}=Uj(),u=Ps(_=>_.proxyAuthStatus),m=Ps(_=>_.isLoadingProxyAuthStatus),p=Ps(_=>_.loadProxyAuthStatus),g=Ps(_=>_.applyProxyAuth),b=Ps(_=>_.clearProxyAuth),[S,x]=f.useState({username:"",password:""}),[k,j]=f.useState(!1);f.useEffect(()=>{p()},[p]);const w=async()=>{const _=S.username.trim();if(_){j(!0);try{await g({username:_,password:S.password}),x({username:"",password:""})}catch(C){console.error("Failed to apply proxy auth:",C)}finally{j(!1)}}},M=async()=>{j(!0);try{await b()}catch(_){console.error("Failed to clear proxy auth:",_)}finally{j(!1)}};return o.jsx(Ce,{size:"small",title:o.jsx(Dl,{strong:!0,children:l("settings.networkCard.title")}),className:"lotus-settings-card",children:o.jsxs(he,{direction:"vertical",size:c.marginSM,style:{width:"100%"},children:[o.jsx(Ht,{message:l("settings.networkCard.guideTip"),type:"info",showIcon:!0}),o.jsxs(he,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[o.jsx(Dl,{type:"secondary",children:l("settings.networkCard.httpProxy")}),o.jsx(et,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:_=>n(_.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),o.jsxs(he,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[o.jsx(Dl,{type:"secondary",children:l("settings.networkCard.httpsProxy")}),o.jsx(et,{style:{width:"100%"},value:t,onChange:_=>s(_.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),o.jsx(Ce,{size:"small",title:l("settings.networkCard.proxyAuthTitle"),className:"lotus-settings-card",style:{marginTop:c.marginSM},children:u!=null&&u.configured?o.jsxs(he,{direction:"vertical",style:{width:"100%"},children:[o.jsx(Ht,{type:"success",message:l("settings.networkCard.proxyConfiguredForUser",{username:u.username??""}),showIcon:!0}),o.jsx(de,{onClick:M,loading:k||m,danger:!0,children:l("settings.networkCard.clearCredentials")})]}):o.jsxs(he,{direction:"vertical",size:c.marginXS,style:{width:"100%"},children:[o.jsx(et,{placeholder:l("settings.networkCard.username"),value:S.username,onChange:_=>x(C=>({...C,username:_.target.value}))}),o.jsx(et.Password,{placeholder:l("settings.networkCard.password"),value:S.password,onChange:_=>x(C=>({...C,password:_.target.value}))}),o.jsx(de,{type:"primary",onClick:w,loading:k||m,disabled:!S.username.trim(),children:l("settings.networkCard.apply")})]})}),o.jsx(Dl,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("settings.networkCard.credentialsStorageNote")}),o.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:c.marginSM},children:[o.jsx(de,{onClick:()=>Promise.resolve(r()).finally(()=>p({force:!0})),disabled:i,children:l("settings.networkCard.reload")}),o.jsx(de,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(a()).finally(()=>p({force:!0})),disabled:i,children:l("settings.networkCard.save")})]})]})})},{Text:Kj}=Ke,{useToken:Yj}=Qe,Vj=({msgApi:e})=>{const{t}=Ae(),{token:n}=Yj(),[s]=Pe.useForm(),[r,a]=f.useState(!1),[i,l]=f.useState(!1),[c,u]=f.useState(!1),[m,p]=f.useState(!1),[g,b]=f.useState(null),S=c&&!m,x=f.useMemo(()=>c?m?t("settings.configTab.accessPassword.helperLocalBypass","当前是本地访问,可直接修改访问密码,无需输入当前密码。"):t("settings.configTab.accessPassword.helperRemote","当前是远程访问。修改访问密码前,必须先输入当前密码。"):t("settings.configTab.accessPassword.helperNotEnabled","未设置访问密码。设置后,远程访问需要先输入密码,本地 loopback 访问可直接绕过。"),[m,c,t]),k=f.useCallback(async()=>{a(!0),b(null);try{const w=await Vt.getAccessStatus();u(w.password_enabled),p(w.local_bypass)}catch(w){const M=w instanceof Error?w.message:t("settings.configTab.accessPassword.loadStatusFailed","Failed to load access status");b(M)}finally{a(!1)}},[t]);f.useEffect(()=>{k()},[k]);const j=async()=>{var w;try{const M=await s.validateFields();l(!0),await Vt.updateAccessPassword({current_password:((w=M.currentPassword)==null?void 0:w.trim())||void 0,new_password:M.newPassword.trim()}),e.success(c?t("settings.configTab.accessPassword.updated","访问密码已更新"):t("settings.configTab.accessPassword.enabled","访问密码已设置")),s.resetFields(),await k()}catch(M){if(M.errorFields)return;const _=M instanceof Error?M.message:t("settings.configTab.accessPassword.updateFailed","Failed to update access password");e.error(_)}finally{l(!1)}};return o.jsx(Ce,{size:"small",className:"lotus-settings-card",title:o.jsx(Kj,{strong:!0,children:t("settings.configTab.accessPasswordTitle","访问密码")}),children:o.jsxs(he,{direction:"vertical",size:n.marginMD,style:{width:"100%"},children:[o.jsx(Ht,{type:c?"info":"warning",showIcon:!0,message:c?t("settings.configTab.accessPassword.statusEnabled","访问密码已启用"):t("settings.configTab.accessPassword.statusDisabled","访问密码未启用"),description:x}),g?o.jsx(Ht,{type:"error",showIcon:!0,message:g}):null,o.jsxs(Pe,{form:s,layout:"vertical",disabled:r||i,children:[S?o.jsx(Pe.Item,{label:t("settings.configTab.accessPassword.currentPasswordLabel","当前密码"),name:"currentPassword",rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.currentPasswordRequired","请输入当前密码")}],children:o.jsx(et.Password,{autoComplete:"current-password"})}):null,o.jsx(Pe.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:o.jsx(et.Password,{autoComplete:"new-password"})}),o.jsx(Pe.Item,{label:t("settings.configTab.accessPassword.confirmPasswordLabel","确认密码"),name:"confirmPassword",dependencies:["newPassword"],rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.confirmPasswordRequired","请再次输入新密码")},({getFieldValue:w})=>({validator(M,_){return!_||w("newPassword")===_?Promise.resolve():Promise.reject(new Error(t("settings.configTab.accessPassword.validation.passwordMismatch","两次输入的密码不一致")))}})],children:o.jsx(et.Password,{autoComplete:"new-password"})}),o.jsx(de,{type:"primary",loading:i,onClick:()=>void j(),children:c?t("settings.configTab.accessPassword.updateAction","更新访问密码"):t("settings.configTab.accessPassword.enableAction","启用访问密码")})]})]})})},{Text:cs}=Ke,{useToken:Xj}=Qe,kp="http://127.0.0.1:9562/v1",Ti=e=>[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort(),Gj=e=>{var n;const t=(n=e.tools)==null?void 0:n.disabled;return Array.isArray(t)?Ti(t.filter(s=>typeof s=="string")):[]},Jj=({msgApi:e,locale:t,onLocaleChange:n})=>{const{t:s}=Ae(),{token:r}=Xj(),[a,i]=f.useState({http_proxy:"",https_proxy:"",memory:{auto_dream_enabled:!1,background_model:""}}),[l,c]=f.useState(kp),[u,m]=f.useState([]),[p,g]=f.useState([]),[b,S]=f.useState([]),[x,k]=f.useState(!1),[j,w]=f.useState(!1),M=f.useCallback(async()=>{var H,P;k(!0);try{const[W,ne]=await Promise.all([Vt.getBambooConfig(),Vt.getBambooTools()]);i({http_proxy:W.http_proxy||"",https_proxy:W.https_proxy||"",memory:{auto_dream_enabled:((H=W.memory)==null?void 0:H.auto_dream_enabled)??!1,background_model:((P=W.memory)==null?void 0:P.background_model)||""}});const K=Gj(W);g(K),S(K),m(Ti(ne.tools||[]))}catch(W){console.error("Failed to load config:",W),e.error(s("settings.configTab.loadConfigFailed"))}finally{k(!1)}},[e,s]);f.useEffect(()=>{M()},[M]);const _=H=>{i(P=>({...P,http_proxy:H}))},C=H=>{i(P=>({...P,https_proxy:H}))},D=H=>{i(P=>({...P,memory:{...P.memory,auto_dream_enabled:H}}))},A=H=>{i(P=>({...P,memory:{...P.memory,background_model:H}}))},B=async()=>{var H,P;k(!0);try{const W=await Vt.validateBambooConfigPatch(a);if(!W.valid){const K=((P=(H=W.errors)==null?void 0:H.proxy)==null?void 0:P[0])??Object.values(W.errors||{}).flat().filter(Boolean)[0];e.error((K==null?void 0:K.message)||s("settings.configTab.invalidConfig"));return}await Vt.setBambooConfig(a),e.success(s("settings.configTab.saveConfigSuccess"))}catch(W){console.error("Failed to save config:",W);const ne=W instanceof Error&&W.message.trim()?W.message:s("settings.configTab.saveConfigFailed");e.error(ne)}finally{k(!1)}},F=async()=>{e.success(s("settings.configTab.backendSaved"))},O=()=>{c(kp),e.success(s("settings.configTab.backendResetDefault"))},R=(H,P)=>{g(W=>{const ne=new Set(W);return P?ne.delete(H):ne.add(H),Ti([...ne])})},I=async()=>{w(!0);try{const H=await Vt.getBambooTools();m(Ti(H.tools||[])),e.success(s("settings.configTab.toolsReloadSuccess"))}catch(H){console.error("Failed to reload tools:",H),e.error(s("settings.configTab.toolsLoadFailed"))}finally{w(!1)}},L=async()=>{w(!0);try{const H=Ti(p);await Vt.setBambooConfig({tools:{disabled:H}}),g(H),S(H),e.success(s("settings.configTab.toolsSaveSuccess"))}catch(H){console.error("Failed to save tool settings:",H),e.error(s("settings.configTab.toolsSaveFailed"))}finally{w(!1)}},U=JSON.stringify(p)!==JSON.stringify(b),q=new Set(p);return o.jsx(Rs,{spinning:x,tip:s("settings.common.loading"),children:o.jsx(Di,{items:[{key:"general",label:s("settings.configTab.tabs.general"),children:o.jsxs(he,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[o.jsx(Ht,{message:s("settings.configTab.providerMovedTitle"),description:s("settings.configTab.providerMovedDescription"),type:"info",showIcon:!0,closable:!0}),o.jsx(Hj,{httpProxy:a.http_proxy,httpsProxy:a.https_proxy,onHttpProxyChange:_,onHttpsProxyChange:C,onReload:M,onSave:B,isLoading:x}),o.jsx(Ce,{size:"small",className:"lotus-settings-card",title:o.jsx(cs,{strong:!0,children:s("settings.configTab.language")}),children:o.jsx(St,{value:t,style:{width:260},options:[{label:s("settings.configTab.languageEnglish"),value:"en-US"},{label:s("settings.configTab.languageChinese"),value:"zh-CN"},{label:s("settings.configTab.languageTraditionalChinese"),value:"zh-TW"},{label:s("settings.configTab.languageFrench"),value:"fr-FR"},{label:s("settings.configTab.languageJapanese"),value:"ja-JP"},{label:s("settings.configTab.languageHindi"),value:"hi-IN"}],onChange:H=>n(H)})}),o.jsx(Ce,{size:"small",className:"lotus-settings-card",title:o.jsx(cs,{strong:!0,children:s("settings.configTab.memoryTitle")}),children:o.jsxs(he,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[o.jsx(cs,{type:"secondary",children:s("settings.configTab.memoryDescription")}),o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:r.marginMD,flexWrap:"wrap"},children:[o.jsxs("div",{children:[o.jsx(cs,{strong:!0,children:s("settings.configTab.autoDreamEnabled")}),o.jsx("div",{children:o.jsx(cs,{type:"secondary",style:{fontSize:r.fontSizeSM},children:s("settings.configTab.autoDreamEnabledHint")})})]}),o.jsx(ln,{"data-testid":"auto-dream-toggle",checked:a.memory.auto_dream_enabled,onChange:D})]}),o.jsxs(he,{direction:"vertical",size:r.marginXXS,style:{width:"100%"},children:[o.jsx(cs,{strong:!0,children:s("settings.configTab.backgroundModel")}),o.jsx(et,{"data-testid":"auto-dream-background-model-input",value:a.memory.background_model,onChange:H=>A(H.target.value),placeholder:s("settings.configTab.backgroundModelPlaceholder")}),o.jsx(cs,{type:"secondary",style:{fontSize:r.fontSizeSM},children:s("settings.configTab.backgroundModelHint")})]}),o.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:o.jsx(de,{"data-testid":"save-memory-settings",type:"primary",onClick:B,loading:x,children:s("settings.configTab.save")})})]})}),o.jsx(Ce,{size:"small",title:o.jsx(cs,{strong:!0,children:s("settings.configTab.backendApiBaseUrlTitle")}),children:o.jsxs(he,{direction:"vertical",size:r.marginSM,style:{width:"100%"},children:[o.jsx(he,{direction:"vertical",size:r.marginXXS,style:{width:"100%"},children:o.jsx(et,{style:{width:"100%"},value:l,onChange:H=>c(H.target.value),placeholder:s("settings.configTab.backendApiPlaceholder")})}),o.jsx(cs,{type:"secondary",style:{fontSize:r.fontSizeSM},children:s("settings.configTab.backendApiHint")}),o.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:r.marginSM},children:[o.jsx(de,{"data-testid":"reset-to-defaults",onClick:O,children:s("settings.configTab.resetToDefault")}),o.jsx(de,{"data-testid":"save-api-settings",type:"primary",onClick:F,children:s("settings.configTab.save")})]})]})}),o.jsx(Vj,{msgApi:e})]})},{key:"tools",label:s("settings.configTab.tabs.tools"),children:o.jsx(Ce,{size:"small",title:o.jsx(cs,{strong:!0,children:s("settings.configTab.toolsTitle")}),children:o.jsxs(he,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[o.jsx(cs,{type:"secondary",children:s("settings.configTab.toolsDescription")}),u.length===0?o.jsx(Ht,{type:"info",showIcon:!0,message:s("settings.configTab.toolsEmpty")}):o.jsx(Qt,{bordered:!0,dataSource:u,renderItem:H=>o.jsx(Qt.Item,{actions:[o.jsx(ln,{checked:!q.has(H),onChange:P=>R(H,P)},`${H}-switch`)],children:o.jsx(cs,{code:!0,children:H})})}),o.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:r.marginSM},children:[o.jsx(de,{onClick:I,loading:j,children:s("settings.configTab.reloadTools")}),o.jsx(de,{type:"primary",onClick:L,loading:j,disabled:!U,children:s("settings.configTab.save")})]})]})})}]})})},Tp={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},wh=Pr()(Z_(e=>({settings:Tp,updateSettings:t=>e(n=>({settings:{...n.settings,...t}})),resetSettings:()=>e({settings:Tp})}),{name:"mermaid-settings"})),Zc=()=>wh(t=>t.settings),Qj=()=>wh(e=>e.updateSettings),Zj=()=>wh(e=>e.resetSettings),{Title:eC,Text:Gd}=Ke,{useToken:tC}=Qe,nC=()=>{const{t:e}=Ae(),{token:t}=tC(),n=Zc(),s=Qj(),r=Zj(),[a]=Pe.useForm();pn.useEffect(()=>{a.setFieldsValue(n)},[n,a]);const i=c=>{s(c)},l=()=>{r(),a.resetFields()};return o.jsxs("div",{style:{padding:"24px",maxWidth:"1200px",margin:"0 auto"},children:[o.jsx(eC,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),o.jsx(Gd,{type:"secondary",style:{display:"block",marginBottom:"24px"},children:e("settings.mermaidTab.description")}),o.jsxs(Pe,{form:a,layout:"vertical",initialValues:n,onValuesChange:i,children:[o.jsxs(Ce,{title:e("settings.mermaidTab.themeCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[o.jsx(fs,{gutter:16,children:o.jsx(Et,{span:24,children:o.jsx(Pe.Item,{name:"theme",label:o.jsxs(he,{children:[e("settings.mermaidTab.themeLabel"),o.jsx(bt,{title:e("settings.mermaidTab.themeTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsxs(St,{children:[o.jsx(St.Option,{value:"default",children:e("settings.mermaidTab.themeOptions.default")}),o.jsx(St.Option,{value:"neutral",children:e("settings.mermaidTab.themeOptions.neutral")}),o.jsx(St.Option,{value:"dark",children:e("settings.mermaidTab.themeOptions.dark")}),o.jsx(St.Option,{value:"forest",children:e("settings.mermaidTab.themeOptions.forest")}),o.jsx(St.Option,{value:"base",children:e("settings.mermaidTab.themeOptions.base")})]})})})}),o.jsxs(Gd,{type:"secondary",style:{display:"block",marginTop:"8px"},children:[o.jsx("strong",{children:e("settings.mermaidTab.themeDescriptionsTitle")}),o.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.default"),o.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.neutral"),o.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.dark"),o.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.forest"),o.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.base")]})]}),o.jsxs(Ce,{title:e("settings.mermaidTab.globalCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[o.jsxs(fs,{gutter:16,children:[o.jsx(Et,{span:12,children:o.jsx(Pe.Item,{name:"fontSize",label:o.jsxs(he,{children:[e("settings.mermaidTab.fontSizeLabel"),o.jsx(bt,{title:e("settings.mermaidTab.fontSizeTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Zt,{min:10,max:32,step:1,style:{width:"100%"},addonAfter:"px"})})}),o.jsx(Et,{span:12,children:o.jsx(Pe.Item,{name:"defaultScale",label:o.jsxs(he,{children:[e("settings.mermaidTab.defaultZoomLabel"),o.jsx(bt,{title:e("settings.mermaidTab.defaultZoomTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Zt,{min:.1,max:3,step:.1,style:{width:"100%"}})})})]}),o.jsx(Pe.Item,{name:"useMaxWidth",label:o.jsxs(he,{children:[e("settings.mermaidTab.responsiveWidthLabel"),o.jsx(bt,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),valuePropName:"checked",children:o.jsx(ln,{})})]}),o.jsx(Ce,{title:e("settings.mermaidTab.flowchartCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:o.jsxs(fs,{gutter:16,children:[o.jsx(Et,{span:8,children:o.jsx(Pe.Item,{name:"flowchartNodeSpacing",label:o.jsxs(he,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),o.jsx(bt,{title:e("settings.mermaidTab.flowchartNodeSpacingTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Zt,{min:20,max:200,step:10,style:{width:"100%"}})})}),o.jsx(Et,{span:8,children:o.jsx(Pe.Item,{name:"flowchartRankSpacing",label:o.jsxs(he,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),o.jsx(bt,{title:e("settings.mermaidTab.flowchartRankSpacingTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Zt,{min:20,max:200,step:10,style:{width:"100%"}})})}),o.jsx(Et,{span:8,children:o.jsx(Pe.Item,{name:"flowchartCurve",label:o.jsxs(he,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),o.jsx(bt,{title:e("settings.mermaidTab.flowchartCurveTypeTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsxs(St,{children:[o.jsx(St.Option,{value:"basis",children:e("settings.mermaidTab.flowchartCurveOptions.basis")}),o.jsx(St.Option,{value:"linear",children:e("settings.mermaidTab.flowchartCurveOptions.linear")}),o.jsx(St.Option,{value:"cardinal",children:e("settings.mermaidTab.flowchartCurveOptions.cardinal")})]})})})]})}),o.jsx(Ce,{title:e("settings.mermaidTab.sequenceCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:o.jsxs(fs,{gutter:16,children:[o.jsx(Et,{span:6,children:o.jsx(Pe.Item,{name:"sequenceActorMargin",label:o.jsxs(he,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),o.jsx(bt,{title:e("settings.mermaidTab.sequenceActorMarginTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Zt,{min:20,max:200,step:10,style:{width:"100%"}})})}),o.jsx(Et,{span:6,children:o.jsx(Pe.Item,{name:"sequenceMessageMargin",label:o.jsxs(he,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),o.jsx(bt,{title:e("settings.mermaidTab.sequenceMessageMarginTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Zt,{min:10,max:100,step:5,style:{width:"100%"}})})}),o.jsx(Et,{span:6,children:o.jsx(Pe.Item,{name:"sequenceWidth",label:o.jsxs(he,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),o.jsx(bt,{title:e("settings.mermaidTab.sequenceActorWidthTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Zt,{min:100,max:300,step:10,style:{width:"100%"}})})}),o.jsx(Et,{span:6,children:o.jsx(Pe.Item,{name:"sequenceHeight",label:o.jsxs(he,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),o.jsx(bt,{title:e("settings.mermaidTab.sequenceActorHeightTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Zt,{min:40,max:150,step:5,style:{width:"100%"}})})})]})}),o.jsx(Ce,{title:e("settings.mermaidTab.ganttCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:o.jsxs(fs,{gutter:16,children:[o.jsx(Et,{span:12,children:o.jsx(Pe.Item,{name:"ganttBarHeight",label:o.jsxs(he,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),o.jsx(bt,{title:e("settings.mermaidTab.ganttBarHeightTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Zt,{min:10,max:50,step:5,style:{width:"100%"},addonAfter:"px"})})}),o.jsx(Et,{span:12,children:o.jsx(Pe.Item,{name:"ganttTopPadding",label:o.jsxs(he,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),o.jsx(bt,{title:e("settings.mermaidTab.ganttTopPaddingTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Zt,{min:20,max:100,step:10,style:{width:"100%"}})})})]})}),o.jsx(he,{children:o.jsx(de,{icon:o.jsx(Qw,{}),onClick:l,children:e("settings.mermaidTab.resetToDefaults")})}),o.jsx(zn,{}),o.jsx(Ce,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:t.colorBgElevated}},children:o.jsx(Gd,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},sC=f.lazy(()=>Bn(()=>import("./index-8MhLoQym.js"),__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url)),{Text:Fr}=Ke,{useToken:rC}=Qe,oC=({promptEnhancement:e,onPromptEnhancementChange:t,mermaidEnhancementEnabled:n,taskEnhancementEnabled:s,showCopilotConclusionWithOptionsEnhancement:r,copilotConclusionWithOptionsEnhancementEnabled:a,onMermaidToggle:i,onTaskToggle:l,onCopilotConclusionWithOptionsToggle:c,onSaveEnhancement:u})=>{const{t:m}=Ae(),{token:p}=rC(),g=p.marginLG;return o.jsxs(ve,{vertical:!0,gap:g,children:[o.jsx(Ce,{size:"small",className:"lotus-settings-card",children:o.jsx(f.Suspense,{fallback:o.jsx(Rs,{size:"small"}),children:o.jsx(sC,{})})}),o.jsx(Ce,{size:"small",className:"lotus-settings-card",children:o.jsxs(he,{direction:"vertical",size:p.marginXS,style:{width:"100%"},children:[o.jsx(Fr,{strong:!0,children:m("settings.promptsTab.title")}),o.jsxs(ve,{align:"center",gap:p.marginSM,children:[o.jsx(Fr,{strong:!0,children:m("settings.promptsTab.mermaidEnhancement")}),o.jsx(ln,{checked:n,onChange:i})]}),o.jsxs(ve,{align:"center",gap:p.marginSM,children:[o.jsx(Fr,{strong:!0,children:m("settings.promptsTab.taskListRules")}),o.jsx(ln,{checked:s,onChange:l})]}),r&&o.jsxs(he,{direction:"vertical",size:p.marginXXS,style:{width:"100%"},children:[o.jsxs(ve,{align:"center",gap:p.marginSM,children:[o.jsx(Fr,{strong:!0,children:m("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),o.jsx(ln,{checked:a,onChange:c})]}),o.jsx(Fr,{type:"secondary",style:{fontSize:p.fontSizeSM},children:m("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:$j()})})]}),o.jsx(et.TextArea,{rows:6,placeholder:m("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:b=>t(b.target.value)}),o.jsx(ve,{justify:"flex-end",children:o.jsx(de,{type:"primary",onClick:u,children:m("settings.promptsTab.saveEnhancement")})}),o.jsx(Fr,{type:"secondary",style:{fontSize:p.fontSizeSM},children:m("settings.promptsTab.description")})]})}),n&&o.jsx(lr,{size:"small",items:[{key:"mermaid",label:o.jsx(Fr,{strong:!0,children:m("settings.mermaidTab.title")}),children:o.jsx(nC,{})}]})]})},_h="bodhi_onboarding_complete",aC=()=>localStorage.getItem(_h)==="true",iC=()=>localStorage.setItem(_h,"true"),lC=()=>localStorage.removeItem(_h),cC=["new-session","task-templates","model-picker","sidebar","open-settings"],dC=()=>{const e={};for(const t of cC)e[t]=document.querySelector(`[data-tour-id="${t}"]`);return e},uC=({disabled:e=!1})=>{const{t}=Ae(),[n,s]=f.useState(!1),[r,a]=f.useState(null);f.useEffect(()=>{if(e||aC())return;const c=setTimeout(()=>{const u=dC();a(u),s(!0)},800);return()=>clearTimeout(c)},[e]);const i=f.useMemo(()=>[{title:t("onboarding.welcome.title"),description:t("onboarding.welcome.description"),target:null},{title:t("onboarding.newSession.title"),description:t("onboarding.newSession.description"),target:(r==null?void 0:r["new-session"])??void 0},{title:t("onboarding.taskTemplates.title"),description:t("onboarding.taskTemplates.description"),target:(r==null?void 0:r["task-templates"])??void 0},{title:t("onboarding.modelPicker.title"),description:t("onboarding.modelPicker.description"),target:(r==null?void 0:r["model-picker"])??void 0},{title:t("onboarding.sidebar.title"),description:t("onboarding.sidebar.description"),target:(r==null?void 0:r.sidebar)??void 0},{title:t("onboarding.settings.title"),description:t("onboarding.settings.description"),target:(r==null?void 0:r["open-settings"])??void 0}],[t,r]),l=()=>{iC(),s(!1)};return o.jsx(Zw,{open:n,onClose:l,steps:i})},{Text:Ns}=Ke,{useToken:mC}=Qe,hC=({autoGenerateTitles:e,isUpdatingAutoTitlePreference:t,onAutoTitleToggle:n,themeMode:s,onThemeModeChange:r,vdiSafeMode:a,onVdiSafeModeToggle:i,onClearLocalStorage:l,onResetApp:c,isResetting:u,darkModeKey:m})=>{const{t:p}=Ae(),{token:g}=mC();return o.jsx(Ce,{size:"small",className:"lotus-settings-card",children:o.jsxs(he,{direction:"vertical",size:g.marginSM,style:{width:"100%"},children:[o.jsxs(ve,{align:"center",gap:g.marginSM,children:[o.jsx(Ns,{strong:!0,children:p("settings.appTab.autoGenerateTitle")}),o.jsx(ln,{checked:e,loading:t,onChange:n})]}),o.jsx(Ns,{type:"secondary",style:{fontSize:g.fontSizeSM},children:p("settings.appTab.autoGenerateTitleDesc")}),o.jsxs(ve,{align:"center",justify:"space-between",gap:g.marginSM,children:[o.jsx(Ns,{strong:!0,children:p("settings.appTab.runningVersion","Running version")}),o.jsxs(Ns,{code:!0,"data-testid":"settings-app-version",children:["v",Gm]})]}),o.jsx(Ns,{type:"secondary",style:{fontSize:g.fontSizeSM},children:p("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),o.jsxs(ve,{align:"center",gap:g.marginSM,children:[o.jsx(Ns,{strong:!0,children:p("settings.appTab.darkMode")}),o.jsx(ln,{"data-testid":"dark-mode-toggle",checked:s==="dark",onChange:b=>{const S=b?"dark":"light";r(S),localStorage.setItem(m,S)}})]}),o.jsxs(ve,{align:"center",gap:g.marginSM,children:[o.jsx(Ns,{strong:!0,children:p("settings.appTab.vdiSafeMode","Graphics compatibility mode")}),o.jsx(ln,{"data-testid":"vdi-safe-mode-toggle",checked:a,onChange:i})]}),o.jsx(Ns,{type:"secondary",style:{fontSize:g.fontSizeSM},children:p("settings.appTab.vdiSafeModeDesc","Disables blur and glass effects that can break dropdowns and hover overlays in some virtual desktop, remote, or graphics-constrained environments.")}),o.jsx(de,{block:!0,icon:o.jsx(Rm,{}),onClick:()=>{lC(),window.location.reload()},children:p("settings.appTab.resetStepReplayGuide")}),o.jsx(fc,{title:p("settings.appTab.clearLocalStorageTitle"),description:p("settings.appTab.clearLocalStorageDescription"),onConfirm:l,okText:p("settings.appTab.confirmClear"),cancelText:p("settings.appTab.cancel"),placement:"top",children:o.jsx(de,{danger:!0,block:!0,icon:o.jsx(Mr,{}),children:p("settings.appTab.clearLocalStorageButton")})}),o.jsx(zn,{style:{margin:`${g.marginSM}px 0`}}),o.jsxs(ve,{align:"center",gap:g.marginSM,children:[o.jsx(Yi,{style:{color:g.colorError}}),o.jsx(Ns,{strong:!0,style:{color:g.colorError},children:p("settings.appTab.dangerZone")})]}),o.jsx(Ns,{type:"secondary",style:{fontSize:g.fontSizeSM},children:p("settings.appTab.dangerDescription")}),o.jsx(fc,{title:p("settings.appTab.resetApplicationTitle"),description:o.jsxs("div",{children:[o.jsx("p",{children:p("settings.appTab.resetApplicationIntro")}),o.jsxs("ul",{style:{margin:0,paddingLeft:16},children:[o.jsx("li",{children:p("settings.appTab.resetStepDeleteAllSessions")}),o.jsx("li",{children:p("settings.appTab.resetStepClearStorage")}),o.jsx("li",{children:p("settings.appTab.resetStepResetConfig")}),o.jsx("li",{children:p("settings.appTab.resetStepSetupFlow")}),o.jsx("li",{children:p("settings.appTab.resetStepReload")})]})]}),onConfirm:c,okText:p("settings.appTab.resetConfirm"),cancelText:p("settings.appTab.cancel"),placement:"top",okButtonProps:{danger:!0},children:o.jsx(de,{"data-testid":"reset-to-defaults",danger:!0,block:!0,type:"primary",icon:o.jsx(kb,{}),loading:u,children:p("settings.appTab.resetButton")})})]})})},{Text:Nr}=Ke,{useToken:fC}=Qe,jp=[{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,}"}],pC=(e,t,n)=>{if(!t)return{masked:e};if(n==="exact")return{masked:e.split(t).join("[MASKED]")};try{const s=new RegExp(t,"g");return{masked:e.replace(s,"[MASKED]")}}catch(s){return{masked:e,error:s instanceof Error?s.message:bs.t("settings.keywordMaskingTab.invalidRegexPattern")}}},gC=()=>{const{t:e}=Ae(),{message:t}=en.useApp(),{token:n}=fC(),[s,r]=f.useState([]),[a,i]=f.useState(!1),[l,c]=f.useState(null),[u,m]=f.useState(""),[p,g]=f.useState("exact"),[b,S]=f.useState(!0),[x,k]=f.useState(),[j,w]=f.useState("My token is sk-123"),M=f.useCallback(async()=>{try{i(!0);const L=await Is.getInstance().getKeywordMaskingConfig();r(L.entries)}catch(I){t.error(e("settings.keywordMaskingTab.loadFailed")),console.error(I)}finally{i(!1)}},[e]);f.useEffect(()=>{M()},[M]);const _=async I=>{try{const L=Is.getInstance(),U=await L.validateKeywordEntries(I);if(!U.valid&&U.errors){const H=U.errors.map(P=>`Entry ${P.index+1}: ${P.message}`).join("; ");return t.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${H}`),!1}const q=await L.updateKeywordMaskingConfig(I);return r(q.entries),t.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch(L){return t.error(L instanceof Error?L.message:e("settings.keywordMaskingTab.saveFailed")),!1}},C=async()=>{const I={pattern:"",match_type:"exact",enabled:!0},L=[...s,I];r(L),c(L.length-1),m(""),g("exact"),S(!0),k(void 0)},D=I=>{const L=s[I];c(I),m(L.pattern),g(L.match_type),S(L.enabled),k(void 0)},A=async()=>{if(l===null)return;if(!u.trim()){t.error(e("settings.keywordMaskingTab.patternRequired"));return}const I=[...s];I[l]={pattern:u.trim(),match_type:p,enabled:b},await _(I)&&c(null)},B=()=>{var I;l!==null&&!((I=s[l])!=null&&I.pattern)&&r(s.filter((L,U)=>U!==l)),c(null)},F=async I=>{const L=s.filter((U,q)=>q!==I);await _(L)},O=async(I,L)=>{const U=[...s];U[I]={...U[I],enabled:L},await _(U)},R=pC(j,u,p);return o.jsx(Ce,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:o.jsx(de,{"data-testid":"add-keyword",type:"primary",icon:o.jsx(or,{}),onClick:C,loading:a,children:e("settings.keywordMaskingTab.addKeyword")}),children:o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:"large",children:[o.jsx(Nr,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),o.jsx(Qt,{loading:a,dataSource:s,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(I,L)=>o.jsx(Qt.Item,{style:{backgroundColor:n.colorFillAlter,marginBottom:8,borderRadius:n.borderRadius,padding:12},actions:l===L?[o.jsx(de,{"data-testid":"save-keyword",type:"primary",icon:o.jsx(Bc,{}),onClick:A,"aria-label":e("settings.keywordMaskingTab.save")},"save"),o.jsx(de,{onClick:B,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[o.jsx(de,{icon:o.jsx(Hi,{}),onClick:()=>D(L),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),o.jsx(de,{"data-testid":`delete-keyword-${L}`,danger:!0,icon:o.jsx(Mr,{}),onClick:()=>F(L),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:o.jsx(ve,{vertical:!0,style:{width:"100%"},gap:8,children:l===L?o.jsxs(o.Fragment,{children:[o.jsx(et,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:u,onChange:U=>m(U.target.value),autoFocus:!0}),o.jsxs(ve,{gap:8,align:"center",wrap:"wrap",children:[o.jsx(St,{"data-testid":"keyword-examples-select","aria-label":e("settings.keywordMaskingTab.examples"),placeholder:e("settings.keywordMaskingTab.examples"),value:x,onChange:U=>{k(U);const q=jp.find(H=>H.value===U);q&&(m(q.pattern),g(q.match_type))},options:jp.map(U=>({value:U.value,label:e(U.labelKey)})),style:{minWidth:220}}),o.jsx(St,{value:p,onChange:g,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),o.jsx(ln,{checked:b,onChange:S})]}),o.jsxs(ve,{vertical:!0,gap:6,children:[o.jsx(Nr,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),o.jsx(et,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:j,onChange:U=>w(U.target.value)}),o.jsx(Nr,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),o.jsx(et,{readOnly:!0,value:R.masked,status:R.error?"error":void 0}),R.error&&o.jsx(Nr,{type:"danger",children:R.error})]})]}):o.jsxs(ve,{justify:"space-between",align:"center",children:[o.jsxs(ve,{vertical:!0,gap:4,children:[o.jsx(Nr,{strong:!0,children:I.pattern||e("settings.keywordMaskingTab.emptyPattern")}),o.jsxs(ve,{gap:8,children:[o.jsx(Nr,{type:"secondary",style:{fontSize:12},children:I.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!I.enabled&&o.jsx(Nr,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),o.jsx(ln,{checked:I.enabled,onChange:U=>O(L,U),size:"small"})]})})})})]})})},{Text:jo,Paragraph:yC}=Ke,bC=/^[A-Za-z_][A-Za-z0-9_]*$/,xC=()=>{const{t:e}=Ae(),{message:t}=en.useApp(),[n,s]=f.useState([]),[r,a]=f.useState(!1),[i,l]=f.useState(!1),[c,u]=f.useState(null),[m]=Pe.useForm(),p=f.useCallback(async()=>{a(!0);try{const w=await Yn.getEnvVars();s(w.entries)}catch{t.error(e("settings.envVars.fetchError","Failed to load environment variables"))}finally{a(!1)}},[e]);f.useEffect(()=>{p()},[p]);const g=async w=>{var _;const M={name:w.name.trim(),value:w.value,secret:w.secret??!1,description:((_=w.description)==null?void 0:_.trim())||void 0};try{const C=await Yn.upsertEnvVar(M);s(C.entries),t.success(c?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),k()}catch(C){t.error((C instanceof Error?C.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},b=async w=>{try{const M=await Yn.deleteEnvVar(w);s(M.entries),t.success(e("settings.envVars.deleted","Variable deleted"))}catch(M){t.error((M instanceof Error?M.message:void 0)||e("settings.envVars.deleteError","Failed to delete variable"))}},S=()=>{u(null),m.resetFields(),m.setFieldsValue({secret:!1}),l(!0)},x=w=>{u(w.name),m.setFieldsValue({name:w.name,value:"",secret:w.secret,description:w.description??""}),l(!0)},k=()=>{l(!1),u(null),m.resetFields()},j=[{title:e("settings.envVars.name","Name"),dataIndex:"name",key:"name",render:w=>o.jsx(jo,{code:!0,children:w})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(w,M)=>M.secret?o.jsxs(jo,{type:"secondary",children:[o.jsx(cf,{style:{marginRight:4}}),M.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):o.jsx(jo,{children:w||o.jsx(jo,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(w,M)=>M.secret?o.jsx(Ne,{color:"warning",icon:o.jsx(cf,{}),children:e("settings.envVars.secret","Secret")}):o.jsx(Ne,{color:"processing",children:e("settings.envVars.plain","Plain")})},{title:e("settings.envVars.descriptionCol","Description"),dataIndex:"description",key:"description",ellipsis:!0,render:w=>w?o.jsx(jo,{type:"secondary",children:w}):o.jsx(jo,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(w,M)=>o.jsxs(he,{size:"small",children:[o.jsx(de,{type:"text",size:"small",icon:o.jsx(Hi,{}),onClick:()=>x(M),"aria-label":e("settings.envVars.edit","Edit")}),o.jsx(fc,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>b(M.name),okText:e("settings.envVars.yes","Yes"),cancelText:e("settings.envVars.no","No"),children:o.jsx(de,{type:"text",size:"small",danger:!0,icon:o.jsx(Mr,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return o.jsxs("div",{style:{maxWidth:900},children:[o.jsxs(Ce,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:o.jsx(de,{type:"primary",icon:o.jsx(or,{}),onClick:S,children:e("settings.envVars.addButton","Add Variable")}),children:[o.jsx(yC,{type:"secondary",style:{marginBottom:16},children:e("settings.envVars.description","Variables are injected into Bash tool processes. Secret variables are encrypted at rest.")}),o.jsx(ar,{dataSource:n,columns:j,rowKey:"name",size:"small",pagination:!1,loading:r,locale:{emptyText:e("settings.envVars.noVars","No environment variables configured")}})]}),o.jsx(Xn,{title:c?e("settings.envVars.editTitle","Edit Variable"):e("settings.envVars.addTitle","Add Environment Variable"),open:i,onCancel:k,onOk:()=>m.submit(),okText:e("settings.envVars.save","Save"),cancelText:e("settings.envVars.cancel","Cancel"),destroyOnClose:!0,children:o.jsxs(Pe,{form:m,layout:"vertical",onFinish:g,initialValues:{secret:!1},children:[o.jsx(Pe.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:bC,message:e("settings.envVars.nameInvalid","Must start with a letter or underscore, followed by letters, digits, or underscores")}],children:o.jsx(et,{placeholder:"GITHUB_TOKEN",disabled:c!==null,autoFocus:c===null})}),o.jsx(Pe.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:o.jsx(et.Password,{placeholder:c?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),o.jsx(Pe.Item,{name:"secret",label:e("settings.envVars.secret","Secret"),valuePropName:"checked",extra:e("settings.envVars.secretHint","Secret variables are encrypted on disk and masked in the UI"),children:o.jsx(ln,{})}),o.jsx(Pe.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:o.jsx(et,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},eo=class eo{constructor(){}static getInstance(){return eo.instance||(eo.instance=new eo),eo.instance}async listWorkflows(){try{Jt("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const t=await at.get("bamboo/workflows"),n=Array.isArray(t)?t:[];return Jt("[WorkflowManager]","[WorkflowManagerService] Listed workflows:",n),n.map(s=>({name:String(s.name||""),filename:String(s.filename||(s.name||"workflow")+".md"),size:Number(s.size||0),modified_at:typeof s.modified_at=="string"?s.modified_at:void 0,source:"global"}))}catch(t){throw console.error("[WorkflowManagerService] Failed to list workflows:",t),t}}async getWorkflow(t){try{Jt("[WorkflowManager]","[WorkflowManagerService] Getting workflow: "+t);const n=await at.get("bamboo/workflows/"+encodeURIComponent(t)),s=n!=null&&n.name?String(n.name):t,r={name:s,filename:String((n==null?void 0:n.filename)||s+".md"),size:Number((n==null?void 0:n.size)||0),modified_at:n==null?void 0:n.modified_at,source:"global"};return Jt("[WorkflowManager]","[WorkflowManagerService] Got workflow:",n),{name:s,content:String((n==null?void 0:n.content)||""),metadata:r}}catch(n){throw console.error("[WorkflowManagerService] Failed to get workflow "+t+":",n),u0(n)&&n.status===404?new Error("Workflow '"+t+"' not found"):n instanceof Error&&n.message.includes("404")?new Error("Workflow '"+t+"' not found"):n}}};jt(eo,"instance");let im=eo;const{Text:Jd}=Ke,{TextArea:vC}=et,{useToken:SC}=Qe,wC=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),_C=()=>{const{t:e}=Ae(),{token:t}=SC(),[n,s]=Cr.useMessage(),[r,a]=f.useState([]),[i,l]=f.useState(!1),[c,u]=f.useState(!1),[m,p]=f.useState(!1),[g,b]=f.useState(null),[S,x]=f.useState(""),[k,j]=f.useState(""),[w,M]=f.useState(!1),_=f.useMemo(()=>im.getInstance(),[]),C=f.useCallback(async()=>{l(!0);try{const O=await _.listWorkflows();return a(O),O}catch{return n.error(e("settings.workflowsTab.loadFailed")),[]}finally{l(!1)}},[n,e,_]);f.useEffect(()=>{C()},[C]);const D=f.useCallback(async O=>{b(O),x(O.name),M(!1),u(!0);try{const R=await _.getWorkflow(O.name);j(R.content??"")}catch{n.error(e("settings.workflowsTab.loadContentFailed")),j("")}finally{u(!1)}},[n,e,_]),A=()=>{b(null),x(""),j(""),M(!1)},B=f.useCallback(async()=>{if(!wC(S)){n.error(e("settings.workflowsTab.invalidName"));return}const O=r.some(R=>R.name===S);if(!g&&O){n.error(e("settings.workflowsTab.nameAlreadyExists"));return}p(!0);try{await Is.getInstance().saveWorkflow(S,k),n.success(e("settings.workflowsTab.saved")),M(!1);const L=(await C()).find(U=>U.name===S);L&&b(L)}catch(R){n.error(R instanceof Error?R.message:e("settings.workflowsTab.saveFailed"))}finally{p(!1)}},[k,S,C,n,g,e,r]),F=f.useCallback(async O=>{try{await Is.getInstance().deleteWorkflow(O.name),n.success(e("settings.workflowsTab.deleted")),(g==null?void 0:g.name)===O.name&&A(),await C()}catch(R){n.error(R instanceof Error?R.message:e("settings.workflowsTab.deleteFailed"))}},[C,n,g,e]);return o.jsxs("div",{style:{padding:"24px"},children:[s,o.jsxs(Ce,{title:e("settings.workflowsTab.title"),extra:o.jsxs(he,{children:[o.jsx(de,{icon:o.jsx(cr,{}),onClick:C,loading:i,children:e("settings.workflowsTab.refresh")}),o.jsx(de,{"data-testid":"create-workflow",icon:o.jsx(or,{}),onClick:A,children:e("settings.workflowsTab.newWorkflow")}),o.jsx(de,{"data-testid":"save-workflow",type:"primary",icon:o.jsx(Bc,{}),onClick:B,loading:m,disabled:!w,children:e("settings.workflowsTab.save")})]}),children:[o.jsx(Jd,{type:"secondary",children:e("settings.workflowsTab.description")}),o.jsxs(ve,{gap:t.marginLG,style:{marginTop:t.marginLG},children:[o.jsx("div",{style:{width:320,flexShrink:0},children:o.jsx(Qt,{loading:i,dataSource:r,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:O=>o.jsx(Qt.Item,{style:{cursor:"pointer",backgroundColor:(g==null?void 0:g.name)===O.name?t.colorFillSecondary:"transparent",borderRadius:t.borderRadius,padding:t.paddingSM},onClick:()=>D(O),actions:[o.jsx(de,{"data-testid":`delete-workflow-${O.name}`,type:"text",danger:!0,size:"small",icon:o.jsx(Mr,{}),onClick:R=>{R.stopPropagation(),F(O)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:o.jsxs(he,{direction:"vertical",size:0,children:[o.jsxs(Jd,{strong:!0,children:["/",O.name]}),o.jsx(Jd,{type:"secondary",style:{fontSize:12},children:O.filename})]})})})}),o.jsx("div",{style:{flex:1},children:o.jsxs(he,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[o.jsx(et,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:S,onChange:O=>{x(O.target.value),M(!0)},disabled:!!g,prefix:o.jsx(Hi,{})}),o.jsx(vC,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:k,onChange:O=>{j(O.target.value),M(!0)},autoSize:{minRows:12},disabled:c})]})})]})]})]})};var Ze=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))(Ze||{});const nl=6e4,sl=3e4,Bi=2e4,Ac=1e4,ed=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:Bi},request_timeout_ms:nl,healthcheck_interval_ms:sl,allowed_tools:[],denied_tools:[]}),kC=()=>({status:"stopped",tool_count:0,restart_count:0}),TC=e=>{switch(typeof e=="string"?e.trim().toLowerCase():""){case Ze.Connecting:return Ze.Connecting;case Ze.Ready:return Ze.Ready;case Ze.Degraded:return Ze.Degraded;case Ze.Error:return Ze.Error;case Ze.Stopped:default:return Ze.Stopped}},sr=(e,t)=>{if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const n=Number(e);if(Number.isFinite(n))return n}return t},jC=(e,t)=>{if(!e||typeof e!="object")return t;const n=e;if(n.type==="sse"){const a=Array.isArray(n.headers)?n.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 n.url=="string"?n.url:"",headers:a,connect_timeout_ms:sr(n.connect_timeout_ms,Ac)}}const s=Array.isArray(n.args)?n.args.filter(a=>typeof a=="string"):[],r=n.env&&typeof n.env=="object"?Object.entries(n.env):[];return{type:"stdio",command:typeof n.command=="string"?n.command:"",args:s,cwd:typeof n.cwd=="string"?n.cwd:void 0,env:r.reduce((a,[i,l])=>(typeof l=="string"&&(a[i]=l),a),{}),startup_timeout_ms:sr(n.startup_timeout_ms,Bi)}},CC=(e,t)=>{const n=ed(e.id),s=t??{};return{...n,...s,id:e.id,name:typeof s.name=="string"?s.name:typeof e.name=="string"?e.name:void 0,enabled:typeof e.enabled=="boolean"?e.enabled:typeof s.enabled=="boolean"?s.enabled:!0,request_timeout_ms:sr(s.request_timeout_ms,nl),healthcheck_interval_ms:sr(s.healthcheck_interval_ms,sl),allowed_tools:Array.isArray(s.allowed_tools)?s.allowed_tools.filter(a=>typeof a=="string"):[],denied_tools:Array.isArray(s.denied_tools)?s.denied_tools.filter(a=>typeof a=="string"):[],reconnect:s.reconnect&&typeof s.reconnect=="object"?{enabled:typeof s.reconnect.enabled=="boolean"?s.reconnect.enabled:!0,initial_backoff_ms:sr(s.reconnect.initial_backoff_ms,1e3),max_backoff_ms:sr(s.reconnect.max_backoff_ms,3e4),max_attempts:sr(s.reconnect.max_attempts,0)}:void 0,transport:jC(s.transport,n.transport)}},MC=e=>{const t=kC(),s=e.runtime??{},r=s.status??e.status;return{status:TC(r),last_error:typeof s.last_error=="string"?s.last_error:typeof e.last_error=="string"?e.last_error:void 0,connected_at:typeof s.connected_at=="string"?s.connected_at:void 0,disconnected_at:typeof s.disconnected_at=="string"?s.disconnected_at:void 0,tool_count:sr(s.tool_count??e.tool_count,t.tool_count),restart_count:sr(s.restart_count??e.restart_count,t.restart_count),last_ping_at:typeof s.last_ping_at=="string"?s.last_ping_at:void 0}},PC=e=>{const t=CC(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:MC(e)}},EC=(e,t)=>`mcp__${e}__${t}`,RC=e=>{if(!e.startsWith("mcp__"))return null;const t=e.slice(5),n=t.indexOf("__");if(n<=0)return null;const s=t.slice(0,n),r=t.slice(n+2);return!s||!r?null:{server_id:s,original_name:r}},AC=(e,t,n=0)=>{if(!e||typeof e!="object")return null;const s=e,r=typeof s.alias=="string"?s.alias:typeof s.name=="string"&&s.name.startsWith("mcp__")?s.name:void 0,a=r&&typeof r=="string"?RC(r):null,i=(typeof s.server_id=="string"?s.server_id:void 0)??(typeof s.serverId=="string"?s.serverId:void 0)??(a==null?void 0:a.server_id)??t??"",l=(typeof s.original_name=="string"?s.original_name:void 0)??(typeof s.originalName=="string"?s.originalName:void 0)??(a==null?void 0:a.original_name)??(typeof s.name=="string"?s.name:void 0)??"",c=r??(i&&l?EC(i,l):""),u=typeof s.description=="string"?s.description:"",m=s,p="parameters"in m?m.parameters:"inputSchema"in m?m.inputSchema:"input_schema"in m?m.input_schema:void 0,g=c||l||`mcp_tool_${n}`;return{alias:g,server_id:i||"unknown",original_name:l||g,description:u,parameters:p}};class IC{async getServers(){const t=await nt.get("mcp/servers");return Array.isArray(t.servers)?t.servers.map(PC):[]}async addServer(t){return nt.post("mcp/servers",t)}async updateServer(t,n){const s={...n,id:t};return nt.put(`mcp/servers/${t}`,s)}async deleteServer(t){return nt.delete(`mcp/servers/${t}`)}async connectServer(t){return nt.post(`mcp/servers/${t}/connect`)}async disconnectServer(t){return nt.post(`mcp/servers/${t}/disconnect`)}async refreshTools(t){return nt.post(`mcp/servers/${t}/refresh`)}async getTools(t){const n=t?`mcp/servers/${t}/tools`:"mcp/tools",s=await nt.get(n);return(Array.isArray(s.tools)?s.tools:[]).map((a,i)=>AC(a,t,i)).filter(a=>!!a)}async importServers(t){return nt.post("mcp/servers/import",t)}}const Kv=new IC,OC=5e3,Zs=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,Cp=(e,t)=>`${e}:${t}`,$C=(e={})=>{const{service:t=Kv,autoRefreshMs:n=OC,autoRefreshEnabled:s=!0}=e,[r,a]=f.useState([]),[i,l]=f.useState(null),[c,u]=f.useState({}),[m,p]=f.useState({}),[g,b]=f.useState({}),[S,x]=f.useState(!1),[k,j]=f.useState(!1),[w,M]=f.useState(!1),[_,C]=f.useState(null),D=f.useRef({}),A=f.useCallback(se=>{const fe=new Set(se.map(me=>me.id)),Se=se.map(me=>{const st=D.current[me.id]??me.config,pt={...st,id:me.id,name:st.name??me.name};return D.current[me.id]=pt,{...me,name:me.name||pt.name||me.id,enabled:me.enabled??pt.enabled,config:pt}});return Object.keys(D.current).forEach(me=>{fe.has(me)||delete D.current[me]}),Se},[]),B=f.useCallback(async({silent:se=!1}={})=>{se||x(!0);try{const fe=await t.getServers(),Se=A(fe);a(Se),l(me=>{var ze;return me&&Se.some(st=>st.id===me)?me:((ze=Se[0])==null?void 0:ze.id)??null}),C(null)}catch(fe){throw C(Zs(fe,"Failed to load MCP servers")),fe}finally{se||x(!1)}},[A,t]),F=f.useCallback(async(se,fe=!1)=>{if(!se)return[];if(!fe&&c[se])return c[se];p(Se=>({...Se,[se]:!0}));try{const Se=await t.getTools(se);return u(me=>({...me,[se]:Se})),C(null),Se}catch(Se){throw C(Zs(Se,"Failed to load MCP tools")),Se}finally{p(Se=>({...Se,[se]:!1}))}},[t,c]),O=f.useCallback((se,fe,Se)=>{const me=Cp(se,fe);b(ze=>({...ze,[me]:Se}))},[]),R=f.useCallback(async se=>{j(!0);try{await t.addServer(se),D.current[se.id]=se,await B()}catch(fe){throw C(Zs(fe,"Failed to add MCP server")),fe}finally{j(!1)}},[B,t]),I=f.useCallback(async(se,fe)=>{j(!0);try{const Se={...fe,id:se};await t.updateServer(se,Se),D.current[se]=Se,await B()}catch(Se){throw C(Zs(Se,"Failed to update MCP server")),Se}finally{j(!1)}},[B,t]),L=f.useCallback(async se=>{O(se,"delete",!0);try{await t.deleteServer(se),u(fe=>{const Se={...fe};return delete Se[se],Se}),delete D.current[se],await B()}catch(fe){throw C(Zs(fe,"Failed to delete MCP server")),fe}finally{O(se,"delete",!1)}},[B,t,O]),U=f.useCallback(async se=>{O(se,"connect",!0);try{await t.connectServer(se),await B({silent:!0})}catch(fe){throw C(Zs(fe,"Failed to connect MCP server")),fe}finally{O(se,"connect",!1)}},[B,t,O]),q=f.useCallback(async se=>{O(se,"disconnect",!0);try{await t.disconnectServer(se),await B({silent:!0})}catch(fe){throw C(Zs(fe,"Failed to disconnect MCP server")),fe}finally{O(se,"disconnect",!1)}},[B,t,O]),H=f.useCallback(async se=>{O(se,"refresh",!0);try{await t.refreshTools(se),await F(se,!0),await B({silent:!0})}catch(fe){throw C(Zs(fe,"Failed to refresh MCP tools")),fe}finally{O(se,"refresh",!1)}},[F,B,t,O]),P=f.useCallback(async()=>{M(!0);try{const se=r.map(fe=>fe.id);await Promise.all(se.map(async fe=>{try{await t.refreshTools(fe)}catch{}})),await B(),i&&await F(i,!0)}catch(se){throw C(Zs(se,"Failed to refresh MCP status")),se}finally{M(!1)}},[F,B,i,r,t]),W=f.useCallback(se=>{l(se)},[]),ne=f.useCallback((se,fe)=>!!g[Cp(se,fe)],[g]),K=f.useMemo(()=>i?c[i]??[]:[],[i,c]),xe=f.useMemo(()=>i?!!m[i]:!1,[i,m]);return f.useEffect(()=>{B().catch(()=>{})},[B]),f.useEffect(()=>{if(!s||n<=0)return;const se=window.setInterval(()=>{B({silent:!0}).catch(()=>{})},n);return()=>{window.clearInterval(se)}},[s,n,B]),f.useEffect(()=>{i&&F(i).catch(()=>{})},[F,i]),{servers:r,selectedServerId:i,selectedServerTools:K,isLoadingServers:S,isMutatingConfig:k,isRefreshingAll:w,isSelectedServerToolsLoading:xe,error:_,setSelectedServerId:W,refreshServers:B,addServer:R,updateServer:I,deleteServer:L,connectServer:U,disconnectServer:q,refreshServerTools:H,refreshAll:P,isServerActionLoading:ne}},DC={[Ze.Connecting]:"blue",[Ze.Ready]:"green",[Ze.Degraded]:"orange",[Ze.Stopped]:"default",[Ze.Error]:"red"},LC=e=>e===Ze.Connecting||e===Ze.Ready||e===Ze.Degraded,FC=e=>{if(!e)return;const t=e.replace(/\s+/g," ").trim();if(t)return t.length>180?`${t.slice(0,180)}...`:t},NC=({servers:e,loading:t=!1,selectedServerId:n,onSelectServer:s,onEditServer:r,onDeleteServer:a,onConnectServer:i,onDisconnectServer:l,onRefreshTools:c,isServerActionLoading:u})=>{const{t:m}=Ae(),{token:p}=Qe.useToken(),g=f.useMemo(()=>({[Ze.Connecting]:m("settings.mcpTab.statusHelp.connecting"),[Ze.Ready]:m("settings.mcpTab.statusHelp.ready"),[Ze.Degraded]:m("settings.mcpTab.statusHelp.degraded"),[Ze.Stopped]:m("settings.mcpTab.statusHelp.stopped"),[Ze.Error]:m("settings.mcpTab.statusHelp.error")}),[m]),b=f.useMemo(()=>[{key:"name",title:m("settings.mcpServerTable.columns.name"),render:(S,x)=>x.name||x.id},{key:"transport",title:m("settings.mcpServerTable.columns.transportType"),render:(S,x)=>x.config.transport.type==="sse"?m("settings.mcpServerTable.transportOptions.sse"):m("settings.mcpServerTable.transportOptions.stdio"),width:140},{key:"status",title:m("settings.mcpServerTable.columns.status"),render:(S,x)=>{var _,C;const k=((_=x.runtime)==null?void 0:_.status)??Ze.Stopped,j=FC((C=x.runtime)==null?void 0:C.last_error),w=g[k],M={[Ze.Connecting]:m("settings.mcpTab.status.connecting"),[Ze.Ready]:m("settings.mcpTab.status.ready"),[Ze.Degraded]:m("settings.mcpTab.status.degraded"),[Ze.Stopped]:m("settings.mcpTab.status.stopped"),[Ze.Error]:m("settings.mcpTab.status.error")};return o.jsx(bt,{title:j?`${w} ${m("settings.mcpTab.statusLastError",{error:j})}`:w,children:o.jsx(Ne,{color:k===Ze.Stopped?void 0:DC[k],style:{marginInlineEnd:0,cursor:"help",...k===Ze.Stopped?{background:p.colorFillSecondary,borderColor:p.colorBorderSecondary,color:p.colorTextSecondary}:void 0},children:M[k]})})},width:120},{key:"toolCount",title:m("settings.mcpServerTable.columns.toolCount"),render:(S,x)=>{var k;return((k=x.runtime)==null?void 0:k.tool_count)??0},width:100},{key:"actions",title:m("settings.mcpServerTable.columns.actions"),width:360,render:(S,x)=>{var w;const k=((w=x.runtime)==null?void 0:w.status)??Ze.Stopped,j=LC(k);return o.jsxs(he,{size:p.marginXS,children:[o.jsx(de,{size:"small",onClick:M=>{M.stopPropagation(),r==null||r(x)},children:m("settings.mcpServerTable.actions.edit")}),o.jsx(fc,{title:m("settings.mcpServerTable.deleteTitle"),description:m("settings.mcpServerTable.deleteDescription",{name:x.name||x.id}),onConfirm:()=>a==null?void 0:a(x),okText:m("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:u==null?void 0:u(x.id,"delete")},children:o.jsx(de,{size:"small",danger:!0,loading:u==null?void 0:u(x.id,"delete"),onClick:M=>M.stopPropagation(),children:m("settings.mcpServerTable.actions.delete")})}),j?o.jsx(de,{size:"small",onClick:M=>{M.stopPropagation(),l==null||l(x)},loading:u==null?void 0:u(x.id,"disconnect"),children:m("settings.mcpServerTable.actions.disconnect")}):o.jsx(de,{size:"small",type:"primary",ghost:!0,onClick:M=>{M.stopPropagation(),i==null||i(x)},loading:u==null?void 0:u(x.id,"connect"),children:m("settings.mcpServerTable.actions.connect")}),o.jsx(de,{size:"small",onClick:M=>{M.stopPropagation(),c==null||c(x)},loading:u==null?void 0:u(x.id,"refresh"),children:m("settings.mcpServerTable.actions.refreshTools")})]})}}],[u,i,a,l,r,c,g,m,p.colorBorderSecondary,p.colorFillSecondary,p.colorTextSecondary,p.marginXS]);return o.jsx(ar,{rowKey:"id",columns:b,dataSource:e,loading:t,pagination:!1,locale:{emptyText:m("settings.mcpServerTable.empty")},onRow:S=>({onClick:()=>s==null?void 0:s(S.id),style:{cursor:s?"pointer":"default",backgroundColor:n===S.id?p.colorFillSecondary:void 0}})})},{Text:Mp}=Ke,{TextArea:zC}=et,Pp=e=>{const t=e??ed(""),n=t.transport,s=n.type==="stdio"?Object.entries(n.env??{}).map(([a,i])=>({key:a,value:i})):[],r=n.type==="sse"?n.headers.map(a=>({name:a.name,value:a.value})):[];return{id:t.id,name:t.name,enabled:t.enabled,transportType:n.type,command:n.type==="stdio"?n.command:void 0,args:n.type==="stdio"?n.args:[],envEntries:s,url:n.type==="sse"?n.url:void 0,headerEntries:r,requestTimeoutMs:t.request_timeout_ms||nl,healthcheckIntervalMs:t.healthcheck_interval_ms||sl,allowedTools:t.allowed_tools||[],deniedTools:t.denied_tools||[]}},BC=e=>e.reduce((t,n)=>{var r;const s=(r=n.key)==null?void 0:r.trim();return s&&(t[s]=n.value??""),t},{}),WC=e=>e.filter(t=>{var n;return(n=t.name)==null?void 0:n.trim()}).map(t=>{var n;return{name:((n=t.name)==null?void 0:n.trim())||"",value:t.value??""}}),Ep=(e,t,n)=>{var m,p,g;const s=t==="edit"&&(n==null?void 0:n.id)||e.id,r=(m=e.name)==null?void 0:m.trim(),a=typeof e.requestTimeoutMs=="number"?e.requestTimeoutMs:(n==null?void 0:n.request_timeout_ms)??nl,i=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(n==null?void 0:n.healthcheck_interval_ms)??sl,l=Array.isArray(e.allowedTools)?e.allowedTools:(n==null?void 0:n.allowed_tools)??[],c=Array.isArray(e.deniedTools)?e.deniedTools:(n==null?void 0:n.denied_tools)??[],u=e.transportType==="sse"?{type:"sse",url:((p=e.url)==null?void 0:p.trim())||"",headers:WC(e.headerEntries||[]),connect_timeout_ms:(n==null?void 0:n.transport.type)==="sse"?n.transport.connect_timeout_ms??Ac:Ac}:{type:"stdio",command:((g=e.command)==null?void 0:g.trim())||"",args:e.args||[],env:BC(e.envEntries||[]),cwd:(n==null?void 0:n.transport.type)==="stdio"?n.transport.cwd:void 0,startup_timeout_ms:(n==null?void 0:n.transport.type)==="stdio"?n.transport.startup_timeout_ms??Bi:Bi};return{id:s,name:r||void 0,enabled:e.enabled,transport:u,request_timeout_ms:a,healthcheck_interval_ms:i,allowed_tools:l,denied_tools:c,reconnect:n==null?void 0:n.reconnect}},Rp=e=>JSON.stringify(e||ed(""),null,2),Qd=(e,t)=>{try{const n=JSON.parse(e);if(!n||typeof n!="object")return{valid:!1,error:t("settings.mcpServerForm.jsonMustBeObject")};const s=n;if(s.mcpServers&&typeof s.mcpServers=="object")return{valid:!1,error:t("settings.mcpServerForm.detectedBulkConfig")};const r=typeof s.id=="string"?s.id:"";if(!r.trim())return{valid:!1,error:t("settings.mcpServerForm.missingIdField")};if(s.transport&&typeof s.transport=="object"){const p=s;return!p.transport||typeof p.transport!="object"?{valid:!1,error:t("settings.mcpServerForm.missingTransportField")}:{valid:!0,config:p}}const a=typeof s.enabled=="boolean"?s.enabled:typeof s.disabled=="boolean"?!s.disabled:!0,i=typeof s.request_timeout_ms=="number"?s.request_timeout_ms:nl,l=typeof s.healthcheck_interval_ms=="number"?s.healthcheck_interval_ms:sl,c=Array.isArray(s.allowed_tools)?s.allowed_tools.filter(p=>typeof p=="string"):[],u=Array.isArray(s.denied_tools)?s.denied_tools.filter(p=>typeof p=="string"):[],m=typeof s.name=="string"?s.name:void 0;if(typeof s.url=="string"){const p=s.headers,g=Array.isArray(p)?p.map(S=>{if(!S||typeof S!="object")return null;const x=S,k=typeof x.name=="string"?x.name:"",j=typeof x.value=="string"?x.value:"";return k.trim()?{name:k,value:j}:null}).filter(S=>!!S):p&&typeof p=="object"?Object.entries(p).filter(([S])=>S.trim()).map(([S,x])=>({name:S,value:typeof x=="string"?x:""})):[],b=typeof s.connect_timeout_ms=="number"?s.connect_timeout_ms:Ac;return{valid:!0,config:{id:r,name:m,enabled:a,transport:{type:"sse",url:s.url,headers:g,connect_timeout_ms:b},request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:u,reconnect:void 0}}}if(typeof s.command=="string"){const p=Array.isArray(s.args)?s.args.filter(x=>typeof x=="string"):[],g=s.env,b=g&&typeof g=="object"?Object.entries(g).reduce((x,[k,j])=>(typeof j=="string"&&(x[k]=j),x),{}):{},S=typeof s.startup_timeout_ms=="number"?s.startup_timeout_ms:Bi;return{valid:!0,config:{id:r,name:m,enabled:a,transport:{type:"stdio",command:s.command,args:p,cwd:typeof s.cwd=="string"?s.cwd:void 0,env:b,startup_timeout_ms:S},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(n){return{valid:!1,error:t("settings.mcpServerForm.invalidJson",{message:n instanceof Error?n.message:t("settings.mcpServerForm.unknownError")})}}},qC=({open:e,mode:t,initialConfig:n,confirmLoading:s=!1,onCancel:r,onSubmit:a})=>{const{t:i}=Ae(),[l]=Pe.useForm(),[c,u]=f.useState("form"),[m,p]=f.useState(""),[g,b]=f.useState(null),S=f.useMemo(()=>Pp(n),[n]),x=Pe.useWatch("transportType",l)??"stdio";f.useEffect(()=>{e&&(l.setFieldsValue(S),p(Rp(n)),b(null),u("form"))},[l,S,n,e]);const k=()=>{l.resetFields(),p(""),b(null),r()},j=async()=>{if(c==="json"){const _=Qd(m,i);if(!_.valid){b(_.error);return}b(null);try{await a(_.config),p("")}catch(C){console.error("MCP server JSON submission error:",C)}return}try{const _=await l.validateFields(),C=Ep(_,t,n);await a(C),l.resetFields()}catch(_){console.error("MCP server form submission error:",_)}},w=_=>{p(_),g&&Qd(_,i).valid&&b(null)},M=_=>{if(_==="json")try{const C=l.getFieldsValue(),D=Ep(C,t,n);p(JSON.stringify(D,null,2))}catch{p(Rp(n))}else{const C=Qd(m,i);C.valid&&l.setFieldsValue(Pp(C.config))}u(_),b(null)};return o.jsxs(Xn,{title:i(t==="edit"?"settings.mcpServerForm.editTitle":"settings.mcpServerForm.addTitle"),open:e,onCancel:k,onOk:()=>{j()},okText:i("settings.mcpServerForm.save"),destroyOnClose:!0,forceRender:!0,confirmLoading:s,width:720,children:[o.jsx("div",{style:{marginBottom:16},children:o.jsxs(xs.Group,{value:c,onChange:_=>M(_.target.value),optionType:"button",buttonStyle:"solid",children:[o.jsxs(xs.Button,{value:"form",children:[o.jsx(e_,{})," ",i("settings.mcpServerForm.modeForm")]}),o.jsxs(xs.Button,{value:"json",children:[o.jsx(Wc,{})," ",i("settings.mcpServerForm.modeJson")]})]})}),c==="json"&&g&&o.jsx(Ht,{type:"error",message:i("settings.mcpServerForm.jsonError"),description:g,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>b(null)}),c==="json"?o.jsx(zC,{value:m,onChange:_=>w(_.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(ed("example-server"),null,2)}):o.jsxs(Pe,{layout:"vertical",form:l,preserve:!0,initialValues:S,children:[o.jsx(Pe.Item,{name:"id",label:i("settings.mcpServerForm.serverId"),rules:[{required:!0,message:i("settings.mcpServerForm.serverIdRequired")},{pattern:/^[a-zA-Z0-9_-]+$/,message:i("settings.mcpServerForm.serverIdPatternError")}],children:o.jsx(et,{placeholder:"filesystem",disabled:t==="edit",autoComplete:"off"})}),o.jsx(Pe.Item,{name:"name",label:i("settings.mcpServerForm.displayName"),children:o.jsx(et,{placeholder:"Filesystem MCP",autoComplete:"off"})}),o.jsx(Pe.Item,{name:"enabled",label:i("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:i("settings.mcpServerForm.enabledHelp"),children:o.jsx(ln,{})}),o.jsx(Pe.Item,{name:"transportType",label:i("settings.mcpServerForm.transportType"),rules:[{required:!0,message:i("settings.mcpServerForm.transportTypeRequired")}],children:o.jsx(St,{options:[{label:i("settings.mcpServerForm.transportOptions.stdio"),value:"stdio"},{label:i("settings.mcpServerForm.transportOptions.sse"),value:"sse"}]})}),x==="stdio"?o.jsxs(o.Fragment,{children:[o.jsx(Pe.Item,{name:"command",label:i("settings.mcpServerForm.command"),rules:[{required:!0,message:i("settings.mcpServerForm.commandRequired")}],children:o.jsx(et,{placeholder:"npx",autoComplete:"off"})}),o.jsx(Pe.Item,{name:"args",label:i("settings.mcpServerForm.arguments"),children:o.jsx(St,{mode:"tags",tokenSeparators:[","],placeholder:i("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),o.jsx(Pe.List,{name:"envEntries",children:(_,{add:C,remove:D})=>o.jsxs(he,{direction:"vertical",style:{width:"100%"},children:[o.jsxs(he,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[o.jsx(Mp,{strong:!0,children:i("settings.mcpServerForm.envVars")}),o.jsx(de,{icon:o.jsx(or,{}),onClick:()=>C({key:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addEnv")})]}),_.map(A=>o.jsxs(he,{align:"baseline",style:{display:"flex"},children:[o.jsx(Pe.Item,{...A,name:[A.name,"key"],rules:[{required:!0,message:i("settings.mcpServerForm.keyRequired")}],children:o.jsx(et,{placeholder:"MCP_ROOT",autoComplete:"off"})}),o.jsx(Pe.Item,{...A,name:[A.name,"value"],children:o.jsx(et,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),o.jsx(de,{danger:!0,type:"text",icon:o.jsx(Ru,{}),onClick:()=>D(A.name),"aria-label":i("settings.mcpServerForm.removeEnv","Remove environment variable")})]},A.key))]})})]}):o.jsxs(o.Fragment,{children:[o.jsx(Pe.Item,{name:"url",label:i("settings.mcpServerForm.sseUrl"),rules:[{required:!0,message:i("settings.mcpServerForm.sseUrlRequired")},{validator:async(_,C)=>{if(C)try{new URL(C)}catch{throw new Error(i("settings.mcpServerForm.validUrlRequired"))}}}],children:o.jsx(et,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),o.jsx(Pe.List,{name:"headerEntries",children:(_,{add:C,remove:D})=>o.jsxs(he,{direction:"vertical",style:{width:"100%"},children:[o.jsxs(he,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[o.jsx(Mp,{strong:!0,children:i("settings.mcpServerForm.headers")}),o.jsx(de,{icon:o.jsx(or,{}),onClick:()=>C({name:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addHeader")})]}),_.map(A=>o.jsxs(he,{align:"baseline",style:{display:"flex"},children:[o.jsx(Pe.Item,{...A,name:[A.name,"name"],rules:[{required:!0,message:i("settings.mcpServerForm.headerNameRequired")}],children:o.jsx(et,{placeholder:"Authorization",autoComplete:"off"})}),o.jsx(Pe.Item,{...A,name:[A.name,"value"],children:o.jsx(et,{placeholder:"Bearer token",autoComplete:"off"})}),o.jsx(de,{danger:!0,type:"text",icon:o.jsx(Ru,{}),onClick:()=>D(A.name),"aria-label":i("settings.mcpServerForm.removeHeader","Remove header")})]},A.key))]})})]})]})]})},UC={maxLines:8,maxCharacters:500},_r=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),br=e=>typeof e=="string"?e:void 0,Xr=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Ap=e=>typeof e=="boolean"?e:void 0,kh=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const n=JSON.parse(t);return _r(n)?n:null}catch{return null}},Yv=e=>/\\u[0-9a-fA-F]{4}|\\n|\\t|\\r/.test(e)?e.replace(/\\u([0-9a-fA-F]{4})/g,(t,n)=>String.fromCharCode(parseInt(n,16))).replace(/\\n/g,`
116
+ `).replace(/\\t/g," ").replace(/\\r/g,"\r"):e,Ks=e=>Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>Yv(t).trim()).filter(Boolean):[],wn=e=>{if(typeof e!="string")return;const t=Yv(e).trim();return t.length>0?t:void 0},HC=e=>{if(!_r(e))return;const t=wn(e.graph);if(t)return{title:wn(e.title),graph:t}},KC=e=>{if(!_r(e))return;const t=wn(e.summary)??wn(e.conclusion);if(t)return{title:wn(e.title)||"Conclusion",summary:t,key_points:Ks(e.key_points),next_steps:Ks(e.next_steps),confidence:wn(e.confidence),mermaid:HC(e.mermaid)}},YC=e=>{const t=kh(e);if(!t)return null;const n=wn(t.conclusion);return!n||t.type!=null&&t.type!=="conclusion"?null:{type:"conclusion",title:wn(t.title)||"Conclusion",conclusion:n,key_points:Ks(t.key_points),next_steps:Ks(t.next_steps),confidence:wn(t.confidence)}},VC=e=>{const t=kh(e);if(!t)return null;const n=wn(t.question);if(!n)return null;const s=wn(t.status);return s&&s!=="awaiting_user_input"&&s!=="awaiting_permission_approval"?null:{question:n,options:Ks(t.options),allow_custom:typeof t.allow_custom=="boolean"?t.allow_custom:!0,conclusion:KC(t.conclusion)}},XC=e=>{var n;if(!e)return null;const t=[`## ${e.title}`,e.summary];if(e.confidence&&t.push(`**Confidence:** ${e.confidence}`),e.key_points.length>0&&t.push(["**Key points**",...e.key_points.map(s=>`- ${s}`)].join(`
117
+ `)),e.next_steps.length>0&&t.push(["**Next steps**",...e.next_steps.map((s,r)=>`${r+1}. ${s}`)].join(`
118
+ `)),(n=e.mermaid)!=null&&n.graph){const s=e.mermaid.title?`**${e.mermaid.title}**
119
+
120
+ `:`**Flow**
121
+
122
+ `;t.push(`${s}\`\`\`mermaid
123
+ ${e.mermaid.graph}
124
+ \`\`\``)}return t.join(`
125
+
126
+ `)},Vv=e=>{const t=YC(e);if(!t)return null;const n=[`## ${t.title}`,t.conclusion];return t.confidence&&n.push(`**Confidence:** ${t.confidence}`),t.key_points.length>0&&n.push(["**Key points**",...t.key_points.map(s=>`- ${s}`)].join(`
127
+ `)),t.next_steps.length>0&&n.push(["**Next steps**",...t.next_steps.map((s,r)=>`${r+1}. ${s}`)].join(`
128
+ `)),n.join(`
129
+
130
+ `)},td=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const n=JSON.parse(t);if(!_r(n))return null;const s=br(n.file_path),r=br(n.operation),a=n.diff;if(!s||!r||!_r(a))return null;const i=br(a.unified);if(!i)return null;const l=n.checkpoint,c=_r(l)?{created:Ap(l.created)??!1,id:br(l.id),path:br(l.path),size_bytes:Xr(l.size_bytes),reason:br(l.reason)}:void 0;return{operation:r,message:br(n.message),file_path:s,workspace:br(n.workspace),checkpoint:c,diff:{unified:i,old_line_count:Xr(a.old_line_count),new_line_count:Xr(a.new_line_count),added_lines:Xr(a.added_lines),removed_lines:Xr(a.removed_lines),truncated:Ap(a.truncated)}}}catch{return null}},Xv=e=>{const t=kh(e);if(!t)return null;const n=wn(t.action);if(n!=="inspect"&&n!=="rebuild")return null;const s=t.data;if(!_r(s))return null;const r=wn(s.scope),a=Xr(s.total_memories);if(!r||typeof a!="number")return null;const i=l=>_r(l)?Object.fromEntries(Object.entries(l).filter(c=>typeof c[0]=="string"&&typeof c[1]=="number")):{};return{action:n,scope:wn(t.scope),project_key:wn(t.project_key),data:{scope:r,project_key:wn(s.project_key),total_memories:a,by_type:i(s.by_type),by_status:i(s.by_status),recent_ids:Ks(s.recent_ids),view_files:Ks(s.view_files),index_files:Ks(s.index_files),state_files:Ks(s.state_files),stale_candidate_count:Xr(s.stale_candidate_count)??0,last_reindex_at:wn(s.last_reindex_at),last_dream_at:wn(s.last_dream_at),topic_paths:Ks(s.topic_paths)}}},lm=e=>e.startsWith("-")&&!e.startsWith("---"),cm=e=>e.startsWith("+")&&!e.startsWith("+++"),Gv=e=>{const t=e.split(`
131
+ `),n=[];let s=0;for(;s<t.length;){const r=t[s]??"";if(r.startsWith("--- ")||r.startsWith("+++ ")){n.push({kind:"meta",text:r}),s+=1;continue}if(r.startsWith("@@")){n.push({kind:"hunk",text:r}),s+=1;continue}if(lm(r)){const a=[];for(;s<t.length&&lm(t[s]??"");)a.push(t[s]??""),s+=1;const i=[];for(;s<t.length&&cm(t[s]??"");)i.push(t[s]??""),s+=1;i.length>0?(a.forEach(l=>n.push({kind:"modified_remove",text:l})),i.forEach(l=>n.push({kind:"modified_add",text:l}))):a.forEach(l=>n.push({kind:"remove",text:l}));continue}if(cm(r)){n.push({kind:"add",text:r}),s+=1;continue}n.push({kind:"context",text:r}),s+=1}return n},GC=e=>{let t=0,n=0;for(const s of e.split(`
132
+ `)){if(cm(s)){t+=1;continue}lm(s)&&(n+=1)}return{added:t,removed:n}},Jv=e=>{const t=td(e);if(!t)return null;const n=GC(t.diff.unified);return{added:t.diff.added_lines??n.added,removed:t.diff.removed_lines??n.removed}},dm=e=>{if(typeof e=="string")return e.replace(/\\n/g,`
133
+ `).replace(/\\t/g," ");if(Array.isArray(e))return e.map(dm);if(e!==null&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=dm(s);return t}return e},um=e=>{if(!e)return{isJson:!1,formattedText:""};const t=e.trim();if(!t)return{isJson:!1,formattedText:""};if(!(t.startsWith("{")&&t.endsWith("}"))&&!(t.startsWith("[")&&t.endsWith("]")))return{isJson:!1,formattedText:e};try{const n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===1){const r=Object.keys(n)[0];if((r==="content"||r==="result"||r==="output")&&typeof n[r]=="string")return{isJson:!1,formattedText:n[r].replace(/\\n/g,`
134
+ `).replace(/\\t/g," "),parsedJson:n}}const s=dm(n);return{isJson:!0,formattedText:JSON.stringify(s,null,2),parsedJson:s}}catch{return{isJson:!1,formattedText:e}}},JC=(e,t={})=>{const n={...UC,...t};return e?e.split(/\r?\n/).length>n.maxLines?!0:e.length>n.maxCharacters:!1},QC=(e,t=320)=>e?e.length<=t?{preview:e,isTruncated:!1}:{preview:e.substring(0,t).trimEnd()+"…",isTruncated:!0}:{preview:"",isTruncated:!1},ZC=e=>{if(!e)return"No content";const t=60,n=e.trim(),s=td(n);if(s){const a=s.file_path.split(/[\\/]/).pop()||s.file_path,i=`${s.operation}: ${a}`;return i.length<=t?i:i.substring(0,t).trimEnd()+"…"}const r=Xv(n);if(r){const a=r.data.project_key||r.data.scope,i=`Memory ${r.action}: ${a} (${r.data.total_memories})`;return i.length<=t?i:i.substring(0,t).trimEnd()+"…"}if(n.length<=t)return n;if(n.startsWith("{")||n.startsWith("["))try{const a=JSON.parse(n);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 n.substring(0,t).trimEnd()+"…"},Qv=e=>{switch(e){case"success":return"green";case"error":return"red";case"warning":return"orange";default:return"blue"}},Uo=(e,t=2)=>{if(typeof e=="string")return e;try{return JSON.stringify(e,null,t)}catch(n){return console.error("[resultFormatters] Failed to stringify value:",n),String(e)}},cc=e=>!!e&&typeof e=="object"&&!Array.isArray(e),zr=(e,t)=>{const n=e[t];return typeof n=="string"?n:void 0},Ip=(e,t)=>{const n=e[t];return typeof n=="boolean"?n:void 0},eM=(e,t)=>{const n=e[t];return Array.isArray(n)?n:void 0},ji=e=>{if(!cc(e))return"any";const t=e.type;if(typeof t=="string"){if(t==="array"){const a=e.items;return`array<${ji(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 n=Array.isArray(e.oneOf)?e.oneOf:null;if(n)return n.map(ji).join(" | ")||"any";const s=Array.isArray(e.anyOf)?e.anyOf:null;if(s)return s.map(ji).join(" | ")||"any";const r=Array.isArray(e.allOf)?e.allOf:null;return r&&r.map(ji).join(" & ")||"any"},tM=e=>{if(!cc(e))return null;const t=e.properties;if(!cc(t))return{schemaUri:zr(e,"$schema"),title:zr(e,"title"),description:zr(e,"description"),additionalProperties:Ip(e,"additionalProperties"),fields:[]};const n=new Set((eM(e,"required")??[]).filter(r=>typeof r=="string").map(r=>r)),s=Object.entries(t).map(([r,a])=>{const i=cc(a)?a:void 0;return{name:r,type:ji(a),required:n.has(r),description:i?zr(i,"description"):void 0,defaultValue:i?i.default:void 0,enumValues:i&&Array.isArray(i.enum)?i.enum:void 0}});return s.sort((r,a)=>r.required!==a.required?r.required?-1:1:r.name.localeCompare(a.name)),{schemaUri:zr(e,"$schema"),title:zr(e,"title"),description:zr(e,"description"),additionalProperties:Ip(e,"additionalProperties"),fields:s}},{Text:zs}=Ke,nM=e=>e===void 0?"":e===null?"null":typeof e=="string"?e:Uo(e,0),sM=({schema:e})=>{const{token:t}=Qe.useToken(),{t:n}=Ae(),s=f.useMemo(()=>tM(e),[e]);if(!s)return o.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:Uo(e,2)});const r=[{title:n("components.jsonSchema.field"),dataIndex:"name",key:"name",width:180,render:i=>o.jsx(zs,{code:!0,children:i})},{title:n("components.jsonSchema.type"),dataIndex:"type",key:"type",width:140,render:i=>o.jsx(zs,{children:i})},{title:n("components.jsonSchema.required"),dataIndex:"required",key:"required",width:110,render:i=>i?o.jsx(zs,{strong:!0,style:{color:t.colorError},children:n("components.jsonSchema.yes")}):o.jsx(zs,{type:"secondary",children:n("components.jsonSchema.no")})},{title:n("components.jsonSchema.default"),dataIndex:"defaultValue",key:"default",width:160,render:i=>i===void 0?o.jsx(zs,{type:"secondary",children:"-"}):o.jsx(zs,{children:nM(i)})},{title:n("components.jsonSchema.description"),dataIndex:"description",key:"description",render:i=>i?o.jsx(zs,{style:{whiteSpace:"pre-wrap"},children:i}):o.jsx(zs,{type:"secondary",children:"-"})}],a=(s.fields??[]).map(i=>({...i,key:i.name}));return o.jsxs("div",{style:{width:"100%"},children:[o.jsx(Fn,{size:"small",column:1,items:[s.schemaUri?{key:"schema",label:"$schema",children:o.jsx(zs,{code:!0,children:s.schemaUri})}:null,typeof s.additionalProperties=="boolean"?{key:"additionalProperties",label:"additionalProperties",children:o.jsx(zs,{children:s.additionalProperties?"true":"false"})}:null].filter(Boolean)}),o.jsx(ar,{size:"small",pagination:!1,columns:r,dataSource:a,locale:{emptyText:n("components.jsonSchema.noProperties")},style:{marginTop:t.marginSM}})]})},{Text:ba}=Ke,rM=(e,t)=>`mcp__${e}__${t}`,oM=({server:e,tools:t,loading:n=!1})=>{const{t:s}=Ae();return o.jsx(Ce,{title:s("settings.mcpToolList.title"),size:"small",children:e?o.jsx(Qt,{loading:n,dataSource:t,locale:{emptyText:s("settings.mcpToolList.empty")},renderItem:r=>{const a=rM(r.server_id,r.original_name);return o.jsx(Qt.Item,{children:o.jsxs(he,{direction:"vertical",size:2,style:{width:"100%"},children:[o.jsx(ba,{strong:!0,children:r.original_name}),o.jsx(ba,{type:"secondary",children:r.description||s("settings.mcpToolList.noDescription")}),o.jsx(ba,{code:!0,children:r.alias}),o.jsxs(ba,{type:"secondary",children:[s("settings.mcpToolList.aliasMapping"),": ",o.jsx(ba,{code:!0,children:a})]}),r.parameters!==void 0&&o.jsx(lr,{size:"small",items:[{key:"schema",label:s("settings.mcpToolList.parametersSchema"),children:o.jsx(sM,{schema:r.parameters})}]})]})})}}):o.jsx(Mn,{image:Mn.PRESENTED_IMAGE_SIMPLE,description:s("settings.mcpToolList.selectServerHint")})})},{Text:xa}=Ke,{useToken:aM}=Qe,{TextArea:iM}=et,Op={[Ze.Connecting]:"processing",[Ze.Ready]:"success",[Ze.Degraded]:"warning",[Ze.Stopped]:"default",[Ze.Error]:"error"},lM=()=>({[Ze.Connecting]:0,[Ze.Ready]:0,[Ze.Degraded]:0,[Ze.Stopped]:0,[Ze.Error]:0}),Br=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,cM=e=>{var n,s,r;const t={};for(const a of e){const i=(n=a.id)==null?void 0:n.trim();if(!i)continue;const c=!(a.enabled??a.config.enabled),u=a.config.transport;if(u.type==="sse"){const p={};for(const b of u.headers??[]){const S=(s=b.name)==null?void 0:s.trim();S&&(p[S]=b.value??"")}const g={url:u.url};c&&(g.disabled=!0),Object.keys(p).length&&(g.headers=p),t[i]=g;continue}const m={command:u.command};c&&(m.disabled=!0),(r=u.args)!=null&&r.length&&(m.args=u.args),u.cwd&&(m.cwd=u.cwd),u.env&&Object.keys(u.env).length&&(m.env=u.env),t[i]=m}return{mcpServers:t}},dM=()=>{const{t:e}=Ae(),{token:t}=aM(),[n,s]=Cr.useMessage(),{servers:r,selectedServerId:a,selectedServerTools:i,isLoadingServers:l,isMutatingConfig:c,isRefreshingAll:u,isSelectedServerToolsLoading:m,error:p,setSelectedServerId:g,addServer:b,updateServer:S,deleteServer:x,connectServer:k,disconnectServer:j,refreshServerTools:w,refreshAll:M,isServerActionLoading:_}=$C(),C=f.useMemo(()=>({[Ze.Connecting]:e("settings.mcpTab.status.connecting"),[Ze.Ready]:e("settings.mcpTab.status.ready"),[Ze.Degraded]:e("settings.mcpTab.status.degraded"),[Ze.Stopped]:e("settings.mcpTab.status.stopped"),[Ze.Error]:e("settings.mcpTab.status.error")}),[e]),D=f.useMemo(()=>({[Ze.Connecting]:e("settings.mcpTab.statusHelp.connecting"),[Ze.Ready]:e("settings.mcpTab.statusHelp.ready"),[Ze.Degraded]:e("settings.mcpTab.statusHelp.degraded"),[Ze.Stopped]:e("settings.mcpTab.statusHelp.stopped"),[Ze.Error]:e("settings.mcpTab.statusHelp.error")}),[e]),[A,B]=f.useState(!1),[F,O]=f.useState("create"),[R,I]=f.useState(null),[L,U]=f.useState(!1),[q,H]=f.useState("merge"),[P,W]=f.useState(""),[ne,K]=f.useState(null),[xe,se]=f.useState(!1),fe=f.useMemo(()=>a?r.find(N=>N.id===a)??null:null,[a,r]),Se=f.useMemo(()=>{const N=lM();let le=0;return r.forEach(be=>{var Le,ue;const De=((Le=be.runtime)==null?void 0:Le.status)??Ze.Stopped;N[De]+=1,le+=((ue=be.runtime)==null?void 0:ue.tool_count)??0}),{byStatus:N,totalServers:r.length,totalTools:le}},[r]),me={background:t.colorFillSecondary,borderColor:t.colorBorderSecondary,color:t.colorTextSecondary},ze=async N=>{try{await x(N.id),n.success(e("settings.mcpTab.serverDeleted"))}catch(le){n.error(Br(le,e("settings.mcpTab.deleteServerFailed")))}},st=async N=>{try{await k(N.id),n.success(e("settings.mcpTab.connectedTo",{name:N.name||N.id}))}catch(le){n.error(Br(le,e("settings.mcpTab.connectServerFailed")))}},pt=async N=>{try{await j(N.id),n.success(e("settings.mcpTab.disconnected",{name:N.name||N.id}))}catch(le){n.error(Br(le,e("settings.mcpTab.disconnectServerFailed")))}},Kt=async N=>{try{await w(N.id),n.success(e("settings.mcpTab.toolsRefreshedFor",{name:N.name||N.id}))}catch(le){n.error(Br(le,e("settings.mcpTab.refreshToolsFailed")))}},Oe=async()=>{try{await M(),n.success(e("settings.mcpTab.statusRefreshed"))}catch(N){n.error(Br(N,e("settings.mcpTab.refreshStatusFailed")))}},Wt=()=>{I(null),O("create"),B(!0)},Xe=N=>{I(N),O("edit"),B(!0)},_e=async N=>{try{if(F==="edit"){if(!R){n.error(e("settings.mcpTab.noServerForEditing"));return}await S(R.id,N),n.success(e("settings.mcpTab.savedServer",{name:R.name||R.id}))}else await b(N),n.success(e("settings.mcpTab.addedServer",{name:N.name||N.id}));B(!1),I(null)}catch(le){n.error(Br(le,e("settings.mcpTab.saveServerFailed")))}},Ye=()=>{U(!0),K(null),H("merge"),W("")},ot=async()=>{const N=cM(r),le=JSON.stringify(N,null,2);try{await Ss(le),n.success(e("settings.mcpTab.copiedConfig"))}catch{U(!0),K(null),H("merge"),W(le),n.warning(e("settings.mcpTab.clipboardUnavailable"))}},Lt=async()=>{var De;K(null);let N;try{N=JSON.parse(P)}catch(Le){K(`${e("settings.mcpTab.invalidJsonPrefix")}: ${Le instanceof Error?Le.message:e("settings.mcpTab.unknownError")}`);return}if(!N||typeof N!="object"){K(e("settings.mcpTab.jsonMustBeObject"));return}const be=N.mcpServers;if(!be||typeof be!="object"){K(e("settings.mcpTab.missingMcpServers"));return}se(!0);try{const Le=await Kv.importServers({mcpServers:be,mode:q}),ue=((De=Le.start_errors)==null?void 0:De.length)??0;n.success(e("settings.mcpTab.importSummary",{count:Le.server_ids.length,added:Le.added,updated:Le.updated,removed:Le.removed,failed:ue})),ue&&n.warning(e("settings.mcpTab.importStartFailures")),U(!1),W(""),await Oe()}catch(Le){K(Br(Le,e("settings.mcpTab.importFailed")))}finally{se(!1)}};return o.jsxs(he,{direction:"vertical",size:t.marginMD,style:{width:"100%"},children:[s,p?o.jsx(Ht,{type:"error",showIcon:!0,message:p}):null,o.jsx(Ce,{size:"small",title:e("settings.mcpTab.overviewTitle"),children:o.jsxs(he,{direction:"vertical",size:t.marginXS,style:{width:"100%"},children:[o.jsx(xa,{type:"secondary",children:e("settings.mcpTab.overviewDescription")}),o.jsxs(he,{wrap:!0,children:[o.jsx(Ne,{style:me,children:e("settings.mcpTab.totalServers",{count:Se.totalServers})}),o.jsx(Ne,{style:me,children:e("settings.mcpTab.totalTools",{count:Se.totalTools})}),Object.values(Ze).map(N=>o.jsx(bt,{title:D[N],children:o.jsxs(Ne,{color:N===Ze.Stopped?void 0:Op[N],style:{cursor:"help",...N===Ze.Stopped?me:void 0},children:[C[N],": ",Se.byStatus[N]]})},N))]}),o.jsx(xa,{type:"secondary",children:e("settings.mcpTab.statusGuideTitle")}),o.jsx(he,{direction:"vertical",size:2,style:{width:"100%"},children:Object.values(Ze).map(N=>o.jsxs(xa,{type:"secondary",children:[o.jsx(Ne,{color:N===Ze.Stopped?void 0:Op[N],style:{marginInlineEnd:8,...N===Ze.Stopped?me:void 0},children:C[N]}),D[N]]},`guide-${N}`))})]})}),o.jsx(Ce,{size:"small",title:e("settings.mcpTab.serversTitle"),extra:o.jsxs(he,{children:[o.jsx(de,{type:"primary",onClick:Wt,children:e("settings.mcpTab.addServer")}),o.jsx(de,{icon:o.jsx(cr,{}),loading:u,onClick:()=>{Oe()},children:e("settings.mcpTab.refreshAll")}),o.jsx(de,{icon:o.jsx(vs,{}),onClick:()=>void ot(),children:e("settings.mcpTab.export")}),o.jsx(de,{icon:o.jsx(t_,{}),onClick:Ye,children:e("settings.mcpTab.import")})]}),children:o.jsx(NC,{servers:r,loading:l,selectedServerId:a,onSelectServer:g,onEditServer:Xe,onDeleteServer:ze,onConnectServer:st,onDisconnectServer:pt,onRefreshTools:Kt,isServerActionLoading:_})}),o.jsx(oM,{server:fe,tools:i,loading:m}),o.jsx(qC,{open:A,mode:F,initialConfig:(R==null?void 0:R.config)??null,confirmLoading:c,onCancel:()=>{c||(B(!1),I(null))},onSubmit:N=>void _e(N)}),o.jsx(Xn,{open:L,title:e("settings.mcpTab.importModalTitle"),okText:e("settings.mcpTab.import"),onOk:()=>void Lt(),okButtonProps:{loading:xe},onCancel:()=>{xe||(U(!1),K(null))},width:800,destroyOnClose:!1,children:o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:"middle",children:[o.jsxs(xa,{type:"secondary",children:[e("settings.mcpTab.importHint"),o.jsx("br",{}),o.jsx(xa,{code:!0,children:'{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "..."] } } }'})]}),o.jsxs(xs.Group,{value:q,onChange:N=>H(N.target.value),optionType:"button",buttonStyle:"solid",children:[o.jsx(xs.Button,{value:"merge",children:e("settings.mcpTab.importModeMerge")}),o.jsx(xs.Button,{value:"replace",children:e("settings.mcpTab.importModeReplace")})]}),q==="replace"?o.jsx(Ht,{type:"warning",showIcon:!0,message:e("settings.mcpTab.replaceWarning")}):null,ne?o.jsx(Ht,{type:"error",showIcon:!0,message:ne}):null,o.jsx(iM,{value:P,onChange:N=>W(N.target.value),rows:14,placeholder:'{"mcpServers": { "filesystem": { "command": "...", "args": [], "env": {} } }}',spellCheck:!1})]})})]})},ds=e=>{const t=new URLSearchParams;Object.entries(e).forEach(([s,r])=>{r===void 0||r===""||t.set(s,String(r))});const n=t.toString();return n?`?${n}`:""};class uM{async getSummary(t={}){const n=ds({start_date:t.startDate,end_date:t.endDate});return nt.get(`metrics/summary${n}`)}async getByModel(t={}){const n=ds({start_date:t.startDate,end_date:t.endDate});return nt.get(`metrics/by-model${n}`)}async getSessions(t={}){const n=ds({start_date:t.startDate,end_date:t.endDate,model:t.model,limit:t.limit});return nt.get(`metrics/sessions${n}`)}async getSessionDetail(t){try{return await nt.get(`metrics/sessions/${encodeURIComponent(t)}`)}catch(n){if(n instanceof Error&&n.message.includes("not found"))return null;throw n}}async getUsageBreakdown(t={}){const n=ds({start_date:t.startDate,end_date:t.endDate,model:t.model});return nt.get(`metrics/usage-breakdown${n}`)}async getDaily(t={}){const n=ds({days:t.days,end_date:t.endDate,granularity:t.granularity});return nt.get(`metrics/daily${n}`)}async getForwardSummary(t={}){const n=ds({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return nt.get(`metrics/forward/summary${n}`)}async getForwardByEndpoint(t={}){const n=ds({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return nt.get(`metrics/forward/by-endpoint${n}`)}async getForwardRequests(t={}){const n=ds({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return nt.get(`metrics/forward/requests${n}`)}async getMemorySummary(t={}){const n=ds({scope:t.scope,project_key:t.projectKey});return nt.get(`metrics/memory/summary${n}`)}async getMemoryTimeline(t={}){const n=ds({scope:t.scope,project_key:t.projectKey,days:t.days,end_date:t.endDate,granularity:t.granularity});return nt.get(`metrics/memory/timeline${n}`)}async getUnifiedSummary(t={}){const n=ds({start_date:t.startDate,end_date:t.endDate});return nt.get(`metrics/v2/summary${n}`)}async getUnifiedTimeline(t={}){const n=ds({days:t.days,end_date:t.endDate,granularity:t.granularity});return nt.get(`metrics/v2/timeline${n}`)}}const Ai=new uM,Zv=1,mM=365,eS=e=>Number.isFinite(e)?Math.min(mM,Math.max(Zv,Math.floor(e??30))):30,Zd=e=>{if(!e)return null;const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=Number(t[1]),s=Number(t[2]),r=Number(t[3]),a=new Date(Date.UTC(n,s-1,r));return a.getUTCFullYear()!==n||a.getUTCMonth()!==s-1||a.getUTCDate()!==r?null:a},va=e=>e.toISOString().slice(0,10),hM=(e,t)=>{const n=new Date(e.getTime());return n.setUTCDate(n.getUTCDate()+t),n},fM=(e,t)=>{const n=t.getTime()-e.getTime(),s=Math.floor(n/864e5)+1;return eS(s)},Th=(e,t=new Date)=>{const n=eS(e.days),s=va(t),r=Zd(e.endDate)??Zd(s);if(!r)return{startDate:s,endDate:s,days:Zv};const a=Zd(e.startDate);if(a){const l=r<a?a:r;return{startDate:va(a),endDate:va(l),days:fM(a,l)}}const i=hM(r,-(n-1));return{startDate:va(i),endDate:va(r),days:n}},pM=15e3,gM=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,yM=(e={})=>{const{filters:t,autoRefreshMs:n=pM}=e,s=f.useMemo(()=>({startDate:t==null?void 0:t.startDate,endDate:t==null?void 0:t.endDate,days:(t==null?void 0:t.days)??30,endpoint:t==null?void 0:t.endpoint,model:t==null?void 0:t.model,limit:(t==null?void 0:t.limit)??100}),[t==null?void 0:t.startDate,t==null?void 0:t.endDate,t==null?void 0:t.days,t==null?void 0:t.endpoint,t==null?void 0:t.model,t==null?void 0:t.limit]),r=f.useMemo(()=>Th({startDate:s.startDate,endDate:s.endDate,days:s.days}),[s.days,s.endDate,s.startDate]),[a,i]=f.useState(null),[l,c]=f.useState([]),[u,m]=f.useState([]),[p,g]=f.useState(!1),[b,S]=f.useState(!1),[x,k]=f.useState(null),j=f.useCallback(async M=>{M?g(!0):S(!0);try{const _={startDate:r.startDate,endDate:r.endDate,endpoint:s.endpoint,model:s.model,limit:s.limit},[C,D,A]=await Promise.all([Ai.getForwardSummary(_),Ai.getForwardByEndpoint(_),Ai.getForwardRequests(_)]);i(C),c(D),m(A),k(null)}catch(_){k(gM(_,"Failed to load forward metrics"))}finally{M?g(!1):S(!1)}},[s.endpoint,s.model,s.limit,r.endDate,r.startDate]),w=f.useCallback(async()=>{await j(!1)},[j]);return f.useEffect(()=>{j(!0)},[j]),f.useEffect(()=>{if(n<=0)return;const M=window.setInterval(()=>{j(!1)},n);return()=>{window.clearInterval(M)}},[n,j]),{summary:a,endpointMetrics:l,requests:u,isLoading:p,isRefreshing:b,error:x,refresh:w}},bM=15e3,$p=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,xM=(e={})=>{const{filters:t,autoRefreshMs:n=bM,service:s=Ai}=e,r=f.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=f.useMemo(()=>Th({startDate:r.startDate,endDate:r.endDate,days:r.days}),[r.days,r.endDate,r.startDate]),[i,l]=f.useState(null),[c,u]=f.useState([]),[m,p]=f.useState([]),[g,b]=f.useState([]),[S,x]=f.useState(null),[k,j]=f.useState([]),[w,M]=f.useState(null),[_,C]=f.useState(!1),[D,A]=f.useState(!1),[B,F]=f.useState(!1),[O,R]=f.useState(null),I=f.useCallback(async H=>{H?A(!0):F(!0);try{const P=s.getMemorySummary?s.getMemorySummary().catch(()=>null):Promise.resolve(null),W=s.getMemoryTimeline?s.getMemoryTimeline({days:a.days,endDate:a.endDate,granularity:r.granularity}).catch(()=>[]):Promise.resolve([]),[ne,K,xe,se,fe,Se]=await Promise.all([s.getSummary({startDate:a.startDate,endDate:a.endDate}),s.getByModel({startDate:a.startDate,endDate:a.endDate}),s.getSessions({startDate:a.startDate,endDate:a.endDate,model:r.model,limit:r.sessionLimit}),s.getDaily({days:a.days,endDate:a.endDate,granularity:r.granularity}),P,W]);l(ne),u(K),p(xe),b(se),x(fe),j(Se),R(null)}catch(P){R($p(P,"Failed to load metrics"))}finally{H?A(!1):F(!1)}},[r.granularity,r.model,r.sessionLimit,a.days,a.endDate,a.startDate,s]),L=f.useCallback(async()=>{await I(!1)},[I]),U=f.useCallback(async H=>{C(!0);try{const P=await s.getSessionDetail(H);M(P)}catch(P){R($p(P,"Failed to load session detail"))}finally{C(!1)}},[s]),q=f.useCallback(()=>{M(null)},[]);return f.useEffect(()=>{I(!0)},[I]),f.useEffect(()=>{if(n<=0)return;const H=window.setInterval(()=>{I(!1)},n);return()=>{window.clearInterval(H)}},[n,I]),{summary:i,modelMetrics:c,sessions:m,timeline:g,memorySummary:S,memoryTimeline:k,sessionDetail:w,isLoading:D,isRefreshing:B,isSessionDetailLoading:_,error:O,refresh:L,loadSessionDetail:U,clearSessionDetail:q}},vM=15e3,SM=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,wM=(e={})=>{const{filters:t,autoRefreshMs:n=vM}=e,s=f.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]),r=f.useMemo(()=>Th({startDate:s.startDate,endDate:s.endDate,days:s.days}),[s.days,s.endDate,s.startDate]),[a,i]=f.useState(null),[l,c]=f.useState(!1),[u,m]=f.useState(!1),[p,g]=f.useState(null),b=f.useCallback(async x=>{x?c(!0):m(!0);try{const k=await Ai.getUsageBreakdown({startDate:r.startDate,endDate:r.endDate,model:s.model});i(k),g(null)}catch(k){g(SM(k,"Failed to load usage breakdown"))}finally{x?c(!1):m(!1)}},[s.model,r.endDate,r.startDate]),S=f.useCallback(async()=>{await b(!1)},[b]);return f.useEffect(()=>{b(!0)},[b]),f.useEffect(()=>{if(n<=0)return;const x=window.setInterval(()=>{b(!1)},n);return()=>{window.clearInterval(x)}},[n,b]),{data:a,isLoading:l,isRefreshing:u,error:p,refresh:S}},{useToken:_M}=Qe,kM=({data:e,loading:t})=>{const{t:n}=Ae(),{token:s}=_M();if(t)return o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.charts.endpointDistribution"),children:o.jsx("div",{style:{width:"100%",height:240},children:o.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100%",color:s.colorTextSecondary},children:n("settings.common.loading")})})});if(e.length===0)return o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.charts.endpointDistribution"),children:o.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:240,color:s.colorTextSecondary},children:n("settings.charts.noForwardMetrics")})});const r=e.map(a=>({endpoint:a.endpoint.split(".").pop()||a.endpoint,requests:a.requests,successful:a.successful,failed:a.failed}));return o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.charts.endpointDistribution"),children:o.jsx("div",{style:{width:"100%",height:240},children:o.jsx(Ko,{children:o.jsxs(Fm,{data:r,children:[o.jsx(Vi,{strokeDasharray:"3 3"}),o.jsx(Xi,{dataKey:"endpoint"}),o.jsx(Gi,{}),o.jsx(Yo,{formatter:(a,i)=>[`${a}`,i.charAt(0).toUpperCase()+i.slice(1)]}),o.jsx(Nm,{}),o.jsx(bc,{dataKey:"successful",fill:"var(--lotus-chart-secondary)",name:n("settings.common.successful"),fillOpacity:.9,radius:[4,4,0,0]}),o.jsx(bc,{dataKey:"failed",fill:"var(--lotus-chart-danger)",name:n("settings.common.failed"),fillOpacity:.9,radius:[4,4,0,0]})]})})})})},{useToken:TM}=Qe,jM=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),n=Math.floor(t/60),s=t%60;if(n>=60){const r=Math.floor(n/60),a=n%60;return`${r}h ${a}m`}return n>0?`${n}m ${s}s`:`${s}s`},Dp=({summary:e,loading:t})=>{const{t:n}=Ae(),{token:s}=TM();if(t)return o.jsx(dr,{active:!0,paragraph:{rows:1}});const r=e&&e.total_requests>0?(e.successful_requests/e.total_requests*100).toFixed(1):"0.0";return o.jsxs(fs,{gutter:[s.marginSM,s.marginSM],children:[o.jsx(Et,{xs:24,sm:12,xl:6,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(sn,{title:n("settings.forwardMetricsCards.totalForwardRequests"),value:(e==null?void 0:e.total_requests)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),o.jsx(Et,{xs:24,sm:12,xl:6,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(sn,{title:n("settings.forwardMetricsCards.successRate"),value:r,suffix:"%",valueStyle:{color:Number(r)>=95?"var(--lotus-chart-secondary)":Number(r)>=80?"var(--lotus-chart-accent)":"var(--lotus-chart-danger)"}})})}),o.jsx(Et,{xs:24,sm:12,xl:6,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(sn,{title:n("settings.forwardMetricsCards.forwardTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),o.jsx(Et,{xs:24,sm:12,xl:6,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(sn,{title:n("settings.forwardMetricsCards.avgResponseTime"),value:jM(e==null?void 0:e.avg_duration_ms),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:Wr}=Ke,CM=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),n=Math.floor(t/60),s=t%60;return n>0?`${n}m ${s}s`:`${s}s`},MM=e=>new Date(e).toLocaleString(),PM=({requests:e,loading:t})=>{const{t:n}=Ae(),s=[{title:n("settings.metricsTable.forward.columns.id"),dataIndex:"forward_id",key:"forward_id",width:120,render:r=>o.jsxs(Wr,{style:{fontSize:12},copyable:!0,children:[r.slice(0,8),"..."]})},{title:n("settings.metricsTable.forward.columns.endpoint"),dataIndex:"endpoint",key:"endpoint",width:150,render:r=>o.jsx(Ne,{color:"processing",children:r.split(".").pop()||r})},{title:n("settings.metricsTable.forward.columns.model"),dataIndex:"model",key:"model",width:120},{title:n("settings.metricsTable.forward.columns.type"),dataIndex:"is_stream",key:"is_stream",width:80,render:r=>o.jsx(Ne,{color:r?"purple":"processing",children:n(r?"settings.metricsTable.forward.typeStream":"settings.metricsTable.forward.typeSync")})},{title:n("settings.metricsTable.forward.columns.status"),key:"status",width:100,render:(r,a)=>{const i=a.status==="success"?"success":a.status==="error"?"error":"default";return o.jsx(Am,{status:i,text:a.status_code?o.jsxs("span",{children:[a.status,o.jsxs(Wr,{type:"secondary",style:{marginLeft:4},children:["(",a.status_code,")"]})]}):a.status||"-"})}},{title:n("settings.metricsTable.forward.columns.tokens"),key:"tokens",width:100,render:(r,a)=>a.token_usage?o.jsx(Wr,{children:a.token_usage.total_tokens.toLocaleString()}):o.jsx(Wr,{type:"secondary",children:"-"})},{title:n("settings.metricsTable.forward.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",width:100,render:r=>CM(r)},{title:n("settings.metricsTable.forward.columns.started"),dataIndex:"started_at",key:"started_at",width:160,render:r=>o.jsx(Wr,{type:"secondary",style:{fontSize:12},children:MM(r)})},{title:n("settings.metricsTable.forward.columns.error"),dataIndex:"error",key:"error",width:200,render:r=>r?o.jsx(Wr,{type:"danger",ellipsis:!0,style:{maxWidth:180},children:r}):o.jsx(Wr,{type:"secondary",children:"-"})}];return o.jsx(ar,{rowKey:"forward_id",className:"lotus-metric-table",columns:s,dataSource:e,loading:t,size:"small",pagination:{pageSize:10,showSizeChanger:!0,showTotal:r=>n("settings.metricsTable.forward.totalRequests",{total:r}),pageSizeOptions:["10","20","50","100"]},scroll:{x:1200},locale:{emptyText:n("settings.metricsTable.forward.empty")}})},{useToken:EM}=Qe,RM=e=>{if(!e)return"-";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},Lp=({summary:e,loading:t})=>{const{t:n}=Ae(),{token:s}=EM();return t?o.jsx(dr,{active:!0,paragraph:{rows:1}}):o.jsxs(fs,{gutter:[s.marginSM,s.marginSM],children:[o.jsx(Et,{xs:24,sm:12,lg:8,xl:6,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(sn,{title:n("settings.unifiedMetricsCards.totalMemories"),value:(e==null?void 0:e.total_memories)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:6,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(sn,{title:n("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)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:6,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(sn,{title:n("settings.unifiedMetricsCards.memoryProjects"),value:(e==null?void 0:e.project_count)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:6,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(sn,{title:n("settings.unifiedMetricsCards.lastReindex"),value:RM(e==null?void 0:e.last_reindex_at),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:AM}=Ke,IM=({data:e,loading:t})=>{const{t:n}=Ae();return t?o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.charts.memoryTrendTitle"),children:o.jsx(dr,{active:!0,paragraph:{rows:5}})}):o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.charts.memoryTrendTitle"),children:e.length===0?o.jsx(Mn,{image:Mn.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noMemoryTrend")}):o.jsxs(o.Fragment,{children:[o.jsx(AM,{type:"secondary",children:n("settings.charts.memoryTrendDescription")}),o.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:o.jsx(Ko,{children:o.jsxs($b,{data:e,children:[o.jsx(Vi,{strokeDasharray:"3 3"}),o.jsx(Xi,{dataKey:"label",minTickGap:24}),o.jsx(Gi,{allowDecimals:!1}),o.jsx(Yo,{}),o.jsx(Nm,{}),o.jsx(Lo,{type:"monotone",dataKey:"total_memories",name:n("settings.charts.totalMemories"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),o.jsx(Lo,{type:"monotone",dataKey:"created_memories",name:n("settings.charts.createdMemories"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),o.jsx(Lo,{type:"monotone",dataKey:"updated_memories",name:n("settings.charts.updatedMemories"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{useToken:OM}=Qe,$M=e=>{const t=Math.floor(e/1e3),n=Math.floor(t/60),s=t%60;return n>0?`${n}m ${s}s`:`${s}s`},DM=e=>{const t=e.filter(s=>typeof s.duration_ms=="number"&&s.duration_ms>0);if(t.length===0)return 0;const n=t.reduce((s,r)=>s+(r.duration_ms??0),0);return Math.floor(n/t.length)},Fp=({summary:e,sessions:t,loading:n})=>{const{t:s}=Ae(),{token:r}=OM();if(n)return o.jsx(dr,{active:!0,paragraph:{rows:1}});const a=DM(t);return o.jsxs(fs,{gutter:[r.marginSM,r.marginSM],children:[o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(sn,{title:s("settings.metricsCards.syncMismatches",{defaultValue:"Sync Mismatches"}),value:(e==null?void 0:e.total_sync_mismatches)??0,precision:0,valueStyle:{color:((e==null?void 0:e.total_sync_mismatches)??0)>0?"var(--lotus-chart-danger)":"var(--lotus-chart-secondary)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(sn,{title:s("settings.metricsCards.totalSessions"),value:(e==null?void 0:e.total_sessions)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(sn,{title:s("settings.metricsCards.chatTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(sn,{title:s("settings.metricsCards.totalToolCalls"),value:(e==null?void 0:e.total_tool_calls)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(sn,{title:s("settings.metricsCards.avgSessionDuration"),value:a>0?$M(a):"-",valueStyle:{color:"var(--lotus-chart-accent)"}})})})]})},{Text:LM}=Ke,Np=["var(--lotus-chart-primary)","var(--lotus-chart-secondary)","var(--lotus-chart-accent)","var(--lotus-chart-purple)","var(--lotus-chart-cyan)"],FM=({data:e,loading:t})=>{const{t:n}=Ae();if(t)return o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.charts.modelDistribution"),children:o.jsx(dr,{active:!0,paragraph:{rows:5}})});const s=e.map(r=>({name:r.model,value:r.tokens.total_tokens}));return o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.charts.modelDistribution"),children:s.length===0?o.jsx(Mn,{image:Mn.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noModelMetrics")}):o.jsxs(o.Fragment,{children:[o.jsx(LM,{type:"secondary",children:n("settings.charts.modelDistributionDescription")}),o.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:o.jsx(Ko,{children:o.jsxs($_,{children:[o.jsx(D_,{data:s,cx:"50%",cy:"50%",outerRadius:90,fill:"var(--lotus-chart-primary)",dataKey:"value",nameKey:"name",label:!0,children:s.map((r,a)=>o.jsx(L_,{fill:Np[a%Np.length]},`${r.name}-${a}`))}),o.jsx(Yo,{})]})})})]})})},NM=e=>{if(!e)return"-";const t=new Date(e);return Number.isNaN(t.getTime())?"-":t.toLocaleString()},zM=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),n=Math.floor(t/60),s=t%60;if(n>=60){const r=Math.floor(n/60),a=n%60;return`${r}h ${a}m`}return n>0?`${n}m ${s}s`:`${s}s`},BM=e=>{switch(e){case"completed":return"success";case"running":return"processing";case"error":return"error";case"cancelled":return"warning";default:return"default"}},WM=({sessions:e,loading:t,onSelectSession:n})=>{const{t:s}=Ae(),r=[{title:s("settings.metricsTable.session.columns.session"),dataIndex:"session_id",key:"session_id",render:a=>o.jsx(bt,{title:a,children:o.jsxs("span",{children:[a.slice(0,8),"..."]})}),width:120},{title:s("settings.metricsTable.session.columns.model"),dataIndex:"model",key:"model",width:160},{title:s("settings.metricsTable.session.columns.status"),dataIndex:"status",key:"status",width:120,render:a=>o.jsx(Ne,{color:BM(a),children:a})},{title:s("settings.metricsTable.session.columns.started"),dataIndex:"started_at",key:"started_at",render:a=>NM(a),width:200,sorter:(a,i)=>new Date(a.started_at).getTime()-new Date(i.started_at).getTime(),defaultSortOrder:"descend"},{title:s("settings.metricsTable.session.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",render:a=>zM(a),width:120},{title:s("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:s("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:s("settings.metricsTable.session.columns.messages"),dataIndex:"message_count",key:"message_count",width:120,sorter:(a,i)=>a.message_count-i.message_count},{title:s("settings.metricsTable.session.columns.action"),key:"action",fixed:"right",width:120,render:(a,i)=>o.jsx(de,{type:"link",onClick:()=>{n(i.session_id)},children:s("settings.metricsTable.session.view")})}];return o.jsx(ar,{rowKey:"session_id",size:"small",className:"lotus-metric-table",columns:r,loading:t,dataSource:e,pagination:{pageSize:10,showSizeChanger:!1},scroll:{x:1100}})},{Text:qM}=Ke,zp={message_count:"Message Count",last_message_id:"Last Message",pending_question:"Pending Question"},UM=e=>zp[e]?zp[e]:e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" "),HM=({breakdown:e,loading:t})=>{const{t:n}=Ae();if(t)return o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),children:o.jsx(dr,{active:!0,paragraph:{rows:5}})});const s=Object.entries(e??{}).map(([r,a])=>({reason:r,label:n(`settings.syncMismatchReasons.${r}`,{defaultValue:UM(r)}),count:a})).sort((r,a)=>a.count-r.count);return o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),extra:o.jsx(qM,{type:"secondary",children:n("settings.metricsDashboard.syncMismatchBreakdownSubtitle",{defaultValue:"Grouped by execute sync mismatch reason"})}),children:s.length===0?o.jsx(Mn,{image:Mn.PRESENTED_IMAGE_SIMPLE,description:n("settings.metricsDashboard.noSyncMismatchBreakdown",{defaultValue:"No sync mismatches recorded for the selected range"})}):o.jsx("div",{style:{width:"100%",minWidth:0,height:280,minHeight:280},children:o.jsx(Ko,{children:o.jsxs(Fm,{data:s,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[o.jsx(Vi,{strokeDasharray:"3 3"}),o.jsx(Xi,{type:"number",allowDecimals:!1}),o.jsx(Gi,{dataKey:"label",type:"category",width:110}),o.jsx(Yo,{formatter:r=>[r.toLocaleString(),n("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})],labelFormatter:r=>n("settings.metricsDashboard.syncMismatchReasonLabel",{defaultValue:"Reason: {{label}}",label:r})}),o.jsx(bc,{dataKey:"count",fill:"var(--lotus-chart-danger)",radius:[0,6,6,0],name:n("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})})]})})})})},{Text:KM}=Ke,YM=({data:e,loading:t})=>{const{t:n}=Ae();return t?o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.charts.tokenUsageOverTime"),children:o.jsx(dr,{active:!0,paragraph:{rows:5}})}):o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.charts.tokenUsageOverTime"),children:e.length===0?o.jsx(Mn,{image:Mn.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noTokenUsage")}):o.jsxs(o.Fragment,{children:[o.jsx(KM,{type:"secondary",children:n("settings.charts.tokenUsageDescription")}),o.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:o.jsx(Ko,{children:o.jsxs($b,{data:e,children:[o.jsx(Vi,{strokeDasharray:"3 3"}),o.jsx(Xi,{dataKey:"label",minTickGap:24}),o.jsx(Gi,{allowDecimals:!1}),o.jsx(Yo,{}),o.jsx(Nm,{}),o.jsx(Lo,{type:"monotone",dataKey:"totalTokens",name:n("settings.charts.total"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),o.jsx(Lo,{type:"monotone",dataKey:"promptTokens",name:n("settings.charts.prompt"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),o.jsx(Lo,{type:"monotone",dataKey:"completionTokens",name:n("settings.charts.completion"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{Text:VM}=Ke,Sa=({title:e,subtitle:t,emptyText:n,color:s="var(--lotus-chart-primary)",data:r,loading:a,countLabel:i})=>{const{t:l}=Ae();return a?o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:e,children:o.jsx(dr,{active:!0,paragraph:{rows:5}})}):o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:e,children:r.length===0?o.jsx(Mn,{image:Mn.PRESENTED_IMAGE_SIMPLE,description:n}):o.jsxs(o.Fragment,{children:[t?o.jsx(VM,{type:"secondary",children:t}):null,o.jsx("div",{style:{width:"100%",minWidth:0,height:280,marginTop:t?12:0},children:o.jsx(Ko,{children:o.jsxs(Fm,{data:r,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[o.jsx(Vi,{strokeDasharray:"3 3"}),o.jsx(Xi,{type:"number",allowDecimals:!1}),o.jsx(Gi,{dataKey:"label",type:"category",width:110}),o.jsx(Yo,{formatter:c=>[c.toLocaleString(),i??l("settings.metricsDashboard.calls",{defaultValue:"Calls"})],labelFormatter:(c,u)=>{var p,g;const m=(g=(p=u==null?void 0:u[0])==null?void 0:p.payload)==null?void 0:g.meta;return m?`${c} · ${m}`:String(c)}}),o.jsx(bc,{dataKey:"count",fill:s,radius:[0,6,6,0],name:i??l("settings.metricsDashboard.calls",{defaultValue:"Calls"})})]})})})]})})},{useToken:XM}=Qe,Bp=({summary:e,loading:t})=>{const{t:n}=Ae(),{token:s}=XM();return t?o.jsx(dr,{active:!0,paragraph:{rows:1}}):o.jsxs(fs,{gutter:[s.marginSM,s.marginSM],children:[o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(sn,{title:n("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)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(sn,{title:n("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)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(sn,{title:n("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)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(sn,{title:n("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)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(sn,{title:n("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)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(sn,{title:n("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:Co}=Ke,{useToken:GM}=Qe,Wp=70,qp=130,Up=2,Hp=1.2,Kp=.65,Yp=45,Vp=1.8,Xp=e=>"date"in e?e.date:e.label,JM=(e,t)=>{if(t<=0||e<=0)return"var(--lotus-heat-0)";const n=e/t;return n>=.8?"var(--lotus-heat-4)":n>=.6?"var(--lotus-heat-3)":n>=.4?"var(--lotus-heat-2)":n>=.2?"var(--lotus-heat-1)":"var(--lotus-heat-0)"},wa=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),n=Math.floor(t/60),s=t%60;if(n>=60){const r=Math.floor(n/60),a=n%60;return`${r}h ${a}m`}return n>0?`${n}m ${s}s`:`${s}s`},Gp=e=>{if(!e)return"-";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},eu=e=>{const t=Object.entries(e??{}).sort((n,s)=>s[1]-n[1]);return t.length===0?"-":t.slice(0,6).map(([n,s])=>`${n}: ${s.toLocaleString()}`).join(" • ")},tu=(e,t=320)=>({width:"100%",display:"grid",gridTemplateColumns:`repeat(auto-fit, minmax(${t}px, 1fr))`,gap:e}),QM=()=>{const{t:e}=Ae(),{token:t}=GM(),n=ho(N=>N.themeMode)==="dark",[s,r]=f.useState(void 0),[a,i]=f.useState(void 0),[l,c]=f.useState(void 0),[u,m]=f.useState(30),[p,g]=f.useState("daily"),{summary:b,modelMetrics:S,sessions:x,timeline:k,memorySummary:j,memoryTimeline:w,sessionDetail:M,isLoading:_,isRefreshing:C,isSessionDetailLoading:D,error:A,refresh:B,loadSessionDetail:F,clearSessionDetail:O}=xM({filters:{startDate:s,endDate:a,model:l,days:u,granularity:p}}),{summary:R,endpointMetrics:I,requests:L,isLoading:U,isRefreshing:q,error:H,refresh:P}=yM({filters:{startDate:s,endDate:a,days:u,model:l}}),{data:W,isLoading:ne,isRefreshing:K,error:xe,refresh:se}=wM({filters:{startDate:s,endDate:a,days:u,model:l}}),fe=f.useMemo(()=>k.map(N=>({label:Xp(N),promptTokens:N.total_token_usage.prompt_tokens,completionTokens:N.total_token_usage.completion_tokens,totalTokens:N.total_token_usage.total_tokens})),[k]),Se=f.useMemo(()=>S.map(N=>({label:N.model,value:N.model})),[S]),me=f.useMemo(()=>{const N=k.map(be=>({label:Xp(be),sessions:be.total_sessions,tokens:be.total_token_usage.total_tokens})),le=N.reduce((be,De)=>Math.max(be,De.sessions),0);return{points:N,maxSessions:le}},[k]),ze=f.useMemo(()=>{const N=L.map(be=>be.duration_ms).filter(be=>typeof be=="number"&&be>0).sort((be,De)=>be-De);if(N.length===0)return null;const le=Math.ceil(N.length*.95)-1;return N[Math.max(0,Math.min(le,N.length-1))]},[L]),st=f.useMemo(()=>[{title:e("settings.metricsDashboard.roundColumns.round"),dataIndex:"round_id",key:"round_id",render:N=>`${N.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:N=>wa(N)},{title:e("settings.metricsDashboard.roundColumns.tokens"),key:"tokens",render:(N,le)=>le.token_usage.total_tokens.toLocaleString()},{title:e("settings.metricsDashboard.roundColumns.toolCalls"),key:"tool_calls",render:(N,le)=>le.tool_calls.length}],[e]),pt=f.useMemo(()=>{const N=(b==null?void 0:b.total_sessions)??0,le=(b==null?void 0:b.total_tokens.total_tokens)??0,be=(b==null?void 0:b.total_tool_calls)??0,De=(b==null?void 0:b.active_sessions)??0,Le=x.reduce((dn,on)=>dn+on.total_rounds,0),ue=(R==null?void 0:R.total_requests)??0,ye=(R==null?void 0:R.total_tokens.total_tokens)??0,qe=(R==null?void 0:R.failed_requests)??0,He=L.filter(dn=>dn.is_stream).length,ae=N>0?De/N*100:0,ke=ue>0?qe/ue*100:0,pe=L.length>0?He/L.length*100:0,Re=le/Wp+be*Up,Je=le/qp+be*Hp,Mt=Math.max(0,Re-Je)*Kp,xt=Math.max(Je,Re-Mt),Ft=wa(Mt*6e4),Dt=Number((Mt/(8*60)).toFixed(2)),Ue=Re>0?Math.min(Yp,Number((Mt/Re*100).toFixed(1))):0,rn=xt>0?Math.min(Vp,Number((Re/xt).toFixed(2))):1;return[{title:e("settings.metricsDashboard.compactStats.avgTokensPerSession"),value:N>0?Math.round(le/N):0},{title:e("settings.metricsDashboard.compactStats.estimatedTimeSaved"),value:Ft},{title:e("settings.metricsDashboard.compactStats.estimatedEfficiencyLift"),value:Ue,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.estimatedSpeedMultiplier"),value:rn,suffix:e("settings.metricsDashboard.multiplierSuffix")},{title:e("settings.metricsDashboard.compactStats.estimatedSavedWorkdays"),value:Dt},{title:e("settings.metricsDashboard.compactStats.avgRoundsPerSession"),value:N>0?Number((Le/N).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.toolCallsPerSession"),value:N>0?Number((be/N).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.activeSessionRate"),value:Number(ae.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.avgTokensPerForward"),value:ue>0?Math.round(ye/ue):0},{title:e("settings.metricsDashboard.compactStats.forwardErrorRate"),value:Number(ke.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.streamingRatio"),value:Number(pe.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.p95ForwardLatency"),value:wa(ze)},{title:e("settings.metricsDashboard.compactStats.modelCoverage"),value:S.length},{title:e("settings.metricsDashboard.compactStats.endpointCoverage"),value:I.length}]},[I.length,L,R,S.length,ze,x,b,e]),Kt=f.useMemo(()=>{const N=(R==null?void 0:R.total_requests)??0,le=(R==null?void 0:R.failed_requests)??0,be=L.filter(ue=>ue.is_stream).length,De=L.length>0?be/L.length*100:0,Le=N>0?le/N*100:0;return[{title:e("settings.metricsDashboard.forward.performance.p95Latency",{defaultValue:"P95 Latency"}),value:wa(ze)},{title:e("settings.metricsDashboard.forward.performance.errorRate",{defaultValue:"Error Rate"}),value:Number(Le.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.streamingRatio",{defaultValue:"Streaming Ratio"}),value:Number(De.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.endpointCoverage",{defaultValue:"Endpoint Coverage"}),value:I.length}]},[I.length,L,R,ze,e]),Oe=f.useMemo(()=>W?[{label:e("settings.metricsDashboard.skillsAndMcp.mix.coreTools",{defaultValue:"Core Tools"}),count:W.core_tool_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.skillLoads",{defaultValue:"Skill Loads"}),count:W.skill_load_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.mcpCalls",{defaultValue:"MCP Calls"}),count:W.mcp_calls}].filter(N=>N.count>0):[],[e,W]),Wt=f.useMemo(()=>((W==null?void 0:W.top_skills)??[]).map(N=>({label:N.skill_id,count:N.count})),[W]),Xe=f.useMemo(()=>((W==null?void 0:W.top_mcp_servers)??[]).map(N=>({label:N.server_id,count:N.count,meta:e("settings.metricsDashboard.skillsAndMcp.meta.uniqueTools",{defaultValue:"{{count}} tools",count:N.unique_tools})})),[e,W]),_e=f.useMemo(()=>((W==null?void 0:W.top_mcp_tools)??[]).map(N=>({label:N.tool_name,count:N.count,meta:N.server_id})),[W]),Ye=f.useMemo(()=>((W==null?void 0:W.top_core_tools)??[]).map(N=>({label:N.name,count:N.count})),[W]),ot=M==null?void 0:M.session,Lt=C||q||K;return o.jsxs(he,{direction:"vertical",size:t.marginMD,style:{width:"100%"},children:[A?o.jsx(Ht,{type:"error",showIcon:!0,message:A}):null,H?o.jsx(Ht,{type:"error",showIcon:!0,message:H}):null,xe?o.jsx(Ht,{type:"error",showIcon:!0,message:xe}):null,o.jsx(Ce,{size:"small",title:e("settings.metricsDashboard.filtersTitle"),extra:o.jsx(de,{icon:o.jsx(cr,{}),loading:Lt,onClick:()=>{B(),P(),se()},children:e("settings.metricsDashboard.refresh")}),children:o.jsxs(he,{wrap:!0,children:[o.jsx(df,{placeholder:e("settings.metricsDashboard.startDate"),onChange:N=>{r(N?N.format("YYYY-MM-DD"):void 0)}}),o.jsx(df,{placeholder:e("settings.metricsDashboard.endDate"),onChange:N=>{i(N?N.format("YYYY-MM-DD"):void 0)}}),o.jsx(St,{allowClear:!0,style:{minWidth:180},placeholder:e("settings.metricsDashboard.model"),value:l,options:Se,onChange:N=>{c(N)}}),o.jsx(St,{style:{width:120},value:u,options:[7,14,30,90].map(N=>({label:e("settings.metricsDashboard.daysOption",{value:N}),value:N})),onChange:N=>{m(N)}}),o.jsx(St,{style:{width:140},value:p,options:[{label:e("settings.metricsDashboard.granularity.daily"),value:"daily"},{label:e("settings.metricsDashboard.granularity.weekly"),value:"weekly"},{label:e("settings.metricsDashboard.granularity.monthly"),value:"monthly"}],onChange:N=>{g(N)}})]})}),o.jsx(Ce,{size:"small",title:e("settings.metricsDashboard.dashboardTitle"),children:o.jsx(Di,{size:"small",destroyInactiveTabPane:!0,items:[{key:"overview",label:e("settings.metricsDashboard.tabs.overview"),children:o.jsxs(he,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[o.jsx(Fp,{summary:b,sessions:x,loading:_}),o.jsx(Dp,{summary:R,loading:U}),o.jsx(Bp,{summary:W,loading:ne}),o.jsx(Lp,{summary:j,loading:_}),o.jsxs(Ce,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.derivedMetricsTitle"),extra:o.jsx(Co,{type:"secondary",children:e("settings.metricsDashboard.derivedMetricsSubtitle")}),children:[o.jsx(fs,{gutter:[t.marginSM,t.marginSM],children:pt.map(N=>o.jsx(Et,{xs:24,sm:12,md:8,xl:6,children:o.jsx("div",{style:{borderRadius:t.borderRadiusSM,padding:t.paddingXS,background:n?"rgba(255, 255, 255, 0.05)":"rgba(255, 255, 255, 0.82)",border:n?"1px solid rgba(255,255,255,0.08)":"1px solid rgba(148,163,184,0.18)"},children:o.jsx(sn,{title:N.title,value:N.value,suffix:N.suffix,valueStyle:{fontSize:t.fontSizeHeading4}})})},N.title))}),o.jsx(Co,{type:"secondary",style:{display:"block",marginTop:t.marginXS},children:e("settings.metricsDashboard.efficiencyHint",{manualTpm:Wp,manualToolMinutes:Up,assistedTpm:qp,assistedToolMinutes:Hp,realization:Math.round(Kp*100),maxLift:Yp,maxMultiplier:Vp})})]})]})},{key:"chat",label:e("settings.metricsDashboard.tabs.chat",{defaultValue:"Chat"}),children:o.jsxs(he,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[o.jsx(Fp,{summary:b,sessions:x,loading:_}),o.jsxs("div",{style:tu(t.marginSM,360),children:[o.jsx(YM,{data:fe,loading:_}),o.jsx(FM,{data:S,loading:_})]}),o.jsxs("div",{style:tu(t.marginSM,360),children:[o.jsx(HM,{breakdown:b==null?void 0:b.sync_mismatch_breakdown,loading:_}),o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.activityHeatmapTitle"),children:me.points.length===0?o.jsx(Co,{type:"secondary",children:e("settings.metricsDashboard.noActivity")}):o.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))",gap:t.marginXS},children:me.points.map(N=>o.jsxs("div",{style:{borderRadius:t.borderRadiusSM,padding:t.paddingXS,background:JM(N.sessions,me.maxSessions),minHeight:64,color:N.sessions>0?"var(--lotus-metric-text-strong)":t.colorTextSecondary},children:[o.jsx("div",{style:{fontSize:12,lineHeight:1.2},children:N.label}),o.jsx("div",{style:{fontWeight:600,marginTop:4},children:e("settings.metricsDashboard.sessionsCount",{count:N.sessions})}),o.jsx("div",{style:{fontSize:12},children:e("settings.metricsDashboard.tokensAmount",{value:N.tokens.toLocaleString()})})]},N.label))})})]})]})},{key:"skills-and-mcp",label:e("settings.metricsDashboard.tabs.skillsAndMcp",{defaultValue:"Skills & MCP"}),children:o.jsxs(he,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[o.jsx(Bp,{summary:W,loading:ne}),o.jsxs("div",{style:tu(t.marginSM,360),children:[o.jsx(Sa,{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:Oe,loading:ne,color:"var(--lotus-chart-primary)"}),o.jsx(Sa,{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:Wt,loading:ne,color:"var(--lotus-chart-purple)"}),o.jsx(Sa,{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:Xe,loading:ne,color:"var(--lotus-chart-cyan)"}),o.jsx(Sa,{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:_e,loading:ne,color:"var(--lotus-chart-accent)"}),o.jsx(Sa,{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:Ye,loading:ne,color:"var(--lotus-chart-secondary)"})]})]})},{key:"forward",label:e("settings.metricsDashboard.tabs.forward",{defaultValue:"Forward"}),children:o.jsxs(he,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[o.jsx(Dp,{summary:R,loading:U}),o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.forward.performanceTitle",{defaultValue:"Forward Performance"}),children:o.jsx(fs,{gutter:[t.marginSM,t.marginSM],children:Kt.map(N=>o.jsx(Et,{xs:24,sm:12,xl:6,children:o.jsx("div",{style:{borderRadius:t.borderRadiusSM,padding:t.paddingXS,background:n?"rgba(255, 255, 255, 0.05)":"rgba(255, 255, 255, 0.82)",border:n?"1px solid rgba(255,255,255,0.08)":"1px solid rgba(148,163,184,0.18)"},children:o.jsx(sn,{title:N.title,value:N.value,suffix:N.suffix,valueStyle:{fontSize:t.fontSizeHeading4}})})},N.title))})}),o.jsx(kM,{data:I,loading:U})]})},{key:"memory",label:e("settings.metricsDashboard.tabs.memory",{defaultValue:"Memory"}),children:o.jsxs(he,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[o.jsx(Lp,{summary:j,loading:_}),o.jsx(IM,{data:w,loading:_}),o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.memory.breakdownTitle",{defaultValue:"Memory Breakdown"}),children:o.jsxs(Fn,{size:"small",bordered:!0,column:1,children:[o.jsx(Fn.Item,{label:e("settings.metricsDashboard.memory.byType",{defaultValue:"By Type"}),children:eu(j==null?void 0:j.by_type)}),o.jsx(Fn.Item,{label:e("settings.metricsDashboard.memory.byStatus",{defaultValue:"By Status"}),children:eu(j==null?void 0:j.by_status)}),o.jsx(Fn.Item,{label:e("settings.metricsDashboard.memory.byScope",{defaultValue:"By Scope"}),children:eu(j==null?void 0:j.by_scope)}),o.jsx(Fn.Item,{label:e("settings.metricsDashboard.memory.lastDream",{defaultValue:"Last Dream"}),children:Gp(j==null?void 0:j.last_dream_at)}),o.jsx(Fn.Item,{label:e("settings.metricsDashboard.memory.lastReindex",{defaultValue:"Last Reindex"}),children:Gp(j==null?void 0:j.last_reindex_at)})]})})]})},{key:"records",label:e("settings.metricsDashboard.tabs.records"),children:o.jsx(Di,{size:"small",destroyInactiveTabPane:!0,items:[{key:"sessions",label:e("settings.metricsDashboard.sessionsTabLabel",{count:x.length}),children:o.jsx(Ce,{size:"small",extra:o.jsx(Co,{type:"secondary",children:e("settings.metricsDashboard.sessionsHint")}),children:o.jsx(WM,{sessions:x,loading:_,onSelectSession:N=>{F(N)}})})},{key:"forward-requests",label:e("settings.metricsDashboard.forwardTabLabel",{count:L.length}),children:o.jsx(Ce,{size:"small",children:o.jsx(PM,{requests:L,loading:U})})}]})}]})}),o.jsx(Xn,{title:e("settings.metricsDashboard.sessionMetricsTitle"),open:!!M,onCancel:O,onOk:O,width:960,destroyOnClose:!0,children:D?o.jsx(Co,{children:e("settings.metricsDashboard.loadingSessionDetails")}):ot?o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:t.marginMD,children:[o.jsxs(Fn,{size:"small",bordered:!0,column:2,children:[o.jsx(Fn.Item,{label:e("settings.metricsDashboard.sessionDetail.sessionId"),span:2,children:ot.session_id}),o.jsx(Fn.Item,{label:e("settings.metricsDashboard.sessionDetail.model"),children:ot.model}),o.jsx(Fn.Item,{label:e("settings.metricsDashboard.sessionDetail.status"),children:ot.status}),o.jsx(Fn.Item,{label:e("settings.metricsDashboard.sessionDetail.duration"),children:wa(ot.duration_ms)}),o.jsx(Fn.Item,{label:e("settings.metricsDashboard.sessionDetail.messages"),children:ot.message_count}),o.jsx(Fn.Item,{label:e("settings.metricsDashboard.sessionDetail.totalTokens"),children:ot.total_token_usage.total_tokens.toLocaleString()}),o.jsx(Fn.Item,{label:e("settings.metricsDashboard.sessionDetail.toolCalls"),children:ot.tool_call_count})]}),o.jsx(ar,{rowKey:"round_id",size:"small",columns:st,dataSource:M.rounds,pagination:{pageSize:6,showSizeChanger:!1}})]}):o.jsx(Co,{type:"secondary",children:e("settings.metricsDashboard.noDetail")})})]})},{Text:Ll}=Ke,{useToken:ZM}=Qe,eP=e=>{const t=e==null?void 0:e.hooks,n=t==null?void 0:t.image_fallback,s=String((n==null?void 0:n.mode)||"placeholder").trim().toLowerCase();return s==="error"||s==="ocr"||s==="vision"?s:"placeholder"},tP=e=>{const t=e==null?void 0:e.hooks,n=t==null?void 0:t.image_fallback,s=n==null?void 0:n.enabled;return typeof s=="boolean"?s:!1},nP=()=>{const{t:e}=Ae(),{token:t}=ZM(),[n,s]=Cr.useMessage(),[r,a]=f.useState(!1),[i,l]=f.useState(!0),[c,u]=f.useState("placeholder"),m=f.useMemo(()=>[{label:e("settings.hooksTab.mode.placeholder"),value:"placeholder"},{label:e("settings.hooksTab.mode.error"),value:"error"},{label:e("settings.hooksTab.mode.ocr"),value:"ocr"},{label:e("settings.hooksTab.mode.vision"),value:"vision"}],[e]),p=f.useCallback(async()=>{a(!0);try{const x=await Vt.getBambooConfig();l(tP(x)),u(eP(x))}catch(x){n.error(x instanceof Error?x.message:e("settings.hooksTab.loadFailed"))}finally{a(!1)}},[n,e]),g=f.useCallback(async(x,k)=>{await Vt.setBambooConfig({hooks:{image_fallback:{enabled:x,mode:k}}})},[]),b=f.useCallback(async x=>{a(!0);try{await g(x,c),n.success(e(x?"settings.hooksTab.enabled":"settings.hooksTab.disabled")),await p()}catch(k){n.error(k instanceof Error?k.message:e("settings.hooksTab.updateFailed"))}finally{a(!1)}},[p,c,n,g,e]),S=f.useCallback(async x=>{var k;a(!0);try{await g(i,x),n.success(e("settings.hooksTab.modeUpdated",{mode:((k=m.find(j=>j.value===x))==null?void 0:k.label)??x})),await p()}catch(j){n.error(j instanceof Error?j.message:e("settings.hooksTab.modeUpdateFailed"))}finally{a(!1)}},[i,p,m,n,g,e]);return f.useEffect(()=>{p()},[p]),o.jsxs(ve,{vertical:!0,gap:t.marginLG,children:[s,o.jsx(Ce,{size:"small",loading:r,children:o.jsxs(ve,{vertical:!0,gap:t.marginXS,children:[o.jsx(Ll,{strong:!0,children:e("settings.hooksTab.title")}),o.jsxs(ve,{align:"center",justify:"space-between",children:[o.jsx(Ll,{children:e("settings.hooksTab.enableImagePreflight")}),o.jsx(ln,{checked:i,onChange:b})]}),o.jsxs(ve,{align:"center",justify:"space-between",children:[o.jsx(Ll,{children:e("settings.hooksTab.modeLabel")}),o.jsx(St,{style:{width:180},value:c,options:m,onChange:S,disabled:!i})]}),o.jsx(Ll,{type:"secondary",style:{fontSize:t.fontSizeSM},children:e("settings.hooksTab.description")})]})})]})},{Text:kn}=Ke,er=os.getInstance();function sP(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 rP=[{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 vn(e){return String(e??"").trim()||void 0}function oP(e){return(e==null?void 0:e.type)==="interval"?e.every_seconds:null}function tS(e){return{type:"interval",every_seconds:e}}function aP(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 iP(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 lP(e){switch(e){case"allow":return"allow overlap";case"skip":return"skip overlap";case"queue_one":default:return"queue one"}}function cP(e){var t;return(t=e.state)!=null&&t.next_fire_at?String(e.state.next_fire_at):"-"}function dP(e){var t,n;return(t=e.state)!=null&&t.last_success_at?String(e.state.last_success_at):(n=e.state)!=null&&n.last_finished_at?String(e.state.last_finished_at):"-"}function uP(e){var t,n,s,r;return((t=e.state)==null?void 0:t.running_run_count)>0?{color:"processing",label:"running",detail:`${e.state.running_run_count} active`}:(((n=e.state)==null?void 0:n.queued_run_count)||0)>0?{color:"gold",label:"queued",detail:`${e.state.queued_run_count} pending`}:(((s=e.state)==null?void 0:s.consecutive_failures)||0)>0?{color:"error",label:"failing",detail:`${e.state.consecutive_failures} consecutive failures`}:e.enabled?(r=e.state)!=null&&r.last_success_at?{color:"success",label:"healthy",detail:"last run succeeded"}:{color:"default",label:"idle"}:{color:"default",label:"disabled"}}function mP(e){const t=vn(e);if(!t)return{days:[],invalid:!1};const s=t.split(/[\s,]+/).filter(Boolean).map(i=>Number(i)),r=s.some(i=>!Number.isInteger(i)||i<1||i>31);return{days:Array.from(new Set(s.filter(i=>Number.isInteger(i)&&i>=1&&i<=31))),invalid:r}}function Jp(e){switch(e.trigger_type){case"interval":{const t=Number(e.interval_seconds||0);return t<=0?{errorKey:"settings.schedulesTab.validation.intervalRequired"}:{trigger:tS(t)}}case"daily":{const t=e.daily_hour,n=e.daily_minute;return t==null||n==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"daily",hour:t,minute:n,second:0}}}case"weekly":{const t=e.weekly_weekdays||[],n=e.weekly_hour,s=e.weekly_minute;return t.length===0?{errorKey:"settings.schedulesTab.validation.weekdaysRequired"}:n==null||s==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"weekly",weekdays:t,hour:n,minute:s,second:0}}}case"monthly":{const{days:t,invalid:n}=mP(e.monthly_days);if(n)return{errorKey:"settings.schedulesTab.validation.invalidMonthDays"};if(t.length===0)return{errorKey:"settings.schedulesTab.validation.monthDaysRequired"};const s=e.monthly_hour,r=e.monthly_minute;return s==null||r==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"monthly",days:t,hour:s,minute:r,second:0}}}case"cron":{const t=vn(e.cron_expr);return t?{trigger:{type:"cron",expr:t}}:{errorKey:"settings.schedulesTab.validation.cronRequired"}}default:return{errorKey:"settings.schedulesTab.validation.triggerRequired"}}}function Qp(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 hP(e){var n,s,r,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:((n=e.misfire_policy)==null?void 0:n.type)||"run_once",overlap_policy:e.overlap_policy||"queue_one",system_prompt:((s=e.run_config)==null?void 0:s.system_prompt)||"",task_message:((r=e.run_config)==null?void 0:r.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 fP(){const{t:e}=Ae(),[t,n]=Cr.useMessage(),[s,r]=f.useState(!1),[a,i]=f.useState([]),[l,c]=f.useState({open:!1,scheduleId:null,sessions:[],loading:!1}),[u,m]=f.useState({open:!1,scheduleId:null,runs:[],loading:!1}),[p,g]=f.useState({open:!1,schedule:null,saving:!1}),b=rr(O=>O.close),[S]=Pe.useForm(),[x]=Pe.useForm(),k=Pe.useWatch("trigger_type",S),j=Pe.useWatch("misfire_policy",S),w=Pe.useWatch("trigger_type",x),M=Pe.useWatch("misfire_policy",x),_=f.useCallback(async()=>{r(!0);try{const O=await er.listSchedules();i(O.schedules||[])}catch(O){console.error("[Schedules] Failed to load schedules:",O),t.error(e("settings.schedulesTab.loadFailed"))}finally{r(!1)}},[t,e]);f.useEffect(()=>{_()},[_]);const C=[{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")}],D=[{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")}],A=[{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")}],B=(O,R)=>o.jsxs(o.Fragment,{children:[o.jsxs(ve,{gap:12,wrap:"wrap",children:[o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.name"),name:"name",rules:[{required:!0,message:e("settings.schedulesTab.validation.nameRequired")}],style:{flex:"1 1 260px"},children:o.jsx(et,{})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.triggerType"),name:"trigger_type",rules:[{required:!0,message:e("settings.schedulesTab.validation.triggerRequired")}],style:{width:220},children:o.jsx(St,{options:C})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",style:{width:120},children:o.jsx(ln,{})})]}),O==="interval"?o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.intervalSeconds"),name:"interval_seconds",rules:[{required:!0,message:e("settings.schedulesTab.validation.intervalRequired")}],style:{width:220},children:o.jsx(Zt,{min:1,style:{width:"100%"}})}):null,O==="daily"?o.jsxs(ve,{gap:12,wrap:"wrap",children:[o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"daily_hour",style:{width:180},children:o.jsx(Zt,{min:0,max:23,style:{width:"100%"}})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"daily_minute",style:{width:180},children:o.jsx(Zt,{min:0,max:59,style:{width:"100%"}})})]}):null,O==="weekly"?o.jsxs(o.Fragment,{children:[o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.weeklyWeekdays"),name:"weekly_weekdays",style:{minWidth:320},children:o.jsx(St,{mode:"multiple",options:rP})}),o.jsxs(ve,{gap:12,wrap:"wrap",children:[o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"weekly_hour",style:{width:180},children:o.jsx(Zt,{min:0,max:23,style:{width:"100%"}})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"weekly_minute",style:{width:180},children:o.jsx(Zt,{min:0,max:59,style:{width:"100%"}})})]})]}):null,O==="monthly"?o.jsxs(o.Fragment,{children:[o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.monthlyDays"),name:"monthly_days",style:{minWidth:320},children:o.jsx(et,{placeholder:e("settings.schedulesTab.form.monthlyDaysPlaceholder")})}),o.jsxs(ve,{gap:12,wrap:"wrap",children:[o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"monthly_hour",style:{width:180},children:o.jsx(Zt,{min:0,max:23,style:{width:"100%"}})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"monthly_minute",style:{width:180},children:o.jsx(Zt,{min:0,max:59,style:{width:"100%"}})})]})]}):null,O==="cron"?o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.cronExpr"),name:"cron_expr",children:o.jsx(et,{placeholder:e("settings.schedulesTab.form.cronExprPlaceholder")})}):null,o.jsxs(ve,{gap:12,wrap:"wrap",children:[o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.timezone"),name:"timezone",style:{flex:"1 1 240px"},children:o.jsx(et,{placeholder:e("settings.schedulesTab.form.timezonePlaceholder")})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.startAt"),name:"start_at",style:{flex:"1 1 240px"},children:o.jsx(et,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.endAt"),name:"end_at",style:{flex:"1 1 240px"},children:o.jsx(et,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})})]}),o.jsxs(ve,{gap:12,wrap:"wrap",children:[o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.misfirePolicy"),name:"misfire_policy",style:{flex:"1 1 240px"},children:o.jsx(St,{options:D})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.overlapPolicy"),name:"overlap_policy",style:{flex:"1 1 240px"},children:o.jsx(St,{options:A})})]}),R==="catch_up_window"?o.jsxs(ve,{gap:12,wrap:"wrap",children:[o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxRuns"),name:"catch_up_window_max_runs",style:{width:220},children:o.jsx(Zt,{min:1,style:{width:"100%"}})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxLatenessSeconds"),name:"catch_up_window_max_lateness_seconds",style:{width:260},children:o.jsx(Zt,{min:1,style:{width:"100%"}})})]}):null,o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.taskMessage"),name:"task_message",children:o.jsx(et.TextArea,{rows:3,placeholder:e("settings.schedulesTab.form.taskMessagePlaceholder")})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.systemPrompt"),name:"system_prompt",children:o.jsx(et.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})}),o.jsxs(ve,{gap:12,wrap:"wrap",children:[o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.model"),name:"model",style:{flex:"1 1 240px"},children:o.jsx(et,{placeholder:e("settings.schedulesTab.form.modelPlaceholder")})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.workspacePath"),name:"workspace_path",style:{flex:"1 1 320px"},children:o.jsx(et,{placeholder:e("settings.schedulesTab.optional")})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.autoExecute"),name:"auto_execute",valuePropName:"checked",style:{width:160},children:o.jsx(ln,{})})]}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.enhancePrompt"),name:"enhance_prompt",children:o.jsx(et.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})})]}),F=f.useMemo(()=>[{title:e("settings.schedulesTab.columns.name"),key:"name",render:(O,R)=>o.jsxs(ve,{vertical:!0,gap:6,children:[o.jsx(kn,{strong:!0,children:R.name}),o.jsxs(ve,{gap:6,wrap:"wrap",children:[o.jsx(Ne,{children:aP(R.trigger)}),R.timezone?o.jsx(Ne,{color:"blue",children:R.timezone}):null,o.jsx(Ne,{children:iP(R.misfire_policy)}),o.jsx(Ne,{children:lP(R.overlap_policy)})]})]})},{title:e("settings.schedulesTab.columns.status"),key:"status",render:(O,R)=>{const I=uP(R);return o.jsxs(ve,{vertical:!0,gap:4,children:[o.jsx(Ne,{color:I.color,children:I.label}),I.detail?o.jsx(kn,{type:"secondary",children:I.detail}):null]})}},{title:e("settings.schedulesTab.columns.activity"),key:"activity",render:(O,R)=>{var I,L,U,q;return o.jsxs(ve,{vertical:!0,gap:2,children:[o.jsxs(kn,{type:"secondary",children:["queued: ",((I=R.state)==null?void 0:I.queued_run_count)??0]}),o.jsxs(kn,{type:"secondary",children:["running: ",((L=R.state)==null?void 0:L.running_run_count)??0]}),o.jsxs(kn,{type:"secondary",children:["ok: ",((U=R.state)==null?void 0:U.total_success_count)??0]}),o.jsxs(kn,{type:"secondary",children:["fail: ",((q=R.state)==null?void 0:q.total_failure_count)??0]})]})}},{title:e("settings.schedulesTab.columns.nextRun"),key:"next_run_at",render:(O,R)=>o.jsx(kn,{type:"secondary",children:cP(R)})},{title:e("settings.schedulesTab.columns.lastRun"),key:"last_run_at",render:(O,R)=>o.jsx(kn,{type:"secondary",children:dP(R)})},{title:e("settings.schedulesTab.columns.autoExecute"),key:"auto_execute",render:(O,R)=>{var I,L;return o.jsx(kn,{type:(I=R.run_config)!=null&&I.auto_execute?void 0:"secondary",children:(L=R.run_config)!=null&&L.auto_execute?e("settings.schedulesTab.yes"):e("settings.schedulesTab.no")})}},{title:e("settings.schedulesTab.columns.model"),key:"model",render:(O,R)=>{var I;return o.jsx(kn,{type:"secondary",children:(I=R.run_config)!=null&&I.model?String(R.run_config.model):"-"})}},{title:e("settings.schedulesTab.columns.enabled"),key:"enabled",render:(O,R)=>o.jsx(ln,{checked:R.enabled,onChange:async I=>{try{await er.patchSchedule(R.id,{enabled:I}),await _()}catch(L){console.error("[Schedules] Failed to toggle:",L),t.error(e("settings.schedulesTab.updateFailed"))}}})},{title:e("settings.schedulesTab.columns.actions"),key:"actions",render:(O,R)=>{const I=o.jsx(Zt,{min:1,value:oP(R.trigger)??void 0,disabled:R.trigger.type!=="interval",onChange:async L=>{const U=typeof L=="number"?L:null;if(!(!U||U<=0))try{await er.patchSchedule(R.id,{trigger:tS(U)}),await _()}catch(q){console.error("[Schedules] Failed to patch interval:",q),t.error(e("settings.schedulesTab.updateFailed"))}}});return o.jsxs(ve,{vertical:!0,gap:8,children:[o.jsxs(ve,{gap:8,wrap:"wrap",children:[o.jsx(de,{size:"small",onClick:()=>{g({open:!0,schedule:R,saving:!1}),x.setFieldsValue(hP(R))},children:e("settings.schedulesTab.actions.edit")}),o.jsx(de,{size:"small",onClick:async()=>{try{await er.runScheduleNow(R.id),t.success(e("settings.schedulesTab.enqueuedRun")),await _()}catch(L){console.error("[Schedules] Failed to run now:",L),t.error(e("settings.schedulesTab.runNowFailed"))}},children:e("settings.schedulesTab.actions.runNow")}),o.jsx(de,{size:"small",onClick:async()=>{c(L=>({...L,open:!0,scheduleId:R.id,loading:!0,sessions:[]}));try{const L=await er.listScheduleSessions(R.id);c(U=>({...U,open:!0,scheduleId:R.id,loading:!1,sessions:(L.sessions||[]).map(q=>({id:q.id,title:q.title,updated_at:q.updated_at}))}))}catch(L){console.error("[Schedules] Failed to list sessions:",L),t.error(e("settings.schedulesTab.loadSessionsFailed")),c(U=>({...U,loading:!1}))}},children:e("settings.schedulesTab.actions.sessions")}),o.jsx(de,{size:"small",onClick:async()=>{m(L=>({...L,open:!0,scheduleId:R.id,loading:!0,runs:[]}));try{const L=await er.listScheduleRuns(R.id);m(U=>({...U,open:!0,scheduleId:R.id,loading:!1,runs:L.runs||[]}))}catch(L){console.error("[Schedules] Failed to list runs:",L),t.error(e("settings.schedulesTab.loadRunsFailed")),m(U=>({...U,loading:!1}))}},children:e("settings.schedulesTab.actions.runs")}),o.jsx(de,{danger:!0,size:"small",onClick:async()=>{try{await er.deleteSchedule(R.id),t.success(e("settings.schedulesTab.deleted")),await _()}catch(L){console.error("[Schedules] Failed to delete:",L),t.error(e("settings.schedulesTab.deleteFailed"))}},children:e("settings.schedulesTab.actions.delete")})]}),o.jsxs(ve,{gap:8,align:"center",wrap:"wrap",children:[o.jsx(kn,{type:"secondary",children:e("settings.schedulesTab.columns.intervalSeconds")}),R.trigger.type==="interval"?I:o.jsx(bt,{title:e("settings.schedulesTab.nonIntervalReadOnly"),children:o.jsx("span",{children:I})})]})]})}}],[x,t,_,e]);return o.jsxs(ve,{vertical:!0,gap:16,children:[n,o.jsx(Ce,{title:e("settings.schedulesTab.createTitle"),className:"lotus-settings-card",children:o.jsxs(Pe,{form:S,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 O=>{try{const R=!!O.auto_execute,I=vn(O.task_message),L=vn(O.model);if(R&&!I){t.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:U,errorKey:q}=Jp(O);if(!U){t.error(e(q||"settings.schedulesTab.validation.triggerRequired"));return}await er.createSchedule({name:String(O.name||"").trim(),trigger:U,timezone:vn(O.timezone),start_at:vn(O.start_at),end_at:vn(O.end_at),misfire_policy:Qp(O),overlap_policy:O.overlap_policy,enabled:!!O.enabled,run_config:{system_prompt:vn(O.system_prompt),task_message:I,model:L,workspace_path:vn(O.workspace_path),enhance_prompt:vn(O.enhance_prompt),auto_execute:R}}),t.success(e("settings.schedulesTab.created")),S.resetFields(),await _()}catch(R){console.error("[Schedules] Failed to create schedule:",R),t.error(e("settings.schedulesTab.createFailed"))}},children:[B(k,j),o.jsx(de,{type:"primary",htmlType:"submit",children:e("settings.schedulesTab.actions.create")})]})}),o.jsx(Ce,{title:e("settings.schedulesTab.listTitle"),className:"lotus-settings-card",extra:o.jsx(de,{onClick:()=>void _(),loading:s,children:e("settings.schedulesTab.actions.refresh")}),children:o.jsx(ar,{rowKey:"id",columns:F,dataSource:a,loading:s,pagination:{pageSize:10},scroll:{x:1500}})}),o.jsx(Xn,{title:e("settings.schedulesTab.scheduleSessionsTitle"),open:l.open,onCancel:()=>c(O=>({...O,open:!1,scheduleId:null})),footer:null,children:l.loading?o.jsx(kn,{type:"secondary",children:e("settings.schedulesTab.loading")}):o.jsx(ve,{vertical:!0,gap:8,children:l.sessions.length===0?o.jsx(kn,{type:"secondary",children:e("settings.schedulesTab.noSessionsYet")}):l.sessions.map(O=>o.jsxs(ve,{justify:"space-between",align:"center",children:[o.jsxs(ve,{vertical:!0,style:{minWidth:0},children:[o.jsx(kn,{strong:!0,ellipsis:!0,children:O.title}),o.jsxs(kn,{type:"secondary",ellipsis:!0,children:[O.id," • ",O.updated_at]})]}),o.jsx(de,{size:"small",onClick:()=>{Qc(O.id,{forceRefreshIndex:!0,forceLoadHistory:!0,subscribeIfRunning:!0,forceSubscribe:!0}),b()},children:e("settings.schedulesTab.actions.open")})]},O.id))})}),o.jsx(Xn,{title:e("settings.schedulesTab.scheduleRunsTitle"),open:u.open,onCancel:()=>m(O=>({...O,open:!1,scheduleId:null})),footer:null,width:960,children:u.loading?o.jsx(kn,{type:"secondary",children:e("settings.schedulesTab.loading")}):u.runs.length===0?o.jsx(kn,{type:"secondary",children:e("settings.schedulesTab.noRunsYet")}):o.jsx(ar,{rowKey:"run_id",pagination:{pageSize:8},dataSource:u.runs,columns:[{title:e("settings.schedulesTab.runHistory.columns.status"),key:"status",render:(O,R)=>o.jsx(Ne,{color:sP(R.status),children:R.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:(O,R)=>R.started_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.completedAt"),key:"completed_at",render:(O,R)=>R.completed_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.session"),key:"session_id",render:(O,R)=>R.session_id||"-"},{title:e("settings.schedulesTab.runHistory.columns.duration"),key:"execution_duration_ms",render:(O,R)=>R.execution_duration_ms!=null?`${R.execution_duration_ms}ms`:"-"},{title:e("settings.schedulesTab.runHistory.columns.outcome"),key:"outcome_reason",render:(O,R)=>R.outcome_reason||(R.was_catch_up?"catch-up":"-")}]})}),o.jsx(Xn,{title:e("settings.schedulesTab.editTitle"),open:p.open,onCancel:()=>g({open:!1,schedule:null,saving:!1}),okText:e("settings.schedulesTab.actions.save"),confirmLoading:p.saving,onOk:()=>x.submit(),forceRender:!0,children:o.jsx(Pe,{form:x,layout:"vertical",onFinish:async O=>{const R=p.schedule;if(!R)return;const I=!!O.auto_execute,L=vn(O.task_message),U=vn(O.model);if(I&&!L){t.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:q,errorKey:H}=Jp(O);if(!q){t.error(e(H||"settings.schedulesTab.validation.triggerRequired"));return}g(P=>({...P,saving:!0}));try{await er.patchSchedule(R.id,{name:String(O.name||"").trim()||void 0,enabled:!!O.enabled,trigger:q,timezone:vn(O.timezone),start_at:vn(O.start_at),end_at:vn(O.end_at),misfire_policy:Qp(O),overlap_policy:O.overlap_policy,run_config:{system_prompt:vn(O.system_prompt),task_message:L,model:U,workspace_path:vn(O.workspace_path),enhance_prompt:vn(O.enhance_prompt),auto_execute:I}}),t.success(e("settings.schedulesTab.updated")),g({open:!1,schedule:null,saving:!1}),await _()}catch(P){console.error("[Schedules] Failed to patch schedule:",P),t.error(e("settings.schedulesTab.updateFailed")),g(W=>({...W,saving:!1}))}},children:B(w,M)})})]})}const{Text:_a}=Ke,ka=os.getInstance();function pP(){const{t:e}=Ae(),{modal:t,message:n}=en.useApp(),s=G(S=>S.chats),r=G(S=>S.currentSessionId),a=G(S=>S.refreshChats),i=G(S=>S.loadChats),l=G(S=>S.loadChatHistory),[c,u]=f.useState(!0),[m,p]=f.useState(!1),g=f.useMemo(()=>r?s.find(S=>S.id===r)??null:null,[s,r]),b=async S=>{if(!m){p(!0);try{await S()}finally{p(!1)}}};return o.jsxs(ve,{vertical:!0,gap:16,children:[o.jsx(Ce,{size:"small",title:e("settings.sessionsTab.currentSessionTitle"),children:g?o.jsxs(ve,{vertical:!0,gap:4,children:[o.jsx(_a,{strong:!0,ellipsis:!0,children:g.title}),o.jsxs(_a,{type:"secondary",ellipsis:!0,children:[e("settings.sessionsTab.id"),": ",g.id," ","•"," ",e("settings.sessionsTab.kind"),": ",g.kind]}),o.jsx(ve,{gap:8,wrap:"wrap",style:{marginTop:8},children:o.jsx(de,{danger:!0,loading:m,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 b(async()=>{await ka.clearSession(g.id),await l(g.id),await a(),n.success(e("settings.sessionsTab.sessionCleared"))})}})},children:e("settings.sessionsTab.clearMessages")})})]}):o.jsx(_a,{type:"secondary",children:e("settings.sessionsTab.noActiveSession")})}),o.jsxs(Ce,{size:"small",title:e("settings.sessionsTab.bulkCleanupTitle"),children:[o.jsxs(ve,{align:"center",gap:8,style:{marginBottom:12},children:[o.jsx(_a,{children:e("settings.sessionsTab.keepPinned")}),o.jsx(ln,{checked:c,onChange:u})]}),o.jsxs(ve,{gap:8,wrap:"wrap",children:[o.jsx(de,{danger:!0,loading:m,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 b(async()=>{await ka.cleanupSessions("all",c),await i(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteAll")}),o.jsx(de,{danger:!0,loading:m,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 b(async()=>{await ka.cleanupSessions("empty",c),await i(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteEmpty")}),o.jsx(de,{danger:!0,loading:m,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 b(async()=>{await ka.cleanupSessions("children",c),await i(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteChildren")})]})]}),o.jsxs(Ce,{size:"small",title:e("settings.sessionsTab.devResetTitle"),children:[o.jsx(_a,{type:"secondary",children:e("settings.sessionsTab.devResetDescription")}),o.jsx(ve,{style:{marginTop:12},children:o.jsx(de,{danger:!0,type:"primary",loading:m,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 b(async()=>{await ka.devResetSessions(),await i(),n.success(e("settings.sessionsTab.devResetDone"))})}})},children:e("settings.sessionsTab.devResetAction")})})]})]})}const{Text:Fl,Paragraph:gP}=Ke,yP=({open:e,onCancel:t,onComplete:n,onCopyCode:s,completingAuth:r,copiedUserCode:a,deviceCodeInfo:i,timeRemaining:l,token:c})=>{const{t:u}=Ae();return o.jsx(Xn,{title:u("settings.providerTab.copilotAuthModalTitle"),open:e,onCancel:t,footer:[o.jsx(de,{onClick:t,children:u("settings.providerTab.cancel")},"cancel"),o.jsx(de,{type:"primary",onClick:n,loading:r,children:u("settings.providerTab.completedAuthorization")},"complete")],children:i&&o.jsxs(he,{direction:"vertical",size:"large",style:{width:"100%"},children:[o.jsx(Ht,{message:u("settings.providerTab.browserOpened"),description:o.jsxs("ol",{children:[o.jsx("li",{children:u("settings.providerTab.authStep1")}),o.jsx("li",{children:u("settings.providerTab.authStep2")}),o.jsx("li",{children:u("settings.providerTab.authStep3")})]}),type:"info"}),o.jsx(Ce,{size:"small",className:"lotus-settings-card",children:o.jsxs(he,{direction:"vertical",style:{width:"100%"},children:[o.jsx(Fl,{type:"secondary",children:u("settings.providerTab.visitUrl")}),o.jsx(he,{children:o.jsx(Fl,{copyable:{text:i.verification_uri},children:i.verification_uri})})]})}),o.jsx(Ce,{style:{textAlign:"center",background:c.colorFillTertiary,borderColor:c.colorBorderSecondary},children:o.jsxs(he,{direction:"vertical",style:{width:"100%"},children:[o.jsx(Fl,{type:"secondary",children:u("settings.providerTab.enterCode")}),o.jsxs(he,{children:[o.jsx(Fl,{style:{color:c.colorText,fontSize:"32px",fontFamily:"monospace",fontWeight:"bold",letterSpacing:"4px"},children:i.user_code}),o.jsx(de,{icon:a?o.jsx(ir,{}):o.jsx(vs,{}),onClick:s,type:a?"default":"primary",children:u(a?"settings.providerTab.copied":"settings.providerTab.copyCode")})]}),o.jsx("div",{style:{marginTop:8},children:o.jsxs(Ne,{color:l<60?"error":l<180?"warning":"success",children:[o.jsx(As,{style:{marginRight:4}}),"Expires in ",Math.floor(l/60),":",(l%60).toString().padStart(2,"0")]})})]})}),o.jsx(gP,{type:"secondary",children:u("settings.providerTab.afterContinueHint")})]})})},nu={copilot:"GitHub Copilot",openai:"OpenAI",anthropic:"Anthropic",gemini:"Google Gemini",bodhi:"Bodhi"},bP=[{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"}],xP=[{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"}],vP=[{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"}],SP=[{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4o-mini",label:"GPT-4o Mini"}];function nS({value:e,onChange:t,disabled:n}){const s=Ct(l=>l.catalog);f.useEffect(()=>{s||Ct.getState().loadCatalog()},[s]);const r=f.useMemo(()=>{if(!(s!=null&&s.models))return[];const l={};for(const m of s.models){const p=m.reference.provider;l[p]||(l[p]={display:m.provider_display_name,models:[]}),l[p].models.push(m)}const c=[];return Object.keys(l).forEach((m,p)=>{const g=l[m];p>0&&c.push({type:"divider"}),c.push({type:"group",label:g.display,children:g.models.map(b=>({key:`${b.reference.provider}/${b.reference.model}`,label:o.jsxs(he,{size:4,children:[o.jsx("span",{children:b.display_name}),b.capabilities.supports_vision&&o.jsx(Ne,{color:"blue",style:{fontSize:10,lineHeight:"16px",padding:"0 3px"},children:"Vision"})]})}))})}),c},[s]),a=e?`${e.provider}/${e.model}`:void 0,i=f.useCallback(l=>{const[c,...u]=l.key.split("/"),m=u.join("/");c&&m&&t({provider:c,model:m})},[t]);return o.jsx(he,{size:4,"data-tour-id":"model-picker",children:o.jsx(lo,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:a?[a]:[],items:r,style:{maxHeight:"50vh",overflowY:"auto"},onClick:i},disabled:n,children:o.jsx(de,{type:"text",size:"small",disabled:n,style:{minWidth:146,padding:"0 12px",height:36,borderRadius:18},title:e?`${e.provider}/${e.model}`:"Select model",children:o.jsxs(he,{size:4,children:[o.jsx("span",{style:{maxWidth:150,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13},children:e?`${e.provider}/${e.model}`:"Select model"}),o.jsx(Gn,{style:{fontSize:10}})]})})})})}const{Password:Zp}=et,{Text:ss,Paragraph:su}=Ke,Nl=["openai","anthropic","gemini","copilot","bodhi"],zl=()=>null,wP=e=>{var n,s;if(!e||typeof e!="object")return!1;const t=e;return!!((n=t.provider)!=null&&n.trim()&&((s=t.model)!=null&&s.trim()))},eg=e=>o.jsxs(he,{direction:"vertical",size:4,children:[o.jsxs(ss,{type:"secondary",children:[e("settings.providerTab.responsesOnlyHelp1")," ",o.jsx(ss,{code:!0,children:"/responses"}),"."]}),o.jsx(ss,{type:"secondary",children:e("settings.providerTab.responsesOnlyHelp2")})]}),_P=()=>{const{t:e}=Ae(),{token:t}=Qe.useToken(),{message:n}=en.useApp(),[s]=Pe.useForm(),[r,a]=f.useState(!1),[i,l]=f.useState(!1),[c,u]=f.useState("copilot"),[m,p]=f.useState(!1),[g,b]=f.useState(null),[S,x]=f.useState(!1),[k,j]=f.useState(!1),[w,M]=f.useState(null),[_,C]=f.useState(!1),[D,A]=f.useState(!1),[B,F]=f.useState(0),[O,R]=f.useState(!1),[I,L]=f.useState([]),[U,q]=f.useState(!1),[H,P]=f.useState("idle"),[W,ne]=f.useState(null);f.useEffect(()=>{if(H!=="success")return;const ue=setTimeout(()=>{P("idle"),ne(null)},2e3);return()=>clearTimeout(ue)},[H]),f.useEffect(()=>{if(!_||!w){F(0);return}F(w.expires_in);const ue=setInterval(()=>{F(ye=>ye<=1?(clearInterval(ue),0):ye-1)},1e3);return()=>clearInterval(ue)},[_,w]);const K=f.useCallback(async()=>{var ue;try{a(!0);const ye=await Yn.getProviderConfig();let qe=ye.defaults;if(!((ue=qe==null?void 0:qe.chat)!=null&&ue.model)&&ye.provider&&ye.providers){const ke=ye.provider,pe=ye.providers[ke],Re=pe==null?void 0:pe.model;Re&&(qe={chat:{provider:ke,model:Re}})}const He={provider:ye.provider,defaults:qe,providers:ye.providers||{},features:ye.features};Jt("[Provider]","Loaded provider config:",He);const ae={...He.providers||{}};Nl.forEach(ke=>{const pe=ae[ke];pe&&pe.request_overrides&&typeof pe.request_overrides=="object"&&(pe.request_overrides_json=JSON.stringify(pe.request_overrides,null,2))}),u(He.provider),s.setFieldsValue({...He,providers:ae,defaults:He.defaults}),p(!0)}catch(ye){n.error(e("settings.providerTab.loadConfigFailed")),console.error("Failed to load provider config:",ye)}finally{a(!1)}},[s,e]),xe=f.useCallback(async()=>{try{const ue=await Yn.getEnvVars();L(ue.entries||[])}catch(ue){console.warn("Failed to load env vars for provider overrides:",ue)}},[]),se=f.useCallback(async()=>{try{x(!0);const ue=await Yn.getCopilotAuthStatus();b(ue)}catch(ue){console.error("Failed to check Copilot auth status:",ue),b({authenticated:!1,message:e("settings.providerTab.checkStatusFailed")})}finally{x(!1)}},[e]);f.useEffect(()=>{K(),xe(),Ct.getState().loadCatalog(),se()},[K,xe,se]);const fe=async()=>{try{j(!0);const ue=await Yn.startCopilotAuth();M(ue),C(!0)}catch(ue){n.error(e("settings.providerTab.startCopilotAuthFailed")),console.error("Failed to start Copilot authentication:",ue)}finally{j(!1)}},Se=async()=>{if(w)try{A(!0),await Yn.completeCopilotAuth({device_code:w.device_code,interval:w.interval||5,expires_in:w.expires_in}),n.success(e("settings.providerTab.copilotAuthSuccess")),C(!1),M(null),await se()}catch(ue){n.error(e("settings.providerTab.completeAuthFailed")),console.error("Authentication completion failed:",ue)}finally{A(!1)}},me=async()=>{if(w)try{await Ss(w.user_code),R(!0),n.success(e("settings.providerTab.userCodeCopied")),setTimeout(()=>R(!1),2e3)}catch{n.error(`${e("settings.providerTab.copyCodeFailedPrefix")} ${w.user_code}`)}},ze=async()=>{try{j(!0),await Yn.logoutCopilot(),n.success(e("settings.providerTab.logoutSuccess")),await se()}catch(ue){n.error(e("settings.providerTab.logoutFailed")),console.error("Failed to logout:",ue)}finally{j(!1)}},st=f.useCallback(async()=>{q(!0);try{const ue=await Yn.fetchCatalogModels();await Ct.getState().loadCatalog();const ye=ue.fetched.filter(He=>He.models&&He.models.length>0).length;ue.fetched.filter(He=>He.error).length>0?n.warning(e("settings.providerTab.fetchModelsPartialSuccess",{success:ye,total:ue.fetched.length})):n.success(e("settings.providerTab.fetchModelsSuccess",{count:ye}))}catch{n.error(e("settings.providerTab.fetchModelsFailed"))}finally{q(!1)}},[e]),pt=ue=>d0(ue)||ue instanceof Error?ue.message:e("settings.providerTab.unknownError"),Kt=ue=>{s.setFields([{name:["provider"],errors:[]},{name:["providers",ue,"api_key"],errors:[]},{name:["defaults","chat"],errors:[]}])},Oe=ue=>{const ye=ue.trim();return ye?ye.includes(".")?ye.split(".").filter(Boolean):ye==="provider"?["provider"]:ye==="provider/providers"?["provider"]:null:null},Wt=(ue,ye)=>{if(!ue.length)return;const qe=ue.map(He=>{const ae=Oe(He.path);return ae?{name:ae,errors:[He.message]}:He.message.toLowerCase().includes("api key")?{name:["providers",ye,"api_key"],errors:[He.message]}:{name:["provider"],errors:[He.message]}}).filter((He,ae,ke)=>ke.findIndex(pe=>JSON.stringify(pe.name)===JSON.stringify(He.name))===ae);qe.length&&s.setFields(qe)},Xe=async ue=>{var qe;const ye=ue.provider||c;Kt(ye);try{const ae=await Is.getInstance().validateBambooConfigPatch({provider:ue.provider,providers:ue.providers||{},defaults:ue.defaults});if(ae.valid)return{valid:!0};const ke=((qe=ae.errors)==null?void 0:qe.provider)||[];Wt(ke,ye);const pe=ke[0];return{valid:!1,message:(pe==null?void 0:pe.message)||e("settings.providerTab.invalidConfig")}}catch(He){return console.warn("Config validation failed, falling back to save:",He),{valid:!0}}},_e=async(ue,ye)=>{var qe,He;try{a(!0);const ae={provider:ue.provider,defaults:ue.defaults,providers:{...ue.providers||{}},features:ue.features},ke=(qe=ae.defaults)==null?void 0:qe.chat;if(!wP(ke)){const Ft=e("settings.providerTab.selectModelRequired");if(s.setFields([{name:["defaults","chat"],errors:[Ft]}]),(ye==null?void 0:ye.showMessage)!==!1&&n.error(Ft),ye!=null&&ye.throwOnError)throw new Error(Ft);return}const pe=ae.providers;for(const Ft of Nl){const Dt=pe[Ft];if(!Dt)continue;const Ue=Dt.request_overrides_json;if(typeof Ue!="string")continue;const rn=Ue.trim();if(!rn)delete Dt.request_overrides;else try{Dt.request_overrides=JSON.parse(rn)}catch(dn){const on=`Invalid request_overrides JSON for ${Ft}: ${dn.message}`;if(s.setFields([{name:["providers",Ft,"request_overrides_json"],errors:[on]}]),(ye==null?void 0:ye.showMessage)!==!1&&n.error(on),ye!=null&&ye.throwOnError)throw dn;return}delete Dt.request_overrides_json}const Re={...ae.providers||{}},Je=ae.provider,gt=(He=ae.defaults)==null?void 0:He.chat;if(gt!=null&&gt.model&&Je){const Ft=Re[Je]||{};Re[Je]={...Ft,model:gt.model}}const Mt={provider:ae.provider,defaults:ae.defaults,providers:Re,features:ae.features},xt=await Xe(ae);if(!xt.valid){const Ft=xt.message||e("settings.providerTab.invalidConfig");if((ye==null?void 0:ye.showMessage)!==!1&&n.error(`${e("settings.providerTab.invalidConfigPrefix")}: ${Ft}`),ye!=null&&ye.throwOnError)throw new Error(Ft);return}Jt("[Provider]","Saving provider config:",Mt),await Yn.saveProviderConfig(Mt),(ye==null?void 0:ye.showMessage)!==!1&&n.success(e("settings.providerTab.saveConfigSuccess"))}catch(ae){const ke=pt(ae);if((ye==null?void 0:ye.showMessage)!==!1&&n.error(ke?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${ke}`:e("settings.providerTab.saveConfigFailed")),console.error("Failed to save configuration:",ae),ye!=null&&ye.throwOnError)throw ae}finally{a(!1)}},Ye=async ue=>{var ye,qe,He,ae,ke;try{l(!0);const{useProviderStore:pe}=await Bn(async()=>{const{useProviderStore:on}=await Promise.resolve().then(()=>f0);return{useProviderStore:on}},void 0,import.meta.url),{useAppStore:Re}=await Bn(async()=>{const{useAppStore:on}=await Promise.resolve().then(()=>Mk);return{useAppStore:on}},void 0,import.meta.url),Je=(ye=pe.getState().providerConfig.defaults)==null?void 0:ye.chat;await pe.getState().loadProviderConfig();const gt=(qe=pe.getState().providerConfig.defaults)==null?void 0:qe.chat;pe.getState().setSelectedModelRef(null);const Mt=Re.getState().currentSessionId,xt=Mt&&Re.getState().chats.find(on=>on.id===Mt)||null,Ft=Je?`${Je.provider}/${Je.model}`:null,Dt=gt?`${gt.provider}/${gt.model}`:null,Ue=(He=xt==null?void 0:xt.config)!=null&&He.model_ref?`${xt.config.model_ref.provider}/${xt.config.model_ref.model}`:null,rn=((ke=(ae=xt==null?void 0:xt.config)==null?void 0:ae.model)==null?void 0:ke.trim())||null;!!(Mt&&(xt!=null&&xt.config)&&gt&&Dt!==Ft&&(!Ue||Ue===Ft)&&(!rn||rn===(Je==null?void 0:Je.model)))&&Mt&&(xt!=null&&xt.config)&&gt&&Re.getState().updateSession(Mt,{config:{...xt.config,model:gt.model,model_ref:gt}}),(ue==null?void 0:ue.showMessage)!==!1&&n.success(e("settings.providerTab.applyConfigSuccess"))}catch(pe){const Re=pt(pe);if((ue==null?void 0:ue.showMessage)!==!1&&n.error(Re?`${e("settings.providerTab.applyConfigErrorPrefix")}: ${Re}`:e("settings.providerTab.applyConfigFailed")),console.error("Failed to apply configuration:",pe),ue!=null&&ue.throwOnError)throw pe}finally{l(!1)}},ot=async ue=>{try{const ye=s.getFieldsValue(!0);await _e(ye,{throwOnError:!0}),await Ye({throwOnError:!0})}catch{}},Lt=async(ue,ye)=>{if(!(ue==="chat"&&!ye)&&H!=="saving"){P("saving"),ne(null);try{const qe=s.getFieldsValue(!0),He=qe.defaults;if(!(He!=null&&He.chat))throw new Error(e("settings.providerTab.selectModelRequired"));qe.defaults={...He,[ue]:ye},await _e(qe,{showMessage:!1,throwOnError:!0}),await Ye({showMessage:!1,throwOnError:!0}),P("success"),n.success(e("settings.providerTab.modelUpdated"))}catch(qe){const He=pt(qe);P("error"),ne(He),n.error(He?`${e("settings.providerTab.updateModelErrorPrefix")}: ${He}`:e("settings.providerTab.updateModelFailed"))}}},N=f.useCallback(ue=>{const ye=s.getFieldValue(["providers",ue]);return ye?ue==="copilot"?(g==null?void 0:g.authenticated)??!1:!!ye.api_key:!1},[s,g]),le=()=>{const ue=ye=>{const qe=s.getFieldValue(["defaults",ye]);return o.jsx(nS,{value:qe,disabled:H==="saving",onChange:He=>{s.setFieldValue(["defaults",ye],He),Lt(ye,He)}})};return o.jsxs(Ce,{size:"small",title:e("settings.providerTab.modelPreferences","模型偏好"),style:{marginBottom:16},children:[o.jsx(Pe.Item,{name:["defaults","chat"],noStyle:!0,preserve:!0,children:o.jsx(zl,{})}),o.jsx(Pe.Item,{name:["defaults","fast"],noStyle:!0,preserve:!0,children:o.jsx(zl,{})}),o.jsx(Pe.Item,{name:["defaults","sub_session"],noStyle:!0,preserve:!0,children:o.jsx(zl,{})}),o.jsx(Pe.Item,{name:["defaults","vision"],noStyle:!0,preserve:!0,children:o.jsx(zl,{})}),o.jsxs(he,{direction:"vertical",size:16,style:{width:"100%"},children:[o.jsxs("div",{children:[o.jsx(ss,{strong:!0,children:e("settings.providerTab.defaultModel")}),o.jsx("div",{style:{marginTop:8},children:ue("chat")})]}),o.jsxs("div",{children:[o.jsx(ss,{strong:!0,children:e("settings.providerTab.fastModel")}),o.jsx("div",{style:{marginTop:8},children:ue("fast")}),o.jsx(ss,{type:"secondary",children:e("settings.providerTab.fastModelHelp")})]}),o.jsxs("div",{children:[o.jsx(ss,{strong:!0,children:e("settings.providerTab.subSessionModel","Sub Session Model (Optional)")}),o.jsx("div",{style:{marginTop:8},children:ue("sub_session")}),o.jsx(ss,{type:"secondary",children:e("settings.providerTab.subSessionModelHelp","Default model for new Sub Sessions. Uses Fast Model when not set.")})]}),o.jsxs("div",{children:[o.jsx(ss,{strong:!0,children:e("settings.providerTab.visionModel")}),o.jsx("div",{style:{marginTop:8},children:ue("vision")}),o.jsx(ss,{type:"secondary",children:e("settings.providerTab.visionModelHelp")})]})]})]})},be=ue=>{const ye=I.map(He=>He.name);return o.jsx(Pe.Item,{name:["providers",ue,"request_overrides_json"],label:"Advanced Request Overrides (JSON)",extra:o.jsxs(he,{direction:"vertical",size:4,children:[o.jsx(ss,{type:"secondary",children:"Customize provider request headers/body patch rules."}),o.jsxs(ss,{type:"secondary",children:["Env var injection:"," ",o.jsx(ss,{code:!0,children:'{ "type": "env_ref", "name": "YOUR_ENV_NAME" }'})]}),ye.length>0&&o.jsx(he,{wrap:!0,size:[6,6],children:ye.map(He=>o.jsx(Ne,{children:He},He))})]}),children:o.jsx(et.TextArea,{autoSize:{minRows:8,maxRows:20},placeholder:`{
135
+ "common": {
136
+ "headers": {
137
+ "x-request-id": { "type": "generated", "generator": "uuid" },
138
+ "x-tenant": { "type": "env_ref", "name": "TENANT_ID" }
139
+ }
140
+ },
141
+ "rules": [
142
+ {
143
+ "model_pattern": "gpt-5*",
144
+ "scope": {
145
+ "body_patch": [
146
+ { "path": "metadata.trace_id", "op": "set", "value": { "type": "generated", "generator": "uuid" } }
147
+ ]
148
+ }
149
+ }
150
+ ]
151
+ }`,style:{fontFamily:"SFMono-Regular, Menlo, Monaco, Consolas, monospace"}})})},De=ue=>{switch(ue){case"openai":return o.jsxs(o.Fragment,{children:[o.jsx(Pe.Item,{name:["providers","openai","api_key"],label:e("settings.providerTab.openaiApiKey"),rules:[{required:!0,message:e("settings.providerTab.openaiApiKeyRequired")}],children:o.jsx(et.Password,{"data-testid":"api-key-input",placeholder:"sk-...",prefix:o.jsx(kl,{})})}),o.jsx(Pe.Item,{name:["providers","openai","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.openaiBaseUrlHelp"),children:o.jsx(et,{placeholder:"https://api.openai.com/v1"})}),o.jsx(Pe.Item,{name:["providers","openai","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:eg(e),children:o.jsx(St,{mode:"tags",placeholder:'e.g. "gpt-5.3-codex", "gpt-5*"',tokenSeparators:[","," ",`
152
+ `," "]})}),o.jsx(zn,{dashed:!0}),be("openai")]});case"anthropic":return o.jsxs(o.Fragment,{children:[o.jsx(Pe.Item,{name:["providers","anthropic","api_key"],label:e("settings.providerTab.anthropicApiKey"),rules:[{required:!0,message:e("settings.providerTab.anthropicApiKeyRequired")}],children:o.jsx(Zp,{placeholder:"sk-ant-...",prefix:o.jsx(kl,{})})}),o.jsx(Pe.Item,{name:["providers","anthropic","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.anthropicBaseUrlHelp"),children:o.jsx(et,{placeholder:"https://api.anthropic.com/v1"})}),o.jsx(Pe.Item,{name:["providers","anthropic","max_tokens"],label:e("settings.providerTab.maxTokensOptional"),extra:e("settings.providerTab.maxTokensHelp"),children:o.jsx(et,{type:"number",placeholder:"4096",min:1,max:1e5})}),o.jsx(zn,{dashed:!0}),be("anthropic")]});case"gemini":return o.jsxs(o.Fragment,{children:[o.jsx(Pe.Item,{name:["providers","gemini","api_key"],label:e("settings.providerTab.geminiApiKey"),rules:[{required:!0,message:e("settings.providerTab.geminiApiKeyRequired")}],children:o.jsx(Zp,{placeholder:"AIza...",prefix:o.jsx(kl,{})})}),o.jsx(Pe.Item,{name:["providers","gemini","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.geminiBaseUrlHelp"),children:o.jsx(et,{placeholder:"https://generativelanguage.googleapis.com/v1beta"})}),o.jsx(zn,{dashed:!0}),be("gemini")]});case"copilot":return o.jsxs(o.Fragment,{children:[o.jsxs(Ce,{size:"small",style:{marginBottom:16},title:e("settings.providerTab.authStatusTitle"),extra:S?o.jsx(Rs,{size:"small"}):g!=null&&g.authenticated?o.jsx(Ne,{icon:o.jsx(ir,{}),color:"success",children:e("settings.providerTab.authenticated")}):o.jsx(Ne,{icon:o.jsx(pc,{}),color:"error",children:e("settings.providerTab.notAuthenticated")}),children:[(g==null?void 0:g.message)&&o.jsx(su,{type:"secondary",style:{marginBottom:16},children:g.message}),o.jsxs(he,{children:[g!=null&&g.authenticated?o.jsx(de,{danger:!0,icon:o.jsx(n_,{}),onClick:ze,loading:k,children:e("settings.providerTab.logoutCopilot")}):o.jsx(de,{type:"primary",icon:o.jsx(s_,{}),onClick:fe,loading:k,children:e("settings.providerTab.authenticateCopilot")}),o.jsx(de,{onClick:se,loading:S,children:e("settings.providerTab.refreshStatus")})]})]}),o.jsx(Pe.Item,{name:["providers","copilot","headless_auth"],label:e("settings.providerTab.headlessAuth"),valuePropName:"checked",extra:e("settings.providerTab.headlessAuthHelp"),children:o.jsx(ln,{})}),o.jsx(Pe.Item,{name:["providers","copilot","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:eg(e),children:o.jsx(St,{mode:"tags",placeholder:'e.g. "gpt-5.3-codex", "gpt-5*"',tokenSeparators:[","," ",`
153
+ `," "]})}),o.jsx(zn,{dashed:!0}),be("copilot"),o.jsxs(su,{type:"secondary",children:[e("settings.providerTab.copilotUsageTitle"),o.jsxs("ul",{style:{marginTop:8,marginBottom:0},children:[o.jsx("li",{children:e("settings.providerTab.copilotUsageStep1")}),o.jsx("li",{children:e("settings.providerTab.copilotUsageStep2")}),o.jsx("li",{children:e("settings.providerTab.copilotUsageStep3")})]})]})]});case"bodhi":return o.jsxs(o.Fragment,{children:[o.jsx(Pe.Item,{name:["providers","bodhi","api_key"],label:"Bodhi API Key",rules:[{required:!0,message:"API key is required"}],children:o.jsx(et.Password,{"data-testid":"bodhi-api-key-input",placeholder:"bhi_sk_...",prefix:o.jsx(kl,{})})}),o.jsx(Pe.Item,{name:["providers","bodhi","base_url"],label:"Base URL",extra:"Your Bodhi Server endpoint address",children:o.jsx(et,{placeholder:"http://localhost:8080"})}),o.jsx(Pe.Item,{name:["providers","bodhi","target_provider"],label:"Target Provider",extra:"Which upstream provider to route through Bodhi",children:o.jsxs(St,{placeholder:"openai",allowClear:!0,children:[o.jsx(St.Option,{value:"openai",children:"OpenAI"}),o.jsx(St.Option,{value:"anthropic",children:"Anthropic"}),o.jsx(St.Option,{value:"gemini",children:"Gemini"})]})}),o.jsx(Pe.Item,{name:["providers","bodhi","reasoning_effort"],label:"Reasoning Effort (optional)",children:o.jsxs(St,{placeholder:"Default",allowClear:!0,children:[o.jsx(St.Option,{value:"low",children:"Low"}),o.jsx(St.Option,{value:"medium",children:"Medium"}),o.jsx(St.Option,{value:"high",children:"High"}),o.jsx(St.Option,{value:"xhigh",children:"Extra High"}),o.jsx(St.Option,{value:"max",children:"Max"})]})}),o.jsx(zn,{dashed:!0}),be("bodhi")]});default:return null}},Le=ue=>{const ye=N(ue),qe=nu[ue];return o.jsxs(he,{size:"small",children:[o.jsx("span",{style:{fontWeight:500},children:qe}),ye?o.jsx(Ne,{color:"success",style:{fontSize:11},children:e("settings.providerTab.authenticated")}):o.jsx(Ne,{color:"default",style:{fontSize:11},children:e("settings.providerTab.providerNotConfigured")})]})};return o.jsxs(Ce,{title:e("settings.providerTab.title"),loading:r&&!m,className:"lotus-settings-card",children:[o.jsx(su,{type:"secondary",children:e("settings.providerTab.description")}),o.jsx(zn,{}),o.jsxs(Pe,{form:s,layout:"vertical",onFinish:ot,disabled:r&&!m,children:[o.jsx(Pe.Item,{name:"provider",label:e("settings.providerTab.activeProvider"),rules:[{required:!0,message:e("settings.providerTab.selectProviderRequired")}],children:o.jsx(St,{"data-testid":"provider-select",size:"large",children:Object.keys(nu).map(ue=>o.jsx(St.Option,{value:ue,children:nu[ue]},ue))})}),o.jsx(zn,{}),o.jsxs("div",{style:{marginBottom:16},children:[o.jsx(de,{icon:o.jsx(cr,{}),onClick:st,loading:U,children:e(U?"settings.providerTab.fetchingAllModels":"settings.providerTab.fetchAllModels")}),H==="saving"&&o.jsx(Rs,{size:"small",style:{marginLeft:8}}),H==="success"&&o.jsx(ir,{style:{color:"var(--lotus-chart-secondary)",marginLeft:8}}),H==="error"&&o.jsx(bt,{title:W,children:o.jsx(pc,{style:{color:"var(--lotus-chart-danger)",marginLeft:8}})})]}),le(),o.jsx(lr,{defaultActiveKey:Nl.filter(ue=>N(ue)),ghost:!0,style:{marginBottom:16},items:Nl.map(ue=>({key:ue,label:Le(ue),children:De(ue)}))}),o.jsx(zn,{}),o.jsx(he,{size:"middle",children:o.jsx(de,{"data-testid":"save-api-settings",type:"primary",htmlType:"submit",icon:o.jsx(Bc,{}),loading:r||i,size:"large",children:e("settings.providerTab.saveAndApply")})})]}),o.jsx(yP,{open:_,onCancel:()=>C(!1),onComplete:Se,onCopyCode:me,completingAuth:D,copiedUserCode:O,deviceCodeInfo:w,timeRemaining:B,token:t})]})},{Text:tg}=Ke,kP=({skill:e,disabled:t=!1,busy:n=!1,onToggleDisabled:s})=>{const{t:r}=Ae(),{token:a}=Qe.useToken();return o.jsx(Ce,{title:o.jsxs(he,{size:a.marginXS,wrap:!0,style:{width:"100%",justifyContent:"space-between"},children:[o.jsxs(he,{size:a.marginXS,wrap:!0,children:[o.jsx("span",{children:e.name}),t&&o.jsx(Ne,{color:"default",children:r("components.skillManager.disabledTag")}),e.license&&o.jsxs(Ne,{color:"processing",children:["License: ",e.license]})]}),s&&o.jsx(ln,{checked:!t,loading:n,onChange:i=>s(e.id,!i),checkedChildren:r("components.skillManager.switchEnabled"),unCheckedChildren:r("components.skillManager.switchDisabled")})]}),styles:{body:{padding:a.paddingMD}},style:{opacity:t?.72:1},children:o.jsxs(he,{direction:"vertical",size:a.marginXS,style:{width:"100%"},children:[o.jsx(tg,{type:"secondary",children:e.description}),e.compatibility&&o.jsxs(tg,{type:"secondary",children:["Compatibility: ",e.compatibility]}),e.tool_refs.length>0&&o.jsx(he,{size:a.marginXXS,wrap:!0,children:e.tool_refs.map(i=>o.jsx(Ne,{style:{background:a.colorFillSecondary,borderColor:a.colorBorderSecondary,color:a.colorText},children:i},i))})]})})},TP=3e4,jP=()=>{const{t:e}=Ae(),{message:t}=en.useApp(),n=Ps(A=>A.config),s=Ps(A=>A.loadConfig),r=Ps(A=>A.saveConfig),[a,i]=f.useState([]),[l,c]=f.useState(!1),[u,m]=f.useState(null),[p,g]=f.useState(null),[b,S]=f.useState(""),[x,k]=f.useState(new Date),j=f.useMemo(()=>{var A;return new Set((((A=n==null?void 0:n.skills)==null?void 0:A.disabled)??[]).map(B=>B.trim()).filter(Boolean))},[n]),w=f.useCallback(async(A=!0)=>{c(!0),m(null);try{const[B]=await Promise.all([Lu.listSkills({includeDisabled:!0},A),s({force:A})]);i(B.skills),k(new Date)}catch(B){const F=B instanceof Error?B.message:e("components.skillManager.loadFailed");m(F)}finally{c(!1)}},[s,e]);f.useEffect(()=>{w(!0);const A=setInterval(()=>{w(!0)},TP);return()=>clearInterval(A)},[w]),f.useEffect(()=>{const A=()=>{w(!0)};return window.addEventListener("focus",A),()=>window.removeEventListener("focus",A)},[w]);const M=f.useCallback(async()=>{await w(!0),t.success(e("components.skillManager.skillsRefreshed"))},[w,e]);f.useEffect(()=>{u&&(t.error(u),m(null))},[u]);const _=f.useCallback(async(A,B)=>{var F;g(A);try{const O=await s({force:!0}),R=((F=O==null?void 0:O.skills)==null?void 0:F.disabled)??[],I=Array.from(new Set((B?[...R,A]:R.filter(L=>L!==A)).map(L=>L.trim()).filter(Boolean))).sort();await r({...O??{},skills:{...(O==null?void 0:O.skills)??{},disabled:I}}),t.success(e("components.skillManager.skillStateSaved"))}catch(O){t.error(O instanceof Error?O.message:e("components.skillManager.saveFailed"))}finally{g(null)}},[s,r,e]),C=a.filter(A=>{const B=b.trim().toLowerCase();return!(B&&![A.name,A.description,A.license??"",A.compatibility??"",...A.tool_refs].join(" ").toLowerCase().includes(B))}),D=()=>{const B=new Date().getTime()-x.getTime(),F=Math.floor(B/1e3);if(F<5)return e("components.skillManager.justNow");if(F<60)return e("components.skillManager.secondsAgo",{count:F});const O=Math.floor(F/60);return O<60?e("components.skillManager.minutesAgo",{count:O}):x.toLocaleTimeString()};return o.jsx("div",{style:{padding:"24px"},children:o.jsxs(Ce,{className:"lotus-settings-card",title:o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[o.jsx("span",{children:e("components.skillManager.title")}),o.jsx(de,{icon:o.jsx(cr,{spin:l}),onClick:M,loading:l,size:"small",children:e("components.skillManager.refresh")}),o.jsx("span",{className:"lotus-settings-note",style:{fontSize:"12px",marginLeft:"auto"},children:e("components.skillManager.lastUpdated",{value:D()})})]}),children:[o.jsx("div",{className:"lotus-settings-note",style:{marginBottom:"16px"},children:e("components.skillManager.readOnlyHint")}),o.jsx("div",{className:"lotus-settings-note",style:{marginBottom:"16px"},children:e("components.skillManager.disabledHint")}),o.jsx(fs,{style:{marginBottom:"24px"},children:o.jsx(et,{placeholder:e("components.skillManager.searchPlaceholder"),prefix:o.jsx($i,{}),value:b,onChange:A=>S(A.target.value),allowClear:!0})}),o.jsx(Rs,{spinning:l,children:C.length===0?o.jsx(Mn,{description:e(b?"components.skillManager.noMatch":"components.skillManager.noSkillsFound")}):o.jsx(Qt,{grid:{gutter:16,xs:1,sm:2,md:3,lg:3,xl:4},dataSource:C,renderItem:A=>o.jsx(Qt.Item,{children:o.jsx(kP,{skill:A,disabled:j.has(A.id),busy:p===A.id,onToggleDisabled:_})})})})]})})},{Title:CP,Text:ru,Paragraph:MP}=Ke,ng="model_limits",mm="modelLimitsConfigs",sg="defaultBudgetStrategy",hs=1e3;function rg(e){return[{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5.4-thinking",max_context_tokens:1e6,max_output_tokens:128e3,safety_margin:hs,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:hs,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:hs,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:hs,note:e("settings.modelLimits.defaults.gpt5Mini")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4.1",max_context_tokens:128e3,max_output_tokens:16384,safety_margin:hs,note:e("settings.modelLimits.defaults.gpt41")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4o",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:hs,note:e("settings.modelLimits.defaults.gpt4o")},{vendor:"Google",model_pattern:"gemini-2.5-pro",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:hs,note:e("settings.modelLimits.defaults.gemini25Pro")},{vendor:"Moonshot",model_pattern:"kimi-k2.5",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:hs,note:e("settings.modelLimits.defaults.kimiK25")},{vendor:"Moonshot",model_pattern:"kimi-for-coding",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:hs,note:e("settings.modelLimits.defaults.kimiCoding")},{vendor:"Zhipu",model_pattern:"glm-5",max_context_tokens:2e5,max_output_tokens:128e3,safety_margin:hs,note:e("settings.modelLimits.defaults.glm5")}]}function PP(e){return Array.isArray(e)?jh(e):[]}function og(e,t){if(typeof e!="number"||!Number.isFinite(e))return t;const n=Math.floor(e);return n>0?n:t}function EP(e,t){if(typeof e!="number"||!Number.isFinite(e))return t;const n=Math.floor(e);return n>=0?n:t}function RP(e){if(!e||typeof e!="object")return null;const t=e,n=t.model_pattern??t.model;if(typeof n!="string"||!n.trim())return null;const s=og(t.max_context_tokens??t.maxContextTokens,128e3),r=og(t.max_output_tokens??t.maxOutputTokens,Math.min(4096,Math.floor(s/4))),a=EP(t.safety_margin??t.safetyMargin,hs);return{vendor:typeof t.vendor=="string"&&t.vendor.trim()?t.vendor.trim():"",model_pattern:n.trim(),max_context_tokens:s,max_output_tokens:r,safety_margin:a,note:typeof t.note=="string"?t.note:""}}function jh(e){return Array.isArray(e)?e.map(t=>RP(t)).filter(t=>!!t):[]}function AP(){const e=localStorage.getItem(mm);if(!e)return[];try{const t=JSON.parse(e);return jh(t)}catch{return[]}}function IP(e){const t=Object.prototype.hasOwnProperty.call(e,ng);return t?{hasModelLimitsKey:t,modelLimits:jh(e[ng])}:{hasModelLimitsKey:!1,modelLimits:[]}}function OP(e,t){if(e.length===0)return t("settings.modelLimits.validation.atLeastOneRow");const n=new Set;for(const s of e){const r=s.model_pattern.trim();if(!r)return t("settings.modelLimits.validation.modelPatternEmpty");const a=r.toLowerCase();if(n.has(a))return t("settings.modelLimits.validation.duplicateModelPattern",{pattern:r});if(n.add(a),s.max_context_tokens<1e3)return t("settings.modelLimits.validation.contextWindowMin",{pattern:r});if(s.max_output_tokens<1)return t("settings.modelLimits.validation.maxOutputMin",{pattern:r});if(s.max_output_tokens>s.max_context_tokens)return t("settings.modelLimits.validation.maxOutputExceedsContext",{pattern:r});if(s.safety_margin<0)return t("settings.modelLimits.validation.safetyMarginNegative",{pattern:r});if(s.safety_margin>=s.max_context_tokens)return t("settings.modelLimits.validation.safetyMarginTooLarge",{pattern:r})}return null}const $P=()=>{const{t:e}=Ae(),[t,n]=f.useState(()=>rg(e)),[s,r]=f.useState(!1),[a,i]=Cr.useMessage(),l=f.useCallback((x,k)=>{n(j=>j.map((w,M)=>M===x?{...w,...k}:w))},[]),c=f.useCallback(()=>{n(x=>[...x,{vendor:"",model_pattern:"",max_context_tokens:128e3,max_output_tokens:4096,safety_margin:hs,note:""}])},[]),u=f.useCallback(x=>{n(k=>k.filter((j,w)=>w!==x))},[]),m=f.useCallback(async()=>{const x=rg(e),k=await Vt.getModelLimitDefaults(),j=PP(k.model_limits);return j.length>0?j:x},[e]),p=f.useCallback(async()=>{r(!0);try{const x=await Vt.getBambooConfig(),{hasModelLimitsKey:k,modelLimits:j}=IP(x);if(j.length>0){n(j);return}if(k){n(await m());return}const w=AP();if(w.length>0){await Vt.setBambooConfig({model_limits:w}),localStorage.removeItem(mm),localStorage.removeItem(sg),n(w),a.info(e("settings.modelLimits.migratedFromLocalStorage"));return}n(await m())}catch(x){console.error("Failed to load model limits settings:",x),a.error(e("settings.modelLimits.loadFailed")),n(await m())}finally{r(!1)}},[m,a,e]);f.useEffect(()=>{p()},[p]);const g=async()=>{const x=OP(t,e);if(x){a.error(x);return}r(!0);try{await Vt.setBambooConfig({model_limits:t}),a.success(e("settings.modelLimits.saveSuccess"))}catch(k){console.error("Failed to save model limits settings:",k),a.error(e("settings.modelLimits.saveFailed"))}finally{r(!1)}},b=async()=>{r(!0);try{const x=await m();await Vt.setBambooConfig({model_limits:x}),n(x),localStorage.removeItem(mm),localStorage.removeItem(sg),a.success(e("settings.modelLimits.resetSuccess"))}catch(x){console.error("Failed to reset model limits settings:",x),a.error(e("settings.modelLimits.resetFailed"))}finally{r(!1)}},S=f.useMemo(()=>[{title:e("settings.modelLimits.columns.vendor"),dataIndex:"vendor",key:"vendor",width:170,render:(x,k,j)=>o.jsx(et,{value:x,placeholder:e("settings.modelLimits.placeholders.vendor"),onChange:w=>l(j,{vendor:w.target.value})})},{title:e("settings.modelLimits.columns.model"),dataIndex:"model_pattern",key:"model_pattern",width:220,render:(x,k,j)=>o.jsx(et,{value:x,placeholder:e("settings.modelLimits.placeholders.model"),onChange:w=>l(j,{model_pattern:w.target.value})})},{title:e("settings.modelLimits.columns.contextWindow"),dataIndex:"max_context_tokens",key:"max_context_tokens",width:180,render:(x,k,j)=>o.jsx(Zt,{value:x,onChange:w=>l(j,{max_context_tokens:Math.max(1e3,Number(w)||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:(x,k,j)=>o.jsx(Zt,{value:x,onChange:w=>l(j,{max_output_tokens:Math.max(1,Number(w)||4096)}),min:1,max:2e6,step:256,style:{width:"100%"}})},{title:e("settings.modelLimits.columns.notes"),dataIndex:"note",key:"note",width:240,render:(x,k,j)=>o.jsx(et,{value:x,placeholder:e("settings.modelLimits.placeholders.optional"),onChange:w=>l(j,{note:w.target.value})})},{title:e("settings.modelLimits.columns.actions"),key:"actions",width:100,render:(x,k,j)=>o.jsx(de,{danger:!0,size:"small",onClick:()=>u(j),children:e("settings.modelLimits.actions.remove")})}],[u,e,l]);return o.jsxs("div",{className:"model-limits-settings",children:[i,o.jsxs(Ce,{children:[o.jsx(CP,{level:4,children:e("settings.modelLimits.title")}),o.jsxs(MP,{type:"secondary",children:[e("settings.modelLimits.descriptionPrefix")," ",o.jsx(ru,{code:!0,children:"config.json"})," ",e("settings.modelLimits.descriptionSuffix")]}),o.jsx(zn,{}),o.jsxs(he,{direction:"vertical",size:"small",style:{width:"100%"},children:[o.jsx(ru,{strong:!0,children:e("settings.modelLimits.defaultsTitle")}),o.jsx(ru,{type:"secondary",children:e("settings.modelLimits.defaultsDescription")})]}),o.jsx(ar,{dataSource:t,columns:S,rowKey:(x,k)=>`${x.model_pattern}-${k}`,pagination:!1,size:"small",style:{margin:"16px 0"},scroll:{x:1150}}),o.jsxs(he,{children:[o.jsx(de,{onClick:c,children:e("settings.modelLimits.actions.addRow")}),o.jsx(de,{type:"primary",icon:o.jsx(Bc,{}),onClick:()=>void g(),loading:s,children:e("settings.modelLimits.actions.save")}),o.jsx(de,{icon:o.jsx(cr,{}),onClick:()=>void b(),loading:s,children:e("settings.modelLimits.actions.resetToDefaults")}),o.jsx(de,{onClick:()=>void p(),loading:s,children:e("settings.modelLimits.actions.reload")})]})]})]})},hm="lotus_experience_mode_v1",sS=new Set(["skills","hooks","masking","env-vars","metrics","sessions","config"]);function ag(){try{const e=localStorage.getItem(hm);if(e==="simple"||e==="advanced")return e}catch{}return"advanced"}const Ic=Pr(e=>({mode:ag(),isAdvanced:ag()==="advanced",setMode:t=>{try{localStorage.setItem(hm,t)}catch{}e({mode:t,isAdvanced:t==="advanced"})},toggleMode:()=>e(t=>{const n=t.mode==="simple"?"advanced":"simple";try{localStorage.setItem(hm,n)}catch{}return{mode:n,isAdvanced:n==="advanced"}})})),{Text:ou}=Ke,{useToken:DP}=Qe,LP="bamboo_dark_mode",FP=({themeMode:e,onThemeModeChange:t,locale:n,onLocaleChange:s,onBack:r})=>{const{t:a}=Ae(),{token:i}=DP(),{deleteAllChats:l,autoGenerateTitles:c,setAutoGenerateTitlesPreference:u,isUpdatingAutoTitlePreference:m}=Wj(),[p,g]=f.useState(!1),[b,S]=Cr.useMessage(),[x,k]=f.useState(""),[j,w]=f.useState(nm()),[M,_]=f.useState(rm()),[C,D]=f.useState(Ec()),[A,B]=f.useState(Rc()),O=Ct(me=>me.currentProvider)==="copilot",R=rr(me=>me.activeTabKey),I=rr(me=>me.setActiveTabKey),L=Ic(me=>me.isAdvanced),U=i.paddingSM,q=(me,ze)=>({key:me,label:o.jsx(ou,{type:"secondary",style:{fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em",cursor:"default",userSelect:"none"},children:ze}),disabled:!0,children:null}),H=(me,ze)=>o.jsx("span",{"data-testid":`settings-tab-${me}`,children:ze}),P=()=>{localStorage.clear(),b.success(a("settings.notifications.localStorageCleared"))},W=async()=>{g(!0);try{await l(),await Vt.resetSetupStatus(),await Vt.resetBambooConfig(),localStorage.clear(),b.success(a("settings.notifications.resetSuccessReloading")),setTimeout(()=>{window.location.reload()},1500)}catch(me){console.error("Failed to reset application:",me),b.error(me instanceof Error?me.message:a("settings.notifications.resetFailed")),g(!1)}},ne=async me=>{try{await u(me),b.success(a(me?"settings.notifications.autoTitleEnabled":"settings.notifications.autoTitleDisabled"))}catch{b.error(a("settings.notifications.autoTitleUpdateFailed"))}},K=()=>{Fj(x),b.success(a("settings.notifications.promptEnhancementSaved"))},xe=me=>{w(me),jj(me)},se=me=>{_(me),Pj(me)},fe=me=>{D(me),Ij(me)},Se=me=>{B(me),qj(me),window.dispatchEvent(new Event("lotus-vdi-safe-mode-change")),b.success(me?a("settings.appTab.vdiSafeModeEnabled","Graphics compatibility mode enabled"):a("settings.appTab.vdiSafeModeDisabled","Graphics compatibility mode disabled"))};return f.useEffect(()=>{k(qv()),w(nm()),_(rm()),D(Ec()),B(Rc())},[]),o.jsxs(ve,{vertical:!0,role:"region","aria-label":a("settings.page.title"),style:{height:"100vh",overflow:"hidden",background:i.colorBgContainer},children:[S,o.jsxs(ve,{align:"center",justify:"space-between",style:{padding:i.padding,paddingTop:i.padding+U,borderBottom:`1px solid ${i.colorBorderSecondary}`},children:[o.jsxs(ve,{align:"center",gap:i.marginSM,children:[o.jsx(de,{icon:o.jsx(r_,{}),onClick:r,"aria-label":a("settings.page.back"),children:a("settings.page.back")}),o.jsx(ou,{strong:!0,"data-testid":"settings-page-title",children:a("settings.page.title")})]}),o.jsxs(ou,{type:"secondary","data-testid":"settings-page-version",children:[a("settings.appTab.runningVersion","Running version"),": v",Gm]})]}),o.jsx(so.Content,{style:{flex:1,minHeight:0,overflow:"auto",padding:i.padding},children:o.jsx(Di,{tabPosition:"left",activeKey:R,onChange:me=>I(me),items:[q("group-ai",a("settings.page.groups.ai")),{key:"provider",label:H("provider",a("settings.page.tabs.provider")),children:o.jsx(_P,{})},{key:"model-limits",label:H("model-limits",a("settings.page.tabs.modelLimits")),children:o.jsx($P,{})},{key:"prompts",label:H("prompts",a("settings.page.tabs.prompts")),children:o.jsx(oC,{promptEnhancement:x,onPromptEnhancementChange:k,mermaidEnhancementEnabled:j,taskEnhancementEnabled:M,showCopilotConclusionWithOptionsEnhancement:O,copilotConclusionWithOptionsEnhancementEnabled:C,onMermaidToggle:xe,onTaskToggle:se,onCopilotConclusionWithOptionsToggle:fe,onSaveEnhancement:K})},q("group-tools",a("settings.page.groups.toolsAndExtensions")),{key:"skills",label:H("skills",a("settings.page.tabs.skills")),children:o.jsx(jP,{})},{key:"mcp",label:H("mcp",a("settings.page.tabs.mcp")),children:o.jsx(dM,{})},{key:"workflows",label:H("workflows",a("settings.page.tabs.workflows")),children:o.jsx(_C,{})},{key:"hooks",label:H("hooks",a("settings.page.tabs.hooks")),children:o.jsx(nP,{})},q("group-security",a("settings.page.groups.securityAndPrivacy")),{key:"masking",label:H("masking",a("settings.page.tabs.masking")),children:o.jsx(gC,{})},{key:"env-vars",label:H("env-vars",a("settings.page.tabs.envVars")),children:o.jsx(xC,{})},q("group-monitoring",a("settings.page.groups.monitoring")),{key:"metrics",label:H("metrics",a("settings.page.tabs.metrics")),children:o.jsx(QM,{})},{key:"sessions",label:H("sessions",a("settings.page.tabs.sessions")),children:o.jsx(pP,{})},q("group-system",a("settings.page.groups.system")),{key:"config",label:H("config",a("settings.page.tabs.config")),children:o.jsx(Jj,{msgApi:b,locale:n,onLocaleChange:s})},{key:"schedules",label:H("schedules",a("settings.page.tabs.schedules")),children:o.jsx(fP,{})},{key:"app",label:H("app",a("settings.page.tabs.app")),children:o.jsx(hC,{autoGenerateTitles:c,isUpdatingAutoTitlePreference:m,onAutoTitleToggle:ne,themeMode:e,onThemeModeChange:t,vdiSafeMode:A,onVdiSafeModeToggle:Se,onClearLocalStorage:P,onResetApp:W,isResetting:p,darkModeKey:LP})}].filter(me=>!(!L&&me.key&&sS.has(me.key)||!L&&(me.key==="group-security"||me.key==="group-monitoring")))})})]})},{Text:ig,Paragraph:NP}=Ke;class Wi extends f.Component{constructor(n){super(n);jt(this,"handleReset",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,s){var a,i;const r=this.props.name??"ErrorBoundary";console.error(`[${r}] Uncaught error:`,n,s),(i=(a=this.props).onError)==null||i.call(a,n,s)}render(){if(!this.state.hasError)return this.props.children;const{fallback:n}=this.props,s=this.state.error;return typeof n=="function"?n(s,this.handleReset):n!==void 0?n:o.jsx(zP,{error:s,onReset:this.handleReset})}}const zP=({error:e,onReset:t})=>{const{token:n}=Qe.useToken(),[s,r]=pn.useState(!1);return o.jsxs("div",{role:"alert",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:n.paddingLG,minHeight:200,textAlign:"center"},children:[o.jsx(Tb,{style:{fontSize:36,color:n.colorWarning}}),o.jsx(ig,{strong:!0,style:{fontSize:16},children:"Something went wrong"}),o.jsx(ig,{type:"secondary",style:{maxWidth:420},children:"An unexpected error occurred in this section. You can try again or reload the page if the issue persists."}),o.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[o.jsx(de,{type:"primary",icon:o.jsx(cr,{}),onClick:t,"aria-label":"Retry rendering this section",children:"Try Again"}),o.jsx(de,{type:"text",size:"small",onClick:()=>r(a=>!a),"aria-expanded":s,"aria-label":"Toggle error details",children:s?"Hide Details":"Show Details"})]}),s&&o.jsxs(NP,{code:!0,copyable:!0,style:{maxWidth:560,maxHeight:200,overflow:"auto",fontSize:12,textAlign:"left",marginTop:8,background:n.colorFillTertiary,padding:n.paddingSM,borderRadius:n.borderRadius},children:[e.message,e.stack?`
154
+
155
+ ${e.stack}`:""]})]})},BP=15e3,WP=()=>{const e=G(i=>i.chats),t=G(i=>i.updateSession),n=G(i=>i.persistSessionTitle),{generateChatTitle:s}=vh({chats:e,updateSession:t,persistSessionTitle:n}),r=f.useRef(new Map),a=f.useRef(new Map);return f.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 m=r.current.get(l);if(u.id===m)return;const p=a.current.get(l);p&&p.messageId===u.id&&Date.now()-p.at<BP||s(l).then(g=>{g&&(r.current.set(l,u.id),a.current.delete(l))}).catch(g=>{a.current.set(l,{messageId:u.id,at:Date.now()}),console.warn("Auto title generation failed for chat",l,":",g)})})},[e,s]),f.useEffect(()=>{const i=new Set(e.map(c=>c.id));Array.from(r.current.keys()).forEach(c=>{i.has(c)||(r.current.delete(c),a.current.delete(c))})},[e]),null},qP=()=>{const{token:e}=Qe.useToken(),t=Zc(),n=f.useRef("");f.useEffect(()=>{const s=UP(e.colorBgContainer),r=`${s}-${t.theme}-${JSON.stringify(t.themeVariables)}`;if(n.current===r)return;n.current=r;let a=t.theme;(t.theme==="default"||t.theme==="neutral")&&(a=s?"dark":t.theme),zm.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 UP(e){if(e.startsWith("#")){const n=e.slice(1),s=parseInt(n.substr(0,2),16),r=parseInt(n.substr(2,2),16),a=parseInt(n.substr(4,2),16);return(.299*s+.587*r+.114*a)/255<.5}const t=e.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(t){const n=parseInt(t[1]),s=parseInt(t[2]),r=parseInt(t[3]);return(.299*n+.587*s+.114*r)/255<.5}return!1}zm.initialize({startOnLoad:!1,theme:"dark",securityLevel:"loose",suppressErrorRendering:!0});zm.parseError=function(e){console.warn("Mermaid parse error (handled gracefully):",e)};const lg=new Map,HP=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,KP=e=>e.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),YP=e=>(HP.test(e)?KP(e):e).replace(/\[([\s\S]*?)\]/g,(n,s)=>{const r=String(s),a=/\r?\n/.test(r),i=/[()]/.test(r),l=/@/.test(r);if(!a&&!i&&!l)return n;const c=r.trim(),u=c.startsWith("(")&&c.endsWith(")")&&c.length>=2;let m=r;return a&&(m=m.replace(/\r?\n/g,"<br/>")),i&&!u&&(m=m.replace(/\(/g,"&#40;").replace(/\)/g,"&#41;")),l&&(m=m.replace(/@/g,"&#64;")),m===r?n:`[${m}]`}),VP=200,Us=new Map,dc=new Map;let au=null;const XP=e=>{const n=new DOMParser().parseFromString(e,"image/svg+xml");return Array.from(n.querySelectorAll("rect")).reduce((r,a)=>{const i=Number(a.getAttribute("width"));return Number.isFinite(i)&&i<0?r+1:r},0)};async function GP(){au||(au=Bn(()=>import("./vendor-mermaid-DA4JIJaA.js").then(t=>t.be),__vite__mapDeps([7,1,2,3,6]),import.meta.url));const e=await au;return e.default??e}function JP(e,t){if(Us.has(e)&&Us.delete(e),Us.set(e,t),Us.size>VP){const n=Us.keys().next().value;n&&Us.delete(n)}}function uc(e){const t=Us.get(e);return t?(Us.delete(e),Us.set(e,t),t):null}function cg(){Us.clear(),dc.clear()}function QP(e,t){const n=uc(e);if(n)return Promise.resolve(n);const s=dc.get(e);if(s)return s;const r=(async()=>{var w,M;const a=await GP();await a.parse(t);const i=`mermaid-${e}`,l=document.createElement("div"),c=Math.max(1600,window.innerWidth||0,((w=document.documentElement)==null?void 0:w.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 m=typeof u=="object"&&"svg"in u?u.svg:String(u),p=XP(m);if(p>0)throw new Error(`Mermaid rendered invalid SVG (${p} rect widths < 0)`);const S=new DOMParser().parseFromString(m,"image/svg+xml").querySelector("svg");let x=800,k=300;if(S){const _=S.getAttribute("viewBox");if(_){const C=_.split(/\s+/).map(Number);C.length===4&&(x=C[2]||800,k=C[3]||300)}if(x===800&&k===300){const C=document.createElement("div");C.style.cssText="position:absolute;visibility:hidden;width:800px;",C.innerHTML=m,document.body.appendChild(C);const D=(M=C.querySelector("svg"))==null?void 0:M.getBoundingClientRect();D&&(x=D.width,k=D.height),document.body.removeChild(C)}}const j={svg:m,width:x,height:k};return JP(e,j),j})().finally(()=>{dc.delete(e)});return dc.set(e,r),r}function Bl(...e){}const ZP=e=>{const t=e;return(t==null?void 0:t.name)==="AbortError"||(t==null?void 0:t.code)===20},dg=220,ug=e=>{const t=e.replace(/\s+/g," ").trim();return t.length<=dg?t:`${t.slice(0,dg)}...`},eE=e=>e==="pending"||e==="in_progress"||e==="completed"||e==="blocked",tE=new Set(["completed","error","cancelled","failed"]),Wl=e=>{const t=e.trim().toLowerCase();return t==="memory_note"||t==="session_note"};function nE(){const{message:e}=en.useApp(),t=G(P=>P.addMessage),n=G(P=>P.applyAgentEvent),s=G(P=>P.updateTokenUsage),r=G(P=>P.setTruncationInfo),a=G(P=>P.updateSession),i=G(P=>P.updateMessage),l=G(P=>P.setTaskList),c=G(P=>P.loadTaskList),u=G(P=>P.updateTaskListDelta),m=G(P=>P.setEvaluationState),p=G(P=>P.applyChildProgress),g=G(P=>P.persistSessionTitle),b=G(P=>P.refreshChatsNow),S=G(P=>P.setPendingQuestion),x=G(P=>P.clearPendingQuestion),k=f.useRef(new os),j=f.useRef(new Set),w=f.useRef(new Map),M=f.useRef(new Map),_=f.useRef(new Map),C=f.useRef(new Map),D=f.useRef(new Map),A=f.useRef(new Map),B=f.useRef(new Set),F=f.useRef(new Map),O=f.useCallback(P=>{const W=F.current.get(P);W!=null&&W.timer&&clearTimeout(W.timer),F.current.delete(P)},[]),R=f.useCallback(P=>{const W=w.current.get(P);W&&(clearTimeout(W),w.current.delete(P))},[]),I=f.useCallback((P,W)=>{O(P),R(P),B.current.delete(P);const ne=M.current.get(P);if(!ne)return;M.current.delete(P),ne.controller.abort(),It.forceFlush();const K=_.current.get(ne.sessionId);K?(W!=null&&W.clearDraft&&(It.clear(K.sessionId,K.messageId),It.clear(K.sessionId,K.reasoningMessageId),It.clear(K.sessionId,K.statusMessageId)),_.current.delete(ne.sessionId)):W!=null&&W.clearDraft&&(It.clear(P,`streaming-${P}`),It.clear(P,`streaming-reasoning-${P}`),It.clear(P,`streaming-status-${P}`))},[R,O]),L=f.useCallback(async P=>{const W=P.trim();if(W&&!j.current.has(W)&&!G.getState().taskLists[W]){j.current.add(W);try{await c(W)}catch(ne){console.warn(`[useAgentEventSubscription] Failed to recover task list baseline for ${W}:`,ne)}finally{j.current.delete(W)}}},[c]),U=f.useCallback(P=>{const W=wc(P)(G.getState())??0;O(P);const ne=new AbortController;M.current.set(P,{sessionId:P,controller:ne,generation:W,streamEnded:!1});const K=`streaming-${P}`,xe=`streaming-reasoning-${P}`,se=`streaming-status-${P}`,fe=It.getLatest(K),Se=It.getLatest(xe),me=It.getLatest(se);_.current.set(P,{sessionId:P,messageId:K,content:fe??"",reasoningMessageId:xe,reasoningContent:Se??"",statusMessageId:se,status:me??""});const ze=N=>{const le=_.current.get(P);if(!le)return;const be=(N??"").trim();if(!be){if(!le.status)return;le.status="",It.clear(le.sessionId,le.statusMessageId);return}le.status!==be&&(le.status=be,It.publish({sessionId:le.sessionId,messageId:le.statusMessageId,content:le.status}))};fe===null&&It.publish({sessionId:P,messageId:K,content:""});const st=()=>{const N=F.current.get(P),le=(N==null?void 0:N.attempt)??0,be=Math.min(5e3,250*Math.pow(2,le));I(P,{clearDraft:!1});const De=setTimeout(()=>{var ye;if(F.current.delete(P),!qr(P)(G.getState()))return;const Le=G.getState().chats.find(qe=>qe.id===P),ue=(ye=Le==null?void 0:Le.id)==null?void 0:ye.trim();ue&&U(ue)},be);F.current.set(P,{attempt:le+1,timer:De})};let pt=!1;const Kt=250,Oe=()=>{const N=M.current.get(P);!N||N.controller!==ne||N.streamEnded||(N.streamEnded=!0,Bl("markStreamEnded",P,"generation:",N.generation,"terminal:",pt))},Wt=()=>{const N=C.current.get(P);return((N==null?void 0:N.children.size)??0)>0},Xe=()=>pt&&!Wt(),_e=()=>{const N=M.current.get(P);N&&(It.clear(P,`streaming-${P}`),It.clear(P,`streaming-reasoning-${P}`),It.clear(P,`streaming-status-${P}`),_.current.delete(N.sessionId))},Ye=async()=>{R(P);try{await b()}catch(ue){console.warn(`[useAgentEventSubscription] High-priority refresh failed while settling parent ${P}:`,ue)}const N=C.current.get(P)??{children:new Set,parentDone:!1};if(!N.parentDone||N.children.size>0)return;const le=M.current.get(P);if(le&&(le.controller!==ne||le.generation!==W))return;const De=G.getState().chats.find(ue=>ue.id===P);De!=null&&De.isRunning||I(P,{clearDraft:!0})},ot=()=>{R(P);const N=setTimeout(()=>{w.current.delete(P),Ye()},Kt);w.current.set(P,N)},Lt=()=>{const N=C.current.get(P)??{children:new Set},le=new Set(N.children);if(C.current.set(P,{children:le,parentDone:!0}),le.size===0){ot();return}_e()};k.current.subscribeToEvents(P,{onToken:N=>{n(P,{type:"token",content:N},W);const le=_.current.get(P);le&&(ze(null),le.content+=N,It.publish({sessionId:le.sessionId,messageId:le.messageId,content:le.content}))},onReasoningToken:N=>{n(P,{type:"reasoning_token",content:N},W);const le=_.current.get(P);le&&(le.reasoningContent+=N,It.publish({sessionId:le.sessionId,messageId:le.reasoningMessageId,content:le.reasoningContent}))},onToolStart:(N,le,be)=>{var ke,pe;n(P,{type:"tool_start",tool_call_id:N,tool_name:le},W);const De=_.current.get(P),Le=(De==null?void 0:De.content)||"",ue=(De==null?void 0:De.reasoningContent)||"",ye=Le.trim().length>0,qe=ue.trim().length>0;if(ye||qe){const Re=G.getState().chats.find(xt=>xt.id===P),Je=(ke=Re==null?void 0:Re.messages)==null?void 0:ke[Re.messages.length-1],gt=typeof((pe=Je==null?void 0:Je.metadata)==null?void 0:pe.reasoning)=="string"?Je.metadata.reasoning:"";(Je==null?void 0:Je.role)==="assistant"&&(Je==null?void 0:Je.type)==="text"&&typeof(Je==null?void 0:Je.content)=="string"&&Je.content===Le&&gt===ue||t(P,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:Le,createdAt:new Date().toISOString(),metadata:{sessionId:P,model:"agent",...qe?{reasoning:ue}:{}}}),De&&(De.content="",De.reasoningContent="",De.status&&(De.status="",It.clear(De.sessionId,De.statusMessageId)),It.publish({sessionId:De.sessionId,messageId:De.messageId,content:""}),It.publish({sessionId:De.sessionId,messageId:De.reasoningMessageId,content:""}))}D.current.set(N,le);const He=le.trim().toLowerCase();Wl(le)?ze("memory_updating"):ze(`tool_running:${He||"tool"}`);const ae=crypto.randomUUID();A.current.set(N,ae),t(P,{id:ae,role:"assistant",type:"tool_call",toolCalls:[{toolCallId:N,toolName:le,parameters:be||{},streamingOutput:""}],metadata:{},createdAt:new Date().toISOString()})},onToolToken:(N,le)=>{n(P,{type:"tool_token",tool_call_id:N,content:le},W);const be=A.current.get(N),De=G.getState().chats.find(qe=>qe.id===P);if(!De)return;const Le=(be?De==null?void 0:De.messages.find(qe=>qe.id===be):null)||(De==null?void 0:De.messages[De.messages.length-1]);if(!Le||!("type"in Le)||Le.type!=="tool_call"||!("toolCalls"in Le)||!Array.isArray(Le.toolCalls))return;const ue=Le.toolCalls.find(qe=>qe.toolCallId===N);ue&&!D.current.has(N)&&(D.current.set(N,ue.toolName),A.current.set(N,Le.id));const ye=Le.toolCalls.map(qe=>{if(qe.toolCallId!==N)return qe;const He=(qe.streamingOutput||"")+(le||"");return{...qe,streamingOutput:He}});i(P,Le.id,{toolCalls:ye})},onToolComplete:(N,le)=>{n(P,{type:"tool_complete",tool_call_id:N},W);const be=D.current.get(N)||"unknown";D.current.delete(N),A.current.delete(N);const De=be.trim().toLowerCase(),Le=_.current.get(P);(Wl(be)?(Le==null?void 0:Le.status)==="memory_updating":!!(Le!=null&&Le.status&&Le.status.includes(De)))&&ze(null);const ye=(le==null?void 0:le.display_preference)||"Default";t(P,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:be,toolCallId:N,result:{tool_name:be,result:(le==null?void 0:le.result)??"",display_preference:ye},isError:!(le!=null&&le.success),createdAt:new Date().toISOString()})},onToolError:(N,le)=>{n(P,{type:"tool_error",tool_call_id:N},W),D.current.delete(N),A.current.delete(N),ze(null),t(P,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:"unknown",toolCallId:N,result:{tool_name:"unknown",result:le,display_preference:"Default"},isError:!0,createdAt:new Date().toISOString()})},onToolLifecycle:(N,le,be,De,Le)=>{if(be==="begin"){const ue=(le||"").trim().toLowerCase();Wl(le||"")?ze("memory_updating"):ze(`tool_running:${ue||"tool"}`)}if(be==="finished"||be==="error"||be==="cancelled"){const ue=A.current.get(N);ue&&i(P,ue,{metadata:{elapsed_ms:De,is_mutating:Le}});const ye=(le||"").trim().toLowerCase(),qe=_.current.get(P);(Wl(le||"")?(qe==null?void 0:qe.status)==="memory_updating":!!(qe!=null&&qe.status&&qe.status.includes(ye)))&&ze(null)}},onContextCompressionStatus:(N,le)=>{if(le==="started"){ze("context_compacting");return}if(le==="degraded_sections"){ze("context_compaction_degraded");return}if(le==="failed"){ze("context_compaction_failed");return}ze(null)},onTokenBudgetUpdated:N=>{const le=typeof N.max_context_tokens=="number"&&N.max_context_tokens>0?N.max_context_tokens:void 0,be={systemTokens:N.system_tokens,summaryTokens:N.summary_tokens,windowTokens:N.window_tokens,totalTokens:N.total_tokens,budgetLimit:N.budget_limit,...le?{maxContextTokens:le}:{},...typeof N.prompt_cached_tool_outputs=="number"&&N.prompt_cached_tool_outputs>0?{promptCachedToolOutputs:N.prompt_cached_tool_outputs}:{}};s(P,be),r(P,N.truncation_occurred,N.segments_removed);const De=G.getState().chats.find(Le=>Le.id===P);De&&a(P,{config:{...De.config,tokenUsage:be,truncationOccurred:N.truncation_occurred,segmentsRemoved:N.segments_removed}})},onContextSummarized:N=>{ze(null),e.info(`Conversation summarized: ${N.messages_summarized} messages compressed, saved ${N.tokens_saved.toLocaleString()} tokens`,5)},onContextPressureNotification:(N,le,be)=>{le==="critical"?e.error(be,6):e.warning(be,5)},onTaskListUpdated:N=>{N.session_id&&l(N.session_id,N)},onTaskListItemProgress:N=>{if(N.session_id){if(!G.getState().taskLists[N.session_id]){L(N.session_id);return}u(N.session_id,N)}},onTaskListCompleted:(N,le,be)=>{e.success(`All tasks completed! Total rounds: ${le}, Tool calls: ${be}`,3)},onTaskEvaluationStarted:(N,le)=>{m(N,{isEvaluating:!0,reasoning:null,timestamp:Date.now()}),e.info(`Evaluating ${le} task(s)...`,2)},onTaskEvaluationCompleted:(N,le,be)=>{const De=ug(be);m(N,{isEvaluating:!1,reasoning:le>0?De:null,timestamp:Date.now()}),le>0?e.success(`Evaluation complete: ${le} task(s) updated.`,3):e.info("Evaluation complete: No updates needed",2)},onComplete:()=>{pt=!0,n(P,{type:"complete"},W);const N=ne,le=()=>{const be=M.current.get(P);return be!=null&&(be.controller!==N||be.generation!==W)};(async()=>{var qe,He,ae;if(ze(null),It.forceFlush(),x(P),le())return;const be=_.current.get(P),De=(be==null?void 0:be.content)||"",Le=(be==null?void 0:be.reasoningContent)||"",ue=De.trim().length>0,ye=Le.trim().length>0;if(ue||ye){const ke=G.getState().chats.find(gt=>gt.id===P),pe=(qe=ke==null?void 0:ke.messages)==null?void 0:qe[ke.messages.length-1],Re=typeof((He=pe==null?void 0:pe.metadata)==null?void 0:He.reasoning)=="string"?pe.metadata.reasoning:"";(pe==null?void 0:pe.role)==="assistant"&&(pe==null?void 0:pe.type)==="text"&&typeof(pe==null?void 0:pe.content)=="string"&&pe.content===De&&Re===Le||await t(P,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:De,createdAt:new Date().toISOString(),metadata:{sessionId:P,model:"agent",...ye?{reasoning:Le}:{}}})}if(!le()&&(await G.getState().loadChatHistory(P,{mode:"monotonic",retries:4,retryDelayMs:200,waitForAssistant:!0}),!le())){if(ye){const ke=G.getState().chats.find(Je=>Je.id===P),pe=[...(ke==null?void 0:ke.messages)||[]].reverse().find(Je=>(Je==null?void 0:Je.role)==="assistant"&&(Je==null?void 0:Je.type)==="text"),Re=typeof((ae=pe==null?void 0:pe.metadata)==null?void 0:ae.reasoning)=="string"&&pe.metadata.reasoning.trim().length>0;pe!=null&&pe.id&&!Re&&i(P,pe.id,{metadata:{...pe.metadata||{},reasoning:Le}})}le()||Lt()}})().catch(be=>{console.warn(`[useAgentEventSubscription] Completion finalization failed for session ${P}:`,be),le()||Lt()})},onError:async N=>{pt=!0,n(P,{type:"error",message:N},W),ze(null);try{const le=om(N)?am(N):N;await t(P,{id:`error-${Date.now()}`,role:"assistant",type:"text",content:`❌ **Error**: ${le}`,createdAt:new Date().toISOString(),finishReason:"error"})}catch(le){console.warn(`[useAgentEventSubscription] Failed to append error message for session ${P}:`,le)}finally{Lt()}},onSubSessionStarted:(N,le,be)=>{const De=C.current.get(N)??{children:new Set,parentDone:!1},Le=new Set(De.children);Le.add(le),C.current.set(N,{children:Le,parentDone:De.parentDone}),p(N,le,{title:be,status:"pending",lastEventAt:new Date().toISOString()}),be&&be.trim()&&g(le,be).catch(ue=>{console.warn(`[useAgentEventSubscription] Failed to persist sub-session title for ${le}:`,ue)}),b()},onSubSessionEvent:(N,le,be)=>{var De,Le,ue;if(be.type==="task_list_updated"&&be.task_list){const ye=be.task_list.session_id||N;l(ye,be.task_list);return}if(be.type==="task_list_item_progress"){const ye=be.session_id||N;if(typeof be.item_id=="string"&&eE(be.status)&&typeof be.tool_calls_count=="number"&&typeof be.version=="number"){if(!G.getState().taskLists[ye]){L(ye);return}u(ye,{session_id:ye,item_id:be.item_id,status:be.status,tool_calls_count:be.tool_calls_count,version:be.version})}return}if(be.type==="task_evaluation_started"){const ye=be.session_id||N;m(ye,{isEvaluating:!0,reasoning:null,timestamp:Date.now()});return}if(be.type==="task_evaluation_completed"){const ye=be.session_id||N,qe=be.updates_count??0;m(ye,{isEvaluating:!1,reasoning:qe>0?ug(be.reasoning??""):null,timestamp:Date.now()});return}if(be.type==="runner_progress"){const ye=(De=Fi(N)(G.getState()))==null?void 0:De[le];if(ye!=null&&ye.status&&tE.has(ye.status))return;p(N,le,{status:"running",roundCount:typeof be.round_count=="number"?be.round_count:ye==null?void 0:ye.roundCount,lastEventAt:new Date().toISOString()});return}if(be.type==="token"&&typeof be.content=="string"){const qe=((((ue=(Le=Fi(N)(G.getState()))==null?void 0:Le[le])==null?void 0:ue.outputPreview)||"")+be.content).slice(-2e3);p(N,le,{status:"running",outputPreview:qe,lastEventAt:new Date().toISOString()})}else p(N,le,{status:"running",lastEventAt:new Date().toISOString()})},onSubSessionHeartbeat:(N,le,be)=>{p(N,le,{status:"running",lastHeartbeatAt:be})},onSubSessionCompleted:(N,le,be,De)=>{const Le=C.current.get(N)??{children:new Set,parentDone:!1},ue=new Set(Le.children);ue.delete(le),C.current.set(N,{children:ue,parentDone:Le.parentDone}),p(N,le,{status:be,error:De,lastEventAt:new Date().toISOString()}),Le.parentDone&&ue.size===0&&ot(),b()},onNeedClarification:N=>{const le=N.session_id||P;S(le,{question:N.question||"",options:N.options||[],allowCustom:N.allow_custom??!0,toolCallId:N.tool_call_id??null})},onExecutionStarted:(N,le)=>{n(P,{type:"execution_started",run_id:N},W)},onRunnerProgress:()=>{}},ne).then(()=>{if(Oe(),Bl("streamEnded",P,"generation:",W,"aborted:",ne.signal.aborted,"terminal:",pt),ne.signal.aborted||Xe())return;const N=M.current.get(P);if(N&&(N.controller!==ne||N.generation!==W))return;if(!qr(P)(G.getState())){I(P,{clearDraft:!0});return}st()}).catch(N=>{if(Oe(),ne.signal.aborted)return;if(ZP(N)){if(Xe())return;if(!qr(P)(G.getState())){I(P,{clearDraft:!0});return}st();return}if(Xe())return;console.error("[useAgentEventSubscription] Subscription error:",N),I(P,{clearDraft:!0});const le=wc(P)(G.getState()),be=qr(P)(G.getState());le===W&&be&&n(P,{type:"error",message:String(N)},W)})},[t,I,R,x,O,L,e,g,b,m,S,n,l,r,i,a,u,s,p]),q=f.useCallback(P=>{const W=P.trim();if(!W)return;B.current.delete(W);const ne=M.current.get(W);if((ne==null?void 0:ne.sessionId)===W&&!ne.controller.signal.aborted&&!ne.streamEnded){Bl("skipExistingSubscription",W,"generation:",ne.generation,"streamEnded:",ne.streamEnded);return}ne&&(Bl("restartStaleSubscription",W,"generation:",ne.generation,"aborted:",ne.controller.signal.aborted,"streamEnded:",ne.streamEnded),I(W,{clearDraft:!1})),U(W)},[I,U]),H=G(P=>P.executionBySession);f.useEffect(()=>{const P={executionBySession:H},W=new Set(Object.entries(H).filter(([ne])=>qr(ne)(P)).map(([ne])=>ne));W.forEach(ne=>q(ne));for(const ne of Array.from(M.current.keys()))W.has(ne)||I(ne,{clearDraft:!0});for(const ne of Array.from(B.current))W.has(ne)||B.current.delete(ne)},[H,q,I]),f.useEffect(()=>G.subscribe(P=>P.chats,()=>{if(B.current.size!==0)for(const P of Array.from(B.current)){if(!qr(P)(G.getState())){B.current.delete(P);continue}q(P)}}),[q]),f.useEffect(()=>{const P=M.current;return()=>{const W=Array.from(P.keys());for(const ne of W)I(ne,{clearDraft:!0})}},[I])}const rS=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_result",sE=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_call",rE=e=>e.role==="assistant"&&"type"in e&&e.type==="workflow_result",oE=e=>e.role==="user"&&"type"in e&&e.type==="file_reference",aE=e=>e.role==="assistant"&&"type"in e&&e.type==="task_list",Oc=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/bmp"],mg=10*1024*1024,iE=2048,lE=2048,cE=.82,dE=512*1024,uE=e=>Oc.includes(e.type)?e.size>mg?{isValid:!1,error:`Image size too large: ${(e.size/1024/1024).toFixed(2)}MB. Maximum size: ${mg/1024/1024}MB`}:{isValid:!0}:{isValid:!1,error:`Unsupported image type: ${e.type}. Supported types: ${Oc.join(", ")}`},mE=e=>new Promise((t,n)=>{const s=new Image;s.onload=()=>t(s),s.onerror=()=>n(new Error("Failed to load image")),s.src=e}),hg=e=>new Promise((t,n)=>{const s=new FileReader;s.onload=()=>{typeof s.result=="string"?t(s.result):n(new Error("Failed to convert file to base64"))},s.onerror=()=>n(new Error("Failed to read file")),s.readAsDataURL(e)}),hE=e=>URL.createObjectURL(e),fE=(e,t,n,s)=>{let{width:r,height:a}=t;if(r>n||a>s){const l=r/a;r>a?(r=n,a=Math.round(r/l)):(a=s,r=Math.round(a*l))}e.width=r,e.height=a;const i=e.getContext("2d");i&&(i.fillStyle="#ffffff",i.fillRect(0,0,r,a),i.drawImage(t,0,0,r,a))},pE=async(e,t)=>{const n=await mE(e),s=document.createElement("canvas");return fE(s,n,iE,lE),bE(s,t)},gE=async e=>{const t=uE(e);if(!t.isValid)throw new Error(t.error);const n=hE(e);try{let s;if(e.type==="image/gif"||e.size<dE)s=await hg(e);else try{s=await pE(n,cE)}catch(a){console.warn("[imageUtils] Failed to re-encode image, using original:",a),s=await hg(e)}const r=`img_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return{file:e,base64:s,preview:n,id:r,name:e.name,size:e.size,type:e.type}}catch(s){throw oS(n),s}},yE=async e=>{const t=Array.from(e),n=[];for(const s of t)try{const r=await gE(s);n.push(r)}catch(r){console.error(`Failed to process image ${s.name}:`,r)}return n},bE=(e,t=.8)=>e.toDataURL("image/jpeg",t),oS=e=>{e.startsWith("blob:")&&URL.revokeObjectURL(e)},fg=e=>{e.forEach(t=>oS(t.preview))},xE=e=>{if(e===0)return"0 Bytes";const t=1024,n=["Bytes","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,s)).toFixed(2))+" "+n[s]},vE=e=>!e.files||e.files.length===0?!1:Array.from(e.files).some(t=>Oc.includes(t.type)),SE=e=>e.files?Array.from(e.files).filter(t=>Oc.includes(t.type)):[],{Text:wE,Title:_E}=Ke,kE=({visible:e,images:t,currentIndex:n=0,onClose:s,onDownload:r})=>{const{token:a}=Qe.useToken(),[i,l]=f.useState(n);if(!t||t.length===0)return null;const c=t[i],u=()=>{if(r&&c)r(c);else{const g=document.createElement("a");g.href=c.base64,g.download=c.name,document.body.appendChild(g),g.click(),document.body.removeChild(g)}},m=()=>{l(g=>g>0?g-1:t.length-1)},p=()=>{l(g=>g<t.length-1?g+1:0)};return o.jsxs(Xn,{open:e,onCancel:s,footer:null,width:"90vw",style:{top:20},styles:{body:{padding:0,height:"80vh",display:"flex",flexDirection:"column"}},closeIcon:o.jsx(Ho,{style:{color:a.colorTextLightSolid}}),children:[o.jsx("div",{style:{padding:a.paddingMD,borderBottom:`1px solid ${a.colorBorder}`,background:a.colorBgContainer},children:o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",width:"100%"},children:[o.jsxs("div",{children:[o.jsx(_E,{level:5,style:{margin:0},children:c.name}),o.jsxs(wE,{type:"secondary",style:{fontSize:a.fontSizeSM},children:[xE(c.size)," • ",c.type,t.length>1&&` • ${i+1} of ${t.length}`]})]}),o.jsxs(he,{children:[t.length>1&&o.jsxs(o.Fragment,{children:[o.jsx(de,{icon:o.jsx(uf,{}),onClick:m,disabled:t.length<=1}),o.jsx(de,{icon:o.jsx(Vs,{}),onClick:p,disabled:t.length<=1})]}),o.jsx(de,{icon:o.jsx(Wo,{}),onClick:u,children:"Download"})]})]})}),o.jsxs("div",{style:{flex:1,display:"flex",justifyContent:"center",alignItems:"center",background:a.colorBgLayout,position:"relative",overflow:"hidden"},children:[t.length===1?o.jsx("img",{src:c.preview,alt:c.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}}):o.jsx(o_,{dots:!1,arrows:!0,infinite:!0,afterChange:l,style:{width:"100%",height:"100%"},children:t.map(g=>o.jsx("div",{children:o.jsx("div",{style:{height:"70vh",display:"flex",justifyContent:"center",alignItems:"center"},children:o.jsx("img",{src:g.preview,alt:g.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}})})},g.id))}),t.length>1&&o.jsxs(o.Fragment,{children:[o.jsx(de,{type:"primary",shape:"circle",icon:o.jsx(uf,{}),onClick:m,style:{position:"absolute",left:20,top:"50%",transform:"translateY(-50%)",zIndex:10}}),o.jsx(de,{type:"primary",shape:"circle",icon:o.jsx(Vs,{}),onClick:p,style:{position:"absolute",right:20,top:"50%",transform:"translateY(-50%)",zIndex:10}})]})]}),t.length>1&&o.jsx("div",{style:{padding:a.paddingSM,borderTop:`1px solid ${a.colorBorder}`,background:a.colorBgContainer,display:"flex",gap:a.marginXS,overflowX:"auto",maxHeight:80},children:t.map((g,b)=>o.jsx("div",{style:{minWidth:60,height:60,border:b===i?`2px solid ${a.colorPrimary}`:`1px solid ${a.colorBorder}`,borderRadius:a.borderRadius,overflow:"hidden",cursor:"pointer",opacity:b===i?1:.7},onClick:()=>l(b),children:o.jsx("img",{src:g.preview,alt:g.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},g.id))})]})},Ta=e=>/\s/.test(e),TE=e=>{if(!e)return[{text:"",type:"text"}];const t=[],n=e.length;let s=0;for(;s<n;){const r=e[s],a=s>0?e[s-1]:"",i=r==="/"&&(s===0||Ta(a)),l=r==="@"&&(s===0||Ta(a));if(!i&&!l){let m=s;for(;s<n&&!((e[s]==="/"||e[s]==="@")&&(s===0||Ta(e[s-1])));)s+=1;t.push({text:e.slice(m,s),type:"text"});continue}let c=s+1;for(;c<n&&!Ta(e[c]);)c+=1;const u=e.slice(s,c);i?c===n||Ta(e[c])?t.push({text:u,type:"workflow"}):t.push({text:u,type:"text"}):l&&t.push({text:u,type:"file"}),s=c}return t.length>0?t:[{text:"",type:"text"}]},jE=/(\/)([a-zA-Z0-9_-]*)$/,CE=e=>{if(!e)return{command:null,isTriggerActive:!1,searchText:""};const t=e.match(jE);if(!t)return{command:null,isTriggerActive:!1,searchText:""};const n=t[2]||"",s=!n.includes(" ")&&t.index!==void 0;return{command:n||null,isTriggerActive:s,searchText:n}},ME=/@([a-zA-Z0-9._\-\/\\]*)$/,PE=e=>{if(!e)return{isTriggerActive:!1,searchText:"",tokenStart:null};const t=e.match(ME);if(!t||t.index===void 0)return{isTriggerActive:!1,searchText:"",tokenStart:null};const n=t[1]||"",s=t.index;return{isTriggerActive:!n.includes(" "),searchText:n,tokenStart:s}},EE=(e,t=80)=>{const[n,s]=f.useState(e);return f.useEffect(()=>{const r=window.setTimeout(()=>{s(e)},t);return()=>{window.clearTimeout(r)}},[e,t]),n},{Text:RE}=Ke,AE=({visible:e,token:t})=>e?o.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:t.colorPrimaryBg,borderRadius:t.borderRadius,zIndex:10,pointerEvents:"none"},children:o.jsxs(he,{direction:"vertical",align:"center",children:[o.jsx(a_,{style:{fontSize:32,color:t.colorPrimary}}),o.jsx(RE,{style:{color:t.colorPrimary,fontWeight:500},children:"Drop images here"})]})}):null,{Text:pg}=Ke,IE=({images:e,token:t,allowImages:n,onPreview:s,onClear:r})=>{const{t:a}=Ae();return!n||e.length===0?null:o.jsx("div",{style:{marginBottom:t.marginSM,padding:`${t.paddingXXS}px ${t.paddingXS}px`,borderRadius:999,border:`1px solid ${t.colorBorderSecondary}`,background:t.colorFillSecondary},children:o.jsxs(ve,{align:"center",wrap:"wrap",gap:t.marginXS,children:[o.jsx(pg,{type:"secondary",style:{fontSize:t.fontSizeSM,minWidth:"fit-content"},children:e.length>1?a("chat.input.imageCountPlural",{count:e.length}):a("chat.input.imageCountSingular",{count:e.length})}),e.slice(0,3).map(i=>o.jsx("div",{style:{position:"relative",width:32,height:32,borderRadius:999,overflow:"hidden",border:`1px solid ${t.colorBorderSecondary}`,cursor:"pointer"},onClick:()=>s(i),children:o.jsx("img",{src:i.preview,alt:i.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},i.id)),e.length>3&&o.jsx(pg,{type:"secondary",style:{fontSize:t.fontSizeSM},children:a("chat.input.moreImages",{count:e.length-3})}),o.jsx(de,{type:"text",size:"small",icon:o.jsx(Ho,{}),onClick:r,style:{marginLeft:"auto",minWidth:"auto",padding:"0 4px",height:24},title:a("chat.input.clearAllImages")})]})})},{TextArea:OE}=et,$E=({value:e,placeholder:t,disabled:n,token:s,highlightSegments:r,textAreaRef:a,highlightOverlayRef:i,onChange:l,onKeyDown:c,onPaste:u,onScrollSync:m})=>{const p=e.length>0&&r.some(x=>x.type!=="text"),g="6px 4px",b=1.65,S=n?s.colorTextDisabled:s.colorText;return o.jsxs("div",{style:{position:"relative",flex:1},children:[p?o.jsxs("div",{ref:i,"aria-hidden":!0,style:{position:"absolute",top:0,left:0,right:0,bottom:0,padding:g,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflow:"hidden",pointerEvents:"none",color:"transparent",fontSize:s.fontSize,lineHeight:b,fontFamily:"inherit",fontWeight:400,letterSpacing:"normal",transform:"translate(0, 0)",zIndex:0},children:[r.map((x,k)=>{let j;return x.type==="workflow"?j={backgroundColor:s.colorPrimaryBg,color:"transparent",WebkitTextFillColor:"transparent",fontWeight:400,textDecoration:"underline",textDecorationStyle:"dotted",textDecorationColor:s.colorPrimary}:x.type==="file"&&(j={backgroundColor:s.colorSuccessBg,color:"transparent",WebkitTextFillColor:"transparent"}),o.jsx("span",{style:j,children:x.text},`segment-${k}`)}),e.endsWith(`
156
+ `)?`
157
+ `:null]}):null,o.jsx(OE,{"data-testid":"chat-input",ref:a,value:e,onChange:x=>l(x.target.value),onKeyDown:c,onPaste:u,placeholder:t,disabled:n,autoSize:{minRows:3,maxRows:8},variant:"borderless",onScroll:m,className:"lotus-message-input-field",style:{resize:"none",flex:1,fontSize:s.fontSize,padding:g,lineHeight:b,border:"none",outline:"none",background:"transparent",color:S,WebkitTextFillColor:S,caretColor:S,position:"relative",zIndex:1,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflowY:"auto"}})]})},DE=({allowImages:e,disabled:t,isStreaming:n,token:s,fileInputRef:r,onFileInputChange:a,onFileReferenceButtonClick:i,extraControl:l})=>{const{t:c}=Ae();return o.jsxs(ve,{align:"center",style:{minWidth:0,gap:0},children:[e&&o.jsxs(o.Fragment,{children:[o.jsx("input",{ref:r,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:a}),o.jsx(de,{type:"text",icon:o.jsx(or,{}),onClick:()=>{var u;return(u=r.current)==null?void 0:u.click()},disabled:t||n,size:"small",style:{minWidth:36,padding:"0 8px",height:36,borderRadius:18,color:s.colorTextSecondary},title:c("chat.input.addAttachments"),"aria-label":c("chat.input.addAttachments")})]}),i&&o.jsx(de,{type:"text",icon:o.jsx(qo,{}),onClick:i,disabled:t||n,size:"small",style:{minWidth:36,padding:"0 8px",height:36,borderRadius:18,color:s.colorTextSecondary},title:c("chat.input.referenceWorkspaceFiles"),"aria-label":c("chat.input.referenceWorkspaceFiles")}),l]})},LE=({allowRetry:e,hasMessages:t,isStreaming:n,canCancel:s,disabled:r,onRetry:a,onCancel:i,onSubmit:l,value:c,images:u,isOverCharLimit:m,token:p,statusIndicator:g,submitButtonLabel:b})=>{const{t:S}=Ae(),x=!c.trim()&&u.length===0,k=s??n,j=k||r||!a,w=b??S("chat.actions.sendMessage");return o.jsxs(ve,{align:"center",style:{flex:"0 0 auto",gap:p.marginXS},children:[g?o.jsx("span",{style:{flex:"0 0 auto"},children:g}):null,e&&t&&o.jsx(lo,{trigger:["click"],menu:{items:[{key:"regenerate",label:S("chat.actions.regenerate"),icon:o.jsx(cr,{})},{key:"error_retry",label:S("chat.actions.retryFailed"),icon:o.jsx(Om,{})}],onClick:({key:M})=>a==null?void 0:a(M)},disabled:j,children:o.jsx(de,{"data-testid":"regenerate-button",type:"text",icon:o.jsx(Im,{spin:n}),disabled:j,title:S("chat.actions.retryOptions"),"aria-label":S("chat.actions.retryOptions"),size:"small",className:"lotus-secondary-button",style:{minWidth:38,padding:"0 8px",height:38,width:38,borderRadius:19,color:p.colorTextSecondary}})}),o.jsx(de,{"data-testid":k?"cancel-button":"send-button",type:"primary",icon:k?o.jsx(i_,{}):o.jsx(l_,{}),onClick:k?i:l,loading:k&&!i,disabled:k?!i||r:x||r||m,size:"small",danger:k,className:k?"message-input-send-button":"message-input-send-button lotus-primary-cta",style:{minWidth:50,padding:0,height:50,width:50,borderRadius:25,display:"inline-flex",alignItems:"center",justifyContent:"center",background:k?void 0:"linear-gradient(135deg, var(--lotus-primary) 0%, var(--lotus-accent-secondary) 100%)",border:k?void 0:"none",boxShadow:k?void 0:"var(--lotus-send-btn-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",transform:"scale(1)"},title:k?S("chat.actions.cancelRequest"):w,"aria-label":k?S("chat.actions.cancelRequest"):w})]})},{Text:gg}=Ke,FE=({charCount:e,maxCharCount:t,isOverCharLimit:n,isNearCharLimit:s,isProcessingAttachments:r,token:a})=>{const i=typeof t=="number"&&Number.isFinite(t)&&t>0;return!r&&!s&&!n?null:o.jsxs(o.Fragment,{children:[i&&o.jsx(ve,{justify:"flex-end",style:{marginTop:a.marginXXS},children:o.jsxs(gg,{type:n?"danger":s?"warning":"secondary",style:{fontSize:a.fontSizeSM},children:[e.toLocaleString()," / ",t.toLocaleString()]})}),r&&o.jsxs(he,{size:"small",style:{marginTop:a.marginXS},children:[o.jsx(Rs,{size:"small"}),o.jsx(gg,{type:"secondary",children:"Processing files…"})]})]})},NE=({onFiles:e,mode:t="images"})=>{const[n,s]=f.useState(!1),r=f.useCallback(l=>{var u,m;l.preventDefault(),l.stopPropagation(),(t==="images"?vE(l.dataTransfer):((m=(u=l.dataTransfer)==null?void 0:u.files)==null?void 0:m.length)>0)&&s(!0)},[t]),a=f.useCallback(l=>{l.preventDefault(),l.stopPropagation(),s(!1)},[]),i=f.useCallback(l=>{if(l.preventDefault(),l.stopPropagation(),s(!1),t==="images"){const u=SE(l.dataTransfer);u.length>0&&e(u);return}const c=Array.from(l.dataTransfer.files||[]);c.length>0&&e(c)},[t,e]);return{isDragOver:n,handleDragOver:r,handleDragLeave:a,handleDrop:i}},zE=e=>{const{message:t}=en.useApp(),[n,s]=f.useState([]),[r,a]=f.useState(!1),[i,l]=f.useState(0),c=f.useCallback(async g=>{if(e)try{const b=await yE(g);b.length>0&&(s(S=>[...S,...b]),t.success(`Added ${b.length} image(s)`))}catch(b){t.error(`Failed to process images: ${b}`)}},[e,t]),u=f.useCallback(g=>{const b=n.find(S=>S.id===g);b&&fg([b]),s(S=>S.filter(x=>x.id!==g))},[n]),m=f.useCallback(g=>{const b=n.findIndex(S=>S.id===g.id);l(b>=0?b:0),a(!0)},[n]),p=f.useCallback(()=>{fg(n),s([])},[n]);return{images:n,setImages:s,previewModalVisible:r,setPreviewModalVisible:a,previewImageIndex:i,handleImageFiles:c,handleRemoveImage:u,handleImagePreview:m,clearImages:p}},BE=({onImages:e,onAttachments:t,allowImages:n})=>({handlePaste:f.useCallback(r=>{if(!r.clipboardData)return;const a=Array.from(r.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&&n&&(r.preventDefault(),e(i)),l.length>0&&t&&(r.preventDefault(),t(l))},[n,e,t])}),Tn=[];for(let e=0;e<256;++e)Tn.push((e+256).toString(16).slice(1));function WE(e,t=0){return(Tn[e[t+0]]+Tn[e[t+1]]+Tn[e[t+2]]+Tn[e[t+3]]+"-"+Tn[e[t+4]]+Tn[e[t+5]]+"-"+Tn[e[t+6]]+Tn[e[t+7]]+"-"+Tn[e[t+8]]+Tn[e[t+9]]+"-"+Tn[e[t+10]]+Tn[e[t+11]]+Tn[e[t+12]]+Tn[e[t+13]]+Tn[e[t+14]]+Tn[e[t+15]]).toLowerCase()}const qE=new Uint8Array(16);function UE(){return crypto.getRandomValues(qE)}function yg(e,t,n){return crypto.randomUUID?crypto.randomUUID():HE(e)}function HE(e,t,n){var r;e=e||{};const s=e.random??((r=e.rng)==null?void 0:r.call(e))??UE();if(s.length<16)throw new Error("Random bytes length must be >= 16");return s[6]=s[6]&15|64,s[8]=s[8]&63|128,WE(s)}const KE=["text/","application/json","application/xml"],YE=[".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"],VE=200*1024,aS=e=>e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`,bg=e=>{const t=e.toLowerCase();return YE.some(n=>t.endsWith(n))},XE=e=>!e.type&&bg(e.name)?!0:KE.some(t=>e.type.startsWith(t))||bg(e.name),GE=e=>new Promise((t,n)=>{const s=new FileReader;s.onerror=()=>n(s.error),s.onload=()=>t(s.result),s.readAsText(e)}),xg=async(e,t)=>{const n=VE,s=[],r=[];for(const a of e)try{if(XE(a)&&a.size<=n){const i=await GE(a);s.push({id:yg(),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 s.push({id:yg(),file:a,name:a.name,size:a.size,type:a.type||"application/octet-stream",kind:"binary",preview:`(${aS(a.size)}) Preview unavailable for this file type.`,lastModified:a.lastModified})}catch(i){console.error("[fileUtils] Failed to process file",a.name,i),r.push(`Failed to process ${a.name}: ${i.message}`)}return{processed:s,errors:r}},JE=e=>{const t=[],n=[];return e.forEach(s=>{s.type.startsWith("image/")?t.push(s):n.push(s)}),{images:t,others:n}},QE=e=>e.length===0?"":e.map(t=>{const n=`### File: ${t.name}`,s=`(_${aS(t.size)}_, ${t.type||"unknown"})`;return t.kind==="text"&&t.content?`${n}
158
+ ${s}
159
+
160
+ \`\`\`
161
+ ${t.content}
162
+ \`\`\``:`${n}
163
+ ${s}
164
+
165
+ > Preview unavailable for this file type.`}).join(`
166
+
167
+ `),ZE=({allowImages:e,onAttachmentsAdded:t,messageApi:n})=>{const[s,r]=f.useState(!1),{images:a,setImages:i,previewModalVisible:l,setPreviewModalVisible:c,previewImageIndex:u,handleImageFiles:m,handleImagePreview:p,clearImages:g}=zE(e),b=f.useCallback(async _=>{if(!_||_.length===0)return;const{images:C,others:D}=JE(_);if(C.length>0&&await m(C),D.length>0&&t){r(!0);const{processed:A,errors:B}=await xg(D);A.length>0&&(t(A),n.success(`Added ${A.length} file(s)`)),B.forEach(F=>n.error(F)),r(!1)}},[m,n,t]),{isDragOver:S,handleDragOver:x,handleDragLeave:k,handleDrop:j}=NE({onFiles:b,mode:"any"}),{handlePaste:w}=BE({onImages:m,onAttachments:t?async _=>{r(!0);const{processed:C,errors:D}=await xg(_);C.length>0&&(t(C),n.success(`Attached ${C.length} file(s)`)),D.forEach(A=>n.error(A)),r(!1)}:void 0,allowImages:e}),M=f.useCallback(_=>{const C=_.target.files;C&&C.length>0&&m(C),_.target.value=""},[m]);return{images:a,setImages:i,previewModalVisible:l,setPreviewModalVisible:c,previewImageIndex:u,handleImageFiles:m,handleImagePreview:p,clearImages:g,isProcessingAttachments:s,isDragOver:S,handleDragOver:x,handleDragLeave:k,handleDrop:j,handlePaste:w,handleFileInputChange:M}},e1=({value:e,debouncedValue:t,onWorkflowCommandChange:n,onFileReferenceChange:s,onImagesChange:r,images:a,propImages:i,setImages:l,syncOverlayScroll:c})=>{f.useEffect(()=>{c()},[e,c]),f.useEffect(()=>{n&&n(CE(t))},[t,n]),f.useEffect(()=>{s&&s(PE(t))},[t,s]),f.useEffect(()=>{r&&r(a)},[a,r]),f.useEffect(()=>{i&&l(i)},[i,l])},t1=({value:e,images:t,isStreaming:n,disabled:s,isWorkflowSelectorVisible:r,onChange:a,onSubmit:i,onRetry:l,onHistoryNavigate:c,validateMessage:u,isOverCharLimit:m,maxCharCount:p,messageApi:g,clearImages:b,textAreaRef:S})=>{const x=f.useCallback(()=>{const w=e.trim();if(!(!w&&t.length===0||n||s)){if(m){const M=typeof p=="number"?p.toLocaleString():"configured";g.error(`Message exceeds the maximum length of ${M} characters.`);return}if(u){const M=u(w);if(!M.isValid){g.error(M.errorMessage||"Message format is incorrect");return}}i(w,t.length>0?t:void 0),b()}},[b,s,t,m,n,p,g,i,u,e]),k=f.useCallback(w=>{if(c&&!s&&!n&&!w.shiftKey&&(w.key==="ArrowUp"||w.key==="ArrowDown")){const M=w.key==="ArrowUp"?"previous":"next",_=c(M,e);if(_!=null){w.preventDefault(),a(_),requestAnimationFrame(()=>{var D,A;const C=((A=(D=S.current)==null?void 0:D.resizableTextArea)==null?void 0:A.textArea)||null;if(C){const B=_.length;C.setSelectionRange(B,B)}});return}}w.key==="Enter"&&!w.shiftKey&&!n&&!s&&!r&&(w.preventDefault(),x())},[s,x,n,r,a,c,S,e]),j=f.useCallback((w="regenerate")=>{n||s||!l||l(w)},[s,n,l]);return{handleKeyDown:k,handleSubmit:x,handleRetry:j}},n1=({value:e,onChange:t,onSubmit:n,interaction:s,placeholder:r,disabled:a=!1,images:i,onImagesChange:l,allowImages:c=!0,isWorkflowSelectorVisible:u=!1,textAreaRef:m,statusIndicator:p,validateMessage:g,onAttachmentsAdded:b,onWorkflowCommandChange:S,onFileReferenceChange:x,onFileReferenceButtonClick:k,maxCharCount:j,leftControlsExtra:w,submitButtonLabel:M})=>{const{t:_}=Ae(),{isStreaming:C,canCancel:D,hasMessages:A,allowRetry:B=!0,onRetry:F,onCancel:O,onHistoryNavigate:R}=s,I=f.useRef(null),L=f.useRef(null),U=m||L,q=f.useRef(null),{token:H}=Qe.useToken(),P=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",[W,ne]=Cr.useMessage(),K=e.length,xe=typeof j=="number"&&Number.isFinite(j)&&j>0,se=xe?K>j:!1,fe=xe?!se&&K>=j*.9:!1,{images:Se,setImages:me,previewModalVisible:ze,setPreviewModalVisible:st,previewImageIndex:pt,handleImagePreview:Kt,clearImages:Oe,isProcessingAttachments:Wt,isDragOver:Xe,handleDragOver:_e,handleDragLeave:Ye,handleDrop:ot,handlePaste:Lt,handleFileInputChange:N}=ZE({allowImages:c,onAttachmentsAdded:b,messageApi:W}),le=EE(e,80),be=f.useMemo(()=>TE(e),[e]),De=()=>{var pe,Re;const He=(Re=(pe=U.current)==null?void 0:pe.resizableTextArea)==null?void 0:Re.textArea;if(!He||!q.current)return;const ae=He.scrollTop,ke=He.scrollLeft;q.current.style.transform=`translate(${-ke}px, ${-ae}px)`};e1({value:e,debouncedValue:le,onWorkflowCommandChange:S,onFileReferenceChange:x,onImagesChange:l,images:Se,propImages:i,setImages:me,syncOverlayScroll:De});const{handleKeyDown:Le,handleSubmit:ue,handleRetry:ye}=t1({value:e,images:Se,isStreaming:C,disabled:a,isWorkflowSelectorVisible:u,onChange:t,onSubmit:n,onRetry:F,onHistoryNavigate:R,validateMessage:g,isOverCharLimit:se,maxCharCount:j,messageApi:W,clearImages:Oe,textAreaRef:U}),qe=r??_("chat.input.placeholder");return o.jsxs(o.Fragment,{children:[ne,o.jsxs("div",{className:`message-input-container lotus-message-input-shell ${Xe?"is-drag-over":""}`,role:"group","aria-label":_("chat.input.messageComposer","Message composer"),style:{position:"relative",border:`1px solid ${Xe?"var(--lotus-input-border-active)":"var(--lotus-input-border)"}`,borderRadius:26,background:Xe?"var(--lotus-input-bg-active)":"var(--lotus-input-bg)",backdropFilter:P?"none":"blur(18px)",WebkitBackdropFilter:P?"none":"blur(18px)",boxShadow:"var(--lotus-input-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",width:"100%",padding:`${H.paddingSM}px`,overflow:"hidden"},onDragOver:_e,onDragLeave:Ye,onDrop:ot,children:[o.jsx(IE,{images:Se,token:H,allowImages:c,onPreview:Kt,onClear:Oe}),o.jsx(AE,{visible:Xe,token:H}),o.jsxs(ve,{vertical:!0,style:{gap:H.marginXS,minHeight:132,width:"100%"},children:[o.jsx($E,{value:e,placeholder:qe,disabled:a,token:H,highlightSegments:be,textAreaRef:U,highlightOverlayRef:q,onChange:t,onKeyDown:Le,onPaste:Lt,onScrollSync:De}),o.jsxs(ve,{align:"center",justify:"space-between",gap:H.marginSM,wrap:"wrap",style:{rowGap:H.marginXS},children:[o.jsx(ve,{align:"center",gap:H.marginXS,wrap:"wrap",style:{minWidth:0,flex:"1 1 260px"},children:o.jsx(DE,{allowImages:c,disabled:a,isStreaming:C,token:H,fileInputRef:I,onFileInputChange:N,onFileReferenceButtonClick:k,extraControl:w})}),o.jsx(LE,{allowRetry:B,hasMessages:A,isStreaming:C,canCancel:D,disabled:a,onRetry:ye,onCancel:O,onSubmit:ue,value:e,images:Se,isOverCharLimit:se,token:H,statusIndicator:p,submitButtonLabel:M})]})]})]}),o.jsx(FE,{charCount:K,maxCharCount:j,isOverCharLimit:se,isNearCharLimit:fe,isProcessingAttachments:Wt,token:H}),c&&o.jsx(kE,{visible:ze,images:Se,currentIndex:pt,onClose:()=>st(!1)})]})},{Text:vg}=Ke,{useToken:s1}=Qe,r1=({text:e,onClose:t})=>{const{token:n}=s1(),r=(e.length>150?e.substring(0,147)+"...":e).replace(/^> |^>/gm,"");return o.jsx("div",{style:{marginBottom:n.marginSM,background:n.colorFillSecondary,borderRadius:999,border:`1px solid ${n.colorBorderSecondary}`,padding:`${n.paddingXXS}px ${n.paddingSM}px`},children:o.jsxs(he,{style:{width:"100%",justifyContent:"space-between",alignItems:"flex-start"},children:[o.jsxs("div",{style:{flex:1},children:[o.jsx(vg,{style:{fontSize:n.fontSizeSM,color:n.colorPrimary},children:"Referencing"}),o.jsx(vg,{style:{fontSize:n.fontSizeSM,color:n.colorTextSecondary,marginLeft:n.marginSM},ellipsis:!0,children:r})]}),o.jsx(de,{type:"text",size:"small",icon:o.jsx(Ho,{}),onClick:t,style:{marginLeft:n.marginXS,color:n.colorTextSecondary,borderRadius:999}})]})})},o1=e=>{const t=f.useRef(new Map),n=f.useRef(!1),[s,r]=f.useState(null);f.useEffect(()=>{r(null),n.current=!1},[e]);const a=f.useCallback(u=>{if(!e)return;const m=u.trim();if(!m)return;const p=t.current.get(e)??[];if(p[p.length-1]===m)return;const g=[...p,m].slice(-50);t.current.set(e,g),r(null),n.current=!1},[e]),i=f.useCallback((u,m)=>{if(!e)return{value:null,applied:!1};const p=t.current.get(e)??[];if(p.length===0)return{value:null,applied:!1};const g=m.trim();if(u==="previous"){if(g.length>0&&s===null)return{value:null,applied:!1};const S=s??p.length,x=Math.max(0,S-1);return x===s?{value:null,applied:!1}:(r(x),n.current=!0,{value:p[x]??null,applied:!0})}if(s===null)return{value:null,applied:!1};const b=s+1;return b>=p.length?(r(null),n.current=!0,{value:"",applied:!0}):(r(b),n.current=!0,{value:p[b]??null,applied:!0})},[e,s]),l=f.useCallback(()=>{if(n.current){n.current=!1;return}s!==null&&r(null)},[s]),c=f.useCallback(()=>{e&&(t.current.delete(e),r(null),n.current=!1)},[e]);return{recordEntry:a,navigate:i,acknowledgeManualInput:l,clearHistory:c}},to=class to{constructor(){jt(this,"cache",null);jt(this,"cacheTime",0);jt(this,"CACHE_TTL",3e4)}static getInstance(){return to.instance||(to.instance=new to),to.instance}async listCommands(t=!1){const n=Date.now();if(!t&&this.cache&&n-this.cacheTime<this.CACHE_TTL)return this.cache;try{const s=await at.get("commands");if(!Array.isArray(s.commands))throw new Error("Invalid command list response");return this.cache=s.commands,this.cacheTime=n,Jt("[CommandService]","[CommandService] Loaded commands:",this.cache.length),this.cache}catch(s){throw console.error("[CommandService] Failed to list commands:",s),s}}async getCommand(t,n){try{return await at.get(`commands/${t}/${n}`)}catch(s){throw console.error(`[CommandService] Failed to get command ${t}/${n}:`,s),s}}clearCache(){this.cache=null,this.cacheTime=0}};jt(to,"instance");let Ii=to;const Jo=e=>{if(typeof e!="string"||!e.startsWith("mcp__"))return null;const t=e.slice(5),n=t.indexOf("__");if(n<=0)return null;const s=t.slice(0,n),r=t.slice(n+2);return!s||!r?null:{serverId:s,toolName:r}},a1=({setContent:e,onWorkflowDraftChange:t,acknowledgeManualInput:n,currentSessionId:s,textAreaRef:r,content:a})=>{const[i,l]=f.useState(!1),[c,u]=f.useState(""),[m,p]=f.useState(null);f.useEffect(()=>{p(null),t==null||t(null)},[s,t]);const g=f.useCallback((C,D)=>{const A=C.trimStart(),B=`/${D}`;if(!A.startsWith(B))return!1;const F=A.charAt(B.length);return!F||/\s/.test(F)},[]),b=f.useCallback(()=>{p(null),t==null||t(null)},[t]),S=f.useCallback((C,D)=>{if(!g(C,D.name))return;const A=`/${D.name}`,F=C.trim().slice(A.length).trim(),O=[D.content,F].filter(Boolean).join(`
168
+
169
+ `);t==null||t({...D,content:O})},[g,t]),x=f.useCallback(C=>{n(),m&&!g(C,m.name)&&b(),m&&g(C,m.name)&&S(C,m),e(C)},[n,b,g,m,S,e]),k=f.useCallback(C=>{l(C.isTriggerActive),u(C.isTriggerActive?C.searchText:"")},[]),j=f.useCallback(async C=>{var q,H,P,W,ne,K;l(!1);const A=(xe=>{var Se;if(xe.type!=="mcp")return xe.name;const se=(Se=xe.metadata)==null?void 0:Se.originalName;if(typeof se=="string"&&se.trim())return se.trim();const fe=Jo(xe.name);return fe!=null&&fe.toolName?fe.toolName:xe.displayName||xe.name})(C),B=(H=(q=r.current)==null?void 0:q.resizableTextArea)==null?void 0:H.textArea,F=(B==null?void 0:B.selectionStart)??a.length;let O,R;const L=a.substring(0,F).match(/\/([a-zA-Z0-9_-]*)$/);if(L){const xe=F-L[0].length,se=a.substring(0,xe),fe=a.substring(F);O=`${se}/${A} ${fe}`,R=`${se}/${A} `.length}else if(a.trim()==="")O=`/${A} `,R=O.length;else{const xe=a.substring(0,F),se=a.substring(F);O=`${xe}/${A} ${se}`,R=`${xe}/${A} `.length}if(e(O),setTimeout(()=>{B&&(B.selectionStart=R,B.selectionEnd=R,B.focus())},0),C.type!=="workflow"){const xe={id:`command-draft-${C.id}`,name:A,content:"",createdAt:new Date().toISOString(),type:C.type,displayName:C.displayName,mcpAlias:C.type==="mcp"?C.name:void 0,mcpServerId:C.type==="mcp"?(P=C.metadata)==null?void 0:P.serverId:void 0,mcpServerName:C.type==="mcp"?(W=C.metadata)==null?void 0:W.serverName:void 0,mcpOriginalName:C.type==="mcp"?(ne=C.metadata)==null?void 0:ne.originalName:void 0};p(xe),t==null||t(xe);return}const U=Ii.getInstance();try{const xe=C.id.startsWith("workflow-")?C.id.slice(9):C.id,fe=((K=(await U.getCommand(C.type,xe)).content)==null?void 0:K.trim())||"";if(fe){const Se={id:`command-draft-${C.id}`,name:C.name,content:fe,createdAt:new Date().toISOString(),type:C.type,displayName:C.displayName};p(Se),t==null||t(Se)}else b()}catch(xe){console.error(`[InputContainer] Failed to apply command '${C.name}':`,xe),b()}},[b,t,e,a,r]),w=f.useCallback(async C=>{try{const B=(await Ii.getInstance().listCommands()).find(F=>F.id===C.id&&F.type===C.type);if(!B){console.error(`[InputContainer] Command '${C.id}' of type '${C.type}' not found`),e(`/${C.name} `),b();return}await j(B)}catch(D){console.error(`[InputContainer] Failed to select command '${C.name}':`,D),e(`/${C.name} `),b()}},[j,b,e]),M=f.useCallback(()=>{l(!1)},[]),_=f.useCallback(async C=>{l(!1);try{const B=(await Ii.getInstance().listCommands()).find(F=>F.name===C);B?await j(B):(console.error(`[InputContainer] Command '${C}' not found in auto-complete`),e(`/${C} `),b())}catch(D){console.error(`[InputContainer] Failed to load command '${C}' in auto-complete:`,D),e(`/${C} `),b()}},[j,b,e]);return{selectedCommand:m,showCommandSelector:i,commandSearchText:c,clearCommandDraft:b,matchesCommandToken:g,handleInputChange:x,handleCommandChange:k,handleCommandSelect:w,handleCommandSelectorCancel:M,handleAutoComplete:_,setShowCommandSelector:l}};class i1{constructor(t={}){jt(this,"cache",null);jt(this,"options");jt(this,"validateWorkspacePath",this.validatePath.bind(this));jt(this,"getRecentWorkspaces",this.getRecent.bind(this));jt(this,"addRecentWorkspace",this.addRecent.bind(this));jt(this,"removeRecentWorkspace",this.removeRecent.bind(this));jt(this,"clearRecentWorkspaces",this.clearRecent.bind(this));jt(this,"getWorkspaceSuggestions",this.getCombinedSuggestions.bind(this));jt(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 at.post("workspace/validate",{path:t})}async getRecent(){var t;if(this.isCacheValid())return this.cache.recentWorkspaces;try{const n=await at.get("workspace/recent",{signal:AbortSignal.timeout(this.options.requestTimeoutMs)});return this.cache={recentWorkspaces:n,timestamp:Date.now()},n}catch(n){if(console.error("Failed to get recent workspaces:",n),(t=this.cache)!=null&&t.recentWorkspaces)return this.cache.recentWorkspaces;throw n}}async addRecent(t,n){await at.post("workspace/recent",{path:t,metadata:n}),this.invalidateCache()}async removeRecent(t){const s=(await this.getRecent()).filter(r=>r.path!==t);this.cache={recentWorkspaces:s,timestamp:Date.now()}}async clearRecent(){this.cache=null}async getPathSuggestions(){return at.get("workspace/suggestions")}async browseFolder(t){return at.post("workspace/browse-folder",{path:t})}async getCombinedSuggestions(){const[t,n]=await Promise.all([this.getPathSuggestions().catch(()=>({suggestions:[]})),this.getRecent().catch(()=>[])]),r=[...t.suggestions.map(i=>({path:i.path,is_valid:!0,workspace_name:i.name})),...n];return this.deduplicateByPath(r).sort((i,l)=>{const c=n.findIndex(m=>m.path===i.path),u=n.findIndex(m=>m.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 n,s,r;const t=Date.now();try{await at.get("workspace/recent",{signal:AbortSignal.timeout(2e3)});const a=((n=this.cache)==null?void 0:n.recentWorkspaces)||await this.getRecent();return{available:!0,cacheValid:this.isCacheValid(),recentCount:a.length,latency:Date.now()-t}}catch(a){return{available:!1,cacheValid:this.isCacheValid(),recentCount:((r=(s=this.cache)==null?void 0:s.recentWorkspaces)==null?void 0:r.length)||0,error:a instanceof Error?a.message:"Unknown error"}}}async listWorkspaceFiles(t,n){return at.post("workspace/files",{path:t,max_depth:(n==null?void 0:n.max_depth)??3,max_entries:(n==null?void 0:n.max_entries)??500,include_hidden:(n==null?void 0:n.include_hidden)??!1})}isCacheValid(){return this.cache?!(Date.now()-this.cache.timestamp>this.options.cacheTimeoutMs):!1}invalidateCache(){this.cache=null}deduplicateByPath(t){const n=new Set;return t.filter(s=>n.has(s.path)?!1:(n.add(s.path),!0))}}const l1=new i1,c1=({content:e,setContent:t,currentSessionId:n,currentChat:s,updateSession:r,messageApi:a})=>{const[i,l]=f.useState(new Map),[c,u]=f.useState([]),[m,p]=f.useState(!1),[g,b]=f.useState(""),[S,x]=f.useState(!1),[k,j]=f.useState(""),[w,M]=f.useState(!1),[_,C]=f.useState(null),[D,A]=f.useState(!1),B=f.useRef(null);f.useEffect(()=>{S&&j((s==null?void 0:s.config.workspacePath)??"")},[S,s==null?void 0:s.config.workspacePath]),f.useEffect(()=>{p(!1),b(""),u([]),l(new Map),B.current=(s==null?void 0:s.config.workspacePath)??null},[n,s==null?void 0:s.config.workspacePath]);const F=f.useCallback(async(H,P)=>{M(!0),u([]),C(null);try{const W=await l1.listWorkspaceFiles(P);u(W),B.current=P}catch(W){console.error("Failed to load workspace files:",W),C(W instanceof Error?W.message:"Workspace file browsing is unavailable.")}finally{M(!1)}},[]),O=f.useCallback(H=>{if(b(H.searchText),!H.isTriggerActive){p(!1);return}if(!n||!s){p(!1);return}const P=s.config.workspacePath;if(!P){j(""),x(!0),p(!1);return}p(!0),(B.current!==P||c.length===0)&&F(n,P)},[s,n,F,c.length]),R=f.useCallback(H=>{const P=e.lastIndexOf("@");let W;P>=0&&e.substring(P).match(/^@[a-zA-Z0-9._\\-\\/\\\\]*$/)?W=`${e.slice(0,P)}@${H.name} `:W=e.trim()?`${e.trim()} @${H.name} `:`@${H.name} `,t(W),l(ne=>{const K=new Map(ne);return K.set(H.name,H),K}),p(!1),b("")},[e,t]),I=f.useCallback(()=>{p(!1)},[]),L=f.useCallback(()=>{if(!n||!s)return;const H=s.config.workspacePath;if(!H){j(""),x(!0),p(!1);return}b(""),p(!0),(B.current!==H||c.length===0)&&F(n,H)},[s,n,F,c.length]),U=f.useCallback(()=>{x(!1),j("")},[]),q=f.useCallback(async H=>{if(!s||!n)return;const P=H.trim();if(!P){a.error("Workspace path cannot be empty");return}A(!0);try{r(n,{config:{...s.config,workspacePath:P}}),x(!1),j(""),p(!1),C(null)}catch(W){const ne=W instanceof Error?W.message:"Unable to save workspace path";a.error(ne)}finally{A(!1)}},[s,n,a,r]);return{fileReferences:i,setFileReferences:l,workspaceFiles:c,showFileSelector:m,setShowFileSelector:p,fileSearchText:g,isWorkspaceLoading:w,workspaceError:_,isWorkspaceModalVisible:S,workspacePathInput:k,isSavingWorkspace:D,setWorkspacePathInput:j,setIsWorkspaceModalVisible:x,handleFileReferenceChange:O,handleFileReferenceSelect:R,handleFileSelectorCancel:I,handleFileReferenceButtonClick:L,handleWorkspaceModalCancel:U,handleWorkspaceModalSubmit:q,fetchWorkspaceFiles:F}},d1=()=>{const[e,t]=f.useState([]),n=f.useCallback(a=>{t(i=>[...i,...a])},[]),s=f.useCallback(a=>{t(i=>i.filter(l=>l.id!==a))},[]),r=f.useCallback(()=>{t([])},[]);return{attachments:e,setAttachments:t,handleAttachmentsAdded:n,handleAttachmentRemove:s,handleClearAttachments:r}},u1=({attachments:e,referenceText:t,selectedWorkflow:n,matchesWorkflowToken:s,fileReferences:r,reasoningEffort:a,sendMessage:i,recordEntry:l,clearWorkflowDraft:c,setContent:u,setReferenceText:m,setAttachments:p,setFileReferences:g})=>({handleSubmit:f.useCallback(async(S,x)=>{const k=S.trim(),j=QE(e),w=(t==null?void 0:t.trim())??"";let M=k,_;if(n!=null&&n.content&&n.type==="workflow"){const D=`/${n.name}`;if(s(k,n.name)){const B=k.slice(D.length).trim();M=[n.content,B].filter(Boolean).join(`
170
+
171
+ `)}}else if((n==null?void 0:n.type)==="skill"){const D=`/${n.name}`;if(s(k,n.name)){const B=k.slice(D.length).trim();M=[`[User explicitly selected skill: ${n.displayName||n.name} (ID: ${n.name})]`,B].filter(Boolean).join(`
172
+
173
+ `),_=[n.name]}}else if((n==null?void 0:n.type)==="mcp"){const D=`/${n.name}`;if(s(k,n.name)){const B=k.slice(D.length).trim();M=[`[User explicitly selected MCP tool: ${n.mcpAlias||n.displayName||n.name}]`,B].filter(Boolean).join(`
174
+
175
+ `)}}if(!M&&!j&&(!x||x.length===0))return;const C=[w,M,j].filter(Boolean).join(`
176
+
177
+ `);if(l(C),u(""),c(),r.size>0){const D=Array.from(C.matchAll(/@([^\\s]+)/g));if(D.length>0){const A=[];for(const B of D){const F=B[1],O=r.get(F);O&&A.push(O)}if(A.length>0){const B=JSON.stringify({type:"file_reference",paths:A.map(F=>F.path),display_text:C});await i(B,x,a,_)}else await i(C,x,a,_)}else await i(C,x,a,_)}else await i(C,x,a,_);m(null),p([]),g(new Map)},[e,c,r,s,l,a,n,i,p,u,g,m,t])}),m1=({currentSessionId:e,currentChat:t,currentMessages:n,reasoningEffort:s,retryLastTurn:r,navigate:a})=>{const i=f.useCallback(async(c="regenerate")=>{if(!e||!t)return;const u=[...n];u.length===0||[...u].reverse().findIndex(p=>p.role==="user")===-1||await r(s,c)},[t,e,n,s,r]),l=f.useCallback((c,u)=>{const m=a(c,u);return m.applied?m.value:null},[a]);return{retryLastMessage:i,handleHistoryNavigate:l}},h1=({referenceText:e,isToolSpecificMode:t,isRestrictConversation:n,allowedTools:s,autoToolPrefix:r,t:a})=>a(e?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows"),fm="chat-toggle-batch-export-selection",pm="chat-focus-input",zo="chat-pending-question-resolved",f1=f.lazy(()=>Bn(()=>import("./index-CTVpEC_u.js"),__vite__mapDeps([8,1,2,3]),import.meta.url)),p1=f.lazy(()=>Bn(()=>import("./index-jIgpBMFj.js"),__vite__mapDeps([9,1,2,3,4,5,6,7,10]),import.meta.url)),g1=f.lazy(()=>Bn(()=>import("./index-BR-Jz13T.js"),__vite__mapDeps([11,1,2,3,4,5,6,7]),import.meta.url)),y1=f.lazy(()=>Bn(()=>import("./index-Byt6VrzO.js"),__vite__mapDeps([12,1,2,3]),import.meta.url)),{useToken:b1}=Qe,Sg="chat-send-message",wg="reference-text",x1="chat-model-options-cache-v1",iS=24*60*60*1e3,v1=["low","medium","high","xhigh","max"],S1=[],lS=e=>`${x1}:${e}`,w1=e=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(lS(e));if(!t)return null;const n=JSON.parse(t);return!n||!Array.isArray(n.options)||Date.now()-n.timestamp>iS?null:n.options.filter(s=>s&&typeof s.value=="string"&&s.value.trim().length>0&&typeof s.label=="string").map(s=>({value:s.value,label:s.label}))}catch{return null}},_1=(e,t)=>{if(!(typeof window>"u"))try{const n={timestamp:Date.now(),options:t};localStorage.setItem(lS(e),JSON.stringify(n))}catch{}},k1=async e=>{const t=Wn.getInstance();try{const n=await t.loadModelOptionsCache(e);if(n)return Date.now()-n.timestamp>iS?null:n.options.filter(s=>s&&typeof s.value=="string"&&s.value.trim().length>0&&typeof s.label=="string")}catch{}return w1(e)},T1=async(e,t)=>{const n=Wn.getInstance();try{await n.saveModelOptionsCache(e,t,Date.now())}catch{}_1(e,t)},j1=({sessionId:e,onWorkflowDraftChange:t,statusIndicator:n})=>{var Ir,al;const{t:s}=Ae(),r=f.useRef(null),{token:a}=b1(),i=Bm(),l=rr(we=>we.open),c=G(we=>e??we.currentSessionId),u=G(we=>we.currentSessionId),m=G(Er(c)),p=(m==null?void 0:m.messages)||[],g=G(we=>we.addMessage),b=G(we=>we.updateSession),S=G(rx(c)),x=G(ox(c)),k=G(we=>we.markRespondStart),j=G(we=>we.markSettleTimeout),w=G(Ci(c)),M=G(we=>we.clearPendingQuestion),_=Jc(c),C=bh((Ir=m==null?void 0:m.config)==null?void 0:Ir.model_ref),D=Ct(we=>we.isProviderModelRefEnabled),A=G(we=>c?we.inputStates[c]:void 0),B=G(we=>we.setInputContent),F=G(we=>we.setReferenceText),O=G(we=>we.setInputReasoningEffort),R=Ct(we=>we.currentProvider),I=Ct(we=>we.providerConfig),[L,U]=f.useState([]),[q,H]=f.useState(!1),[P,W]=f.useState(null),[ne,K]=f.useState(!1),xe=(A==null?void 0:A.content)||"",se=(A==null?void 0:A.referenceText)||null,fe=f.useMemo(()=>{var we;return(we=I.providers[R])==null?void 0:we.reasoning_effort},[I,R]),Se=f.useMemo(()=>c?Vm(c):void 0,[c]),me=((al=m==null?void 0:m.config)==null?void 0:al.reasoningEffort)??(A==null?void 0:A.reasoningEffort)??Se??fe??"medium",ze=f.useCallback(we=>{c&&B(c,we)},[c,B]),st=f.useCallback(we=>{c&&F(c,we)},[c,F]),pt=f.useCallback(async we=>{if(c&&(O(c,we),!!m))try{await Fo.patchSession(c,{reasoning_effort:we}),b(c,{config:{...m.config,reasoningEffort:we}})}catch($t){console.warn("[InputContainer] Failed to persist reasoning effort:",$t)}},[m,c,O,b]),Kt=S,{sendMessage:Oe,retryLastTurn:Wt,cancel:Xe}=Uv({sessionId:c,addMessage:g,updateSession:b});f.useEffect(()=>{if(typeof window>"u")return;const we=Gt=>Gt?c===Gt:c!==null&&c===u,$t=Gt=>{const kt=Gt;if(!kt.detail||typeof kt.detail.text!="string")return;const Pt=typeof kt.detail.sessionId=="string"?kt.detail.sessionId:null;if(!we(Pt))return;const un=kt.detail.text.trim();un&&(kt.detail.handled=!0,st(un),requestAnimationFrame(()=>{var an;(an=r.current)==null||an.focus()}))},Nt=Gt=>{var un;const kt=Gt,Pt=typeof((un=kt.detail)==null?void 0:un.sessionId)=="string"?kt.detail.sessionId:null;we(Pt)&&(kt.detail&&(kt.detail.handled=!0),requestAnimationFrame(()=>{var an;(an=r.current)==null||an.focus()}))};return window.addEventListener(wg,$t),window.addEventListener(pm,Nt),()=>{window.removeEventListener(wg,$t),window.removeEventListener(pm,Nt)}},[u,c,st]);const _e=Kt,{message:Ye}=en.useApp(),ot=!1,Lt=!1,N=S1,le=void 0,{recordEntry:be,navigate:De,acknowledgeManualInput:Le}=o1(c),{attachments:ue,setAttachments:ye,handleAttachmentsAdded:qe,handleAttachmentRemove:He,handleClearAttachments:ae}=d1(),ke=a1({setContent:ze,onWorkflowDraftChange:t,acknowledgeManualInput:Le,currentSessionId:c,textAreaRef:r,content:xe}),pe=c1({content:xe,setContent:ze,currentSessionId:c,currentChat:m,updateSession:b,messageApi:Ye}),{setShowFileSelector:Re}=pe;f.useEffect(()=>{ke.showCommandSelector&&Re(!1)},[ke.showCommandSelector,Re]);const{handleSubmit:Je}=u1({attachments:ue,referenceText:se,selectedWorkflow:ke.selectedCommand,matchesWorkflowToken:ke.matchesCommandToken,fileReferences:pe.fileReferences,reasoningEffort:me,sendMessage:Oe,recordEntry:be,clearWorkflowDraft:ke.clearCommandDraft,setContent:ze,setReferenceText:st,setAttachments:ye,setFileReferences:pe.setFileReferences}),gt=w,Mt=!!gt,xt=(gt==null?void 0:gt.options)||[],Ft=(gt==null?void 0:gt.allowCustom)??!0,Dt=f.useCallback(we=>we?!!Ci(we)(G.getState()):!1,[]),Ue=f.useCallback(async we=>{const $t=we.trim();if(!$t||!c)return;const Gt=Ci(c)(G.getState());if(Gt&&!Gt.allowCustom&&Gt.options.length>0&&!Gt.options.includes($t)){Ye.warning(s("components.questionDialog.selectOptionWarning"));return}k(c,(gt==null?void 0:gt.toolCallId)??null),await new Promise(kt=>setTimeout(kt,0));try{const kt={response:$t,reasoning_effort:me};D()&&C&&(kt.model_ref=C,kt.provider=C.provider);const Pt=await nt.post(`respond/${c}`,kt);Ye.success(s("components.questionDialog.responseSubmittedContinue")),ze(""),M(c),typeof window<"u"&&window.dispatchEvent(new CustomEvent(zo,{detail:{sessionId:c}}));const un=Pt==null?void 0:Pt.auto_resume_status;(!un||!["started","already_running"].includes(un))&&j(c)}catch(kt){console.error("[InputContainer] Failed to submit respond:",kt),Ye.error(kt instanceof Error?kt.message:s("components.questionDialog.submitFailed")),j(c)}},[c,me,C,D,Ye,ze,M,k,j,gt==null?void 0:gt.toolCallId,s]),rn=f.useCallback(async(we,$t)=>{if(Dt(c)){await Ue(we);return}await Je(we,$t)},[c,Dt,Ue,Je]),dn=f.useCallback(async(we,$t)=>{await rn(we,$t)},[rn]);f.useEffect(()=>{if(typeof window>"u")return;const we=$t=>{var un,an,ea;const Nt=$t;if(!Nt.detail)return;const Gt=typeof Nt.detail.sessionId=="string"?Nt.detail.sessionId:null;if(!(Gt?c===Gt:c!==null&&c===u))return;Nt.detail.handled=!0;const Pt=(un=Nt.detail)==null?void 0:un.content;if(typeof Pt!="string"||Pt.trim().length===0){(ea=(an=Nt.detail)==null?void 0:an.reject)==null||ea.call(an,new Error("External send message content is empty"));return}rn(Pt,void 0).then(()=>{var _s,ks;(ks=(_s=Nt.detail)==null?void 0:_s.resolve)==null||ks.call(_s)}).catch(_s=>{var ks,go;(go=(ks=Nt.detail)==null?void 0:ks.reject)==null||go.call(ks,_s)})};return window.addEventListener(Sg,we),()=>{window.removeEventListener(Sg,we)}},[u,c,rn]);const{retryLastMessage:on,handleHistoryNavigate:Be}=m1({currentSessionId:c,currentChat:m,currentMessages:p,reasoningEffort:me,retryLastTurn:Wt,navigate:De}),Ar=()=>st(null),as=f.useMemo(()=>I.providers[R],[I,R]),En=f.useMemo(()=>!as||typeof as!="object"?!1:R==="copilot"?Object.keys(as).length>0:"api_key"in as?typeof as.api_key=="string"&&as.api_key.trim().length>0:!1,[R,as]),$s=f.useCallback(()=>En?!1:(l("chat"),Ye.warning("Please configure provider first"),!0),[En,Ye,l]);f.useEffect(()=>{(async()=>{const we=await k1(R);U(we??[]),W(null)})()},[R]);const Jn=f.useCallback(we=>we instanceof Error&&we.message.trim()?we.message:"Unknown error",[]),Xs=f.useMemo(()=>({openai:[...bP],anthropic:[...xP],gemini:[...vP],copilot:[...SP],bodhi:[]})[R]||[],[R]),mr=f.useMemo(()=>{const $t=[...L.length>0?L:Xs];return _&&!$t.some(Nt=>Nt.value===_)&&$t.unshift({value:_,label:_}),$t},[L,Xs,_]),is=f.useCallback(async(we,$t)=>{if(!(!($t!=null&&$t.force)&&L.length>0))try{H(!0),W(null);const Gt=(we==="copilot"?await Hb.getModels():Xs).map(kt=>({value:typeof kt=="string"?kt:kt.value,label:typeof kt=="string"?kt:kt.label}));U(Gt),await T1(we,Gt)}catch(Nt){W(Jn(Nt))}finally{H(!1)}},[Xs,Jn,L.length]),ws=f.useCallback(we=>{we&&($s()||q||L.length>0||is(R))},[R,is,q,L.length,$s]),Fe=f.useCallback(async we=>{var $t,Nt,Gt;if(!(!we||we===_)&&!ne)try{if($s())return;if(K(!0),!c||!m){c&&b(c,{config:{systemPromptId:(($t=m==null?void 0:m.config)==null?void 0:$t.systemPromptId)||"default",baseSystemPrompt:((Nt=m==null?void 0:m.config)==null?void 0:Nt.baseSystemPrompt)||"",lastUsedEnhancedPrompt:((Gt=m==null?void 0:m.config)==null?void 0:Gt.lastUsedEnhancedPrompt)??null,...(m==null?void 0:m.config)||{},model:we}});return}await Fo.patchSession(c,{model:we}),b(c,{config:{...m.config,model:we}}),Ye.success(s("settings.providerTab.modelUpdated"))}catch(kt){Ye.error(`${s("settings.providerTab.updateModelErrorPrefix")}: ${Jn(kt)}`)}finally{K(!1)}},[_,m,Jn,ne,Ye,$s,c,s,b]),yt=f.useCallback(async we=>{if(!c||!(m!=null&&m.config)){Ct.getState().setSelectedModelRef(we);return}if(!ne)try{K(!0),await Fo.patchSession(c,{model:we.model,model_ref:we,provider:we.provider}),Ct.getState().setSelectedModelRef(we),b(c,{config:{...m.config,model:we.model,model_ref:we}}),Ye.success(s("settings.providerTab.modelUpdated"))}catch($t){Ye.error(`${s("settings.providerTab.updateModelErrorPrefix")}: ${Jn($t)}`)}finally{K(!1)}},[m==null?void 0:m.config,Jn,ne,Ye,c,s,b]),tt=f.useMemo(()=>h1({referenceText:se,isToolSpecificMode:ot,isRestrictConversation:Lt,allowedTools:N,autoToolPrefix:le,t:s}),[se,ot,Lt,N,le,s]),mt=Mt&&Ft?s("chat.respond.customAnswerPlaceholder"):Mt?s("components.questionDialog.selectOptionWarning"):tt,_n=Mt?s("chat.respond.submitToolResult","Submit tool result"):void 0,Un=f.useMemo(()=>({low:s("chat.input.reasoning.low"),medium:s("chat.input.reasoning.medium"),high:s("chat.input.reasoning.high"),xhigh:s("chat.input.reasoning.xhigh"),max:s("chat.input.reasoning.max")}),[s]),Hn=f.useMemo(()=>Un[me]??me,[me,Un]),Rn=o.jsx(lo,{trigger:["click"],placement:"topLeft",disabled:!_||S,menu:{selectable:!0,selectedKeys:[me],items:v1.map(we=>({key:we,label:Un[we]})),onClick:({key:we})=>{pt(we)}},children:o.jsx(de,{type:"text",size:"small",disabled:!_||_e,style:{minWidth:i?74:88,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:me==="medium"?a.colorTextSecondary:a.colorPrimary},title:s("chat.input.reasoningTitle",{label:Hn}),children:o.jsxs(he,{size:6,children:[o.jsx(jb,{}),o.jsx("span",{children:Hn}),o.jsx(Gn,{style:{fontSize:10}})]})})}),ls=_||s(En?"chat.model.selectModel":"chat.model.configureProvider"),yn=f.useMemo(()=>mr.length>0?mr.map(we=>({key:we.value,label:we.label})):[{key:"__no_models__",label:P||s("chat.model.noModelsAvailable"),disabled:!0}],[mr,P,s]),An=o.jsx(de,{type:"text",size:"small",disabled:_e||ne,onClick:()=>{En||$s()},style:{minWidth:i?112:146,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:P?a.colorError:a.colorTextSecondary},title:ls,children:o.jsxs(he,{size:6,children:[q?o.jsx(io,{}):o.jsx($m,{}),o.jsx("span",{style:{maxWidth:i?84:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ls}),o.jsx(Gn,{style:{fontSize:10}})]})}),Ds=D()?o.jsx(nS,{value:C,onChange:yt,disabled:_e||ne}):En?o.jsx(lo,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:_?[_]:[],items:yn,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:we})=>{we!=="__no_models__"&&Fe(String(we))}},onOpenChange:ws,disabled:S||ne,children:An}):An;return o.jsxs("div",{style:{padding:`${a.paddingXXS}px ${a.paddingXS}px`,background:"transparent",borderTop:"none",boxShadow:"none",width:"100%",position:"relative",overflow:"visible"},children:[!_&&o.jsx(Ht,{type:"warning",showIcon:!0,icon:o.jsx(Ki,{}),message:s(En?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:s(En?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:En?void 0:o.jsx(he,{children:o.jsx("a",{onClick:()=>l("chat"),children:s("chat.model.openSettings")})}),style:{marginBottom:a.marginSM}}),ot,se&&o.jsx(r1,{text:se,onClose:Ar}),ue.length>0&&o.jsx(f.Suspense,{fallback:o.jsx(Rs,{size:"small"}),children:o.jsx(f1,{files:ue,onRemove:He,onClear:ae})}),Mt&&xt.length>0&&o.jsx("div",{style:{marginBottom:a.marginSM},children:o.jsx(he,{wrap:!0,size:[8,8],children:xt.map(we=>o.jsx(de,{size:"small",onClick:()=>{Ue(we)},disabled:S,children:we},we))})}),o.jsx(n1,{value:xe,onChange:ke.handleInputChange,onSubmit:dn,placeholder:mt,allowImages:!0,disabled:!_||Mt&&!Ft&&xt.length>0,statusIndicator:n,submitButtonLabel:_n,isWorkflowSelectorVisible:ke.showCommandSelector,textAreaRef:r,validateMessage:we=>({isValid:!0}),onAttachmentsAdded:qe,onWorkflowCommandChange:ke.handleCommandChange,onFileReferenceChange:pe.handleFileReferenceChange,onFileReferenceButtonClick:pe.handleFileReferenceButtonClick,leftControlsExtra:o.jsxs(he,{size:0,wrap:!0,children:[Ds,Rn]}),interaction:{isStreaming:_e,canCancel:x,hasMessages:p.some(we=>we.role==="user"),allowRetry:!0,onRetry:on,onCancel:Xe,onHistoryNavigate:Be}}),o.jsx(f.Suspense,{fallback:null,children:o.jsx(p1,{visible:ke.showCommandSelector,onSelect:ke.handleCommandSelect,onCancel:ke.handleCommandSelectorCancel,onAutoComplete:ke.handleAutoComplete,searchText:ke.commandSearchText})}),pe.showFileSelector&&o.jsx(f.Suspense,{fallback:o.jsx(Rs,{size:"small"}),children:o.jsx(y1,{visible:pe.showFileSelector,files:pe.workspaceFiles,searchText:pe.fileSearchText,loading:pe.isWorkspaceLoading,error:pe.workspaceError,onSelect:pe.handleFileReferenceSelect,onCancel:pe.handleFileSelectorCancel,onChangeWorkspace:()=>{pe.setWorkspacePathInput((m==null?void 0:m.config.workspacePath)??""),pe.setIsWorkspaceModalVisible(!0)}})}),o.jsx(f.Suspense,{fallback:null,children:o.jsx(g1,{open:pe.isWorkspaceModalVisible,initialPath:pe.workspacePathInput,loading:pe.isSavingWorkspace,onSubmit:pe.handleWorkspaceModalSubmit,onCancel:pe.handleWorkspaceModalCancel})})]})},{Text:tr}=Ke,C1=220,M1="chat-session-diff-collapse:",P1=e=>e.split(/[\\/]/).pop()||e,cS=e=>`${M1}${e??"default"}`,iu=e=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(cS(e));if(!t)return null;const n=JSON.parse(t);if(!n||typeof n!="object")return null;const s="isExpanded"in n&&typeof n.isExpanded=="boolean"?n.isExpanded:!0,r="expandedFiles"in n&&Array.isArray(n.expandedFiles)?n.expandedFiles.filter(a=>typeof a=="string"):[];return{isExpanded:s,expandedFiles:r}}catch{return null}},E1=async(e,t)=>{if(typeof window>"u")return;await Wn.getInstance().saveDiffCollapse(e??"default",t);try{window.localStorage.setItem(cS(e),JSON.stringify(t))}catch{}},R1=({sessionDiffSummary:e,sessionId:t})=>{const{token:n}=Qe.useToken(),s=!!(e&&e.files.length>0),[r,a]=f.useState(s),[i,l]=f.useState(s),[c,u]=f.useState(()=>{var S;return((S=iu(t))==null?void 0:S.isExpanded)??!0}),[m,p]=f.useState(()=>{var S;return new Set(((S=iu(t))==null?void 0:S.expandedFiles)??[])});f.useEffect(()=>{if(s){a(!0);const x=window.setTimeout(()=>l(!0),0);return()=>window.clearTimeout(x)}l(!1);const S=window.setTimeout(()=>a(!1),C1);return()=>window.clearTimeout(S)},[s]);const g=f.useMemo(()=>e?e.files:[],[e]),b=f.useMemo(()=>{const S=new Map;return e&&e.files.forEach(x=>{S.set(x.filePath,Gv(x.unifiedDiff))}),S},[e]);return f.useEffect(()=>{const S=iu(t);u((S==null?void 0:S.isExpanded)??!0),p(new Set((S==null?void 0:S.expandedFiles)??[])),Wn.getInstance().loadDiffCollapse(t??"default").then(k=>{k&&(u(k.isExpanded),p(new Set(k.expandedFiles)))}).catch(()=>{})},[t]),f.useEffect(()=>{E1(t,{isExpanded:c,expandedFiles:Array.from(m)}).catch(()=>{})},[t,c,m]),f.useEffect(()=>{if(!e||e.files.length===0)return;const S=new Set(e.files.map(x=>x.filePath));p(x=>{const k=new Set;let j=!1;return x.forEach(w=>{S.has(w)?k.add(w):j=!0}),!j&&k.size===x.size?x:k})},[e]),!r||!e?null:o.jsx("div",{className:`active-tool-card-wrapper ${i?"visible":""}`,"aria-hidden":!i,"data-testid":"session-diff-card",children:o.jsx(Ce,{size:"small",style:{width:"100%",borderRadius:n.borderRadiusLG,border:`1px solid ${n.colorBorderSecondary}`,background:n.colorBgContainer,boxShadow:n.boxShadowSecondary},styles:{body:{padding:`${n.paddingXS}px ${n.paddingSM}px`}},children:o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:6,children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:n.marginSM,cursor:"pointer"},onClick:()=>u(S=>!S),"data-testid":"session-diff-toggle",children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:n.marginSM,minWidth:0},children:[o.jsx(Cb,{style:{color:n.colorPrimary}}),o.jsx(tr,{strong:!0,style:{whiteSpace:"nowrap"},children:"Session diffs"}),o.jsxs(tr,{type:"secondary",style:{fontSize:n.fontSizeSM,whiteSpace:"nowrap"},children:["(",e.files.length," files / ",e.changedTools," tools)"]}),o.jsxs(he,{size:4,style:{marginInlineStart:n.marginXS},children:[o.jsxs(tr,{style:{color:n.colorSuccess,fontSize:n.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",e.totalAdded]}),o.jsxs(tr,{style:{color:n.colorError,fontSize:n.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",e.totalRemoved]})]})]}),o.jsx("div",{style:{color:n.colorTextSecondary},children:c?o.jsx(Gn,{}):o.jsx(Vs,{})})]}),c&&o.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr",gap:6,maxHeight:280,overflowY:"auto"},"data-testid":"session-diff-file-list",children:g.map(S=>{const x=m.has(S.filePath),k=b.get(S.filePath)??[];return o.jsxs("div",{style:{border:`1px solid ${n.colorBorderSecondary}`,borderRadius:n.borderRadiusSM,overflow:"hidden",background:n.colorBgContainer},"data-testid":"session-diff-file-item","data-file-path":S.filePath,children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:n.marginSM,padding:"4px 8px",borderRadius:n.borderRadiusSM,background:n.colorFillTertiary,cursor:"pointer"},onClick:()=>{p(j=>{const w=new Set(j);return w.has(S.filePath)?w.delete(S.filePath):w.add(S.filePath),w})},"data-testid":"session-diff-file-header","data-file-path":S.filePath,children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:n.marginXS,minWidth:0,flex:1},children:[o.jsx("span",{style:{color:n.colorTextSecondary},children:x?o.jsx(Gn,{}):o.jsx(Vs,{})}),o.jsx(tr,{ellipsis:{tooltip:S.filePath},style:{flex:1,minWidth:0,fontSize:n.fontSizeSM},children:P1(S.filePath)})]}),o.jsxs(he,{size:4,children:[o.jsxs(tr,{style:{color:n.colorSuccess,fontSize:n.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",S.added]}),o.jsxs(tr,{style:{color:n.colorError,fontSize:n.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",S.removed]})]})]}),x&&o.jsxs("div",{style:{borderTop:`1px solid ${n.colorBorderSecondary}`,maxHeight:220,overflow:"auto",background:n.colorBgContainer},"data-testid":"session-diff-file-panel","data-file-path":S.filePath,children:[k.length>0?k.map((j,w)=>{const M={margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:n.fontSizeSM,lineHeight:1.5,padding:"0 8px",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"};return j.kind==="add"?M.background=n.colorSuccessBg:j.kind==="remove"?M.background=n.colorErrorBg:j.kind==="modified_add"?(M.background=n.colorWarningBg,M.borderLeft=`3px solid ${n.colorSuccess}`):j.kind==="modified_remove"?(M.background=n.colorWarningBg,M.borderLeft=`3px solid ${n.colorError}`):j.kind==="hunk"?(M.background=n.colorFillSecondary,M.color=n.colorTextSecondary):j.kind==="meta"&&(M.background=n.colorFillTertiary,M.color=n.colorTextSecondary),o.jsx("pre",{style:M,"data-testid":"session-diff-line","data-kind":j.kind,children:j.text||" "},`${S.filePath}-${w}`)}):o.jsx(tr,{type:"secondary",style:{display:"block",padding:"8px",fontSize:n.fontSizeSM},children:"No diff preview available."}),S.truncated&&o.jsx(tr,{type:"secondary",style:{display:"block",padding:"6px 8px 8px",fontSize:n.fontSizeSM},children:"Diff truncated for display."})]})]},S.filePath)})})]})})})},A1=e=>{if(!e)return;const{activeLeafId:t,setLeafSessionId:n,setActiveLeafId:s}=wt.getState();n(t,e),s(t),G.getState().selectSession(e)},I1=["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(" "),O1=["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(" "),$1=["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(" "),D1=["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(" "),L1=["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(" "),F1=["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(" "),N1=["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(" "),z1=["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(" "),B1=["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(" "),W1=["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(" "),q1=["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(" "),U1=["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(" "),H1=["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(" "),K1=["development","debugging","analysis","documentation","operations"],Y1={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"}},V1=(e,t)=>{const n=e.find(r=>r.id===t),s=e.find(r=>r.id==="general_assistant")||e[0];return{systemPromptId:(n==null?void 0:n.id)||(s==null?void 0:s.id)||"",baseSystemPrompt:(n==null?void 0:n.content)||(s==null?void 0:s.content)||""}},dS=({sessionId:e=null,embedded:t=!1,hideHeader:n=!1,layoutMode:s="default"})=>{var R;const{t:r}=Ae(),{token:a}=Qe.useToken(),{message:i}=en.useApp(),l=G(I=>e??I.currentSessionId),c=G(Er(l)),u=G(I=>I.addChat),m=G(I=>I.lastSelectedPromptId),p=G(I=>I.setInputContent),g=G(I=>I.systemPrompts),b=G(I=>I.chats),[S,x]=f.useState(null),[k,j]=f.useState(""),w=(c==null?void 0:c.config.workspacePath)??((R=b.find(I=>I.config.workspacePath))==null?void 0:R.config.workspacePath),M=f.useMemo(()=>[{id:"blank",icon:o.jsx(or,{}),title:r("chat.emptyLauncher.actions.blank.title","Blank session"),description:r("chat.emptyLauncher.actions.blank.description","Start from scratch with the default assistant and an empty composer."),sessionTitle:r("chat.emptyLauncher.actions.blank.sessionTitle","New Session"),prefill:r("chat.emptyLauncher.actions.blank.prefill",""),category:"development"},{id:"codeReview",icon:o.jsx(Wc,{}),title:r("chat.emptyLauncher.actions.codeReview.title","Code review"),description:r("chat.emptyLauncher.actions.codeReview.description","Open a review-focused session with an editable review brief."),sessionTitle:r("chat.emptyLauncher.actions.codeReview.sessionTitle","Code Review"),prefill:r("chat.emptyLauncher.actions.codeReview.prefill","Review the relevant code changes in this workspace or repository. Start with the overall scope, then list risks, notable diffs, and the most important fixes."),baseSystemPrompt:I1,category:"development",recommendWorkspace:!0},{id:"implementFeature",icon:o.jsx(Ui,{}),title:r("chat.emptyLauncher.actions.implementFeature.title","Implement feature"),description:r("chat.emptyLauncher.actions.implementFeature.description","Plan and build a feature step by step following existing code conventions."),sessionTitle:r("chat.emptyLauncher.actions.implementFeature.sessionTitle","Implement Feature"),prefill:r("chat.emptyLauncher.actions.implementFeature.prefill","Help me implement a new feature in this workspace. Start by understanding the codebase structure, then propose an implementation plan before writing code."),baseSystemPrompt:$1,category:"development",recommendWorkspace:!0},{id:"refactor",icon:o.jsx(Cb,{}),title:r("chat.emptyLauncher.actions.refactor.title","Refactor code"),description:r("chat.emptyLauncher.actions.refactor.description","Get targeted suggestions for improving code quality and maintainability."),sessionTitle:r("chat.emptyLauncher.actions.refactor.sessionTitle","Refactor Suggestion"),prefill:r("chat.emptyLauncher.actions.refactor.prefill","Suggest refactoring improvements for the code in this workspace. Focus on readability, maintainability, and performance. Propose incremental changes with clear rationale."),baseSystemPrompt:N1,category:"development",recommendWorkspace:!0},{id:"bugInvestigation",icon:o.jsx(Tb,{}),title:r("chat.emptyLauncher.actions.bugInvestigation.title","Bug investigation"),description:r("chat.emptyLauncher.actions.bugInvestigation.description","Diagnose issues by analyzing code, logs, and runtime behavior."),sessionTitle:r("chat.emptyLauncher.actions.bugInvestigation.sessionTitle","Bug Investigation"),prefill:r("chat.emptyLauncher.actions.bugInvestigation.prefill","Help me investigate a bug. I'll describe the symptoms and share relevant code or logs. Trace the root cause and suggest targeted fixes."),baseSystemPrompt:O1,category:"debugging",recommendWorkspace:!0},{id:"explainError",icon:o.jsx(Rm,{}),title:r("chat.emptyLauncher.actions.explainError.title","Explain error"),description:r("chat.emptyLauncher.actions.explainError.description","Understand what went wrong from an error message or stack trace."),sessionTitle:r("chat.emptyLauncher.actions.explainError.sessionTitle","Explain Error"),prefill:r("chat.emptyLauncher.actions.explainError.prefill","Help me understand the following error. Explain the root cause, suggest fixes, and share prevention tips."),baseSystemPrompt:L1,category:"debugging"},{id:"tokenUsage",icon:o.jsx(c_,{}),title:r("chat.emptyLauncher.actions.tokenUsage.title","Token usage investigation"),description:r("chat.emptyLauncher.actions.tokenUsage.description","Diagnose context growth, truncation risk, and token budget pressure."),sessionTitle:r("chat.emptyLauncher.actions.tokenUsage.sessionTitle","Token Usage Investigation"),prefill:r("chat.emptyLauncher.actions.tokenUsage.prefill","Help me investigate token usage, context growth, and truncation risk for this session or workflow. Summarize the likely drivers and recommend concrete next fixes."),baseSystemPrompt:H1,category:"debugging"},{id:"architectureReview",icon:o.jsx(d_,{}),title:r("chat.emptyLauncher.actions.architectureReview.title","Read repo architecture"),description:r("chat.emptyLauncher.actions.architectureReview.description","Analyze repository structure, modules, and architectural patterns."),sessionTitle:r("chat.emptyLauncher.actions.architectureReview.sessionTitle","Architecture Review"),prefill:r("chat.emptyLauncher.actions.architectureReview.prefill","Analyze the architecture of this repository. Map the key modules, data flow, abstractions, and dependency patterns. Identify strengths and potential improvements."),baseSystemPrompt:D1,category:"analysis",recommendWorkspace:!0},{id:"compareFiles",icon:o.jsx(u_,{}),title:r("chat.emptyLauncher.actions.compareFiles.title","Compare files"),description:r("chat.emptyLauncher.actions.compareFiles.description","Diff and understand differences between files or code sections."),sessionTitle:r("chat.emptyLauncher.actions.compareFiles.sessionTitle","Compare Files"),prefill:r("chat.emptyLauncher.actions.compareFiles.prefill","Compare the following files or code sections. Highlight key differences, their implications, and any potential risks."),baseSystemPrompt:F1,category:"analysis",recommendWorkspace:!0},{id:"releaseNotes",icon:o.jsx(qo,{}),title:r("chat.emptyLauncher.actions.releaseNotes.title","Generate release notes"),description:r("chat.emptyLauncher.actions.releaseNotes.description","Create structured release notes from git history and code changes."),sessionTitle:r("chat.emptyLauncher.actions.releaseNotes.sessionTitle","Release Notes"),prefill:r("chat.emptyLauncher.actions.releaseNotes.prefill","Generate release notes for the latest changes in this workspace. Categorize into features, fixes, improvements, and breaking changes."),baseSystemPrompt:z1,category:"documentation",recommendWorkspace:!0},{id:"summarizeWork",icon:o.jsx(m_,{}),title:r("chat.emptyLauncher.actions.summarizeWork.title","Summarize work"),description:r("chat.emptyLauncher.actions.summarizeWork.description","Create a work summary for standups or weekly status reports."),sessionTitle:r("chat.emptyLauncher.actions.summarizeWork.sessionTitle","Work Summary"),prefill:r("chat.emptyLauncher.actions.summarizeWork.prefill","Help me summarize my recent work for a status update. Pull key accomplishments, blockers, and next steps."),baseSystemPrompt:B1,category:"documentation"},{id:"writeDocs",icon:o.jsx(qo,{}),title:r("chat.emptyLauncher.actions.writeDocs.title","Write documentation"),description:r("chat.emptyLauncher.actions.writeDocs.description","Create or improve technical documentation from code and context."),sessionTitle:r("chat.emptyLauncher.actions.writeDocs.sessionTitle","Write Documentation"),prefill:r("chat.emptyLauncher.actions.writeDocs.prefill","Help me write technical documentation for this project. Analyze the code and produce clear, well-structured Markdown documentation."),baseSystemPrompt:W1,category:"documentation",recommendWorkspace:!0},{id:"createSchedule",icon:o.jsx(As,{}),title:r("chat.emptyLauncher.actions.createSchedule.title","Create scheduled task"),description:r("chat.emptyLauncher.actions.createSchedule.description","Set up a recurring task that runs automatically on a schedule."),sessionTitle:r("chat.emptyLauncher.actions.createSchedule.sessionTitle","Create Schedule"),prefill:r("chat.emptyLauncher.actions.createSchedule.prefill","Help me set up a recurring scheduled task. I'll describe what I want it to do, and you guide me through the configuration."),baseSystemPrompt:q1,category:"operations"},{id:"sessionReview",icon:o.jsx($i,{}),title:r("chat.emptyLauncher.actions.sessionReview.title","Review session history"),description:r("chat.emptyLauncher.actions.sessionReview.description","Inspect and analyze past sessions for patterns and insights."),sessionTitle:r("chat.emptyLauncher.actions.sessionReview.sessionTitle","Session Review"),prefill:r("chat.emptyLauncher.actions.sessionReview.prefill","Help me review my recent session history. Summarize key decisions, outcomes, and areas that need follow-up."),baseSystemPrompt:U1,category:"operations"}],[r]),_=k.trim().toLowerCase(),C=f.useMemo(()=>_?M.filter(I=>I.title.toLowerCase().includes(_)||I.description.toLowerCase().includes(_)):M,[_,M]),D=f.useMemo(()=>{const I={};for(const L of C)I[L.category]||(I[L.category]=[]),I[L.category].push(L);return I},[C]),A=f.useCallback(I=>{typeof window>"u"||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent(pm,{detail:{sessionId:I}}))},0)},[]),B=f.useCallback(async I=>{if(!S){x(I.id);try{const L=V1(g,m),U=await u({title:I.sessionTitle,createdAt:Date.now(),messages:[],config:{systemPromptId:L.systemPromptId,baseSystemPrompt:I.baseSystemPrompt??L.baseSystemPrompt,lastUsedEnhancedPrompt:null,...w?{workspacePath:w}:{}}});A1(U),I.prefill.trim().length>0&&p(U,I.prefill),A(U)}catch(L){console.error("[EmptyTaskLauncher] Failed to create session",L),i.error(L instanceof Error?L.message:r("chat.emptyLauncher.errors.createFailed","Failed to create session"))}finally{x(null)}}},[u,m,i,S,A,p,g,r,w]),F=f.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]),O=!!w;return o.jsxs("div",{className:`lotus-empty-task-launcher ${t?"is-embedded":""} ${n?"is-headerless":""} ${s==="staggered"?"is-staggered":""}`,style:F,children:[!n&&o.jsxs("div",{className:"lotus-empty-task-launcher__header",children:[o.jsx(Ke.Title,{level:t?4:3,style:{margin:0},children:r("chat.emptyLauncher.title","Start with a task")}),o.jsx(Ke.Paragraph,{type:"secondary",className:"lotus-empty-task-launcher__subtitle",children:r("chat.emptyLauncher.subtitle","Create a focused session in this pane and prefill the first message before you send it.")}),o.jsx(Ke.Text,{type:"secondary",className:"lotus-empty-task-launcher__hint",children:r("chat.emptyLauncher.hint","Nothing is sent automatically — you can edit the prompt first.")})]}),o.jsx("div",{className:"lotus-empty-task-launcher__search",children:o.jsx(et,{placeholder:r("chat.emptyLauncher.searchPlaceholder","Search templates..."),prefix:o.jsx($i,{style:{color:a.colorTextQuaternary}}),value:k,onChange:I=>j(I.target.value),allowClear:!0,size:"middle",variant:"filled"})}),o.jsxs("div",{className:"lotus-empty-task-launcher__categories",children:[K1.map(I=>{const L=D[I];if(!L||L.length===0)return null;const U=Y1[I];return o.jsxs("div",{className:"lotus-empty-task-launcher__category",children:[o.jsx(Ke.Text,{type:"secondary",className:"lotus-empty-task-launcher__category-label",children:r(U.titleKey,U.fallback)}),o.jsx("div",{className:"lotus-empty-task-launcher__grid",children:L.map(q=>{const H=S===q.id,P=q.recommendWorkspace&&O;return o.jsxs("button",{type:"button",className:"lotus-empty-task-card",onClick:()=>{B(q)},disabled:S!==null,"aria-busy":H,"aria-label":q.title,children:[o.jsx("div",{className:"lotus-empty-task-card__icon","aria-hidden":!0,children:H?o.jsx(io,{}):q.icon}),o.jsxs("div",{className:"lotus-empty-task-card__body",children:[o.jsxs("div",{className:"lotus-empty-task-card__titleRow",children:[o.jsx("span",{className:"lotus-empty-task-card__title",children:q.title}),o.jsx(h_,{className:"lotus-empty-task-card__arrow","aria-hidden":!0})]}),o.jsx("p",{className:"lotus-empty-task-card__description",children:q.description}),P&&o.jsx("div",{className:"lotus-empty-task-card__badges",children:o.jsxs("span",{className:"lotus-empty-task-card__badge",title:w,children:["📂 ",r("chat.emptyLauncher.badges.workspace","workspace")]})})]})]},q.id)})})]},I)}),C.length===0&&o.jsx("div",{className:"lotus-empty-task-launcher__no-results",children:o.jsx(Ke.Text,{type:"secondary",children:r("chat.emptyLauncher.noResults","No templates match your search. Try a different keyword or start a blank session.")})})]})]})},X1=({sessionId:e,isCenteredLayout:t,maxWidth:n,onWorkflowDraftChange:s,showMessagesView:r,sessionDiffSummary:a,contextUsageIndicator:i})=>o.jsx(ve,{justify:"center",className:`chat-view-input-container-wrapper ${r?"messages-view":"centered-view"}`,children:o.jsxs("div",{style:{width:"100%",maxWidth:r?n:"min(100%, 920px)",margin:r?"0 auto":void 0,position:"relative",paddingBottom:r?12:0,display:"flex",flexDirection:"column",gap:r?0:24},children:[r&&o.jsx(R1,{sessionDiffSummary:a,sessionId:e}),!r&&e&&o.jsx(dS,{sessionId:e}),o.jsx(j1,{sessionId:e,isCenteredLayout:t,onWorkflowDraftChange:s,statusIndicator:i})]})});function Mo(e,t,n){let s=n.initialDeps??[],r;function a(){var i,l,c,u;let m;n.key&&((i=n.debug)!=null&&i.call(n))&&(m=Date.now());const p=e();if(!(p.length!==s.length||p.some((S,x)=>s[x]!==S)))return r;s=p;let b;if(n.key&&((l=n.debug)!=null&&l.call(n))&&(b=Date.now()),r=t(...p),n.key&&((c=n.debug)!=null&&c.call(n))){const S=Math.round((Date.now()-m)*100)/100,x=Math.round((Date.now()-b)*100)/100,k=x/16,j=(w,M)=>{for(w=String(w);w.length<M;)w=" "+w;return w};console.info(`%c⏱ ${j(x,5)} /${j(S,5)} ms`,`
178
+ font-size: .6rem;
179
+ font-weight: bold;
180
+ color: hsl(${Math.max(0,Math.min(120-120*k,120))}deg 100% 31%);`,n==null?void 0:n.key)}return(u=n==null?void 0:n.onChange)==null||u.call(n,r),r}return a.updateDeps=i=>{s=i},a}function _g(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const G1=(e,t)=>Math.abs(e-t)<1.01,J1=(e,t,n)=>{let s;return function(...r){e.clearTimeout(s),s=e.setTimeout(()=>t.apply(this,r),n)}},kg=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},Q1=e=>e,Z1=e=>{const t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1),s=[];for(let r=t;r<=n;r++)s.push(r);return s},eR=(e,t)=>{const n=e.scrollElement;if(!n)return;const s=e.targetWindow;if(!s)return;const r=i=>{const{width:l,height:c}=i;t({width:Math.round(l),height:Math.round(c)})};if(r(kg(n)),!s.ResizeObserver)return()=>{};const a=new s.ResizeObserver(i=>{const l=()=>{const c=i[0];if(c!=null&&c.borderBoxSize){const u=c.borderBoxSize[0];if(u){r({width:u.inlineSize,height:u.blockSize});return}}r(kg(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(n,{box:"border-box"}),()=>{a.unobserve(n)}},Tg={passive:!0},jg=typeof window>"u"?!0:"onscrollend"in window,tR=(e,t)=>{const n=e.scrollElement;if(!n)return;const s=e.targetWindow;if(!s)return;let r=0;const a=e.options.useScrollendEvent&&jg?()=>{}:J1(s,()=>{t(r,!1)},e.options.isScrollingResetDelay),i=m=>()=>{const{horizontal:p,isRtl:g}=e.options;r=p?n.scrollLeft*(g&&-1||1):n.scrollTop,a(),t(r,m)},l=i(!0),c=i(!1);c(),n.addEventListener("scroll",l,Tg);const u=e.options.useScrollendEvent&&jg;return u&&n.addEventListener("scrollend",c,Tg),()=>{n.removeEventListener("scroll",l),u&&n.removeEventListener("scrollend",c)}},nR=(e,t,n)=>{if(t!=null&&t.borderBoxSize){const s=t.borderBoxSize[0];if(s)return Math.round(s[n.options.horizontal?"inlineSize":"blockSize"])}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},sR=(e,{adjustments:t=0,behavior:n},s)=>{var r,a;const i=e+t;(a=(r=s.scrollElement)==null?void 0:r.scrollTo)==null||a.call(r,{[s.options.horizontal?"left":"top"]:i,behavior:n})};class rR{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.measurementsCache=[],this.itemSizeCache=new Map,this.pendingMeasuredCacheIndexes=[],this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.observer=(()=>{let n=null;const s=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(r=>{r.forEach(a=>{const i=()=>{this._measureElement(a.target,a)};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var r;(r=s())==null||r.disconnect(),n=null},observe:r=>{var a;return(a=s())==null?void 0:a.observe(r,{box:"border-box"})},unobserve:r=>{var a;return(a=s())==null?void 0:a.unobserve(r)}}})(),this.range=null,this.setOptions=n=>{Object.entries(n).forEach(([s,r])=>{typeof r>"u"&&delete n[s]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:Q1,rangeExtractor:Z1,onChange:()=>{},measureElement:nR,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,...n}},this.notify=n=>{var s,r;(r=(s=this.options).onChange)==null||r.call(s,this,n)},this.maybeNotify=Mo(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const s=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==s){if(this.cleanup(),!s){this.maybeNotify();return}this.scrollElement=s,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(r=>{this.observer.observe(r)}),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0}),this.unsubs.push(this.options.observeElementRect(this,r=>{this.scrollRect=r,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(r,a)=>{this.scrollAdjustments=0,this.scrollDirection=a?this.getScrollOffset()<r?"forward":"backward":null,this.scrollOffset=r,this.isScrolling=a,this.maybeNotify()}))}},this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(n,s)=>{const r=new Map,a=new Map;for(let i=s-1;i>=0;i--){const l=n[i];if(r.has(l.lane))continue;const c=a.get(l.lane);if(c==null||l.end>c.end?a.set(l.lane,l):l.end<c.end&&r.set(l.lane,!0),r.size===this.options.lanes)break}return a.size===this.options.lanes?Array.from(a.values()).sort((i,l)=>i.end===l.end?i.index-l.index:i.end-l.end)[0]:void 0},this.getMeasurementOptions=Mo(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled],(n,s,r,a,i)=>(this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:s,scrollMargin:r,getItemKey:a,enabled:i}),{key:!1}),this.getMeasurements=Mo(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:s,scrollMargin:r,getItemKey:a,enabled:i},l)=>{if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),[];this.measurementsCache.length===0&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(m=>{this.itemSizeCache.set(m.key,m.size)}));const c=this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[];const u=this.measurementsCache.slice(0,c);for(let m=c;m<n;m++){const p=a(m),g=this.options.lanes===1?u[m-1]:this.getFurthestMeasurement(u,m),b=g?g.end+this.options.gap:s+r,S=l.get(p),x=typeof S=="number"?S:this.options.estimateSize(m),k=b+x,j=g?g.lane:m%this.options.lanes;u[m]={index:m,start:b,size:x,end:k,key:p,lane:j}}return this.measurementsCache=u,u},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Mo(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,s,r,a)=>this.range=n.length>0&&s>0?oR({measurements:n,outerSize:s,scrollOffset:r,lanes:a}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Mo(()=>{let n=null,s=null;const r=this.calculateRange();return r&&(n=r.startIndex,s=r.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,s]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,s]},(n,s,r,a,i)=>a===null||i===null?[]:n({startIndex:a,endIndex:i,overscan:s,count:r}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const s=this.options.indexAttribute,r=n.getAttribute(s);return r?parseInt(r,10):(console.warn(`Missing attribute name '${s}={index}' on measured element.`),-1)},this._measureElement=(n,s)=>{const r=this.indexFromElement(n),a=this.measurementsCache[r];if(!a)return;const i=a.key,l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),n.isConnected&&this.resizeItem(r,this.options.measureElement(n,s,this))},this.resizeItem=(n,s)=>{const r=this.measurementsCache[n];if(!r)return;const a=this.itemSizeCache.get(r.key)??r.size,i=s-a;i!==0&&((this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(r,i,this):r.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=i,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(r.index),this.itemSizeCache=new Map(this.itemSizeCache.set(r.key,s)),this.notify(!1))},this.measureElement=n=>{if(!n){this.elementsCache.forEach((s,r)=>{s.isConnected||(this.observer.unobserve(s),this.elementsCache.delete(r))});return}this._measureElement(n,void 0)},this.getVirtualItems=Mo(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,s)=>{const r=[];for(let a=0,i=n.length;a<i;a++){const l=n[a],c=s[l];r.push(c)}return r},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const s=this.getMeasurements();if(s.length!==0)return _g(s[uS(0,s.length-1,r=>_g(s[r]).start,n)])},this.getOffsetForAlignment=(n,s,r=0)=>{const a=this.getSize(),i=this.getScrollOffset();s==="auto"&&(s=n>=i+a?"end":"start"),s==="center"?n+=(r-a)/2:s==="end"&&(n-=a);const l=this.getTotalSize()+this.options.scrollMargin-a;return Math.max(Math.min(l,n),0)},this.getOffsetForIndex=(n,s="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const r=this.measurementsCache[n];if(!r)return;const a=this.getSize(),i=this.getScrollOffset();if(s==="auto")if(r.end>=i+a-this.options.scrollPaddingEnd)s="end";else if(r.start<=i+this.options.scrollPaddingStart)s="start";else return[i,s];const l=s==="end"?r.end+this.options.scrollPaddingEnd:r.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,s,r.size),s]},this.isDynamicMode=()=>this.elementsCache.size>0,this.scrollToOffset=(n,{align:s="start",behavior:r}={})=>{r==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getOffsetForAlignment(n,s),{adjustments:void 0,behavior:r})},this.scrollToIndex=(n,{align:s="auto",behavior:r}={})=>{r==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),n=Math.max(0,Math.min(n,this.options.count-1));let a=0;const i=10,l=u=>{if(!this.targetWindow)return;const m=this.getOffsetForIndex(n,u);if(!m){console.warn("Failed to get offset for index:",n);return}const[p,g]=m;this._scrollToOffset(p,{adjustments:void 0,behavior:r}),this.targetWindow.requestAnimationFrame(()=>{const b=this.getScrollOffset(),S=this.getOffsetForIndex(n,g);if(!S){console.warn("Failed to get offset for index:",n);return}G1(S[0],b)||c(g)})},c=u=>{this.targetWindow&&(a++,a<i?this.targetWindow.requestAnimationFrame(()=>l(u)):console.warn(`Failed to scroll to index ${n} after ${i} attempts.`))};l(s)},this.scrollBy=(n,{behavior:s}={})=>{s==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getScrollOffset()+n,{adjustments:void 0,behavior:s})},this.getTotalSize=()=>{var n;const s=this.getMeasurements();let r;if(s.length===0)r=this.options.paddingStart;else if(this.options.lanes===1)r=((n=s[s.length-1])==null?void 0:n.end)??0;else{const a=Array(this.options.lanes).fill(null);let i=s.length-1;for(;i>=0&&a.some(l=>l===null);){const l=s[i];a[l.lane]===null&&(a[l.lane]=l.end),i--}r=Math.max(...a.filter(l=>l!==null))}return Math.max(r-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(n,{adjustments:s,behavior:r})=>{this.options.scrollToFn(n,{behavior:r,adjustments:s},this)},this.measure=()=>{this.itemSizeCache=new Map,this.notify(!1)},this.setOptions(t)}}const uS=(e,t,n,s)=>{for(;e<=t;){const r=(e+t)/2|0,a=n(r);if(a<s)e=r+1;else if(a>s)t=r-1;else return r}return e>0?e-1:0};function oR({measurements:e,outerSize:t,scrollOffset:n,lanes:s}){const r=e.length-1,a=c=>e[c].start;if(e.length<=s)return{startIndex:0,endIndex:r};let i=uS(0,r,a,n),l=i;if(s===1)for(;l<r&&e[l].end<n+t;)l++;else if(s>1){const c=Array(s).fill(0);for(;l<r&&c.some(m=>m<n+t);){const m=e[l];c[m.lane]=m.end,l++}const u=Array(s).fill(n+t);for(;i>=0&&u.some(m=>m>=n);){const m=e[i];u[m.lane]=m.start,i--}i=Math.max(0,i-i%s),l=Math.min(r,l+(s-1-l%s))}return{startIndex:i,endIndex:l}}const Cg=typeof document<"u"?f.useLayoutEffect:f.useEffect;function aR(e){const t=f.useReducer(()=>({}),{})[1],n={...e,onChange:(r,a)=>{var i;a?f_.flushSync(t):t(),(i=e.onChange)==null||i.call(e,r,a)}},[s]=f.useState(()=>new rR(n));return s.setOptions(n),Cg(()=>s._didMount(),[]),Cg(()=>s._willUpdate()),s}function iR(e){return aR({observeElementRect:eR,observeElementOffset:tR,scrollToFn:sR,...e})}const{Text:Mg,Paragraph:lR}=Ke,cR=({content:e,token:t,headingColor:n})=>o.jsx(Es,{components:{p:({children:s})=>o.jsx(lR,{style:{marginBottom:t.marginSM},children:s}),ol:({children:s})=>o.jsx("ol",{style:{marginBottom:t.marginSM,paddingLeft:20},children:s}),ul:({children:s})=>o.jsx("ul",{style:{marginBottom:t.marginSM,paddingLeft:20},children:s}),li:({children:s})=>o.jsx("li",{style:{marginBottom:t.marginXS},children:s}),h1:({children:s})=>o.jsx(Mg,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block",color:n},children:s}),h2:({children:s})=>o.jsx(Mg,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block",color:n},children:s})},children:e}),Pg=f.memo(cR),dR=e=>{if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null},uR=e=>e?[["base",e.base_system_prompt],["enhancement",e.enhancement_prompt],["workspace",e.workspace_context],["instruction",e.instruction_context],["env",e.env_context],["skills",e.skill_context],["toolGuide",e.tool_guide_context],["dream",e.dream_notebook],["sessionMemory",e.session_memory_note],["externalMemory",e.external_memory],["taskList",e.task_list],["effective",e.effective_system_prompt]].flatMap(([n,s])=>{const r=dR(s);return r?[{key:n,content:r}]:[]}):[],mR=({currentChat:e,message:t,systemPrompts:n})=>{var O;const[s,r]=f.useState(null),[a,i]=f.useState(null),[l,c]=f.useState(null),[u,m]=f.useState(!1),[p,g]=f.useState(!1),b=f.useMemo(()=>vc.getInstance(),[]),S=f.useMemo(()=>os.getInstance(),[]),x=t.role==="system"&&typeof t.content=="string"?t.content:"",k=t.role==="system"&&!t.id.startsWith("system-prompt-")&&x.trim().length>0;f.useEffect(()=>{t.role==="system"&&(i(null),c(null),g(!1))},[t.id,t.role,x]);const j=(e==null?void 0:e.id)??null,w=((O=e==null?void 0:e.config)==null?void 0:O.systemPromptId)??null,M=f.useMemo(()=>w?n.find(R=>R.id===w)??null:null,[w,n]),_=(M==null?void 0:M.content)??(s==null?void 0:s.content)??"",C=(M==null?void 0:M.description)??(s==null?void 0:s.description)??"",D=f.useRef(null);f.useEffect(()=>{r(null),D.current=null},[j,w]),f.useEffect(()=>{if(!w)return;const R=w;if(M!=null&&M.content)return;const I=`${j??"no-chat"}:${R}`;if(D.current===I)return;D.current=I;let L=!1;return(async()=>{try{const q=await b.findPresetById(R);if(L)return;const H=q?{content:q.content,description:q.description}:null;r(P=>!P&&!H||P&&H&&P.content===H.content&&P.description===H.description?P:H)}catch(q){console.error("Failed to load preset prompt:",q)}})(),()=>{L=!0}},[j,w,b,M==null?void 0:M.content]);const A=f.useCallback(async()=>{var R;if(!u){m(!0);try{if(j)try{const I=await S.getSessionSystemPrompt(j);c(I);const L=(R=I.effective_system_prompt)==null?void 0:R.trim();if(L){i(L),g(!0);return}}catch(I){console.warn("Failed to load backend prompt snapshot:",I)}if(k){c(null),i(x),g(!0);return}console.warn("Enhanced prompt snapshot unavailable; keeping base prompt view.")}catch(I){console.error("Failed to load enhanced prompt:",I)}finally{m(!1)}}},[S,j,k,u,x]),B=f.useMemo(()=>p&&a?a:_||C||(t.role==="system"?x:"System prompt is being prepared..."),[p,a,_,C,t.role,x]),F=f.useMemo(()=>uR(l),[l]);return{basePrompt:_,categoryDescription:C,enhancedPrompt:a,loadingEnhanced:u,loadEnhancedPrompt:A,promptSnapshot:l,promptToDisplay:B,showEnhanced:p,setShowEnhanced:g,snapshotSections:F,systemMessageContent:x}},{Text:Eg}=Ke,{useToken:hR}=Qe,fR=(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],pR=({currentChat:e,message:t})=>{const{token:n}=hR(),{t:s}=Ae(),r=G(S=>S.systemPrompts),{basePrompt:a,loadingEnhanced:i,loadEnhancedPrompt:l,promptSnapshot:c,promptToDisplay:u,showEnhanced:m,setShowEnhanced:p,snapshotSections:g}=mR({currentChat:e,message:t,systemPrompts:r}),b=f.useCallback(async S=>{try{await Ss(S)}catch(x){console.error("Failed to copy text:",x)}},[]);return o.jsx(Ce,{style:{width:"100%",maxWidth:"100%",background:n.colorBgContainer,borderRadius:n.borderRadiusLG,boxShadow:"none"},children:o.jsxs(he,{direction:"vertical",size:n.marginSM,style:{width:"100%"},children:[o.jsxs(ve,{justify:"space-between",align:"center",children:[o.jsx(ve,{align:"center",gap:n.marginXS,children:o.jsx(Eg,{type:"secondary",strong:!0,style:{fontSize:n.fontSizeSM},children:s("chat.prompt.systemCard.title")})}),o.jsxs(he,{children:[a&&!m?o.jsx(de,{type:"text",size:"small",icon:o.jsx(Nc,{}),onClick:l,loading:i,children:s("chat.prompt.systemCard.viewEnhanced")}):null,a&&m?o.jsx(de,{type:"text",size:"small",onClick:()=>p(!1),children:s("chat.prompt.systemCard.viewBase")}):null,o.jsx(de,{type:"text",size:"small",icon:o.jsx(vs,{}),onClick:()=>b(u),children:s("chat.prompt.systemCard.copy")})]})]}),o.jsx(ve,{vertical:!0,style:{maxHeight:m?400:300,overflowY:"auto",paddingRight:n.paddingXS},children:o.jsx(Pg,{content:u,token:n,headingColor:n.colorPrimary})}),c&&g.length>0?o.jsxs(o.Fragment,{children:[o.jsx(zn,{style:{margin:`${n.marginXS}px 0`}}),o.jsxs(he,{direction:"vertical",size:n.marginXS,style:{width:"100%"},children:[o.jsx(Eg,{type:"secondary",strong:!0,style:{fontSize:n.fontSizeSM},children:s("chat.prompt.systemCard.snapshotTitle")}),o.jsx(lr,{defaultActiveKey:g.map(S=>S.key),items:g.map(S=>({key:S.key,label:fR(s,S.key),children:o.jsx(Pg,{content:S.content,token:n,headingColor:n.colorPrimary})}))})]})]}):null]})})},mS=f.memo(pR);mS.displayName="SystemMessageCard";const hS=6048e5,gR=864e5,Rg=Symbol.for("constructDateFrom");function Tr(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&Rg in e?e[Rg](t):e instanceof Date?new e.constructor(t):new Date(t)}function Os(e,t){return Tr(t||e,e)}let yR={};function nd(){return yR}function qi(e,t){var l,c,u,m;const n=nd(),s=(t==null?void 0:t.weekStartsOn)??((c=(l=t==null?void 0:t.locale)==null?void 0:l.options)==null?void 0:c.weekStartsOn)??n.weekStartsOn??((m=(u=n.locale)==null?void 0:u.options)==null?void 0:m.weekStartsOn)??0,r=Os(e,t==null?void 0:t.in),a=r.getDay(),i=(a<s?7:0)+a-s;return r.setDate(r.getDate()-i),r.setHours(0,0,0,0),r}function $c(e,t){return qi(e,{...t,weekStartsOn:1})}function fS(e,t){const n=Os(e,t==null?void 0:t.in),s=n.getFullYear(),r=Tr(n,0);r.setFullYear(s+1,0,4),r.setHours(0,0,0,0);const a=$c(r),i=Tr(n,0);i.setFullYear(s,0,4),i.setHours(0,0,0,0);const l=$c(i);return n.getTime()>=a.getTime()?s+1:n.getTime()>=l.getTime()?s:s-1}function Ag(e){const t=Os(e),n=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return n.setUTCFullYear(t.getFullYear()),+e-+n}function bR(e,...t){const n=Tr.bind(null,t.find(s=>typeof s=="object"));return t.map(n)}function Ig(e,t){const n=Os(e,t==null?void 0:t.in);return n.setHours(0,0,0,0),n}function xR(e,t,n){const[s,r]=bR(n==null?void 0:n.in,e,t),a=Ig(s),i=Ig(r),l=+a-Ag(a),c=+i-Ag(i);return Math.round((l-c)/gR)}function vR(e,t){const n=fS(e,t),s=Tr(e,0);return s.setFullYear(n,0,4),s.setHours(0,0,0,0),$c(s)}function SR(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function wR(e){return!(!SR(e)&&typeof e!="number"||isNaN(+Os(e)))}function _R(e,t){const n=Os(e,t==null?void 0:t.in);return n.setFullYear(n.getFullYear(),0,1),n.setHours(0,0,0,0),n}const kR={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"}},TR=(e,t,n)=>{let s;const r=kR[e];return typeof r=="string"?s=r:t===1?s=r.one:s=r.other.replace("{{count}}",t.toString()),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"in "+s:s+" ago":s};function lu(e){return(t={})=>{const n=t.width?String(t.width):e.defaultWidth;return e.formats[n]||e.formats[e.defaultWidth]}}const jR={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},CR={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},MR={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},PR={date:lu({formats:jR,defaultWidth:"full"}),time:lu({formats:CR,defaultWidth:"full"}),dateTime:lu({formats:MR,defaultWidth:"full"})},ER={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},RR=(e,t,n,s)=>ER[e];function ja(e){return(t,n)=>{const s=n!=null&&n.context?String(n.context):"standalone";let r;if(s==="formatting"&&e.formattingValues){const i=e.defaultFormattingWidth||e.defaultWidth,l=n!=null&&n.width?String(n.width):i;r=e.formattingValues[l]||e.formattingValues[i]}else{const i=e.defaultWidth,l=n!=null&&n.width?String(n.width):e.defaultWidth;r=e.values[l]||e.values[i]}const a=e.argumentCallback?e.argumentCallback(t):t;return r[a]}}const AR={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},IR={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},OR={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"]},$R={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"]},DR={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"}},LR={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"}},FR=(e,t)=>{const n=Number(e),s=n%100;if(s>20||s<10)switch(s%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},NR={ordinalNumber:FR,era:ja({values:AR,defaultWidth:"wide"}),quarter:ja({values:IR,defaultWidth:"wide",argumentCallback:e=>e-1}),month:ja({values:OR,defaultWidth:"wide"}),day:ja({values:$R,defaultWidth:"wide"}),dayPeriod:ja({values:DR,defaultWidth:"wide",formattingValues:LR,defaultFormattingWidth:"wide"})};function Ca(e){return(t,n={})=>{const s=n.width,r=s&&e.matchPatterns[s]||e.matchPatterns[e.defaultMatchWidth],a=t.match(r);if(!a)return null;const i=a[0],l=s&&e.parsePatterns[s]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(l)?BR(l,p=>p.test(i)):zR(l,p=>p.test(i));let u;u=e.valueCallback?e.valueCallback(c):c,u=n.valueCallback?n.valueCallback(u):u;const m=t.slice(i.length);return{value:u,rest:m}}}function zR(e,t){for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&t(e[n]))return n}function BR(e,t){for(let n=0;n<e.length;n++)if(t(e[n]))return n}function WR(e){return(t,n={})=>{const s=t.match(e.matchPattern);if(!s)return null;const r=s[0],a=t.match(e.parsePattern);if(!a)return null;let i=e.valueCallback?e.valueCallback(a[0]):a[0];i=n.valueCallback?n.valueCallback(i):i;const l=t.slice(r.length);return{value:i,rest:l}}}const qR=/^(\d+)(th|st|nd|rd)?/i,UR=/\d+/i,HR={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},KR={any:[/^b/i,/^(a|c)/i]},YR={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},VR={any:[/1/i,/2/i,/3/i,/4/i]},XR={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},GR={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]},JR={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},QR={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]},ZR={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},eA={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}},tA={ordinalNumber:WR({matchPattern:qR,parsePattern:UR,valueCallback:e=>parseInt(e,10)}),era:Ca({matchPatterns:HR,defaultMatchWidth:"wide",parsePatterns:KR,defaultParseWidth:"any"}),quarter:Ca({matchPatterns:YR,defaultMatchWidth:"wide",parsePatterns:VR,defaultParseWidth:"any",valueCallback:e=>e+1}),month:Ca({matchPatterns:XR,defaultMatchWidth:"wide",parsePatterns:GR,defaultParseWidth:"any"}),day:Ca({matchPatterns:JR,defaultMatchWidth:"wide",parsePatterns:QR,defaultParseWidth:"any"}),dayPeriod:Ca({matchPatterns:ZR,defaultMatchWidth:"any",parsePatterns:eA,defaultParseWidth:"any"})},nA={code:"en-US",formatDistance:TR,formatLong:PR,formatRelative:RR,localize:NR,match:tA,options:{weekStartsOn:0,firstWeekContainsDate:1}};function sA(e,t){const n=Os(e,t==null?void 0:t.in);return xR(n,_R(n))+1}function rA(e,t){const n=Os(e,t==null?void 0:t.in),s=+$c(n)-+vR(n);return Math.round(s/hS)+1}function pS(e,t){var m,p,g,b;const n=Os(e,t==null?void 0:t.in),s=n.getFullYear(),r=nd(),a=(t==null?void 0:t.firstWeekContainsDate)??((p=(m=t==null?void 0:t.locale)==null?void 0:m.options)==null?void 0:p.firstWeekContainsDate)??r.firstWeekContainsDate??((b=(g=r.locale)==null?void 0:g.options)==null?void 0:b.firstWeekContainsDate)??1,i=Tr((t==null?void 0:t.in)||e,0);i.setFullYear(s+1,0,a),i.setHours(0,0,0,0);const l=qi(i,t),c=Tr((t==null?void 0:t.in)||e,0);c.setFullYear(s,0,a),c.setHours(0,0,0,0);const u=qi(c,t);return+n>=+l?s+1:+n>=+u?s:s-1}function oA(e,t){var l,c,u,m;const n=nd(),s=(t==null?void 0:t.firstWeekContainsDate)??((c=(l=t==null?void 0:t.locale)==null?void 0:l.options)==null?void 0:c.firstWeekContainsDate)??n.firstWeekContainsDate??((m=(u=n.locale)==null?void 0:u.options)==null?void 0:m.firstWeekContainsDate)??1,r=pS(e,t),a=Tr((t==null?void 0:t.in)||e,0);return a.setFullYear(r,0,s),a.setHours(0,0,0,0),qi(a,t)}function aA(e,t){const n=Os(e,t==null?void 0:t.in),s=+qi(n,t)-+oA(n,t);return Math.round(s/hS)+1}function zt(e,t){const n=e<0?"-":"",s=Math.abs(e).toString().padStart(t,"0");return n+s}const xr={y(e,t){const n=e.getFullYear(),s=n>0?n:1-n;return zt(t==="yy"?s%100:s,t.length)},M(e,t){const n=e.getMonth();return t==="M"?String(n+1):zt(n+1,2)},d(e,t){return zt(e.getDate(),t.length)},a(e,t){const n=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];case"aaaa":default:return n==="am"?"a.m.":"p.m."}},h(e,t){return zt(e.getHours()%12||12,t.length)},H(e,t){return zt(e.getHours(),t.length)},m(e,t){return zt(e.getMinutes(),t.length)},s(e,t){return zt(e.getSeconds(),t.length)},S(e,t){const n=t.length,s=e.getMilliseconds(),r=Math.trunc(s*Math.pow(10,n-3));return zt(r,t.length)}},Po={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Og={G:function(e,t,n){const s=e.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return n.era(s,{width:"abbreviated"});case"GGGGG":return n.era(s,{width:"narrow"});case"GGGG":default:return n.era(s,{width:"wide"})}},y:function(e,t,n){if(t==="yo"){const s=e.getFullYear(),r=s>0?s:1-s;return n.ordinalNumber(r,{unit:"year"})}return xr.y(e,t)},Y:function(e,t,n,s){const r=pS(e,s),a=r>0?r:1-r;if(t==="YY"){const i=a%100;return zt(i,2)}return t==="Yo"?n.ordinalNumber(a,{unit:"year"}):zt(a,t.length)},R:function(e,t){const n=fS(e);return zt(n,t.length)},u:function(e,t){const n=e.getFullYear();return zt(n,t.length)},Q:function(e,t,n){const s=Math.ceil((e.getMonth()+1)/3);switch(t){case"Q":return String(s);case"QQ":return zt(s,2);case"Qo":return n.ordinalNumber(s,{unit:"quarter"});case"QQQ":return n.quarter(s,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(s,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(s,{width:"wide",context:"formatting"})}},q:function(e,t,n){const s=Math.ceil((e.getMonth()+1)/3);switch(t){case"q":return String(s);case"qq":return zt(s,2);case"qo":return n.ordinalNumber(s,{unit:"quarter"});case"qqq":return n.quarter(s,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(s,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(s,{width:"wide",context:"standalone"})}},M:function(e,t,n){const s=e.getMonth();switch(t){case"M":case"MM":return xr.M(e,t);case"Mo":return n.ordinalNumber(s+1,{unit:"month"});case"MMM":return n.month(s,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(s,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(s,{width:"wide",context:"formatting"})}},L:function(e,t,n){const s=e.getMonth();switch(t){case"L":return String(s+1);case"LL":return zt(s+1,2);case"Lo":return n.ordinalNumber(s+1,{unit:"month"});case"LLL":return n.month(s,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(s,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(s,{width:"wide",context:"standalone"})}},w:function(e,t,n,s){const r=aA(e,s);return t==="wo"?n.ordinalNumber(r,{unit:"week"}):zt(r,t.length)},I:function(e,t,n){const s=rA(e);return t==="Io"?n.ordinalNumber(s,{unit:"week"}):zt(s,t.length)},d:function(e,t,n){return t==="do"?n.ordinalNumber(e.getDate(),{unit:"date"}):xr.d(e,t)},D:function(e,t,n){const s=sA(e);return t==="Do"?n.ordinalNumber(s,{unit:"dayOfYear"}):zt(s,t.length)},E:function(e,t,n){const s=e.getDay();switch(t){case"E":case"EE":case"EEE":return n.day(s,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(s,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(s,{width:"short",context:"formatting"});case"EEEE":default:return n.day(s,{width:"wide",context:"formatting"})}},e:function(e,t,n,s){const r=e.getDay(),a=(r-s.weekStartsOn+8)%7||7;switch(t){case"e":return String(a);case"ee":return zt(a,2);case"eo":return n.ordinalNumber(a,{unit:"day"});case"eee":return n.day(r,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(r,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(r,{width:"short",context:"formatting"});case"eeee":default:return n.day(r,{width:"wide",context:"formatting"})}},c:function(e,t,n,s){const r=e.getDay(),a=(r-s.weekStartsOn+8)%7||7;switch(t){case"c":return String(a);case"cc":return zt(a,t.length);case"co":return n.ordinalNumber(a,{unit:"day"});case"ccc":return n.day(r,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(r,{width:"narrow",context:"standalone"});case"cccccc":return n.day(r,{width:"short",context:"standalone"});case"cccc":default:return n.day(r,{width:"wide",context:"standalone"})}},i:function(e,t,n){const s=e.getDay(),r=s===0?7:s;switch(t){case"i":return String(r);case"ii":return zt(r,t.length);case"io":return n.ordinalNumber(r,{unit:"day"});case"iii":return n.day(s,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(s,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(s,{width:"short",context:"formatting"});case"iiii":default:return n.day(s,{width:"wide",context:"formatting"})}},a:function(e,t,n){const r=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(r,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(r,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(r,{width:"wide",context:"formatting"})}},b:function(e,t,n){const s=e.getHours();let r;switch(s===12?r=Po.noon:s===0?r=Po.midnight:r=s/12>=1?"pm":"am",t){case"b":case"bb":return n.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(r,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(r,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(r,{width:"wide",context:"formatting"})}},B:function(e,t,n){const s=e.getHours();let r;switch(s>=17?r=Po.evening:s>=12?r=Po.afternoon:s>=4?r=Po.morning:r=Po.night,t){case"B":case"BB":case"BBB":return n.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(r,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(r,{width:"wide",context:"formatting"})}},h:function(e,t,n){if(t==="ho"){let s=e.getHours()%12;return s===0&&(s=12),n.ordinalNumber(s,{unit:"hour"})}return xr.h(e,t)},H:function(e,t,n){return t==="Ho"?n.ordinalNumber(e.getHours(),{unit:"hour"}):xr.H(e,t)},K:function(e,t,n){const s=e.getHours()%12;return t==="Ko"?n.ordinalNumber(s,{unit:"hour"}):zt(s,t.length)},k:function(e,t,n){let s=e.getHours();return s===0&&(s=24),t==="ko"?n.ordinalNumber(s,{unit:"hour"}):zt(s,t.length)},m:function(e,t,n){return t==="mo"?n.ordinalNumber(e.getMinutes(),{unit:"minute"}):xr.m(e,t)},s:function(e,t,n){return t==="so"?n.ordinalNumber(e.getSeconds(),{unit:"second"}):xr.s(e,t)},S:function(e,t){return xr.S(e,t)},X:function(e,t,n){const s=e.getTimezoneOffset();if(s===0)return"Z";switch(t){case"X":return Dg(s);case"XXXX":case"XX":return Hr(s);case"XXXXX":case"XXX":default:return Hr(s,":")}},x:function(e,t,n){const s=e.getTimezoneOffset();switch(t){case"x":return Dg(s);case"xxxx":case"xx":return Hr(s);case"xxxxx":case"xxx":default:return Hr(s,":")}},O:function(e,t,n){const s=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+$g(s,":");case"OOOO":default:return"GMT"+Hr(s,":")}},z:function(e,t,n){const s=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+$g(s,":");case"zzzz":default:return"GMT"+Hr(s,":")}},t:function(e,t,n){const s=Math.trunc(+e/1e3);return zt(s,t.length)},T:function(e,t,n){return zt(+e,t.length)}};function $g(e,t=""){const n=e>0?"-":"+",s=Math.abs(e),r=Math.trunc(s/60),a=s%60;return a===0?n+String(r):n+String(r)+t+zt(a,2)}function Dg(e,t){return e%60===0?(e>0?"-":"+")+zt(Math.abs(e)/60,2):Hr(e,t)}function Hr(e,t=""){const n=e>0?"-":"+",s=Math.abs(e),r=zt(Math.trunc(s/60),2),a=zt(s%60,2);return n+r+t+a}const Lg=(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"})}},gS=(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"})}},iA=(e,t)=>{const n=e.match(/(P+)(p+)?/)||[],s=n[1],r=n[2];if(!r)return Lg(e,t);let a;switch(s){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}}",Lg(s,t)).replace("{{time}}",gS(r,t))},lA={p:gS,P:iA},cA=/^D+$/,dA=/^Y+$/,uA=["D","DD","YY","YYYY"];function mA(e){return cA.test(e)}function hA(e){return dA.test(e)}function fA(e,t,n){const s=pA(e,t,n);if(console.warn(s),uA.includes(e))throw new RangeError(s)}function pA(e,t,n){const s=e[0]==="Y"?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${s} to the input \`${n}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const gA=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,yA=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,bA=/^'([^]*?)'?$/,xA=/''/g,vA=/[a-zA-Z]/;function SA(e,t,n){var m,p,g,b;const s=nd(),r=s.locale??nA,a=s.firstWeekContainsDate??((p=(m=s.locale)==null?void 0:m.options)==null?void 0:p.firstWeekContainsDate)??1,i=s.weekStartsOn??((b=(g=s.locale)==null?void 0:g.options)==null?void 0:b.weekStartsOn)??0,l=Os(e,n==null?void 0:n.in);if(!wR(l))throw new RangeError("Invalid time value");let c=t.match(yA).map(S=>{const x=S[0];if(x==="p"||x==="P"){const k=lA[x];return k(S,r.formatLong)}return S}).join("").match(gA).map(S=>{if(S==="''")return{isToken:!1,value:"'"};const x=S[0];if(x==="'")return{isToken:!1,value:wA(S)};if(Og[x])return{isToken:!0,value:S};if(x.match(vA))throw new RangeError("Format string contains an unescaped latin alphabet character `"+x+"`");return{isToken:!1,value:S}});r.localize.preprocessor&&(c=r.localize.preprocessor(l,c));const u={firstWeekContainsDate:a,weekStartsOn:i,locale:r};return c.map(S=>{if(!S.isToken)return S.value;const x=S.value;(hA(x)||mA(x))&&fA(x,t,String(e));const k=Og[x[0]];return k(l,x,r.localize,u)}).join("")}function wA(e){const t=e.match(bA);return t?t[1].replace(xA,"'"):e}const{useToken:_A}=Qe,{Text:ql}=Ke,kA=({images:e,className:t,style:n,maxHeight:s={single:400,multiple:200}})=>{const{token:r}=_A(),{t:a}=Ae();return!e||e.length===0?null:o.jsx(Ce,{className:t,style:{marginBottom:r.marginMD,...n},styles:{body:{padding:0}},variant:"borderless",children:o.jsx(ve,{wrap:"wrap",gap:r.marginSM,style:{width:"100%"},children:e.map(i=>o.jsxs(Ce,{size:"small",style:{flex:e.length===1?"1 1 100%":"1 1 200px",overflow:"hidden",borderRadius:r.borderRadius,border:`1px solid ${r.colorBorderSecondary}`,backgroundColor:r.colorBgLayout},styles:{body:{padding:0}},children:[o.jsxs("div",{style:{position:"relative"},children:[o.jsx(p_,{src:i.url||i.base64,alt:i.name,style:{width:"100%",height:"auto",maxHeight:e.length===1?s.single:s.multiple,objectFit:"cover"},preview:{mask:o.jsxs(ve,{align:"center",justify:"center",gap:r.marginXS,style:{color:r.colorTextLightSolid},children:[o.jsx(Nc,{}),o.jsx(ql,{style:{color:r.colorTextLightSolid},children:a("components.imageGrid.preview")})]})}}),o.jsxs(ve,{vertical:!0,style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(transparent, rgba(0,0,0,0.7))",color:r.colorTextLightSolid,padding:`${r.paddingXS}px ${r.paddingSM}px`,fontSize:r.fontSizeSM},children:[o.jsx(ql,{style:{color:r.colorTextLightSolid},strong:!0,children:i.name}),i.size&&o.jsxs(ql,{style:{fontSize:r.fontSizeSM*.85,opacity:.8,color:r.colorTextLightSolid},children:[(i.size/1024).toFixed(1)," KB",i.width&&i.height&&` • ${i.width}×${i.height}`]})]})]}),(i.ocrText||i.ocrError)&&o.jsx("div",{style:{padding:r.paddingSM},children:o.jsx(lr,{ghost:!0,size:"small",items:[{key:"ocr",label:a("components.imageGrid.ocr"),children:o.jsxs(o.Fragment,{children:[i.ocrError&&o.jsx(ql,{type:"danger",children:i.ocrError}),i.ocrText&&o.jsx(Ke.Paragraph,{style:{marginTop:i.ocrError?r.marginXS:0,marginBottom:0,whiteSpace:"pre-wrap"},children:i.ocrText})]})}]})})]},i.id))})})},{useToken:TA}=Qe,{useBreakpoint:jA}=zc,CA=({buttons:e,isVisible:t,className:n,style:s,position:r={bottom:"8px",right:"8px"}})=>{const{token:a}=TA(),i=jA(),l=()=>(i.xs,"small");return o.jsx(ve,{justify:"flex-end",gap:a.marginXS,className:n,style:{marginTop:a.marginXS,position:"absolute",bottom:r.bottom,right:r.right,top:r.top,left:r.left,background:"transparent",zIndex:1,opacity:t?1:0,transition:"opacity 0.2s ease",pointerEvents:t?"auto":"none",...s},children:e.map(c=>o.jsx(bt,{title:c.title,children:o.jsx(de,{"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))})},MA=(e,t)=>({key:"copy","data-testid":"copy-message",icon:o.jsx(vs,{}),title:t||"Copy message",onClick:e}),PA=(e,t)=>({key:"reference",icon:o.jsx(Mb,{}),title:t||"Reference message",onClick:e}),{Title:Fg,Text:us,Paragraph:Ng}=Ke,{useToken:EA}=Qe,RA=({plan:e,contextId:t,onExecute:n,onRefine:s,timestamp:r})=>{const{t:a}=Ae(),{token:i}=EA(),[l,c]=f.useState(!1),[u,m]=f.useState(""),p=()=>{u.trim()&&(s(u),m(""),c(!1))};return o.jsxs(Ce,{style:{marginBottom:i.marginMD,borderColor:i.colorPrimary,borderWidth:2,backgroundColor:i.colorPrimaryBg},title:o.jsxs(he,{children:[o.jsx(ir,{style:{color:i.colorPrimary}}),o.jsx(us,{strong:!0,style:{color:i.colorPrimary},children:a("components.plan.executionPlan")})]}),extra:r?o.jsx(us,{type:"secondary",style:{fontSize:i.fontSizeSM},children:r}):void 0,children:[o.jsxs(ve,{vertical:!0,style:{marginBottom:i.marginLG},children:[o.jsx(Fg,{level:5,style:{marginBottom:i.marginXS},children:a("components.plan.goal")}),o.jsx(Ng,{style:{fontSize:15,marginBottom:0},children:e.goal})]}),o.jsxs(ve,{vertical:!0,style:{marginBottom:i.marginLG},children:[o.jsx(Fg,{level:5,style:{marginBottom:i.marginMD},children:a("components.plan.steps")}),o.jsx(Pb,{direction:"vertical",current:-1,items:e.steps.map(g=>({title:o.jsxs(us,{strong:!0,children:[a("components.plan.stepTitle",{number:g.step_number}),": ",g.action]}),description:o.jsxs(ve,{vertical:!0,children:[o.jsxs(Ng,{style:{marginBottom:i.marginXS},children:[o.jsxs(us,{type:"secondary",children:[a("components.plan.reason"),":"]})," ",g.reason]}),o.jsxs(he,{wrap:!0,children:[o.jsxs(us,{type:"secondary",children:[o.jsx(Ui,{})," ",a("components.plan.tools"),":"]}),g.tools_needed.map((b,S)=>o.jsx(Ne,{color:"processing",children:b},S))]}),o.jsx(ve,{style:{marginTop:i.marginXS},children:o.jsxs(us,{type:"secondary",children:[o.jsx(As,{})," ",a("components.plan.estimated"),": ",g.estimated_time]})})]}),icon:o.jsx(us,{children:g.step_number})}))})]}),o.jsxs(he,{direction:"vertical",style:{width:"100%",marginBottom:i.marginLG},children:[o.jsxs(ve,{align:"center",gap:i.marginXS,wrap:"wrap",children:[o.jsxs(us,{type:"secondary",children:[o.jsx(As,{})," ",a("components.plan.totalEstimatedTime")," "]}),o.jsx(Ne,{color:"processing",children:e.estimated_total_time})]}),e.prerequisites&&e.prerequisites.length>0&&o.jsxs(ve,{vertical:!0,children:[o.jsxs(us,{type:"secondary",children:[a("components.plan.prerequisites"),":"]}),o.jsx(Qt,{size:"small",dataSource:e.prerequisites,renderItem:(g,b)=>o.jsx(Qt.Item,{style:{padding:0},children:o.jsx(us,{children:g})},`${g}-${b}`)})]})]}),e.risks&&e.risks.length>0&&o.jsx(lr,{ghost:!0,style:{marginBottom:i.marginLG},items:[{key:"risks",label:o.jsxs(he,{children:[o.jsx(Yi,{style:{color:i.colorWarning}}),o.jsx(us,{strong:!0,children:a("components.plan.potentialRisks",{count:e.risks.length})})]}),children:o.jsx(Qt,{size:"small",dataSource:e.risks,renderItem:(g,b)=>o.jsx(Qt.Item,{style:{padding:0},children:o.jsx(us,{children:g})},`${g}-${b}`)})}]}),o.jsx(he,{style:{width:"100%",justifyContent:"flex-end"},children:l?o.jsxs(o.Fragment,{children:[o.jsx(de,{onClick:()=>c(!1),children:a("common.cancel")}),o.jsx(de,{type:"primary",onClick:p,disabled:!u.trim(),children:a("components.plan.sendFeedback")})]}):o.jsxs(o.Fragment,{children:[o.jsx(de,{onClick:()=>c(!0),children:a("components.plan.refinePlan")}),o.jsx(de,{type:"primary",icon:o.jsx(Eb,{}),onClick:n,children:a("components.plan.executePlan")})]})}),l&&o.jsx(ve,{vertical:!0,style:{marginTop:i.marginMD},children:o.jsx(et.TextArea,{value:u,onChange:g=>m(g.target.value),placeholder:a("components.plan.feedbackPlaceholder"),autoSize:{minRows:4,maxRows:10}})})]})},yS=f.memo(RA);yS.displayName="PlanMessageCard";const{Title:AA,Text:Eo,Paragraph:IA}=Ke,{useToken:OA}=Qe,$A=({question:e,contextId:t,onAnswer:n,disabled:s=!1,timestamp:r})=>{const{t:a}=Ae(),{token:i}=OA(),[l,c]=f.useState(e.default),[u,m]=f.useState(!1),p=async()=>{if(l){m(!0);try{await n(l)}catch(x){console.error("Failed to submit answer:",x)}finally{m(!1)}}},g=()=>{switch(e.severity){case"critical":return o.jsx(Om,{style:{color:i.colorError}});case"major":return o.jsx(Yi,{style:{color:i.colorWarning}});case"minor":return o.jsx(Kn,{style:{color:i.colorInfo}});default:return o.jsx(Rm,{style:{color:i.colorPrimary}})}},b=()=>{switch(e.severity){case"critical":return i.colorErrorBg;case"major":return i.colorWarningBg;case"minor":return i.colorInfoBg;default:return i.colorPrimaryBg}},S=()=>{switch(e.severity){case"critical":return i.colorError;case"major":return i.colorWarning;case"minor":return i.colorInfo;default:return i.colorPrimary}};return o.jsxs(Ce,{style:{marginBottom:i.marginMD,borderColor:S(),borderWidth:2,backgroundColor:b()},title:o.jsxs(he,{children:[g(),o.jsx(Eo,{strong:!0,style:{color:S()},children:a("components.question.agentQuestion")}),o.jsxs(Eo,{type:"secondary",style:{fontSize:12},children:["(",e.severity,")"]})]}),extra:r?o.jsx(Eo,{type:"secondary",style:{fontSize:i.fontSizeSM},children:r}):void 0,children:[o.jsx(ve,{vertical:!0,style:{marginBottom:i.marginLG},children:o.jsx(AA,{level:5,style:{marginBottom:i.marginXS},children:e.question})}),e.context&&o.jsx(Ht,{message:a("components.question.context"),description:e.context,type:"info",showIcon:!0,style:{marginBottom:i.marginLG}}),o.jsxs(ve,{vertical:!0,style:{marginBottom:i.marginLG},children:[o.jsx(Eo,{strong:!0,style:{display:"block",marginBottom:i.marginSM},children:a("components.question.chooseOption")}),o.jsx(xs.Group,{value:l,onChange:x=>c(x.target.value),disabled:s||u,style:{width:"100%"},children:o.jsx(he,{direction:"vertical",style:{width:"100%"},children:e.options.map(x=>o.jsx(Ce,{size:"small",hoverable:!s&&!u,style:{borderColor:l===x.value?i.colorPrimary:i.colorBorder,backgroundColor:l===x.value?i.colorPrimaryBg:i.colorBgContainer,cursor:s||u?"not-allowed":"pointer"},onClick:()=>!s&&!u&&c(x.value),children:o.jsx(xs,{value:x.value,style:{width:"100%"},children:o.jsxs(ve,{vertical:!0,children:[o.jsxs(ve,{align:"center",gap:i.marginXS,wrap:"wrap",children:[o.jsx(Eo,{strong:!0,children:x.label}),x.value===e.default&&o.jsx(Ne,{color:"processing",style:{marginLeft:i.marginXS},children:a("components.question.recommended")})]}),o.jsx(IA,{type:"secondary",style:{marginTop:i.marginXXS,marginBottom:0},children:x.description})]})})},x.value))})})]}),e.allow_custom&&o.jsxs(ve,{vertical:!0,style:{marginBottom:i.marginMD},children:[o.jsx(Eo,{type:"secondary",style:{fontSize:12},children:a("components.question.customAnswerHint")}),o.jsx(et.TextArea,{value:l&&!e.options.find(x=>x.value===l)?l:"",onChange:x=>c(x.target.value),placeholder:a("components.question.customAnswerPlaceholder"),disabled:s||u,autoSize:{minRows:3,maxRows:8},style:{marginTop:i.marginXS}})]}),o.jsx(ve,{justify:"flex-end",children:o.jsx(de,{type:"primary",icon:o.jsx(ir,{}),onClick:p,loading:u,disabled:s||!l,children:a("components.question.submitAnswer")})})]})},bS=f.memo($A);bS.displayName="QuestionMessageCard";const{Text:zg}=Ke,DA=({paths:e,displayText:t})=>{const{token:n}=Qe.useToken(),s=t.replace(/@[^\s]+/g,"").trim();return o.jsxs(Ce,{size:"small",styles:{body:{padding:`${n.paddingSM}px ${n.paddingMD}px`}},style:{maxWidth:"100%"},children:[o.jsx(he,{direction:"vertical",size:n.marginXXS,children:e.map((r,a)=>{const i=r.split("/").pop()||r,l=r.substring(0,r.lastIndexOf("/"))||"",c=!i.includes(".");return o.jsxs(ve,{vertical:!0,children:[o.jsxs(he,{size:n.marginXS,align:"center",wrap:!0,children:[c?o.jsx(gc,{style:{color:n.colorWarning,fontSize:n.fontSizeLG}}):o.jsx(qo,{style:{color:n.colorPrimary,fontSize:n.fontSizeLG}}),o.jsx(Ne,{color:c?"warning":"processing",style:{margin:0,fontFamily:n.fontFamilyCode,fontSize:n.fontSize},children:i})]}),l&&o.jsx(bt,{title:r,children:o.jsxs(he,{size:4,align:"center",style:{marginTop:4},children:[o.jsx(gc,{style:{color:n.colorTextTertiary,fontSize:n.fontSizeSM}}),o.jsx(zg,{type:"secondary",style:{fontSize:n.fontSizeSM,fontFamily:n.fontFamilyCode,maxWidth:"400px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},copyable:{text:r},children:l})]})})]},a)})}),s&&o.jsx(zg,{style:{fontSize:n.fontSize,color:n.colorText,marginTop:n.marginXS,paddingTop:n.marginXS,borderTop:`1px solid ${n.colorBorderSecondary}`},children:s})]})},xS=f.memo(DA);xS.displayName="FileReferenceCard";const LA=({taskList:e})=>{const{token:t}=Qe.useToken(),{Text:n}=Ke,s=l=>{switch(l){case"pending":return o.jsx(Ne,{icon:o.jsx(As,{}),color:"default",children:"Pending"});case"in_progress":return o.jsx(Ne,{icon:o.jsx(io,{spin:!0}),color:"processing",children:"In Progress"});case"completed":return o.jsx(Ne,{icon:o.jsx(ir,{}),color:"success",children:"Completed"});case"skipped":return o.jsx(Ne,{icon:o.jsx(Ru,{}),color:"default",children:"Skipped"});case"failed":return o.jsx(Ne,{icon:o.jsx(pc,{}),color:"error",children:"Failed"});default:return null}},r=()=>{switch(e.status){case"active":return o.jsx(Ne,{color:"processing",children:"Active"});case"completed":return o.jsx(Ne,{color:"success",children:"Completed"});case"abandoned":return o.jsx(Ne,{color:"error",children:"Abandoned"});default:return null}},a=pn.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=pn.useMemo(()=>e.items.find(l=>l.status==="in_progress"),[e.items]);return o.jsx(Ce,{size:"small",styles:{body:{padding:t.paddingSM}},style:{borderRadius:t.borderRadiusLG},children:o.jsxs(ve,{vertical:!0,gap:t.marginSM,children:[o.jsxs(ve,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[o.jsxs(he,{direction:"vertical",size:2,children:[o.jsx(n,{strong:!0,children:e.title}),e.description?o.jsx(n,{type:"secondary",children:e.description}):null]}),r()]}),o.jsxs(he,{direction:"vertical",size:4,children:[o.jsx(Dm,{percent:a,status:e.status==="completed"?"success":e.status==="abandoned"?"exception":"active",showInfo:!0}),o.jsxs(n,{type:"secondary",children:[a,"% Complete"]})]}),o.jsx(Qt,{size:"small",dataSource:e.items,renderItem:l=>{var u;const c=(i==null?void 0:i.id)===l.id;return o.jsx(Qt.Item,{style:{borderRadius:t.borderRadius,padding:t.paddingXS,background:c?t.colorPrimaryBg:"transparent",border:"1px solid",borderColor:c?t.colorPrimaryBorder:t.colorBorderSecondary},children:o.jsxs(ve,{vertical:!0,style:{width:"100%"},gap:4,children:[o.jsxs(ve,{align:"center",justify:"space-between",wrap:"wrap",gap:8,children:[o.jsx(n,{children:l.description}),s(l.status)]}),l.status==="failed"&&((u=l.metadata)!=null&&u.error)?o.jsx(n,{type:"danger",style:{fontSize:12},children:l.metadata.error}):null,l.status==="completed"&&l.summary?o.jsx(n,{type:"success",style:{fontSize:12},children:l.summary}):null]})})}}),o.jsxs(ve,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[o.jsxs(n,{type:"secondary",style:{fontSize:12},children:[e.items.filter(l=>l.status==="completed").length," /"," ",e.items.length," tasks completed"]}),i?o.jsxs(n,{type:"secondary",style:{fontSize:12},children:["Current: ",i.description]}):null]})]})})},FA=100,Kr=new Set;function NA(e){if(Kr.has(e)&&Kr.delete(e),Kr.add(e),Kr.size>FA){const t=Kr.values().next().value;t&&Kr.delete(t)}}function zA(e){let t=2166136261;for(let n=0;n<e.length;n++)t=(t^e.charCodeAt(n))*16777619;return(t>>>0).toString(36)}const BA=e=>{const{t}=Ae(),n=zA(e.chart),[s,r]=f.useState(()=>Kr.has(n)),a=f.useRef(null);return f.useEffect(()=>{if(s)return;const i=a.current;if(!i)return;const l=new IntersectionObserver(c=>{c.some(u=>u.isIntersecting)&&(NA(n),r(!0),l.disconnect())},{rootMargin:"50px",threshold:.01});return l.observe(i),()=>l.disconnect()},[s,n]),o.jsx("div",{ref:a,style:{minHeight:s?"auto":"200px"},children:s?o.jsx(pn.Suspense,{fallback:o.jsx(Rs,{size:"small",tip:t("components.mermaid.loadingDiagram")}),children:o.jsx(WA,{...e})}):o.jsx("div",{style:{minHeight:"200px"}})})},WA=e=>{const{t}=Ae(),[n,s]=f.useState(null);return f.useEffect(()=>{let r=!1;return Bn(()=>Promise.resolve().then(()=>pO),void 0,import.meta.url).then(a=>{r||s(()=>a.MermaidChart)}),()=>{r=!0}},[]),n?o.jsx(n,{...e}):o.jsx(Rs,{size:"small",tip:t("components.mermaid.loadingDiagram")})},qA=pn.memo(BA),UA=({error:e,className:t,style:n,token:s,onFix:r,isFixing:a,fixError:i})=>{const{t:l}=Ae(),c=e.split(`
181
+
182
+ `);return o.jsxs("div",{className:t,style:{color:s.colorError,padding:`${s.paddingXS}px ${s.paddingSM}px`,fontSize:s.fontSizeSM,background:s.colorErrorBg,borderRadius:s.borderRadiusSM,border:`1px solid ${s.colorErrorBorder}`,margin:`${s.marginXS}px 0`,minHeight:"60px",maxHeight:"120px",display:"flex",flexDirection:"column",alignItems:"flex-start",justifyContent:"flex-start",overflow:"auto",position:"relative",maxWidth:"100%",boxSizing:"border-box",...n},title:`${l("components.mermaid.errorTitlePrefix")}: ${e}
183
+
184
+ ${l("components.mermaid.checkConsoleHint")}`,children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:s.marginXXS},children:[o.jsx("span",{style:{marginRight:s.marginXS,fontSize:"14px",flexShrink:0,lineHeight:1},children:o.jsx(Yi,{})}),o.jsx("span",{style:{fontWeight:600,color:s.colorError},children:l("components.mermaid.diagramError")})]}),o.jsx("div",{style:{fontSize:s.fontSizeSM,lineHeight:1.4,wordBreak:"break-word",flex:1,width:"100%"},children:c.map((u,m)=>o.jsx("div",{style:{marginBottom:m<c.length-1?s.marginXS:0,...u.startsWith("💡")?{backgroundColor:s.colorInfoBg,border:`1px solid ${s.colorInfoBorder}`,borderRadius:s.borderRadiusSM,padding:s.paddingXS,marginTop:s.marginXS,color:s.colorInfo,fontWeight:500}:{}},children:u},`${m}-${u.substring(0,12)}`))}),r&&o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.marginXS,marginTop:s.marginXS,width:"100%"},children:[o.jsx(de,{size:"small",type:"primary",onClick:r,loading:a,children:l("components.mermaid.fixMermaid")}),i&&o.jsx("span",{style:{color:s.colorError,fontSize:s.fontSizeSM,wordBreak:"break-word",flex:1},children:i})]}),o.jsxs("div",{style:{fontSize:s.fontSizeSM,color:s.colorTextSecondary,marginTop:s.marginXS,fontStyle:"italic"},children:[o.jsx(wb,{style:{marginRight:4}})," ",l("components.mermaid.checkConsoleHint")]})]})};var ys=function(e,t){return Number(e.toFixed(t))},HA=function(e,t){return typeof e=="number"?e:t},Yt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},KA=function(e){return-Math.cos(e*Math.PI)/2+.5},YA=function(e){return e},VA=function(e){return e*e},XA=function(e){return e*(2-e)},GA=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},JA=function(e){return e*e*e},QA=function(e){return--e*e*e+1},ZA=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},eI=function(e){return e*e*e*e},tI=function(e){return 1- --e*e*e*e},nI=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},sI=function(e){return e*e*e*e*e},rI=function(e){return 1+--e*e*e*e*e},oI=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},vS={easeOut:KA,linear:YA,easeInQuad:VA,easeOutQuad:XA,easeInOutQuad:GA,easeInCubic:JA,easeOutCubic:QA,easeInOutCubic:ZA,easeInQuart:eI,easeOutQuart:tI,easeInOutQuart:nI,easeInQuint:sI,easeOutQuint:rI,easeInOutQuint:oI},SS=function(e){typeof e=="number"&&cancelAnimationFrame(e)},Ms=function(e){e.mounted&&(SS(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function wS(e,t,n,s){if(e.mounted){var r=new Date().getTime(),a=1;Ms(e),e.animation=function(){if(!e.mounted)return SS(e.animation);var i=new Date().getTime()-r,l=i/n,c=vS[t],u=c(l);i>=n?(s(a),e.animation=null):e.animation&&(s(u),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function aI(e){var t=e.scale,n=e.positionX,s=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(s))}function Rr(e,t,n,s){var r=aI(t);if(!(!e.mounted||!r)){var a=e.setTransformState,i=e.transformState,l=i.scale,c=i.positionX,u=i.positionY,m=t.scale-l,p=t.positionX-c,g=t.positionY-u;n===0?a(t.scale,t.positionX,t.positionY):wS(e,s,n,function(b){var S=l+m*b,x=c+p*b,k=u+g*b;a(S,x,k)})}}function iI(e,t,n){var s=e.offsetWidth,r=e.offsetHeight,a=t.offsetWidth,i=t.offsetHeight,l=a*n,c=i*n,u=s-l,m=r-c;return{wrapperWidth:s,wrapperHeight:r,newContentWidth:l,newDiffWidth:u,newContentHeight:c,newDiffHeight:m}}var lI=function(e,t,n,s,r,a,i){var l=e>t?n*(i?1:.5):0,c=s>r?a*(i?1:.5):0,u=e-t-l,m=l,p=s-r-c,g=c;return{minPositionX:u,maxPositionX:m,minPositionY:p,maxPositionY:g}},Ch=function(e,t){var n=e.wrapperComponent,s=e.contentComponent,r=e.setup.centerZoomedOut;if(!n||!s)throw new Error("Components are not mounted");var a=iI(n,s,t),i=a.wrapperWidth,l=a.wrapperHeight,c=a.newContentWidth,u=a.newDiffWidth,m=a.newContentHeight,p=a.newDiffHeight,g=lI(i,c,u,l,m,p,!!r);return g},gm=function(e,t,n,s){return s?e<t?ys(t,2):e>n?ys(n,2):ys(e,2):ys(e,2)},ao=function(e,t){var n=Ch(e,t);return e.bounds=n,n};function rl(e,t,n,s,r,a,i){var l=n.minPositionX,c=n.minPositionY,u=n.maxPositionX,m=n.maxPositionY,p=0,g=0;i&&(p=r,g=a);var b=gm(e,l-p,u+p,s),S=gm(t,c-g,m+g,s);return{x:b,y:S}}function sd(e,t,n,s,r,a){var i=e.transformState,l=i.scale,c=i.positionX,u=i.positionY,m=s-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:c,y:u};var p=c-t*m,g=u-n*m,b=rl(p,g,r,a,0,0,null);return b}function ol(e,t,n,s,r){var a=r?s:0,i=t-a;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=i?i:e}var Bg=function(e,t){var n=e.setup.panning.excluded,s=e.isInitialized,r=e.wrapperComponent,a=t.target,i="shadowRoot"in a&&"composedPath"in t,l=i?t.composedPath().some(function(m){return m instanceof Element?r==null?void 0:r.contains(m):!1}):r==null?void 0:r.contains(a),c=s&&a&&l;if(!c)return!1;var u=rd(a,n);return!u},Wg=function(e){var t=e.isInitialized,n=e.isPanning,s=e.setup,r=s.panning.disabled,a=t&&n&&!r;return!!a},cI=function(e,t){var n=e.transformState,s=n.positionX,r=n.positionY;e.isPanning=!0;var a=t.clientX,i=t.clientY;e.startCoords={x:a-s,y:i-r}},dI=function(e,t){var n=t.touches,s=e.transformState,r=s.positionX,a=s.positionY;e.isPanning=!0;var i=n.length===1;if(i){var l=n[0].clientX,c=n[0].clientY;e.startCoords={x:l-r,y:c-a}}};function uI(e){var t=e.transformState,n=t.positionX,s=t.positionY,r=t.scale,a=e.setup,i=a.disabled,l=a.limitToBounds,c=a.centerZoomedOut,u=e.wrapperComponent;if(!(i||!u||!e.bounds)){var m=e.bounds,p=m.maxPositionX,g=m.minPositionX,b=m.maxPositionY,S=m.minPositionY,x=n>p||n<g,k=s>b||s<S,j=n>p?u.offsetWidth:e.setup.minPositionX||0,w=s>b?u.offsetHeight:e.setup.minPositionY||0,M=sd(e,j,w,r,e.bounds,l||c),_=M.x,C=M.y;return{scale:r,positionX:x?_:n,positionY:k?C:s}}}function _S(e,t,n,s,r){var a=e.setup.limitToBounds,i=e.wrapperComponent,l=e.bounds,c=e.transformState,u=c.scale,m=c.positionX,p=c.positionY;if(!(i===null||l===null||t===m&&n===p)){var g=rl(t,n,l,a,s,r,i),b=g.x,S=g.y;e.setTransformState(u,b,S)}}var mI=function(e,t,n){var s=e.startCoords,r=e.transformState,a=e.setup.panning,i=a.lockAxisX,l=a.lockAxisY,c=r.positionX,u=r.positionY;if(!s)return{x:c,y:u};var m=t-s.x,p=n-s.y,g=i?c:m,b=l?u:p;return{x:g,y:b}},jr=function(e,t){var n=e.setup,s=e.transformState,r=s.scale,a=n.minScale,i=n.disablePadding;return t>0&&r>=a&&!i?t:0},hI=function(e){var t=e.mounted,n=e.setup,s=n.disabled,r=n.velocityAnimation,a=e.transformState.scale,i=r.disabled,l=!i||a>1||!s||t;return!!l},fI=function(e){var t=e.mounted,n=e.velocity,s=e.bounds,r=e.setup,a=r.disabled,i=r.velocityAnimation,l=e.transformState.scale,c=i.disabled,u=!c||l>1||!a||t;return!(!u||!n||!s)};function pI(e,t){var n=e.setup.velocityAnimation,s=n.equalToMove,r=n.animationTime,a=n.sensitivity;return s?r*t*a:r}function qg(e,t,n,s,r,a,i,l,c,u){if(r){if(t>i&&n>i){var m=i+(e-i)*u;return m>c?c:m<i?i:m}if(t<a&&n<a){var m=a+(e-a)*u;return m<l?l:m>a?a:m}}return s?t:gm(e,a,i,r)}function gI(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function yI(e,t){var n=hI(e);if(n){var s=e.lastMousePosition,r=e.velocityTime,a=e.setup,i=e.wrapperComponent,l=a.velocityAnimation.equalToMove,c=Date.now();if(s&&r&&i){var u=gI(i,l),m=t.x-s.x,p=t.y-s.y,g=m/u,b=p/u,S=c-r,x=m*m+p*p,k=Math.sqrt(x)/S;e.velocity={velocityX:g,velocityY:b,total:k}}e.lastMousePosition=t,e.velocityTime=c}}function bI(e){var t=e.velocity,n=e.bounds,s=e.setup,r=e.wrapperComponent,a=fI(e);if(!(!a||!t||!n||!r)){var i=t.velocityX,l=t.velocityY,c=t.total,u=n.maxPositionX,m=n.minPositionX,p=n.maxPositionY,g=n.minPositionY,b=s.limitToBounds,S=s.alignmentAnimation,x=s.zoomAnimation,k=s.panning,j=k.lockAxisY,w=k.lockAxisX,M=x.animationType,_=S.sizeX,C=S.sizeY,D=S.velocityAlignmentTime,A=D,B=pI(e,c),F=Math.max(B,A),O=jr(e,_),R=jr(e,C),I=O*r.offsetWidth/100,L=R*r.offsetHeight/100,U=u+I,q=m-I,H=p+L,P=g-L,W=e.transformState,ne=new Date().getTime();wS(e,M,F,function(K){var xe=e.transformState,se=xe.scale,fe=xe.positionX,Se=xe.positionY,me=new Date().getTime()-ne,ze=me/A,st=vS[S.animationType],pt=1-st(Math.min(1,ze)),Kt=1-K,Oe=fe+i*Kt,Wt=Se+l*Kt,Xe=qg(Oe,W.positionX,fe,w,b,m,u,q,U,pt),_e=qg(Wt,W.positionY,Se,j,b,g,p,P,H,pt);(fe!==Oe||Se!==Wt)&&e.setTransformState(se,Xe,_e)})}}function Ug(e,t){var n=e.transformState.scale;Ms(e),ao(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?dI(e,t):cI(e,t)}function Mh(e,t){var n=e.transformState.scale,s=e.setup,r=s.minScale,a=s.alignmentAnimation,i=a.disabled,l=a.sizeX,c=a.sizeY,u=a.animationTime,m=a.animationType,p=i||n<r||!l&&!c;if(!p){var g=uI(e);g&&Rr(e,g,t??u,m)}}function Hg(e,t,n){var s=e.startCoords,r=e.setup,a=r.alignmentAnimation,i=a.sizeX,l=a.sizeY;if(s){var c=mI(e,t,n),u=c.x,m=c.y,p=jr(e,i),g=jr(e,l);yI(e,{x:u,y:m}),_S(e,u,m,p,g)}}function xI(e){if(e.isPanning){var t=e.setup.panning.velocityDisabled,n=e.velocity,s=e.wrapperComponent,r=e.contentComponent;e.isPanning=!1,e.animate=!1,e.animation=null;var a=s==null?void 0:s.getBoundingClientRect(),i=r==null?void 0:r.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,m=(i==null?void 0:i.height)||0,p=l<u||c<m,g=!t&&n&&(n==null?void 0:n.total)>.1&&p;g?bI(e):Mh(e)}}function Ph(e,t,n,s){var r=e.setup,a=r.minScale,i=r.maxScale,l=r.limitToBounds,c=ol(ys(t,2),a,i,0,!1),u=ao(e,c),m=sd(e,n,s,c,u,l),p=m.x,g=m.y;return{scale:c,positionX:p,positionY:g}}function kS(e,t,n){var s=e.transformState.scale,r=e.wrapperComponent,a=e.setup,i=a.minScale,l=a.limitToBounds,c=a.zoomAnimation,u=c.disabled,m=c.animationTime,p=c.animationType,g=u||s>=i;if((s>=1||l)&&Mh(e),!(g||!r||!e.mounted)){var b=t||r.offsetWidth/2,S=n||r.offsetHeight/2,x=Ph(e,i,b,S);x&&Rr(e,x,m,p)}}var kr=function(){return kr=Object.assign||function(t){for(var n,s=1,r=arguments.length;s<r;s++){n=arguments[s];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},kr.apply(this,arguments)};function Kg(e,t,n){for(var s=0,r=t.length,a;s<r;s++)(a||!(s in t))&&(a||(a=Array.prototype.slice.call(t,0,s)),a[s]=t[s]);return e.concat(a||Array.prototype.slice.call(t))}var Ul={scale:1,positionX:0,positionY:0},Ma={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}},ym={wrapperClass:"react-transform-wrapper",contentClass:"react-transform-component"},TS=function(e){var t,n,s,r;return{previousScale:(t=e.initialScale)!==null&&t!==void 0?t:Ul.scale,scale:(n=e.initialScale)!==null&&n!==void 0?n:Ul.scale,positionX:(s=e.initialPositionX)!==null&&s!==void 0?s:Ul.positionX,positionY:(r=e.initialPositionY)!==null&&r!==void 0?r:Ul.positionY}},Yg=function(e){var t=kr({},Ma);return Object.keys(e).forEach(function(n){var s=typeof e[n]<"u",r=typeof Ma[n]<"u";if(r&&s){var a=Object.prototype.toString.call(Ma[n]),i=a==="[object Object]",l=a==="[object Array]";i?t[n]=kr(kr({},Ma[n]),e[n]):l?t[n]=Kg(Kg([],Ma[n],!0),e[n]):t[n]=e[n]}}),t},jS=function(e,t,n){var s=e.transformState.scale,r=e.wrapperComponent,a=e.setup,i=a.maxScale,l=a.minScale,c=a.zoomAnimation,u=a.smooth,m=c.size;if(!r)throw new Error("Wrapper is not mounted");var p=u?s*Math.exp(t*n):s+t*n,g=ol(ys(p,3),l,i,m,!1);return g};function CS(e,t,n,s,r){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 m=a.offsetWidth,p=a.offsetHeight,g=(m/2-c)/l,b=(p/2-u)/l,S=jS(e,t,n),x=Ph(e,S,g,b);if(!x)return console.error("Error during zoom event. New transformation state was not calculated.");Rr(e,x,s,r)}function MS(e,t,n,s){var r=e.setup,a=e.wrapperComponent,i=r.limitToBounds,l=TS(e.props),c=e.transformState,u=c.scale,m=c.positionX,p=c.positionY;if(a){var g=Ch(e,l.scale),b=rl(l.positionX,l.positionY,g,i,0,0,a),S={scale:l.scale,positionX:b.x,positionY:b.y};u===l.scale&&m===l.positionX&&p===l.positionY||(s==null||s(),Rr(e,S,t,n))}}function vI(e,t,n,s){var r=e.getBoundingClientRect(),a=t.getBoundingClientRect(),i=n.getBoundingClientRect(),l=a.x*s.scale,c=a.y*s.scale;return{x:(r.x-i.x+l)/s.scale,y:(r.y-i.y+c)/s.scale}}function SI(e,t,n){var s=e.wrapperComponent,r=e.contentComponent,a=e.transformState,i=e.setup,l=i.limitToBounds,c=i.minScale,u=i.maxScale;if(!s||!r)return a;var m=s.getBoundingClientRect(),p=t.getBoundingClientRect(),g=vI(t,s,r,a),b=g.x,S=g.y,x=p.width/a.scale,k=p.height/a.scale,j=s.offsetWidth/x,w=s.offsetHeight/k,M=ol(n||Math.min(j,w),c,u,0,!1),_=(m.width-x*M)/2,C=(m.height-k*M)/2,D=(m.left-b)*M+_,A=(m.top-S)*M+C,B=Ch(e,M),F=rl(D,A,B,l,0,0,s),O=F.x,R=F.y;return{positionX:O,positionY:R,scale:M}}var wI=function(e){return function(t,n,s){t===void 0&&(t=.5),n===void 0&&(n=300),s===void 0&&(s="easeOut"),CS(e,1,t,n,s)}},_I=function(e){return function(t,n,s){t===void 0&&(t=.5),n===void 0&&(n=300),s===void 0&&(s="easeOut"),CS(e,-1,t,n,s)}},kI=function(e){return function(t,n,s,r,a){r===void 0&&(r=300),a===void 0&&(a="easeOut");var i=e.transformState,l=i.positionX,c=i.positionY,u=i.scale,m=e.wrapperComponent,p=e.contentComponent,g=e.setup.disabled;if(!(g||!m||!p)){var b={positionX:Number.isNaN(t)?l:t,positionY:Number.isNaN(n)?c:n,scale:Number.isNaN(s)?u:s};Rr(e,b,r,a)}}},TI=function(e){return function(t,n){t===void 0&&(t=200),n===void 0&&(n="easeOut"),MS(e,t,n)}},jI=function(e){return function(t,n,s){n===void 0&&(n=200),s===void 0&&(s="easeOut");var r=e.transformState,a=e.wrapperComponent,i=e.contentComponent;if(a&&i){var l=PS(t||r.scale,a,i);Rr(e,l,n,s)}}},CI=function(e){return function(t,n,s,r){s===void 0&&(s=600),r===void 0&&(r="easeOut"),Ms(e);var a=e.wrapperComponent,i=typeof t=="string"?document.getElementById(t):t;if(a&&i&&a.contains(i)){var l=SI(e,i,n);Rr(e,l,s,r)}}},bm=function(e){return{instance:e,zoomIn:wI(e),zoomOut:_I(e),setTransform:kI(e),resetTransform:TI(e),centerView:jI(e),zoomToElement:CI(e)}},MI=function(e){return{instance:e,state:e.transformState}},Ut=function(e){var t={};return Object.assign(t,MI(e)),Object.assign(t,bm(e)),t},cu=!1;function du(){try{var e={get passive(){return cu=!0,!1}};return e}catch{return cu=!1,cu}}var Hl=".".concat(ym.wrapperClass),rd=function(e,t){return t.some(function(n){return e.matches("".concat(Hl," ").concat(n,", ").concat(Hl," .").concat(n,", ").concat(Hl," ").concat(n," *, ").concat(Hl," .").concat(n," *"))})},xm=function(e){e&&clearTimeout(e)},PI=function(e,t,n){return"translate(".concat(e,"px, ").concat(t,"px) scale(").concat(n,")")},PS=function(e,t,n){var s=n.offsetWidth*e,r=n.offsetHeight*e,a=(t.offsetWidth-s)/2,i=(t.offsetHeight-r)/2;return{scale:e,positionX:a,positionY:i}};function EI(e){return function(t){e.forEach(function(n){typeof n=="function"?n(t):n!=null&&(n.current=t)})}}var RI=function(e,t){var n=e.setup.wheel,s=n.disabled,r=n.wheelDisabled,a=n.touchPadDisabled,i=n.excluded,l=e.isInitialized,c=e.isPanning,u=t.target,m=l&&!c&&!s&&u;if(!m||r&&!t.ctrlKey||a&&t.ctrlKey)return!1;var p=rd(u,i);return!p},AI=function(e){return e?e.deltaY<0?1:-1:0};function II(e,t){var n=AI(e),s=HA(t,n);return s}function ES(e,t,n){var s=t.getBoundingClientRect(),r=0,a=0;if("clientX"in e)r=(e.clientX-s.left)/n,a=(e.clientY-s.top)/n;else{var i=e.touches[0];r=(i.clientX-s.left)/n,a=(i.clientY-s.top)/n}return(Number.isNaN(r)||Number.isNaN(a))&&console.error("No mouse or touch offset found"),{x:r,y:a}}var OI=function(e,t,n,s,r){var a=e.transformState.scale,i=e.wrapperComponent,l=e.setup,c=l.maxScale,u=l.minScale,m=l.zoomAnimation,p=l.disablePadding,g=m.size,b=m.disabled;if(!i)throw new Error("Wrapper is not mounted");var S=a+t*n,x=s?!1:!b,k=ol(ys(S,3),u,c,g,x&&!p);return k},$I=function(e,t){var n=e.previousWheelEvent,s=e.transformState.scale,r=e.setup,a=r.maxScale,i=r.minScale;return n?s<a||s>i||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaY<t.deltaY||n.deltaY<0&&n.deltaY>t.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},DI=function(e,t){var n=e.setup.pinch,s=n.disabled,r=n.excluded,a=e.isInitialized,i=t.target,l=a&&!s&&i;if(!l)return!1;var c=rd(i,r);return!c},LI=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,s=e.pinchStartDistance,r=n&&!t&&s;return!!r},FI=function(e,t,n){var s=n.getBoundingClientRect(),r=e.touches,a=ys(r[0].clientX-s.left,5),i=ys(r[0].clientY-s.top,5),l=ys(r[1].clientX-s.left,5),c=ys(r[1].clientY-s.top,5);return{x:(a+l)/2/t,y:(i+c)/2/t}},RS=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))},NI=function(e,t){var n=e.pinchStartScale,s=e.pinchStartDistance,r=e.setup,a=r.maxScale,i=r.minScale,l=r.zoomAnimation,c=r.disablePadding,u=l.size,m=l.disabled;if(!n||s===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var p=t/s,g=p*n;return ol(ys(g,2),i,a,u,!m&&!c)},zI=160,BI=100,WI=function(e,t){var n=e.props,s=n.onWheelStart,r=n.onZoomStart;e.wheelStopEventTimer||(Ms(e),Yt(Ut(e),t,s),Yt(Ut(e),t,r))},qI=function(e,t){var n=e.props,s=n.onWheel,r=n.onZoom,a=e.contentComponent,i=e.setup,l=e.transformState,c=l.scale,u=i.limitToBounds,m=i.centerZoomedOut,p=i.zoomAnimation,g=i.wheel,b=i.disablePadding,S=i.smooth,x=p.size,k=p.disabled,j=g.step,w=g.smoothStep;if(!a)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var M=II(t,null),_=S?w*Math.abs(t.deltaY):j,C=OI(e,M,_,!t.ctrlKey);if(c!==C){var D=ao(e,C),A=ES(t,a,c),B=k||x===0||m||b,F=u&&B,O=sd(e,A.x,A.y,C,D,F),R=O.x,I=O.y;e.previousWheelEvent=t,e.setTransformState(C,R,I),Yt(Ut(e),t,s),Yt(Ut(e),t,r)}},UI=function(e,t){var n=e.props,s=n.onWheelStop,r=n.onZoomStop;xm(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(kS(e,t.x,t.y),e.wheelAnimationTimer=null)},BI);var a=$I(e,t);a&&(xm(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Yt(Ut(e),t,s),Yt(Ut(e),t,r))},zI))},AS=function(e){for(var t=0,n=0,s=0;s<2;s+=1)t+=e.touches[s].clientX,n+=e.touches[s].clientY;var r=t/2,a=n/2;return{x:r,y:a}},HI=function(e,t){var n=RS(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1;var s=AS(t);e.pinchLastCenterX=s.x,e.pinchLastCenterY=s.y,Ms(e)},KI=function(e,t){var n=e.contentComponent,s=e.pinchStartDistance,r=e.wrapperComponent,a=e.transformState.scale,i=e.setup,l=i.limitToBounds,c=i.centerZoomedOut,u=i.zoomAnimation,m=i.alignmentAnimation,p=u.disabled,g=u.size;if(!(s===null||!n)){var b=FI(t,a,n);if(!(!Number.isFinite(b.x)||!Number.isFinite(b.y))){var S=RS(t),x=NI(e,S),k=AS(t),j=k.x-(e.pinchLastCenterX||0),w=k.y-(e.pinchLastCenterY||0);if(!(x===a&&j===0&&w===0)){e.pinchLastCenterX=k.x,e.pinchLastCenterY=k.y;var M=ao(e,x),_=p||g===0||c,C=l&&_,D=sd(e,b.x,b.y,x,M,C),A=D.x,B=D.y;e.pinchMidpoint=b,e.lastDistance=S;var F=m.sizeX,O=m.sizeY,R=jr(e,F),I=jr(e,O),L=A+j,U=B+w,q=rl(L,U,M,l,R,I,r),H=q.x,P=q.y;e.setTransformState(x,H,P)}}}},YI=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,kS(e,t==null?void 0:t.x,t==null?void 0:t.y)},IS=function(e,t){var n=e.props.onZoomStop,s=e.setup.doubleClick.animationTime;xm(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Yt(Ut(e),t,n)},s)},VI=function(e,t){var n=e.props,s=n.onZoomStart,r=n.onZoom,a=e.setup.doubleClick,i=a.animationTime,l=a.animationType;Yt(Ut(e),t,s),MS(e,i,l,function(){return Yt(Ut(e),t,r)}),IS(e,t)};function XI(e,t){return e==="toggle"?t===1?1:-1:e==="zoomOut"?-1:1}function GI(e,t){var n=e.setup,s=e.doubleClickStopEventTimer,r=e.transformState,a=e.contentComponent,i=r.scale,l=e.props,c=l.onZoomStart,u=l.onZoom,m=n.doubleClick,p=m.disabled,g=m.mode,b=m.step,S=m.animationTime,x=m.animationType;if(!p&&!s){if(g==="reset")return VI(e,t);if(!a)return console.error("No ContentComponent found");var k=XI(g,e.transformState.scale),j=jS(e,k,b);if(i!==j){Yt(Ut(e),t,c);var w=ES(t,a,i),M=Ph(e,j,w.x,w.y);if(!M)return console.error("Error during zoom event. New transformation state was not calculated.");Yt(Ut(e),t,u),Rr(e,M,S,x),IS(e,t)}}}var JI=function(e,t){var n=e.isInitialized,s=e.setup,r=e.wrapperComponent,a=s.doubleClick,i=a.disabled,l=a.excluded,c=t.target,u=r==null?void 0:r.contains(c),m=n&&c&&u&&!i;if(!m)return!1;var p=rd(c,l);return!p},QI=function(){function e(t){var n=this;this.mounted=!0,this.pinchLastCenterX=null,this.pinchLastCenterY=null,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.isWheelPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(s){n.props=s,ao(n,n.transformState.scale),n.setup=Yg(s)},this.initializeWindowEvents=function(){var s,r,a=du(),i=(s=n.wrapperComponent)===null||s===void 0?void 0:s.ownerDocument,l=i==null?void 0:i.defaultView;(r=n.wrapperComponent)===null||r===void 0||r.addEventListener("wheel",n.onWheelPanning,a),l==null||l.addEventListener("mousedown",n.onPanningStart,a),l==null||l.addEventListener("mousemove",n.onPanning,a),l==null||l.addEventListener("mouseup",n.onPanningStop,a),i==null||i.addEventListener("mouseleave",n.clearPanning,a),l==null||l.addEventListener("keyup",n.setKeyUnPressed,a),l==null||l.addEventListener("keydown",n.setKeyPressed,a)},this.cleanupWindowEvents=function(){var s,r,a=du(),i=(s=n.wrapperComponent)===null||s===void 0?void 0:s.ownerDocument,l=i==null?void 0:i.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,a),l==null||l.removeEventListener("mousemove",n.onPanning,a),l==null||l.removeEventListener("mouseup",n.onPanningStop,a),i==null||i.removeEventListener("mouseleave",n.clearPanning,a),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,a),l==null||l.removeEventListener("keydown",n.setKeyPressed,a),document.removeEventListener("mouseleave",n.clearPanning,a),Ms(n),(r=n.observer)===null||r===void 0||r.disconnect()},this.handleInitializeWrapperEvents=function(s){var r=du();s.addEventListener("wheel",n.onWheelZoom,r),s.addEventListener("dblclick",n.onDoubleClick,r),s.addEventListener("touchstart",n.onTouchPanningStart,r),s.addEventListener("touchmove",n.onTouchPanning,r),s.addEventListener("touchend",n.onTouchPanningStop,r)},this.handleInitialize=function(s,r){var a=!1,i=n.setup.centerOnInit,l=function(c,u){for(var m=0,p=c;m<p.length;m++){var g=p[m];if(g.target===u)return!0}return!1};n.applyTransformation(),n.onInitCallbacks.forEach(function(c){c(Ut(n))}),n.observer=new ResizeObserver(function(c){if(l(c,s)||l(c,r))if(i&&!a){var u=r.offsetWidth,m=r.offsetHeight;(u>0||m>0)&&(a=!0,n.setCenter())}else Ms(n),ao(n,n.transformState.scale),Mh(n,0)}),n.observer.observe(s),n.observer.observe(r)},this.onWheelZoom=function(s){var r=n.setup.disabled;if(!r){var a=RI(n,s);if(a){var i=n.isPressingKeys(n.setup.wheel.activationKeys);i&&(WI(n,s),qI(n,s),UI(n,s))}}},this.onWheelPanning=function(s){var r=n.setup,a=r.disabled,i=r.wheel,l=r.panning;if(!(!n.wrapperComponent||!n.contentComponent||a||!i.wheelDisabled||l.disabled||!l.wheelPanning||s.ctrlKey)){s.preventDefault(),s.stopPropagation();var c=n.transformState,u=c.positionX,m=c.positionY,p=u-s.deltaX,g=m-s.deltaY,b=l.lockAxisX?u:p,S=l.lockAxisY?m:g,x=n.setup.alignmentAnimation,k=x.sizeX,j=x.sizeY,w=jr(n,k),M=jr(n,j);b===u&&S===m||_S(n,b,S,w,M)}},this.onPanningStart=function(s){var r=n.setup.disabled,a=n.props.onPanningStart;if(!r){var i=Bg(n,s);if(i){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(s.button===0&&!n.setup.panning.allowLeftClickPan||s.button===1&&!n.setup.panning.allowMiddleClickPan||s.button===2&&!n.setup.panning.allowRightClickPan||(s.preventDefault(),s.stopPropagation(),Ms(n),Ug(n,s),Yt(Ut(n),s,a)))}}},this.onPanning=function(s){var r=n.setup.disabled,a=n.props.onPanning;if(!r){var i=Wg(n);if(i){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(s.preventDefault(),s.stopPropagation(),Hg(n,s.clientX,s.clientY),Yt(Ut(n),s,a))}}},this.onPanningStop=function(s){var r=n.props.onPanningStop;n.isPanning&&(xI(n),Yt(Ut(n),s,r))},this.onPinchStart=function(s){var r=n.setup.disabled,a=n.props,i=a.onPinchingStart,l=a.onZoomStart;if(!r){var c=DI(n,s);c&&(HI(n,s),Ms(n),Yt(Ut(n),s,i),Yt(Ut(n),s,l))}},this.onPinch=function(s){var r=n.setup.disabled,a=n.props,i=a.onPinching,l=a.onZoom;if(!r){var c=LI(n);c&&(s.preventDefault(),s.stopPropagation(),KI(n,s),Yt(Ut(n),s,i),Yt(Ut(n),s,l))}},this.onPinchStop=function(s){var r=n.props,a=r.onPinchingStop,i=r.onZoomStop;n.pinchStartScale&&(YI(n),Yt(Ut(n),s,a),Yt(Ut(n),s,i))},this.onTouchPanningStart=function(s){var r=n.setup.disabled,a=n.props.onPanningStart;if(!r){var i=Bg(n,s);if(i){var l=n.lastTouch&&+new Date-n.lastTouch<200&&s.touches.length===1;if(!l){n.lastTouch=+new Date,Ms(n);var c=s.touches,u=c.length===1,m=c.length===2;u&&(Ms(n),Ug(n,s),Yt(Ut(n),s,a)),m&&n.onPinchStart(s)}}}},this.onTouchPanning=function(s){var r=n.setup.disabled,a=n.props.onPanning;if(n.isPanning&&s.touches.length===1){if(r)return;var i=Wg(n);if(!i)return;s.preventDefault(),s.stopPropagation();var l=s.touches[0];Hg(n,l.clientX,l.clientY),Yt(Ut(n),s,a)}else s.touches.length>1&&n.onPinch(s)},this.onTouchPanningStop=function(s){n.onPanningStop(s),n.onPinchStop(s)},this.onDoubleClick=function(s){var r=n.setup.disabled;if(!r){var a=JI(n,s);a&&GI(n,s)}},this.clearPanning=function(s){n.isPanning&&n.onPanningStop(s)},this.setKeyPressed=function(s){n.pressedKeys[s.key]=!0},this.setKeyUnPressed=function(s){n.pressedKeys[s.key]=!1},this.isPressingKeys=function(s){return s.length?!!s.find(function(r){return n.pressedKeys[r]}):!0},this.setTransformState=function(s,r,a){var i=n.props.onTransformed;if(!Number.isNaN(s)&&!Number.isNaN(r)&&!Number.isNaN(a)){s!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=s),n.transformState.positionX=r,n.transformState.positionY=a,n.applyTransformation();var l=Ut(n);n.onChangeCallbacks.forEach(function(c){return c(l)}),Yt(l,{scale:s,positionX:r,positionY:a},i)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var s=PS(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(s.scale,s.positionX,s.positionY)}},this.handleTransformStyles=function(s,r,a){return n.props.customTransform?n.props.customTransform(s,r,a):PI(s,r,a)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var s=n.transformState,r=s.scale,a=s.positionX,i=s.positionY,l=n.handleTransformStyles(a,i,r);n.contentComponent.style.transform=l}},this.getContext=function(){return Ut(n)},this.onChange=function(s){return n.onChangeCallbacks.has(s)||n.onChangeCallbacks.add(s),function(){n.onChangeCallbacks.delete(s)}},this.onInit=function(s){return n.onInitCallbacks.has(s)||n.onInitCallbacks.add(s),function(){n.onInitCallbacks.delete(s)}},this.init=function(s,r){n.cleanupWindowEvents(),n.wrapperComponent=s,n.contentComponent=r,ao(n,n.transformState.scale),n.handleInitializeWrapperEvents(s),n.handleInitialize(s,r),n.initializeWindowEvents(),n.isInitialized=!0;var a=Ut(n);Yt(a,void 0,n.props.onInit)},this.props=t,this.setup=Yg(this.props),this.transformState=TS(this.props)}return e}(),Eh=pn.createContext(null),ZI=function(e,t){return typeof e=="function"?e(t):e},eO=pn.forwardRef(function(e,t){var n=f.useRef(new QI(e)).current,s=ZI(e.children,bm(n));return f.useImperativeHandle(t,function(){return bm(n)},[n]),f.useEffect(function(){n.update(e)},[n,e]),pn.createElement(Eh.Provider,{value:n},s)});pn.forwardRef(function(e,t){var n=f.useRef(null),s=f.useContext(Eh);return f.useEffect(function(){return s.onChange(function(r){if(n.current){var a=0,i=0;n.current.style.transform=s.handleTransformStyles(a,i,1/r.instance.transformState.scale)}})},[s]),pn.createElement("div",kr({},e,{ref:EI([n,t])}))});function tO(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(typeof document>"u")){var s=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",n==="top"&&s.firstChild?s.insertBefore(r,s.firstChild):s.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}var nO=`.transform-component-module_wrapper__SPB86 {
185
+ position: relative;
186
+ width: -moz-fit-content;
187
+ width: fit-content;
188
+ height: -moz-fit-content;
189
+ height: fit-content;
190
+ overflow: hidden;
191
+ -webkit-touch-callout: none; /* iOS Safari */
192
+ -webkit-user-select: none; /* Safari */
193
+ -khtml-user-select: none; /* Konqueror HTML */
194
+ -moz-user-select: none; /* Firefox */
195
+ -ms-user-select: none; /* Internet Explorer/Edge */
196
+ user-select: none;
197
+ margin: 0;
198
+ padding: 0;
199
+ transform: translate3d(0, 0, 0);
200
+ }
201
+ .transform-component-module_content__FBWxo {
202
+ display: flex;
203
+ flex-wrap: wrap;
204
+ width: -moz-fit-content;
205
+ width: fit-content;
206
+ height: -moz-fit-content;
207
+ height: fit-content;
208
+ margin: 0;
209
+ padding: 0;
210
+ transform-origin: 0% 0%;
211
+ }
212
+ .transform-component-module_content__FBWxo img {
213
+ pointer-events: none;
214
+ }
215
+ `,Vg={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};tO(nO);var sO=function(e){var t=e.children,n=e.wrapperClass,s=n===void 0?"":n,r=e.contentClass,a=r===void 0?"":r,i=e.wrapperStyle,l=e.contentStyle,c=e.wrapperProps,u=c===void 0?{}:c,m=e.contentProps,p=m===void 0?{}:m,g=f.useContext(Eh),b=g.init,S=g.cleanupWindowEvents,x=f.useRef(null),k=f.useRef(null);return f.useEffect(function(){var j=x.current,w=k.current;return j!==null&&w!==null&&b&&(b==null||b(j,w)),function(){S==null||S()}},[]),pn.createElement("div",kr({},u,{ref:x,className:"".concat(ym.wrapperClass," ").concat(Vg.wrapper," ").concat(s),style:i}),pn.createElement("div",kr({},p,{ref:k,className:"".concat(ym.contentClass," ").concat(Vg.content," ").concat(a),style:l}),t))};const OS=()=>typeof window<"u"&&!!window.__TAURI_INTERNALS__;class rO{async saveFile(t){const{content:n,filters:s,defaultPath:r}=t,{save:a}=await Bn(async()=>{const{save:u}=await import("./index-BmjFP0ha.js");return{save:u}},__vite__mapDeps([13,14]),import.meta.url),{writeFile:i,writeTextFile:l}=await Bn(async()=>{const{writeFile:u,writeTextFile:m}=await import("./index-_XI0Qq6F.js");return{writeFile:u,writeTextFile:m}},__vite__mapDeps([15,14]),import.meta.url),c=await a({filters:s.map(u=>({name:u.name,extensions:[...u.extensions]})),defaultPath:r});if(!c)throw new Error("User cancelled save operation");return typeof n=="string"?await l(c,n):await i(c,n),{filename:$S(c,r),success:!0}}}class oO{async saveFile(t){const{content:n,filters:s,defaultPath:r}=t,a=$S(r,r);if(typeof window>"u"||typeof document>"u")throw new Error("File save is unavailable in this environment");const i=lO(s,n),l=typeof n=="string"?new Blob([n],{type:`${i};charset=utf-8`}):new Blob([n],{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 aO=new rO,iO=new oO,$S=(e,t)=>e.split(/[/\\]/).pop()||t,lO=(e,t)=>{var s,r,a;switch(((a=(r=(s=e[0])==null?void 0:s.extensions)==null?void 0:r[0])==null?void 0:a.toLowerCase())||""){case"md":return"text/markdown";case"txt":return"text/plain";case"json":return"application/json";case"pdf":return"application/pdf";case"svg":return"image/svg+xml";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";default:return typeof t=="string"?"text/plain":"application/octet-stream"}},cO=()=>OS()?aO:iO;class Hs{static async saveFile(t){try{return await cO().saveFile(t)}catch(n){return{filename:"",success:!1,error:n instanceof Error?n.message:"Unknown error occurred"}}}static async saveTextFile(t,n,s){return this.saveFile({content:t,filters:n,defaultPath:s})}static async saveBinaryFile(t,n,s){return this.saveFile({content:t,filters:n,defaultPath:s})}static generateTimestampedFilename(t,n){const s=new Date().toISOString().slice(0,19).replace(/:/g,"-");return`${t}-${s}.${n}`}}jt(Hs,"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 dO=e=>{const s=new DOMParser().parseFromString(e,"image/svg+xml").querySelector("svg");return s?(s.getAttribute("xmlns")||s.setAttribute("xmlns","http://www.w3.org/2000/svg"),s.getAttribute("xmlns:xlink")||s.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink"),`<?xml version="1.0" encoding="UTF-8"?>
216
+ ${new XMLSerializer().serializeToString(s)}`):e},uO=({svg:e,height:t,isLoading:n,initialScale:s,chartKey:r,className:a,style:i,token:l,containerRef:c})=>{const{t:u}=Ae(),{message:m}=en.useApp(),[p,g]=f.useState(!1),b=f.useCallback(async()=>{var x;if(!(!e||p)){g(!0);try{const k=dO(e),j=new TextEncoder().encode(k),w=r?`mermaid-${r.slice(0,8)}`:"mermaid-graph",M=Hs.generateTimestampedFilename(w,"svg"),_=await Hs.saveBinaryFile(j,Hs.FILTERS.SVG,M);if(_.success){m.success(u("chat.messageActions.savedFile",{filename:_.filename}));return}if((x=_.error)!=null&&x.toLowerCase().includes("cancel"))return;m.error(_.error||u("chat.messageActions.exportFailed"))}catch(k){const j=k instanceof Error?k.message:u("components.mermaid.exportFailed");m.error(j)}finally{g(!1)}}},[m,r,p,e,u]),S=n||!e||p;return o.jsxs("div",{ref:c,"data-mermaid-loading":n?"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:[n&&o.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")}),o.jsx("div",{style:{width:"100%",height:"100%",opacity:n?0:1,position:"relative"},children:o.jsx(eO,{initialScale:s,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:x,zoomOut:k,resetTransform:j})=>o.jsxs(o.Fragment,{children:[o.jsxs("div",{"data-mermaid-controls":"true",style:{position:"absolute",top:8,right:8,zIndex:10,display:"flex",flexDirection:"column",gap:4,background:l.colorBgContainer,borderRadius:l.borderRadiusSM,border:`1px solid ${l.colorBorder}`,padding:4,boxShadow:l.boxShadowSecondary},children:[o.jsx(de,{size:"small",type:"text",onClick:()=>x(),style:{fontSize:12,padding:"2px 6px"},children:"+"}),o.jsx(de,{size:"small",type:"text",onClick:()=>k(),style:{fontSize:12,padding:"2px 6px"},children:"-"}),o.jsx(de,{size:"small",type:"text",onClick:()=>j(),style:{fontSize:10,padding:"2px 6px"},children:"⌂"}),o.jsx(bt,{title:u("components.mermaid.exportSvg"),children:o.jsx(de,{size:"small",type:"text",icon:o.jsx(Wo,{}),"aria-label":"Download chart",disabled:S,loading:p,onClick:()=>{b()},style:{fontSize:11,padding:"2px 6px"}})})]}),o.jsx(sO,{wrapperStyle:{width:"100%",height:"100%"},contentStyle:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%"},children:o.jsx("div",{style:{display:"inline-block",lineHeight:0},dangerouslySetInnerHTML:{__html:e.replace(/<svg([^>]*)>/,'<svg$1 style="display: block; max-width: 100%; max-height: 100%;">')}})})]})})})]})};function mO(e){let t=2166136261;for(let n=0;n<e.length;n++)t=(t^e.charCodeAt(n))*16777619;return(t>>>0).toString(36)}const hO=(e,t)=>{const n=f.useMemo(()=>YP(e),[e]),s=f.useMemo(()=>mO(n),[n]),[r,a]=f.useState(()=>{const i=uc(s);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 f.useEffect(()=>{const i=uc(s);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})},[s]),f.useEffect(()=>{if(uc(s))return;let l=!1;return a(c=>({...c,isLoading:!0})),QP(s,n).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(m=>({...m,error:u||"Failed to render Mermaid diagram",isLoading:!1}))}}),()=>{l=!0}},[s,n,t]),{renderState:r,chartKey:s}},{useToken:fO}=Qe,Dc=pn.memo(({chart:e,id:t,className:n,style:s,onFix:r})=>{const{token:a}=fO(),i=Zc(),[l,c]=f.useState(!1),[u,m]=f.useState(""),p=f.useRef(null),{renderState:g,chartKey:b}=hO(e,!0),{svg:S,height:x,svgWidth:k,error:j,isLoading:w}=g,_=(()=>{const D=i.defaultScale;return k>1200?D*.8:k>800?D*1:D*1.2})(),C=async()=>{if(!(!r||l)){c(!0),m("");try{await r(e,j)}catch(D){const A=D instanceof Error?D.message:String(D);m(A||"Failed to fix Mermaid diagram")}finally{c(!1)}}};return j?o.jsx(UA,{error:j,className:n,style:s,token:a,onFix:r?C:void 0,isFixing:l,fixError:u}):o.jsx(uO,{svg:S,height:x,isLoading:w,initialScale:_,chartKey:b,className:n,style:s,token:a,containerRef:p})});Dc.displayName="MermaidChart";const pO=Object.freeze(Object.defineProperty({__proto__:null,MermaidChart:Dc,default:Dc},Symbol.toStringTag,{value:"Module"}));gn.registerLanguage("javascript",pb);gn.registerLanguage("js",pb);gn.registerLanguage("typescript",gb);gn.registerLanguage("ts",gb);gn.registerLanguage("python",yb);gn.registerLanguage("py",yb);gn.registerLanguage("json",Nw);gn.registerLanguage("bash",Cm);gn.registerLanguage("shell",Cm);gn.registerLanguage("sh",Cm);gn.registerLanguage("css",zw);gn.registerLanguage("html",bb);gn.registerLanguage("xml",bb);gn.registerLanguage("sql",Bw);gn.registerLanguage("yaml",xb);gn.registerLanguage("yml",xb);gn.registerLanguage("markdown",vb);gn.registerLanguage("md",vb);const gO=()=>mo,yO=["javascript","js","typescript","ts","python","py","json","bash","shell","sh","css","html","xml","sql","yaml","yml","markdown","md"],bO=({language:e,codeString:t,token:n})=>{const{t:s}=Ae(),{message:r}=en.useApp(),[a,i]=f.useState(!1),l=async()=>{try{await Ss(t),r.success(s("components.markdown.codeCopiedSuccess"))}catch(m){console.error("Copy failed:",m),r.error(s("components.markdown.copyFailed"))}},c=e.toLowerCase(),u=yO.includes(c);return o.jsxs(Ce,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto"},onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:[o.jsx(gn,{style:gO(),language:u?c:"text",PreTag:"div",customStyle:{margin:`${n.marginXS}px 0`,borderRadius:n.borderRadiusSM,fontSize:n.fontSizeSM,maxWidth:"100%",paddingRight:"50px"},showLineNumbers:t.split(`
217
+ `).length>10,wrapLines:!0,wrapLongLines:!0,children:t}),a&&o.jsx(de,{type:"text",size:"small",icon:o.jsx(vs,{}),onClick:l,"aria-label":"Copy code",style:{position:"absolute",top:n.paddingSM,right:n.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:n.borderRadiusSM,opacity:.8,transition:"opacity 0.2s",zIndex:10},onMouseEnter:m=>{const p=m.currentTarget;p.style.opacity="1"},onMouseLeave:m=>{const p=m.currentTarget;p.style.opacity="0.8"}})]})},xO=({codeString:e,token:t})=>{const{t:n}=Ae(),{message:s}=en.useApp();return o.jsxs(Ce,{size:"small",styles:{body:{padding:0}},style:{position:"relative",margin:`${t.marginXS}px 0`},onMouseEnter:r=>{const a=r.currentTarget.querySelector(".fallback-copy-btn");a&&(a.style.display="block")},onMouseLeave:r=>{const a=r.currentTarget.querySelector(".fallback-copy-btn");a&&(a.style.display="none")},children:[o.jsx("pre",{style:{backgroundColor:t.colorBgContainer,border:`1px solid ${t.colorBorder}`,padding:t.padding,borderRadius:t.borderRadiusSM,overflow:"auto",fontSize:t.fontSizeSM,paddingRight:"50px",margin:0},children:o.jsx("code",{style:{color:t.colorText},children:e})}),o.jsx(de,{type:"text",size:"small",icon:o.jsx(vs,{}),"aria-label":"Copy code",className:"fallback-copy-btn",onClick:async()=>{try{await Ss(e),s.success(n("components.markdown.codeCopiedSuccess"))}catch(r){console.error("Copy failed:",r),s.error(n("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}})]})},vO={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"},DS=/^(\s*%%\{[\s\S]*?\}%%\s*)+/,SO=/^(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,wO=e=>e.replace(DS,"").trimStart(),_O=(e,t)=>{const n=e.match(DS);if(!n)return`${t}
218
+ ${e}`.trim();const s=n[0].trimEnd(),r=e.slice(n[0].length).trimStart();return r?`${s}
219
+ ${t}
220
+ ${r}`:`${s}
221
+ ${t}`},kO=(e,t)=>{const n=vO[e];if(!n)return null;const s=t.trim();if(!s)return"";if(e==="mermaid")return s;const r=wO(s);return SO.test(r)?s:_O(s,n)},LS=(e,t,n,s,r="lazy")=>{try{if(!t||typeof t!="string")return console.warn("Invalid codeString provided to renderCodeBlock:",t),null;const a=e.toLowerCase().trim(),i=kO(a,t);if(i!==null){const l=i.trim();return l?r==="eager"?o.jsx(Dc,{chart:l,onFix:s}):o.jsx(qA,{chart:l,onFix:s}):(console.warn("Empty Mermaid chart content"),null)}return o.jsx(bO,{language:a,codeString:t,token:n})}catch(a){return console.warn("Syntax highlighting failed:",a),o.jsx(xO,{codeString:t,token:n})}},Xg=(e,t)=>{if(typeof window>"u")return;const n=window.open(e,"_blank","noopener,noreferrer");if(n){n.opener=null;return}((t==null?void 0:t.allowLocationFallback)??!0)&&window.location.assign(e)},FS=async e=>{const t=e.trim();if(!t)return;if(OS()){const s=window.__TAURI_INTERNALS__,r=s==null?void 0:s.invoke;if(typeof r=="function")try{await r("plugin:shell|open",{path:t});return}catch(a){console.warn("[openExternalLink] Failed to open via Tauri shell plugin, falling back to browser open.",a)}Xg(t,{allowLocationFallback:!1});return}Xg(t)},{Text:Gg}=Ke,NS=(e,t)=>({p:({children:n})=>o.jsx(Gg,{style:{marginBottom:e.marginSM,display:"block"},children:n}),ol:({children:n})=>o.jsx("ol",{style:{marginBottom:e.marginSM,paddingLeft:20},children:n}),ul:({children:n})=>o.jsx("ul",{style:{marginBottom:e.marginSM,paddingLeft:20},children:n}),li:({children:n})=>o.jsx("li",{style:{marginBottom:e.marginXS},children:n}),code({className:n,children:s,inline:r,...a}){const i=/language-([^\s]+)/i.exec(n||""),l=i?i[1]:"",c=r??(!i&&!n),u=s?String(s).replace(/\n$/,""):"";return c?o.jsx(Gg,{code:!0,className:n,...a,children:s}):u.trim()?LS(l,u,e,t==null?void 0:t.onFixMermaid,t==null?void 0:t.mermaidRenderMode):null},blockquote:({children:n})=>o.jsx(Ce,{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:n}),a:({children:n,href:s})=>{const r=typeof s=="string"?s.trim():"";return r?o.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",onClick:a=>{a.preventDefault(),a.stopPropagation(),FS(r)},style:{color:e.colorLink,textDecoration:"underline",overflowWrap:"anywhere"},children:n}):o.jsx(o.Fragment,{children:n})},table:({children:n})=>o.jsx(Ce,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${e.marginSM}px 0`},children:o.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${e.colorBorder}`},children:n})}),thead:({children:n})=>o.jsx("thead",{style:{backgroundColor:e.colorFillTertiary,color:e.colorText},children:n}),tbody:({children:n})=>o.jsx("tbody",{children:n}),tr:({children:n})=>o.jsx("tr",{style:{borderBottom:`1px solid ${e.colorBorder}`},children:n}),th:({children:n})=>o.jsx("th",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,textAlign:"left",fontWeight:"bold",borderRight:`1px solid ${e.colorBorder}`},children:n}),td:({children:n})=>o.jsx("td",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,borderRight:`1px solid ${e.colorBorder}`},children:n}),input:({type:n,checked:s,disabled:r})=>n==="checkbox"?o.jsx("input",{type:"checkbox",checked:s,disabled:r,style:{marginRight:e.marginXS,accentColor:e.colorPrimary},readOnly:!0}):o.jsx("input",{type:n,checked:s,disabled:r})}),{Text:At}=Ke,Jg=e=>{if(!e)return;const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},TO=({content:e,toolName:t,status:n="success",timestamp:s,defaultCollapsed:r=!0,isLoading:a,errorMessage:i})=>{var j;const{t:l}=Ae(),{token:c}=Qe.useToken(),u=f.useMemo(()=>um(e),[e]),m=f.useMemo(()=>typeof a=="boolean"?a:u.formattedText.trim().length===0,[u.formattedText,a]),p=f.useMemo(()=>ZC(u.formattedText),[u.formattedText]),g=f.useMemo(()=>td(e),[e]),b=f.useMemo(()=>Xv(e),[e]),S=f.useMemo(()=>g?Gv(g.diff.unified):[],[g]),x=async()=>{try{const w=u.isJson?Uo(u.parsedJson):u.formattedText;await Ss(w)}catch(w){console.error("[ToolResultCard] Failed to copy result:",w)}},k=f.useMemo(()=>{const w=e?e.slice(0,50).replace(/[^a-zA-Z0-9]/g,""):"empty";return`tool-result-${t}-${w}`},[t,e]);return o.jsx(lr,{defaultActiveKey:r?[]:[k],style:{backgroundColor:c.colorBgContainer,borderColor:c.colorBorderSecondary,borderWidth:1,borderStyle:"solid",borderRadius:c.borderRadiusLG},items:[{key:k,label:o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:c.marginSM,width:"100%"},children:[o.jsx($m,{style:{color:c.colorPrimary,flexShrink:0}}),o.jsx(At,{strong:!0,style:{color:c.colorText,flexShrink:0},children:t}),o.jsx(At,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:c.fontSizeSM},children:m?l("components.toolResult.waiting"):p}),o.jsx(Ne,{color:Qv(n),style:{flexShrink:0,margin:0},children:n})]}),children:o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:c.marginSM,children:[s&&o.jsx(At,{type:"secondary",style:{fontSize:c.fontSizeSM},children:new Date(s).toLocaleString()}),i&&o.jsx(Ht,{type:"error",message:l("components.toolResult.executionFailed"),description:i,showIcon:!0}),o.jsxs("div",{style:{position:"relative"},children:[o.jsx(bt,{title:l("components.toolResult.copyResult"),children:o.jsx(de,{type:"text",size:"small",icon:o.jsx(vs,{}),"aria-label":l("components.toolResult.copyResult"),onClick:w=>{w.stopPropagation(),x()},style:{position:"absolute",top:8,right:8,zIndex:1}})}),m?o.jsx(At,{type:"secondary",children:l("components.toolResult.waitingForResult")}):b?o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:10,children:[o.jsxs(he,{wrap:!0,children:[o.jsx(Ne,{color:b.action==="rebuild"?"gold":"blue",children:l(`components.toolResult.memory.action.${b.action}`)}),o.jsx(Ne,{children:b.data.scope}),b.data.project_key?o.jsx(Ne,{children:b.data.project_key}):null,o.jsx(Ne,{color:"green",children:l("components.toolResult.memory.totalMemories",{count:b.data.total_memories})}),o.jsx(Ne,{color:b.data.stale_candidate_count>0?"orange":"default",children:l("components.toolResult.memory.staleCandidates",{count:b.data.stale_candidate_count})})]}),o.jsxs("div",{children:[o.jsx(At,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.coverage")}),o.jsxs("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:[Object.entries(b.data.by_type).map(([w,M])=>o.jsx(Ne,{children:`${w}: ${M}`},`type-${w}`)),Object.entries(b.data.by_status).map(([w,M])=>o.jsx(Ne,{color:"processing",children:`${w}: ${M}`},`status-${w}`))]})]}),o.jsx(zn,{style:{margin:`${c.marginXS}px 0`}}),o.jsxs("div",{style:{display:"grid",gap:c.marginXS},children:[o.jsxs(At,{style:{fontSize:c.fontSizeSM},children:[o.jsx(At,{strong:!0,children:l("components.toolResult.memory.viewsLabel")})," ",b.data.view_files.length]}),o.jsxs(At,{style:{fontSize:c.fontSizeSM},children:[o.jsx(At,{strong:!0,children:l("components.toolResult.memory.indexesLabel")})," ",b.data.index_files.length]}),o.jsxs(At,{style:{fontSize:c.fontSizeSM},children:[o.jsx(At,{strong:!0,children:l("components.toolResult.memory.stateFilesLabel")})," ",b.data.state_files.length]}),b.data.last_reindex_at?o.jsxs(At,{style:{fontSize:c.fontSizeSM},children:[o.jsx(At,{strong:!0,children:l("components.toolResult.memory.lastReindexLabel")})," ",Jg(b.data.last_reindex_at)]}):null,b.data.last_dream_at?o.jsxs(At,{style:{fontSize:c.fontSizeSM},children:[o.jsx(At,{strong:!0,children:l("components.toolResult.memory.lastDreamLabel")})," ",Jg(b.data.last_dream_at)]}):null]}),b.data.view_files.length>0?o.jsxs("div",{children:[o.jsx(At,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.viewFiles")}),o.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:b.data.view_files.map(w=>o.jsx(Ne,{children:w},`view-${w}`))})]}):null,b.data.index_files.length>0?o.jsxs("div",{children:[o.jsx(At,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.indexFiles")}),o.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:b.data.index_files.map(w=>o.jsx(Ne,{children:w},`index-${w}`))})]}):null,b.data.state_files.length>0?o.jsxs("div",{children:[o.jsx(At,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.stateFiles")}),o.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:b.data.state_files.map(w=>o.jsx(Ne,{children:w},`state-${w}`))})]}):null,b.data.topic_paths.length>0?o.jsxs("div",{children:[o.jsx(At,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.topicPaths")}),o.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:b.data.topic_paths.map(w=>o.jsx(Ne,{children:w},`topic-${w}`))})]}):null,b.data.recent_ids.length>0?o.jsxs("div",{children:[o.jsx(At,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.recentMemories")}),o.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:b.data.recent_ids.map(w=>o.jsx(Ne,{color:"default",children:w},`recent-${w}`))})]}):null]}):g?o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:8,children:[g.message&&o.jsx(At,{style:{fontSize:c.fontSizeSM},children:g.message}),o.jsxs(At,{style:{fontSize:c.fontSizeSM},children:[o.jsxs(At,{strong:!0,children:[l("common.file"),":"]})," ",o.jsx(At,{code:!0,children:g.file_path})]}),g.workspace&&o.jsxs(At,{style:{fontSize:c.fontSizeSM},children:[o.jsxs(At,{strong:!0,children:[l("common.workspace"),":"]})," ",o.jsx(At,{code:!0,children:g.workspace})]}),(j=g.checkpoint)!=null&&j.created?o.jsxs(At,{style:{fontSize:c.fontSizeSM},children:[o.jsxs(At,{strong:!0,children:[l("components.toolResult.checkpoint"),":"]})," ",o.jsx(At,{code:!0,children:g.checkpoint.path})]}):o.jsx(At,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("components.toolResult.checkpointNone")}),o.jsx("div",{style:{border:`1px solid ${c.colorBorderSecondary}`,borderRadius:c.borderRadiusSM,maxHeight:400,overflow:"auto",background:c.colorBgContainer},children:S.map((w,M)=>{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 w.kind==="add"?_.background=c.colorSuccessBg:w.kind==="remove"?_.background=c.colorErrorBg:w.kind==="modified_add"?(_.background=c.colorWarningBg,_.borderLeft=`3px solid ${c.colorSuccess}`):w.kind==="modified_remove"?(_.background=c.colorWarningBg,_.borderLeft=`3px solid ${c.colorError}`):w.kind==="hunk"?(_.background=c.colorFillSecondary,_.color=c.colorTextSecondary):w.kind==="meta"&&(_.background=c.colorFillTertiary,_.color=c.colorTextSecondary),o.jsx("pre",{style:_,children:w.text||" "},`${M}-${w.kind}`)})}),g.diff.truncated&&o.jsx(At,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("components.toolResult.diffTruncated")})]}):u.isJson?o.jsx(Bo,{language:"json",style:mo,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}):o.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:c.fontSizeSM,backgroundColor:c.colorBgContainer,padding:c.paddingSM,borderRadius:c.borderRadiusSM,margin:0,maxHeight:400,overflow:"auto"},children:u.formattedText})]})]})}]})},zS=f.memo(TO);zS.displayName="ToolResultCard";function BS(e,t){const n=Jo(e);if(n)return`MCP ${n.serverId}: ${n.toolName}`;const s=(i,l)=>{const c=typeof i=="string"?i:String(i??"");return!c||c.length<=l?c:c.substring(0,l).trimEnd()+"…"},r={file_read:i=>`Reading: ${s(i.path||i.file_path||"file",40)}`,file_write:i=>`Writing to: ${s(i.path||i.file_path||"file",35)}`,file_edit:i=>`Editing: ${s(i.path||i.file_path||"file",40)}`,bash:i=>`Executing: ${s(i.command,40)}`,grep:i=>`Searching: "${s(i.pattern,30)}"`,glob:i=>`Finding files: "${i.pattern}"`,conclusion:i=>`Presenting conclusion: "${s(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: "${s(i.query||i.pattern,30)}"`,default:()=>`Calling ${e}`};return(r[e]||r.default)(t)}const{Text:Bs}=Ke,jO=e=>e==null?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`,CO=({open:e,onClose:t,call:n,metadata:s,initialTab:r="preview",result:a})=>{var w,M;const{t:i}=Ae(),{token:l}=Qe.useToken(),c=f.useMemo(()=>Jo(n.toolName),[n.toolName]),u=f.useMemo(()=>BS(n.toolName,n.parameters),[n.toolName,n.parameters]),m=f.useMemo(()=>Uo(n.parameters,2),[n.parameters]),p=async()=>{try{await Ss(m)}catch(_){console.error("[ToolStepDetailDrawer] Failed to copy parameters:",_)}},g=f.useMemo(()=>{const _=["path","file_path","command","pattern","query","limit"];return Object.entries(n.parameters).sort((A,B)=>{const F=_.indexOf(A[0]),O=_.indexOf(B[0]);return F!==-1&&O!==-1?F-O:F!==-1?-1:O!==-1?1:0}).slice(0,3)},[n.parameters]),b=!!((w=n.streamingOutput)!=null&&w.trim()),S=f.useMemo(()=>a?a.isError?o.jsx(Ne,{color:"error",children:"error"}):o.jsx(Ne,{color:"success",children:"finish"}):b?o.jsx(Ne,{color:"processing",children:"process"}):o.jsx(Ne,{color:"default",children:"wait"}),[a,b]),x=(s==null?void 0:s.elapsed_ms)!=null?o.jsx(Ne,{color:s.is_mutating?"orange":"green",children:jO(s.elapsed_ms)}):null,k=o.jsxs(he,{size:"small",children:[c?o.jsxs(o.Fragment,{children:[o.jsx(Ne,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:8,fontWeight:700},children:"MCP"}),o.jsx(Bs,{strong:!0,children:c.toolName}),o.jsx(Bs,{type:"secondary",style:{fontSize:l.fontSizeSM},children:o.jsx(Bs,{code:!0,style:{fontSize:l.fontSizeSM},children:c.serverId})})]}):o.jsx(Bs,{strong:!0,children:n.toolName}),S,x]}),j=[{key:"preview",label:i("components.toolSteps.preview"),children:o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:l.marginSM,children:[o.jsxs("div",{children:[o.jsx(Bs,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolSteps.intent")}),o.jsx("div",{style:{marginTop:l.marginXS},children:o.jsx(Bs,{style:{fontSize:l.fontSizeSM},children:u})})]}),g.length>0&&o.jsxs("div",{children:[o.jsx(Bs,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolSteps.keyParameters")}),o.jsx("ul",{style:{margin:`${l.marginXS}px 0 0`,paddingLeft:l.paddingLG,fontSize:l.fontSizeSM},children:g.map(([_,C])=>o.jsxs("li",{children:[o.jsx(Bs,{code:!0,style:{fontSize:l.fontSizeSM},children:_}),o.jsxs(Bs,{style:{fontSize:l.fontSizeSM},children:[": ",typeof C=="string"?C:JSON.stringify(C)]})]},_))})]}),(M=n.streamingOutput)!=null&&M.trim()?o.jsxs("div",{children:[o.jsx(Bs,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolCall.liveOutput")}),o.jsx("div",{className:"lotus-code-surface",style:{marginTop:l.marginXS,borderRadius:l.borderRadiusSM,backgroundColor:l.colorBgContainer,maxHeight:360,overflow:"auto"},children:o.jsx(Bo,{language:"text",style:mo,wrapLongLines:!0,customStyle:{margin:0,backgroundColor:"transparent",fontSize:l.fontSizeSM},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:n.streamingOutput})})]}):null]})},{key:"parameters",label:i("components.toolSteps.parameters"),children:o.jsxs("div",{style:{position:"relative"},children:[o.jsx(bt,{title:i("components.toolCall.copyParameters"),children:o.jsx(de,{type:"text",size:"small",icon:o.jsx(vs,{}),"aria-label":i("components.toolCall.copyParameters"),onClick:p,style:{position:"absolute",top:0,right:0,zIndex:1}})}),o.jsx(Bo,{language:"json",style:mo,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:m})]})},{key:"result",label:i("components.toolSteps.result"),children:a?o.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:l.fontSizeSM,backgroundColor:l.colorBgContainer,padding:l.paddingSM,borderRadius:l.borderRadiusSM,margin:0,maxHeight:400,overflow:"auto"},children:a.result.result}):o.jsx(Mn,{description:i("components.toolSteps.noResult")})}];return o.jsx(Rb,{placement:"right",width:480,open:e,onClose:t,title:k,destroyOnClose:!0,children:o.jsx(Di,{defaultActiveKey:r,items:j})})},{Text:Pa}=Ke;function MO(e){var n;return!((n=e.streamingOutput)!=null&&n.trim())?{status:"wait",icon:o.jsx(As,{})}:{status:"process",icon:o.jsx(io,{spin:!0})}}function PO(e){var s;const t=e.call.toolCalls[0];return e.result?e.result.isError?{status:"error",icon:o.jsx(pc,{})}:{status:"finish",icon:o.jsx(ir,{})}:!((s=t==null?void 0:t.streamingOutput)!=null&&s.trim())?{status:"wait",icon:o.jsx(As,{})}:{status:"process",icon:o.jsx(io,{spin:!0})}}const Qg=e=>e==null?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`,EO=({toolCalls:e,metadata:t,tools:n,defaultExpanded:s=!1,hideHeader:r=!1})=>{const{t:a}=Ae(),{token:i}=Qe.useToken(),[l,c]=f.useState(s),u=f.useMemo(()=>n&&n.length>0?n.map(O=>{const R=O.call.toolCalls[0];return{key:(R==null?void 0:R.toolCallId)||"unknown",toolName:(R==null?void 0:R.toolName)||"tool",parameters:(R==null?void 0:R.parameters)||{},streamingOutput:R==null?void 0:R.streamingOutput,info:PO(O),result:O.result,metadata:t}}):(e||[]).map(O=>({key:O.toolCallId,toolName:O.toolName,parameters:O.parameters,streamingOutput:O.streamingOutput,info:MO(O),result:void 0,metadata:t})),[n,e,t]),[m,p]=f.useState(!1),[g,b]=f.useState(null),[S,x]=f.useState("preview"),k=(O,R)=>{b(O),x(R??"preview"),p(!0)},j=()=>{p(!1)},w=f.useMemo(()=>{const O=u.findIndex(R=>R.info.status!=="finish");return O===-1?u.length-1:O},[u]),M=u.some(O=>O.info.status==="error"),_=u.filter(O=>O.info.status==="finish").length,C=u.length,D=Qg(t==null?void 0:t.elapsed_ms),A=f.useMemo(()=>{const O=[a("components.toolSteps.title"),`${_}/${C}`];return D&&O.push(D),O.join(" · ")},[a,_,C,D]),B=f.useMemo(()=>u.map(O=>{var P,W,ne;const R=Jo(O.toolName),I=BS(O.toolName,O.parameters),L=I.length>60?I.substring(0,60).trimEnd()+"…":I;let U=null,q=null;if(O.info.status==="process"&&((P=O.streamingOutput)!=null&&P.trim()))U=O.streamingOutput.split(`
222
+ `).slice(-3).join(`
223
+ `),q="live";else if((O.info.status==="finish"||O.info.status==="error")&&((ne=(W=O.result)==null?void 0:W.result)!=null&&ne.result)){const K=String(O.result.result.result).trimEnd();K.length>0&&(U=K.split(`
224
+ `).slice(0,3).join(`
225
+ `),q="result")}const H=O.info.status==="process"?a("components.toolSteps.running"):(t==null?void 0:t.elapsed_ms)!=null?Qg(t.elapsed_ms):void 0;return{key:O.key,title:o.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:i.marginXS},children:R?o.jsxs(o.Fragment,{children:[o.jsx(Ne,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:6,fontWeight:700,fontSize:i.fontSizeSM-1,lineHeight:"18px"},children:"MCP"}),o.jsx(Pa,{strong:!0,style:{fontSize:i.fontSizeSM},children:R.toolName})]}):o.jsx(Pa,{strong:!0,style:{fontSize:i.fontSizeSM},children:O.toolName})}),subTitle:H?o.jsx(Pa,{type:"secondary",style:{fontSize:i.fontSizeSM-1},children:H}):void 0,description:o.jsxs("div",{style:{minWidth:0},children:[o.jsx(Pa,{ellipsis:!0,style:{fontSize:i.fontSizeSM,display:"block",maxWidth:"100%"},children:L}),o.jsx("div",{style:{marginTop:i.marginXXS,display:"flex",gap:i.marginXS,alignItems:"center"},children:o.jsx(de,{type:"link",size:"small",icon:o.jsx(Nc,{}),style:{padding:0,height:"auto",fontSize:i.fontSizeSM},"data-testid":`tool-step-details-${O.key}`,onClick:()=>k(O,"preview"),children:a("components.toolSteps.details")})}),U&&o.jsxs("div",{style:{marginTop:i.marginXS},children:[o.jsx("pre",{className:"lotus-tool-step-preview",style:{margin:0,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:i.fontSizeSM,color:i.colorTextSecondary,background:"transparent",border:"none",padding:0,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:72,overflow:"hidden"},children:U}),o.jsx(de,{type:"link",size:"small",style:{padding:0,height:"auto",fontSize:i.fontSizeSM-1},onClick:()=>k(O,q==="result"?"result":"preview"),children:q==="result"?a("components.toolSteps.viewFullResult",{defaultValue:"View full result"}):a("components.toolSteps.viewFullOutput")})]})]}),status:O.info.status,icon:O.info.icon}}),[u,i,t,a]),F=r?{background:"transparent"}:{background:"var(--lotus-tool-card-bg)",borderColor:"var(--lotus-tool-card-border)",borderWidth:1,borderStyle:"solid",borderRadius:i.borderRadiusLG,overflow:"hidden"};return o.jsxs("div",{className:"lotus-tool-steps",style:F,children:[!r&&o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:i.marginSM,padding:`${i.paddingSM}px ${i.paddingSM}px`,cursor:"pointer",userSelect:"none"},onClick:()=>c(O=>!O),"data-testid":"tool-steps-header",children:[o.jsx("span",{style:{flexShrink:0},children:l?o.jsx(Gn,{style:{color:i.colorTextSecondary,fontSize:i.fontSizeSM}}):o.jsx(Vs,{style:{color:i.colorTextSecondary,fontSize:i.fontSizeSM}})}),o.jsxs(Pa,{strong:!0,style:{fontSize:i.fontSizeSM},children:["🛠 ",A]})]}),(r||l)&&o.jsx("div",{style:{padding:r?`${i.paddingXS}px 0 0 0`:`${i.paddingXS}px ${i.paddingSM}px ${i.paddingSM}px`},children:o.jsx(Pb,{direction:"vertical",size:"small",current:w,status:M?"error":"process",items:B})}),g&&o.jsx(CO,{open:m,onClose:j,call:{toolCallId:g.key,toolName:g.toolName,parameters:g.parameters,streamingOutput:g.streamingOutput},metadata:g.metadata,initialTab:S,result:g.result})]})},Rh=f.memo(EO);Rh.displayName="ToolStepsCard";const{Text:uu}=Ke,RO=({content:e,workflowName:t,parameters:n,status:s="success",timestamp:r,onRetry:a,isLoading:i,errorMessage:l})=>{const{t:c}=Ae(),{token:u}=Qe.useToken(),[m,p]=f.useState(!1),g=f.useMemo(()=>um(e),[e]),b=f.useMemo(()=>typeof i=="boolean"?i:g.formattedText.trim().length===0,[g.formattedText,i]),S=f.useMemo(()=>JC(g.formattedText),[g.formattedText]),x=g.isJson||S,k=!x||m,j=f.useMemo(()=>QC(g.formattedText),[g.formattedText]),w=f.useMemo(()=>{if(n==null)return null;if(typeof n=="string")return um(n);try{return{isJson:!0,formattedText:JSON.stringify(n,null,2),parsedJson:n}}catch(C){return console.error("[WorkflowResultCard] Failed to stringify parameters:",C),{isJson:!1,formattedText:String(n)}}},[n]),M=async()=>{try{const C=g.isJson?Uo(g.parsedJson):g.formattedText;await Ss(C)}catch(C){console.error("[WorkflowResultCard] Failed to copy content:",C)}},_=async()=>{if(w)try{const C=w.isJson?Uo(w.parsedJson):w.formattedText;await Ss(C)}catch(C){console.error("[WorkflowResultCard] Failed to copy parameters:",C)}};return o.jsx(Ce,{size:"small",variant:"outlined",style:{borderRadius:u.borderRadiusLG,borderColor:u.colorBorderSecondary,backgroundColor:u.colorBgContainer},styles:{body:{padding:u.paddingMD}},children:o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:u.marginSM,children:[o.jsxs(ve,{align:"center",justify:"space-between",children:[o.jsxs(he,{size:u.marginXS,align:"center",children:[o.jsx(g_,{style:{color:u.colorWarning}}),o.jsx(uu,{strong:!0,children:c("components.workflowResult.userWorkflow")}),o.jsx(Ne,{color:u.colorWarning,children:t}),o.jsx(Ne,{color:Qv(s),children:s})]}),o.jsxs(he,{size:"small",children:[o.jsx(bt,{title:c(m?"components.workflowResult.collapseResult":"components.workflowResult.expandResult"),children:x&&o.jsx(de,{type:"text",size:"small",icon:m?o.jsx(y_,{}):o.jsx(b_,{}),onClick:()=>p(C=>!C)})}),o.jsx(bt,{title:c("components.workflowResult.copyResult"),children:o.jsx(de,{type:"text",size:"small",icon:o.jsx(vs,{}),onClick:M,"aria-label":c("components.workflowResult.copyContent")})}),a&&o.jsx(bt,{title:c("components.workflowResult.retryWorkflow"),children:o.jsx(de,{type:"text",size:"small",icon:o.jsx(cr,{}),onClick:a,"aria-label":c("components.workflowResult.retryWorkflow")})})]})]}),r&&o.jsx(uu,{type:"secondary",style:{fontSize:u.fontSizeSM},children:new Date(r).toLocaleString()}),o.jsx(zn,{style:{margin:`${u.marginXS}px 0`}}),l&&o.jsx(Ht,{type:"error",message:c("components.workflowResult.executionFailed"),description:l,showIcon:!0,style:{marginBottom:u.marginXS}}),o.jsx(ve,{vertical:!0,style:{width:"100%"},children:b?o.jsx(Rs,{tip:c("components.workflowResult.waitingForResult")}):g.isJson?o.jsx(Bo,{language:"json",style:mo,wrapLongLines:!0,customStyle:{margin:0,borderRadius:u.borderRadiusSM,backgroundColor:u.colorBgContainer,fontSize:u.fontSizeSM,maxHeight:k?"none":280,overflow:k?"auto":"hidden"},children:g.formattedText}):o.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:u.fontSizeSM,maxHeight:k?"none":280,overflow:k?"visible":"hidden",marginBottom:0},children:[k?g.formattedText:j.preview,!k&&j.isTruncated&&`
226
+ …`]})}),w&&o.jsxs(ve,{vertical:!0,style:{width:"100%"},children:[o.jsx(zn,{style:{margin:`${u.marginXS}px 0`},children:o.jsxs(he,{size:"small",children:[o.jsx(uu,{strong:!0,children:c("common.parameters")}),o.jsx(bt,{title:c("components.workflowResult.copyParameters"),children:o.jsx(de,{type:"text",size:"small",icon:o.jsx(vs,{}),onClick:_,"aria-label":c("components.workflowResult.copyParameters")})})]})}),w.isJson?o.jsx(Bo,{language:"json",style:mo,wrapLongLines:!0,customStyle:{margin:0,borderRadius:u.borderRadiusSM,backgroundColor:u.colorBgContainer,fontSize:u.fontSizeSM,maxHeight:220,overflow:"auto"},children:w.formattedText}):o.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:u.fontSizeSM,marginBottom:0},children:w.formattedText})]})]})})},WS=f.memo(RO);WS.displayName="WorkflowResultCard";const AO=e=>Array.isArray(e)?e.map(t=>String(t??"")):[],mc=({sessionId:e,question:t,options:n,allowCustom:s,toolCallId:r})=>JSON.stringify({sessionId:e??null,question:t??"",options:AO(n),allowCustom:s??!0,toolCallId:r??null}),{Text:mu}=Ke,IO=({sessionId:e,question:t,options:n,allowCustom:s,toolCallId:r,conclusionMarkdown:a,markdownComponents:i,markdownPlugins:l,rehypePlugins:c})=>{const{t:u}=Ae(),[m,p]=f.useState(null),g=f.useMemo(()=>mc({sessionId:e,question:t,options:n,allowCustom:s,toolCallId:r}),[e,t,n,s,r]),b=m===g;return f.useEffect(()=>{if(typeof window>"u")return;const S=x=>{var w;const j=((w=x.detail)==null?void 0:w.sessionId)??null;!e||j!==e||p(g)};return window.addEventListener(zo,S),()=>{window.removeEventListener(zo,S)}},[e,g]),o.jsxs(he,{direction:"vertical",size:"middle",style:{width:"100%"},children:[a?o.jsx(Es,{remarkPlugins:l,rehypePlugins:c,components:i,children:a}):null,o.jsxs("div",{children:[o.jsx(mu,{strong:!0,children:u("components.questionDialog.questionLabel","Question")}),o.jsx("div",{style:{marginTop:8},children:o.jsx(Es,{remarkPlugins:l,rehypePlugins:c,components:i,children:t})})]}),b?o.jsx(mu,{type:"secondary",children:u("components.questionDialog.responseSubmittedContinue","Response submitted. Continuing...")}):o.jsx(mu,{type:"secondary",children:s?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:js}=Ke,OO=e=>{var a;if(!e)return{cleanText:e,hints:[]};const t=e.split(`
227
+ `),n=[],s=[];for(const i of t){const l=i.trim(),c=l.match(/^\[User explicitly selected MCP tool:\s*(.+?)\s*\]$/);if(c){const m=c[1]??"",p=Jo(m);n.push({type:"mcp",label:m,serverId:p==null?void 0:p.serverId,toolName:p==null?void 0:p.toolName});continue}const u=l.match(/^\[User explicitly selected skill:\s*(.+?)\s*\]$/);if(u){const m=u[1]??"",p=m.match(/\(ID:\s*([^)]+)\)\s*$/i),g=(a=p==null?void 0:p[1])==null?void 0:a.trim(),b=p?m.replace(/\(ID:\s*([^)]+)\)\s*$/i,"").trim():m;n.push({type:"skill",label:b||m,skillId:g});continue}s.push(i)}return{cleanText:s.join(`
228
+ `).trimStart(),hints:n}},$O=({sessionId:e,message:t,messageText:n,isUserToolCall:s,formatUserToolCall:r,markdownComponents:a,markdownPlugins:i,rehypePlugins:l})=>{var S;const{t:c}=Ae(),u=x=>(x??"").trim().toLowerCase()==="conclusion";if(rS(t)){const x=t.result.result??"",k=t.isError?x||c("components.toolResult.executionFailed"):void 0,j=!k&&x.trim().length===0;if(t.result.display_preference==="Hidden")return null;const w=(t.toolName??"").trim().toLowerCase(),M=w==="conclusion",_=VC(x),C=(w==="conclusion_with_options"||w==="exitplanmode"||w==="request_permissions")&&!t.isError&&_,D=w==="conclusion"?Vv(x):null;return C&&_?o.jsx(IO,{sessionId:e,question:_.question,options:_.options,allowCustom:_.allow_custom,toolCallId:t.toolCallId,conclusionMarkdown:XC(_.conclusion),markdownComponents:a,markdownPlugins:i,rehypePlugins:l}):D?o.jsx(he,{direction:"vertical",style:{width:"100%"},size:"small",children:o.jsx(Es,{remarkPlugins:i,rehypePlugins:l,components:a,children:D})}):o.jsx(zS,{content:x,toolName:t.toolName,status:t.isError?"error":j?"warning":"success",timestamp:t.createdAt,defaultCollapsed:!M,isLoading:j,errorMessage:k})}if(rE(t)){const x=t.content??"",k=t.status==="error"?x||c("components.workflowResult.executionFailed"):void 0,j=!k&&x.trim().length===0;return o.jsx(WS,{content:x,workflowName:t.workflowName,parameters:t.parameters,status:j?"warning":t.status??"success",timestamp:t.createdAt,isLoading:j,errorMessage:k})}if(sE(t)){const x=t.toolCalls.filter(k=>!u(k.toolName));return x.length===0?null:o.jsx(Rh,{toolCalls:x,metadata:t.metadata,defaultExpanded:!1})}if(t.isAuthError)return o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:"middle",children:[o.jsx(Ht,{message:c("chat.messageCard.authRequired"),description:o.jsx(Es,{remarkPlugins:i,rehypePlugins:l,components:a,children:n}),type:"error",showIcon:!0}),o.jsx(de,{type:"primary",icon:o.jsx(Ki,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:m,hints:p}=t.role==="user"?OO(n):{cleanText:n,hints:[]},g=t.role==="assistant"&&"type"in t&&t.type==="text"&&"metadata"in t&&typeof((S=t.metadata)==null?void 0:S.reasoning)=="string"?t.metadata.reasoning:"",b=g.trim().length>0;return t.role==="assistant"&&!n&&!b?o.jsx(js,{italic:!0,children:c("chat.messageCard.assistantThinking")}):o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:"small",children:[b?o.jsx(lr,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:o.jsx(js,{strong:!0,children:c("chat.messageCard.reasoning")}),children:o.jsx(Es,{remarkPlugins:i,rehypePlugins:l,components:a,children:g})}]}):null,p.map((x,k)=>x.type==="mcp"?o.jsx(Ht,{type:"info",showIcon:!1,message:o.jsxs(he,{wrap:!0,size:"small",children:[o.jsx(Ne,{color:"purple",children:"MCP"}),o.jsx(js,{strong:!0,children:c("chat.messageCard.selectedTool")}),x.serverId&&o.jsx(js,{type:"secondary",children:o.jsx(js,{code:!0,children:x.serverId})}),x.toolName&&o.jsx(js,{type:"secondary",children:o.jsx(js,{code:!0,children:x.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${k}`):o.jsx(Ht,{type:"success",showIcon:!1,message:o.jsxs(he,{wrap:!0,size:"small",children:[o.jsx(Ne,{color:"success",children:"Skill"}),o.jsx(js,{strong:!0,children:c("chat.messageCard.selected")}),x.label&&o.jsx(js,{children:x.label}),x.skillId&&o.jsx(js,{type:"secondary",children:o.jsx(js,{code:!0,children:x.skillId})})]}),style:{marginBottom:0}},`hint-skill-${k}`)),m?o.jsx(Es,{remarkPlugins:i,rehypePlugins:l,components:a,children:s?r(m):m}):null]})},DO=f.memo($O),{Text:hu}=Ke,LO=({role:e,formattedTimestamp:t,token:n})=>{const s=e==="user",r=e==="assistant",a=s?"You":r?"Bodhi":e,i=s?"Y":r?"B":e.slice(0,1).toUpperCase();return o.jsxs(ve,{align:"center",justify:"space-between",gap:n.marginXS,style:{marginBottom:n.marginXS},children:[o.jsxs(ve,{align:"center",gap:10,children:[o.jsx("div",{style:{width:30,height:30,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:700,letterSpacing:"0.3px",background:s?"var(--lotus-avatar-user-bg)":r?"var(--lotus-avatar-assistant-bg)":"var(--lotus-avatar-system-bg)",color:"white",boxShadow:s?"var(--lotus-avatar-user-shadow)":r?"var(--lotus-avatar-assistant-shadow)":"var(--lotus-avatar-system-shadow)",border:"var(--lotus-avatar-border)"},children:i}),o.jsxs(ve,{vertical:!0,gap:0,children:[o.jsx(hu,{strong:!0,style:{fontSize:13,color:s?"var(--lotus-primary)":n.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:a}),o.jsx(hu,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:s?"Prompt":r?"Assistant":"System"})]})]}),t&&o.jsx(hu,{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})]})},Ah=e=>{if(e.includes("```json")){const t=e.indexOf("```json")+7,n=e.indexOf("```",t);if(n>t)return e.substring(t,n).trim()}else if(e.includes("{")){const t=e.indexOf("{"),n=e.lastIndexOf("}");if(n>t)return e.substring(t,n+1).trim()}return null},FO=e=>e==="text"||e==="plan"||e==="question"||e==="tool_call"||e==="tool_result",NO=(e,t)=>{if(t)return t;if("message_type"in e&&e.message_type){const n=e.message_type;if(FO(n))return n}if(e.role==="assistant"&&e.type==="text"){const n=typeof e.content=="string"?e.content:"";try{const s=Ah(n);if(s){const r=JSON.parse(s);if(r.goal&&r.steps&&Array.isArray(r.steps))return"plan";if(r.type==="question"&&r.question)return"question"}}catch{return"text"}}return"text"},zO=(e,t)=>{if(t!=="plan"||e.role!=="assistant"||e.type!=="text")return null;const n=e.content??"";try{const s=Ah(n);if(s){const r=JSON.parse(s);if(r.goal&&r.steps)return{goal:r.goal,steps:r.steps.map(a=>({step_number:a.step_number||a.stepNumber||0,action:a.action||"",reason:a.reason||a.rationale||"",tools_needed:a.tools_needed||a.tools||[],estimated_time:a.estimated_time||a.estimatedTime||""})),estimated_total_time:r.estimated_total_time||r.estimatedTotalTime||"",risks:r.risks||[],prerequisites:r.prerequisites||[]}}}catch(s){console.error("Failed to parse plan:",s)}return null},BO=(e,t)=>{if(t!=="question"||e.role!=="assistant"||e.type!=="text")return null;const n=e.content??"";try{const s=Ah(n);if(s){const r=JSON.parse(s);if(r.type==="question"&&r.question)return{type:"question",question:r.question,context:r.context||"",severity:r.severity||"minor",options:r.options||[],default:r.default,allow_custom:r.allow_custom||!1}}}catch(s){console.error("Failed to parse question:",s)}return null},qS=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"?Vv(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""},WO=e=>{if(!e.startsWith("/"))return e;const t=e.split(" "),n=t[0].substring(1),s=t.slice(1).join(" ");if(n.startsWith("mcp__")){const a=n.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}: ${s}`}}return`🔧 ${n.replace(/_/g," ").replace(/\b\w/g,a=>a.toUpperCase())}: ${s}`},Zg=e=>e.map(t=>({name:t.name,extensions:[...t.extensions]})),ey=e=>e.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",qO={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"},UO='[data-mermaid-loading="true"]';class US{static async exportMessageText(t){const{format:n,content:s,sessionId:r=null,messageId:a=null,filenamePrefix:i}=t,l=i||["chat-message",r?ey(r.slice(0,8)):null,a?ey(a.slice(0,8)):null].filter(Boolean).join("-"),c=n==="markdown"?Hs.generateTimestampedFilename(l,"md"):Hs.generateTimestampedFilename(l,"pdf");if(n==="markdown"){const u=await Hs.saveTextFile(s,Zg(Hs.FILTERS.MARKDOWN),c);return u.success?{success:!0,filename:u.filename}:{success:!1,error:u.error}}try{const u=await this.generatePdfFromText(s),m=await Hs.saveBinaryFile(u,Zg(Hs.FILTERS.PDF),c);return m.success?{success:!0,filename:m.filename}:{success:!1,error:m.error}}catch(u){return{success:!1,error:u instanceof Error?u.message:bs.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(t){if(typeof document>"u")throw new Error(bs.t("chat.messageActions.pdfUnavailable"));const n=(await Bn(async()=>{const{default:b}=await import("./vendor-pdf-xt0MLWhy.js").then(S=>S.h);return{default:b}},__vite__mapDeps([16,1,2,3]),import.meta.url)).default,{jsPDF:s}=await Bn(async()=>{const{jsPDF:b}=await import("./vendor-pdf-xt0MLWhy.js").then(S=>S.j);return{jsPDF:b}},__vite__mapDeps([16,1,2,3]),import.meta.url),{createRoot:r}=await Bn(async()=>{const{createRoot:b}=await import("./main-_fs1sZGu.js").then(S=>S.c);return{createRoot:b}},__vite__mapDeps([4,1,2,3,5]),import.meta.url),{flushSync:a}=await Bn(async()=>{const{flushSync:b}=await import("./vendor-antd-BpW-8RO2.js").then(S=>S.R);return{flushSync:b}},__vite__mapDeps([3,2]),import.meta.url),i=NS(qO,{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=bs.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 m=document.createElement("style");m.textContent=`
229
+ .md-export { color: #111; }
230
+ .md-export h1 { font-size: 24px; margin: 0 0 16px; }
231
+ .md-export h2 { font-size: 18px; margin: 18px 0 12px; }
232
+ .md-export h3 { font-size: 16px; margin: 14px 0 10px; }
233
+ .md-export [data-mermaid-controls="true"] { display: none !important; }
234
+ `,u.appendChild(m);const p=document.createElement("div");p.className="md-export",u.appendChild(p),document.body.appendChild(u),document.body.appendChild(l);const g=r(p);a(()=>{g.render(pn.createElement(Es,{remarkPlugins:[Fc,Pm],rehypePlugins:[Mm],components:i},t||""))});try{await this.waitForExportRenderReady(u);const b=await this.renderCanvasWithFallback(n,u),S=new s({unit:"pt",format:"a4",orientation:"portrait"}),x=S.internal.pageSize.getWidth(),k=S.internal.pageSize.getHeight(),j=24,w=x-j*2,M=k-j*2,_=b.width/w,C=Math.max(1,Math.floor(M*_));let D=0,A=0;for(;D<b.height;){const F=this.computeSmartSliceHeight(b,D,C),O=Math.max(1,Math.min(F,b.height-D)),R=document.createElement("canvas");R.width=b.width,R.height=O;const I=R.getContext("2d");if(!I)throw new Error("PDF render failed (no canvas context)");I.fillStyle="#ffffff",I.fillRect(0,0,R.width,R.height),I.drawImage(b,0,D,b.width,O,0,0,b.width,O);const L=R.toDataURL("image/jpeg",.92),U=O/_;A>0&&S.addPage(),S.addImage(L,"JPEG",j,j,w,U),D+=O,A+=1}const B=S.output("arraybuffer");return new Uint8Array(B)}finally{g.unmount(),l.remove(),u.remove()}}static async waitForExportRenderReady(t){var r,a,i;await new Promise(l=>requestAnimationFrame(()=>requestAnimationFrame(()=>l()))),await((i=(a=(r=document.fonts)==null?void 0:r.ready)==null?void 0:a.catch)==null?void 0:i.call(a,()=>{}));const n=Date.now(),s=6e3;for(;Date.now()-n<s;){if(!t.querySelector(UO)){await new Promise(c=>requestAnimationFrame(()=>c()));return}await new Promise(c=>setTimeout(c,50))}}static async renderCanvasWithFallback(t,n){const s={backgroundColor:"#ffffff",scale:2,useCORS:!0,allowTaint:!0};try{const a=await t(n,{...s,foreignObjectRendering:!0});if(a.width&&a.height)return a}catch(a){console.warn("PDF capture with foreignObjectRendering=true failed:",a)}const r=await t(n,{...s,foreignObjectRendering:!1});if(!r.width||!r.height)throw new Error("PDF render failed (empty canvas)");return r}static computeSmartSliceHeight(t,n,s){const r=t.height-n;if(r<=s)return r;const a=n+s,i=Math.max(1,Math.floor(s*.72)),l=Math.max(8,Math.floor(s*.12)),c=Math.max(n+i,a-l),u=Math.min(t.height-1,a+l),m=this.findWhitespaceBreakY(t,a,c,u);return m===null||m<=n?s:m-n}static findWhitespaceBreakY(t,n,s,r){if(s>r||t.width<=0)return null;try{const a=t.getContext("2d",{willReadFrequently:!0});if(!a||typeof a.getImageData!="function")return null;const i=r-s+1,l=a.getImageData(0,s,t.width,i).data,c=t.width*4,u=Math.max(1,Math.floor(t.width/320)),m=245,p=16,g=.03;let b=null,S=Number.POSITIVE_INFINITY,x=Number.POSITIVE_INFINITY;for(let k=0;k<i;k+=1){let j=0,w=0;const M=k*c;for(let B=0;B<t.width;B+=u){const F=M+B*4,O=l[F+3];if(w+=1,O<=p)continue;const R=l[F],I=l[F+1],L=l[F+2];(R<m||I<m||L<m)&&(j+=1)}if(w===0)continue;const _=j/w,C=s+k,D=Math.abs(C-n);(_<S||_===S&&D<x)&&(S=_,x=D,b=C)}return b===null||S>g?null:b}catch{return null}}}const HO=({messageText:e,messageId:t,currentSessionId:n,onDelete:s,onRestoreChat:r,onRestoreFilesAndChat:a,cardRef:i})=>{const{message:l}=en.useApp(),{t:c}=Ae(),[u,m]=f.useState(""),p=f.useCallback(async j=>{try{await Ss(j)}catch(w){console.error("Failed to copy text:",w)}},[]),g=f.useCallback(j=>`> ${j.replace(/\n/g,`
235
+ > `)}`,[]),b=f.useCallback(()=>{if(!n)return;const j=g(u||e),w=new CustomEvent("reference-text",{detail:{text:j,sessionId:n}});window.dispatchEvent(w)},[g,n,e,u]),S=f.useCallback(async j=>{var _;const w=u||e;if(!w){l.warning(c("chat.messageActions.nothingToExport"));return}const M=await US.exportMessageText({format:j,content:w,sessionId:n??null,messageId:t??null});if(M.success)l.success(c("chat.messageActions.savedFile",{filename:M.filename}));else{if((_=M.error)!=null&&_.toLowerCase().includes("cancel"))return;l.error(M.error||c("chat.messageActions.exportFailed"))}},[l,n,t,e,u,c]),x=f.useCallback(j=>{j.preventDefault(),j.stopPropagation();const w=window.getSelection(),M=w?w.toString():"";M&&i.current&&w&&i.current.contains(w.anchorNode)?m(M):m("")},[i]);return{contextMenuItems:f.useMemo(()=>{const j=[...r&&a&&n&&t?[{key:"restore-chat",label:c("chat.messageActions.restoreChat"),icon:o.jsx(x_,{}),onClick:()=>{r()}},{key:"restore-chat-files",label:c("chat.messageActions.restoreFilesAndChat"),icon:o.jsx(kb,{}),onClick:()=>{a()}},{type:"divider"}]:[],{key:"copy",label:c("chat.messageActions.copy"),icon:o.jsx(vs,{}),onClick:()=>{p(u||e)}},{key:"reference",label:c("chat.actions.referenceMessage"),icon:o.jsx(Mb,{}),onClick:b},{type:"divider"},{key:"export-md",label:c("chat.messageActions.exportMarkdown"),icon:o.jsx(Wo,{}),onClick:()=>S("markdown")},{key:"export-pdf",label:c("chat.messageActions.exportPdf"),icon:o.jsx(Wo,{}),onClick:()=>S("pdf")}];return s&&t&&j.push({key:"delete",label:c("chat.messageActions.deleteMessage"),icon:o.jsx(Mr,{}),onClick:()=>s(t),danger:!0}),j},[p,S,t,e,s,r,a,b,u,n,c]),handleMouseUp:x,copyToClipboard:p,referenceMessage:b}},KO=({currentSessionId:e,updateSession:t,sendMessage:n})=>{const s=f.useCallback(async()=>{if(!e)return;const l=G.getState().chats.find(c=>c.id===e);if(l)try{t(e,{config:{...l.config,agentRole:"actor"}})}catch(c){console.error("Failed to switch to Actor role:",c)}},[e,t]),r=f.useCallback(async i=>{if(i.trim())try{await n(i.trim())}catch(l){console.error("Failed to send plan refinement:",l)}},[n]),a=f.useCallback(async i=>{if(i)try{await n(i)}catch(l){throw console.error("Failed to send answer:",l),l}},[n]);return{handleExecutePlan:s,handleRefinePlan:r,handleQuestionAnswer:a}},HS=e=>{const t=e.match(/```mermaid\s*([\s\S]*?)```/i);return t?t[1].trim():e.trim()},YO=(e,t,n)=>{const s=t.trim(),r=HS(n),a=/```mermaid\s*([\s\S]*?)```/gi;let i=!1;const l=e.replace(a,(u,m)=>i||m.trim()!==s?u:(i=!0,`\`\`\`mermaid
236
+ ${r}
237
+ \`\`\``));return i?l:e.match(a)?e.replace(a,u=>i?u:(i=!0,`\`\`\`mermaid
238
+ ${r}
239
+ \`\`\``)):null},ty="_text",Lc=e=>!!(e&&e.role==="assistant"&&"type"in e&&e.type==="text"),ny=(e,t,n)=>{var r;const s=typeof((r=t.metadata)==null?void 0:r.backendMessageId)=="string"?t.metadata.backendMessageId.trim():"";if(s)return s;if(e.endsWith(ty)){const a=e.slice(0,-ty.length);if(a&&n.some(i=>i.id===a))return a}return e},VO=(e,t)=>{const n=t.trim();if(!n)return!1;const s=e.matchAll(/```mermaid\s*([\s\S]*?)```/gi);for(const r of s)if((r[1]||"").trim()===n)return!0;return!1},XO=e=>(e instanceof Error?e.message:String(e)).toLowerCase().includes("message not found"),GO=(e,t,n,s)=>{const r=e.find(a=>a.id===t);return Lc(r)?r:e.find(a=>Lc(a)&&(a.content===n||VO(a.content,s)))},JO=(e,t)=>{const n=(t??"").trim(),s=["Original Mermaid code:","```mermaid",e.trim(),"```"];return n&&s.push("","Mermaid parser/render error:",n),s.push("","Please fix the Mermaid syntax while preserving the original meaning and labels."),s.join(`
240
+ `)},QO=async(e,t,n)=>{var l,c,u;const s=t==null?void 0:t.trim();if(!s)throw new Error("No model configured. Please select a default model in Provider Settings.");const i=((u=(c=(l=(await Av().chat.completions.create({model:s,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:JO(e,n)}],temperature:0})).choices)==null?void 0:l[0])==null?void 0:c.message)==null?void 0:u.content)??"";return HS(i)},ZO=(e,t)=>{const n=Iv(),s=Ov(),r=(s==null?void 0:s.model)??n;return f.useCallback(async(a,i)=>{const l=G.getState(),c=t??l.currentSessionId,u=l.chats.find(w=>w.id===c);if(!c||!u)throw new Error("No active chat available");const m=u.messages.find(w=>w.id===e);if(!Lc(m))throw new Error("Mermaid fix is only available for assistant text messages");const p=await QO(a,r,i);if(!p)throw new Error("AI did not return a Mermaid fix");const g=YO(m.content,a,p);if(!g)throw new Error("Unable to locate Mermaid block to update");let b=ny(e,m,u.messages);try{await Fo.patchSessionMessage(c,b,{content:g})}catch(w){if(!XO(w))throw w;await l.loadChatHistory(c,{mode:"replace",retries:2,retryDelayMs:150,waitForAssistant:!0});const _=G.getState().chats.find(D=>D.id===c);if(!_)throw w;const C=GO(_.messages,e,m.content,a);if(!C)throw w;b=ny(C.id,C,_.messages),await Fo.patchSessionMessage(c,b,{content:g})}const S=G.getState(),x=S.chats.find(w=>w.id===c);if(!x)throw new Error("No active chat available");const k=new Set([e,b]),j=x.messages.map(w=>!k.has(w.id)||!Lc(w)?w:{...w,content:g});S.updateSession(c,{messages:j})},[e,t,r])},e$=e=>e.xs?"100%":e.sm?"95%":"800px",t$=[{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:"}],n$=({messageId:e,isVisible:t,onRetryWithVariation:n})=>{const{t:s}=Ae(),[r,a]=f.useState(null),[i,l]=f.useState(!1),c=f.useCallback(()=>{a(b=>b==="like"?null:"like"),l(!1)},[]),u=f.useCallback(()=>{a(b=>{const S=b==="dislike"?null:"dislike";return l(S==="dislike"),S})},[]),m=f.useCallback(b=>{n&&n(b.prefix)},[n]),g=["lotus-msg-feedback",t?"is-visible":"",r!==null?"has-rating":""].filter(Boolean).join(" ");return o.jsxs("div",{className:g,"data-message-id":e,children:[o.jsx(bt,{title:s("feedback.helpful","Helpful"),children:o.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${r==="like"?"is-liked":""}`,onClick:c,"aria-label":s("feedback.helpful","Helpful"),children:r==="like"?o.jsx(v_,{}):o.jsx(S_,{})})}),o.jsx(bt,{title:s("feedback.notHelpful","Not helpful"),children:o.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${r==="dislike"?"is-disliked":""}`,onClick:u,"aria-label":s("feedback.notHelpful","Not helpful"),children:r==="dislike"?o.jsx(w_,{}):o.jsx(__,{})})}),i&&n&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"lotus-msg-feedback-sep"}),o.jsx("span",{className:"lotus-msg-feedback-retry",children:t$.map(b=>o.jsx(Ne,{color:b.color,bordered:!1,className:"lotus-msg-feedback-retry-tag",onClick:()=>m(b),children:s(b.labelKey,b.fallbackLabel)},b.key))})]})]})},{useToken:s$}=Qe,{useBreakpoint:r$}=zc,o$="chat-send-message",a$=({sessionId:e,message:t,onDelete:n,messageType:s})=>{const{role:r,id:a}=t,{token:i}=s$(),l=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:c}=Ae(),{message:u}=en.useApp(),m=r$(),p=G(Se=>Se.updateSession),g=G(Se=>Se.loadChatHistory),b=G(Se=>Se.refreshChats),S=f.useRef(null),[x,k]=f.useState(!1),j=G(ur(e)),w=f.useCallback(Se=>typeof window>"u"?Promise.reject(new Error("window is unavailable")):new Promise((me,ze)=>{const st={content:Se,sessionId:e,handled:!1,resolve:me,reject:ze};window.dispatchEvent(new CustomEvent(o$,{detail:st})),st.handled||ze(new Error("No chat message dispatcher available"))}),[e]),M=f.useMemo(()=>{if(!t.createdAt)return null;const Se=new Date(t.createdAt);if(Number.isNaN(Se.getTime()))return null;try{return SA(Se,"MMM d, yyyy HH:mm")}catch{return Se.toLocaleString()}},[t.createdAt]),_=f.useMemo(()=>NO(t,s),[t,s]),C=f.useMemo(()=>zO(t,_),[t,_]),D=f.useMemo(()=>BO(t,_),[t,_]),A=f.useMemo(()=>qS(t),[t]),B=ZO(a,e),F=f.useCallback(async Se=>{var me;if(!e||!a){u.warning(c("chat.messageActions.cannotRestore"));return}try{const ze=await Fo.restoreSessionState(e,{target_message_id:a,restore_files:Se});await g(e,{mode:"replace"}),await b();const st=((me=ze.file_errors)==null?void 0:me.length)??0;if(st>0){u.warning(c("chat.messageActions.restorePartial",{count:st}));return}Se?u.success(c("chat.messageActions.restoreFilesSuccess",{count:ze.messages_removed})):u.success(c("chat.messageActions.restoreSuccess",{count:ze.messages_removed}))}catch(ze){const st=ze instanceof Error?ze.message:c("chat.messageActions.restoreFailed");u.error(st)}},[u,e,g,a,b,c]),O=f.useCallback(()=>{F(!1)},[F]),R=f.useCallback(()=>{F(!0)},[F]),{contextMenuItems:I,handleMouseUp:L,copyToClipboard:U,referenceMessage:q}=HO({messageText:A,messageId:a,currentSessionId:e,onDelete:n,onRestoreChat:O,onRestoreFilesAndChat:R,cardRef:S}),H=f.useMemo(()=>r==="user"&&A.startsWith("/"),[r,A]),P=f.useMemo(()=>NS(i,{onFixMermaid:B}),[i,B]),W=f.useMemo(()=>[Fc,Pm],[]),ne=f.useMemo(()=>[Mm],[]),K=f.useMemo(()=>[MA(()=>U(A),c("chat.actions.copyMessage")),PA(q,c("chat.actions.referenceMessage"))],[A,U,q,c]),{handleExecutePlan:xe,handleRefinePlan:se,handleQuestionAnswer:fe}=KO({currentSessionId:e,updateSession:p,sendMessage:w});return _==="plan"&&C&&r==="assistant"?o.jsx(yS,{plan:C,contextId:e||"",onExecute:xe,onRefine:se,timestamp:M??void 0}):_==="question"&&D&&r==="assistant"?o.jsx(bS,{question:D,contextId:e||"",onAnswer:fe,disabled:j||!1,timestamp:M??void 0}):aE(t)?o.jsx(LA,{taskList:t.taskList}):oE(t)?(Jt("[MessageCard]","[MessageCard] Rendering FileReferenceCard for message:",t.id,"paths:",t.paths),o.jsx(ve,{justify:"flex-end",style:{width:"100%"},children:o.jsx(xS,{paths:t.paths,displayText:t.displayText,timestamp:M??void 0})})):o.jsxs(ve,{vertical:!0,onContextMenu:Se=>L(Se),style:{width:"100%"},children:[o.jsx(lo,{menu:{items:I},trigger:["contextMenu"],children:o.jsx(Ce,{"data-testid":r==="assistant"?"assistant-message":"user-message",id:a?`message-${a}`:void 0,ref:S,style:{width:"100%",minWidth:"100%",maxWidth:e$(m),margin:"0 auto",background:r==="user"?"var(--lotus-message-user-bg)":r==="assistant"?"var(--lotus-message-assistant-bg)":i.colorBgContainer,backdropFilter:l?"none":"blur(14px)",WebkitBackdropFilter:l?"none":"blur(14px)",border:r==="user"?"1px solid var(--lotus-message-user-border)":"1px solid var(--lotus-glass-border-subtle)",borderRadius:i.borderRadiusLG,boxShadow:x?"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:x?"translateY(-2px) scale(1.002)":"none",overflow:"hidden"},styles:{body:{padding:i.paddingMD}},onMouseEnter:()=>k(!0),onMouseLeave:()=>k(!1),children:o.jsxs(he,{direction:"vertical",size:i.marginXS,style:{width:"100%",maxWidth:"100%"},children:[o.jsx(LO,{role:r,formattedTimestamp:M,token:i}),t.role==="user"&&t.images&&o.jsx(kA,{images:t.images}),o.jsx(ve,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:o.jsx(DO,{sessionId:e,message:t,messageText:A,isUserToolCall:H,formatUserToolCall:WO,markdownComponents:P,markdownPlugins:W,rehypePlugins:ne})}),o.jsx(CA,{isVisible:x,position:{bottom:i.paddingXS,right:i.paddingXS},buttons:K})]})})}),r==="assistant"&&_==="text"&&a&&o.jsx(n$,{messageId:a,isVisible:x})]})},KS=f.memo(a$,(e,t)=>e.message===t.message&&e.messageType===t.messageType&&e.onDelete===t.onDelete);KS.displayName="MessageCard";const{Text:Oi}=Ke,{useToken:i$}=Qe,l$=e=>({p:({children:t})=>o.jsx(Oi,{style:{marginBottom:e.marginSM,display:"block"},children:t}),ol:({children:t})=>o.jsx("ol",{style:{marginBottom:e.marginSM,paddingLeft:20},children:t}),ul:({children:t})=>o.jsx("ul",{style:{marginBottom:e.marginSM,paddingLeft:20},children:t}),li:({children:t})=>o.jsx("li",{style:{marginBottom:e.marginXS},children:t}),code({className:t,children:n,inline:s,...r}){const a=/language-([^\s]+)/i.exec(t||""),i=a?a[1]:"",l=s??(!a&&!t),c=n?String(n).replace(/\n$/,""):"";return l?o.jsx(Oi,{code:!0,className:t,...r,children:n}):c.trim()?i.toLowerCase()==="mermaid"?o.jsx(Ce,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto",marginBottom:e.marginSM},children:o.jsx("pre",{style:{margin:0,padding:e.paddingSM,background:e.colorBgContainer,borderRadius:e.borderRadiusSM,fontSize:"13px"},children:o.jsx("code",{children:c})})}):LS(i,c,e,void 0):null},blockquote:({children:t})=>o.jsx(Ce,{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:n})=>{const s=typeof n=="string"?n.trim():"";return s?o.jsx("a",{href:s,target:"_blank",rel:"noopener noreferrer",onClick:r=>{r.preventDefault(),FS(s)},style:{color:e.colorLink,textDecoration:"underline",overflowWrap:"anywhere"},children:t}):o.jsx(o.Fragment,{children:t})},table:({children:t})=>o.jsx(Ce,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${e.marginSM}px 0`},children:o.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${e.colorBorder}`},children:t})}),thead:({children:t})=>o.jsx("thead",{style:{backgroundColor:e.colorBgContainer},children:t}),tbody:({children:t})=>o.jsx("tbody",{children:t}),tr:({children:t})=>o.jsx("tr",{style:{borderBottom:`1px solid ${e.colorBorder}`},children:t}),th:({children:t})=>o.jsx("th",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,textAlign:"left",fontWeight:"bold",borderRight:`1px solid ${e.colorBorder}`},children:t}),td:({children:t})=>o.jsx("td",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,borderRight:`1px solid ${e.colorBorder}`},children:t}),input:({type:t,checked:n,disabled:s})=>t==="checkbox"?o.jsx("input",{type:"checkbox",checked:n,disabled:s,style:{marginRight:e.marginXS,accentColor:e.colorPrimary},readOnly:!0}):o.jsx("input",{type:t,checked:n,disabled:s})}),YS=f.memo(({sessionId:e})=>{const{token:t}=i$(),n=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:s}=Ae(),r=`streaming-${e}`,a=`streaming-reasoning-${e}`,i=`streaming-status-${e}`,[l,c]=f.useState(()=>It.getLatest(r)??""),[u,m]=f.useState(()=>It.getLatest(a)??""),[p,g]=f.useState(()=>It.getLatest(i)??"");f.useEffect(()=>It.subscribeMessage(r,j=>{c(j??"")}),[r]),f.useEffect(()=>It.subscribeMessage(a,j=>{m(j??"")}),[a]),f.useEffect(()=>It.subscribeMessage(i,j=>{g(j??"")}),[i]);const b=f.useMemo(()=>{const j=p.trim().toLowerCase();if(!j)return s("chat.messageCard.assistantThinking");if(j==="context_compacting")return s("chat.messageCard.assistantCompactingContext");if(j==="context_compaction_degraded")return s("chat.messageCard.assistantCompactingContextDegraded");if(j==="context_compaction_failed")return s("chat.messageCard.assistantCompactingContextFailed");if(j==="memory_updating")return s("chat.messageCard.assistantUpdatingMemory");if(j.startsWith("tool_running:")){const M=(j.slice(13).trim()||"tool").replace(/[_-]+/g," ");return s("chat.messageCard.assistantRunningTool",{tool:M})}return s("chat.messageCard.assistantThinking")},[p,s]),S=f.useMemo(()=>[Fc,Pm],[]),x=f.useMemo(()=>[Mm],[]),k=f.useMemo(()=>l$(t),[t]);return o.jsx(Ce,{"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:n?"none":"blur(14px)",WebkitBackdropFilter:n?"none":"blur(14px)",borderRadius:t.borderRadiusLG,boxShadow:"none",position:"relative",wordWrap:"break-word",overflowWrap:"break-word"},children:o.jsxs(he,{direction:"vertical",size:t.marginXS,style:{width:"100%",maxWidth:"100%"},children:[o.jsx(ve,{align:"baseline",justify:"space-between",gap:t.marginXS,children:o.jsx(Oi,{type:"secondary",strong:!0,style:{fontSize:t.fontSizeSM},children:s("chat.streaming.assistant")})}),o.jsxs(ve,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:[u?o.jsx(lr,{size:"small",defaultActiveKey:["reasoning"],style:{marginBottom:t.marginSM,background:t.colorBgContainer,borderColor:t.colorBorderSecondary},items:[{key:"reasoning",label:o.jsx(Oi,{strong:!0,children:s("chat.messageCard.reasoning")}),children:o.jsx(Es,{remarkPlugins:S,rehypePlugins:x,components:k,children:u})}]}):null,!l||p?o.jsx(Oi,{italic:!0,className:"thinking-shimmer",children:b}):null,l?o.jsx(Es,{remarkPlugins:S,rehypePlugins:x,components:k,children:l}):null,o.jsx("span",{className:"blinking-cursor",style:{display:"inline-block",marginLeft:"0.2em",color:t.colorText}})]})]})})});YS.displayName="StreamingMessageCard";const{Text:Kl}=Ke,c$="chat-session-tool-collapse:",VS=(e,t)=>`${c$}${e}:${t}`,sy=(e,t)=>{if(typeof window>"u")return null;try{const n=window.localStorage.getItem(VS(e,t));if(!n)return null;const s=JSON.parse(n);return!s||typeof s!="object"?null:{isExpanded:"isExpanded"in s&&typeof s.isExpanded=="boolean"?s.isExpanded:!0,expandedTools:[]}}catch{return null}},d$=async(e,t,n)=>{if(typeof window>"u")return;await Wn.getInstance().saveToolSessionCollapse(e,t,n);try{window.localStorage.setItem(VS(e,t),JSON.stringify(n))}catch{}},u$="synthetic-tool-call:",m$=e=>{var n,s,r,a;const t=new Set;return(n=e.callMessageId)!=null&&n.trim()?t.add(e.callMessageId.trim()):e.call.id&&!e.call.id.includes(":")&&!e.call.id.startsWith(u$)&&t.add(e.call.id),(s=e.resultMessageId)!=null&&s.trim()?t.add(e.resultMessageId.trim()):(a=(r=e.result)==null?void 0:r.id)!=null&&a.trim()&&t.add(e.result.id.trim()),Array.from(t)},h$=e=>{const t=new Set;return e.forEach(n=>{m$(n).forEach(s=>t.add(s))}),Array.from(t)},f$=({tools:e,sessionId:t,defaultExpanded:n=!1,autoCollapseWhenStale:s=!1,onDeleteMessageIds:r})=>{const{t:a}=Ae(),{token:i}=Qe.useToken(),l=f.useMemo(()=>{var A,B,F,O;const _=e[0],C=(B=(A=_==null?void 0:_.call)==null?void 0:A.toolCalls)==null?void 0:B[0];return`${(_==null?void 0:_.callMessageId)||((F=_==null?void 0:_.call)==null?void 0:F.id)||(_==null?void 0:_.resultMessageId)||((O=_==null?void 0:_.result)==null?void 0:O.id)||"tool-message-missing"}:${(C==null?void 0:C.toolCallId)||"tool-call-missing"}`},[e]),[c,u]=f.useState(()=>{const _=sy(t,l);return _?_.isExpanded:n});f.useEffect(()=>{const _=sy(t,l);u(_?_.isExpanded:n),Wn.getInstance().loadToolSessionCollapse(t,l).then(D=>{D&&u(D.isExpanded)}).catch(()=>{})},[n,t,l]),f.useEffect(()=>{d$(t,l,{isExpanded:c,expandedTools:[]}).catch(()=>{})},[t,l,c]);const m=f.useRef(s);f.useEffect(()=>{!m.current&&s&&u(!1),m.current=s},[s]);const{completedCount:p,pendingCount:g,hasErrors:b}=f.useMemo(()=>{let _=0,C=0,D=!1;return e.forEach(A=>{A.result?(_++,A.result.isError&&(D=!0)):C++}),{completedCount:_,pendingCount:C,hasErrors:D}},[e]),S=f.useMemo(()=>g>0?{color:"processing",text:a("components.toolSession.completedProgress",{completed:p,total:e.length})}:b?{color:"warning",text:a("components.toolSession.completedWithErrors",{completed:p})}:{color:"success",text:a("components.toolSession.completedOnly",{completed:p})},[p,g,b,e.length,a]),x=f.useMemo(()=>{let _=0,C=0,D=0;return e.forEach(A=>{var O,R;const B=(R=(O=A.result)==null?void 0:O.result)==null?void 0:R.result;if(!B)return;const F=Jv(B);F&&(_+=F.added,C+=F.removed,D+=1)}),{added:_,removed:C,changedTools:D}},[e]),k=f.useMemo(()=>{const _=e.map(A=>{var O,R;const B=(R=(O=A.call)==null?void 0:O.toolCalls)==null?void 0:R[0];if(!B)return null;const F=Jo(B.toolName);return F?F.toolName:B.toolName||null}).filter(A=>!!A);if(_.length===0)return a("components.toolSession.title");if(_.length===1)return _[0];const C=_.filter((A,B)=>B===0||A!==_[B-1]),D=3;return C.length<=D?C.join(" → "):`${C.slice(0,D).join(" → ")} +${C.length-D}`},[e,a]),j=f.useMemo(()=>h$(e),[e]),w=o.jsx(Rh,{tools:e,defaultExpanded:!0,hideHeader:!0}),M={background:"transparent"};return o.jsxs("div",{style:M,children:[o.jsxs("div",{style:{padding:`${i.paddingXS}px 0`,backgroundColor:"transparent",borderBottom:"none",cursor:"pointer",display:"flex",alignItems:"center",gap:i.marginSM,transition:"border-color 240ms ease, background-color 240ms ease"},onClick:()=>u(!c),"data-testid":"tool-session-card-header",children:[o.jsx(Ui,{style:{color:i.colorPrimary}}),o.jsx(Kl,{strong:!0,style:{flex:1},children:k}),o.jsx(Am,{count:e.length,style:{backgroundColor:i.colorPrimary}}),x.changedTools>0&&o.jsxs(he,{size:4,style:{marginInlineStart:i.marginXS},children:[o.jsxs(Kl,{style:{color:i.colorSuccess,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",x.added]}),o.jsxs(Kl,{style:{color:i.colorError,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",x.removed]})]}),o.jsx(Kl,{type:"secondary",style:{fontSize:i.fontSizeSM},children:S.text}),r&&o.jsx(bt,{title:j.length>0?a("components.toolSession.deleteMessage"):a("components.toolSession.noPersistedMessage"),children:o.jsx(de,{type:"text",size:"small",danger:!0,icon:o.jsx(Mr,{}),"aria-label":a("components.toolSession.deleteMessage"),"data-testid":"delete-tool-session",disabled:j.length===0,onClick:_=>{_.preventDefault(),_.stopPropagation(),j.length!==0&&r(j)}})}),o.jsx("div",{style:{marginLeft:i.marginXS},children:c?o.jsx(Gn,{style:{color:i.colorTextSecondary}}):o.jsx(Vs,{style:{color:i.colorTextSecondary}})})]}),c&&w]})},XS=f.memo(f$);XS.displayName="ToolSessionCard";const{Content:p$}=so,{Text:ry}=Ke,g$=24,y$=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};function fu(e){return"type"in e&&(e.type==="tool_session"||e.type==="compression_divider")?e.id:e.message.id}const b$=({currentChat:e,currentSessionId:t,convertRenderableEntry:n,handleDeleteMessage:s,handleDeleteToolMessages:r,handleMessagesScroll:a,hasSystemPrompt:i,messagesListRef:l,renderableMessages:c,rowGap:u,showMessagesView:m,screens:p,workflowDraftId:g,isThinking:b,padding:S,selectionMode:x,selectedMessageIds:k,selectableMessageIds:j,onToggleMessageSelection:w})=>{const{t:M}=Ae(),_=f.useRef(c);_.current=c;const C=f.useCallback(I=>{const L=_.current[I];return L?fu(L):String(I)},[]),D=iR({count:c.length,getScrollElement:()=>l.current,estimateSize:()=>120,overscan:5,gap:u,getItemKey:C}),A=(I,L)=>{if(!x)return null;const U=j.has(I);return o.jsx(k_,{checked:k.has(I),disabled:!U,onChange:()=>{U&&w(I)},style:{marginTop:8,marginLeft:L==="flex-end"?8:0,marginRight:L==="flex-start"?8:0}})},B=(I,L)=>{const U=n(I),q=L===void 0||L===c.length-1;if(U.type==="compression_divider"){const H=y$(U.createdAt);return o.jsx("div",{role:"note","aria-label":M("chat.compression.timelineAria",{detail:U.label,time:H,defaultValue:"{{detail}} at {{time}}"}),style:{margin:"6px 0 10px 0",borderRadius:10,border:"1px solid rgba(250, 173, 20, 0.45)",background:"rgba(250, 173, 20, 0.12)",padding:p.xs?"8px 10px":"10px 12px"},children:o.jsxs(ve,{align:"center",justify:"space-between",gap:8,wrap:!0,children:[o.jsxs(ve,{align:"center",gap:8,wrap:!0,children:[o.jsx(Ne,{color:"gold",icon:o.jsx(Ab,{}),children:M("chat.compression.tag","Context compressed")}),o.jsx(ry,{strong:!0,style:{fontSize:12},children:U.label})]}),o.jsx(ry,{type:"secondary",style:{fontSize:11},children:H})]})})}return U.type==="tool_session"?o.jsx(ve,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:o.jsx("div",{id:`message-${U.id}`,style:{width:"100%",maxWidth:p.xs?"100%":"90%"},children:o.jsx(XS,{tools:U.tools,sessionId:U.sessionId,createdAt:U.createdAt,defaultExpanded:q,autoCollapseWhenStale:!q,onDeleteMessageIds:t?r:void 0})})}):U.message.role==="system"?o.jsxs(ve,{align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[A(U.message.id,"flex-start"),o.jsx("div",{style:{flex:1,minWidth:0},children:o.jsx(mS,{currentChat:e,message:U.message})})]}):o.jsxs(ve,{justify:U.align,align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[U.align==="flex-start"&&A(U.message.id,U.align),o.jsx("div",{style:{width:U.message.role==="user"?"85%":"100%",maxWidth:p.xs?"100%":"90%"},children:o.jsx(KS,{sessionId:t,message:U.message,messageType:U.messageType,onDelete:U.message.id===g?void 0:s})}),U.align==="flex-end"&&A(U.message.id,U.align)]})},F=(m||i)&&c.length>0,O=D.getVirtualItems(),R=c.length>g$;return o.jsxs(p$,{role:"log","aria-live":"polite","aria-label":"Chat messages",className:`chat-view-messages-list ${m?"visible":"hidden"}`,style:{flex:1,minHeight:0,padding:S,overflowY:"auto",opacity:m?1:0,scrollbarWidth:"none",msOverflowStyle:"none"},ref:l,onScroll:a,children:[F&&(R?o.jsx("div",{style:{position:"relative",width:"100%",height:D.getTotalSize()},children:O.map(I=>{const L=c[I.index];if(!L)return null;const U=fu(L);return o.jsx("div",{"data-chat-entry-id":U,"data-index":I.index,ref:D.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${I.start}px)`},children:o.jsx("div",{className:"messageEnter",children:B(L,I.index)})},I.key)})}):o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:u,width:"100%"},children:c.map((I,L)=>{const U=fu(I);return o.jsx("div",{"data-chat-entry-id":U,className:"messageEnter",children:B(I,L)},U)})})),b&&t&&o.jsx("div",{className:"streaming-card-enter",style:{paddingTop:u},children:o.jsx(ve,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:o.jsx("div",{style:{width:"100%",maxWidth:p.xs?"100%":"90%"},children:o.jsx(YS,{sessionId:t})})})})]})},{Text:Ro}=Ke,x$=e=>({pending:{icon:o.jsx(As,{}),color:e.colorTextTertiary,textKey:"components.todoList.status.pending",tagColor:"default"},in_progress:{icon:o.jsx(Im,{spin:!0}),color:e.colorPrimary,textKey:"components.todoList.status.inProgress",tagColor:"processing"},completed:{icon:o.jsx(ir,{}),color:e.colorSuccess,textKey:"components.todoList.status.completed",tagColor:"success"},blocked:{icon:o.jsx(Om,{}),color:e.colorError,textKey:"components.todoList.status.blocked",tagColor:"error"}}),v$=({sessionId:e,initialCollapsed:t=!0})=>{const{t:n}=Ae(),{token:s}=Qe.useToken(),r=pn.useMemo(()=>x$(s),[s]),a=G(A=>A.chats.find(B=>B.id===e)),i=(a==null?void 0:a.kind)==="child"&&(a.parentSessionId||a.rootSessionId)||e,l=G(A=>A.taskLists[i]),c=G(A=>A.activeItems[i]),u=G(A=>A.evaluationStates[i]),[m,p]=f.useState(t),[g,b]=f.useState(!1),S=(u==null?void 0:u.isEvaluating)||!1,x=(u==null?void 0:u.reasoning)||null,k=l?{session_id:l.session_id,title:l.title,items:l.items,progress:{completed:l.items.filter(A=>A.status==="completed").length,total:l.items.length,percentage:l.items.length>0?Math.round(l.items.filter(A=>A.status==="completed").length/l.items.length*100):0}}:null;if(!k)return null;const j=()=>{g||p(!m)},w=A=>{A.stopPropagation(),b(!g),g||p(!1)},{title:M,items:_,progress:C}=k,D=C.percentage===100;return o.jsx(Ce,{size:"small",style:{marginBottom:16,borderRadius:8,boxShadow:S?`0 0 0 2px ${s.colorPrimaryBorder}`:"0 2px 8px rgba(0, 0, 0, 0.06)",opacity:m&&!g?.9:1},styles:{body:{padding:m?"12px 16px":16}},title:o.jsxs(he,{onClick:j,style:{cursor:"pointer",width:"100%"},children:[o.jsx(j_,{style:{color:s.colorPrimary}}),o.jsx(Ro,{strong:!0,style:{fontSize:15},children:M||n("components.todoList.title")}),S&&o.jsx(Ne,{icon:o.jsx(Im,{spin:!0}),color:"processing",children:n("components.todoList.evaluating")}),!m&&C.total>0&&o.jsx(Am,{count:`${C.completed}/${C.total}`,style:{backgroundColor:D?s.colorSuccess:s.colorPrimary}})]}),extra:o.jsxs(he,{children:[C.total>0&&m&&o.jsxs(Ro,{type:"secondary",style:{fontSize:13},children:[C.completed,"/",C.total,D&&o.jsx(ir,{style:{color:s.colorSuccess,marginLeft:4}})]}),o.jsx(bt,{title:n(g?"components.todoList.unpin":"components.todoList.pin"),children:o.jsx("span",{onClick:w,style:{cursor:"pointer",color:g?s.colorPrimary:s.colorTextSecondary,fontSize:16},children:g?o.jsx(Eu,{}):o.jsx(Em,{})})}),!g&&o.jsx("span",{onClick:j,style:{cursor:"pointer",color:s.colorTextSecondary,fontSize:12,transform:m?"rotate(-90deg)":void 0,transition:"transform 0.2s"},children:m?o.jsx(Vs,{}):o.jsx(Gn,{})})]}),children:!m&&o.jsxs(o.Fragment,{children:[x&&o.jsx(Ht,{icon:o.jsx($m,{}),message:n("components.todoList.llmEvaluation"),description:x,type:"info",showIcon:!0,style:{marginBottom:16}}),C.total>0&&o.jsx("div",{style:{marginBottom:16},children:o.jsx(Dm,{percent:C.percentage,size:"small",status:D?"success":"active",format:A=>o.jsxs(Ro,{type:"secondary",children:[A,"%"]})})}),o.jsx(Qt,{size:"small",dataSource:_,renderItem:A=>{const B=r[A.status],F=c===A.id,O=n(B.textKey);return o.jsx(Qt.Item,{style:{padding:"12px 0",borderLeft:F?`3px solid ${s.colorPrimary}`:"3px solid transparent",paddingLeft:F?12:15,backgroundColor:F?s.colorPrimaryBg:"transparent",borderRadius:4,marginBottom:4},children:o.jsx("div",{style:{width:"100%"},children:o.jsxs(he,{align:"start",style:{width:"100%"},children:[o.jsx(bt,{title:O,children:o.jsx("span",{style:{color:B.color,fontSize:16},children:B.icon})}),o.jsxs("div",{style:{flex:1,minWidth:0},children:[o.jsx(Ro,{style:{textDecoration:A.status==="completed"?"line-through":"none",color:A.status==="completed"?s.colorTextSecondary:s.colorText,fontWeight:F?500:400},children:A.description}),o.jsx("div",{style:{marginTop:4},children:o.jsxs(he,{size:8,wrap:!0,children:[o.jsx(Ne,{color:B.tagColor,children:O}),A.tool_calls_count!==void 0&&A.tool_calls_count>0&&o.jsxs(Ne,{icon:o.jsx(Ui,{}),color:"processing",children:[A.tool_calls_count," ",n("components.todoList.tools")]}),A.depends_on.length>0&&o.jsx(bt,{title:n("components.todoList.dependsOn",{deps:A.depends_on.join(", ")}),children:o.jsxs(Ne,{icon:o.jsx(T_,{}),children:[A.depends_on.length," ",n("components.todoList.dependencies")]})})]})}),A.status==="completed"&&A.summary&&o.jsx(Ro,{type:"secondary",style:{display:"block",marginTop:6,fontSize:12,padding:"4px 8px",backgroundColor:s.colorSuccessBg,borderRadius:4,color:s.colorSuccess},children:A.summary}),A.notes&&o.jsx(Ro,{type:"secondary",style:{display:"block",marginTop:6,fontSize:12,padding:"4px 8px",backgroundColor:s.colorFillQuaternary,borderRadius:4},children:A.notes})]})]})})})}})]})})},S$="_questionCard_15meh_1",w$="_questionHeader_15meh_8",_$="_headerLeft_15meh_27",k$="_questionIcon_15meh_35",T$="_questionText_15meh_40",j$="_collapseBtn_15meh_52",C$="_questionBody_15meh_57",M$="_optionsGroup_15meh_61",P$="_optionItem_15meh_65",E$="_customHint_15meh_81",R$="_questionFooter_15meh_93",ms={questionCard:S$,questionHeader:w$,headerLeft:_$,questionIcon:k$,questionText:T$,collapseBtn:j$,questionBody:C$,optionsGroup:M$,optionItem:P$,customHint:E$,questionFooter:R$},{Text:Yl}=Ke,{useToken:A$}=Qe,I$=e=>{const t=(e||"").replace(/\\r\\n/g,`
241
+ `).replace(/\\n/g,`
242
+ `).replace(/\r\n?/g,`
243
+ `).trim();return t?t.includes(`
244
+ `)?t:t.replace(/\s+(?=\d+[).]\s)/g,`
245
+ `).replace(/\s+(?=[一二三四五六七八九十]+[、.]\s)/g,`
246
+ `).replace(/\s+(?=[-*•]\s)/g,`
247
+ `):""},O$=({sessionId:e,onResponseSubmitted:t,onQuestionAppeared:n})=>{var Wt,Xe;const{t:s}=Ae(),{token:r}=A$(),{message:a}=en.useApp(),[i,l]=f.useState(null),[c,u]=f.useState(null),[m,p]=f.useState(!1),[g,b]=f.useState(!0),[S,x]=f.useState(!1),k=f.useRef(0),j=f.useRef(0),w=f.useRef(null),M=f.useRef(n);M.current=n;const[_,C]=f.useState(()=>typeof document>"u"?!0:!document.hidden),D=G(_e=>_e.markRespondStart),A=G(_e=>_e.markSettleTimeout),B=G(_e=>_e.setPendingQuestion),F=G(_e=>_e.clearPendingQuestion),O=G(_e=>_e.chats.find(Ye=>Ye.id===e)||null),R=G(_e=>{if(!e)return null;const Ye=sx(e)(_e);return(Ye==null?void 0:Ye.interaction.pendingQuestion)??null}),I=f.useMemo(()=>R?{has_pending_question:!0,question:R.question,options:R.options,allow_custom:R.allowCustom,tool_call_id:R.toolCallId??void 0}:i,[R,i]),L=bh((Wt=O==null?void 0:O.config)==null?void 0:Wt.model_ref),U=G(_e=>{var Ye;return e?(Ye=_e.inputStates)==null?void 0:Ye[e]:void 0}),q=Ct(_e=>_e.currentProvider),H=Ct(_e=>_e.providerConfig),P=f.useMemo(()=>{var _e;return(_e=H.providers[q])==null?void 0:_e.reasoning_effort},[H,q]),W=f.useMemo(()=>e?Vm(e):void 0,[e]),ne=((Xe=O==null?void 0:O.config)==null?void 0:Xe.reasoningEffort)??(U==null?void 0:U.reasoningEffort)??W??P??"medium",K=G(ur(e)),se=G(_e=>_e.currentSessionId)===e,fe=f.useCallback(async()=>{try{const _e=await nt.get(`respond/${e}/pending`);_e.has_pending_question?(l(Ye=>{const ot=mc({sessionId:e,question:_e.question,options:_e.options,allowCustom:_e.allow_custom,toolCallId:_e.tool_call_id});return(Ye!=null&&Ye.has_pending_question?mc({sessionId:e,question:Ye.question,options:Ye.options,allowCustom:Ye.allow_custom,toolCallId:Ye.tool_call_id}):null)===ot?Ye??_e:_e}),k.current=0,j.current=0):(l(null),w.current=null,k.current+=1,k.current>=6?j.current=2:k.current>=2&&(j.current=1))}catch(_e){if(_e instanceof Error&&_e.message.includes("404")){l(null),w.current=null,k.current+=1;return}l(null),w.current=null,k.current+=1,k.current>=6?j.current=2:k.current>=2&&(j.current=1),console.error("Failed to fetch pending question:",_e)}finally{b(!1)}},[e]);f.useEffect(()=>{k.current=0,j.current=0,w.current=null,b(!0),u(null),x(!1)},[e]),f.useEffect(()=>{if(typeof document>"u")return;const _e=()=>{C(!document.hidden)};return document.addEventListener("visibilitychange",_e),()=>document.removeEventListener("visibilitychange",_e)},[]),f.useEffect(()=>{var _e;if(I!=null&&I.has_pending_question){const Ye=mc({sessionId:e,question:I==null?void 0:I.question,options:I==null?void 0:I.options,allowCustom:I==null?void 0:I.allow_custom,toolCallId:I==null?void 0:I.tool_call_id}),ot=w.current===Ye;B(e,{question:(I==null?void 0:I.question)||"",options:(I==null?void 0:I.options)||[],allowCustom:(I==null?void 0:I.allow_custom)??!0,toolCallId:(I==null?void 0:I.tool_call_id)??null}),ot||(u(null),x(!1),(_e=M.current)==null||_e.call(M)),w.current=Ye}else w.current=null,F(e)},[I==null?void 0:I.allow_custom,I==null?void 0:I.has_pending_question,I==null?void 0:I.options,I==null?void 0:I.question,I==null?void 0:I.tool_call_id,e,B,F]);const Se=f.useCallback(()=>{if(R)return null;if(I!=null&&I.has_pending_question)return _?5e3:15e3;if(K)return se?_?5e3:15e3:null;if(!se||!_)return null;const _e=j.current;return _e===0?3e4:_e===1?6e4:12e4},[R,I==null?void 0:I.has_pending_question,K,se,_]);f.useEffect(()=>{if(R){b(!1);return}let _e=!1,Ye=null;const ot=async()=>{if(_e||m||(await fe(),_e))return;const Lt=Se();Lt!==null&&(Ye=setTimeout(ot,Lt))};return ot(),()=>{_e=!0,Ye&&clearTimeout(Ye)}},[R,fe,Se,m]),f.useEffect(()=>{if(typeof window>"u")return;const _e=Ye=>{var N;const Lt=((N=Ye.detail)==null?void 0:N.sessionId)??null;!Lt||Lt!==e||(l(null),u(null),k.current=0)};return window.addEventListener(zo,_e),()=>{window.removeEventListener(zo,_e)}},[e]);const me=f.useCallback(_e=>{u(_e)},[]),ze=async()=>{if(!c||c==="custom"){a.warning(s("components.questionDialog.selectOptionWarning"));return}p(!0),D(e,(I==null?void 0:I.tool_call_id)??null),await new Promise(_e=>setTimeout(_e,0));try{const _e={};Ct.getState().isProviderModelRefEnabled()&&L&&(_e.model_ref=L,_e.provider=L.provider);const Ye=await nt.post(`respond/${e}`,{response:c,reasoning_effort:ne,..._e});a.success(s("components.questionDialog.responseSubmitted")),l(null),u(null),k.current=0,F(e),typeof window<"u"&&window.dispatchEvent(new CustomEvent(zo,{detail:{sessionId:e}}));const ot=Ye==null?void 0:Ye.auto_resume_status;ot==="error"?(console.error("[QuestionDialog] Failed to auto-resume agent execution"),A(e)):(!ot||!["started","already_running"].includes(ot))&&A(e),t==null||t()}catch(_e){console.error("Failed to submit response:",_e),a.error(_e instanceof Error?_e.message:s("components.questionDialog.submitFailed")),A(e)}finally{p(!1)}};if(g||!(I!=null&&I.has_pending_question))return null;const{question:st,options:pt,allow_custom:Kt}=I,Oe=I$(st);return o.jsxs("div",{className:ms.questionCard,style:{background:r.colorBgContainer,borderColor:r.colorBorderSecondary,border:`1px solid ${r.colorBorderSecondary}`},children:[o.jsxs("div",{className:ms.questionHeader,"data-collapsed":S?"true":"false",onClick:()=>x(_e=>!_e),role:"button",tabIndex:0,onKeyDown:_e=>{(_e.key==="Enter"||_e.key===" ")&&x(Ye=>!Ye)},children:[o.jsxs("span",{className:ms.headerLeft,children:[o.jsx("span",{className:ms.questionIcon,children:"🤔"}),o.jsx(Yl,{strong:!0,className:ms.questionText,style:{color:r.colorPrimary,whiteSpace:"pre-wrap"},title:S?Oe:void 0,children:Oe})]}),o.jsx(de,{type:"text",size:"small",icon:S?o.jsx(Gn,{}):o.jsx(Lm,{}),className:ms.collapseBtn,tabIndex:-1})]}),!S&&o.jsxs("div",{className:ms.questionBody,children:[o.jsx(xs.Group,{className:ms.optionsGroup,value:c,onChange:_e=>me(_e.target.value),children:o.jsxs(he,{direction:"vertical",size:4,style:{width:"100%"},children:[pt==null?void 0:pt.map((_e,Ye)=>o.jsx(xs,{value:_e,className:ms.optionItem,children:o.jsx(Yl,{style:{color:r.colorText},children:_e})},Ye)),Kt&&o.jsx(xs,{value:"custom",className:ms.optionItem,children:o.jsxs(he,{size:4,children:[o.jsx(Hi,{}),o.jsx(Yl,{style:{color:r.colorText},children:s("components.questionDialog.otherTypeBelow")})]})})]})}),c==="custom"&&o.jsx("div",{className:ms.customHint,children:o.jsx(Yl,{type:"secondary",style:{fontSize:12},children:s("components.questionDialog.customAnswerTip")})}),c&&c!=="custom"&&o.jsx("div",{className:ms.questionFooter,children:o.jsx(de,{type:"primary",size:"small",onClick:ze,loading:m,children:s("components.questionDialog.confirm")})})]})]})};function GS(e){return typeof e.maxContextTokens=="number"&&e.maxContextTokens>0?e.maxContextTokens:e.budgetLimit>0?e.budgetLimit:0}function JS(e){const t=GS(e);return t===0?0:e.totalTokens/t*100}function $$(e){const t=JS(e);return t>=90?"error":t>=70?"warning":t>=50?"success":"default"}function Ea(e){return e.toLocaleString()}const D$=({usage:e,showDetails:t=!0,size:n="small",className:s=""})=>{const{t:r}=Ae(),a=GS(e),i=JS(e),l=p=>{const g=Math.round(p*10)/10;return Number.isInteger(g)?g.toFixed(0):g.toFixed(1)},c=$$(e),u=()=>i>=90?"var(--lotus-chart-danger)":i>=70?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",m=o.jsxs("div",{style:{minWidth:180,color:"var(--lotus-metric-text-strong)"},children:[o.jsx("div",{style:{marginBottom:4,fontWeight:"bold"},children:r("components.tokenUsage.title")}),o.jsxs("div",{style:{fontSize:12},children:[r("components.tokenUsage.contextWindow"),":"," ",Ea(e.totalTokens)," / ",Ea(a)," ",r("components.tokenUsage.tokens")]}),o.jsx("div",{style:{fontSize:12,color:"var(--lotus-metric-text-muted)"},children:r("components.tokenUsage.usedPercent",{value:i.toFixed(1)})}),t&&o.jsxs("div",{style:{marginTop:6,borderTop:"1px solid var(--lotus-metric-tooltip-border)",paddingTop:6,fontSize:11},children:[o.jsxs("div",{children:[r("components.tokenUsage.system"),": ",Ea(e.systemTokens)]}),e.summaryTokens>0&&o.jsxs("div",{children:[r("components.tokenUsage.summary"),": ",Ea(e.summaryTokens)]}),o.jsxs("div",{children:[r("components.tokenUsage.messages"),": ",Ea(e.windowTokens)]}),typeof e.promptCachedToolOutputs=="number"&&e.promptCachedToolOutputs>0&&o.jsx("div",{style:{color:"var(--lotus-metric-text-muted)"},children:r("components.tokenUsage.cachedToolOutputs",{count:e.promptCachedToolOutputs,defaultValue:"Prompt cache: {{count}} tool outputs summarized"})})]})]});return o.jsx(bt,{title:m,placement:"top",arrow:!0,children:o.jsxs(he,{className:`token-usage-display ${s}`,size:4,align:"center",style:{lineHeight:1},children:[o.jsx(Dm,{type:"line",percent:Math.min(i,100),size:{height:n==="small"?6:8,width:80},strokeColor:u(),showInfo:!1,style:{margin:0,lineHeight:1}}),o.jsxs("span",{style:{fontSize:n==="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),"%"]})]})})},no=class no{static getInstance(){return no.instance||(no.instance=new no),no.instance}parseUserCommand(t){Jt("[ToolService]",`[ToolService] parseUserCommand: Parsing content: "${t}"`);const n=t.trim();if(!n.startsWith("/"))return Jt("[ToolService]",'[ToolService] parseUserCommand: Content does not start with "/", not a tool command.'),null;const s=n.indexOf(" ");let r,a;if(s===-1?(r=n.substring(1),a=""):(r=n.substring(1,s),a=n.substring(s+1).trim()),r){const i={tool_name:r,user_description:a};return Jt("[ToolService]","[ToolService] parseUserCommand: Successfully parsed command:",i),i}return Jt("[ToolService]","[ToolService] parseUserCommand: Failed to parse tool name from content."),null}parseAIResponseToToolCall(t){return this.parseUserCommand(t)}async executeTool(t){Jt("[ToolService]","[ToolService] executeTool: Attempting to execute tool via HTTP with request:",t);try{const n=await at.post("tools/execute",t),s=JSON.parse(n.result);return Jt("[ToolService]","[ToolService] executeTool: Parsed structured result:",s),s}catch(n){throw console.error("[ToolService] executeTool: HTTP tool execution failed:",n),n instanceof uo?new Error(`Workflow execution failed: ${n.message}`):n}}};jt(no,"instance");let vm=no;const pu=new vm;class L${async listProfiles(){return at.get("subagent_profiles")}}const F$=new L$,N$=[];function z$(e={}){const{enabled:t=!0,refreshKey:n}=e,[s,r]=f.useState(null),[a,i]=f.useState(!1),[l,c]=f.useState(null),u=f.useCallback(async()=>{i(!0);try{const p=await F$.listProfiles();r(p),c(null)}catch(p){c(p instanceof Error?p:new Error(String(p)))}finally{i(!1)}},[]);f.useEffect(()=>{t&&u()},[t,u,n]);const m=f.useMemo(()=>{const p=new Map;if(s!=null&&s.profiles)for(const g of s.profiles)p.set(g.id,g);return p},[s]);return{profiles:(s==null?void 0:s.profiles)??N$,fallbackId:(s==null?void 0:s.fallback_id)??null,loading:a,error:l,refresh:u,byId:m}}const B$=(e,t)=>{var l,c,u,m,p;const n=e==null?void 0:e.trim();if(!n)return null;const s=t.get(n),r=((l=s==null?void 0:s.display_name)==null?void 0:l.trim())||n,a=(u=(c=s==null?void 0:s.ui)==null?void 0:c.icon)==null?void 0:u.trim(),i=((p=(m=s==null?void 0:s.ui)==null?void 0:m.color)==null?void 0:p.trim())||void 0;return o.jsx(Ne,{color:i,style:{marginInlineEnd:0,flex:"0 0 auto"},"data-testid":`sub-session-role-tag-${n}`,children:a?`${a} ${r}`:r})},{Text:Sr}=Ke,{useToken:QS}=Qe,W$="chat-session-sub-sessions-collapsed:",q$=3,U$=600,hc=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"},H$=(e,t)=>{if(t&&t.trim())return t;if(e.isRunning)return"running";if(e.lastRunStatus&&e.lastRunStatus.trim())return e.lastRunStatus;const n=e.messageCount??0;return n>2?"completed":(n>0,"pending")},ZS=e=>`${W$}${e}`,gu=e=>{if(typeof window>"u")return!1;try{const t=window.localStorage.getItem(ZS(e));return t==="1"?!0:t==="0"?!1:null}catch{return null}},K$=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(ZS(e),t?"1":"0")}catch{}},Y$=({parentSessionId:e})=>{const{t}=Ae(),{token:n}=QS(),[s,r]=f.useState(()=>gu(e)??!1),[a,i]=f.useState(null),[l,c]=f.useState(null),[u,m]=f.useState(null),p=G(q=>Fi(e)(q)),g=G(q=>q.chats),b=G(q=>q.loadChatHistory),S=G(q=>q.refreshChats),x=G(q=>q.markOptimisticStart),k=G(q=>q.markRetryStart),j=G(q=>q.markSettleTimeout),w=G(q=>q.pinSession),M=G(q=>q.unpinSession),_=G(q=>q.applyChildProgress),C=G(q=>q.clearChildProgress),{byId:D}=z$(),A=f.useMemo(()=>Object.entries(p).map(([q,H])=>({childSessionId:q,...H})),[p]),B=f.useMemo(()=>g.filter(q=>q.kind==="child"&&q.parentSessionId===e).sort((q,H)=>{const P=Date.parse(q.updatedAt||"")||0;return(Date.parse(H.updatedAt||"")||0)-P}),[g,e]),F=f.useMemo(()=>{const q=new Map(A.map(P=>[P.childSessionId,P])),H=[];for(const P of B){const W=q.get(P.id);H.push({childSessionId:P.id,title:P.title||(W==null?void 0:W.title),status:hc(H$(P,W==null?void 0:W.status)),error:(W==null?void 0:W.error)||P.lastRunError,lastHeartbeatAt:W==null?void 0:W.lastHeartbeatAt,lastEventAt:W==null?void 0:W.lastEventAt,outputPreview:W==null?void 0:W.outputPreview,roundCount:W==null?void 0:W.roundCount,pinned:P.pinned,updatedAt:P.updatedAt,isRunning:P.isRunning,messageCount:P.messageCount,lastRunStatus:P.lastRunStatus,lastRunError:P.lastRunError,subagentType:P.subagentType??null}),q.delete(P.id)}for(const P of q.values())H.push({childSessionId:P.childSessionId,title:P.title,status:hc(P.status),error:P.error,lastHeartbeatAt:P.lastHeartbeatAt,lastEventAt:P.lastEventAt,outputPreview:P.outputPreview,roundCount:P.roundCount});return H},[B,A]);f.useEffect(()=>{r(gu(e)??!1)},[e]),f.useEffect(()=>{gu(e)===null&&r(F.length>q$)},[e,F.length]);const O=f.useCallback(()=>{r(q=>{const H=!q;return K$(e,H),H})},[e]),R=f.useCallback(q=>q instanceof Error&&q.message.trim()?q.message:"Failed to run child session",[]),I=f.useCallback(async(q,H="regenerate")=>{i(q),_(e,q,{status:"running",error:void 0,lastEventAt:new Date().toISOString()}),k(q);try{const P=await pu.executeTool({tool_name:"SubSession",session_id:e,parameters:[{name:"action",value:"run"},{name:"child_session_id",value:q},{name:"reset_to_last_user",value:H==="error_retry"?"false":"true"}]});if(!P.success)throw new Error(P.result||"Failed to run child session");_(e,q,{status:"running",error:void 0,lastEventAt:new Date().toISOString()}),await b(q,{mode:"replace"}),await S()}catch(P){j(q),_(e,q,{status:"error",error:R(P),lastEventAt:new Date().toISOString()})}finally{i(P=>P===q?null:P)}},[b,e,S,k,j,R,_]),L=f.useCallback(async q=>{const H=typeof window<"u"?window.prompt.bind(window):null;if(!H)return;const P=H("Send a follow-up message to this child session:","Continue from where you left off.");if(P===null)return;const W=P.trim();if(!W){_(e,q,{status:"error",error:"Follow-up message cannot be empty.",lastEventAt:new Date().toISOString()});return}c(q),_(e,q,{status:"running",error:void 0,lastEventAt:new Date().toISOString()}),x(q);try{const ne=await pu.executeTool({tool_name:"SubSession",session_id:e,parameters:[{name:"action",value:"send_message"},{name:"child_session_id",value:q},{name:"message",value:W},{name:"auto_run",value:"true"}]});if(!ne.success)throw new Error(ne.result||"Follow-up failed");let K="running";try{JSON.parse(ne.result).status==="pending"&&(K="pending")}catch{K="running"}_(e,q,{status:K,error:void 0,lastEventAt:new Date().toISOString()}),await S()}catch(ne){j(q),_(e,q,{status:"error",error:ne instanceof Error&&ne.message.trim()?ne.message:"Failed to continue child session",lastEventAt:new Date().toISOString()})}finally{c(ne=>ne===q?null:ne)}},[e,S,x,j,_]),U=f.useCallback(async q=>{m(q);try{const H=await pu.executeTool({tool_name:"SubSession",session_id:e,parameters:[{name:"action",value:"delete"},{name:"child_session_id",value:q}]});if(!H.success)throw new Error(H.result||"Failed to delete child session");C(e,q),await S()}finally{m(H=>H===q?null:H)}},[C,e,S]);return F.length===0?null:o.jsxs(Ce,{size:"small",className:"lotus-settings-card",style:{marginBottom:n.marginMD},"data-testid":"sub-sessions-panel",title:o.jsxs(Sr,{strong:!0,children:[t("chat.subSessions.title")," ",o.jsxs(Sr,{type:"secondary",children:["(",F.length,")"]})]}),extra:o.jsx(de,{type:"text",size:"small",icon:s?o.jsx(Gn,{}):o.jsx(Lm,{}),onClick:O,"data-testid":"sub-sessions-toggle",children:t(s?"chat.subSessions.expand":"chat.subSessions.collapse")}),children:[s?o.jsx(Sr,{type:"secondary","data-testid":"sub-sessions-collapsed-hint",children:t("chat.subSessions.hiddenHint",{count:F.length})}):o.jsx(ve,{vertical:!0,gap:n.marginSM,"data-testid":"sub-sessions-list",style:{maxHeight:`${U$}px`,overflowY:"auto",paddingRight:n.paddingXS},children:F.map(q=>{const H=hc(q.status),P=H==="running",W=a===q.childSessionId,ne=l===q.childSessionId,K=u===q.childSessionId,xe=W||ne||K;return o.jsxs(ve,{align:"flex-start",justify:"space-between",gap:n.marginSM,className:"lotus-settings-list-item",style:{padding:n.paddingSM,borderRadius:n.borderRadiusSM},children:[o.jsxs(ve,{vertical:!0,style:{flex:1,minWidth:0},children:[o.jsxs(ve,{align:"center",gap:n.marginXS,style:{minWidth:0},children:[o.jsx(Sr,{strong:!0,ellipsis:!0,style:{minWidth:0},children:q.title||"Child Session"}),o.jsx(Ne,{color:H==="running"?"processing":H==="completed"?"success":H==="error"||H==="failed"?"error":H==="cancelled"?"warning":"default",style:{marginInlineEnd:0,flex:"0 0 auto"},children:H}),q.pinned?o.jsx(Ne,{color:"warning",style:{marginInlineEnd:0,flex:"0 0 auto"},children:"Pinned"}):null,B$(q.subagentType,D)]}),o.jsxs(Sr,{type:"secondary",style:{fontSize:12,marginTop:2},children:[q.childSessionId.slice(0,8),q.updatedAt?` • ${q.updatedAt}`:"",q.lastHeartbeatAt?` • heartbeat: ${q.lastHeartbeatAt}`:"",typeof q.roundCount=="number"?` • round ${q.roundCount+1}`:""]}),q.outputPreview?o.jsx(Sr,{type:"secondary",style:{marginTop:n.marginXS,fontSize:13},ellipsis:!0,children:q.outputPreview}):null,q.error?o.jsx(Sr,{type:"danger",style:{marginTop:n.marginXS},children:q.error}):null]}),o.jsxs(ve,{gap:8,children:[o.jsx(de,{size:"small",disabled:xe,onClick:()=>{Qc(q.childSessionId),b(q.childSessionId)},children:t("chat.subSessions.open")}),o.jsx(de,{size:"small",loading:ne,disabled:K||W||P,"data-testid":`sub-session-continue-${q.childSessionId}`,onClick:()=>{L(q.childSessionId)},children:t("chat.subSessions.continue")}),o.jsx(lo,{trigger:["click"],menu:{items:[{key:"regenerate",label:t("chat.actions.regenerate")},{key:"error_retry",label:t("chat.actions.retryFailed")}],onClick:({key:se})=>{I(q.childSessionId,se)}},disabled:K||P||ne,children:o.jsx(de,{size:"small",loading:W,disabled:K||P||ne,"data-testid":`sub-session-retry-${q.childSessionId}`,children:t("chat.subSessions.retry")})}),typeof q.pinned=="boolean"?o.jsx(de,{size:"small",disabled:xe,onClick:()=>{q.pinned?M(q.childSessionId):w(q.childSessionId)},children:q.pinned?t("chat.actions.unpin"):t("chat.actions.pin")}):null,o.jsx(de,{danger:!0,size:"small",loading:K,disabled:W,"data-testid":`sub-session-delete-${q.childSessionId}`,onClick:()=>{U(q.childSessionId)},children:t("common.delete")})]})]},q.childSessionId)})}),!s&&F.length>1&&o.jsx(V$,{items:F})]})},V$=({items:e})=>{const{token:t}=QS(),n=e.reduce((r,a)=>{const i=hc(a.status);return i==="completed"?r.completed++:i==="running"?r.running++:i==="error"||i==="failed"?r.error++:r.pending++,r},{completed:0,running:0,error:0,pending:0}),s=[];return n.completed>0&&s.push(`${n.completed} completed`),n.running>0&&s.push(`${n.running} running`),n.pending>0&&s.push(`${n.pending} pending`),n.error>0&&s.push(`${n.error} failed`),s.length===0?null:o.jsx(Sr,{type:"secondary",style:{fontSize:11,marginTop:t.marginXS,display:"block"},children:s.join(" · ")})},{useToken:X$}=Qe,G$=e=>{const t=e.replace(/\/$/,"").split("/").filter(Boolean);return t.length<=2?e:`~/${t.slice(-2).join("/")}`},J$=({sessionId:e})=>{const{t}=Ae(),{token:n}=X$(),s=G(Er(e)),r=G(m=>m.systemPrompts),a=s==null?void 0:s.config.workspacePath,i=s==null?void 0:s.config.systemPromptId,l=f.useMemo(()=>{if(!i)return null;const m=r.find(p=>p.id===i);return(m==null?void 0:m.name)||i},[i,r]),c=f.useMemo(()=>s!=null&&s.messages?s.messages.filter(m=>m.role==="user"&&"type"in m&&m.type==="file_reference").length:0,[s==null?void 0:s.messages]);return!s||!(a||l||c>0)?null:o.jsx("div",{className:"lotus-context-bar",style:{borderBottomColor:n.colorBorderSecondary,backgroundColor:n.colorBgContainer},children:o.jsxs(ve,{align:"center",gap:6,wrap:"wrap",className:"lotus-context-bar__content",children:[a&&o.jsx(bt,{title:a,children:o.jsx(Ne,{className:"lotus-context-bar__tag",icon:o.jsx(gc,{}),bordered:!1,children:G$(a)})}),c>0&&o.jsx(bt,{title:t("chat.contextBar.fileRefsTooltip",{count:c,defaultValue:"{{count}} file reference(s) in this session"}),children:o.jsxs(Ne,{className:"lotus-context-bar__tag",icon:o.jsx(C_,{}),bordered:!1,children:[c," ",t("chat.contextBar.files","files")]})}),l&&o.jsx(bt,{title:t("chat.contextBar.promptTooltip",{name:l,defaultValue:"System prompt: {{name}}"}),children:o.jsx(Ne,{className:"lotus-context-bar__tag",icon:o.jsx(Wc,{}),bordered:!1,children:l})})]})})},Q$=new Set(["Write","Edit","apply_patch","NotebookEdit"]),Z$=e=>{const t=e.match(/(?:file_path|Wrote file|Edited file)[:\s]*["']?([^\s"',]+)/i);if(t){const n=t[1];return n.split("/").pop()||n}return null},eD=(e,t)=>{const n=t-e;if(n<0)return"";const s=Math.floor(n/1e3);if(s<60)return`${s}s`;const r=Math.floor(s/60);return r<60?`${r}m ${s%60}s`:`${Math.floor(r/60)}h ${r%60}m`},tD=e=>{var p,g;let t=0,n=0,s=0,r=0,a=!1,i=0,l="";const c=new Set;let u=0,m=0;for(const b of e){const S=b.createdAt?new Date(b.createdAt).getTime():0;if(S>0&&(u===0||S<u)&&(u=S),S>m&&(m=S),b.isCompressed){a=!0,i++;continue}if(b.role==="user"&&!("type"in b&&b.type==="file_reference")&&t++,b.role==="assistant"){if("type"in b&&b.type==="tool_call"&&(s+=((p=b.toolCalls)==null?void 0:p.length)??0),"type"in b&&b.type==="tool_result"){const x=b;if(x.isError&&r++,Q$.has(x.toolName)){const k=Z$(((g=x.result)==null?void 0:g.result)??"");k&&c.add(k)}}if("type"in b&&b.type==="text"){n++;const x=b.content||"";x.length>0&&x.length>30&&(l=x.slice(0,300))}}}return{messageCount:e.length,userMessageCount:t,assistantMessageCount:n,toolCallCount:s,toolErrorCount:r,fileChanges:Array.from(c).slice(0,10),lastAssistantExcerpt:l,hasCompression:a,compressionCount:i,duration:u>0&&m>u?eD(u,m):""}},nD=({sessionId:e})=>{const{t}=Ae(),{token:n}=Qe.useToken(),[s,r]=f.useState(!1),a=G(Er(e)),i=a==null?void 0:a.messages,l=f.useMemo(()=>!i||i.length===0?null:tD(i),[i]);if(!l||l.messageCount<3)return null;const c=l.fileChanges.length>0,u=l.lastAssistantExcerpt.length>0;return o.jsxs("div",{className:"lotus-session-summary",style:{borderColor:n.colorBorderSecondary,background:`${n.colorBgElevated}`},children:[o.jsxs("div",{className:"lotus-session-summary-header",onClick:()=>r(m=>!m),role:"button",tabIndex:0,onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),r(p=>!p))},"aria-expanded":s,children:[o.jsx("span",{className:"lotus-session-summary-header-icon",style:{color:n.colorPrimary},children:o.jsx(M_,{})}),o.jsx("span",{className:"lotus-session-summary-header-title",style:{color:n.colorText},children:t("sessionSummary.title","Session Summary")}),!s&&o.jsxs("span",{className:"lotus-session-summary-stats",children:[o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:n.colorTextSecondary},children:[o.jsx(yc,{className:"lotus-session-summary-stat-icon"}),o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.messageCount})]}),l.toolCallCount>0&&o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:n.colorTextSecondary},children:[o.jsx(mf,{className:"lotus-session-summary-stat-icon"}),o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolCallCount})]}),c&&o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:n.colorTextSecondary},children:[o.jsx(qo,{className:"lotus-session-summary-stat-icon"}),o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.fileChanges.length})]})]}),o.jsx("span",{className:`lotus-session-summary-toggle ${s?"is-expanded":""}`,style:{color:n.colorTextTertiary},children:o.jsx(Gn,{})})]}),s&&o.jsxs("div",{className:"lotus-session-summary-body",children:[o.jsxs("div",{className:"lotus-session-summary-stats",children:[o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:n.colorTextSecondary},children:[o.jsx(yc,{className:"lotus-session-summary-stat-icon"}),o.jsxs("span",{children:[o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.messageCount})," ",t("sessionSummary.messages","messages")]})]}),o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:n.colorTextSecondary},children:[o.jsx("span",{className:"lotus-session-summary-stat-icon",children:"👤"}),o.jsxs("span",{children:[o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.userMessageCount})," ",t("sessionSummary.userTurns","user")]})]}),o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:n.colorTextSecondary},children:[o.jsx("span",{className:"lotus-session-summary-stat-icon",children:"🤖"}),o.jsxs("span",{children:[o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.assistantMessageCount})," ",t("sessionSummary.assistantTurns","assistant")]})]}),l.toolCallCount>0&&o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:n.colorTextSecondary},children:[o.jsx(mf,{className:"lotus-session-summary-stat-icon"}),o.jsxs("span",{children:[o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolCallCount})," ",t("sessionSummary.toolCalls","tool calls")]})]}),l.toolErrorCount>0&&o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:"#ff4d4f"},children:[o.jsx(Yi,{className:"lotus-session-summary-stat-icon"}),o.jsxs("span",{children:[o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolErrorCount})," ",t("sessionSummary.errors","errors")]})]}),l.duration&&o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:n.colorTextSecondary},children:[o.jsx(As,{className:"lotus-session-summary-stat-icon"}),o.jsx("span",{children:l.duration})]}),l.hasCompression&&o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:n.colorTextSecondary},children:[o.jsx(Wc,{className:"lotus-session-summary-stat-icon"}),o.jsxs("span",{children:[o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.compressionCount})," ",t("sessionSummary.compressions","compressions")]})]})]}),c&&o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:11,fontWeight:600,color:n.colorTextSecondary,marginBottom:4,textTransform:"uppercase",letterSpacing:.3},children:t("sessionSummary.filesChanged","Files Changed")}),o.jsx("div",{className:"lotus-session-summary-files",children:l.fileChanges.map(m=>o.jsx(bt,{title:m,children:o.jsxs(Ne,{bordered:!1,className:"lotus-session-summary-file-tag",children:[o.jsx(qo,{style:{marginRight:4}}),m]})},m))})]}),u&&o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:11,fontWeight:600,color:n.colorTextSecondary,marginBottom:4,textTransform:"uppercase",letterSpacing:.3},children:t("sessionSummary.lastResponse","Latest Response")}),o.jsx("div",{className:"lotus-session-summary-conclusion",style:{color:n.colorTextSecondary},children:l.lastAssistantExcerpt})]})]})]})},Sm="chat_scroll_anchors_v1",ew="chat_scroll_anchor_v2:";function tw(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 sD(){try{const e=localStorage.getItem(Sm);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const n={};for(const[s,r]of Object.entries(t))tw(r)&&(n[s]=r);return n}catch{return{}}}function rD(e){const t=sD(),n=t[e];if(!n)return null;Wn.getInstance().saveScrollAnchor(e,n).catch(()=>{}),delete t[e];const r=Object.keys(t).length;try{r===0?localStorage.removeItem(Sm):localStorage.setItem(Sm,JSON.stringify(t))}catch{}return n}async function oD(e){if(typeof window>"u")return null;try{const n=await Wn.getInstance().loadScrollAnchor(e);if(n)return n}catch{}try{const t=localStorage.getItem(`${ew}${e}`);if(t){const n=JSON.parse(t);if(tw(n))return Wn.getInstance().saveScrollAnchor(e,n).catch(()=>{}),n}}catch{}return rD(e)}async function aD(e,t){if(!(typeof window>"u")){try{await Wn.getInstance().saveScrollAnchor(e,t)}catch(n){console.warn("[ScrollAnchor] IndexedDB save failed:",n)}try{localStorage.setItem(`${ew}${e}`,JSON.stringify(t))}catch{}}}const yu=1,iD=3,lD=2e3;function cD(e,t){const n=Math.max(0,e.scrollHeight-e.clientHeight);return Math.min(Math.max(0,t),n)}function dD(e){const{scrollEl:t,getAnchorElement:n,offsetPx:s,isCancelled:r}=e;return new Promise(a=>{const i=performance.now();let l=0,c=-1,u=Number.NaN;const m=()=>{if(r()){a();return}const p=n();if(!p){requestAnimationFrame(m);return}const g=t.getBoundingClientRect(),S=p.getBoundingClientRect().top-g.top,x=cD(t,t.scrollTop+(S-s));if(Math.abs(t.scrollTop-x)>yu)t.scrollTop=x,l=0;else{const j=Number.isFinite(u)?Math.abs(x-u)<=yu:!1,w=Math.abs(t.scrollTop-c)<=yu;l=j&&w?l+1:0}u=x,c=t.scrollTop;const k=performance.now()-i>lD;if(l>=iD||k){a();return}requestAnimationFrame(m)};requestAnimationFrame(m)})}const uD=300,mD=.5;function hD(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 nw(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 oy(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function fD(e,t){const n=oy(e.createdAt);if(n!=null){let s=null,r=Number.POSITIVE_INFINITY;for(let a=0;a<t.length;a++){const i=oy(nw(t[a]));if(i==null)continue;const l=Math.abs(i-n);l<r&&(r=l,s=a)}if(s!=null)return s}if(typeof e.indexHint=="number"){const s=Math.max(0,Math.min(t.length-1,e.indexHint));return Number.isFinite(s)?s:null}return null}function Ih(e){return Array.from(e.querySelectorAll("[data-chat-entry-id]"))}function pD(e,t){const n=Ih(e);for(const s of n)if(s.dataset.chatEntryId===t)return s;return null}function gD(e,t){const n=Ih(e);if(n.length===0)return null;const s=Math.max(0,Math.min(n.length-1,t));return n[s]??null}function yD(e){const t=Ih(e);if(t.length===0)return null;const n=e.getBoundingClientRect().top;for(const s of t)if(s.getBoundingClientRect().bottom>n)return s;return t[t.length-1]??null}function bD(e){const{currentSessionId:t,messagesListRef:n,renderableMessages:s}=e,r=f.useRef(new Set),a=f.useRef(!1),i=f.useRef(0),l=f.useRef(null),c=f.useRef(null),u=f.useRef(!1);f.useEffect(()=>{const S=n.current;if(!S)return;const x=()=>{u.current=!0};return S.addEventListener("wheel",x,{passive:!0}),S.addEventListener("touchmove",x,{passive:!0}),S.addEventListener("pointerdown",x),()=>{S.removeEventListener("wheel",x),S.removeEventListener("touchmove",x),S.removeEventListener("pointerdown",x)}},[n]);const m=f.useMemo(()=>{const S=new Map;for(let x=0;x<s.length;x++){const k=hD(s[x]);k&&S.set(k,x)}return S},[s]),p=f.useCallback(()=>{const S=n.current;if(!S||s.length===0)return null;const x=yD(S);if(!x)return null;const k=x.dataset.chatEntryId;if(!k)return null;const j=S.getBoundingClientRect(),w=x.getBoundingClientRect(),M=m.get(k),_=typeof M=="number"?s[M]:void 0;return{v:1,anchorId:k,offsetPx:w.top-j.top,ts:Date.now(),indexHint:M,createdAt:_?nw(_):void 0}},[m,n,s]),g=f.useCallback(async S=>{if(a.current)return;const x=p();if(!x)return;const k=c.current;k&&k.anchorId===x.anchorId&&Math.abs(k.offsetPx-x.offsetPx)<=mD||(await aD(S,x),c.current=x)},[p]),b=f.useCallback(S=>{if(!t||a.current)return;l.current&&clearTimeout(l.current);const x=t;l.current=setTimeout(()=>{g(x).catch(()=>{})},uD)},[t,g]);return f.useEffect(()=>{const S=t;return()=>{S&&(l.current&&(clearTimeout(l.current),l.current=null),g(S).catch(()=>{}))}},[t,g]),f.useLayoutEffect(()=>{if(!t)return;const S=n.current;if(!S||s.length===0||r.current.has(t))return;let x=!1;return oD(t).then(k=>{if(x||!k){x||r.current.add(t);return}const j=m.get(k.anchorId),w=typeof j=="number"?j:fD(k,s);if(w==null){r.current.add(t);return}l.current&&(clearTimeout(l.current),l.current=null);const M=++i.current;a.current=!0,u.current=!1,S.style.overflowAnchor="none";const _=()=>i.current!==M||u.current;dD({scrollEl:S,getAnchorElement:()=>pD(S,k.anchorId)??gD(S,w),offsetPx:k.offsetPx,isCancelled:_}).finally(()=>{i.current===M&&(a.current=!1,r.current.add(t),S.style.overflowAnchor="",g(t).catch(()=>{}))})}),()=>{x=!0}},[t,m,s,s.length,n,g]),{handleScroll:b}}const ay=2,iy=6,xD=({currentSessionId:e,isThinking:t,messagesListRef:n,renderableMessages:s})=>{const[r,a]=f.useState(!1),[i,l]=f.useState(!1),c=f.useRef(!1),u=f.useRef(!0),{handleScroll:m}=bD({currentSessionId:e,messagesListRef:n,renderableMessages:s}),p=f.useCallback(k=>{const j=n.current;if(!j)return;if(s.length===0){a(!1),l(!1);return}const w=j.scrollHeight-j.scrollTop-j.clientHeight,M=j.scrollTop,_=150,C=150,D=w<_,A=M<C;a(!D),l(!A&&s.length>3),w>_*2?c.current=!0:D&&(c.current=!1),m(k)},[n,s.length,m]),g=f.useCallback(()=>{if(!n.current||s.length===0)return;let j=0,w=-1;const M=()=>{const _=n.current;if(!_)return;const C=Math.max(0,_.scrollHeight-_.clientHeight),D=Math.max(0,_.scrollHeight-_.scrollTop-_.clientHeight),A=_.scrollHeight!==w,B=D>ay||A||j===0;B&&_.scrollTo({top:C,behavior:j===0?"smooth":"auto"}),w=_.scrollHeight,j+=1,j<iy&&B&&requestAnimationFrame(M)};requestAnimationFrame(M)},[n,s.length]),b=f.useCallback(()=>{if(!n.current)return;let j=0;const w=()=>{const M=n.current;if(!M)return;const _=M.scrollTop>ay||j===0;_&&M.scrollTo({top:0,behavior:"auto"}),j+=1,j<iy&&_&&requestAnimationFrame(w)};requestAnimationFrame(w)},[n]),S=f.useCallback(()=>{c.current=!1},[]);f.useEffect(()=>{const k=j=>{var O,R;const M=(O=j.detail)==null?void 0:O.messageId;if(!M){console.error("No messageId provided for navigation");return}const _=s.findIndex(I=>"message"in I&&I.message?I.message.id===M:"id"in I?I.id===M:!1);if(_===-1){console.warn("Message not found for navigation:",M);return}const C=s[_],D=C&&"message"in C?C.message.id:C&&"id"in C?C.id:M,A=document.getElementById(`message-${D}`),B=Array.from(((R=n.current)==null?void 0:R.querySelectorAll("[data-chat-entry-id]"))||[]),F=A||B.find(I=>I.dataset.chatEntryId===D);if(!F){console.warn("Message element not found for navigation:",M);return}F.scrollIntoView({behavior:"smooth",block:"center"}),F.classList.add("highlight-message"),setTimeout(()=>{F.classList.remove("highlight-message")},2e3)};return window.addEventListener("navigate-to-message",k),()=>{window.removeEventListener("navigate-to-message",k)}},[n,s]);const x=f.useRef(t);return f.useEffect(()=>{!x.current&&t&&(S(),g()),x.current=t},[t,S,g]),f.useEffect(()=>It.subscribe(k=>{k.sessionId===e&&(c.current||k.content&&g())}),[e,g]),f.useEffect(()=>{!c.current&&s.length>0&&!u.current&&g(),u.current=!1},[s.length,g]),f.useEffect(()=>{if(!n.current){a(!1),l(!1);return}if(s.length===0){a(!1),l(!1);return}const j=()=>{const M=n.current;if(!M)return;const _=M.scrollHeight-M.scrollTop-M.clientHeight,C=M.scrollTop,D=150,A=150,B=_<D,F=C<A;a(!B),l(!F&&s.length>3)};j();let w=requestAnimationFrame(()=>{j(),w=requestAnimationFrame(j)});return()=>cancelAnimationFrame(w)},[n,s.length,e]),f.useEffect(()=>{u.current=!0,c.current=!1},[e]),{handleMessagesScroll:p,resetUserScroll:S,scrollToBottom:g,scrollToTop:b,showScrollToBottom:r,showScrollToTop:i}};function vD(e){return"type"in e&&e.type==="tool_session"}function SD(e){return"type"in e&&e.type==="compression_divider"}const ly=e=>{const t=Date.parse(e||"");return Number.isFinite(t)?t:Number.MAX_SAFE_INTEGER},wD=e=>"type"in e?e.createdAt:e.message.createdAt,_D=e=>!("type"in e)&&e.message.role==="system";function kD(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_call"}function TD(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_result"}const cy=e=>(e??"").trim().toLowerCase()==="conclusion",jD=e=>{const t=(e??"").trim().toLowerCase();return t==="conclusion_with_options"||t==="exitplanmode"||t==="request_permissions"},CD=e=>{var t,n,s;return((n=(t=e.call.toolCalls)==null?void 0:t[0])==null?void 0:n.toolCallId)||((s=e.result)==null?void 0:s.toolCallId)||"tool-call-missing"},MD=(e,t)=>{var n;return e.call.id||e.callMessageId||e.resultMessageId||((n=e.result)==null?void 0:n.id)||`tool-message-missing-${t}`},PD=(e,t)=>`tool-session-${MD(e,t)}:${CD(e)}`;function ED(e){const t=[],n=new Map,s=new Set,r=(i,l)=>{const c=n.get(i)||[];c.push(l),n.set(i,c)},a=i=>{const l=n.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?n.delete(i):n.set(i,l),c};for(const i of e){if(kD(i)){const l=i.toolCalls||[];if(l.length===0){t.push(i);continue}l.forEach((c,u)=>{const m=c.toolCallId||`${i.id}-${u}`;if(cy(c.toolName)){s.add(m);return}if(jD(c.toolName)){s.add(m);const S={...i,id:`${i.id}:tool-call:${u}:${m}`,toolCalls:[{...c,toolCallId:m}]};t.push(S);return}const g={call:{...i,id:`${i.id}:tool-call:${u}:${m}`,toolCalls:[{...c,toolCallId:m}]},callMessageId:i.id};r(m,g);const b=t[t.length-1];Array.isArray(b)?b.push(g):t.push([g])});continue}if(TD(i)){const l=i.toolCallId;if(l&&s.has(l)){s.delete(l),t.push(i);continue}if(cy(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}`,p={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},g=t[t.length-1];Array.isArray(g)?g.push(p):t.push([p])}continue}t.push(i)}return t}const RD=(e,t)=>{var l;const{t:n}=Ae(),s=f.useMemo(()=>{var u;const c=t.find(m=>m.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]),r=f.useCallback(c=>!1,[]),a=f.useCallback(c=>{if(SD(c))return{type:"compression_divider",id:c.id,createdAt:c.createdAt,label:c.label};if(vD(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 m=c.messageType;if(!m&&c.message.role==="assistant"&&"type"in c.message){const p="type"in c.message?c.message.type:void 0;(p==="text"||p==="plan"||p==="question"||p==="tool_call"||p==="tool_result")&&(m=p)}return{type:"message",message:c.message,align:u,messageType:m}},[]),i=f.useMemo(()=>{var x;const c=t.filter(k=>{const j=k.role;return!(j!=="user"&&j!=="assistant"&&j!=="system"&&j!=="tool"||r(k))}),u=ED(c),m=[];u.forEach((k,j)=>{var _,C;if(Array.isArray(k)){const D=k[0];m.push({type:"tool_session",id:D?PD(D,j):`tool-session-unknown-${j}`,sessionId:(e==null?void 0:e.id)||"default",tools:k,createdAt:((_=D==null?void 0:D.call)==null?void 0:_.createdAt)||((C=D==null?void 0:D.result)==null?void 0:C.createdAt)||new Date().toISOString()});return}const w=k;let M;if(w.role==="assistant"&&"type"in w){const D="type"in w?w.type:void 0;(D==="text"||D==="plan"||D==="question"||D==="tool_call"||D==="tool_result")&&(M=D)}m.push({message:w,messageType:M})}),!c.some(k=>k.role==="system")&&s&&m.unshift({message:s});const g=((x=e==null?void 0:e.config)==null?void 0:x.compressionEvents)||[],b=m.findIndex(k=>!_D(k)),S=b===-1?m.length:b;for(const k of g){const j={type:"compression_divider",id:`compression-divider-${k.id}`,createdAt:k.createdAt,label:n("chat.compression.timelineDetail",{count:k.messagesCompressed,defaultValue:"{{count}} messages archived"})},w=ly(k.createdAt),M=m.findIndex((_,C)=>C>=S&&ly(wD(_))>w);M===-1?m.push(j):m.splice(M,0,j)}return m},[(l=e==null?void 0:e.config)==null?void 0:l.compressionEvents,e==null?void 0:e.id,t,r,s,n]);return{systemPromptMessage:s,renderableMessages:i,convertRenderableEntry:a}},{useToken:AD}=Qe,{useBreakpoint:ID}=zc,{Text:OD}=Ke,$D=e=>e.role==="user"?"You":e.role==="assistant"?"Assistant":e.role==="system"?"System":"Message",sw=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},DD=e=>e.map(({message:t,text:n},s)=>{const r=$D(t),a=sw(t.createdAt);return[`## ${s+1}. ${r} · ${a}`,"",n].join(`
248
+ `)}).join(`
249
+
250
+ ---
251
+
252
+ `),LD=({sessionId:e,embedded:t=!1})=>{var Jn,Xs,mr,is,ws;const{message:n}=en.useApp(),{t:s}=Ae(),r=Ic(Fe=>Fe.isAdvanced),a=G(Fe=>e??Fe.currentSessionId),i=G(Er(a)),l=G(Fe=>Fe.deleteMessage),c=G(Fe=>Fe.loadChatHistory),u=G(Fe=>Fe.loadTaskList),m=G(Fe=>Fe.tokenUsages),p=G(Fe=>Fe.truncationOccurred),g=G(Fe=>Fe.segmentsRemoved),b=f.useMemo(()=>(i==null?void 0:i.messages)||[],[i]),S=f.useMemo(()=>!a||!i?a:i.kind==="child"&&(i.parentSessionId||i.rootSessionId)||a,[i,a]),x=G(Fe=>S?!!Fe.taskLists[S]:!1),k=G(ur(a)),j=f.useMemo(()=>!a||!i?!1:!!(x||i.kind==="child"||k),[i,x,a,k]),w=G(Fe=>{if(!a)return!1;const yt=Fi(a)(Fe);return Object.keys(yt).length>0?!0:Fe.chats.some(tt=>tt.kind==="child"&&tt.parentSessionId===a)});f.useEffect(()=>{if(!a)return;const Fe=G.getState().chats.find(yt=>yt.id===a);Fe&&Array.isArray(Fe.messages)&&Fe.messages.length>0||c(a)},[a,c]);const M=(i==null?void 0:i.messageCount)??0,_=((Jn=i==null?void 0:i.messages)==null?void 0:Jn.length)??0;f.useEffect(()=>{if(!a)return;M-_>0&&c(a,{mode:"monotonic"})},[a,M,_,c]),f.useEffect(()=>{!S||x||j&&u(S).catch(Fe=>{console.warn(`[ChatView] Failed to load task list for ${S}:`,Fe)})},[S,x,j,u]);const C=k,D=f.useMemo(()=>{var Un;if(!b||b.length===0)return null;const Fe=new Map;let yt=0,tt=0,mt=0;for(const Hn of b){if(!rS(Hn))continue;const Rn=((Un=Hn.result)==null?void 0:Un.result)??"",ls=td(Rn),yn=Jv(Rn);if(!ls||!yn)continue;mt+=1,yt+=yn.added,tt+=yn.removed;const An=Fe.get(ls.file_path);An?(An.added+=yn.added,An.removed+=yn.removed,An.diffChunks.push(ls.diff.unified),An.truncated=An.truncated||!!ls.diff.truncated):Fe.set(ls.file_path,{added:yn.added,removed:yn.removed,diffChunks:[ls.diff.unified],truncated:!!ls.diff.truncated})}if(Fe.size===0)return null;const _n=Array.from(Fe.entries()).map(([Hn,Rn])=>({filePath:Hn,added:Rn.added,removed:Rn.removed,unifiedDiff:Rn.diffChunks.join(`
253
+
254
+ `),truncated:Rn.truncated})).sort((Hn,Rn)=>Hn.filePath.localeCompare(Rn.filePath));return{totalAdded:yt,totalRemoved:tt,files:_n,changedTools:mt}},[b]),A=C,B=f.useCallback(Fe=>{if(Fe.success)return null;switch(Fe.reason){case"session_not_found":case"message_not_found":case"backend_not_found":return s("chat.messageActions.deleteNotFound");case"session_running":return s("chat.messageActions.deleteConflict");default:return Fe.errorMessage||s("chat.messageActions.deleteFailed")}},[s]),F=f.useCallback(async(Fe,yt)=>{if(!a){const mt={success:!1,sessionId:"",messageId:Fe,reason:"session_not_found"};return(yt==null?void 0:yt.notify)!==!1&&n.error(B(mt)),mt}const tt=await l(a,Fe);return!tt.success&&(yt==null?void 0:yt.notify)!==!1&&n.error(B(tt)),tt},[a,l,n,B]),O=f.useCallback(async Fe=>{const yt=Array.from(new Set(Fe.map(_n=>_n.trim()).filter(Boolean)));if(yt.length===0)return;const mt=(await Promise.all(yt.map(_n=>F(_n,{notify:!1})))).filter(_n=>!_n.success);if(mt.length!==0){if(mt.length===1){n.error(B(mt[0]));return}n.error(s("chat.messageActions.deleteBatchFailed",{failed:mt.length,total:yt.length}))}},[F,n,B,s]),R=f.useRef(null),{token:I}=AD(),L=ID(),U=Bm(),[q,H]=f.useState(null),[P,W]=f.useState(!1),[ne,K]=f.useState(new Set),xe=wt(Fe=>Fe.sidebar.collapsed),se=()=>t||L.xs||L.sm?"100%":L.md?"90%":L.lg?"85%":"1024px",fe=()=>{let Fe;return t?Fe=I.paddingSM:L.xs?Fe=I.paddingXS:L.sm?Fe=I.paddingSM:Fe=I.padding,!t&&xe&&!U?Fe+18:Fe};f.useEffect(()=>{H(null),W(!1),K(new Set)},[a]);const{systemPromptMessage:Se,renderableMessages:me,convertRenderableEntry:ze}=RD(i,b),st=b.length>0,pt=!!(q!=null&&q.content),Kt=!!Se,Oe=!!a&&(st||pt),Wt=t&&!L.xs?190:0,Xe=f.useMemo(()=>{if(!(q!=null&&q.content))return me;const Fe={message:{id:q.id,role:"user",content:q.content,createdAt:q.createdAt},messageType:"text"};return[...me,Fe]},[me,q]),_e=f.useMemo(()=>{const Fe=[];for(const yt of Xe){if(!("message"in yt))continue;const tt=qS(yt.message).trim();tt&&Fe.push({id:yt.message.id,message:yt.message,text:tt})}return Fe},[Xe]),Ye=f.useMemo(()=>new Set(_e.map(Fe=>Fe.id)),[_e]);f.useEffect(()=>{K(Fe=>{let yt=!1;const tt=new Set;for(const mt of Fe)Ye.has(mt)?tt.add(mt):yt=!0;return yt?tt:Fe})},[Ye]);const ot=f.useMemo(()=>_e.filter(Fe=>ne.has(Fe.id)),[_e,ne]),Lt=_e.length>0,N=f.useCallback(Fe=>{K(yt=>{const tt=new Set(yt);return tt.has(Fe)?tt.delete(Fe):tt.add(Fe),tt})},[]),le=f.useCallback(()=>{if(!Lt){n.warning("No exportable messages");return}W(!0)},[n,Lt]),be=f.useCallback(()=>{W(!1),K(new Set)},[]),De=f.useCallback(()=>{if(P){be();return}le()},[le,be,P]),Le=f.useCallback(()=>{K(new Set(_e.map(Fe=>Fe.id)))},[_e]),ue=f.useCallback(()=>{K(new Set)},[]),ye=f.useCallback(async Fe=>{var mt;if(!a){n.warning("No active chat");return}if(ot.length===0){n.warning("Please select at least one message");return}const yt=DD(ot),tt=await US.exportMessageText({format:Fe,content:yt,sessionId:a,filenamePrefix:`chat-messages-${ot.length}`});if(tt.success){n.success(`Saved: ${tt.filename}`);return}(mt=tt.error)!=null&&mt.toLowerCase().includes("cancel")||n.error(tt.error||"Export failed")},[n,a,ot]);f.useEffect(()=>{if(typeof window>"u")return;const Fe=yt=>{var _n;const mt=((_n=yt.detail)==null?void 0:_n.sessionId)??null;!a||mt!==a||De()};return window.addEventListener(fm,Fe),()=>{window.removeEventListener(fm,Fe)}},[a,De]);const qe=a?m[a]:null,He=(Xs=i==null?void 0:i.config)==null?void 0:Xs.tokenUsage,ae=qe||He||null,ke=a?p[a]:!1,pe=(mr=i==null?void 0:i.config)==null?void 0:mr.truncationOccurred,Re=ke||pe||!1,Je=a?g[a]:0,gt=(is=i==null?void 0:i.config)==null?void 0:is.segmentsRemoved,Mt=Je||gt||0,xt=f.useMemo(()=>{var yt;const Fe=(yt=i==null?void 0:i.config)==null?void 0:yt.compressionEvents;return!Fe||Fe.length===0?null:Fe.reduce((tt,mt)=>{const _n=Date.parse(tt.createdAt),Un=Date.parse(mt.createdAt);return Number.isFinite(_n)?Number.isFinite(Un)&&Un>_n?mt:tt:mt})},[(ws=i==null?void 0:i.config)==null?void 0:ws.compressionEvents]),Ft=I.marginMD,{handleMessagesScroll:Dt,resetUserScroll:Ue,scrollToBottom:rn,scrollToTop:dn,showScrollToBottom:on,showScrollToTop:Be}=xD({currentSessionId:a,isThinking:A,messagesListRef:R,renderableMessages:Xe}),Ar=()=>L.xs?16:32,as=!!Oe&&Lt&&(!t||P),En=xt?o.jsx(bt,{title:s("chat.compression.tooltip",{count:xt.messagesCompressed,time:sw(xt.createdAt),defaultValue:"Latest compression at {{time}}: {{count}} messages archived"}),children:o.jsx(Ne,{color:"gold",icon:o.jsx(Ab,{}),style:{marginInlineEnd:0,whiteSpace:"nowrap"},children:s("chat.compression.archivedShort",{count:xt.messagesCompressed,defaultValue:"{{count}} archived"})})}):null,$s=ae&&ae.budgetLimit>0?o.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:I.marginXS},children:[o.jsx(D$,{usage:ae,showDetails:!0,size:"small"}),Re&&o.jsxs("span",{style:{fontSize:11,color:I.colorTextSecondary,whiteSpace:"nowrap"},children:["(",Mt," truncated)"]}),En]}):En?o.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:I.marginXS},children:En}):null;return o.jsx(so,{role:"region","aria-label":s("chat.view.chatRegion","Chat conversation"),style:{flex:1,minHeight:0,height:"100%",background:I.colorBgContainer,position:"relative",overflow:"hidden"},children:o.jsxs(ve,{vertical:!0,style:{flex:1,minHeight:0,height:"100%"},children:[a&&o.jsx(J$,{sessionId:a}),r&&a&&Oe&&o.jsx("div",{style:{paddingTop:I.paddingXS,paddingRight:fe(),paddingBottom:0,paddingLeft:fe(),maxWidth:se(),margin:"0 auto",width:"100%"},children:o.jsx(nD,{sessionId:a})}),a&&j&&o.jsx("div",{style:{paddingTop:fe(),paddingRight:fe(),paddingBottom:0,paddingLeft:fe(),maxWidth:se(),margin:"0 auto",width:"100%"},children:o.jsx(v$,{sessionId:a,initialCollapsed:!0})}),a&&w&&o.jsx("div",{style:{paddingTop:I.paddingXS,paddingRight:fe(),paddingBottom:0,paddingLeft:fe(),maxWidth:se(),margin:"0 auto",width:"100%"},children:o.jsx(Y$,{parentSessionId:a})}),as&&o.jsx("div",{style:{paddingTop:I.paddingXS,paddingRight:fe()+Wt,paddingBottom:0,paddingLeft:fe(),maxWidth:se(),margin:"0 auto",width:"100%"},children:P?o.jsxs(ve,{align:"center",justify:"space-between",wrap:"wrap",gap:I.marginXS,children:[o.jsx(OD,{type:"secondary",children:s("chat.selectionToolbar.selectedCount",{selected:ot.length,total:_e.length})}),o.jsxs(he,{size:I.marginXS,wrap:!0,children:[o.jsx(de,{size:"small",onClick:Le,children:s("chat.selectionToolbar.selectAll")}),o.jsx(de,{size:"small",onClick:ue,children:s("chat.selectionToolbar.clear")}),o.jsx(de,{size:"small",icon:o.jsx(Wo,{}),onClick:()=>{ye("markdown")},disabled:ot.length===0,children:s("chat.selectionToolbar.exportMarkdown")}),o.jsx(de,{size:"small",type:"primary",icon:o.jsx(Wo,{}),onClick:()=>{ye("pdf")},disabled:ot.length===0,children:s("chat.selectionToolbar.exportPdf")}),o.jsx(de,{size:"small",icon:o.jsx(Ho,{}),onClick:De,children:s("chat.selectionToolbar.done")})]})]}):o.jsx(ve,{justify:"flex-end",children:o.jsx(bt,{title:s("chat.selectionToolbar.selectMessages"),children:o.jsx(de,{"aria-label":s("chat.selectionToolbar.selectMessages"),icon:o.jsx(Ib,{}),size:"small",onClick:De})})})}),o.jsx(b$,{currentChat:i,currentSessionId:a,convertRenderableEntry:ze,handleDeleteMessage:F,handleDeleteToolMessages:O,handleMessagesScroll:Dt,hasSystemPrompt:Kt,messagesListRef:R,renderableMessages:Xe,rowGap:Ft,showMessagesView:!!Oe,screens:L,workflowDraftId:q==null?void 0:q.id,isThinking:A,padding:fe(),selectionMode:P,selectedMessageIds:ne,selectableMessageIds:Ye,onToggleMessageSelection:N}),(Be||on)&&o.jsxs("div",{style:{position:"absolute",right:Ar(),bottom:L.xs?160:180,display:"flex",flexDirection:"column",gap:I.marginXS,zIndex:1e3},children:[Be&&o.jsx(hf,{type:"default",icon:o.jsx(Lm,{}),style:{position:"relative",inset:"unset"},onClick:()=>{dn()}}),on&&o.jsx(hf,{type:"primary",icon:o.jsx(Gn,{}),style:{position:"relative",inset:"unset"},onClick:()=>{Ue(),rn()}})]}),a&&o.jsx("div",{style:{paddingTop:I.paddingXS,paddingRight:fe(),paddingBottom:0,paddingLeft:fe(),maxWidth:se(),margin:"0 auto",width:"100%"},children:o.jsx(O$,{sessionId:a})}),o.jsx(X1,{sessionId:a,isCenteredLayout:!Oe,maxWidth:Oe?se():"100%",onWorkflowDraftChange:H,showMessagesView:!!Oe,sessionDiffSummary:D,contextUsageIndicator:$s})]})})},FD=5,ND=5,zD=5,BD=e=>{if(!e)return"";try{const t=Date.now()-new Date(e).getTime();if(t<0)return"";const n=Math.floor(t/1e3);if(n<60)return"just now";const s=Math.floor(n/60);if(s<60)return`${s}m ago`;const r=Math.floor(s/60);if(r<24)return`${r}h ago`;const a=Math.floor(r/24);return a<30?`${a}d ago`:new Date(e).toLocaleDateString()}catch{return""}},WD=(e,t)=>t?"is-running":e.lastRunStatus==="error"?"is-error":e.pinned?"is-pinned":"is-idle",bu=({chat:e,onOpen:t,textSecondary:n})=>{const s=G(ur(e.id)),r=e.config.workspacePath?e.config.workspacePath.split("/").pop()||e.config.workspacePath:null;return o.jsxs("button",{type:"button",className:"lotus-home-session-item",onClick:()=>t(e.id),children:[o.jsx("span",{className:`lotus-home-session-status ${WD(e,s)}`}),o.jsxs("span",{className:"lotus-home-session-content",children:[o.jsx("span",{className:"lotus-home-session-title",children:e.title}),o.jsxs("span",{className:"lotus-home-session-meta",style:{color:n},children:[o.jsx("span",{children:BD(e.updatedAt)}),r?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"lotus-home-session-meta-sep"}),o.jsxs("span",{children:[o.jsx(gc,{style:{marginRight:3}}),r]})]}):null,e.messageCount!=null?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"lotus-home-session-meta-sep"}),o.jsxs("span",{children:[o.jsx(yc,{style:{marginRight:3}}),e.messageCount]})]}):null]})]}),s?o.jsx(Ne,{color:"green",bordered:!1,style:{margin:0,fontSize:11},children:"Running"}):null,o.jsx(Vs,{className:"lotus-home-session-arrow"})]})},qD=({onOpenSession:e})=>{const{t}=Ae(),{token:n}=Qe.useToken(),s=G(u=>u.chats),r=f.useCallback(u=>ur(u)(G.getState()),[]),a=f.useMemo(()=>s.filter(u=>r(u.id)).slice(0,ND),[s,r]),i=f.useMemo(()=>s.filter(u=>u.pinned&&!r(u.id)).slice(0,zD),[s,r]),l=f.useMemo(()=>{const u=new Set(a.map(p=>p.id)),m=new Set(i.map(p=>p.id));return s.filter(p=>p.kind!=="child"&&!u.has(p.id)&&!m.has(p.id)).sort((p,g)=>{const b=p.updatedAt?new Date(p.updatedAt).getTime():p.createdAt;return(g.updatedAt?new Date(g.updatedAt).getTime():g.createdAt)-b}).slice(0,FD)},[s,a,i]),c=f.useCallback(u=>{e(u)},[e]);return o.jsx("div",{className:"lotus-home-dashboard",children:o.jsxs("div",{className:"lotus-home-dashboard-inner",children:[o.jsxs("div",{className:"lotus-home-header",children:[o.jsx("span",{className:"lotus-home-header-icon",style:{background:`${n.colorPrimary}15`,color:n.colorPrimary},children:o.jsx(P_,{})}),o.jsxs("div",{className:"lotus-home-header-text",children:[o.jsx("h2",{style:{color:n.colorText},children:t("home.title","Welcome to Bodhi")}),o.jsx("p",{style:{color:n.colorTextSecondary},children:t("home.subtitle","Here's an overview of your workspace.")})]})]}),o.jsx("div",{className:"lotus-home-launcher-shell","data-tour-id":"task-templates",children:o.jsx(dS,{embedded:!0,layoutMode:"staggered"})}),o.jsxs("div",{className:"lotus-home-secondary-sections",children:[a.length>0?o.jsxs("div",{className:"lotus-home-section",children:[o.jsxs("div",{className:"lotus-home-section-title",style:{color:n.colorTextSecondary},children:[o.jsx(Eb,{className:"lotus-home-section-icon",style:{color:"#52c41a"}}),o.jsx("span",{children:t("home.sections.running","Running Now")})]}),o.jsx("div",{className:"lotus-home-session-list",children:a.map(u=>o.jsx(bu,{chat:u,onOpen:c,textSecondary:n.colorTextTertiary},u.id))})]}):null,i.length>0?o.jsxs("div",{className:"lotus-home-section",children:[o.jsxs("div",{className:"lotus-home-section-title",style:{color:n.colorTextSecondary},children:[o.jsx(Em,{className:"lotus-home-section-icon",style:{color:"#faad14"}}),o.jsx("span",{children:t("home.sections.pinned","Pinned")})]}),o.jsx("div",{className:"lotus-home-session-list",children:i.map(u=>o.jsx(bu,{chat:u,onOpen:c,textSecondary:n.colorTextTertiary},u.id))})]}):null,l.length>0?o.jsxs("div",{className:"lotus-home-section",children:[o.jsxs("div",{className:"lotus-home-section-title",style:{color:n.colorTextSecondary},children:[o.jsx(As,{className:"lotus-home-section-icon"}),o.jsx("span",{children:t("home.sections.recent","Recent Sessions")})]}),o.jsx("div",{className:"lotus-home-session-list",children:l.map(u=>o.jsx(bu,{chat:u,onOpen:c,textSecondary:n.colorTextTertiary},u.id))})]}):null,s.length===0?o.jsx("div",{className:"lotus-home-empty-hint",style:{color:n.colorTextTertiary},children:t("home.empty","No sessions yet. Create one to get started!")}):null]})]})})},vr=(e,t,n)=>Math.max(t,Math.min(n,e)),Vl=(e,t)=>t==="horizontal"?e.clientWidth:e.clientHeight,Xl=(e,t,n)=>{const s=Math.max(0,Math.round(e)),r=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(n));return r+a>s?{minFirst:0,maxFirst:s,appliedMinFirst:0,appliedMinSecond:0}:{minFirst:r,maxFirst:s-a,appliedMinFirst:r,appliedMinSecond:a}},rw=({layout:e,first:t,second:n,sizesPx:s,defaultSplitRatio:r=.5,minFirstPx:a=0,minSecondPx:i=0,handleSizePx:l=6,disabled:c=!1,onResizeEnd:u,style:m,className:p})=>{const g=f.useRef(null),b=f.useRef(null),[S,x]=f.useState(null),[k,j]=f.useState(0),[w,M]=f.useState(null),_=f.useMemo(()=>{if(!s)return null;const K=Number(s[0]);return Number.isFinite(K)?K:null},[s]),C=f.useMemo(()=>{if(!s)return null;const K=Number(s[0]),xe=Number(s[1]);if(!Number.isFinite(K)||!Number.isFinite(xe))return null;const se=K+xe;return se<=0||xe<=0?null:vr(K/se,0,1)},[s]);f.useLayoutEffect(()=>{const K=g.current;K&&j(Vl(K,e))},[e]),f.useEffect(()=>{const K=g.current;if(!K)return;const xe=()=>{const se=Vl(K,e);j(fe=>fe===se?fe:se)};if(xe(),typeof ResizeObserver<"u"){const se=new ResizeObserver(xe);return se.observe(K),()=>se.disconnect()}return window.addEventListener("resize",xe),()=>window.removeEventListener("resize",xe)},[e]),f.useEffect(()=>{if(C!==null){M(C);return}M(K=>K??vr(r,.1,.9))},[r,C]);const D=f.useMemo(()=>Xl(k,a,i),[k,a,i]),A=vr(r,.1,.9),B=w??A,F=k>0?Math.round(k*B):null,O=S??(C!==null?F:null)??_??F??0,R=k>0?vr(O,D.minFirst,D.maxFirst):Math.max(0,Math.round(O)),I=f.useCallback(K=>{if(c)return;const xe=g.current;if(!xe)return;K.preventDefault(),K.stopPropagation();const se=e==="horizontal"?K.clientX:K.clientY,fe=Vl(xe,e),Se=Xl(fe,a,i),me=vr(R||Math.round(fe*A),Se.minFirst,Se.maxFirst);b.current={pointerId:K.pointerId,startPos:se,startFirstPx:me,containerSize:fe};try{K.currentTarget.setPointerCapture(K.pointerId)}catch{}},[c,R,A,e,a,i]),L=f.useCallback(K=>{const xe=b.current;if(!xe||K.pointerId!==xe.pointerId)return;K.preventDefault(),K.stopPropagation();const fe=(e==="horizontal"?K.clientX:K.clientY)-xe.startPos,Se=xe.containerSize,me=Xl(Se,a,i),ze=vr(Math.round(xe.startFirstPx+fe),me.minFirst,me.maxFirst);x(ze)},[e,a,i]),U=f.useCallback(K=>{const xe=b.current;if(!xe||xe.pointerId!==K)return;const se=g.current,fe=se?Vl(se,e):xe.containerSize,Se=S??xe.startFirstPx,me=Xl(fe,a,i),ze=vr(Se,me.minFirst,me.maxFirst),st=Math.max(0,fe-ze);x(null),fe>0&&M(vr(ze/fe,0,1)),b.current=null,u==null||u([ze,st])},[e,S,a,i,u]),q=f.useCallback(K=>{K.preventDefault(),K.stopPropagation(),U(K.pointerId)},[U]),H=f.useCallback(K=>{K.preventDefault(),K.stopPropagation(),U(K.pointerId)},[U]),P=e==="horizontal",W=c?"default":P?"col-resize":"row-resize",ne=Math.max(0,Math.round(l));return o.jsxs("div",{ref:g,className:p,style:{display:"flex",flexDirection:P?"row":"column",height:"100%",minHeight:0,minWidth:0,width:"100%",position:"relative",...m},children:[o.jsx("div",{style:{flex:`0 0 ${R}px`,minWidth:P?D.appliedMinFirst:0,minHeight:P?0:D.appliedMinFirst,overflow:"hidden",display:"flex"},children:o.jsx("div",{style:{flex:1,minHeight:0,minWidth:0},children:t})}),o.jsx("div",{style:{flex:"1 1 auto",minWidth:P?D.appliedMinSecond:0,minHeight:P?0:D.appliedMinSecond,overflow:"hidden",display:"flex"},children:o.jsx("div",{style:{flex:1,minHeight:0,minWidth:0},children:n})}),ne>0?o.jsx("div",{role:"separator","aria-orientation":P?"vertical":"horizontal",onPointerDown:I,onPointerMove:L,onPointerUp:q,onPointerCancel:H,style:{position:"absolute",top:P?0:`${R-ne/2}px`,left:P?`${R-ne/2}px`:0,width:P?`${ne}px`:"100%",height:P?"100%":`${ne}px`,cursor:W,touchAction:"none",background:"transparent",zIndex:5}}):null]})},{useToken:UD}=Qe,HD=4,KD=({leafId:e})=>{const{token:t}=UD(),{t:n}=Ae(),s=wt(F=>F.tree),r=wt(F=>F.leafSessionIds),a=wt(F=>F.activeLeafId),i=wt(F=>F.setActiveLeafId),l=wt(F=>F.splitLeaf),c=wt(F=>F.closeLeaf),u=wt(F=>F.setLeafSessionId),m=G(F=>F.selectSession),p=G(F=>F.addChat),g=G(F=>F.systemPrompts),b=G(F=>F.lastSelectedPromptId),S=r[e]??null,x=f.useMemo(()=>rs(s).length,[s]),k=x<HD,j=Db("(max-width: 768px)"),w=x>1,_=w||!!S,C=x>1,D=a===e,A=f.useCallback(F=>{u(e,F),i(e),m(F)},[e,m,i,u]),B=f.useCallback(async()=>{var I,L;const F=g.find(U=>U.id===b),O=(F==null?void 0:F.id)||(g.length>0?((I=g.find(U=>U.id==="general_assistant"))==null?void 0:I.id)||g[0].id:""),R=await p({title:n("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:O,baseSystemPrompt:(F==null?void 0:F.content)||(g.length>0?((L=g.find(U=>U.id==="general_assistant"))==null?void 0:L.content)||g[0].content:""),lastUsedEnhancedPrompt:null}});u(e,R),i(e)},[p,b,g,n,e,u,i]);return o.jsxs("div",{className:"chat-pane-shell",onMouseDownCapture:()=>{ps("pane focus (mouse)",{leafId:e,sessionId:S,prevActiveLeafId:a}),i(e),S&&m(S)},onFocusCapture:()=>{ps("pane focus (focus)",{leafId:e,sessionId:S,prevActiveLeafId:a}),i(e)},style:{height:"100%",minHeight:0,border:C?`1px solid ${D?t.colorPrimaryBorder:t.colorBorderSecondary}`:"none",borderRadius:C?t.borderRadiusLG:0,overflow:"hidden",background:t.colorBgContainer,position:"relative"},children:[!j&&o.jsx("div",{className:"chat-pane-actions",style:{background:t.colorBgElevated,border:`1px solid ${t.colorBorderSecondary}`,borderRadius:10,padding:"2px 4px"},children:o.jsxs(ve,{gap:t.marginXS,children:[o.jsx(de,{size:"small",type:"text",icon:o.jsx(E_,{}),disabled:!k,title:n("chat.multiPane.splitHorizontal"),"aria-label":n("chat.multiPane.splitHorizontal"),onClick:F=>{F.preventDefault(),F.stopPropagation(),ps("pane split request",{leafId:e,layout:"horizontal"}),l(e,"horizontal");const O=wt.getState(),R=O.leafSessionIds[O.activeLeafId]??null;R&&m(R)}}),o.jsx(de,{size:"small",type:"text",icon:o.jsx(R_,{}),disabled:!k,title:n("chat.multiPane.splitVertical"),"aria-label":n("chat.multiPane.splitVertical"),onClick:F=>{F.preventDefault(),F.stopPropagation(),ps("pane split request",{leafId:e,layout:"vertical"}),l(e,"vertical");const O=wt.getState(),R=O.leafSessionIds[O.activeLeafId]??null;R&&m(R)}}),o.jsx(de,{size:"small",type:"text",icon:o.jsx(Ib,{}),disabled:!S,title:n("chat.multiPane.selectMessagesToExport"),"aria-label":n("chat.multiPane.selectMessagesToExport"),onClick:F=>{F.preventDefault(),F.stopPropagation(),S&&window.dispatchEvent(new CustomEvent(fm,{detail:{sessionId:S}}))}}),o.jsx(de,{size:"small",type:"text",danger:!0,icon:o.jsx(Ho,{}),disabled:!_,title:n("chat.multiPane.closePane"),"aria-label":n("chat.multiPane.closePane"),onClick:F=>{F.preventDefault(),F.stopPropagation(),ps("pane close request",{leafId:e}),w?c(e):u(e,null);const O=wt.getState(),R=O.leafSessionIds[O.activeLeafId]??null;m(R)}})]})}),S?o.jsx(Wi,{name:"ChatView",children:o.jsx(LD,{sessionId:S,embedded:!0})}):o.jsx(Wi,{name:"HomeDashboard",children:o.jsx(qD,{onOpenSession:A,onCreateSession:B})})]})},YD=({node:e})=>{const t=wt(s=>s.splitSizesPx[e.id]??null),n=wt(s=>s.setSplitSizesPx);return o.jsx(rw,{layout:e.layout,sizesPx:t,defaultSplitRatio:.5,minFirstPx:240,minSecondPx:240,style:{height:"100%",minHeight:0},onResizeEnd:s=>{n(e.id,s)},first:o.jsx(wm,{node:e.children[0]}),second:o.jsx(wm,{node:e.children[1]})})},wm=({node:e})=>e.type==="leaf"?o.jsx(KD,{leafId:e.id}):o.jsx(YD,{node:e}),dy=()=>{const e=wt(p=>p.tree),t=wt(p=>p.leafSessionIds),n=wt(p=>p.activeLeafId),s=wt(p=>p.setActiveLeafId),r=wt(p=>p.setLeafSessionId),a=wt(p=>p.clearSessionFromAllLeaves),i=G(p=>p.chats),l=G(p=>p.currentSessionId),c=f.useRef(!1),u=f.useMemo(()=>rs(e),[e]),m=f.useMemo(()=>new Set(i.map(p=>p.id)),[i]);return f.useEffect(()=>{u.length!==0&&(u.includes(n)||s(u[0]))},[n,u,s]),f.useEffect(()=>{for(const[p,g]of Object.entries(t))g&&!m.has(g)&&r(p,null)},[m,t,r]),f.useEffect(()=>{if(!l||c.current)return;if(!Object.values(t).some(Boolean)){r(n,l),c.current=!0;return}c.current=!0},[n,l,t,r]),f.useEffect(()=>{const p=new Set(Object.values(t).filter(Boolean));for(const g of p)m.has(g)||a(g)},[m,a,t]),o.jsx("div",{style:{height:"100%",minHeight:0,padding:0},children:o.jsx(wm,{node:e})})},VD=[{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"]}],XD=(e,t)=>{const n=[e.title,e.id,e.kind||"root"];return e.pinned&&n.push("pinned","pin"),t&&n.push("running","processing"),e.config.workspacePath&&n.push(e.config.workspacePath),e.updatedAt&&n.push(e.updatedAt),n.filter(Boolean)},GD=(e,t,n)=>{const s=[];if(e.kind==="child"?s.push(t):s.push(n),e.config.workspacePath&&s.push(e.config.workspacePath),e.updatedAt)try{s.push(new Date(e.updatedAt).toLocaleString())}catch{s.push(e.updatedAt)}return s.join(" • ")},JD=(e,t)=>{const n=t.trim().toLowerCase();return n?e.filter(s=>[s.title,s.subtitle||"",...s.keywords].join(" ").toLowerCase().includes(n)):e},QD=e=>{if(!(e instanceof HTMLElement))return!1;const t=e.tagName.toLowerCase();return e.isContentEditable?!0:t==="input"||t==="textarea"||t==="select"},ZD=()=>{const{t:e}=Ae(),{token:t}=Qe.useToken(),n=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{message:s}=en.useApp(),r=G(L=>L.chats),a=G(L=>L.addChat),i=G(L=>L.lastSelectedPromptId),l=G(L=>L.systemPrompts),c=G(L=>L.executionBySession),[u,m]=f.useState(!1),[p,g]=f.useState(""),[b,S]=f.useState(0),x=f.useRef(null),k=f.useRef(null),j=rr(L=>L.open),w=ho(L=>L.toggleTheme),M=ho(L=>L.themeMode),_=wt(L=>L.sidebar.collapsed),C=wt(L=>L.setSidebarCollapsed),D=Ic(L=>L.mode),A=Ic(L=>L.toggleMode),B=f.useCallback(async()=>{var ne,K;const L=l.find(xe=>xe.id===i),U=(L==null?void 0:L.id)||(l.length>0?((ne=l.find(xe=>xe.id==="general_assistant"))==null?void 0:ne.id)||l[0].id:""),q=await a({title:e("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:U,baseSystemPrompt:(L==null?void 0:L.content)||(l.length>0?((K=l.find(xe=>xe.id==="general_assistant"))==null?void 0:K.content)||l[0].content:""),lastUsedEnhancedPrompt:null}}),{activeLeafId:H,setLeafSessionId:P,setActiveLeafId:W}=wt.getState();P(H,q),W(H)},[a,i,l,e]),F=f.useMemo(()=>{const L=VD.filter(U=>!(D==="simple"&&sS.has(U.tabKey))).map(U=>({id:U.id,kind:"action",title:e(U.titleKey,U.fallbackTitle),subtitle:e(U.subtitleKey||"commandPalette.groups.settings",U.fallbackSubtitle||"System settings"),keywords:[U.tabKey,U.badge||"","settings","config",...U.keywords||[]],icon:o.jsx(Ki,{}),badge:U.badge,onSelect:()=>{j("chat",U.tabKey)}}));return[{id:"new-session",kind:"action",title:e("commandPalette.actions.newSession","Create New Session"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["new","create","session","chat","conversation"],icon:o.jsx(or,{}),badge:e("commandPalette.badges.quickAction","Action"),onSelect:async()=>{await B()}},{id:"toggle-theme",kind:"action",title:M==="dark"?e("commandPalette.actions.switchToLight","Switch to Light Mode"):e("commandPalette.actions.switchToDark","Switch to Dark Mode"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["theme","dark","light","mode","appearance","toggle","color"],icon:o.jsx(A_,{}),badge:M==="dark"?"☀️":"🌙",onSelect:()=>{w()}},{id:"toggle-sidebar",kind:"action",title:_?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:_?o.jsx(Ob,{}):o.jsx(_b,{}),badge:"Layout",onSelect:()=>{C(!_)}},{id:"split-pane",kind:"action",title:e("commandPalette.actions.splitPane","Split Pane"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["split","pane","multi","dual","side","layout"],icon:o.jsx(I_,{}),badge:"Layout",onSelect:()=>{const{tree:U,activeLeafId:q,splitLeaf:H}=wt.getState();rs(U).length<4&&H(q,"vertical")}},...L,{id:"toggle-experience-mode",kind:"action",title:D==="simple"?e("commandPalette.actions.switchToAdvanced","Switch to Advanced Mode"):e("commandPalette.actions.switchToSimple","Switch to Simple Mode"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["mode","simple","advanced","beginner","expert","experience","complexity"],icon:o.jsx(jb,{}),badge:D==="simple"?"Simple":"Advanced",onSelect:()=>{A()}}]},[B,j,w,M,_,C,D,A,e]),O=f.useMemo(()=>r.map(L=>{const U=ur(L.id)({executionBySession:c});return{id:`session-${L.id}`,kind:"session",title:L.title,subtitle:GD(L,e("commandPalette.badges.childSession","Child session"),e("commandPalette.badges.rootSession","Session")),keywords:XD(L,U),icon:o.jsx(yc,{}),badge:L.pinned?e("commandPalette.badges.pinned","Pinned"):U?e("commandPalette.badges.running","Running"):L.kind==="child"?e("commandPalette.badges.child","Child"):void 0,onSelect:()=>{Qc(L.id)}}}),[r,c,e]),R=f.useMemo(()=>[...F,...O],[F,O]),I=f.useMemo(()=>JD(R,p).slice(0,40),[R,p]);return f.useEffect(()=>{S(L=>I.length===0?0:Math.min(L,I.length-1))},[I.length]),f.useEffect(()=>{if(!u)return;const L=window.setTimeout(()=>{var U,q;(U=x.current)==null||U.focus(),(q=x.current)==null||q.select()},0);return()=>window.clearTimeout(L)},[u]),f.useEffect(()=>{if(typeof window>"u")return;const L=U=>{if((U.metaKey||U.ctrlKey)&&U.key.toLowerCase()==="k"){U.preventDefault(),m(H=>!H);return}if(u){if(U.key==="Escape"){U.preventDefault(),m(!1);return}if(!(QD(U.target)&&U.key!=="ArrowUp"&&U.key!=="ArrowDown"&&U.key!=="Enter")){if(U.key==="ArrowDown"){U.preventDefault(),S(H=>I.length===0?0:(H+1)%I.length);return}if(U.key==="ArrowUp"){U.preventDefault(),S(H=>I.length===0?0:H===0?I.length-1:H-1);return}if(U.key==="Enter"){const H=I[b];if(!H)return;U.preventDefault(),(async()=>{try{await H.onSelect(),m(!1),g("")}catch(P){console.error("[CommandPalette] action failed",P),s.error(P instanceof Error?P.message:e("commandPalette.errors.actionFailed","Command failed"))}})()}}}};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[I,s,u,b,e]),f.useEffect(()=>{u||(g(""),S(0))},[u]),f.useEffect(()=>{const L=k.current;if(!L)return;const U=L.querySelector(`[data-command-index="${b}"]`);U==null||U.scrollIntoView({block:"nearest"})},[b]),o.jsx(Xn,{open:u,onCancel:()=>m(!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:n?"none":"blur(18px)",WebkitBackdropFilter:n?"none":"blur(18px)"},body:{padding:0},mask:{backdropFilter:n?"none":"blur(6px)",WebkitBackdropFilter:n?"none":"blur(6px)"}},children:o.jsxs("div",{className:"lotus-command-palette-shell",children:[o.jsxs("div",{className:"lotus-command-palette-search",children:[o.jsx($i,{style:{color:t.colorTextTertiary,fontSize:16}}),o.jsx(et,{ref:x,value:p,onChange:L=>g(L.target.value),variant:"borderless",placeholder:e("commandPalette.searchPlaceholder","Search sessions, settings, and actions"),"aria-label":e("commandPalette.searchPlaceholder","Search sessions, settings, and actions"),suffix:o.jsx(Ke.Text,{type:"secondary",style:{fontSize:12},children:"⌘K"})})]}),o.jsxs("div",{className:"lotus-command-palette-hint",children:[o.jsx(As,{}),o.jsx("span",{children:e("commandPalette.navigationHint","Use ↑↓ to navigate, Enter to open, and Esc to close.")})]}),o.jsx("div",{ref:k,className:"lotus-command-palette-list",role:"listbox",children:I.length===0?o.jsxs("div",{className:"lotus-command-palette-empty",children:[o.jsx(O_,{}),o.jsx("span",{children:e("commandPalette.empty","No matching commands")})]}):I.map((L,U)=>{const q=U===b;return o.jsxs("button",{type:"button",className:`lotus-command-palette-item ${q?"is-selected":""}`,"data-command-index":U,onMouseEnter:()=>S(U),onClick:()=>{(async()=>{try{await L.onSelect(),m(!1),g("")}catch(H){console.error("[CommandPalette] action failed",H),s.error(H instanceof Error?H.message:e("commandPalette.errors.actionFailed","Command failed"))}})()},children:[o.jsx("span",{className:"lotus-command-palette-item-icon",children:L.icon}),o.jsxs("span",{className:"lotus-command-palette-item-content",children:[o.jsxs("span",{className:"lotus-command-palette-item-title-row",children:[o.jsx("span",{className:"lotus-command-palette-item-title",children:L.title}),L.badge?o.jsx(Ne,{bordered:!1,children:L.badge}):null]}),L.subtitle?o.jsx("span",{className:"lotus-command-palette-item-subtitle",children:L.subtitle}):null]})]},L.id)})})]})})},uy="bodhi_open_provider_on_entry",eL=({themeMode:e,onThemeModeChange:t,locale:n,onLocaleChange:s})=>{const r=rr(R=>R.isOpen),a=rr(R=>R.close),{t:i}=Ae(),{token:l}=Qe.useToken(),c=Zc(),u=f.useMemo(()=>zv()==="macos",[]),m=Ct(R=>R.loadProviderConfig);f.useEffect(()=>{m()},[m]),f.useEffect(()=>{localStorage.getItem(uy)==="true"&&(localStorage.removeItem(uy),rr.getState().open("chat","provider"))},[]),nE(),qP(),f.useEffect(()=>{lg.clear(),cg()},[e]),f.useEffect(()=>{lg.clear(),cg()},[c]);const p=wt(R=>R.sidebar.collapsed),g=wt(R=>R.sidebar.widthPx),b=wt(R=>R.sidebar.minWidthPx),S=wt(R=>R.sidebar.maxWidthPx),x=wt(R=>R.setSidebarCollapsed),k=wt(R=>R.setSidebarWidthPx),j=18,w=0,_=!r&&p&&u?44:w,C=0,D=88,A=10,B="none",F=Bm();return o.jsxs(o.Fragment,{children:[o.jsx("a",{href:"#lotus-main-content",className:"lotus-skip-link",style:{position:"absolute",top:-9999,left:-9999,zIndex:1e4,padding:"8px 16px",background:"var(--lotus-main-surface, #fff)",color:"var(--ant-color-primary, #0d9488)",borderRadius:8,fontWeight:600,textDecoration:"none"},onFocus:R=>{R.currentTarget.style.top="8px",R.currentTarget.style.left="8px"},onBlur:R=>{R.currentTarget.style.top="-9999px",R.currentTarget.style.left="-9999px"},children:i("app.skipToContent","Skip to main content")}),o.jsx(ZD,{}),o.jsx(uC,{disabled:r}),o.jsx(so,{style:{minHeight:"100vh",height:"100vh",overflow:"hidden",background:"transparent",display:"flex",flexDirection:"row",position:"relative"},children:o.jsxs("div",{style:{display:"flex",flex:1,minHeight:0,height:"100%",width:"100%",boxSizing:"border-box",paddingTop:_,paddingLeft:w,paddingRight:w,paddingBottom:w,background:"transparent"},children:[r?o.jsx(so,{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:`${j}px 0 0 ${j}px`,border:B,overflow:"hidden"},children:o.jsx(Wi,{name:"SystemSettings",children:o.jsx(FP,{themeMode:e,onThemeModeChange:t,locale:n,onLocaleChange:s,onBack:a})})}):o.jsxs(o.Fragment,{children:[o.jsx(WP,{}),F?o.jsxs(o.Fragment,{children:[o.jsx(Rb,{placement:"left",closable:!1,onClose:()=>x(!0),open:!p,width:"min(86vw, 360px)",styles:{body:{padding:0,background:"var(--lotus-sidebar-bg)"}},children:o.jsx(bp,{})}),o.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{flex:1,height:"100%",minHeight:0,borderRadius:`${j}px`,border:B,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:o.jsx(so,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:o.jsx(dy,{})})})]}):o.jsx(rw,{layout:"horizontal",style:{flex:1,minHeight:0,height:"100%",background:"transparent"},sizesPx:[p?C:g,0],minFirstPx:p?C:b,minSecondPx:320,disabled:p,handleSizePx:p?0:2,onResizeEnd:([R])=>{if(p)return;const I=Math.max(b,Math.min(S,R));k(I)},first:o.jsx("div",{className:"lotus-shell-panel lotus-shell-sidebar",style:{height:"100%",minHeight:0,borderRadius:`${j}px 0 0 ${j}px`,border:B,overflow:"hidden",background:"var(--lotus-sidebar-bg)"},children:o.jsx(bp,{})}),second:o.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{height:"100%",minHeight:0,borderRadius:`0 ${j}px ${j}px 0`,border:B,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:o.jsx(so,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:o.jsx(dy,{})})})})]}),!r&&p?o.jsx(de,{"data-testid":"show-sidebar",type:"text",size:"small",icon:o.jsx(Ob,{}),onClick:()=>x(!1),title:i("layout.showSidebar"),"aria-label":i("layout.showSidebar"),className:"lotus-toolbar-icon lotus-floating-sidebar-toggle",style:{position:"absolute",top:F?8:A,left:F?8:D,zIndex:40,width:36,height:36,borderRadius:12,border:`1px solid ${l.colorBorderSecondary}`,background:l.colorBgElevated,boxShadow:l.boxShadowSecondary}}):null]})})]})},tL="bodhi_open_provider_on_entry",{Title:my,Paragraph:hy}=Ke,nL=()=>{const{t:e}=Ae(),[t,n]=f.useState(!1),[s,r]=f.useState(null),[a,i]=f.useState(!1),l=async c=>{try{r(null),i(!0),await Is.getInstance().markSetupComplete(),c&&localStorage.setItem(tL,"true"),n(!0)}catch(u){console.error("Failed to complete setup:",u),r(e("setup.error.completeFailed"))}finally{i(!1)}};return t?o.jsxs("div",{"data-testid":"setup-complete",className:"setup-complete",children:[o.jsx(my,{level:2,children:e("setup.complete.title")}),o.jsx(hy,{children:e("setup.complete.restartMessage")}),o.jsx(de,{"data-testid":"setup-restart",onClick:()=>window.location.reload(),children:e("setup.complete.restartMessage")})]}):o.jsx("div",{className:"setup-page",children:o.jsxs(Ce,{className:"setup-page__card",children:[o.jsxs("div",{className:"setup-page__hero",children:[o.jsx("div",{className:"setup-page__hero-icon",children:o.jsx(ff,{})}),o.jsx(my,{level:2,style:{marginTop:0},children:e("setup.welcome.heading")}),o.jsx(hy,{type:"secondary",children:e("setup.welcome.description")})]}),o.jsx(Ht,{message:e("setup.welcome.providerHint"),type:"info",showIcon:!0,style:{marginBottom:16}}),o.jsx(Ht,{message:e("setup.welcome.proxyHint"),type:"info",showIcon:!0,style:{marginBottom:24}}),s?o.jsx(Ht,{message:s,type:"error",showIcon:!0,style:{marginBottom:16}}):null,o.jsxs("div",{className:"setup-page__actions",children:[o.jsx(de,{"data-testid":"setup-configure-provider",icon:o.jsx(Ki,{}),onClick:()=>void l(!0),loading:a,children:e("setup.button.configureProvider")}),o.jsx(de,{"data-testid":"setup-get-started",type:"primary",icon:o.jsx(ff,{}),onClick:()=>void l(!1),loading:a,children:e("setup.button.getStarted")})]})]})})},{Title:sL,Text:fy}=Ke,rL=({onVerified:e,verifyPassword:t})=>{const{t:n}=Ae(),[s,r]=f.useState(""),[a,i]=f.useState(null),[l,c]=f.useState(!1),u=async()=>{const m=s.trim();if(!m){i(n("app.passwordGate.validation.required","请输入访问密码"));return}c(!0),i(null);try{await t(m),await e(),r("")}catch(p){const g=p instanceof Error?p.message:n("app.passwordGate.validation.verifyFailed","密码验证失败");i(g)}finally{c(!1)}};return o.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:o.jsx(Ce,{style:{width:"100%",maxWidth:480},children:o.jsxs(he,{direction:"vertical",size:20,style:{width:"100%"},children:[o.jsxs("div",{children:[o.jsx(sL,{level:3,style:{marginBottom:8},children:n("app.passwordGate.title","请输入访问密码")}),o.jsx(fy,{type:"secondary",children:n("app.passwordGate.description","当前访问需要先通过密码验证,验证成功后才会进入应用。")})]}),a?o.jsx(Ht,{type:"error",showIcon:!0,message:a}):null,o.jsxs(he,{direction:"vertical",size:8,style:{width:"100%"},children:[o.jsx(fy,{strong:!0,children:n("app.passwordGate.passwordLabel","访问密码")}),o.jsx(et.Password,{value:s,autoFocus:!0,autoComplete:"current-password",onChange:m=>r(m.target.value),onPressEnter:()=>void u(),placeholder:n("app.passwordGate.passwordPlaceholder","请输入访问密码")})]}),o.jsx(de,{type:"primary",block:!0,loading:l,onClick:()=>void u(),children:n("app.passwordGate.submit","验证并进入")})]})})})};var Ra={},xu={exports:{}},py;function Xt(){return py||(py=1,function(e){function t(n){return n&&n.__esModule?n:{default:n}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}(xu)),xu.exports}var Aa={},gy;function oL(){if(gy)return Aa;gy=1,Object.defineProperty(Aa,"__esModule",{value:!0}),Aa.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 Aa.default=e,Aa}var Ia={},Oa={},$a={},vu={exports:{}},Su={exports:{}},wu={exports:{}},_u={exports:{}},yy;function aL(){return yy||(yy=1,function(e){var t=Sb().default;function n(s,r){if(t(s)!="object"||!s)return s;var a=s[Symbol.toPrimitive];if(a!==void 0){var i=a.call(s,r||"default");if(t(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(s)}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports}(_u)),_u.exports}var by;function iL(){return by||(by=1,function(e){var t=Sb().default,n=aL();function s(r){var a=n(r,"string");return t(a)=="symbol"?a:a+""}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}(wu)),wu.exports}var xy;function lL(){return xy||(xy=1,function(e){var t=iL();function n(s,r,a){return(r=t(r))in s?Object.defineProperty(s,r,{value:a,enumerable:!0,configurable:!0,writable:!0}):s[r]=a,s}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports}(Su)),Su.exports}var vy;function Qo(){return vy||(vy=1,function(e){var t=lL();function n(r,a){var i=Object.keys(r);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(r);a&&(l=l.filter(function(c){return Object.getOwnPropertyDescriptor(r,c).enumerable})),i.push.apply(i,l)}return i}function s(r){for(var a=1;a<arguments.length;a++){var i=arguments[a]!=null?arguments[a]:{};a%2?n(Object(i),!0).forEach(function(l){t(r,l,i[l])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(i)):n(Object(i)).forEach(function(l){Object.defineProperty(r,l,Object.getOwnPropertyDescriptor(i,l))})}return r}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}(vu)),vu.exports}var Da={},Sy;function Zo(){return Sy||(Sy=1,Object.defineProperty(Da,"__esModule",{value:!0}),Da.commonLocale=void 0,Da.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0}),Da}var wy;function cL(){if(wy)return $a;wy=1;var e=Xt().default;Object.defineProperty($a,"__esModule",{value:!0}),$a.default=void 0;var t=e(Qo()),n=Zo(),s=(0,t.default)((0,t.default)({},n.commonLocale),{},{locale:"en_US",today:"Today",now:"Now",backToToday:"Back to today",ok:"OK",clear:"Clear",week:"Week",month:"Month",year:"Year",timeSelect:"select time",dateSelect:"select date",weekSelect:"Choose a week",monthSelect:"Choose a month",yearSelect:"Choose a year",decadeSelect:"Choose a decade",dateFormat:"M/D/YYYY",dateTimeFormat:"M/D/YYYY HH:mm:ss",previousMonth:"Previous month (PageUp)",nextMonth:"Next month (PageDown)",previousYear:"Last year (Control + left)",nextYear:"Next year (Control + right)",previousDecade:"Last decade",nextDecade:"Next decade",previousCentury:"Last century",nextCentury:"Next century"});return $a.default=s,$a}var La={},_y;function ow(){if(_y)return La;_y=1,Object.defineProperty(La,"__esModule",{value:!0}),La.default=void 0;const e={placeholder:"Select time",rangePlaceholder:["Start time","End time"]};return La.default=e,La}var ky;function aw(){if(ky)return Oa;ky=1;var e=Xt().default;Object.defineProperty(Oa,"__esModule",{value:!0}),Oa.default=void 0;var t=e(cL()),n=e(ow());const s={lang:Object.assign({placeholder:"Select date",yearPlaceholder:"Select year",quarterPlaceholder:"Select quarter",monthPlaceholder:"Select month",weekPlaceholder:"Select week",rangePlaceholder:["Start date","End date"],rangeYearPlaceholder:["Start year","End year"],rangeQuarterPlaceholder:["Start quarter","End quarter"],rangeMonthPlaceholder:["Start month","End month"],rangeWeekPlaceholder:["Start week","End week"]},t.default),timePickerLocale:Object.assign({},n.default)};return Oa.default=s,Oa}var Ty;function dL(){if(Ty)return Ia;Ty=1;var e=Xt().default;Object.defineProperty(Ia,"__esModule",{value:!0}),Ia.default=void 0;var t=e(aw());return Ia.default=t.default,Ia}var jy;function uL(){if(jy)return Ra;jy=1;var e=Xt().default;Object.defineProperty(Ra,"__esModule",{value:!0}),Ra.default=void 0;var t=e(oL()),n=e(dL()),s=e(aw()),r=e(ow());const a="${label} is not a valid ${type}",i={locale:"en",Pagination:t.default,DatePicker:s.default,TimePicker:r.default,Calendar:n.default,global:{placeholder:"Please select"},Table:{filterTitle:"Filter menu",filterConfirm:"OK",filterReset:"Reset",filterEmptyText:"No filters",filterCheckAll:"Select all items",filterSearchPlaceholder:"Search in filters",emptyText:"No data",selectAll:"Select current page",selectInvert:"Invert current page",selectNone:"Clear all data",selectionAll:"Select all data",sortTitle:"Sort",expand:"Expand row",collapse:"Collapse row",triggerDesc:"Click to sort descending",triggerAsc:"Click to sort ascending",cancelSort:"Click to cancel sorting"},Tour:{Next:"Next",Previous:"Previous",Finish:"Finish"},Modal:{okText:"OK",cancelText:"Cancel",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Cancel"},Transfer:{titles:["",""],searchPlaceholder:"Search here",itemUnit:"item",itemsUnit:"items",remove:"Remove",selectCurrent:"Select current page",removeCurrent:"Remove current page",selectAll:"Select all data",deselectAll:"Deselect all data",removeAll:"Remove all data",selectInvert:"Invert current page"},Upload:{uploading:"Uploading...",removeFile:"Remove file",uploadError:"Upload error",previewFile:"Preview file",downloadFile:"Download file"},Empty:{description:"No data"},Icon:{icon:"icon"},Text:{edit:"Edit",copy:"Copy",copied:"Copied",expand:"Expand",collapse:"Collapse"},Form:{optional:"(optional)",defaultValidateMessages:{default:"Field validation error for ${label}",required:"Please enter ${label}",enum:"${label} must be one of [${enum}]",whitespace:"${label} cannot be a blank character",date:{format:"${label} date format is invalid",parse:"${label} cannot be converted to a date",invalid:"${label} is an invalid date"},types:{string: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 Ra.default=i,Ra}var ku,Cy;function mL(){return Cy||(Cy=1,ku=uL()),ku}var hL=mL();const fL=po(hL);var Fa={},Na={},My;function pL(){if(My)return Na;My=1,Object.defineProperty(Na,"__esModule",{value:!0}),Na.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 Na.default=e,Na}var za={},Ba={},Wa={},Py;function gL(){if(Py)return Wa;Py=1;var e=Xt().default;Object.defineProperty(Wa,"__esModule",{value:!0}),Wa.default=void 0;var t=e(Qo()),n=Zo(),s=(0,t.default)((0,t.default)({},n.commonLocale),{},{locale:"fr_FR",today:"Aujourd'hui",now:"Maintenant",backToToday:"Aujourd'hui",ok:"OK",clear:"Rétablir",week:"Semaine",month:"Mois",year:"Année",timeSelect:"Sélectionner l'heure",dateSelect:"Sélectionner la date",monthSelect:"Choisissez un mois",yearSelect:"Choisissez une année",decadeSelect:"Choisissez une décennie",dateFormat:"DD/MM/YYYY",dayFormat:"DD",dateTimeFormat:"DD/MM/YYYY HH:mm:ss",previousMonth:"Mois précédent (PageUp)",nextMonth:"Mois suivant (PageDown)",previousYear:"Année précédente (Ctrl + gauche)",nextYear:"Année prochaine (Ctrl + droite)",previousDecade:"Décennie précédente",nextDecade:"Décennie suivante",previousCentury:"Siècle précédent",nextCentury:"Siècle suivant"});return Wa.default=s,Wa}var qa={},Ey;function iw(){if(Ey)return qa;Ey=1,Object.defineProperty(qa,"__esModule",{value:!0}),qa.default=void 0;const e={placeholder:"Sélectionner l'heure",rangePlaceholder:["Heure de début","Heure de fin"]};return qa.default=e,qa}var Ry;function lw(){if(Ry)return Ba;Ry=1;var e=Xt().default;Object.defineProperty(Ba,"__esModule",{value:!0}),Ba.default=void 0;var t=e(gL()),n=e(iw());const s={lang:Object.assign({placeholder:"Sélectionner une date",yearPlaceholder:"Sélectionner une année",quarterPlaceholder:"Sélectionner un trimestre",monthPlaceholder:"Sélectionner un mois",weekPlaceholder:"Sélectionner une semaine",rangePlaceholder:["Date de début","Date de fin"],rangeYearPlaceholder:["Année de début","Année de fin"],rangeMonthPlaceholder:["Mois de début","Mois de fin"],rangeWeekPlaceholder:["Semaine de début","Semaine de fin"]},t.default),timePickerLocale:Object.assign({},n.default)};return Ba.default=s,Ba}var Ay;function yL(){if(Ay)return za;Ay=1;var e=Xt().default;Object.defineProperty(za,"__esModule",{value:!0}),za.default=void 0;var t=e(lw());return za.default=t.default,za}var Iy;function bL(){if(Iy)return Fa;Iy=1;var e=Xt().default;Object.defineProperty(Fa,"__esModule",{value:!0}),Fa.default=void 0;var t=e(pL()),n=e(yL()),s=e(lw()),r=e(iw());const a="La valeur du champ ${label} n'est pas valide pour le type ${type}",i={locale:"fr",Pagination:t.default,DatePicker:s.default,TimePicker:r.default,Calendar:n.default,Table:{filterTitle:"Filtrer",filterConfirm:"OK",filterReset:"Réinitialiser",filterEmptyText:"Aucun filtre",filterCheckAll:"Tout sélectionner",filterSearchPlaceholder:"Chercher dans les filtres",emptyText:"Aucune donnée",selectAll:"Sélectionner la page actuelle",selectInvert:"Inverser la sélection de la page actuelle",selectNone:"Désélectionner toutes les données",selectionAll:"Sélectionner toutes les données",sortTitle:"Trier",expand:"Développer la ligne",collapse:"Réduire la ligne",triggerDesc:"Trier par ordre décroissant",triggerAsc:"Trier par ordre croissant",cancelSort:"Annuler le tri"},Tour:{Next:"Étape suivante",Previous:"Étape précédente",Finish:"Fin de la visite guidée"},Modal:{okText:"OK",cancelText:"Annuler",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Annuler"},Transfer:{titles:["",""],searchPlaceholder:"Rechercher",itemUnit:"élément",itemsUnit:"éléments",remove:"Désélectionner",selectCurrent:"Sélectionner la page actuelle",removeCurrent:"Désélectionner la page actuelle",selectAll:"Sélectionner toutes les données",removeAll:"Désélectionner toutes les données",selectInvert:"Inverser la sélection de la page actuelle"},Upload:{uploading:"Téléchargement...",removeFile:"Effacer le fichier",uploadError:"Erreur de téléchargement",previewFile:"Fichier de prévisualisation",downloadFile:"Télécharger un fichier"},Empty:{description:"Aucune donnée"},Icon:{icon:"icône"},Text:{edit:"Éditer",copy:"Copier",copied:"Copie effectuée",expand:"Développer"},Form:{optional:"(optionnel)",defaultValidateMessages:{default:"Erreur de validation pour le champ ${label}",required:"Le champ ${label} est obligatoire",enum:"La valeur du champ ${label} doit être parmi [${enum}]",whitespace:"La valeur du champ ${label} ne peut pas être vide",date:{format:"La valeur du champ ${label} n'est pas au format date",parse:"La valeur du champ ${label} ne peut pas être convertie vers une date",invalid:"La valeur du champ ${label} n'est pas une date valide"},types:{string: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 Fa.default=i,Fa}var Tu,Oy;function xL(){return Oy||(Oy=1,Tu=bL()),Tu}var vL=xL();const SL=po(vL);var Ua={},Ha={},$y;function wL(){if($y)return Ha;$y=1,Object.defineProperty(Ha,"__esModule",{value:!0}),Ha.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 Ha.default=e,Ha}var Ka={},Ya={},Va={},Dy;function _L(){if(Dy)return Va;Dy=1;var e=Xt().default;Object.defineProperty(Va,"__esModule",{value:!0}),Va.default=void 0;var t=e(Qo()),n=Zo(),s=(0,t.default)((0,t.default)({},n.commonLocale),{},{locale:"hi_IN",today:"आज",now:"अभी",backToToday:"आज तक",ok:"ठीक",clear:"स्पष्ट",week:"सप्ताह",month:"महीना",year:"साल",timeSelect:"समय का चयन करें",dateSelect:"तारीख़ चुनें",weekSelect:"एक सप्ताह चुनें",monthSelect:"एक महीना चुनें",yearSelect:"एक वर्ष चुनें",decadeSelect:"एक दशक चुनें",dateFormat:"M/D/YYYY",dateTimeFormat:"M/D/YYYY HH:mm:ss",previousMonth:"पिछला महीना (पेजअप)",nextMonth:"अगले महीने (पेजडाउन)",previousYear:"पिछले साल (Ctrl + बाएं)",nextYear:"अगले साल (Ctrl + दाहिना)",previousDecade:"पिछला दशक",nextDecade:"अगले दशक",previousCentury:"पीछ्ली शताब्दी",nextCentury:"अगली सदी"});return Va.default=s,Va}var Xa={},Ly;function cw(){if(Ly)return Xa;Ly=1,Object.defineProperty(Xa,"__esModule",{value:!0}),Xa.default=void 0;const e={placeholder:"समय का चयन करें",rangePlaceholder:["आरंभिक समय","अंत समय"]};return Xa.default=e,Xa}var Fy;function dw(){if(Fy)return Ya;Fy=1;var e=Xt().default;Object.defineProperty(Ya,"__esModule",{value:!0}),Ya.default=void 0;var t=e(_L()),n=e(cw());const s={lang:Object.assign({placeholder:"तारीख़ चुनें",yearPlaceholder:"वर्ष चुनें",quarterPlaceholder:"तिमाही चुनें",monthPlaceholder:"महीना चुनिए",weekPlaceholder:"सप्ताह चुनें",rangePlaceholder:["प्रारंभ तिथि","समाप्ति तिथि"],rangeYearPlaceholder:["आरंभिक वर्ष","अंत वर्ष"],rangeMonthPlaceholder:["आरंभिक महीना","अंत महीना"],rangeWeekPlaceholder:["आरंभिक सप्ताह","अंत सप्ताह"]},t.default),timePickerLocale:Object.assign({},n.default)};return Ya.default=s,Ya}var Ny;function kL(){if(Ny)return Ka;Ny=1;var e=Xt().default;Object.defineProperty(Ka,"__esModule",{value:!0}),Ka.default=void 0;var t=e(dw());return Ka.default=t.default,Ka}var zy;function TL(){if(zy)return Ua;zy=1;var e=Xt().default;Object.defineProperty(Ua,"__esModule",{value:!0}),Ua.default=void 0;var t=e(wL()),n=e(kL()),s=e(dw()),r=e(cw());const a="${label} मान्य ${type} नहीं है",i={locale:"hi",Pagination:t.default,DatePicker:s.default,TimePicker:r.default,Calendar:n.default,global:{placeholder:"कृपया चुनें"},Table:{filterTitle:"सूची बंद करें",filterConfirm:"अच्छी तरह से",filterReset:"रीसेट",filterEmptyText:"कोई फ़िल्टर नहीं",emptyText:"कोई जानकारी नहीं",selectAll:"वर्तमान पृष्ठ का चयन करें",selectInvert:"वर्तमान पृष्ठ घुमाएं",selectNone:"सभी डेटा साफ़ करें",selectionAll:"सभी डेटा का चयन करें",sortTitle:"द्वारा क्रमबद्ध करें",expand:"पंक्ति का विस्तार करें",collapse:"पंक्ति संक्षिप्त करें",triggerDesc:"अवरोही क्रमित करने के लिए क्लिक करें",triggerAsc:"आरोही क्रमित करने के लिए क्लिक करें",cancelSort:"छँटाई रद्द करने के लिए क्लिक करें"},Modal:{okText:"अच्छी तरह से",cancelText:"रद्द करना",justOkText:"अच्छी तरह से"},Popconfirm:{okText:"अच्छी तरह से",cancelText:"रद्द करना"},Transfer:{titles:["",""],searchPlaceholder:"यहां खोजें",itemUnit:"तत्त्व",itemsUnit:"विषय-वस्तु",remove:"हटाए",selectCurrent:"वर्तमान पृष्ठ का चयन करें",removeCurrent:"वर्तमान पृष्ठ हटाएं",selectAll:"सभी डेटा का चयन करें",removeAll:"सभी डेटा हटाएं",selectInvert:"वर्तमान पृष्ठ को उल्टा करें"},Upload:{uploading:"अपलोड हो रहा...",removeFile:"फ़ाइल निकालें",uploadError:"अपलोड में त्रुटि",previewFile:"फ़ाइल पूर्वावलोकन",downloadFile:"फ़ाइल डाउनलोड करें"},Empty:{description:"कोई आकड़ा उपलब्ध नहीं है"},Icon:{icon:"आइकन"},Text:{edit:"संपादित करें",copy:"प्रतिलिपि",copied:"कॉपी किया गया",expand:"विस्तार"},Form:{optional:"(ऐच्छिक)",defaultValidateMessages:{default:"${label} के लिए फील्ड सत्यापन त्रुटि",required:"कृपया ${label} दर्ज करें",enum:"${label} [${enum}] में से एक होना चाहिए",whitespace:"${label} एक खाली अक्षर नहीं हो सकता",date:{format:"${label} तिथि प्रारूप अमान्य है",parse:"${label} को तारीख में नहीं बदला जा सकता",invalid:"${label} एक अमान्य तिथि है"},types:{string: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 Ua.default=i,Ua}var ju,By;function jL(){return By||(By=1,ju=TL()),ju}var CL=jL();const ML=po(CL);var Ga={},Ja={},Wy;function PL(){if(Wy)return Ja;Wy=1,Object.defineProperty(Ja,"__esModule",{value:!0}),Ja.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 Ja.default=e,Ja}var Qa={},Za={},ei={},qy;function EL(){if(qy)return ei;qy=1;var e=Xt().default;Object.defineProperty(ei,"__esModule",{value:!0}),ei.default=void 0;var t=e(Qo()),n=Zo(),s=(0,t.default)((0,t.default)({},n.commonLocale),{},{locale:"ja_JP",today:"今日",now:"現在時刻",backToToday:"今日に戻る",ok:"確定",timeSelect:"時間を選択",dateSelect:"日時を選択",weekSelect:"週を選択",clear:"クリア",week:"週",month:"月",year:"年",previousMonth:"前月 (ページアップキー)",nextMonth:"翌月 (ページダウンキー)",monthSelect:"月を選択",yearSelect:"年を選択",decadeSelect:"年代を選択",yearFormat:"YYYY年",dateFormat:"YYYY年M月D日",dateTimeFormat:"YYYY年M月D日 HH時mm分ss秒",previousYear:"前年 (Controlを押しながら左キー)",nextYear:"翌年 (Controlを押しながら右キー)",previousDecade:"前の年代",nextDecade:"次の年代",previousCentury:"前の世紀",nextCentury:"次の世紀",monthBeforeYear:!1});return ei.default=s,ei}var ti={},Uy;function uw(){if(Uy)return ti;Uy=1,Object.defineProperty(ti,"__esModule",{value:!0}),ti.default=void 0;const e={placeholder:"時間を選択",rangePlaceholder:["開始時間","終了時間"]};return ti.default=e,ti}var Hy;function mw(){if(Hy)return Za;Hy=1;var e=Xt().default;Object.defineProperty(Za,"__esModule",{value:!0}),Za.default=void 0;var t=e(EL()),n=e(uw());const s={lang:Object.assign({placeholder:"日付を選択",yearPlaceholder:"年を選択",quarterPlaceholder:"四半期を選択",monthPlaceholder:"月を選択",weekPlaceholder:"週を選択",rangePlaceholder:["開始日付","終了日付"],rangeYearPlaceholder:["開始年","終了年"],rangeMonthPlaceholder:["開始月","終了月"],rangeQuarterPlaceholder:["開始四半期","終了四半期"],rangeWeekPlaceholder:["開始週","終了週"],shortWeekDays:["日","月","火","水","木","金","土"],shortMonths:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"]},t.default),timePickerLocale:Object.assign({},n.default)};return Za.default=s,Za}var Ky;function RL(){if(Ky)return Qa;Ky=1;var e=Xt().default;Object.defineProperty(Qa,"__esModule",{value:!0}),Qa.default=void 0;var t=e(mw());return Qa.default=t.default,Qa}var Yy;function AL(){if(Yy)return Ga;Yy=1;var e=Xt().default;Object.defineProperty(Ga,"__esModule",{value:!0}),Ga.default=void 0;var t=e(PL()),n=e(RL()),s=e(mw()),r=e(uw());const a="${label}は有効な${type}ではありません",i={locale:"ja",Pagination:t.default,DatePicker:s.default,TimePicker:r.default,Calendar:n.default,global:{placeholder:"選んでください"},Table:{filterTitle:"フィルター",filterConfirm:"OK",filterReset:"リセット",filterEmptyText:"フィルターなし",filterCheckAll:"すべてを選択",filterSearchPlaceholder:"フィルターで検索",emptyText:"データなし",selectAll:"ページ単位で選択",selectInvert:"ページ単位で反転",selectNone:"クリア",selectionAll:"すべてを選択",sortTitle:"ソート",expand:"展開する",collapse:"折り畳む",triggerDesc:"クリックで降順にソート",triggerAsc:"クリックで昇順にソート",cancelSort:"ソートをキャンセル"},Tour:{Next:"次",Previous:"前の",Finish:"仕上げる"},Modal:{okText:"OK",cancelText:"キャンセル",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"キャンセル"},Transfer:{titles:["",""],searchPlaceholder:"ここを検索",itemUnit:"アイテム",itemsUnit:"アイテム",remove:"削除",selectCurrent:"現在のページを選択",removeCurrent:"現在のページを削除",selectAll:"ページ単位で選択",deselectAll:"すべてのデータの選択を解除する",removeAll:"ページ単位で削除",selectInvert:"ページ単位で反転"},Upload:{uploading:"アップロード中...",removeFile:"ファイルを削除",uploadError:"アップロードエラー",previewFile:"ファイルをプレビュー",downloadFile:"ダウンロードファイル"},Empty:{description:"データがありません"},Icon:{icon:"アイコン"},Text:{edit:"編集",copy:"コピー",copied:"コピーされました",expand:"拡大する",collapse:"崩壊"},Form:{optional:"(オプション)",defaultValidateMessages:{default:"${label}のフィールド検証エラー",required:"${label}を入力してください",enum:"${label}は[${enum}]のいずれかである必要があります",whitespace:"${label}は空白文字にすることはできません",date:{format:"${label}の日付形式は不正です",parse:"${label}は日付に変換できません",invalid:"${label}は不正な日付です"},types:{string: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 Ga.default=i,Ga}var Cu,Vy;function IL(){return Vy||(Vy=1,Cu=AL()),Cu}var OL=IL();const $L=po(OL);var ni={},si={},Xy;function DL(){if(Xy)return si;Xy=1,Object.defineProperty(si,"__esModule",{value:!0}),si.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 si.default=e,si}var ri={},oi={},ai={},Gy;function LL(){if(Gy)return ai;Gy=1;var e=Xt().default;Object.defineProperty(ai,"__esModule",{value:!0}),ai.default=void 0;var t=e(Qo()),n=Zo(),s=(0,t.default)((0,t.default)({},n.commonLocale),{},{locale:"zh_CN",today:"今天",now:"此刻",backToToday:"返回今天",ok:"确定",timeSelect:"选择时间",dateSelect:"选择日期",weekSelect:"选择周",clear:"清除",week:"周",month:"月",year:"年",previousMonth:"上个月 (翻页上键)",nextMonth:"下个月 (翻页下键)",monthSelect:"选择月份",yearSelect:"选择年份",decadeSelect:"选择年代",previousYear:"上一年 (Control键加左方向键)",nextYear:"下一年 (Control键加右方向键)",previousDecade:"上一年代",nextDecade:"下一年代",previousCentury:"上一世纪",nextCentury:"下一世纪",yearFormat:"YYYY年",cellDateFormat:"D",monthBeforeYear:!1});return ai.default=s,ai}var ii={},Jy;function hw(){if(Jy)return ii;Jy=1,Object.defineProperty(ii,"__esModule",{value:!0}),ii.default=void 0;const e={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return ii.default=e,ii}var Qy;function fw(){if(Qy)return oi;Qy=1;var e=Xt().default;Object.defineProperty(oi,"__esModule",{value:!0}),oi.default=void 0;var t=e(LL()),n=e(hw());const s={lang:Object.assign({placeholder:"请选择日期",yearPlaceholder:"请选择年份",quarterPlaceholder:"请选择季度",monthPlaceholder:"请选择月份",weekPlaceholder:"请选择周",rangePlaceholder:["开始日期","结束日期"],rangeYearPlaceholder:["开始年份","结束年份"],rangeMonthPlaceholder:["开始月份","结束月份"],rangeQuarterPlaceholder:["开始季度","结束季度"],rangeWeekPlaceholder:["开始周","结束周"]},t.default),timePickerLocale:Object.assign({},n.default)};return s.lang.ok="确定",oi.default=s,oi}var Zy;function FL(){if(Zy)return ri;Zy=1;var e=Xt().default;Object.defineProperty(ri,"__esModule",{value:!0}),ri.default=void 0;var t=e(fw());return ri.default=t.default,ri}var eb;function NL(){if(eb)return ni;eb=1;var e=Xt().default;Object.defineProperty(ni,"__esModule",{value:!0}),ni.default=void 0;var t=e(DL()),n=e(FL()),s=e(fw()),r=e(hw());const a="${label}不是一个有效的${type}",i={locale:"zh-cn",Pagination:t.default,DatePicker:s.default,TimePicker:r.default,Calendar:n.default,global:{placeholder:"请选择"},Table:{filterTitle:"筛选",filterConfirm:"确定",filterReset:"重置",filterEmptyText:"无筛选项",filterCheckAll:"全选",filterSearchPlaceholder:"在筛选项中搜索",emptyText:"暂无数据",selectAll:"全选当页",selectInvert:"反选当页",selectNone:"清空所有",selectionAll:"全选所有",sortTitle:"排序",expand:"展开行",collapse:"关闭行",triggerDesc:"点击降序",triggerAsc:"点击升序",cancelSort:"取消排序"},Modal:{okText:"确定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"结束导览"},Popconfirm:{cancelText:"取消",okText:"确定"},Transfer:{titles:["",""],searchPlaceholder:"请输入搜索内容",itemUnit:"项",itemsUnit:"项",remove:"删除",selectCurrent:"全选当页",removeCurrent:"删除当页",selectAll:"全选所有",deselectAll:"取消全选",removeAll:"删除全部",selectInvert:"反选当页"},Upload:{uploading:"文件上传中",removeFile:"删除文件",uploadError:"上传错误",previewFile:"预览文件",downloadFile:"下载文件"},Empty:{description:"暂无数据"},Icon:{icon:"图标"},Text:{edit:"编辑",copy:"复制",copied:"复制成功",expand:"展开",collapse:"收起"},Form:{optional:"(可选)",defaultValidateMessages:{default:"字段验证错误${label}",required:"请输入${label}",enum:"${label}必须是其中一个[${enum}]",whitespace:"${label}不能为空字符",date:{format:"${label}日期格式无效",parse:"${label}不能转换为日期",invalid:"${label}是一个无效日期"},types:{string: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 ni.default=i,ni}var Mu,tb;function zL(){return tb||(tb=1,Mu=NL()),Mu}var BL=zL();const WL=po(BL);var li={},ci={},nb;function qL(){if(nb)return ci;nb=1,Object.defineProperty(ci,"__esModule",{value:!0}),ci.default=void 0;var e={items_per_page:"條/頁",jump_to:"跳至",jump_to_confirm:"確定",page:"頁",prev_page:"上一頁",next_page:"下一頁",prev_5:"向前 5 頁",next_5:"向後 5 頁",prev_3:"向前 3 頁",next_3:"向後 3 頁",page_size:"頁碼"};return ci.default=e,ci}var di={},ui={},mi={},sb;function UL(){if(sb)return mi;sb=1;var e=Xt().default;Object.defineProperty(mi,"__esModule",{value:!0}),mi.default=void 0;var t=e(Qo()),n=Zo(),s=(0,t.default)((0,t.default)({},n.commonLocale),{},{locale:"zh_TW",today:"今天",now:"此刻",backToToday:"返回今天",ok:"確定",timeSelect:"選擇時間",dateSelect:"選擇日期",weekSelect:"選擇周",clear:"清除",week:"週",month:"月",year:"年",previousMonth:"上個月 (翻頁上鍵)",nextMonth:"下個月 (翻頁下鍵)",monthSelect:"選擇月份",yearSelect:"選擇年份",decadeSelect:"選擇年代",yearFormat:"YYYY年",dateFormat:"YYYY年M月D日",dateTimeFormat:"YYYY年M月D日 HH時mm分ss秒",previousYear:"上一年 (Control鍵加左方向鍵)",nextYear:"下一年 (Control鍵加右方向鍵)",previousDecade:"上一年代",nextDecade:"下一年代",previousCentury:"上一世紀",nextCentury:"下一世紀",cellDateFormat:"D",monthBeforeYear:!1});return mi.default=s,mi}var hi={},rb;function pw(){if(rb)return hi;rb=1,Object.defineProperty(hi,"__esModule",{value:!0}),hi.default=void 0;const e={placeholder:"請選擇時間"};return hi.default=e,hi}var ob;function gw(){if(ob)return ui;ob=1;var e=Xt().default;Object.defineProperty(ui,"__esModule",{value:!0}),ui.default=void 0;var t=e(UL()),n=e(pw());const s={lang:Object.assign({placeholder:"請選擇日期",yearPlaceholder:"請選擇年份",quarterPlaceholder:"請選擇季度",monthPlaceholder:"請選擇月份",weekPlaceholder:"請選擇周",rangePlaceholder:["開始日期","結束日期"],rangeYearPlaceholder:["開始年份","結束年份"],rangeMonthPlaceholder:["開始月份","結束月份"],rangeQuarterPlaceholder:["開始季度","結束季度"],rangeWeekPlaceholder:["開始周","結束周"]},t.default),timePickerLocale:Object.assign({},n.default)};return s.lang.ok="確 定",ui.default=s,ui}var ab;function HL(){if(ab)return di;ab=1;var e=Xt().default;Object.defineProperty(di,"__esModule",{value:!0}),di.default=void 0;var t=e(gw());return di.default=t.default,di}var ib;function KL(){if(ib)return li;ib=1;var e=Xt().default;Object.defineProperty(li,"__esModule",{value:!0}),li.default=void 0;var t=e(qL()),n=e(HL()),s=e(gw()),r=e(pw());const a="${label}不是一個有效的${type}",i={locale:"zh-tw",Pagination:t.default,DatePicker:s.default,TimePicker:r.default,Calendar:n.default,global:{placeholder:"請選擇"},Table:{filterTitle:"篩選器",filterConfirm:"確定",filterReset:"重置",filterEmptyText:"無篩選項",filterCheckAll:"全選",filterSearchPlaceholder:"在篩選項中搜尋",emptyText:"暫無數據",selectAll:"全部選取",selectInvert:"反向選取",selectNone:"清空所有",selectionAll:"全選所有",sortTitle:"排序",expand:"展開行",collapse:"關閉行",triggerDesc:"點擊降序",triggerAsc:"點擊升序",cancelSort:"取消排序"},Modal:{okText:"確定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"結束導覽"},Popconfirm:{okText:"確定",cancelText:"取消"},Transfer:{titles:["",""],searchPlaceholder:"搜尋資料",itemUnit:"項目",itemsUnit:"項目",remove:"删除",selectCurrent:"全選當頁",removeCurrent:"删除當頁",selectAll:"全選所有",removeAll:"删除全部",selectInvert:"反選當頁"},Upload:{uploading:"正在上傳...",removeFile:"刪除檔案",uploadError:"上傳失敗",previewFile:"檔案預覽",downloadFile:"下载文件"},Empty:{description:"無此資料"},Icon:{icon:"圖標"},Text:{edit:"編輯",copy:"複製",copied:"複製成功",expand:"展開",collapse:"收起"},Form:{optional:"(可選)",defaultValidateMessages:{default:"字段驗證錯誤${label}",required:"請輸入${label}",enum:"${label}必須是其中一個[${enum}]",whitespace:"${label}不能為空字符",date:{format:"${label}日期格式無效",parse:"${label}不能轉換為日期",invalid:"${label}是一個無效日期"},types:{string: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 li.default=i,li}var Pu,lb;function YL(){return lb||(lb=1,Pu=KL()),Pu}var VL=YL();const XL=po(VL),cb=e=>{switch(e){case"zh-CN":return WL;case"zh-TW":return XL;case"fr-FR":return SL;case"ja-JP":return $L;case"hi-IN":return ML;default:return fL}};async function GL(){const e=Wn.getInstance();for(const t of Object.keys(localStorage))if(t.startsWith("chat-model-options-cache-v1:")){const n=t.split(":")[1];try{const s=localStorage.getItem(t);if(s){const r=JSON.parse(s);r&&Array.isArray(r.options)&&(await e.saveModelOptionsCache(n,r.options,r.timestamp),localStorage.removeItem(t))}}catch{localStorage.removeItem(t)}}for(const t of Object.keys(localStorage))if(t.startsWith("chat-session-diff-collapse:")){const n=t.split(":")[1];try{const s=localStorage.getItem(t);if(s){const r=JSON.parse(s);r&&typeof r.isExpanded=="boolean"&&(await e.saveDiffCollapse(n,{isExpanded:r.isExpanded,expandedFiles:r.expandedFiles||[]}),localStorage.removeItem(t))}}catch{localStorage.removeItem(t)}}for(const t of Object.keys(localStorage))if(t.startsWith("chat-session-tool-collapse:")){const n=t.split(":");if(n.length>=3){const s=n[1],r=n.slice(2).join(":");try{const a=localStorage.getItem(t);if(a){const i=JSON.parse(a);i&&typeof i.isExpanded=="boolean"&&(await e.saveToolSessionCollapse(s,r,{isExpanded:i.isExpanded,expandedTools:i.expandedTools||[]}),localStorage.removeItem(t))}}catch{localStorage.removeItem(t)}}}try{const t=localStorage.getItem("chat_input_reasoning_by_session_v1");if(t){const n=JSON.parse(t);for(const[s,r]of Object.entries(n))typeof r=="string"&&await e.saveInputReasoning(s,r);localStorage.removeItem("chat_input_reasoning_by_session_v1")}}catch{localStorage.removeItem("chat_input_reasoning_by_session_v1")}try{const t=localStorage.getItem("chat_input_reasoning_last_used_v1");t&&typeof t=="string"&&(await e.saveLastUsedReasoningEffort(t),localStorage.removeItem("chat_input_reasoning_last_used_v1"))}catch{localStorage.removeItem("chat_input_reasoning_last_used_v1")}for(const t of Object.keys(localStorage))if(t.startsWith("chat_scroll_anchor_v2:")){const n=t.split(":")[1];try{const s=localStorage.getItem(t);if(s){const r=JSON.parse(s);r&&r.v===1&&typeof r.anchorId=="string"&&(await e.saveScrollAnchor(n,r),localStorage.removeItem(t))}}catch{localStorage.removeItem(t)}}localStorage.removeItem("chat_scroll_anchors_v1")}const JL="copilot_ui_theme_v1",_m={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)"},km={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)"},Tm={Tag:{defaultBg:"rgba(13, 148, 136, 0.1)",defaultColor:"#0f766e"},Table:{bodySortBg:"rgba(13, 148, 136, 0.08)"}},jm={Tag:{defaultBg:"rgba(45, 212, 191, 0.18)",defaultColor:"#ccfbf1"},Table:{bodySortBg:"rgba(45, 212, 191, 0.14)"}},db={..._m,colorBgElevated:"#ffffff",colorBgSpotlight:"#0f172a",colorFillTertiary:"#f3f7f6"},ub={...km,colorBgElevated:"#0f1b18",colorBgSpotlight:"#22332f",colorFillTertiary:"#162622"},mb={...Tm,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"}},hb={...jm,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 QL(){const{t:e}=Ae(),t=ho(_=>_.themeMode),n=ho(_=>_.setThemeMode),[s,r]=f.useState(()=>qw()),[a,i]=f.useState(()=>Rc()),[l,c]=f.useState(null),[u,m]=f.useState(null),[p,g]=f.useState(0),[b,S]=f.useState(null),[x,k]=f.useState(!1);if(f.useEffect(()=>{localStorage.setItem(JL,t)},[t]),f.useEffect(()=>{localStorage.setItem(Uw,s),bs.changeLanguage(s)},[s]),f.useEffect(()=>{let _=!1;const C=Date.now(),D=async()=>{try{const A=Is.getInstance(),B=await A.getAccessStatus();if(_)return;if(m(null),S(B),B.requires_password&&!x){c(!1);return}const F=await A.getSetupStatus();if(_)return;c(F.is_complete)}catch(A){if(_)return;const B=Date.now()-C;if(B>=2e4){const R=Vo(),I=A instanceof Error&&A.message.trim()?A.message:"Unknown error";m(e("app.backendNotReachable",{baseUrl:R,message:I}));return}const O=Math.min(500+Math.floor(B/2),2e3);setTimeout(()=>{_||D()},O)}};return D(),()=>{_=!0}},[x,p,e]),f.useEffect(()=>{document.body.setAttribute("data-theme",t)},[t]),f.useEffect(()=>{const _=()=>{const C=Rc();i(C),document.body.setAttribute("data-vdi-safe",C?"true":"false");const D=document.getElementById("root");D&&D.setAttribute("data-vdi-safe",C?"true":"false")};return _(),window.addEventListener("storage",_),window.addEventListener("lotus-vdi-safe-mode-change",_),()=>{window.removeEventListener("storage",_),window.removeEventListener("lotus-vdi-safe-mode-change",_)}},[]),f.useEffect(()=>{var C;const _=(C=window.__TAURI_INTERNALS__)==null?void 0:C.invoke;typeof _=="function"&&_("set_window_theme",{theme:t}).catch(D=>{console.warn("[App] Failed to sync native window theme:",D)})},[t]),f.useEffect(()=>{l&&ix()},[l]),f.useEffect(()=>{const _=Wn.getInstance();_.cleanupStaleData(30).catch(D=>{console.warn("[App] Failed to cleanup stale storage data:",D)});const C=setInterval(()=>{_.cleanupStaleData(30).catch(()=>{})},24*60*60*1e3);return()=>clearInterval(C)},[]),f.useEffect(()=>{const _=setTimeout(()=>{GL().catch(C=>{console.warn("[App] Storage migration failed:",C)})},5e3);return()=>clearTimeout(_)},[]),b!=null&&b.requires_password&&!x)return o.jsx(pf,{locale:cb(s),theme:{token:t==="dark"?a?ub:km:a?db:_m,algorithm:t==="dark"?Qe.darkAlgorithm:Qe.defaultAlgorithm,components:t==="dark"?a?hb:jm:a?mb:Tm},children:o.jsx(en,{children:o.jsx(Wi,{name:"PasswordGatePage",children:o.jsx(rL,{verifyPassword:async _=>{await Is.getInstance().verifyAccessPassword(_)},onVerified:async()=>{k(!0),m(null),g(_=>_+1)}})})})});if(l===null)return u?o.jsxs("div",{style:{padding:40,textAlign:"center"},children:[o.jsx("div",{style:{marginBottom:12},children:u}),o.jsx(de,{type:"primary",onClick:()=>{m(null),S(null),c(null),g(_=>_+1)},children:e("app.retry")})]}):o.jsx("div",{style:{padding:40,textAlign:"center"},children:e("app.loading")});const j=l?o.jsx(eL,{themeMode:t,onThemeModeChange:n,locale:s,onLocaleChange:r}):o.jsx(nL,{}),w=t==="dark"?a?ub:km:a?db:_m,M=t==="dark"?a?hb:jm:a?mb:Tm;return o.jsx(pf,{locale:cb(s),theme:{token:w,algorithm:t==="dark"?Qe.darkAlgorithm:Qe.defaultAlgorithm,components:M},children:o.jsx(en,{children:o.jsx(Wi,{name:"App",children:o.jsx("div",{style:{position:"relative"},children:j})})})})}const TF=Object.freeze(Object.defineProperty({__proto__:null,default:QL},Symbol.toStringTag,{value:"Module"}));export{TF as A,Ii as C,at as a,Jt as d,Jo as p,G as u,l1 as w};