@bigduu/lotus 2026.3.106 → 2026.3.111
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/App-BE21QjOb.js +247 -0
- package/dist/assets/{App-DuLzjNFa.css → App-DIj4bUd8.css} +1 -1
- package/dist/assets/{_basePickBy-DWVgPMAB.js → _basePickBy-B_yEwOSD.js} +1 -1
- package/dist/assets/{_baseUniq-_NKhoFXr.js → _baseUniq-P6d782Sk.js} +1 -1
- package/dist/assets/{architectureDiagram-VXUJARFQ-U9RcPH2N.js → architectureDiagram-VXUJARFQ-DZqZto7W.js} +1 -1
- package/dist/assets/{blockDiagram-VD42YOAC-EDx61oZH.js → blockDiagram-VD42YOAC-ja9Insq0.js} +1 -1
- package/dist/assets/{c4Diagram-YG6GDRKO-Dnp_O5g0.js → c4Diagram-YG6GDRKO-DpMgvpVJ.js} +1 -1
- package/dist/assets/{chunk-4BX2VUAB-BePiSovW.js → chunk-4BX2VUAB-BEgOFc9T.js} +1 -1
- package/dist/assets/{chunk-55IACEB6-GsmkzHKQ.js → chunk-55IACEB6-LEtICOYk.js} +1 -1
- package/dist/assets/{chunk-B4BG7PRW-CLyc4Tbj.js → chunk-B4BG7PRW-CPb7q-_J.js} +1 -1
- package/dist/assets/{chunk-DI55MBZ5-OaDB3cNe.js → chunk-DI55MBZ5-DY5JLB9Z.js} +1 -1
- package/dist/assets/{chunk-FMBD7UC4--Q4cKEfx.js → chunk-FMBD7UC4-AwmWm_kv.js} +1 -1
- package/dist/assets/{chunk-QN33PNHL-DYuUSRud.js → chunk-QN33PNHL-7p2qAfFA.js} +1 -1
- package/dist/assets/{chunk-QZHKN3VN-Br2yqP-Z.js → chunk-QZHKN3VN-DxypS4En.js} +1 -1
- package/dist/assets/{chunk-TZMSLE5B-Z63HAHA5.js → chunk-TZMSLE5B-DavZ7f53.js} +1 -1
- package/dist/assets/classDiagram-2ON5EDUG-BC2Rqfys.js +1 -0
- package/dist/assets/classDiagram-v2-WZHVMYZB-BC2Rqfys.js +1 -0
- package/dist/assets/clone-1-Ton2uv.js +1 -0
- package/dist/assets/{cose-bilkent-S5V4N54A-Ba0KWrtt.js → cose-bilkent-S5V4N54A-CUua84VE.js} +1 -1
- package/dist/assets/{dagre-6UL2VRFP-eakb8DDD.js → dagre-6UL2VRFP-CFCiN4cw.js} +1 -1
- package/dist/assets/{diagram-PSM6KHXK-CDMsOtQm.js → diagram-PSM6KHXK-LaxqZ29_.js} +1 -1
- package/dist/assets/{diagram-QEK2KX5R-5Qvq0wIW.js → diagram-QEK2KX5R-DsI95g6H.js} +1 -1
- package/dist/assets/{diagram-S2PKOQOG-B-PGnlsL.js → diagram-S2PKOQOG-t6_j1W4K.js} +1 -1
- package/dist/assets/{erDiagram-Q2GNP2WA-Co_XI4OJ.js → erDiagram-Q2GNP2WA-C-Y2vVDJ.js} +1 -1
- package/dist/assets/{flowDiagram-NV44I4VS-reQO4edI.js → flowDiagram-NV44I4VS-XIagCyBZ.js} +1 -1
- package/dist/assets/{ganttDiagram-JELNMOA3-DvFzkKJX.js → ganttDiagram-JELNMOA3-BmI36pAC.js} +1 -1
- package/dist/assets/{gitGraphDiagram-V2S2FVAM-D6s0JhDP.js → gitGraphDiagram-V2S2FVAM-C7qyL2_l.js} +1 -1
- package/dist/assets/{graph-CXsaN0Gm.js → graph-BwEqHpzs.js} +1 -1
- package/dist/assets/{index-uBFcBz8p.js → index-DMfxTHKB.js} +1 -1
- package/dist/assets/{index-DIwhPdo2.js → index-DN4T64sQ.js} +1 -1
- package/dist/assets/{index-DOm9R_-7.js → index-Df-GVUQB.js} +1 -1
- package/dist/assets/{index-B2hxunKJ.js → index-Ds0z78TD.js} +1 -1
- package/dist/assets/{index-BVQO64L2.js → index-eDRjOrKd.js} +1 -1
- package/dist/assets/{index.es-C0KRJwo1.js → index.es-hnFjDpXl.js} +1 -1
- package/dist/assets/{infoDiagram-HS3SLOUP-238dMyeb.js → infoDiagram-HS3SLOUP-DmzD1_9k.js} +1 -1
- package/dist/assets/{journeyDiagram-XKPGCS4Q-DbtBs1Gn.js → journeyDiagram-XKPGCS4Q-CQxAXogN.js} +1 -1
- package/dist/assets/{kanban-definition-3W4ZIXB7-MKCv6diY.js → kanban-definition-3W4ZIXB7-BQ7lsbrO.js} +1 -1
- package/dist/assets/{layout-CeaMb8qs.js → layout-C0ZV9Aq9.js} +1 -1
- package/dist/assets/{main-BpLLxKjn.js → main-fT0cr1NN.js} +6 -6
- package/dist/assets/{mindmap-definition-VGOIOE7T-CZ7X7DPT.js → mindmap-definition-VGOIOE7T-BgVzrs3B.js} +1 -1
- package/dist/assets/{pieDiagram-ADFJNKIX-D1hZ2_fe.js → pieDiagram-ADFJNKIX-BIApgcRo.js} +1 -1
- package/dist/assets/{quadrantDiagram-AYHSOK5B-TulHOGP2.js → quadrantDiagram-AYHSOK5B-nkQQggfX.js} +1 -1
- package/dist/assets/{requirementDiagram-UZGBJVZJ-b0mw_Ccv.js → requirementDiagram-UZGBJVZJ-ek_pnEPB.js} +1 -1
- package/dist/assets/{sankeyDiagram-TZEHDZUN-DItRVaUj.js → sankeyDiagram-TZEHDZUN-CAuGjYnS.js} +1 -1
- package/dist/assets/{sequenceDiagram-WL72ISMW-B3rTiWIg.js → sequenceDiagram-WL72ISMW-DZcj3siC.js} +1 -1
- package/dist/assets/{stateDiagram-FKZM4ZOC-CPac79Qj.js → stateDiagram-FKZM4ZOC-KpOz7vrk.js} +1 -1
- package/dist/assets/stateDiagram-v2-4FDKWEC3-BbaFt78-.js +1 -0
- package/dist/assets/{timeline-definition-IT6M3QCI-CUc3wUD0.js → timeline-definition-IT6M3QCI-Dl_vgiNE.js} +1 -1
- package/dist/assets/{treemap-GDKQZRPO-CUaj-MZ8.js → treemap-GDKQZRPO-CID4XMcv.js} +1 -1
- package/dist/assets/vendor-antd-CQLaBms0.js +502 -0
- package/dist/assets/{vendor-charts-BUIOsgUp.js → vendor-charts-BCoGxogD.js} +1 -1
- package/dist/assets/{vendor-markdown-Dp-3E-KT.js → vendor-markdown-D28-Y5XP.js} +1 -1
- package/dist/assets/{vendor-mermaid-6OmS-Qsz.js → vendor-mermaid-BD0lXko3.js} +54 -54
- package/dist/assets/{vendor-pdf-Bqs7ZEuY.js → vendor-pdf-Du4-g8Ia.js} +55 -55
- package/dist/assets/{xychartDiagram-PRI3JC2R-Bfk_okZ6.js → xychartDiagram-PRI3JC2R-Bud7miGK.js} +1 -1
- package/dist/index.html +3 -3
- package/package.json +1 -1
- package/dist/assets/App-JyzlIuKJ.js +0 -231
- package/dist/assets/classDiagram-2ON5EDUG-3bs1BaYh.js +0 -1
- package/dist/assets/classDiagram-v2-WZHVMYZB-3bs1BaYh.js +0 -1
- package/dist/assets/clone-DIn3Qjtq.js +0 -1
- package/dist/assets/stateDiagram-v2-4FDKWEC3-CzuUBYSi.js +0 -1
- package/dist/assets/vendor-antd-UVhfUgc_.js +0 -502
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-DN4T64sQ.js","./vendor-markdown-D28-Y5XP.js","./vendor-i18n-BNURlJ23.js","./vendor-antd-CQLaBms0.js","./main-fT0cr1NN.js","./main-B6snAd4S.css","./vendor-charts-BCoGxogD.js","./vendor-mermaid-BD0lXko3.js","./index-eDRjOrKd.js","./index-Ds0z78TD.js","./index-Bi-vGirQ.css","./index-Df-GVUQB.js","./index-DMfxTHKB.js","./index-BmjFP0ha.js","./core-Cfh-QHsP.js","./index-_XI0Qq6F.js","./vendor-pdf-Du4-g8Ia.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var ax=Object.defineProperty;var ix=(e,t,s)=>t in e?ax(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var We=(e,t,s)=>ix(e,typeof t!="symbol"?t+"":t,s);import{j as r,M as us,r as wi,h as ir,_ as kt,S as ut,a as xp,t as bp,p as vp,b as lx,c as Bc,d as cx,m as Sp,s as dx,y as wp,e as _p,f as Wc,g as Uc,i as Tp}from"./vendor-markdown-D28-Y5XP.js";import{R as dt,i as Kt,u as se,a as m,g as mr}from"./vendor-i18n-BNURlJ23.js";import{r as ux,A as mx}from"./main-fT0cr1NN.js";import{S as q,B,C as te,n as le,L as Ge,Y as Gt,T as fe,Z as hx,$ as qc,a0 as Jt,l as pe,M as Et,E as Qt,a1 as hr,t as xe,a2 as Vl,a3 as Za,j as pr,O as ta,a4 as kp,k as cn,H as px,p as fr,a5 as lr,a6 as fx,I as ye,K,a7 as Zt,a8 as Bs,i as ks,a9 as sa,o as je,aa as gx,ab as yx,ac as ts,ad as Cp,ae as Ho,af as xx,ag as _i,A as Ne,u as Cs,v as ct,ah as Oe,V as Dt,ai as js,aj as ei,ak as ot,F as ee,al as zs,am as Qe,an as jt,ao as Tt,ap as bx,P as ti,aq as gr,ar as jp,as as Ti,at as Bd,au as dn,av as vx,aw as ki,ax as Kl,ay as Os,az as Sx,aA as na,aB as _s,aC as Hc,aD as Wd,Q as Ws,aE as Us,aF as wx,aG as _x,aH as Gl,aI as qi,G as Tx,aJ as nr,aK as Mp,aL as Ud,aM as cr,aN as kx,aO as Cx,m as dr,aP as Yc,U as Ci,aQ as jx,aR as Mx,aS as Pp,aT as Xc,aU as Ep,aV as Rp,aW as Px,aX as Ex,aY as Rx,aZ as Ax,a_ as Ix,a$ as $x,b0 as Fx,b1 as Ap,b2 as Ip,x as La,q as Yo,b3 as Vc,w as Lx,b4 as Ox,b5 as Dx,N as zx,b6 as Nx,b7 as Bx,b8 as Wx,b9 as Ux,ba as $p,bb as Fp,bc as qx,bd as Hx,be as Kc,bf as Yx,bg as Xx,bh as Xo,bi as qd,bj as Lp,bk as Hd,bl as Vx,bm as Kx,bn as Gx,bo as Jx,bp as Qx,bq as Op,br as Zx,bs as eb,bt as tb}from"./vendor-antd-CQLaBms0.js";import{Z as ra,_ as sb,$ as nb,a0 as rb,a1 as oa,a2 as ob,a3 as ji,a4 as Mi,a5 as Pi,a6 as Dp,a7 as Hi,a8 as Gc,a9 as si}from"./vendor-charts-BCoGxogD.js";import{b9 as Jc}from"./vendor-mermaid-BD0lXko3.js";const ab=({buttons:e,className:t,style:s,size:n="middle",align:o="right"})=>{const a={className:t,style:{width:"100%",justifyContent:o==="left"?"flex-start":o==="center"?"center":"flex-end",...s}};return r.jsx(q,{...a,children:e.map(i=>r.jsx(B,{type:i.type||"default",disabled:i.disabled,loading:i.loading,danger:i.danger,onClick:i.onClick,size:n,icon:i.icon,children:i.text},i.key))})},ib=(e,t)=>({key:"cancel",text:t||"Cancel",type:"default",onClick:e}),lb=(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}),Yd=e=>{let t;const s=new Set,n=(d,u)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const p=t;t=u??(typeof h!="object"||h===null)?h:Object.assign({},t,h),s.forEach(y=>y(t,p))}},o=()=>t,l={setState:n,getState:o,getInitialState:()=>c,subscribe:d=>(s.add(d),()=>s.delete(d))},c=t=e(n,o,l);return l},cb=e=>e?Yd(e):Yd,db=e=>e;function ub(e,t=db){const s=dt.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return dt.useDebugValue(s),s}const Xd=e=>{const t=cb(e),s=n=>ub(t,n);return Object.assign(s,t),s},un=e=>e?Xd(e):Xd,Vd={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},Vo=new Map,fa=e=>{const t=Vo.get(e);return t?Object.fromEntries(Object.entries(t.stores).map(([s,n])=>[s,n.getState()])):{}},mb=(e,t,s)=>{if(e===void 0)return{type:"untracked",connection:t.connect(s)};const n=Vo.get(s.name);if(n)return{type:"tracked",store:e,...n};const o={connection:t.connect(s),stores:{}};return Vo.set(s.name,o),{type:"tracked",store:e,...o}},hb=(e,t)=>{if(t===void 0)return;const s=Vo.get(e);s&&(delete s.stores[t],Object.keys(s.stores).length===0&&Vo.delete(e))},pb=e=>{var t,s;if(!e)return;const n=e.split(`
|
|
3
|
+
`),o=n.findIndex(i=>i.includes("api.setState"));if(o<0)return;const a=((t=n[o+1])==null?void 0:t.trim())||"";return(s=/.+ (.+) .+/.exec(a))==null?void 0:s[1]},fb=(e,t={})=>(s,n,o)=>{const{enabled:a,anonymousActionType:i,store:l,...c}=t;let d;try{d=(a??(Vd?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!d)return e(s,n,o);const{connection:u,...h}=mb(l,d,c);let p=!0;o.setState=(f,b,x)=>{const S=s(f,b);if(!p)return S;const w=x===void 0?{type:i||pb(new Error().stack)||"anonymous"}:typeof x=="string"?{type:x}:x;return l===void 0?(u==null||u.send(w,n()),S):(u==null||u.send({...w,type:`${l}/${w.type}`},{...fa(c.name),[l]:o.getState()}),S)},o.devtools={cleanup:()=>{u&&typeof u.unsubscribe=="function"&&u.unsubscribe(),hb(c.name,l)}};const y=(...f)=>{const b=p;p=!1,s(...f),p=b},g=e(o.setState,n,o);if(h.type==="untracked"?u==null||u.init(g):(h.stores[h.store]=o,u==null||u.init(Object.fromEntries(Object.entries(h.stores).map(([f,b])=>[f,f===h.store?g:b.getState()])))),o.dispatchFromDevtools&&typeof o.dispatch=="function"){let f=!1;const b=o.dispatch;o.dispatch=(...x)=>{(Vd?"production":void 0)!=="production"&&x[0].type==="__setState"&&!f&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),f=!0),b(...x)}}return u.subscribe(f=>{var b;switch(f.type){case"ACTION":if(typeof f.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return Yi(f.payload,x=>{if(x.type==="__setState"){if(l===void 0){y(x.state);return}Object.keys(x.state).length!==1&&console.error(`
|
|
4
|
+
[zustand devtools middleware] Unsupported __setState action format.
|
|
5
|
+
When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
|
|
6
|
+
and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
|
|
7
|
+
`);const S=x.state[l];if(S==null)return;JSON.stringify(o.getState())!==JSON.stringify(S)&&y(S);return}o.dispatchFromDevtools&&typeof o.dispatch=="function"&&o.dispatch(x)});case"DISPATCH":switch(f.payload.type){case"RESET":return y(g),l===void 0?u==null?void 0:u.init(o.getState()):u==null?void 0:u.init(fa(c.name));case"COMMIT":if(l===void 0){u==null||u.init(o.getState());return}return u==null?void 0:u.init(fa(c.name));case"ROLLBACK":return Yi(f.state,x=>{if(l===void 0){y(x),u==null||u.init(o.getState());return}y(x[l]),u==null||u.init(fa(c.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return Yi(f.state,x=>{if(l===void 0){y(x);return}JSON.stringify(o.getState())!==JSON.stringify(x[l])&&y(x[l])});case"IMPORT_STATE":{const{nextLiftedState:x}=f.payload,S=(b=x.computedStates.slice(-1)[0])==null?void 0:b.state;if(!S)return;y(l===void 0?S:S[l]),u==null||u.send(null,x);return}case"PAUSE_RECORDING":return p=!p}return}}),g},gb=fb,Yi=(e,t)=>{let s;try{s=JSON.parse(e)}catch(n){console.error("[zustand devtools middleware] Could not parse the received json",n)}s!==void 0&&t(s)},yb=e=>(t,s,n)=>{const o=n.subscribe;return n.subscribe=(i,l,c)=>{let d=i;if(l){const u=(c==null?void 0:c.equalityFn)||Object.is;let h=i(n.getState());d=p=>{const y=i(p);if(!u(h,y)){const g=h;l(h=y,g)}},c!=null&&c.fireImmediately&&l(h,h)}return o(d)},e(t,s,n)},xb=yb;function bb(e,t){let s;try{s=e()}catch{return}return{getItem:o=>{var a;const i=c=>c===null?null:JSON.parse(c,void 0),l=(a=s.getItem(o))!=null?a:null;return l instanceof Promise?l.then(i):i(l)},setItem:(o,a)=>s.setItem(o,JSON.stringify(a,void 0)),removeItem:o=>s.removeItem(o)}}const Jl=e=>t=>{try{const s=e(t);return s instanceof Promise?s:{then(n){return Jl(n)(s)},catch(n){return this}}}catch(s){return{then(n){return this},catch(n){return Jl(n)(s)}}}},vb=(e,t)=>(s,n,o)=>{let a={storage:bb(()=>localStorage),partialize:f=>f,version:0,merge:(f,b)=>({...b,...f}),...t},i=!1;const l=new Set,c=new Set;let d=a.storage;if(!d)return e((...f)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),s(...f)},n,o);const u=()=>{const f=a.partialize({...n()});return d.setItem(a.name,{state:f,version:a.version})},h=o.setState;o.setState=(f,b)=>{h(f,b),u()};const p=e((...f)=>{s(...f),u()},n,o);o.getInitialState=()=>p;let y;const g=()=>{var f,b;if(!d)return;i=!1,l.forEach(S=>{var w;return S((w=n())!=null?w:p)});const x=((b=a.onRehydrateStorage)==null?void 0:b.call(a,(f=n())!=null?f:p))||void 0;return Jl(d.getItem.bind(d))(a.name).then(S=>{if(S)if(typeof S.version=="number"&&S.version!==a.version){if(a.migrate){const w=a.migrate(S.state,S.version);return w instanceof Promise?w.then(C=>[!0,C]):[!0,w]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,S.state];return[!1,void 0]}).then(S=>{var w;const[C,_]=S;if(y=a.merge(_,(w=n())!=null?w:p),s(y,!0),C)return u()}).then(()=>{x==null||x(y,void 0),y=n(),i=!0,c.forEach(S=>S(y))}).catch(S=>{x==null||x(void 0,S)})};return o.persist={setOptions:f=>{a={...a,...f},f.storage&&(d=f.storage)},clearStorage:()=>{d==null||d.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>g(),hasHydrated:()=>i,onHydrate:f=>(l.add(f),()=>{l.delete(f)}),onFinishHydration:f=>(c.add(f),()=>{c.delete(f)})},a.skipHydration||g(),y||p},Sb=vb,zp=()=>!1,Np=e=>{if(!zp())return!1;try{return localStorage.getItem(e)==="1"}catch{return!1}},wb=()=>Np("bodhi_debug_ui_layout"),Yt=(e,t)=>{wb()&&console.log(`[ui-layout] ${e}`,t??"")},He=(e,t,...s)=>{zp()&&Np("bodhi_debug_verbose")&&console.log(`${e} ${t}`,...s)};var Xi={};const Kd="copilot_backend_base_url",_b="http://127.0.0.1:9562/v1",Bp=e=>e.trim().replace(/\/+$/,""),Tb=()=>{const t=Xi==null?void 0:Xi.VITE_BACKEND_BASE_URL;return t?Bp(t):_b},yr=()=>{const e=localStorage.getItem(Kd);if(e){const t=Bp(e);try{return new URL(t),t}catch{console.warn("Invalid stored backend URL, using default:",t),localStorage.removeItem(Kd)}}return Tb()};class Ln extends Error{constructor(t,s,n,o){super(t),this.status=s,this.statusText=n,this.body=o,this.name="ApiError"}}function kb(e){return e instanceof Ln}class Qc{constructor(t={}){We(this,"baseUrl");We(this,"defaultHeaders");this.baseUrl=t.baseUrl??this.resolveBaseUrl(),this.defaultHeaders=t.defaultHeaders??{"Content-Type":"application/json"}}resolveBaseUrl(){let t=yr().trim().replace(/\/+$/,"");return t.endsWith("/v1")?t:`${t}/v1`}buildUrl(t){const s=t.replace(/^\/+/,"");return`${this.baseUrl}/${s}`}async handleResponse(t){var n,o,a;if(!t.ok){const i=await t.text().catch(()=>{});let l=t.statusText;if(i)try{const c=JSON.parse(i),d=typeof(c==null?void 0:c.error)=="object"?(n=c.error)==null?void 0:n.message:void 0;l=(typeof(c==null?void 0:c.error)=="string"?c.error:void 0)||(typeof d=="string"?d:void 0)||c.message||c.detail||t.statusText}catch{l=i||t.statusText}throw new Ln(l,t.status,t.statusText,i)}return t.status===204?void 0:(((a=(o=t.headers)==null?void 0:o.get)==null?void 0:a.call(o,"content-type"))||"").includes("application/json")?t.json():typeof t.text=="function"?await t.text():t.json()}delay(t){return new Promise(s=>setTimeout(s,t))}async fetchWithRetry(t,s,n=3){let o=null;for(let a=0;a<n;a++)try{const i=await fetch(t,s);if(i.status>=500&&a<n-1){const l=1e3*Math.pow(2,a);console.warn(`Request failed with ${i.status}, retrying in ${l}ms (attempt ${a+1}/${n})`),await this.delay(l);continue}return i}catch(i){if(o=i,a<n-1){const l=1e3*Math.pow(2,a);console.warn(`Network error: ${o.message}, retrying in ${l}ms (attempt ${a+1}/${n})`),await this.delay(l)}}throw o||new Error("Max retries exceeded")}async get(t,s){const n=this.buildUrl(t),o=new AbortController,a=setTimeout(()=>o.abort(),3e4);try{const i=await this.fetchWithRetry(n,{...s,method:"GET",headers:{...this.defaultHeaders,...s==null?void 0:s.headers},signal:o.signal},3);return this.handleResponse(i)}finally{clearTimeout(a)}}async post(t,s,n){const o=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(o,{...n,method:"POST",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},body:s?JSON.stringify(s):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async put(t,s,n){const o=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(o,{...n,method:"PUT",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},body:s?JSON.stringify(s):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async patch(t,s,n){const o=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(o,{...n,method:"PATCH",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},body:s?JSON.stringify(s):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async delete(t,s){const n=this.buildUrl(t),o=new AbortController,a=setTimeout(()=>o.abort(),3e4);try{const i=await this.fetchWithRetry(n,{...s,method:"DELETE",headers:{...this.defaultHeaders,...s==null?void 0:s.headers},signal:o.signal},3);return this.handleResponse(i)}finally{clearTimeout(a)}}async request(t,s,n){const o=this.buildUrl(s),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(o,{...n,method:t,headers:{...this.defaultHeaders,...n==null?void 0:n.headers},signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async fetchRaw(t,s){const n=this.buildUrl(t),o=await fetch(n,{...s,headers:{...this.defaultHeaders,...s==null?void 0:s.headers}});if(!o.ok)throw new Ln(`API request failed: ${o.statusText}`,o.status,o.statusText);return o}}const Te=new Qc,Se=new Qc({baseUrl:(()=>{let e=yr().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`})()});function Cb(e){return e instanceof Ln}const jn=class jn{static getInstance(){return jn.instance||(jn.instance=new jn),jn.instance}async sendMessage(t){return Se.post("chat",t)}async execute(t,s,n,o){const a={model:s};return n&&(a.reasoning_effort=n),o&&(a.client_sync=o),Se.post(`execute/${t}`,a)}async listSessions(){return Se.get("sessions")}async createSession(t){return Se.post("sessions",t)}async patchSession(t,s){const n=encodeURIComponent(t);await Se.patch(`sessions/${n}`,s)}async getSessionSystemPrompt(t){const s=encodeURIComponent(t);return Se.get(`sessions/${s}/system-prompt`)}async clearSession(t){const s=encodeURIComponent(t);await Se.post(`sessions/${s}/clear`)}async truncateSessionMessages(t,s){const n=encodeURIComponent(t);return Se.post(`sessions/${n}/messages/truncate`,s)}async restoreSessionState(t,s){const n=encodeURIComponent(t);return Se.post(`sessions/${n}/restore`,s)}async patchSessionMessage(t,s,n){const o=encodeURIComponent(t),a=encodeURIComponent(s);await Se.patch(`sessions/${o}/messages/${a}`,n)}async deleteSessionMessage(t,s){const n=encodeURIComponent(t),o=encodeURIComponent(s);await Se.delete(`sessions/${n}/messages/${o}`)}async cleanupSessions(t,s){await Se.post("sessions/cleanup",{mode:t,keep_pinned:s})}async devResetSessions(){await Se.post("dev/reset")}async listSchedules(){return Se.get("schedules")}async createSchedule(t){return Se.post("schedules",t)}async patchSchedule(t,s){const n=encodeURIComponent(t);return Se.patch(`schedules/${n}`,s)}async deleteSchedule(t){const s=encodeURIComponent(t);await Se.delete(`schedules/${s}`)}async runScheduleNow(t){const s=encodeURIComponent(t);await Se.post(`schedules/${s}/run`)}async listScheduleSessions(t){const s=encodeURIComponent(t);return Se.get(`schedules/${s}/sessions`)}async subscribeToEvents(t,s,n){var a;const o=n==null?void 0:n.signal;He("[AgentClient]","[AgentClient] Subscribing to events for session:",t);try{const i=await Se.fetchRaw(`events/${t}`,{signal:o});if(He("[AgentClient]","[AgentClient] Events subscription response:",i.status,i.statusText,"Content-Type:",i.headers.get("content-type")),!i.ok){let u=`Failed to subscribe to events: ${i.statusText}`;try{const h=await i.text();if(h)try{const p=JSON.parse(h);u=p.error||p.message||p.detail||u}catch{u=h||u}}catch(h){console.error("Failed to parse error response:",h)}throw new Error(u)}const l=(a=i.body)==null?void 0:a.getReader();if(!l)throw new Error("No response body");const c=new TextDecoder;let d="";try{for(;!(o!=null&&o.aborted);){const{done:u,value:h}=await l.read();if(u)break;d+=c.decode(h,{stream:!0});const p=d.split(`
|
|
8
|
+
`);d=p.pop()||"";for(const y of p)if(y.startsWith("data: ")){const g=y.slice(6);if(g==="[DONE]")return;try{const f=JSON.parse(g);this.handleEvent(f,s)}catch(f){console.warn("Failed to parse event:",g,f)}}}}finally{l.releaseLock()}}catch(i){if(o!=null&&o.aborted){He("[AgentClient]","Events subscription aborted for session:",t);return}throw console.error("[AgentClient] Events subscription error:",i),i}}handleEvent(t,s){var n,o,a,i,l,c,d,u,h,p,y,g,f,b,x,S,w,C,_,T,j;switch(t.type){case"token":(n=s.onToken)==null||n.call(s,t.content||"");break;case"reasoning_token":(o=s.onReasoningToken)==null||o.call(s,t.content||"");break;case"tool_token":(a=s.onToolToken)==null||a.call(s,t.tool_call_id||"",t.content||"");break;case"tool_start":(i=s.onToolStart)==null||i.call(s,t.tool_call_id||"",t.tool_name||"",t.arguments||{});break;case"tool_complete":t.result&&((l=s.onToolComplete)==null||l.call(s,t.tool_call_id||"",t.result));break;case"tool_error":(c=s.onToolError)==null||c.call(s,t.tool_call_id||"",t.error||"");break;case"task_list_updated":t.task_list&&((d=s.onTaskListUpdated)==null||d.call(s,t.task_list));break;case"task_list_item_progress":if(t.session_id&&t.item_id&&t.status&&t.tool_calls_count!==void 0&&t.version!==void 0){const v=t.status;if(!(v==="pending"||v==="in_progress"||v==="completed"||v==="blocked"))break;(u=s.onTaskListItemProgress)==null||u.call(s,{session_id:t.session_id,item_id:t.item_id,status:v,tool_calls_count:t.tool_calls_count,version:t.version})}break;case"task_list_completed":t.session_id&&t.total_rounds!==void 0&&t.total_tool_calls!==void 0&&((h=s.onTaskListCompleted)==null||h.call(s,t.session_id,t.total_rounds,t.total_tool_calls));break;case"task_evaluation_started":t.session_id&&t.items_count!==void 0&&((p=s.onTaskEvaluationStarted)==null||p.call(s,t.session_id,t.items_count));break;case"task_evaluation_completed":t.session_id&&t.updates_count!==void 0&&t.reasoning&&((y=s.onTaskEvaluationCompleted)==null||y.call(s,t.session_id,t.updates_count,t.reasoning));break;case"token_budget_updated":t.usage&&"system_tokens"in t.usage&&((g=s.onTokenBudgetUpdated)==null||g.call(s,t.usage));break;case"context_compression_status":typeof t.phase=="string"&&typeof t.status=="string"&&((f=s.onContextCompressionStatus)==null||f.call(s,t.phase,t.status));break;case"tool_lifecycle":(b=s.onToolLifecycle)==null||b.call(s,t.tool_call_id||"",t.tool_name||"",t.phase||"",t.elapsed_ms,t.is_mutating,t.auto_approved,t.summary,t.error);break;case"context_summarized":t.summary_info&&((x=s.onContextSummarized)==null||x.call(s,t.summary_info));break;case"sub_session_started":t.parent_session_id&&t.child_session_id&&((S=s.onSubSessionStarted)==null||S.call(s,t.parent_session_id,t.child_session_id,t.title));break;case"sub_session_event":t.parent_session_id&&t.child_session_id&&t.event&&((w=s.onSubSessionEvent)==null||w.call(s,t.parent_session_id,t.child_session_id,t.event));break;case"sub_session_heartbeat":t.parent_session_id&&t.child_session_id&&t.timestamp&&((C=s.onSubSessionHeartbeat)==null||C.call(s,t.parent_session_id,t.child_session_id,t.timestamp));break;case"sub_session_completed":t.parent_session_id&&t.child_session_id&&((_=s.onSubSessionCompleted)==null||_.call(s,t.parent_session_id,t.child_session_id,typeof t.status=="string"?t.status:"completed",t.error));break;case"complete":(T=s.onComplete)==null||T.call(s,t.usage);break;case"error":(j=s.onError)==null||j.call(s,t.message||t.error||"Unknown error");break;default:console.warn("Unknown event type:",t)}}async stopGeneration(t){await Se.post(`stop/${t}`)}async deleteSession(t){const s=encodeURIComponent(t);await Se.delete(`sessions/${s}`)}async getHistory(t){return Se.get(`history/${t}`)}async healthCheck(){try{return await Se.get("health"),!0}catch{return!1}}};We(jn,"instance");let hs=jn;const Ko=hs.getInstance(),jb=()=>({id:"general_assistant",name:"Bodhi",description:Kt.t("chat.prompt.defaultDescription"),content:`You are Bodhi, a highly capable AI assistant.
|
|
9
|
+
|
|
10
|
+
You help users solve problems quickly and correctly. Be concise, practical, and proactive.
|
|
11
|
+
If requirements are unclear, ask focused clarifying questions before proceeding.`,isDefault:!0}),ni=()=>[jb()];class Mb{async getProviderConfig(){return Te.get("/bamboo/settings/provider")}async saveProviderConfig(t){return Te.post("/bamboo/settings/provider",t)}async reloadConfig(){return Te.post("/bamboo/settings/reload")}async getCopilotAuthStatus(){return Te.post("/bamboo/copilot/auth/status")}async startCopilotAuth(){return Te.post("/bamboo/copilot/auth/start")}async completeCopilotAuth(t){return Te.post("/bamboo/copilot/auth/complete",t)}async authenticateCopilot(){return Te.post("/bamboo/copilot/authenticate")}async logoutCopilot(){return Te.post("/bamboo/copilot/logout")}async fetchProviderModels(t){return(await Te.post("/bamboo/settings/provider/models",{provider:t})).models}async getEnvVars(){return Te.get("/bamboo/env-vars")}async upsertEnvVar(t){return Te.post("/bamboo/env-vars",t)}async deleteEnvVar(t){return Te.delete(`/bamboo/env-vars/${encodeURIComponent(t)}`)}async replaceEnvVars(t){return Te.post("/bamboo/env-vars/replace",{entries:t})}}const bt=new Mb,Rt=un((e,t)=>({currentProvider:"copilot",providerConfig:{provider:"copilot",providers:{}},isLoading:!1,error:null,loadProviderConfig:async()=>{e({isLoading:!0,error:null});try{const s=await bt.getProviderConfig();e({providerConfig:s,currentProvider:s.provider,isLoading:!1})}catch(s){console.error("Failed to load provider config:",s),e({error:s instanceof Error?s.message:"Failed to load provider config",isLoading:!1})}},setCurrentProvider:s=>{e({currentProvider:s})},updateProviderConfig:s=>{e(n=>({providerConfig:{...n.providerConfig,...s}}))},getActiveModel:()=>{const s=t(),n=s.providerConfig.providers[s.currentProvider];if(n&&"model"in n&&n.model)return n.model},getFastModel:()=>{const s=t(),n=s.providerConfig.providers[s.currentProvider];return n&&"fast_model"in n&&n.fast_model?n.fast_model:s.getActiveModel()},getVisionModel:()=>{const s=t(),n=s.providerConfig.providers[s.currentProvider];return n&&"vision_model"in n&&n.vision_model?n.vision_model:s.getActiveModel()}})),Pb=Object.freeze(Object.defineProperty({__proto__:null,useProviderStore:Rt},Symbol.toStringTag,{value:"Module"})),Gd="copilot_auto_generate_titles",Vs=hs.getInstance(),rr=ni()[0],Eb=(rr==null?void 0:rr.id)||"general_assistant";var yp;const Wp=((yp=rr==null?void 0:rr.content)==null?void 0:yp.trim())||"",Vi="tool",Rb=()=>{try{const e=globalThis.crypto;if(e!=null&&e.randomUUID)return e.randomUUID()}catch{}return`id_${Date.now()}_${Math.random().toString(16).slice(2)}`},Ab=()=>{let e=yr().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`},Up=e=>{const t=e.trim();if(!t.startsWith("bamboo-attachment://"))return null;const s=t.slice(20),[n,o]=s.split("/",2);return!n||!o?null:{sessionId:n,attachmentId:o}},Ib=e=>{const t=Up(e);return t?`${Ab()}/sessions/${encodeURIComponent(t.sessionId)}/attachments/${encodeURIComponent(t.attachmentId)}`:e},kn=e=>{if(typeof e!="string")return;const t=e.trim();if(t&&t.toLowerCase()!=="unknown")return t},$b=e=>{const t=(e||"").trim();if(!t)return;const s=t.match(/tool policy blocked ['"`]([^'"`]+)['"`]/i);if(s!=null&&s[1])return kn(s[1]);try{const n=JSON.parse(t);if(typeof(n==null?void 0:n.tool_name)=="string")return kn(n.tool_name)}catch{}},Ki=e=>{var n,o;const t=Number.isFinite(Date.parse(e.created_at))?Date.parse(e.created_at):Date.now(),s=e.token_usage?{systemTokens:e.token_usage.system_tokens,summaryTokens:e.token_usage.summary_tokens,windowTokens:e.token_usage.window_tokens,totalTokens:e.token_usage.total_tokens,budgetLimit:e.token_usage.budget_limit,...typeof e.token_usage.max_context_tokens=="number"&&e.token_usage.max_context_tokens>0?{maxContextTokens:e.token_usage.max_context_tokens}:{},...typeof e.token_usage.prompt_cached_tool_outputs=="number"&&e.token_usage.prompt_cached_tool_outputs>0?{promptCachedToolOutputs:e.token_usage.prompt_cached_tool_outputs}:{}}:void 0;return{id:e.id,kind:e.kind,parentSessionId:e.parent_session_id??null,rootSessionId:e.root_session_id,spawnDepth:e.spawn_depth,createdByScheduleId:e.created_by_schedule_id??null,isRunning:e.is_running,updatedAt:e.updated_at,lastActivityAt:e.last_activity_at,messageCount:e.message_count,hasAttachments:e.has_attachments,lastRunStatus:e.last_run_status,lastRunError:e.last_run_error,title:e.title||Kt.t("chat.session.defaultTitle"),createdAt:t,pinned:e.pinned,messages:[],config:{systemPromptId:Eb,baseSystemPrompt:Wp,lastUsedEnhancedPrompt:null,tokenUsage:s,truncationOccurred:(n=e.token_usage)==null?void 0:n.truncation_occurred,segmentsRemoved:(o=e.token_usage)==null?void 0:o.segments_removed,compressionEvents:[]},currentInteraction:null}},Fb=(e,t)=>{var a,i,l,c,d;const s=new Map,n=new Map;for(const u of t)u.role==="tool"&&u.tool_call_id&&u.metadata&&n.set(u.tool_call_id,u.metadata);const o=[];for(const u of t){const h=u.created_at||new Date().toISOString();if(u.role==="system"){const p={role:"system",id:u.id,createdAt:h,content:u.content||"",isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(p);continue}if(u.role==="user"){const p=new Map;for(const f of u.image_ocr||[]){const b=(a=f.image_url)==null?void 0:a.trim();if(!b)continue;const S=(f.lines||[]).map(w=>((w==null?void 0:w.text)||"").trim()).filter(Boolean);p.set(b,{ocrText:S.length?S.join(`
|
|
12
|
+
`):void 0,ocrError:f.error?String(f.error):void 0})}const y=[];for(const f of u.content_parts||[]){if(f.type!=="image_url")continue;const b=((i=f.image_url)==null?void 0:i.url)||"";if(!b)continue;const x=Ib(b),S=Up(b),w=p.get(b.trim());y.push({id:Rb(),url:x,ocrText:w==null?void 0:w.ocrText,ocrError:w==null?void 0:w.ocrError,name:S?`attachment-${S.attachmentId}`:"image",size:0,type:"image/*"})}const g={role:"user",id:u.id,createdAt:h,content:u.content||"",images:y.length?y:void 0,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(g);continue}if(u.role==="assistant"){const p=u.tool_calls||[];if(p.length>0){const f=(u.content||"").trim(),b=typeof u.reasoning=="string"&&u.reasoning.trim().length>0;if(f||b){const C=b?{reasoning:u.reasoning,backendMessageId:u.id}:{backendMessageId:u.id},_={role:"assistant",type:"text",id:`${u.id}_text`,createdAt:h,content:u.content||"",metadata:C,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(_)}for(const C of p)C.id&&s.set(C.id,kn((l=C.function)==null?void 0:l.name)||Vi);const x=(c=p[0])==null?void 0:c.id,S=x?n.get(x):void 0,w={role:"assistant",type:"tool_call",id:u.id,createdAt:h,toolCalls:p.map(C=>{var _;return{toolCallId:C.id,toolName:kn((_=C.function)==null?void 0:_.name)||Vi,parameters:(()=>{var T,j;try{return JSON.parse(((T=C.function)==null?void 0:T.arguments)||"{}")}catch{return{raw:((j=C.function)==null?void 0:j.arguments)||""}}})(),streamingOutput:""}}),...S?{metadata:S}:{},isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(w);continue}const y=typeof u.reasoning=="string"&&u.reasoning.trim().length>0?{reasoning:u.reasoning}:{},g={role:"assistant",type:"text",id:u.id,createdAt:h,content:u.content||"",metadata:y,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(g);continue}if(u.role==="tool"){const p=((d=u.tool_call_id)==null?void 0:d.trim())||`orphan-tool-call:${u.id}`,y=kn(s.get(p))||kn(u.tool_name)||kn(u.name)||$b(u.content)||Vi,g=u.tool_success===!1||u.tool_success==null&&typeof u.content=="string"&&u.content.trimStart().startsWith("Error:"),f={role:"assistant",type:"tool_result",id:u.id,createdAt:h,toolName:y,toolCallId:p,result:{tool_name:y,result:u.content||"",display_preference:"Default"},isError:g,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(f);continue}}return o},Lb=(e,t)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,processingChats:new Set,autoGenerateTitles:!0,isUpdatingAutoTitlePreference:!1,subSessionsByParent:{},addChat:async s=>{var d,u,h;const n=(s.title||Kt.t("chat.sidebar.newSession")).trim(),o=((u=(d=s.config)==null?void 0:d.baseSystemPrompt)==null?void 0:u.trim())||"",i=((h=Rt.getState().getActiveModel())==null?void 0:h.trim())||void 0,l=await Vs.createSession({title:n,system_prompt:o||void 0,model:i}),c={...Ki(l.session),title:n,config:{...s.config,baseSystemPrompt:o||Wp},messages:[],currentInteraction:null};return e(p=>{const y=[c,...p.chats.filter(g=>g.id!==c.id)];return{...p,chats:y,currentSessionId:c.id,latestActiveSessionId:c.id}}),c.id},selectSession:s=>{const n=t();n.currentSessionId===s&&n.latestActiveSessionId===s||e({currentSessionId:s,latestActiveSessionId:s})},deleteSession:async s=>{try{await Vs.deleteSession(s)}catch(n){console.error(`[ChatSlice] Failed to delete backend session ${s}:`,n)}e(n=>{var c;const o=new Set;for(const d of n.chats)d.id===s&&o.add(d.id),d.rootSessionId===s&&o.add(d.id);const a=n.chats.filter(d=>!o.has(d.id)),i=n.currentSessionId&&o.has(n.currentSessionId)?null:n.currentSessionId,l=n.latestActiveSessionId&&o.has(n.latestActiveSessionId)?((c=a[0])==null?void 0:c.id)??null:n.latestActiveSessionId;return{...n,chats:a,currentSessionId:i,latestActiveSessionId:l}})},deleteSessions:async s=>{for(const n of s)await t().deleteSession(n)},updateSession:(s,n)=>{e(a=>{const i=a.chats.map(l=>l.id===s?{...l,...n}:l);return{...a,chats:i}});const o={};typeof n.title=="string"&&(o.title=n.title),typeof n.pinned=="boolean"&&(o.pinned=n.pinned),Object.keys(o).length>0&&Vs.patchSession(s,o).catch(a=>{console.warn(`[ChatSlice] Failed to patch session ${s}:`,a)})},pinSession:s=>{t().updateSession(s,{pinned:!0})},unpinSession:s=>{t().updateSession(s,{pinned:!1})},setMessages:(s,n)=>{t().chats.find(a=>a.id===s)&&t().updateSession(s,{messages:n})},addMessage:async(s,n)=>{const o=t().chats.find(i=>i.id===s);if(!o)return;const a=[...o.messages,n];t().updateSession(s,{messages:a})},updateMessage:(s,n,o)=>{const a=t().chats.find(l=>l.id===s);if(!a)return;const i=a.messages.map(l=>{if(l.id!==n)return l;const c={...l};return Object.keys(o).forEach(d=>{Object.prototype.hasOwnProperty.call(c,d)&&(c[d]=o[d])}),c});t().updateSession(s,{messages:i})},deleteMessage:async(s,n)=>{const o=t().chats.find(a=>a.id===s);if(!o)return{success:!1,sessionId:s,messageId:n,reason:"session_not_found"};if(!o.messages.some(a=>a.id===n))return{success:!1,sessionId:s,messageId:n,reason:"message_not_found"};try{await Vs.deleteSessionMessage(s,n)}catch(a){return console.warn(`[ChatSlice] Failed to delete message ${n} from session ${s}:`,a),a instanceof Ln?a.status===404?{success:!1,sessionId:s,messageId:n,reason:"backend_not_found",statusCode:a.status,errorMessage:a.message}:a.status===409?{success:!1,sessionId:s,messageId:n,reason:"session_running",statusCode:a.status,errorMessage:a.message}:{success:!1,sessionId:s,messageId:n,reason:"backend_error",statusCode:a.status,errorMessage:a.message}:{success:!1,sessionId:s,messageId:n,reason:"backend_error",errorMessage:a instanceof Error?a.message:void 0}}return e(a=>({...a,chats:a.chats.map(i=>i.id===s?{...i,messages:i.messages.filter(l=>l.id!==n)}:i)})),{success:!0,sessionId:s,messageId:n}},refreshChats:async()=>{const n=(await Vs.listSessions()).sessions.map(Ki);e(o=>{const a=new Map(o.chats.map(l=>[l.id,l])),i=n.map(l=>{const c=a.get(l.id);return c?{...l,messages:c.messages,config:c.config}:l});return{...o,chats:i}})},loadChats:async()=>{var l;const s=localStorage.getItem(Gd),n=s===null?t().autoGenerateTitles:s==="true";let o=await Vs.listSessions();(!o.sessions||o.sessions.length===0)&&(o={sessions:[(await Vs.createSession({title:Kt.t("chat.sidebar.newSession")})).session]});const a=o.sessions.map(Ki),i=((l=a[0])==null?void 0:l.id)??null;e({chats:a,latestActiveSessionId:i,currentSessionId:i,processingChats:new Set,autoGenerateTitles:n}),i&&await t().loadChatHistory(i)},loadChatHistory:async(s,n)=>{var l,c,d,u,h,p,y;const o=(n==null?void 0:n.mode)??"replace",a=Math.max(0,(n==null?void 0:n.retries)??0),i=Math.max(0,(n==null?void 0:n.retryDelayMs)??0);for(let g=0;g<=a;g+=1)try{const f=t().chats.find(w=>w.id===s);if(!f)return;const b=await Vs.getHistory(s),x=(l=b.messages[b.messages.length-1])==null?void 0:l.role;if(n!=null&&n.waitForAssistant&&x==="user"&&g<a){const w=i>0?i*(g+1):200*(g+1);await new Promise(C=>setTimeout(C,w));continue}const S=Fb(s,b.messages);if(o==="monotonic"){const w=f.messages||[],C=w.length,_=S.length,T=(c=S[S.length-1])==null?void 0:c.role,j=(d=w[w.length-1])==null?void 0:d.role,v=w[w.length-1],k=S[S.length-1],E=v==null?void 0:v.id,M=k==null?void 0:k.id;let R=!1;if(_>C?R=!0:_===C&&(R=j==="user"&&T!=="user"||typeof E=="string"&&typeof M=="string"&&E!==M),!R){t().updateSession(s,{messageCount:Math.max(f.messageCount??0,b.messages.length)});return}}t().updateSession(s,{messages:S,messageCount:b.messages.length,config:{...f.config||{},compressionEvents:(b.compression_events||[]).map(w=>({id:w.id,createdAt:w.created_at,messagesCompressed:w.messages_compressed,segmentsRemoved:w.segments_removed})),syncCursor:{messageCount:b.messages.length,lastMessageId:((u=b.messages[b.messages.length-1])==null?void 0:u.id)??null,hasPendingQuestion:((h=t().pendingQuestionRespond)==null?void 0:h.sessionId)===s,pendingQuestionToolCallId:((p=t().pendingQuestionRespond)==null?void 0:p.sessionId)===s?((y=t().pendingQuestionRespond)==null?void 0:y.toolCallId)??null:null}}});return}catch(f){if(g>=a){console.warn(`[ChatSlice] Failed to load history for ${s}:`,f);return}const b=i>0?i*(g+1):200*(g+1);await new Promise(x=>setTimeout(x,b))}},upsertSubSessionProgress:(s,n,o)=>{e(a=>{const i=a.subSessionsByParent[s]||{},l=i[n]||{},c={...i,[n]:{...l,...o}};return{subSessionsByParent:{...a.subSessionsByParent,[s]:c}}})},clearSubSessionProgress:(s,n)=>{e(o=>{const a=o.subSessionsByParent[s];if(!a||!a[n])return{};const{[n]:i,...l}=a;return{subSessionsByParent:{...o.subSessionsByParent,[s]:l}}})},setSessionProcessing:(s,n)=>{e(o=>{const a=new Set(o.processingChats);return n?a.add(s):a.delete(s),{processingChats:a}})},isSessionProcessing:s=>t().processingChats.has(s),setAutoGenerateTitlesPreference:async s=>{const n=t().autoGenerateTitles;e({autoGenerateTitles:s,isUpdatingAutoTitlePreference:!0});try{localStorage.setItem(Gd,String(s))}catch(o){throw console.warn("[ChatSlice] Failed to update auto-title preference:",o),e({autoGenerateTitles:n}),o}finally{e({isUpdatingAutoTitlePreference:!1})}}});class ri extends Error{constructor(s="Proxy authentication required"){super(s);We(this,"code","proxy_auth_required");this.name="ProxyAuthRequiredError"}}const Mn=class Mn{constructor(){}static getInstance(){return Mn.instance||(Mn.instance=new Mn),Mn.instance}resolveOpenAICompatBaseUrl(){const t=yr().trim().replace(/\/+$/,"");return t.endsWith("/openai/v1")?t:`${t.endsWith("/v1")?t.slice(0,-3):t}/openai/v1`}async getModels(){var t,s;try{return(await new Qc({baseUrl:this.resolveOpenAICompatBaseUrl()}).get("models")).data.map(a=>a.id)}catch(n){if(console.error("Failed to fetch models from HTTP API:",n),n instanceof Ln){if(n.status===428)throw new ri(n.message);let o;if(n.body)try{o=JSON.parse(n.body)}catch{}if(o&&typeof o=="object"&&"error"in o&&((t=o.error)==null?void 0:t.code)==="proxy_auth_required")throw new ri(((s=o.error)==null?void 0:s.message)||n.message)}throw n}}};We(Mn,"instance");let oi=Mn;const Ei=oi.getInstance(),Ob=Object.freeze(Object.defineProperty({__proto__:null,ModelService:oi,ProxyAuthRequiredError:ri,modelService:Ei},Symbol.toStringTag,{value:"Module"})),Db=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)},zb=e=>{if(typeof document>"u")throw new Error("document is unavailable");const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","true"),t.style.position="fixed",t.style.top="-9999px",t.style.left="-9999px",t.style.opacity="0",document.body.appendChild(t),t.focus(),t.select();const s=document.execCommand("copy");if(document.body.removeChild(t),!s)throw new Error("document.execCommand('copy') returned false")},es=async e=>{try{await Db(e);return}catch(t){try{zb(e);return}catch(s){const n=t instanceof Error?t.message:String(t),o=s instanceof Error?s.message:String(s);throw new Error(`Clipboard copy failed: navigator(${n}); fallback(${o})`)}}};class Nb{async copyToClipboard(t){await es(t)}async getBambooConfig(){try{return await Te.get("bamboo/config")}catch(t){return console.error("Failed to fetch Bamboo config:",t),{}}}async getBambooTools(){try{return await Te.get("bamboo/tools")}catch(t){return console.error("Failed to fetch Bamboo tools:",t),{tools:[]}}}async getModelLimitDefaults(){try{return await Te.get("bamboo/model-limits/defaults")}catch(t){return console.error("Failed to fetch model limit defaults:",t),{model_limits:[]}}}async setBambooConfig(t){return Te.post("bamboo/config",t)}async validateBambooConfigPatch(t){return Te.post("bamboo/config/validate",t)}async setProxyAuth(t){return Te.post("bamboo/proxy-auth",t)}async getProxyAuthStatus(){try{return await Te.get("bamboo/proxy-auth/status")}catch(t){return console.error("Failed to fetch proxy auth status:",t),{configured:!1,username:null}}}async clearProxyAuth(){return Te.post("bamboo/proxy-auth",{username:"",password:""})}async getAnthropicModelMapping(){try{return await Te.get("bamboo/anthropic-model-mapping")}catch(t){return console.error("Failed to fetch Anthropic model mapping:",t),{mappings:{}}}}async setAnthropicModelMapping(t){return Te.post("bamboo/anthropic-model-mapping",t)}async resetBambooConfig(){return Te.post("bamboo/config/reset",{})}async saveWorkflow(t,s){return Te.post("bamboo/workflows",{name:t,content:s})}async deleteWorkflow(t){return Te.delete(`bamboo/workflows/${encodeURIComponent(t)}`)}async getKeywordMaskingConfig(){try{return await Te.get("bamboo/keyword-masking")}catch(t){return console.error("Failed to fetch keyword masking config:",t),{entries:[]}}}async updateKeywordMaskingConfig(t){return Te.post("bamboo/keyword-masking",t)}async validateKeywordEntries(t){return Te.post("bamboo/keyword-masking/validate",t)}async getSetupStatus(){return await Te.get("bamboo/setup/status")}async markSetupComplete(){return Te.post("bamboo/setup/complete",{})}async resetSetupStatus(){await Te.post("bamboo/setup/incomplete",{})}}const Pn=class Pn{constructor(){We(this,"httpUtilityService",new Nb)}static getInstance(){return Pn.instance||(Pn.instance=new Pn),Pn.instance}getUtilityService(){return{copyToClipboard:t=>this.httpUtilityService.copyToClipboard(t),getBambooConfig:()=>this.httpUtilityService.getBambooConfig(),getBambooTools:()=>this.httpUtilityService.getBambooTools(),getModelLimitDefaults:()=>this.httpUtilityService.getModelLimitDefaults(),setBambooConfig:t=>this.httpUtilityService.setBambooConfig(t),validateBambooConfigPatch:t=>this.httpUtilityService.validateBambooConfigPatch(t),setProxyAuth:t=>this.httpUtilityService.setProxyAuth(t),getProxyAuthStatus:()=>this.httpUtilityService.getProxyAuthStatus(),clearProxyAuth:()=>this.httpUtilityService.clearProxyAuth(),getAnthropicModelMapping:()=>this.httpUtilityService.getAnthropicModelMapping(),setAnthropicModelMapping:t=>this.httpUtilityService.setAnthropicModelMapping(t),resetBambooConfig:()=>this.httpUtilityService.resetBambooConfig(),resetSetupStatus:()=>this.httpUtilityService.resetSetupStatus(),saveWorkflow:(t,s)=>this.httpUtilityService.saveWorkflow(t,s),deleteWorkflow:t=>this.httpUtilityService.deleteWorkflow(t),getKeywordMaskingConfig:()=>this.httpUtilityService.getKeywordMaskingConfig(),updateKeywordMaskingConfig:t=>this.httpUtilityService.updateKeywordMaskingConfig(t),validateKeywordEntries:t=>this.httpUtilityService.validateKeywordEntries(t),getSetupStatus:()=>this.httpUtilityService.getSetupStatus(),markSetupComplete:()=>this.httpUtilityService.markSetupComplete()}}async copyToClipboard(t){return this.getUtilityService().copyToClipboard(t)}async getBambooConfig(){return this.getUtilityService().getBambooConfig()}async getBambooTools(){return this.getUtilityService().getBambooTools()}async getModelLimitDefaults(){return this.getUtilityService().getModelLimitDefaults()}async setBambooConfig(t){return this.getUtilityService().setBambooConfig(t)}async validateBambooConfigPatch(t){return this.getUtilityService().validateBambooConfigPatch(t)}async setProxyAuth(t){return this.getUtilityService().setProxyAuth(t)}async getProxyAuthStatus(){return this.getUtilityService().getProxyAuthStatus()}async clearProxyAuth(){return this.getUtilityService().clearProxyAuth()}async getAnthropicModelMapping(){return this.getUtilityService().getAnthropicModelMapping()}async setAnthropicModelMapping(t){return this.getUtilityService().setAnthropicModelMapping(t)}async resetBambooConfig(){return this.getUtilityService().resetBambooConfig()}async resetSetupStatus(){return this.getUtilityService().resetSetupStatus()}async saveWorkflow(t,s){return this.getUtilityService().saveWorkflow(t,s)}async deleteWorkflow(t){return this.getUtilityService().deleteWorkflow(t)}async getKeywordMaskingConfig(){return this.getUtilityService().getKeywordMaskingConfig()}async updateKeywordMaskingConfig(t){return this.getUtilityService().updateKeywordMaskingConfig(t)}async validateKeywordEntries(t){return this.getUtilityService().validateKeywordEntries(t)}async getSetupStatus(){return this.getUtilityService().getSetupStatus()}async markSetupComplete(){return this.getUtilityService().markSetupComplete()}};We(Pn,"instance");let Pt=Pn;const Ye=Pt.getInstance();let _r=null,Tr=null;const Gi=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,ds=un((e,t)=>({config:null,proxyAuthStatus:null,isLoadingConfig:!1,isLoadingProxyAuthStatus:!1,lastLoadedAt:null,error:null,loadConfig:async({force:s=!1}={})=>{const n=t().config;if(!s&&n)return n;if(_r)return _r;_r=(async()=>{e({isLoadingConfig:!0,error:null});try{const o=await Ye.getBambooConfig()??{};return e({config:o,lastLoadedAt:Date.now(),error:null}),o}catch(o){const a=Gi(o,"Failed to load Bamboo config");throw e({error:a}),o}finally{e({isLoadingConfig:!1})}})();try{return await _r}finally{_r=null}},saveConfig:async s=>{e({isLoadingConfig:!0,error:null,config:s});try{const n=await Ye.setBambooConfig(s);return e({config:n,lastLoadedAt:Date.now(),error:null}),n}catch(n){const o=Gi(n,"Failed to save Bamboo config");throw e({error:o}),n}finally{e({isLoadingConfig:!1})}},patchConfig:async s=>{const o={...await t().loadConfig()??{},...s??{}};return t().saveConfig(o)},loadProxyAuthStatus:async({force:s=!1}={})=>{const n=t().proxyAuthStatus;if(!s&&n)return n;if(Tr)return Tr;Tr=(async()=>{e({isLoadingProxyAuthStatus:!0,error:null});try{const o=await Ye.getProxyAuthStatus();return e({proxyAuthStatus:o,error:null}),o}catch(o){const a=Gi(o,"Failed to load proxy auth status");throw e({error:a}),o}finally{e({isLoadingProxyAuthStatus:!1})}})();try{return await Tr}finally{Tr=null}},applyProxyAuth:async s=>{await Ye.setProxyAuth(s),await t().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await Ye.clearProxyAuth(),await t().loadProxyAuthStatus({force:!0})}}));let kr=null;const Bb=(e,t)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:s=>{e({selectedModel:s})},loadConfigModel:async()=>{try{const s=await ds.getState().loadConfig(),n=typeof(s==null?void 0:s.model)=="string"?s.model:void 0;n&&e({configModel:n})}catch(s){console.error("Failed to load model from config:",s)}},fetchModels:async()=>{if(kr)return kr;kr=(async()=>{e({isLoadingModels:!0,modelsError:null});try{try{if(!(await Ye.getSetupStatus()).is_complete){He("[ModelSlice]","Setup not complete, skipping model fetch"),e({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:"Complete setup to access all models"});return}}catch(n){console.error("Failed to check setup status:",n)}const s=await Ei.getModels();e(n=>{const o=n.selectedModel;let a=n.selectedModel;return o&&s.includes(o)||(s.length>0?a=s[0]:a=void 0),{...n,models:s,selectedModel:a,modelsError:s.length>0?null:"No available model options"}}),t().models.length===0&&console.warn("No models available from service")}catch(s){const n=s instanceof Error?s.message:String(s);if(console.error("Failed to fetch models:",s),s instanceof ri){e(o=>({...o,models:o.models,selectedModel:o.selectedModel,modelsError:n||"Proxy authentication required. Please configure proxy auth."}));return}e(o=>({...o,models:[],selectedModel:o.selectedModel,modelsError:n}))}finally{e({isLoadingModels:!1})}})();try{await kr}finally{kr=null}}}),Wb=["system_prompt","system_prompt_selected_id"],Ji=e=>({id:e.id,name:e.name||e.id,content:e.content||"",description:e.description,isDefault:!!e.is_default}),rn=class rn{constructor(){We(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return rn.instance||(rn.instance=new rn),rn.instance.cleanupDeprecatedPromptStorageKeys(),rn.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const t of Wb)localStorage.removeItem(t)}catch(t){console.warn("[SystemPromptService] Failed to cleanup deprecated prompt storage keys:",t)}}}async getSystemPromptPresets(){try{const t=await Se.get("prompt-presets"),n=(Array.isArray(t==null?void 0:t.prompts)?t.prompts:[]).filter(o=>o.id&&o.id.trim().length>0).map(Ji);if(n.length>0)return n}catch(t){console.error("Failed to load prompt presets from backend:",t)}return ni()}async createSystemPromptPreset(t){var o;const s={name:t.name,content:t.content};(o=t.id)!=null&&o.trim()&&(s.id=t.id.trim()),t.description!==void 0&&(s.description=t.description);const n=await Se.post("prompt-presets",s);if(!(n!=null&&n.prompt))throw new Error("Backend did not return created prompt preset");return Ji(n.prompt)}async updateSystemPromptPreset(t){const s=encodeURIComponent(t.id),n={name:t.name,content:t.content,description:t.description},o=await Se.patch(`prompt-presets/${s}`,n);if(!(o!=null&&o.prompt))throw new Error("Backend did not return updated prompt preset");return Ji(o.prompt)}async deleteSystemPromptPreset(t){const s=encodeURIComponent(t);await Se.delete(`prompt-presets/${s}`)}async findPresetById(t){return(await this.getSystemPromptPresets()).find(n=>n.id===t)}async getCurrentSystemPromptContent(t){const s=await this.findPresetById(t);if(s)return s.content;const n=await this.getSystemPromptPresets(),o=n.find(a=>a.isDefault)||n[0];return(o==null?void 0:o.content)||""}};We(rn,"instance");let ai=rn;const Jd="copilot_last_selected_prompt_id",qp="copilot_custom_system_prompts_v2",Hp="copilot_custom_system_prompts_v2_migrated_to_backend",Yp="general_assistant",Zc=80,tr=ai.getInstance();let ga=null;function ed(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,Zc)}function Xp(e){if(typeof e!="string")return null;const t=e.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return t?t.slice(0,Zc):null}function Vp(e,t){if(!t.has(e))return e;let s=2;for(;;){const n=`_${s}`,a=`${e.slice(0,Math.max(0,Zc-n.length))}${n}`;if(!t.has(a))return a;s+=1}}function Kp(){try{const e=localStorage.getItem(qp);if(!e)return[];const t=JSON.parse(e);if(!Array.isArray(t))return[];const s=new Set,n=[];for(const o of t){const a=typeof(o==null?void 0:o.name)=="string"?o.name.trim():"",i=typeof(o==null?void 0:o.content)=="string"?o.content.trim():"";if(!a||!i)continue;const c=Xp(o==null?void 0:o.id)||ed(a),d=Vp(c,s);d!==Yp&&(s.add(d),n.push({id:d,name:a,content:i,description:typeof(o==null?void 0:o.description)=="string"&&o.description.trim()||void 0,isDefault:!!(o!=null&&o.isDefault)}))}return n}catch(e){return console.error("[promptSlice] Failed to read legacy custom prompts:",e),[]}}function Gp(){try{return localStorage.getItem(Hp)==="1"}catch(e){return console.error("[promptSlice] Failed to read migration marker:",e),!1}}function Qd(){try{localStorage.setItem(Hp,"1")}catch(e){console.error("[promptSlice] Failed to write migration marker:",e)}}function Zd(){try{localStorage.removeItem(qp)}catch(e){console.error("[promptSlice] Failed to clear legacy custom prompts:",e)}}async function Ub(){var o,a;if(Gp())return;const e=Kp();if(e.length===0){Zd(),Qd();return}const t=await tr.getSystemPromptPresets(),s=new Set(t.map(i=>i.id));let n=!1;for(const i of e){const l=(o=i.name)==null?void 0:o.trim(),c=(a=i.content)==null?void 0:a.trim();if(!l||!c||i.id===Yp||i.isDefault)continue;const d=Xp(i.id)||ed(l),u=Vp(d,s);try{const h=await tr.createSystemPromptPreset({id:u,name:l,content:c,description:i.description});s.add(h.id)}catch(h){n=!0,console.error(`[promptSlice] Failed to migrate legacy prompt '${l}' to backend:`,h)}}n||(Zd(),Qd())}async function qb(){ga||(ga=Ub().finally(()=>{ga=null})),await ga}const Hb=(e,t)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(Jd)||null,loadSystemPrompts:async()=>{try{await qb()}catch(o){console.warn("[promptSlice] Legacy prompt migration skipped:",o)}let s=[];try{s=await tr.getSystemPromptPresets()}catch(o){console.error("Failed to load system prompts from backend:",o)}let n=s.length?s:ni();if(!Gp()){const o=Kp();n=Yb(n,o)}n.length===0&&(n=ni()),e({systemPrompts:n})},addSystemPrompt:async s=>{try{await tr.createSystemPromptPreset({id:ed(s.name),name:s.name,content:s.content,description:s.description}),await t().loadSystemPrompts()}catch(n){throw console.error("Failed to add system prompt:",n),n}},updateSystemPrompt:async s=>{try{await tr.updateSystemPromptPreset(s),await t().loadSystemPrompts()}catch(n){throw console.error("Failed to update system prompt:",n),n}},deleteSystemPrompt:async s=>{try{await tr.deleteSystemPromptPreset(s),await t().loadSystemPrompts()}catch(n){throw console.error("Failed to delete system prompt:",n),n}},setLastSelectedPromptId:s=>{e({lastSelectedPromptId:s});try{localStorage.setItem(Jd,s)}catch(n){console.error("Failed to save last selected prompt ID to localStorage:",n)}}}),Yb=(e,t)=>{const s=new Map;return e.forEach(n=>{s.set(n.id,n)}),t.forEach(n=>{s.set(n.id,n)}),Array.from(s.values())},Xb=(e,t)=>({currentRequestController:null,setCurrentRequestController:s=>{e({currentRequestController:s})},cancelCurrentRequest:()=>{var s;(s=t().currentRequestController)==null||s.abort(),t().processingChats.forEach(n=>{t().setSessionProcessing(n,!1)}),e({currentRequestController:null})}});class Vb{async listSkills(t,s){const n=new URLSearchParams;t!=null&&t.search&&n.append("search",t.search),t!=null&&t.includeDisabled&&n.append("include_disabled","true"),s&&n.append("refresh","true");const o=n.toString(),a=o?`skills?${o}`:"skills";return Te.get(a)}async getSkill(t){return Te.get(`skills/${t}`)}async getFilteredTools(t){const s=t?`?session_id=${encodeURIComponent(t)}`:"";return(await Te.get(`skills/filtered-tools${s}`)).tools??[]}}const Ql=new Vb,Kb=(e,t)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(s,n)=>{e({isLoadingSkills:!0,skillsError:null});try{const o=await Ql.listSkills(s,n);e({skills:o.skills,isLoadingSkills:!1})}catch(o){e({skillsError:o instanceof Error?o.message:Kt.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async s=>{e({isLoadingSkills:!0,skillsError:null});try{const n=await Ql.getSkill(s),o=t().skills,i=o.findIndex(l=>l.id===n.id)>=0?o.map(l=>l.id===n.id?n:l):[...o,n];e({skills:i,isLoadingSkills:!1})}catch(n){e({skillsError:n instanceof Error?n.message:Kt.t("components.skillManager.getFailed"),isLoadingSkills:!1})}},clearSkillsError:()=>{e({skillsError:null})}}),Gb=e=>({tokenUsages:{},truncationOccurred:{},segmentsRemoved:{},updateTokenUsage:(t,s)=>e(n=>({tokenUsages:{...n.tokenUsages,[t]:s}})),setTruncationInfo:(t,s,n)=>e(o=>({truncationOccurred:{...o.truncationOccurred,[t]:s},segmentsRemoved:{...o.segmentsRemoved,[t]:n}})),clearTokenUsage:t=>e(s=>{const{[t]:n,...o}=s.tokenUsages,{[t]:a,...i}=s.truncationOccurred,{[t]:l,...c}=s.segmentsRemoved;return{tokenUsages:o,truncationOccurred:i,segmentsRemoved:c}})}),Jb=(e,t)=>({taskLists:{},taskListVersions:{},activeItems:{},evaluationStates:{},setTaskList:(s,n)=>e(o=>({taskLists:{...o.taskLists,[s]:n},taskListVersions:{...o.taskListVersions,[s]:n.version||0}})),updateTaskListDelta:(s,n)=>e(o=>{const a=o.taskListVersions[s]||0;if(n.version<=a)return o;const i=o.taskLists[s];if(!i)return o;const l=i.items.map(c=>c.id===n.item_id?{...c,status:n.status,tool_calls_count:n.tool_calls_count}:c);return{taskLists:{...o.taskLists,[s]:{...i,items:l,updated_at:new Date().toISOString()}},taskListVersions:{...o.taskListVersions,[s]:n.version},activeItems:{...o.activeItems,[s]:n.status==="in_progress"?n.item_id:null}}}),clearTaskList:s=>e(n=>{const{[s]:o,...a}=n.taskLists,{[s]:i,...l}=n.taskListVersions,{[s]:c,...d}=n.activeItems,{[s]:u,...h}=n.evaluationStates;return{taskLists:a,taskListVersions:l,activeItems:d,evaluationStates:h}}),getTaskListVersion:s=>t().taskListVersions[s]||0,setEvaluationState:(s,n)=>e(o=>({evaluationStates:{...o.evaluationStates,[s]:n}})),clearEvaluationState:s=>e(n=>{const{[s]:o,...a}=n.evaluationStates;return{evaluationStates:a}})}),Jp="chat_input_reasoning_by_session_v1",Qp="chat_input_reasoning_last_used_v1",eu={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},td=e=>e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",Zp=()=>{if(typeof window>"u")return{};try{const e=localStorage.getItem(Jp);if(!e)return{};const t=JSON.parse(e),s={};for(const[n,o]of Object.entries(t||{}))td(o)&&(s[n]=o);return s}catch{return{}}},Qb=e=>{if(!(typeof window>"u"))try{localStorage.setItem(Jp,JSON.stringify(e))}catch{}},Zb=()=>{if(!(typeof window>"u"))try{const e=localStorage.getItem(Qp);return td(e)?e:void 0}catch{return}},ev=e=>{if(!(typeof window>"u"))try{localStorage.setItem(Qp,e)}catch{}},sd=e=>{const t=Zp();return td(t[e])?t[e]:Zb()},Cr=e=>({...eu,reasoningEffort:sd(e)??eu.reasoningEffort}),tv=(e,t)=>({inputStates:{},pendingQuestionRespond:null,setInputContent:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Cr(s),content:n}}})),setReferenceText:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Cr(s),referenceText:n}}})),setAttachments:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Cr(s),attachments:n}}})),setInputReasoningEffort:(s,n)=>{e(a=>({inputStates:{...a.inputStates,[s]:{...a.inputStates[s]||Cr(s),reasoningEffort:n}}}));const o=Zp();o[s]=n,Qb(o),ev(n)},clearInputState:s=>e(n=>{const{[s]:o,...a}=n.inputStates;return{inputStates:a}}),getInputState:s=>t().inputStates[s]||Cr(s),setPendingQuestionRespond:s=>e({pendingQuestionRespond:s}),clearPendingQuestionRespondForSession:s=>e(n=>{var o;return((o=n.pendingQuestionRespond)==null?void 0:o.sessionId)!==s?{}:{pendingQuestionRespond:null}})}),sv="bamboo_proxy_auth",nv=()=>{try{const e=localStorage.getItem(sv);if(!e)return null;const t=JSON.parse(e);if(!t||typeof t!="object")return null;const s=typeof t.username=="string"?t.username.trim():"",n=typeof t.password=="string"?t.password:"";return s?{username:s,password:n}:null}catch{return null}},rv="auto",ov="required",av=1e4,iv=2e3,lv=hs.getInstance();let tu=null,jr=null,su=null,Mr=null;const nu=new WeakMap,z=un()(gb(xb((e,t,s)=>({...Lb(e,t),...Bb(e,t),...Hb(e,t),...Xb(e,t),...Kb(e,t),...Gb(e),...Jb(e,t),...tv(e,t),agentAvailability:null,setAgentAvailability:n=>{e({agentAvailability:n})},checkAgentAvailability:async()=>{if(jr)return jr;jr=(async()=>{const n=await lv.healthCheck();return t().agentAvailability!==n&&e({agentAvailability:n}),n})();try{return await jr}finally{jr=null}},startAgentHealthCheck:()=>{tu||(t().checkAgentAvailability(),tu=setInterval(()=>{t().checkAgentAvailability()},av))},refreshSessionsIndex:async()=>{if(Mr)return Mr;Mr=(async()=>{try{await t().refreshChats()}catch(n){console.warn("[AppStore] refreshChats failed:",n)}})();try{return await Mr}finally{Mr=null}},startSessionsIndexSync:()=>{su||(t().refreshSessionsIndex(),su=setInterval(()=>{t().refreshSessionsIndex()},iv))}})),{name:"AppStore"})),ef=e=>{const t=nu.get(e);if(t)return t;const s=new Map(e.map(n=>[n.id,n]));return nu.set(e,s),s},xr=e=>t=>e?ef(t.chats).get(e)??null:null,cv=e=>e.currentSessionId?ef(e.chats).get(e.currentSessionId)??null:null,ru=async()=>{const e=nv();if(!e)return!1;try{return await Ye.setProxyAuth(e),!0}catch(t){return console.error("Failed to apply stored proxy auth during startup:",t),!1}},dv=async()=>{try{const e=await ds.getState().loadConfig();if((typeof(e==null?void 0:e.proxy_auth_mode)=="string"?e.proxy_auth_mode:rv)!==ov)return await ru(),!1;const s=await ds.getState().loadProxyAuthStatus({force:!0});return s!=null&&s.configured||await ru()?!1:(z.setState(o=>({...o,models:[],selectedModel:void 0,modelsError:"Proxy auth mode is set to required. Please configure proxy username/password and apply it.",isLoadingModels:!1})),!0)}catch(e){return console.error("Failed to evaluate startup proxy auth mode:",e),!1}};let ou=!1;const uv=async(e=!1)=>{if(ou&&!e)return;ou=!0,z.getState().startAgentHealthCheck(),z.getState().startSessionsIndexSync(),await z.getState().loadChats(),await dv()||await z.getState().fetchModels(),await z.getState().loadSystemPrompts()},On={'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:au,Paragraph:mv}=le,hv=({content:e,token:t,showGradient:s,onClick:n})=>r.jsx(te,{size:"small",style:{marginLeft:t.marginLG,marginTop:t.marginXS,backgroundColor:t.colorBgLayout,borderColor:t.colorBorderSecondary},bodyStyle:{padding:t.paddingMD},onClick:n,children:r.jsxs("div",{style:{maxHeight:"60vh",overflowY:"auto",position:"relative",paddingRight:t.paddingXS},children:[r.jsx(us,{remarkPlugins:[wi],components:{p:({children:o})=>r.jsx(mv,{style:{marginBottom:t.marginSM},children:o}),ol:({children:o})=>r.jsx("ol",{style:{marginBottom:t.marginSM,paddingLeft:t.paddingLG},children:o}),ul:({children:o})=>r.jsx("ul",{style:{marginBottom:t.marginSM,paddingLeft:t.paddingLG},children:o}),li:({children:o})=>r.jsx("li",{style:{marginBottom:t.marginXS},children:o}),h1:({children:o})=>r.jsx(au,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block"},children:o}),h2:({children:o})=>r.jsx(au,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block"},children:o}),code:({inline:o,className:a,children:i,...l})=>{const c=/language-(\w+)/.exec(a||"");return o?r.jsx("code",{className:a,style:{backgroundColor:t.colorFillTertiary,padding:"0 4px",borderRadius:t.borderRadiusSM,fontSize:t.fontSizeSM},...l,children:i}):r.jsx(ir,{style:On,language:(c==null?void 0:c[1])||"text",PreTag:"div",wrapLongLines:!0,children:String(i).replace(/\n$/,"")})}},children:e||"No content available."}),s?r.jsx("div",{style:{position:"sticky",bottom:0,height:48,background:`linear-gradient(180deg, transparent, ${t.colorBgLayout})`,pointerEvents:"none",marginTop:-48}}):null]})}),{Text:Qi,Paragraph:pv}=le,fv=({prompt:e,token:t,isSelected:s,isExpanded:n,onSelect:o,onToggleExpand:a,onCopy:i})=>{const{t:l}=se(),c=e.content||"",{nonEmptyLineCount:d,wordCount:u,characterCount:h,showGradient:p}=m.useMemo(()=>{const g=(c?c.split(/\r?\n/):[]).filter(x=>x.trim().length>0).length,f=c.trim()?c.trim().split(/\s+/).filter(Boolean).length:0,b=c.length;return{nonEmptyLineCount:g,wordCount:f,characterCount:b,showGradient:!n&&b>600}},[c,n]);return r.jsx(Ge.Item,{style:{cursor:"pointer",padding:t.paddingMD,borderRadius:t.borderRadius,border:s?`2px solid ${t.colorPrimary}`:`1px solid ${t.colorBorderSecondary}`,marginBottom:t.marginXS,backgroundColor:s?t.colorPrimaryBg:t.colorBgContainer,transition:"all 0.2s ease"},onClick:()=>o(e.id),children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:t.marginSM,children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",width:"100%",gap:t.marginSM},children:[r.jsxs(q,{align:"start",children:[r.jsx(Gt,{checked:s,onChange:()=>o(e.id),onClick:y=>y.stopPropagation()}),r.jsxs("div",{children:[r.jsx(Qi,{strong:!0,children:e.name||e.id}),r.jsx("div",{children:r.jsx(Qi,{code:!0,style:{fontSize:t.fontSizeSM,color:t.colorTextSecondary},children:e.id})})]}),e.isDefault?r.jsx(fe,{color:"warning",children:l("chat.systemPromptSelector.defaultTag")}):null]}),r.jsxs(q,{size:"small",children:[r.jsx(B,{type:"text",size:"small",icon:n?r.jsx(hx,{}):r.jsx(qc,{}),onClick:y=>{y.stopPropagation(),a(e.id)},children:l(n?"chat.systemPromptSelector.hide":"chat.systemPromptSelector.preview")}),r.jsx(B,{type:"text",size:"small",icon:r.jsx(Jt,{}),onClick:y=>i(y,e),children:l("chat.systemPromptSelector.copy")})]})]}),e.description?r.jsx(Qi,{type:"secondary",style:{marginLeft:t.marginLG,fontSize:t.fontSizeSM},children:e.description}):null,r.jsxs(q,{size:"small",wrap:!0,style:{marginLeft:t.marginLG},children:[r.jsx(fe,{color:"processing",children:l("chat.systemPromptSelector.lines",{count:d})}),r.jsx(fe,{color:"purple",children:l("chat.systemPromptSelector.words",{count:u})}),r.jsx(fe,{color:"success",children:l("chat.systemPromptSelector.chars",{count:h})})]}),n?r.jsx(hv,{content:c,token:t,showGradient:p,onClick:y=>y.stopPropagation()}):r.jsx(pv,{type:"secondary",ellipsis:{rows:3},style:{marginLeft:t.marginLG,marginBottom:0,color:t.colorTextSecondary},children:c||l("chat.systemPromptSelector.noContent")})]})},e.id)},{Text:gv}=le,{useToken:yv}=xe,xv=({open:e,onClose:t,onSelect:s,prompts:n,title:o,showCancelButton:a=!0})=>{const{t:i}=se(),{token:l}=yv(),[c,d]=pe.useMessage(),u=z(_=>_.lastSelectedPromptId),h=z(_=>_.setLastSelectedPromptId),[p,y]=m.useState(null),[g,f]=m.useState(null),b=m.useMemo(()=>n.filter(_=>_.id&&_.id.trim()!==""),[n]),x=async(_,T)=>{_.stopPropagation();const j=T.content??"";try{await es(j),c.success(i("success.promptCopied",{name:T.name}))}catch(v){console.error("[SystemPromptSelector] Failed to copy prompt:",v),c.error(i("error.copyPromptFailed"))}},S=o??i("chat.prompt.selectorTitle");m.useEffect(()=>{if(e){const _=b.find(j=>j.isDefault),T=u||(_==null?void 0:_.id)||(b.length>0?b[0].id:null);y(T)}},[e,u,b.length]);const w=_=>{y(_.id),h(_.id),s(_),t()},C=()=>{t()};return r.jsxs(r.Fragment,{children:[d,r.jsxs(Et,{title:r.jsxs(q,{children:[r.jsx(hr,{}),S]}),open:e,onCancel:C,width:700,footer:r.jsx(ab,{buttons:[...a?[ib(C)]:[],lb(()=>{const _=b.find(T=>T.id===p);_&&w(_)},{text:i("chat.prompt.createButton"),disabled:!p})]}),styles:{body:{maxHeight:"70vh",overflowY:"auto",padding:l.paddingMD}},children:[r.jsx("div",{style:{marginBottom:l.marginMD},children:r.jsx(gv,{type:"secondary",style:{fontSize:l.fontSizeSM},children:i("chat.prompt.helperText")})}),b.length===0?r.jsx(Qt,{description:i("chat.prompt.emptyDescription"),style:{margin:l.marginLG}}):r.jsx("div",{children:b.map(_=>r.jsx(fv,{prompt:_,token:l,isSelected:p===_.id,isExpanded:g===_.id,onSelect:T=>y(T),onToggleExpand:T=>f(g===T?null:T),onCopy:x},_.id))})]})]})},bv=({chat:e,isSelected:t,onSelect:s,onDelete:n,onPin:o,onUnpin:a,onEdit:i,onGenerateTitle:l,isGeneratingTitle:c,titleGenerationError:d})=>{const{t:u}=se(),[h,p]=m.useState(!1),[y,g]=m.useState(e.title),[f,b]=m.useState(!1),[x,S]=m.useState(!1),{token:w}=xe.useToken(),C=m.useCallback(M=>{M.stopPropagation(),i&&y.trim()&&i(e.id,y.trim()),p(!1)},[e.id,y,i]),_=m.useCallback(M=>{M.stopPropagation(),g(e.title),p(!1)},[e.title]),T=[{key:"pin",icon:e.pinned?r.jsx(Vl,{style:{color:w.colorWarning}}):r.jsx(Za,{}),label:e.pinned?u("chat.actions.unpin"):u("chat.actions.pin"),onClick:({domEvent:M})=>{M.stopPropagation(),e.pinned?a(e.id):o(e.id)}},{key:"edit",icon:r.jsx(pr,{}),label:u("chat.chatItem.edit"),onClick:({domEvent:M})=>{M.stopPropagation(),p(!0)}},...l?[{key:"generate-title",icon:c?r.jsx(ta,{}):r.jsx(kp,{style:d?{color:w.colorError}:void 0}),label:d||u("chat.actions.generateTitle"),disabled:c,onClick:({domEvent:M})=>{M.stopPropagation(),l(e.id)}}]:[],{type:"divider"},{key:"delete",icon:r.jsx(cn,{}),label:u("common.delete"),danger:!0,onClick:({domEvent:M})=>{M.stopPropagation(),n(e.id)}}],j={padding:"8px 12px",borderRadius:w.borderRadiusSM,marginBottom:w.marginXXS,cursor:"pointer",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)",backgroundColor:t?"var(--lotus-primary-soft)":f||x?"var(--lotus-item-hover-bg)":"transparent",border:"1px solid transparent",borderColor:t?"var(--lotus-tool-card-border)":f||x?w.colorBorderSecondary:"transparent",position:"relative",overflow:"visible",boxShadow:t?"var(--lotus-tool-card-shadow)":"none",transform:f&&!t?"translateX(2px)":"none"},v={flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontSize:13,fontWeight:t?600:500,color:t?"var(--lotus-primary)":w.colorText},k={flex:1,fontSize:w.fontSizeSM,marginRight:w.marginSM},E=h?[r.jsx(B,{type:"text",size:"small",icon:r.jsx(px,{style:{color:w.colorSuccess}}),onClick:C,"aria-label":u("common.save")},"save"),r.jsx(B,{type:"text",size:"small",icon:r.jsx(fr,{style:{color:w.colorError}}),onClick:_,"aria-label":u("common.cancel")},"cancel")]:f||x?[r.jsx(lr,{menu:{items:T},trigger:["click"],placement:"bottomRight",open:x,onOpenChange:M=>S(M),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(fx,{}),"aria-label":u("common.moreActions","More actions"),onClick:M=>M.stopPropagation(),style:{color:w.colorTextSecondary,borderRadius:w.borderRadiusSM,background:w.colorFillTertiary,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return r.jsx(Ge.Item,{style:j,tabIndex:0,onClick:()=>!h&&s(e.id),onKeyDown:M=>{M.key==="Enter"&&!h?(M.preventDefault(),s(e.id)):(M.key==="Delete"||M.key==="Backspace")&&!h&&M.metaKey&&(M.preventDefault(),n(e.id))},onMouseEnter:()=>b(!0),onMouseLeave:()=>{x||b(!1)},onFocus:()=>b(!0),onBlur:()=>{x||b(!1)},actions:E,"data-testid":"chat-item",role:"option","aria-selected":t,"aria-label":e.title||u("chat.sidebar.untitledChat"),children:r.jsx(Ge.Item.Meta,{title:h?r.jsx(ye,{value:y,onChange:M=>g(M.target.value),onClick:M=>M.stopPropagation(),onPressEnter:M=>{M.preventDefault(),C(M)},autoFocus:!0,style:k,variant:"borderless",size:"small"}):r.jsxs("div",{style:{...v,display:"flex",alignItems:"center",gap:w.marginXS,minWidth:0},children:[e.pinned&&r.jsx(Vl,{style:{color:w.colorWarning,fontSize:11,flexShrink:0}}),r.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.title}),e.kind==="child"?r.jsx(fe,{color:"processing",style:{marginInlineEnd:0,flex:"0 0 auto"},children:u("chat.chatItem.childTag")}):null]})})})},vv=(e,t)=>e.chat.id===t.chat.id&&e.chat.title===t.chat.title&&e.chat.pinned===t.chat.pinned&&e.isSelected===t.isSelected&&e.isGeneratingTitle===t.isGeneratingTitle&&e.titleGenerationError===t.titleGenerationError,Zl=m.memo(bv,vv);Zl.displayName="ChatItem";const iu=e=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[e]??4,Sv=e=>{const t={},s=e.filter(o=>o.pinned);s.length>0&&(t.Pinned=s.sort((o,a)=>a.createdAt-o.createdAt));const n=e.filter(o=>!o.pinned&&!!o.createdByScheduleId);return n.length>0&&(t.Scheduled=n.sort((o,a)=>a.createdAt-o.createdAt)),e.filter(o=>!o.pinned&&!o.createdByScheduleId).forEach(o=>{const i=new Date(o.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});t[i]||(t[i]=[]),t[i].push(o)}),Object.keys(t).forEach(o=>{t[o].sort((a,i)=>i.createdAt-a.createdAt)}),t},wv=e=>{const t=s=>Array.isArray(s)?s.reduce((n,o)=>Math.max(n,o.createdAt),0):Object.values(s).reduce((n,o)=>{const a=o.reduce((i,l)=>Math.max(i,l.createdAt),0);return Math.max(n,a)},0);return Object.keys(e).sort((s,n)=>{if(s==="Pinned")return-1;if(n==="Pinned")return 1;if(s==="Scheduled")return-1;if(n==="Scheduled")return 1;const o=e[s],a=e[n];if(!o||!a)return 0;const i=t(o),l=t(a);return i!==l?l-i:iu(s)-iu(n)})},_v=(e,t)=>e[t]?e[t].map(s=>s.id):[],tf=(e,t)=>e[t]?e[t].length:0,lu=e=>e.pinned?"Pinned":e.createdByScheduleId?"Scheduled":new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),cu=(e,t)=>{const n={Today:"chat.sidebar.dateGroups.today",Yesterday:"chat.sidebar.dateGroups.yesterday","This Week":"chat.sidebar.dateGroups.thisWeek","This Month":"chat.sidebar.dateGroups.thisMonth",Pinned:"chat.sidebar.dateGroups.pinned",Scheduled:"chat.sidebar.dateGroups.scheduled"}[e];return n?t(n):e},Tv=({groupedChatsByDate:e,childrenByRoot:t,expandedRootIds:s,onToggleRootExpanded:n,sortedDateKeys:o,expandedKeys:a,onCollapseChange:i,currentSessionId:l,onSelectChat:c,onDeleteChat:d,onDeleteByDate:u,onPinChat:h,onUnpinChat:p,onEditTitle:y,onGenerateTitle:g,titleGenerationState:f,token:b,hasActiveFilters:x})=>{const{t:S}=se(),w=m.useMemo(()=>o.length?o.map(_=>{const T=e[_],j=tf(e,_);return{dateKey:_,dateGroup:T,totalChatsInDate:j}}):[],[e,o]);if(!o.length)return r.jsx(Qt,{image:Qt.PRESENTED_IMAGE_SIMPLE,description:r.jsxs(q,{direction:"vertical",size:4,align:"center",children:[r.jsx("span",{style:{color:b.colorTextSecondary},children:x?S("chat.sidebar.empty.noMatches","No matching sessions"):S("chat.sidebar.empty.noSessions")}),r.jsx("span",{style:{color:b.colorTextSecondary,fontSize:12},children:x?S("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):S("chat.sidebar.empty.hint")}),x&&r.jsx(B,{size:"small",type:"link",onClick:()=>{var T;const _=document.querySelector('[data-testid="sidebar-search-input"] input, .lotus-sidebar-search input');if(_){const j=(T=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value"))==null?void 0:T.set;j==null||j.call(_,""),_.dispatchEvent(new Event("input",{bubbles:!0}))}},children:S("chat.sidebar.empty.clearFilters","Clear filters")})]})});const C=new Set(a);return r.jsx(q,{direction:"vertical",size:"small",style:{width:"100%"},children:w.map(({dateKey:_,dateGroup:T,totalChatsInDate:j})=>{const v=C.has(_);return r.jsxs("div",{style:{borderRadius:b.borderRadiusSM,background:v?b.colorFillTertiary:"transparent",padding:4},children:[r.jsxs(K,{align:"center",justify:"space-between",style:{cursor:"pointer",padding:"8px 12px",borderRadius:b.borderRadiusSM,transition:"all 0.2s ease",border:"1px solid transparent"},role:"button",tabIndex:0,"aria-expanded":v,"aria-label":`${cu(_,S)} (${j})`,onKeyDown:k=>{if(k.key==="Enter"||k.key===" "){k.preventDefault();const E=new Set(C);E.has(_)?E.delete(_):E.add(_),i(Array.from(E))}},onMouseEnter:k=>{k.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.92))",k.currentTarget.style.borderColor="var(--lotus-sidebar-item-hover-border, rgba(13, 148, 136, 0.28))";const E=k.currentTarget.querySelector(".chat-sidebar-date-group-delete");E&&(E.style.opacity="1")},onMouseLeave:k=>{k.currentTarget.style.background="transparent",k.currentTarget.style.borderColor="transparent";const E=k.currentTarget.querySelector(".chat-sidebar-date-group-delete");E&&(E.style.opacity="0")},onClick:()=>{const k=new Set(C);k.has(_)?k.delete(_):k.add(_),i(Array.from(k))},className:"chat-sidebar-date-group-header",children:[r.jsxs(K,{align:"center",gap:"small",style:{minWidth:0},children:[v?r.jsx(Zt,{style:{fontSize:12,opacity:.6}}):r.jsx(Bs,{style:{fontSize:12,opacity:.6}}),r.jsxs("span",{style:{fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:_==="Today"?"var(--lotus-primary)":b.colorTextSecondary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[cu(_,S)," (",j,")"]})]}),r.jsx(B,{type:"text",size:"small",icon:r.jsx(cn,{}),className:"chat-sidebar-date-group-delete",style:{color:b.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:k=>{k.stopPropagation(),u(_)}})]}),v?r.jsx("div",{style:{marginTop:4},children:r.jsx(Ge,{itemLayout:"horizontal",dataSource:T,split:!1,renderItem:k=>{var E,M,R,I,P;return r.jsxs("div",{children:[r.jsxs(K,{align:"center",gap:6,children:[(E=t[k.id])!=null&&E.length?r.jsx(B,{size:"small",type:"text",style:{padding:0,width:22},"aria-label":s.has(k.id)?S("chat.sidebar.actions.collapseChildren"):S("chat.sidebar.actions.expandChildren"),onClick:L=>{L.preventDefault(),L.stopPropagation(),n(k.id)},children:s.has(k.id)?r.jsx(Zt,{}):r.jsx(Bs,{})}):r.jsx("div",{style:{width:22}}),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsx(Zl,{chat:k,isSelected:k.id===l,onSelect:c,onDelete:d,onPin:h,onUnpin:p,onEdit:y,onGenerateTitle:g,isGeneratingTitle:((M=f[k.id])==null?void 0:M.status)==="loading",titleGenerationError:((R=f[k.id])==null?void 0:R.status)==="error"?(I=f[k.id])==null?void 0:I.error:void 0})})]}),s.has(k.id)&&(((P=t[k.id])==null?void 0:P.length)??0)>0?r.jsx("div",{style:{marginLeft:22,marginTop:2},children:r.jsx(Ge,{itemLayout:"horizontal",dataSource:t[k.id],split:!1,renderItem:L=>{var O,A,$;return r.jsx("div",{style:{paddingLeft:12},children:r.jsx(Zl,{chat:L,isSelected:L.id===l,onSelect:c,onDelete:d,onPin:h,onUnpin:p,onEdit:y,onGenerateTitle:g,isGeneratingTitle:((O=f[L.id])==null?void 0:O.status)==="loading",titleGenerationError:((A=f[L.id])==null?void 0:A.status)==="error"?($=f[L.id])==null?void 0:$.error:void 0})},L.id)}})}):null]},k.id)}})}):null]},_)})})},kv="copilot_ui_theme_v1";function Cv(){var e;try{const t=localStorage.getItem(kv);if(t==="light"||t==="dark")return t}catch{}return(e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const Dn=un(e=>({themeMode:Cv(),setThemeMode:t=>e({themeMode:t}),toggleTheme:()=>e(t=>({themeMode:t.themeMode==="dark"?"light":"dark"}))})),jv="2026.3.111",Mv={version:jv},nd=Mv.version,{Text:Pv}=le,Ev=({collapsed:e,onNewChat:t,onOpenSettings:s,screens:n,token:o})=>{const{t:a}=se(),i=Dn(h=>h.themeMode),l=Dn(h=>h.toggleTheme),c=a("chat.sidebar.newSession"),d=a("settings.page.title"),u=i==="dark"?a("settings.app.lightMode","Light mode"):a("settings.app.darkMode","Dark mode");return r.jsxs(K,{vertical:!0,gap:e?"small":"middle",style:{padding:e?10:16,background:"transparent",borderTop:`1px solid ${o.colorBorderSecondary}`},children:[r.jsx(B,{"data-testid":"new-chat",type:"primary",icon:r.jsx(ks,{}),onClick:t,block:!e,shape:"default",size:e?"large":n.xs?"small":"middle",title:c,"aria-label":c,className:"lotus-primary-cta",style:{...e?{width:"44px",height:"44px",margin:"0 auto"}:{},borderRadius:o.borderRadiusLG,minHeight:e?44:46,fontWeight:600},children:!e&&c}),r.jsxs(K,{gap:8,align:"center",children:[r.jsx(B,{"data-testid":"open-settings",icon:r.jsx(sa,{}),onClick:s,block:!e,shape:"default",size:e?"large":n.xs?"small":"middle",title:d,"aria-label":d,className:"lotus-secondary-button",style:{...e?{width:"44px",height:"44px",margin:"0 auto"}:{},borderRadius:o.borderRadiusLG,minHeight:44,flex:e?void 0:1},children:!e&&d}),!e&&r.jsx(je,{title:u,placement:"top",children:r.jsx(B,{"data-testid":"toggle-theme",type:"text",icon:i==="dark"?r.jsx(gx,{}):r.jsx(yx,{}),onClick:l,"aria-label":u,className:"lotus-toolbar-icon",style:{width:44,height:44,borderRadius:o.borderRadiusLG,flexShrink:0}})})]}),!e&&r.jsxs(Pv,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:o.fontSizeSM,textAlign:"center",userSelect:"text"},children:[a("settings.appTab.runningVersion","Running version"),": v",nd]})]})},du="provider",qs=un(e=>({isOpen:!1,origin:"chat",activeTabKey:du,open:(t,s=du)=>e({isOpen:!0,origin:t,activeTabKey:s}),close:()=>e({isOpen:!1}),setActiveTabKey:t=>e({activeTabKey:t})}));function we(e,t,s,n,o){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,s),s}function N(e,t,s,n){if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return s==="m"?n:s==="a"?n.call(e):n?n.value:t.get(e)}let sf=function(){const{crypto:e}=globalThis;if(e!=null&&e.randomUUID)return sf=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),s=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^s()&15>>+n/4).toString(16))};function ec(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const tc=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};class _e extends Error{}class vt extends _e{constructor(t,s,n,o){super(`${vt.makeMessage(t,s,n)}`),this.status=t,this.headers=o,this.requestID=o==null?void 0:o.get("x-request-id"),this.error=s;const a=s;this.code=a==null?void 0:a.code,this.param=a==null?void 0:a.param,this.type=a==null?void 0:a.type}static makeMessage(t,s,n){const o=s!=null&&s.message?typeof s.message=="string"?s.message:JSON.stringify(s.message):s?JSON.stringify(s):n;return t&&o?`${t} ${o}`:t?`${t} status code (no body)`:o||"(no status code or body)"}static generate(t,s,n,o){if(!t||!o)return new Ri({message:n,cause:tc(s)});const a=s==null?void 0:s.error;return t===400?new nf(t,a,n,o):t===401?new rf(t,a,n,o):t===403?new of(t,a,n,o):t===404?new af(t,a,n,o):t===409?new lf(t,a,n,o):t===422?new cf(t,a,n,o):t===429?new df(t,a,n,o):t>=500?new uf(t,a,n,o):new vt(t,a,n,o)}}class Xt extends vt{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class Ri extends vt{constructor({message:t,cause:s}){super(void 0,void 0,t||"Connection error.",void 0),s&&(this.cause=s)}}class rd extends Ri{constructor({message:t}={}){super({message:t??"Request timed out."})}}class nf extends vt{}class rf extends vt{}class of extends vt{}class af extends vt{}class lf extends vt{}class cf extends vt{}class df extends vt{}class uf extends vt{}class mf extends _e{constructor(){super("Could not parse response content as the length limit was reached")}}class hf extends _e{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class jo extends Error{constructor(t){super(t)}}const Rv=/^[a-z][a-z0-9+.-]*:/i,Av=e=>Rv.test(e);let Mt=e=>(Mt=Array.isArray,Mt(e)),uu=Mt;function Iv(e){return typeof e!="object"?{}:e??{}}function $v(e){if(!e)return!0;for(const t in e)return!1;return!0}function Fv(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Zi(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}const Lv=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new _e(`${e} must be an integer`);if(t<0)throw new _e(`${e} must be a positive integer`);return t},Ov=e=>{try{return JSON.parse(e)}catch{return}},aa=e=>new Promise(t=>setTimeout(t,e)),Qn="5.10.2",Dv=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function zv(){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 Nv=()=>{var s;const e=zv();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Qn,"X-Stainless-OS":hu(Deno.build.os),"X-Stainless-Arch":mu(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((s=Deno.version)==null?void 0:s.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Qn,"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":Qn,"X-Stainless-OS":hu(globalThis.process.platform??"unknown"),"X-Stainless-Arch":mu(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=Bv();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Qn,"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":Qn,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Bv(){if(typeof navigator>"u"||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:s}of e){const n=s.exec(navigator.userAgent);if(n){const o=n[1]||0,a=n[2]||0,i=n[3]||0;return{browser:t,version:`${o}.${a}.${i}`}}}return null}const mu=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",hu=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 pu;const Wv=()=>pu??(pu=Nv());function Uv(){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 pf(...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 ff(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return pf({start(){},async pull(s){const{done:n,value:o}=await t.next();n?s.close():s.enqueue(o)},async cancel(){var s;await((s=t.return)==null?void 0:s.call(t))}})}function gf(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const s=await t.read();return s!=null&&s.done&&t.releaseLock(),s}catch(s){throw t.releaseLock(),s}},async return(){const s=t.cancel();return t.releaseLock(),await s,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function qv(e){var n,o;if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await((o=(n=e[Symbol.asyncIterator]()).return)==null?void 0:o.call(n));return}const t=e.getReader(),s=t.cancel();t.releaseLock(),await s}const Hv=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),yf="RFC3986",xf=e=>String(e),fu={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:xf},Yv="RFC1738";let sc=(e,t)=>(sc=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),sc(e,t));const ys=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),el=1024,Xv=(e,t,s,n,o)=>{if(e.length===0)return e;let a=e;if(typeof e=="symbol"?a=Symbol.prototype.toString.call(e):typeof e!="string"&&(a=String(e)),s==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<a.length;l+=el){const c=a.length>=el?a.slice(l,l+el):a,d=[];for(let u=0;u<c.length;++u){let h=c.charCodeAt(u);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||o===Yv&&(h===40||h===41)){d[d.length]=c.charAt(u);continue}if(h<128){d[d.length]=ys[h];continue}if(h<2048){d[d.length]=ys[192|h>>6]+ys[128|h&63];continue}if(h<55296||h>=57344){d[d.length]=ys[224|h>>12]+ys[128|h>>6&63]+ys[128|h&63];continue}u+=1,h=65536+((h&1023)<<10|c.charCodeAt(u)&1023),d[d.length]=ys[240|h>>18]+ys[128|h>>12&63]+ys[128|h>>6&63]+ys[128|h&63]}i+=d.join("")}return i};function Vv(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function gu(e,t){if(Mt(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}const bf={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},vf=function(e,t){Array.prototype.push.apply(e,Mt(t)?t:[t])};let yu;const lt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Xv,encodeValuesOnly:!1,format:yf,formatter:xf,indices:!1,serializeDate(e){return(yu??(yu=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function Kv(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}const tl={};function Sf(e,t,s,n,o,a,i,l,c,d,u,h,p,y,g,f,b,x){let S=e,w=x,C=0,_=!1;for(;(w=w.get(tl))!==void 0&&!_;){const E=w.get(e);if(C+=1,typeof E<"u"){if(E===C)throw new RangeError("Cyclic object value");_=!0}typeof w.get(tl)>"u"&&(C=0)}if(typeof d=="function"?S=d(t,S):S instanceof Date?S=p==null?void 0:p(S):s==="comma"&&Mt(S)&&(S=gu(S,function(E){return E instanceof Date?p==null?void 0:p(E):E})),S===null){if(a)return c&&!f?c(t,lt.encoder,b,"key",y):t;S=""}if(Kv(S)||Vv(S)){if(c){const E=f?t:c(t,lt.encoder,b,"key",y);return[(g==null?void 0:g(E))+"="+(g==null?void 0:g(c(S,lt.encoder,b,"value",y)))]}return[(g==null?void 0:g(t))+"="+(g==null?void 0:g(String(S)))]}const T=[];if(typeof S>"u")return T;let j;if(s==="comma"&&Mt(S))f&&c&&(S=gu(S,c)),j=[{value:S.length>0?S.join(",")||null:void 0}];else if(Mt(d))j=d;else{const E=Object.keys(S);j=u?E.sort(u):E}const v=l?String(t).replace(/\./g,"%2E"):String(t),k=n&&Mt(S)&&S.length===1?v+"[]":v;if(o&&Mt(S)&&S.length===0)return k+"[]";for(let E=0;E<j.length;++E){const M=j[E],R=typeof M=="object"&&typeof M.value<"u"?M.value:S[M];if(i&&R===null)continue;const I=h&&l?M.replace(/\./g,"%2E"):M,P=Mt(S)?typeof s=="function"?s(k,I):k:k+(h?"."+I:"["+I+"]");x.set(e,C);const L=new WeakMap;L.set(tl,x),vf(T,Sf(R,P,s,n,o,a,i,l,s==="comma"&&f&&Mt(S)?null:c,d,u,h,p,y,g,f,b,L))}return T}function Gv(e=lt){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||lt.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let s=yf;if(typeof e.format<"u"){if(!sc(fu,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const n=fu[s];let o=lt.filter;(typeof e.filter=="function"||Mt(e.filter))&&(o=e.filter);let a;if(e.arrayFormat&&e.arrayFormat in bf?a=e.arrayFormat:"indices"in e?a=e.indices?"indices":"repeat":a=lt.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:lt.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:lt.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:lt.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:lt.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?lt.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:lt.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:lt.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:lt.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:lt.encodeValuesOnly,filter:o,format:s,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:lt.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:lt.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:lt.strictNullHandling}}function Jv(e,t={}){let s=e;const n=Gv(t);let o,a;typeof n.filter=="function"?(a=n.filter,s=a("",s)):Mt(n.filter)&&(a=n.filter,o=a);const i=[];if(typeof s!="object"||s===null)return"";const l=bf[n.arrayFormat],c=l==="comma"&&n.commaRoundTrip;o||(o=Object.keys(s)),n.sort&&o.sort(n.sort);const d=new WeakMap;for(let p=0;p<o.length;++p){const y=o[p];n.skipNulls&&s[y]===null||vf(i,Sf(s[y],y,l,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,d))}const u=i.join(n.delimiter);let h=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),u.length>0?h+u:""}function Qv(e){let t=0;for(const o of e)t+=o.length;const s=new Uint8Array(t);let n=0;for(const o of e)s.set(o,n),n+=o.length;return s}let xu;function od(e){let t;return(xu??(t=new globalThis.TextEncoder,xu=t.encode.bind(t)))(e)}let bu;function vu(e){let t;return(bu??(t=new globalThis.TextDecoder,bu=t.decode.bind(t)))(e)}var Ft,Lt;class Ai{constructor(){Ft.set(this,void 0),Lt.set(this,void 0),we(this,Ft,new Uint8Array),we(this,Lt,null)}decode(t){if(t==null)return[];const s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?od(t):t;we(this,Ft,Qv([N(this,Ft,"f"),s]));const n=[];let o;for(;(o=Zv(N(this,Ft,"f"),N(this,Lt,"f")))!=null;){if(o.carriage&&N(this,Lt,"f")==null){we(this,Lt,o.index);continue}if(N(this,Lt,"f")!=null&&(o.index!==N(this,Lt,"f")+1||o.carriage)){n.push(vu(N(this,Ft,"f").subarray(0,N(this,Lt,"f")-1))),we(this,Ft,N(this,Ft,"f").subarray(N(this,Lt,"f"))),we(this,Lt,null);continue}const a=N(this,Lt,"f")!==null?o.preceding-1:o.preceding,i=vu(N(this,Ft,"f").subarray(0,a));n.push(i),we(this,Ft,N(this,Ft,"f").subarray(o.index)),we(this,Lt,null)}return n}flush(){return N(this,Ft,"f").length?this.decode(`
|
|
13
|
+
`):[]}}Ft=new WeakMap,Lt=new WeakMap;Ai.NEWLINE_CHARS=new Set([`
|
|
14
|
+
`,"\r"]);Ai.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Zv(e,t){for(let o=t??0;o<e.length;o++){if(e[o]===10)return{preceding:o,index:o+1,carriage:!1};if(e[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function eS(e){for(let n=0;n<e.length-1;n++){if(e[n]===10&&e[n+1]===10||e[n]===13&&e[n+1]===13)return n+2;if(e[n]===13&&e[n+1]===10&&n+3<e.length&&e[n+2]===13&&e[n+3]===10)return n+4}return-1}const ii={off:0,error:200,warn:300,info:400,debug:500},Su=(e,t,s)=>{if(e){if(Fv(ii,e))return e;yt(s).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(ii))}`)}};function Mo(){}function ya(e,t,s){return!t||ii[e]>ii[s]?Mo:t[e].bind(t)}const tS={error:Mo,warn:Mo,info:Mo,debug:Mo};let wu=new WeakMap;function yt(e){const t=e.logger,s=e.logLevel??"off";if(!t)return tS;const n=wu.get(t);if(n&&n[0]===s)return n[1];const o={error:ya("error",t,s),warn:ya("warn",t,s),info:ya("info",t,s),debug:ya("debug",t,s)};return wu.set(t,[s,o]),o}const wn=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,s])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":s]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var Pr;class Ts{constructor(t,s,n){this.iterator=t,Pr.set(this,void 0),this.controller=s,we(this,Pr,n)}static fromSSEResponse(t,s,n){let o=!1;const a=n?yt(n):console;async function*i(){if(o)throw new _e("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let l=!1;try{for await(const c of sS(t,s))if(!l){if(c.data.startsWith("[DONE]")){l=!0;continue}if(c.event===null||c.event.startsWith("response.")||c.event.startsWith("image_edit.")||c.event.startsWith("image_generation.")||c.event.startsWith("transcript.")){let d;try{d=JSON.parse(c.data)}catch(u){throw a.error("Could not parse message into JSON:",c.data),a.error("From chunk:",c.raw),u}if(d&&d.error)throw new vt(void 0,d.error,void 0,t.headers);yield d}else{let d;try{d=JSON.parse(c.data)}catch(u){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),u}if(c.event=="error")throw new vt(void 0,d.error,d.message,void 0);yield{event:c.event,data:d}}}l=!0}catch(c){if(ec(c))return;throw c}finally{l||s.abort()}}return new Ts(i,s,n)}static fromReadableStream(t,s,n){let o=!1;async function*a(){const l=new Ai,c=gf(t);for await(const d of c)for(const u of l.decode(d))yield u;for(const d of l.flush())yield d}async function*i(){if(o)throw new _e("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let l=!1;try{for await(const c of a())l||c&&(yield JSON.parse(c));l=!0}catch(c){if(ec(c))return;throw c}finally{l||s.abort()}}return new Ts(i,s,n)}[(Pr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const t=[],s=[],n=this.iterator(),o=a=>({next:()=>{if(a.length===0){const i=n.next();t.push(i),s.push(i)}return a.shift()}});return[new Ts(()=>o(t),this.controller,N(this,Pr,"f")),new Ts(()=>o(s),this.controller,N(this,Pr,"f"))]}toReadableStream(){const t=this;let s;return pf({async start(){s=t[Symbol.asyncIterator]()},async pull(n){try{const{value:o,done:a}=await s.next();if(a)return n.close();const i=od(JSON.stringify(o)+`
|
|
15
|
+
`);n.enqueue(i)}catch(o){n.error(o)}},async cancel(){var n;await((n=s.return)==null?void 0:n.call(s))}})}}async function*sS(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new _e("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new _e("Attempted to iterate over a response with no body");const s=new rS,n=new Ai,o=gf(e.body);for await(const a of nS(o))for(const i of n.decode(a)){const l=s.decode(i);l&&(yield l)}for(const a of n.flush()){const i=s.decode(a);i&&(yield i)}}async function*nS(e){let t=new Uint8Array;for await(const s of e){if(s==null)continue;const n=s instanceof ArrayBuffer?new Uint8Array(s):typeof s=="string"?od(s):s;let o=new Uint8Array(t.length+n.length);o.set(t),o.set(n,t.length),t=o;let a;for(;(a=eS(t))!==-1;)yield t.slice(0,a),t=t.slice(a)}t.length>0&&(yield t)}class rS{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;const a={event:this.event,data:this.data.join(`
|
|
16
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(t),t.startsWith(":"))return null;let[s,n,o]=oS(t,":");return o.startsWith(" ")&&(o=o.substring(1)),s==="event"?this.event=o:s==="data"&&this.data.push(o),null}}function oS(e,t){const s=e.indexOf(t);return s!==-1?[e.substring(0,s),t,e.substring(s+t.length)]:[e,"",""]}async function wf(e,t){const{response:s,requestLogID:n,retryOfRequestLogID:o,startTime:a}=t,i=await(async()=>{var h;if(t.options.stream)return yt(e).debug("response",s.status,s.url,s.headers,s.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(s,t.controller,e):Ts.fromSSEResponse(s,t.controller,e);if(s.status===204)return null;if(t.options.__binaryResponse)return s;const l=s.headers.get("content-type"),c=(h=l==null?void 0:l.split(";")[0])==null?void 0:h.trim();if((c==null?void 0:c.includes("application/json"))||(c==null?void 0:c.endsWith("+json"))){const p=await s.json();return _f(p,s)}return await s.text()})();return yt(e).debug(`[${n}] response parsed`,wn({retryOfRequestLogID:o,url:s.url,status:s.status,body:i,durationMs:Date.now()-a})),i}function _f(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 Po;class Ii extends Promise{constructor(t,s,n=wf){super(o=>{o(null)}),this.responsePromise=s,this.parseResponse=n,Po.set(this,void 0),we(this,Po,t)}_thenUnwrap(t){return new Ii(N(this,Po,"f"),this.responsePromise,async(s,n)=>_f(t(await this.parseResponse(s,n),n),n.response))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){const[t,s]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:s,request_id:s.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(N(this,Po,"f"),t))),this.parsedPromise}then(t,s){return this.parse().then(t,s)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}}Po=new WeakMap;var xa;class Tf{constructor(t,s,n,o){xa.set(this,void 0),we(this,xa,t),this.options=o,this.response=s,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const t=this.nextPageRequestOptions();if(!t)throw new _e("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await N(this,xa,"f").requestAPIList(this.constructor,t)}async*iterPages(){let t=this;for(yield t;t.hasNextPage();)t=await t.getNextPage(),yield t}async*[(xa=new WeakMap,Symbol.asyncIterator)](){for await(const t of this.iterPages())for(const s of t.getPaginatedItems())yield s}}class aS extends Ii{constructor(t,s,n){super(t,s,async(o,a)=>new n(o,a.response,await wf(o,a),a.options))}async*[Symbol.asyncIterator](){const t=await this;for await(const s of t)yield s}}class $i extends Tf{constructor(t,s,n,o){super(t,s,n,o),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class at extends Tf{constructor(t,s,n,o){super(t,s,n,o),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var n;const t=this.getPaginatedItems(),s=(n=t[t.length-1])==null?void 0:n.id;return s?{...this.options,query:{...Iv(this.options.query),after:s}}:null}}const kf=()=>{var e;if(typeof File>"u"){const{process:t}=globalThis,s=typeof((e=t==null?void 0:t.versions)==null?void 0:e.node)=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(s?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function zo(e,t,s){return kf(),new File(e,t??"unknown_file",s)}function Oa(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 Cf=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",zn=async(e,t)=>({...e,body:await lS(e.body,t)}),_u=new WeakMap;function iS(e){const t=typeof e=="function"?e:e.fetch,s=_u.get(t);if(s)return s;const n=(async()=>{try{const o="Response"in t?t.Response:(await t("data:,")).constructor,a=new FormData;return a.toString()!==await new o(a).text()}catch{return!0}})();return _u.set(t,n),n}const lS=async(e,t)=>{if(!await iS(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const s=new FormData;return await Promise.all(Object.entries(e||{}).map(([n,o])=>nc(s,n,o))),s},cS=e=>e instanceof Blob&&"name"in e,nc=async(e,t,s)=>{if(s!==void 0){if(s==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")e.append(t,String(s));else if(s instanceof Response)e.append(t,zo([await s.blob()],Oa(s)));else if(Cf(s))e.append(t,zo([await new Response(ff(s)).blob()],Oa(s)));else if(cS(s))e.append(t,s,Oa(s));else if(Array.isArray(s))await Promise.all(s.map(n=>nc(e,t+"[]",n)));else if(typeof s=="object")await Promise.all(Object.entries(s).map(([n,o])=>nc(e,`${t}[${n}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${s} instead`)}},jf=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",dS=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&jf(e),uS=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function mS(e,t,s){if(kf(),e=await e,dS(e))return e instanceof File?e:zo([await e.arrayBuffer()],e.name);if(uS(e)){const o=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),zo(await rc(o),t,s)}const n=await rc(e);if(t||(t=Oa(e)),!(s!=null&&s.type)){const o=n.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof o=="string"&&(s={...s,type:o})}return zo(n,t,s)}async function rc(e){var s;let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(jf(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Cf(e))for await(const n of e)t.push(...await rc(n));else{const n=(s=e==null?void 0:e.constructor)==null?void 0:s.name;throw new Error(`Unexpected data type: ${typeof e}${n?`; constructor: ${n}`:""}${hS(e)}`)}return t}function hS(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(s=>`"${s}"`).join(", ")}]`}class ke{constructor(t){this._client=t}}function Mf(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Tu=Object.freeze(Object.create(null)),pS=(e=Mf)=>function(s,...n){if(s.length===1)return s[0];let o=!1;const a=[],i=s.reduce((u,h,p)=>{var f;/[?#]/.test(h)&&(o=!0);const y=n[p];let g=(o?encodeURIComponent:e)(""+y);return p!==n.length&&(y==null||typeof y=="object"&&y.toString===((f=Object.getPrototypeOf(Object.getPrototypeOf(y.hasOwnProperty??Tu)??Tu))==null?void 0:f.toString))&&(g=y+"",a.push({start:u.length+h.length,length:g.length,error:`Value of type ${Object.prototype.toString.call(y).slice(8,-1)} is not a valid path parameter`})),u+h+(p===n.length?"":g)},""),l=i.split(/[?#]/,1)[0],c=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let d;for(;(d=c.exec(l))!==null;)a.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(a.sort((u,h)=>u.start-h.start),a.length>0){let u=0;const h=a.reduce((p,y)=>{const g=" ".repeat(y.start-u),f="^".repeat(y.length);return u=y.start+y.length,p+g+f},"");throw new _e(`Path parameters result in path with invalid segments:
|
|
17
|
+
${a.map(p=>p.error).join(`
|
|
18
|
+
`)}
|
|
19
|
+
${i}
|
|
20
|
+
${h}`)}return i},ne=pS(Mf);let Pf=class extends ke{list(t,s={},n){return this._client.getAPIList(ne`/chat/completions/${t}/messages`,at,{query:s,...n})}};function fS(e){return typeof e.parse=="function"}const li=e=>(e==null?void 0:e.role)==="assistant",Ef=e=>(e==null?void 0:e.role)==="tool";var oc,Da,za,Eo,Ro,Na,Ao,Ds,Io,ci,di,Zn,Rf;class ad{constructor(){oc.add(this),this.controller=new AbortController,Da.set(this,void 0),za.set(this,()=>{}),Eo.set(this,()=>{}),Ro.set(this,void 0),Na.set(this,()=>{}),Ao.set(this,()=>{}),Ds.set(this,{}),Io.set(this,!1),ci.set(this,!1),di.set(this,!1),Zn.set(this,!1),we(this,Da,new Promise((t,s)=>{we(this,za,t,"f"),we(this,Eo,s,"f")})),we(this,Ro,new Promise((t,s)=>{we(this,Na,t,"f"),we(this,Ao,s,"f")})),N(this,Da,"f").catch(()=>{}),N(this,Ro,"f").catch(()=>{})}_run(t){setTimeout(()=>{t().then(()=>{this._emitFinal(),this._emit("end")},N(this,oc,"m",Rf).bind(this))},0)}_connected(){this.ended||(N(this,za,"f").call(this),this._emit("connect"))}get ended(){return N(this,Io,"f")}get errored(){return N(this,ci,"f")}get aborted(){return N(this,di,"f")}abort(){this.controller.abort()}on(t,s){return(N(this,Ds,"f")[t]||(N(this,Ds,"f")[t]=[])).push({listener:s}),this}off(t,s){const n=N(this,Ds,"f")[t];if(!n)return this;const o=n.findIndex(a=>a.listener===s);return o>=0&&n.splice(o,1),this}once(t,s){return(N(this,Ds,"f")[t]||(N(this,Ds,"f")[t]=[])).push({listener:s,once:!0}),this}emitted(t){return new Promise((s,n)=>{we(this,Zn,!0),t!=="error"&&this.once("error",n),this.once(t,s)})}async done(){we(this,Zn,!0),await N(this,Ro,"f")}_emit(t,...s){if(N(this,Io,"f"))return;t==="end"&&(we(this,Io,!0),N(this,Na,"f").call(this));const n=N(this,Ds,"f")[t];if(n&&(N(this,Ds,"f")[t]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...s))),t==="abort"){const o=s[0];!N(this,Zn,"f")&&!(n!=null&&n.length)&&Promise.reject(o),N(this,Eo,"f").call(this,o),N(this,Ao,"f").call(this,o),this._emit("end");return}if(t==="error"){const o=s[0];!N(this,Zn,"f")&&!(n!=null&&n.length)&&Promise.reject(o),N(this,Eo,"f").call(this,o),N(this,Ao,"f").call(this,o),this._emit("end")}}_emitFinal(){}}Da=new WeakMap,za=new WeakMap,Eo=new WeakMap,Ro=new WeakMap,Na=new WeakMap,Ao=new WeakMap,Ds=new WeakMap,Io=new WeakMap,ci=new WeakMap,di=new WeakMap,Zn=new WeakMap,oc=new WeakSet,Rf=function(t){if(we(this,ci,!0),t instanceof Error&&t.name==="AbortError"&&(t=new Xt),t instanceof Xt)return we(this,di,!0),this._emit("abort",t);if(t instanceof _e)return this._emit("error",t);if(t instanceof Error){const s=new _e(t.message);return s.cause=t,this._emit("error",s)}return this._emit("error",new _e(String(t)))};function id(e){return(e==null?void 0:e.$brand)==="auto-parseable-response-format"}function ia(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function gS(e,t){return!t||!Af(t)?{...e,choices:e.choices.map(s=>({...s,message:{...s.message,parsed:null,...s.message.tool_calls?{tool_calls:s.message.tool_calls}:void 0}}))}:ld(e,t)}function ld(e,t){const s=e.choices.map(n=>{var o;if(n.finish_reason==="length")throw new mf;if(n.finish_reason==="content_filter")throw new hf;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((o=n.message.tool_calls)==null?void 0:o.map(a=>xS(t,a)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?yS(t,n.message.content):null}}});return{...e,choices:s}}function yS(e,t){var s,n;return((s=e.response_format)==null?void 0:s.type)!=="json_schema"?null:((n=e.response_format)==null?void 0:n.type)==="json_schema"?"$parseRaw"in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function xS(e,t){var n;const s=(n=e.tools)==null?void 0:n.find(o=>{var a;return((a=o.function)==null?void 0:a.name)===t.function.name});return{...t,function:{...t.function,parsed_arguments:ia(s)?s.$parseRaw(t.function.arguments):s!=null&&s.function.strict?JSON.parse(t.function.arguments):null}}}function bS(e,t){var n;if(!e)return!1;const s=(n=e.tools)==null?void 0:n.find(o=>{var a;return((a=o.function)==null?void 0:a.name)===t.function.name});return ia(s)||(s==null?void 0:s.function.strict)||!1}function Af(e){var t;return id(e.response_format)?!0:((t=e.tools)==null?void 0:t.some(s=>ia(s)||s.type==="function"&&s.function.strict===!0))??!1}function vS(e){for(const t of e??[]){if(t.type!=="function")throw new _e(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new _e(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var _t,ac,ui,ic,lc,cc,If,$f;const SS=10;class Ff extends ad{constructor(){super(...arguments),_t.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(t){var n;this._chatCompletions.push(t),this._emit("chatCompletion",t);const s=(n=t.choices[0])==null?void 0:n.message;return s&&this._addMessage(s),t}_addMessage(t,s=!0){if("content"in t||(t.content=null),this.messages.push(t),s){if(this._emit("message",t),Ef(t)&&t.content)this._emit("functionToolCallResult",t.content);else if(li(t)&&t.tool_calls)for(const n of t.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();const t=this._chatCompletions[this._chatCompletions.length-1];if(!t)throw new _e("stream ended without producing a ChatCompletion");return t}async finalContent(){return await this.done(),N(this,_t,"m",ac).call(this)}async finalMessage(){return await this.done(),N(this,_t,"m",ui).call(this)}async finalFunctionToolCall(){return await this.done(),N(this,_t,"m",ic).call(this)}async finalFunctionToolCallResult(){return await this.done(),N(this,_t,"m",lc).call(this)}async totalUsage(){return await this.done(),N(this,_t,"m",cc).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const t=this._chatCompletions[this._chatCompletions.length-1];t&&this._emit("finalChatCompletion",t);const s=N(this,_t,"m",ui).call(this);s&&this._emit("finalMessage",s);const n=N(this,_t,"m",ac).call(this);n&&this._emit("finalContent",n);const o=N(this,_t,"m",ic).call(this);o&&this._emit("finalFunctionToolCall",o);const a=N(this,_t,"m",lc).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",N(this,_t,"m",cc).call(this))}async _createChatCompletion(t,s,n){const o=n==null?void 0:n.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),N(this,_t,"m",If).call(this,s);const a=await t.chat.completions.create({...s,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(ld(a,s))}async _runChatCompletion(t,s,n){for(const o of s.messages)this._addMessage(o,!1);return await this._createChatCompletion(t,s,n)}async _runTools(t,s,n){var y,g,f;const o="tool",{tool_choice:a="auto",stream:i,...l}=s,c=typeof a!="string"&&((y=a==null?void 0:a.function)==null?void 0:y.name),{maxChatCompletions:d=SS}=n||{},u=s.tools.map(b=>{if(ia(b)){if(!b.$callback)throw new _e("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:b.$callback,name:b.function.name,description:b.function.description||"",parameters:b.function.parameters,parse:b.$parseRaw,strict:!0}}}return b}),h={};for(const b of u)b.type==="function"&&(h[b.function.name||b.function.function.name]=b.function);const p="tools"in s?u.map(b=>b.type==="function"?{type:"function",function:{name:b.function.name||b.function.function.name,parameters:b.function.parameters,description:b.function.description,strict:b.function.strict}}:b):void 0;for(const b of s.messages)this._addMessage(b,!1);for(let b=0;b<d;++b){const S=(g=(await this._createChatCompletion(t,{...l,tool_choice:a,tools:p,messages:[...this.messages]},n)).choices[0])==null?void 0:g.message;if(!S)throw new _e("missing message in ChatCompletion response");if(!((f=S.tool_calls)!=null&&f.length))return;for(const w of S.tool_calls){if(w.type!=="function")continue;const C=w.id,{name:_,arguments:T}=w.function,j=h[_];if(j){if(c&&c!==_){const M=`Invalid tool_call: ${JSON.stringify(_)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:o,tool_call_id:C,content:M});continue}}else{const M=`Invalid tool_call: ${JSON.stringify(_)}. Available options are: ${Object.keys(h).map(R=>JSON.stringify(R)).join(", ")}. Please try again`;this._addMessage({role:o,tool_call_id:C,content:M});continue}let v;try{v=fS(j)?await j.parse(T):T}catch(M){const R=M instanceof Error?M.message:String(M);this._addMessage({role:o,tool_call_id:C,content:R});continue}const k=await j.function(v,this),E=N(this,_t,"m",$f).call(this,k);if(this._addMessage({role:o,tool_call_id:C,content:E}),c)return}}}}_t=new WeakSet,ac=function(){return N(this,_t,"m",ui).call(this).content??null},ui=function(){let t=this.messages.length;for(;t-- >0;){const s=this.messages[t];if(li(s))return{...s,content:s.content??null,refusal:s.refusal??null}}throw new _e("stream ended without producing a ChatCompletionMessage with role=assistant")},ic=function(){var t,s;for(let n=this.messages.length-1;n>=0;n--){const o=this.messages[n];if(li(o)&&((t=o==null?void 0:o.tool_calls)!=null&&t.length))return(s=o.tool_calls.at(-1))==null?void 0:s.function}},lc=function(){for(let t=this.messages.length-1;t>=0;t--){const s=this.messages[t];if(Ef(s)&&s.content!=null&&typeof s.content=="string"&&this.messages.some(n=>{var o;return n.role==="assistant"&&((o=n.tool_calls)==null?void 0:o.some(a=>a.type==="function"&&a.id===s.tool_call_id))}))return s.content}},cc=function(){const t={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:s}of this._chatCompletions)s&&(t.completion_tokens+=s.completion_tokens,t.prompt_tokens+=s.prompt_tokens,t.total_tokens+=s.total_tokens);return t},If=function(t){if(t.n!=null&&t.n>1)throw new _e("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},$f=function(t){return typeof t=="string"?t:t===void 0?"undefined":JSON.stringify(t)};class cd extends Ff{static runTools(t,s,n){const o=new cd,a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(t,s,a)),o}_addMessage(t,s=!0){super._addMessage(t,s),li(t)&&t.content&&this._emit("content",t.content)}}const Lf=1,Of=2,Df=4,zf=8,Nf=16,Bf=32,Wf=64,Uf=128,qf=256,Hf=Uf|qf,Yf=Nf|Bf|Hf|Wf,Xf=Lf|Of|Yf,Vf=Df|zf,wS=Xf|Vf,ht={STR:Lf,NUM:Of,ARR:Df,OBJ:zf,NULL:Nf,BOOL:Bf,NAN:Wf,INFINITY:Uf,MINUS_INFINITY:qf,INF:Hf,SPECIAL:Yf,ATOM:Xf,COLLECTION:Vf,ALL:wS};class _S extends Error{}class TS extends Error{}function kS(e,t=ht.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return CS(e.trim(),t)}const CS=(e,t)=>{const s=e.length;let n=0;const o=p=>{throw new _S(`${p} at position ${n}`)},a=p=>{throw new TS(`${p} at position ${n}`)},i=()=>(h(),n>=s&&o("Unexpected end of input"),e[n]==='"'?l():e[n]==="{"?c():e[n]==="["?d():e.substring(n,n+4)==="null"||ht.NULL&t&&s-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):e.substring(n,n+4)==="true"||ht.BOOL&t&&s-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):e.substring(n,n+5)==="false"||ht.BOOL&t&&s-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):e.substring(n,n+8)==="Infinity"||ht.INFINITY&t&&s-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):e.substring(n,n+9)==="-Infinity"||ht.MINUS_INFINITY&t&&1<s-n&&s-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):e.substring(n,n+3)==="NaN"||ht.NAN&t&&s-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):u()),l=()=>{const p=n;let y=!1;for(n++;n<s&&(e[n]!=='"'||y&&e[n-1]==="\\");)y=e[n]==="\\"?!y:!1,n++;if(e.charAt(n)=='"')try{return JSON.parse(e.substring(p,++n-Number(y)))}catch(g){a(String(g))}else if(ht.STR&t)try{return JSON.parse(e.substring(p,n-Number(y))+'"')}catch{return JSON.parse(e.substring(p,e.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},c=()=>{n++,h();const p={};try{for(;e[n]!=="}";){if(h(),n>=s&&ht.OBJ&t)return p;const y=l();h(),n++;try{const g=i();Object.defineProperty(p,y,{value:g,writable:!0,enumerable:!0,configurable:!0})}catch(g){if(ht.OBJ&t)return p;throw g}h(),e[n]===","&&n++}}catch{if(ht.OBJ&t)return p;o("Expected '}' at end of object")}return n++,p},d=()=>{n++;const p=[];try{for(;e[n]!=="]";)p.push(i()),h(),e[n]===","&&n++}catch{if(ht.ARR&t)return p;o("Expected ']' at end of array")}return n++,p},u=()=>{if(n===0){e==="-"&&ht.NUM&t&&o("Not sure what '-' is");try{return JSON.parse(e)}catch(y){if(ht.NUM&t)try{return e[e.length-1]==="."?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(y))}}const p=n;for(e[n]==="-"&&n++;e[n]&&!",]}".includes(e[n]);)n++;n==s&&!(ht.NUM&t)&&o("Unterminated number literal");try{return JSON.parse(e.substring(p,n))}catch{e.substring(p,n)==="-"&&ht.NUM&t&&o("Not sure what '-' is");try{return JSON.parse(e.substring(p,e.lastIndexOf("e")))}catch(g){a(String(g))}}},h=()=>{for(;n<s&&`
|
|
21
|
+
\r `.includes(e[n]);)n++};return i()},ku=e=>kS(e,ht.ALL^ht.NUM);var it,As,Un,Ks,sl,ba,nl,rl,ol,va,al,Cu;class Go extends Ff{constructor(t){super(),it.add(this),As.set(this,void 0),Un.set(this,void 0),Ks.set(this,void 0),we(this,As,t),we(this,Un,[])}get currentChatCompletionSnapshot(){return N(this,Ks,"f")}static fromReadableStream(t){const s=new Go(null);return s._run(()=>s._fromReadableStream(t)),s}static createChatCompletion(t,s,n){const o=new Go(s);return o._run(()=>o._runChatCompletion(t,{...s,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(t,s,n){var i;super._createChatCompletion;const o=n==null?void 0:n.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),N(this,it,"m",sl).call(this);const a=await t.chat.completions.create({...s,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const l of a)N(this,it,"m",nl).call(this,l);if((i=a.controller.signal)!=null&&i.aborted)throw new Xt;return this._addChatCompletion(N(this,it,"m",va).call(this))}async _fromReadableStream(t,s){var i;const n=s==null?void 0:s.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),N(this,it,"m",sl).call(this),this._connected();const o=Ts.fromReadableStream(t,this.controller);let a;for await(const l of o)a&&a!==l.id&&this._addChatCompletion(N(this,it,"m",va).call(this)),N(this,it,"m",nl).call(this,l),a=l.id;if((i=o.controller.signal)!=null&&i.aborted)throw new Xt;return this._addChatCompletion(N(this,it,"m",va).call(this))}[(As=new WeakMap,Un=new WeakMap,Ks=new WeakMap,it=new WeakSet,sl=function(){this.ended||we(this,Ks,void 0)},ba=function(s){let n=N(this,Un,"f")[s.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},N(this,Un,"f")[s.index]=n,n)},nl=function(s){var o,a,i,l,c,d,u,h,p,y,g,f,b,x,S;if(this.ended)return;const n=N(this,it,"m",Cu).call(this,s);this._emit("chunk",s,n);for(const w of s.choices){const C=n.choices[w.index];w.delta.content!=null&&((o=C.message)==null?void 0:o.role)==="assistant"&&((a=C.message)!=null&&a.content)&&(this._emit("content",w.delta.content,C.message.content),this._emit("content.delta",{delta:w.delta.content,snapshot:C.message.content,parsed:C.message.parsed})),w.delta.refusal!=null&&((i=C.message)==null?void 0:i.role)==="assistant"&&((l=C.message)!=null&&l.refusal)&&this._emit("refusal.delta",{delta:w.delta.refusal,snapshot:C.message.refusal}),((c=w.logprobs)==null?void 0:c.content)!=null&&((d=C.message)==null?void 0:d.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(u=w.logprobs)==null?void 0:u.content,snapshot:((h=C.logprobs)==null?void 0:h.content)??[]}),((p=w.logprobs)==null?void 0:p.refusal)!=null&&((y=C.message)==null?void 0:y.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(g=w.logprobs)==null?void 0:g.refusal,snapshot:((f=C.logprobs)==null?void 0:f.refusal)??[]});const _=N(this,it,"m",ba).call(this,C);C.finish_reason&&(N(this,it,"m",ol).call(this,C),_.current_tool_call_index!=null&&N(this,it,"m",rl).call(this,C,_.current_tool_call_index));for(const T of w.delta.tool_calls??[])_.current_tool_call_index!==T.index&&(N(this,it,"m",ol).call(this,C),_.current_tool_call_index!=null&&N(this,it,"m",rl).call(this,C,_.current_tool_call_index)),_.current_tool_call_index=T.index;for(const T of w.delta.tool_calls??[]){const j=(b=C.message.tool_calls)==null?void 0:b[T.index];j!=null&&j.type&&((j==null?void 0:j.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(x=j.function)==null?void 0:x.name,index:T.index,arguments:j.function.arguments,parsed_arguments:j.function.parsed_arguments,arguments_delta:((S=T.function)==null?void 0:S.arguments)??""}):(j==null||j.type,void 0))}}},rl=function(s,n){var i,l,c;if(N(this,it,"m",ba).call(this,s).done_tool_calls.has(n))return;const a=(i=s.message.tool_calls)==null?void 0:i[n];if(!a)throw new Error("no tool call snapshot");if(!a.type)throw new Error("tool call snapshot missing `type`");if(a.type==="function"){const d=(c=(l=N(this,As,"f"))==null?void 0:l.tools)==null?void 0:c.find(u=>u.type==="function"&&u.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:n,arguments:a.function.arguments,parsed_arguments:ia(d)?d.$parseRaw(a.function.arguments):d!=null&&d.function.strict?JSON.parse(a.function.arguments):null})}else a.type},ol=function(s){var o,a;const n=N(this,it,"m",ba).call(this,s);if(s.message.content&&!n.content_done){n.content_done=!0;const i=N(this,it,"m",al).call(this);this._emit("content.done",{content:s.message.content,parsed:i?i.$parseRaw(s.message.content):null})}s.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:s.message.refusal})),(o=s.logprobs)!=null&&o.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:s.logprobs.content})),(a=s.logprobs)!=null&&a.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:s.logprobs.refusal}))},va=function(){if(this.ended)throw new _e("stream has ended, this shouldn't happen");const s=N(this,Ks,"f");if(!s)throw new _e("request ended without sending any chunks");return we(this,Ks,void 0),we(this,Un,[]),jS(s,N(this,As,"f"))},al=function(){var n;const s=(n=N(this,As,"f"))==null?void 0:n.response_format;return id(s)?s:null},Cu=function(s){var n,o,a,i;let l=N(this,Ks,"f");const{choices:c,...d}=s;l?Object.assign(l,d):l=we(this,Ks,{...d,choices:[]});for(const{delta:u,finish_reason:h,index:p,logprobs:y=null,...g}of s.choices){let f=l.choices[p];if(f||(f=l.choices[p]={finish_reason:h,index:p,message:{},logprobs:y,...g}),y)if(!f.logprobs)f.logprobs=Object.assign({},y);else{const{content:T,refusal:j,...v}=y;Object.assign(f.logprobs,v),T&&((n=f.logprobs).content??(n.content=[]),f.logprobs.content.push(...T)),j&&((o=f.logprobs).refusal??(o.refusal=[]),f.logprobs.refusal.push(...j))}if(h&&(f.finish_reason=h,N(this,As,"f")&&Af(N(this,As,"f")))){if(h==="length")throw new mf;if(h==="content_filter")throw new hf}if(Object.assign(f,g),!u)continue;const{content:b,refusal:x,function_call:S,role:w,tool_calls:C,..._}=u;if(Object.assign(f.message,_),x&&(f.message.refusal=(f.message.refusal||"")+x),w&&(f.message.role=w),S&&(f.message.function_call?(S.name&&(f.message.function_call.name=S.name),S.arguments&&((a=f.message.function_call).arguments??(a.arguments=""),f.message.function_call.arguments+=S.arguments)):f.message.function_call=S),b&&(f.message.content=(f.message.content||"")+b,!f.message.refusal&&N(this,it,"m",al).call(this)&&(f.message.parsed=ku(f.message.content))),C){f.message.tool_calls||(f.message.tool_calls=[]);for(const{index:T,id:j,type:v,function:k,...E}of C){const M=(i=f.message.tool_calls)[T]??(i[T]={});Object.assign(M,E),j&&(M.id=j),v&&(M.type=v),k&&(M.function??(M.function={name:k.name??"",arguments:""})),k!=null&&k.name&&(M.function.name=k.name),k!=null&&k.arguments&&(M.function.arguments+=k.arguments,bS(N(this,As,"f"),M)&&(M.function.parsed_arguments=ku(M.function.arguments)))}}}return l},Symbol.asyncIterator)](){const t=[],s=[];let n=!1;return this.on("chunk",o=>{const a=s.shift();a?a.resolve(o):t.push(o)}),this.on("end",()=>{n=!0;for(const o of s)o.resolve(void 0);s.length=0}),this.on("abort",o=>{n=!0;for(const a of s)a.reject(o);s.length=0}),this.on("error",o=>{n=!0;for(const a of s)a.reject(o);s.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>s.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Ts(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function jS(e,t){const{id:s,choices:n,created:o,model:a,system_fingerprint:i,...l}=e,c={...l,id:s,choices:n.map(({message:d,finish_reason:u,index:h,logprobs:p,...y})=>{if(!u)throw new _e(`missing finish_reason for choice ${h}`);const{content:g=null,function_call:f,tool_calls:b,...x}=d,S=d.role;if(!S)throw new _e(`missing role for choice ${h}`);if(f){const{arguments:w,name:C}=f;if(w==null)throw new _e(`missing function_call.arguments for choice ${h}`);if(!C)throw new _e(`missing function_call.name for choice ${h}`);return{...y,message:{content:g,function_call:{arguments:w,name:C},role:S,refusal:d.refusal??null},finish_reason:u,index:h,logprobs:p}}return b?{...y,index:h,finish_reason:u,logprobs:p,message:{...x,role:S,content:g,refusal:d.refusal??null,tool_calls:b.map((w,C)=>{const{function:_,type:T,id:j,...v}=w,{arguments:k,name:E,...M}=_||{};if(j==null)throw new _e(`missing choices[${h}].tool_calls[${C}].id
|
|
22
|
+
${Sa(e)}`);if(T==null)throw new _e(`missing choices[${h}].tool_calls[${C}].type
|
|
23
|
+
${Sa(e)}`);if(E==null)throw new _e(`missing choices[${h}].tool_calls[${C}].function.name
|
|
24
|
+
${Sa(e)}`);if(k==null)throw new _e(`missing choices[${h}].tool_calls[${C}].function.arguments
|
|
25
|
+
${Sa(e)}`);return{...v,id:j,type:T,function:{...M,name:E,arguments:k}}})}}:{...y,message:{...x,content:g,role:S,refusal:d.refusal??null},finish_reason:u,index:h,logprobs:p}}),created:o,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return gS(c,t)}function Sa(e){return JSON.stringify(e)}class mi extends Go{static fromReadableStream(t){const s=new mi(null);return s._run(()=>s._fromReadableStream(t)),s}static runTools(t,s,n){const o=new mi(s),a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(t,s,a)),o}}let dd=class extends ke{constructor(){super(...arguments),this.messages=new Pf(this._client)}create(t,s){return this._client.post("/chat/completions",{body:t,...s,stream:t.stream??!1})}retrieve(t,s){return this._client.get(ne`/chat/completions/${t}`,s)}update(t,s,n){return this._client.post(ne`/chat/completions/${t}`,{body:s,...n})}list(t={},s){return this._client.getAPIList("/chat/completions",at,{query:t,...s})}delete(t,s){return this._client.delete(ne`/chat/completions/${t}`,s)}parse(t,s){return vS(t.tools),this._client.chat.completions.create(t,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>ld(n,t))}runTools(t,s){return t.stream?mi.runTools(this._client,t,s):cd.runTools(this._client,t,s)}stream(t,s){return Go.createChatCompletion(this._client,t,s)}};dd.Messages=Pf;class ud extends ke{constructor(){super(...arguments),this.completions=new dd(this._client)}}ud.Completions=dd;const Kf=Symbol("brand.privateNullableHeaders");function*MS(e){if(!e)return;if(Kf in e){const{values:n,nulls:o}=e;yield*n.entries();for(const a of o)yield[a,null];return}let t=!1,s;e instanceof Headers?s=e.entries():uu(e)?s=e:(t=!0,s=Object.entries(e??{}));for(let n of s){const o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");const a=uu(n[1])?n[1]:[n[1]];let i=!1;for(const l of a)l!==void 0&&(t&&!i&&(i=!0,yield[o,null]),yield[o,l])}}const be=e=>{const t=new Headers,s=new Set;for(const n of e){const o=new Set;for(const[a,i]of MS(n)){const l=a.toLowerCase();o.has(l)||(t.delete(a),o.add(l)),i===null?(t.delete(a),s.add(l)):(t.append(a,i),s.delete(l))}}return{[Kf]:!0,values:t,nulls:s}};class Gf extends ke{create(t,s){return this._client.post("/audio/speech",{body:t,...s,headers:be([{Accept:"application/octet-stream"},s==null?void 0:s.headers]),__binaryResponse:!0})}}class Jf extends ke{create(t,s){return this._client.post("/audio/transcriptions",zn({body:t,...s,stream:t.stream??!1,__metadata:{model:t.model}},this._client))}}class Qf extends ke{create(t,s){return this._client.post("/audio/translations",zn({body:t,...s,__metadata:{model:t.model}},this._client))}}class la extends ke{constructor(){super(...arguments),this.transcriptions=new Jf(this._client),this.translations=new Qf(this._client),this.speech=new Gf(this._client)}}la.Transcriptions=Jf;la.Translations=Qf;la.Speech=Gf;class Zf extends ke{create(t,s){return this._client.post("/batches",{body:t,...s})}retrieve(t,s){return this._client.get(ne`/batches/${t}`,s)}list(t={},s){return this._client.getAPIList("/batches",at,{query:t,...s})}cancel(t,s){return this._client.post(ne`/batches/${t}/cancel`,s)}}class eg extends ke{create(t,s){return this._client.post("/assistants",{body:t,...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,s){return this._client.get(ne`/assistants/${t}`,{...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,s,n){return this._client.post(ne`/assistants/${t}`,{body:s,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t={},s){return this._client.getAPIList("/assistants",at,{query:t,...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}delete(t,s){return this._client.delete(ne`/assistants/${t}`,{...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class tg extends ke{create(t,s){return this._client.post("/realtime/sessions",{body:t,...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class sg extends ke{create(t,s){return this._client.post("/realtime/transcription_sessions",{body:t,...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class Fi extends ke{constructor(){super(...arguments),this.sessions=new tg(this._client),this.transcriptionSessions=new sg(this._client)}}Fi.Sessions=tg;Fi.TranscriptionSessions=sg;class ng extends ke{create(t,s,n){return this._client.post(ne`/threads/${t}/messages`,{body:s,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,s,n){const{thread_id:o}=s;return this._client.get(ne`/threads/${o}/messages/${t}`,{...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,s,n){const{thread_id:o,...a}=s;return this._client.post(ne`/threads/${o}/messages/${t}`,{body:a,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s={},n){return this._client.getAPIList(ne`/threads/${t}/messages`,at,{query:s,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,s,n){const{thread_id:o}=s;return this._client.delete(ne`/threads/${o}/messages/${t}`,{...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class rg extends ke{retrieve(t,s,n){const{thread_id:o,run_id:a,...i}=s;return this._client.get(ne`/threads/${o}/runs/${a}/steps/${t}`,{query:i,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s,n){const{thread_id:o,...a}=s;return this._client.getAPIList(ne`/threads/${o}/runs/${t}/steps`,at,{query:a,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}const PS=e=>{if(typeof Buffer<"u"){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{const t=atob(e),s=t.length,n=new Uint8Array(s);for(let o=0;o<s;o++)n[o]=t.charCodeAt(o);return Array.from(new Float32Array(n.buffer))}};var il={};const qn=e=>{var t,s,n,o;if(typeof globalThis.process<"u")return((t=il==null?void 0:il[e])==null?void 0:t.trim())??void 0;if(typeof globalThis.Deno<"u")return(o=(n=(s=globalThis.Deno.env)==null?void 0:s.get)==null?void 0:n.call(s,e))==null?void 0:o.trim()};var xt,In,dc,vs,Ba,ls,$n,sr,Cn,hi,Ot,Wa,Ua,No,$o,Fo,ju,Mu,Pu,Eu,Ru,Au,Iu;class Bo extends ad{constructor(){super(...arguments),xt.add(this),dc.set(this,[]),vs.set(this,{}),Ba.set(this,{}),ls.set(this,void 0),$n.set(this,void 0),sr.set(this,void 0),Cn.set(this,void 0),hi.set(this,void 0),Ot.set(this,void 0),Wa.set(this,void 0),Ua.set(this,void 0),No.set(this,void 0)}[(dc=new WeakMap,vs=new WeakMap,Ba=new WeakMap,ls=new WeakMap,$n=new WeakMap,sr=new WeakMap,Cn=new WeakMap,hi=new WeakMap,Ot=new WeakMap,Wa=new WeakMap,Ua=new WeakMap,No=new WeakMap,xt=new WeakSet,Symbol.asyncIterator)](){const t=[],s=[];let n=!1;return this.on("event",o=>{const a=s.shift();a?a.resolve(o):t.push(o)}),this.on("end",()=>{n=!0;for(const o of s)o.resolve(void 0);s.length=0}),this.on("abort",o=>{n=!0;for(const a of s)a.reject(o);s.length=0}),this.on("error",o=>{n=!0;for(const a of s)a.reject(o);s.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>s.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(t){const s=new In;return s._run(()=>s._fromReadableStream(t)),s}async _fromReadableStream(t,s){var a;const n=s==null?void 0:s.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();const o=Ts.fromReadableStream(t,this.controller);for await(const i of o)N(this,xt,"m",$o).call(this,i);if((a=o.controller.signal)!=null&&a.aborted)throw new Xt;return this._addRun(N(this,xt,"m",Fo).call(this))}toReadableStream(){return new Ts(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,s,n,o){const a=new In;return a._run(()=>a._runToolAssistantStream(t,s,n,{...o,headers:{...o==null?void 0:o.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(t,s,n,o){var c;const a=o==null?void 0:o.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},l=await t.submitToolOutputs(s,i,{...o,signal:this.controller.signal});this._connected();for await(const d of l)N(this,xt,"m",$o).call(this,d);if((c=l.controller.signal)!=null&&c.aborted)throw new Xt;return this._addRun(N(this,xt,"m",Fo).call(this))}static createThreadAssistantStream(t,s,n){const o=new In;return o._run(()=>o._threadAssistantStream(t,s,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),o}static createAssistantStream(t,s,n,o){const a=new In;return a._run(()=>a._runAssistantStream(t,s,n,{...o,headers:{...o==null?void 0:o.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return N(this,Wa,"f")}currentRun(){return N(this,Ua,"f")}currentMessageSnapshot(){return N(this,ls,"f")}currentRunStepSnapshot(){return N(this,No,"f")}async finalRunSteps(){return await this.done(),Object.values(N(this,vs,"f"))}async finalMessages(){return await this.done(),Object.values(N(this,Ba,"f"))}async finalRun(){if(await this.done(),!N(this,$n,"f"))throw Error("Final run was not received.");return N(this,$n,"f")}async _createThreadAssistantStream(t,s,n){var l;const o=n==null?void 0:n.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const a={...s,stream:!0},i=await t.createAndRun(a,{...n,signal:this.controller.signal});this._connected();for await(const c of i)N(this,xt,"m",$o).call(this,c);if((l=i.controller.signal)!=null&&l.aborted)throw new Xt;return this._addRun(N(this,xt,"m",Fo).call(this))}async _createAssistantStream(t,s,n,o){var c;const a=o==null?void 0:o.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},l=await t.create(s,i,{...o,signal:this.controller.signal});this._connected();for await(const d of l)N(this,xt,"m",$o).call(this,d);if((c=l.controller.signal)!=null&&c.aborted)throw new Xt;return this._addRun(N(this,xt,"m",Fo).call(this))}static accumulateDelta(t,s){for(const[n,o]of Object.entries(s)){if(!t.hasOwnProperty(n)){t[n]=o;continue}let a=t[n];if(a==null){t[n]=o;continue}if(n==="index"||n==="type"){t[n]=o;continue}if(typeof a=="string"&&typeof o=="string")a+=o;else if(typeof a=="number"&&typeof o=="number")a+=o;else if(Zi(a)&&Zi(o))a=this.accumulateDelta(a,o);else if(Array.isArray(a)&&Array.isArray(o)){if(a.every(i=>typeof i=="string"||typeof i=="number")){a.push(...o);continue}for(const i of o){if(!Zi(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const l=i.index;if(l==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);const c=a[l];c==null?a.push(i):a[l]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${o}, accValue: ${a}`);t[n]=a}return t}_addRun(t){return t}async _threadAssistantStream(t,s,n){return await this._createThreadAssistantStream(s,t,n)}async _runAssistantStream(t,s,n,o){return await this._createAssistantStream(s,t,n,o)}async _runToolAssistantStream(t,s,n,o){return await this._createToolAssistantStream(s,t,n,o)}}In=Bo,$o=function(t){if(!this.ended)switch(we(this,Wa,t),N(this,xt,"m",Pu).call(this,t),t.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":N(this,xt,"m",Iu).call(this,t);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":N(this,xt,"m",Mu).call(this,t);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":N(this,xt,"m",ju).call(this,t);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Fo=function(){if(this.ended)throw new _e("stream has ended, this shouldn't happen");if(!N(this,$n,"f"))throw Error("Final run has not been received");return N(this,$n,"f")},ju=function(t){const[s,n]=N(this,xt,"m",Ru).call(this,t,N(this,ls,"f"));we(this,ls,s),N(this,Ba,"f")[s.id]=s;for(const o of n){const a=s.content[o.index];(a==null?void 0:a.type)=="text"&&this._emit("textCreated",a.text)}switch(t.event){case"thread.message.created":this._emit("messageCreated",t.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",t.data.delta,s),t.data.delta.content)for(const o of t.data.delta.content){if(o.type=="text"&&o.text){let a=o.text,i=s.content[o.index];if(i&&i.type=="text")this._emit("textDelta",a,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(o.index!=N(this,sr,"f")){if(N(this,Cn,"f"))switch(N(this,Cn,"f").type){case"text":this._emit("textDone",N(this,Cn,"f").text,N(this,ls,"f"));break;case"image_file":this._emit("imageFileDone",N(this,Cn,"f").image_file,N(this,ls,"f"));break}we(this,sr,o.index)}we(this,Cn,s.content[o.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(N(this,sr,"f")!==void 0){const o=t.data.content[N(this,sr,"f")];if(o)switch(o.type){case"image_file":this._emit("imageFileDone",o.image_file,N(this,ls,"f"));break;case"text":this._emit("textDone",o.text,N(this,ls,"f"));break}}N(this,ls,"f")&&this._emit("messageDone",t.data),we(this,ls,void 0)}},Mu=function(t){const s=N(this,xt,"m",Eu).call(this,t);switch(we(this,No,s),t.event){case"thread.run.step.created":this._emit("runStepCreated",t.data);break;case"thread.run.step.delta":const n=t.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&s.step_details.type=="tool_calls")for(const a of n.step_details.tool_calls)a.index==N(this,hi,"f")?this._emit("toolCallDelta",a,s.step_details.tool_calls[a.index]):(N(this,Ot,"f")&&this._emit("toolCallDone",N(this,Ot,"f")),we(this,hi,a.index),we(this,Ot,s.step_details.tool_calls[a.index]),N(this,Ot,"f")&&this._emit("toolCallCreated",N(this,Ot,"f")));this._emit("runStepDelta",t.data.delta,s);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":we(this,No,void 0),t.data.step_details.type=="tool_calls"&&N(this,Ot,"f")&&(this._emit("toolCallDone",N(this,Ot,"f")),we(this,Ot,void 0)),this._emit("runStepDone",t.data,s);break}},Pu=function(t){N(this,dc,"f").push(t),this._emit("event",t)},Eu=function(t){switch(t.event){case"thread.run.step.created":return N(this,vs,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let s=N(this,vs,"f")[t.data.id];if(!s)throw Error("Received a RunStepDelta before creation of a snapshot");let n=t.data;if(n.delta){const o=In.accumulateDelta(s,n.delta);N(this,vs,"f")[t.data.id]=o}return N(this,vs,"f")[t.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":N(this,vs,"f")[t.data.id]=t.data;break}if(N(this,vs,"f")[t.data.id])return N(this,vs,"f")[t.data.id];throw new Error("No snapshot available")},Ru=function(t,s){let n=[];switch(t.event){case"thread.message.created":return[t.data,n];case"thread.message.delta":if(!s)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let o=t.data;if(o.delta.content)for(const a of o.delta.content)if(a.index in s.content){let i=s.content[a.index];s.content[a.index]=N(this,xt,"m",Au).call(this,a,i)}else s.content[a.index]=a,n.push(a);return[s,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(s)return[s,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Au=function(t,s){return In.accumulateDelta(s,t)},Iu=function(t){switch(we(this,Ua,t.data),t.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":we(this,$n,t.data),N(this,Ot,"f")&&(this._emit("toolCallDone",N(this,Ot,"f")),we(this,Ot,void 0));break}};let md=class extends ke{constructor(){super(...arguments),this.steps=new rg(this._client)}create(t,s,n){const{include:o,...a}=s;return this._client.post(ne`/threads/${t}/runs`,{query:{include:o},body:a,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:s.stream??!1})}retrieve(t,s,n){const{thread_id:o}=s;return this._client.get(ne`/threads/${o}/runs/${t}`,{...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,s,n){const{thread_id:o,...a}=s;return this._client.post(ne`/threads/${o}/runs/${t}`,{body:a,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s={},n){return this._client.getAPIList(ne`/threads/${t}/runs`,at,{query:s,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(t,s,n){const{thread_id:o}=s;return this._client.post(ne`/threads/${o}/runs/${t}/cancel`,{...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(t,s,n){const o=await this.create(t,s,n);return await this.poll(o.id,{thread_id:t},n)}createAndStream(t,s,n){return Bo.createAssistantStream(t,this._client.beta.threads.runs,s,n)}async poll(t,s,n){var a;const o=be([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=n==null?void 0:n.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const{data:i,response:l}=await this.retrieve(t,s,{...n,headers:{...n==null?void 0:n.headers,...o}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let c=5e3;if(n!=null&&n.pollIntervalMs)c=n.pollIntervalMs;else{const d=l.headers.get("openai-poll-after-ms");if(d){const u=parseInt(d);isNaN(u)||(c=u)}}await aa(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(t,s,n){return Bo.createAssistantStream(t,this._client.beta.threads.runs,s,n)}submitToolOutputs(t,s,n){const{thread_id:o,...a}=s;return this._client.post(ne`/threads/${o}/runs/${t}/submit_tool_outputs`,{body:a,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:s.stream??!1})}async submitToolOutputsAndPoll(t,s,n){const o=await this.submitToolOutputs(t,s,n);return await this.poll(o.id,s,n)}submitToolOutputsStream(t,s,n){return Bo.createToolAssistantStream(t,this._client.beta.threads.runs,s,n)}};md.Steps=rg;class Li extends ke{constructor(){super(...arguments),this.runs=new md(this._client),this.messages=new ng(this._client)}create(t={},s){return this._client.post("/threads",{body:t,...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,s){return this._client.get(ne`/threads/${t}`,{...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,s,n){return this._client.post(ne`/threads/${t}`,{body:s,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,s){return this._client.delete(ne`/threads/${t}`,{...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}createAndRun(t,s){return this._client.post("/threads/runs",{body:t,...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers]),stream:t.stream??!1})}async createAndRunPoll(t,s){const n=await this.createAndRun(t,s);return await this.runs.poll(n.id,{thread_id:n.thread_id},s)}createAndRunStream(t,s){return Bo.createThreadAssistantStream(t,this._client.beta.threads,s)}}Li.Runs=md;Li.Messages=ng;class ca extends ke{constructor(){super(...arguments),this.realtime=new Fi(this._client),this.assistants=new eg(this._client),this.threads=new Li(this._client)}}ca.Realtime=Fi;ca.Assistants=eg;ca.Threads=Li;class og extends ke{create(t,s){return this._client.post("/completions",{body:t,...s,stream:t.stream??!1})}}let ag=class extends ke{retrieve(t,s,n){const{container_id:o}=s;return this._client.get(ne`/containers/${o}/files/${t}/content`,{...n,headers:be([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}},hd=class extends ke{constructor(){super(...arguments),this.content=new ag(this._client)}create(t,s,n){return this._client.post(ne`/containers/${t}/files`,zn({body:s,...n},this._client))}retrieve(t,s,n){const{container_id:o}=s;return this._client.get(ne`/containers/${o}/files/${t}`,n)}list(t,s={},n){return this._client.getAPIList(ne`/containers/${t}/files`,at,{query:s,...n})}delete(t,s,n){const{container_id:o}=s;return this._client.delete(ne`/containers/${o}/files/${t}`,{...n,headers:be([{Accept:"*/*"},n==null?void 0:n.headers])})}};hd.Content=ag;class pd extends ke{constructor(){super(...arguments),this.files=new hd(this._client)}create(t,s){return this._client.post("/containers",{body:t,...s})}retrieve(t,s){return this._client.get(ne`/containers/${t}`,s)}list(t={},s){return this._client.getAPIList("/containers",at,{query:t,...s})}delete(t,s){return this._client.delete(ne`/containers/${t}`,{...s,headers:be([{Accept:"*/*"},s==null?void 0:s.headers])})}}pd.Files=hd;class ig extends ke{create(t,s){const n=!!t.encoding_format;let o=n?t.encoding_format:"base64";n&&yt(this._client).debug("embeddings/user defined encoding_format:",t.encoding_format);const a=this._client.post("/embeddings",{body:{...t,encoding_format:o},...s});return n?a:(yt(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(i=>(i&&i.data&&i.data.forEach(l=>{const c=l.embedding;l.embedding=PS(c)}),i)))}}class lg extends ke{retrieve(t,s,n){const{eval_id:o,run_id:a}=s;return this._client.get(ne`/evals/${o}/runs/${a}/output_items/${t}`,n)}list(t,s,n){const{eval_id:o,...a}=s;return this._client.getAPIList(ne`/evals/${o}/runs/${t}/output_items`,at,{query:a,...n})}}class fd extends ke{constructor(){super(...arguments),this.outputItems=new lg(this._client)}create(t,s,n){return this._client.post(ne`/evals/${t}/runs`,{body:s,...n})}retrieve(t,s,n){const{eval_id:o}=s;return this._client.get(ne`/evals/${o}/runs/${t}`,n)}list(t,s={},n){return this._client.getAPIList(ne`/evals/${t}/runs`,at,{query:s,...n})}delete(t,s,n){const{eval_id:o}=s;return this._client.delete(ne`/evals/${o}/runs/${t}`,n)}cancel(t,s,n){const{eval_id:o}=s;return this._client.post(ne`/evals/${o}/runs/${t}`,n)}}fd.OutputItems=lg;class gd extends ke{constructor(){super(...arguments),this.runs=new fd(this._client)}create(t,s){return this._client.post("/evals",{body:t,...s})}retrieve(t,s){return this._client.get(ne`/evals/${t}`,s)}update(t,s,n){return this._client.post(ne`/evals/${t}`,{body:s,...n})}list(t={},s){return this._client.getAPIList("/evals",at,{query:t,...s})}delete(t,s){return this._client.delete(ne`/evals/${t}`,s)}}gd.Runs=fd;let cg=class extends ke{create(t,s){return this._client.post("/files",zn({body:t,...s},this._client))}retrieve(t,s){return this._client.get(ne`/files/${t}`,s)}list(t={},s){return this._client.getAPIList("/files",at,{query:t,...s})}delete(t,s){return this._client.delete(ne`/files/${t}`,s)}content(t,s){return this._client.get(ne`/files/${t}/content`,{...s,headers:be([{Accept:"application/binary"},s==null?void 0:s.headers]),__binaryResponse:!0})}async waitForProcessing(t,{pollInterval:s=5e3,maxWait:n=30*60*1e3}={}){const o=new Set(["processed","error","deleted"]),a=Date.now();let i=await this.retrieve(t);for(;!i.status||!o.has(i.status);)if(await aa(s),i=await this.retrieve(t),Date.now()-a>n)throw new rd({message:`Giving up on waiting for file ${t} to finish processing after ${n} milliseconds.`});return i}};class dg extends ke{}let ug=class extends ke{run(t,s){return this._client.post("/fine_tuning/alpha/graders/run",{body:t,...s})}validate(t,s){return this._client.post("/fine_tuning/alpha/graders/validate",{body:t,...s})}};class yd extends ke{constructor(){super(...arguments),this.graders=new ug(this._client)}}yd.Graders=ug;class mg extends ke{create(t,s,n){return this._client.getAPIList(ne`/fine_tuning/checkpoints/${t}/permissions`,$i,{body:s,method:"post",...n})}retrieve(t,s={},n){return this._client.get(ne`/fine_tuning/checkpoints/${t}/permissions`,{query:s,...n})}delete(t,s,n){const{fine_tuned_model_checkpoint:o}=s;return this._client.delete(ne`/fine_tuning/checkpoints/${o}/permissions/${t}`,n)}}let xd=class extends ke{constructor(){super(...arguments),this.permissions=new mg(this._client)}};xd.Permissions=mg;class hg extends ke{list(t,s={},n){return this._client.getAPIList(ne`/fine_tuning/jobs/${t}/checkpoints`,at,{query:s,...n})}}class bd extends ke{constructor(){super(...arguments),this.checkpoints=new hg(this._client)}create(t,s){return this._client.post("/fine_tuning/jobs",{body:t,...s})}retrieve(t,s){return this._client.get(ne`/fine_tuning/jobs/${t}`,s)}list(t={},s){return this._client.getAPIList("/fine_tuning/jobs",at,{query:t,...s})}cancel(t,s){return this._client.post(ne`/fine_tuning/jobs/${t}/cancel`,s)}listEvents(t,s={},n){return this._client.getAPIList(ne`/fine_tuning/jobs/${t}/events`,at,{query:s,...n})}pause(t,s){return this._client.post(ne`/fine_tuning/jobs/${t}/pause`,s)}resume(t,s){return this._client.post(ne`/fine_tuning/jobs/${t}/resume`,s)}}bd.Checkpoints=hg;class br extends ke{constructor(){super(...arguments),this.methods=new dg(this._client),this.jobs=new bd(this._client),this.checkpoints=new xd(this._client),this.alpha=new yd(this._client)}}br.Methods=dg;br.Jobs=bd;br.Checkpoints=xd;br.Alpha=yd;class pg extends ke{}class vd extends ke{constructor(){super(...arguments),this.graderModels=new pg(this._client)}}vd.GraderModels=pg;class fg extends ke{createVariation(t,s){return this._client.post("/images/variations",zn({body:t,...s},this._client))}edit(t,s){return this._client.post("/images/edits",zn({body:t,...s,stream:t.stream??!1},this._client))}generate(t,s){return this._client.post("/images/generations",{body:t,...s,stream:t.stream??!1})}}class gg extends ke{retrieve(t,s){return this._client.get(ne`/models/${t}`,s)}list(t){return this._client.getAPIList("/models",$i,t)}delete(t,s){return this._client.delete(ne`/models/${t}`,s)}}class yg extends ke{create(t,s){return this._client.post("/moderations",{body:t,...s})}}function ES(e,t){return!t||!AS(t)?{...e,output_parsed:null,output:e.output.map(s=>s.type==="function_call"?{...s,parsed_arguments:null}:s.type==="message"?{...s,content:s.content.map(n=>({...n,parsed:null}))}:s)}:xg(e,t)}function xg(e,t){const s=e.output.map(o=>{if(o.type==="function_call")return{...o,parsed_arguments:FS(t,o)};if(o.type==="message"){const a=o.content.map(i=>i.type==="output_text"?{...i,parsed:RS(t,i.text)}:i);return{...o,content:a}}return o}),n=Object.assign({},e,{output:s});return Object.getOwnPropertyDescriptor(e,"output_text")||uc(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const o of n.output)if(o.type==="message"){for(const a of o.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function RS(e,t){var s,n,o,a;return((n=(s=e.text)==null?void 0:s.format)==null?void 0:n.type)!=="json_schema"?null:"$parseRaw"in((o=e.text)==null?void 0:o.format)?((a=e.text)==null?void 0:a.format).$parseRaw(t):JSON.parse(t)}function AS(e){var t;return!!id((t=e.text)==null?void 0:t.format)}function IS(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function $S(e,t){return e.find(s=>s.type==="function"&&s.name===t)}function FS(e,t){const s=$S(e.tools??[],t.name);return{...t,...t,parsed_arguments:IS(s)?s.$parseRaw(t.arguments):s!=null&&s.strict?JSON.parse(t.arguments):null}}function uc(e){const t=[];for(const s of e.output)if(s.type==="message")for(const n of s.content)n.type==="output_text"&&t.push(n.text);e.output_text=t.join("")}var Hn,wa,Gs,_a,$u,Fu,Lu,Ou;class Sd extends ad{constructor(t){super(),Hn.add(this),wa.set(this,void 0),Gs.set(this,void 0),_a.set(this,void 0),we(this,wa,t)}static createResponse(t,s,n){const o=new Sd(s);return o._run(()=>o._createOrRetrieveResponse(t,s,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createOrRetrieveResponse(t,s,n){var l;const o=n==null?void 0:n.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),N(this,Hn,"m",$u).call(this);let a,i=null;"response_id"in s?(a=await t.responses.retrieve(s.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=s.starting_after??null):a=await t.responses.create({...s,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(const c of a)N(this,Hn,"m",Fu).call(this,c,i);if((l=a.controller.signal)!=null&&l.aborted)throw new Xt;return N(this,Hn,"m",Lu).call(this)}[(wa=new WeakMap,Gs=new WeakMap,_a=new WeakMap,Hn=new WeakSet,$u=function(){this.ended||we(this,Gs,void 0)},Fu=function(s,n){if(this.ended)return;const o=(i,l)=>{(n==null||l.sequence_number>n)&&this._emit(i,l)},a=N(this,Hn,"m",Ou).call(this,s);switch(o("event",s),s.type){case"response.output_text.delta":{const i=a.output[s.output_index];if(!i)throw new _e(`missing output at index ${s.output_index}`);if(i.type==="message"){const l=i.content[s.content_index];if(!l)throw new _e(`missing content at index ${s.content_index}`);if(l.type!=="output_text")throw new _e(`expected content to be 'output_text', got ${l.type}`);o("response.output_text.delta",{...s,snapshot:l.text})}break}case"response.function_call_arguments.delta":{const i=a.output[s.output_index];if(!i)throw new _e(`missing output at index ${s.output_index}`);i.type==="function_call"&&o("response.function_call_arguments.delta",{...s,snapshot:i.arguments});break}default:o(s.type,s);break}},Lu=function(){if(this.ended)throw new _e("stream has ended, this shouldn't happen");const s=N(this,Gs,"f");if(!s)throw new _e("request ended without sending any events");we(this,Gs,void 0);const n=LS(s,N(this,wa,"f"));return we(this,_a,n),n},Ou=function(s){let n=N(this,Gs,"f");if(!n){if(s.type!=="response.created")throw new _e(`When snapshot hasn't been set yet, expected 'response.created' event, got ${s.type}`);return n=we(this,Gs,s.response),n}switch(s.type){case"response.output_item.added":{n.output.push(s.item);break}case"response.content_part.added":{const o=n.output[s.output_index];if(!o)throw new _e(`missing output at index ${s.output_index}`);o.type==="message"&&o.content.push(s.part);break}case"response.output_text.delta":{const o=n.output[s.output_index];if(!o)throw new _e(`missing output at index ${s.output_index}`);if(o.type==="message"){const a=o.content[s.content_index];if(!a)throw new _e(`missing content at index ${s.content_index}`);if(a.type!=="output_text")throw new _e(`expected content to be 'output_text', got ${a.type}`);a.text+=s.delta}break}case"response.function_call_arguments.delta":{const o=n.output[s.output_index];if(!o)throw new _e(`missing output at index ${s.output_index}`);o.type==="function_call"&&(o.arguments+=s.delta);break}case"response.completed":{we(this,Gs,s.response);break}}return n},Symbol.asyncIterator)](){const t=[],s=[];let n=!1;return this.on("event",o=>{const a=s.shift();a?a.resolve(o):t.push(o)}),this.on("end",()=>{n=!0;for(const o of s)o.resolve(void 0);s.length=0}),this.on("abort",o=>{n=!0;for(const a of s)a.reject(o);s.length=0}),this.on("error",o=>{n=!0;for(const a of s)a.reject(o);s.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>s.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const t=N(this,_a,"f");if(!t)throw new _e("stream ended without producing a ChatCompletion");return t}}function LS(e,t){return ES(e,t)}class bg extends ke{list(t,s={},n){return this._client.getAPIList(ne`/responses/${t}/input_items`,at,{query:s,...n})}}class wd extends ke{constructor(){super(...arguments),this.inputItems=new bg(this._client)}create(t,s){return this._client.post("/responses",{body:t,...s,stream:t.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&uc(n),n))}retrieve(t,s={},n){return this._client.get(ne`/responses/${t}`,{query:s,...n,stream:(s==null?void 0:s.stream)??!1})._thenUnwrap(o=>("object"in o&&o.object==="response"&&uc(o),o))}delete(t,s){return this._client.delete(ne`/responses/${t}`,{...s,headers:be([{Accept:"*/*"},s==null?void 0:s.headers])})}parse(t,s){return this._client.responses.create(t,s)._thenUnwrap(n=>xg(n,t))}stream(t,s){return Sd.createResponse(this._client,t,s)}cancel(t,s){return this._client.post(ne`/responses/${t}/cancel`,s)}}wd.InputItems=bg;class vg extends ke{create(t,s,n){return this._client.post(ne`/uploads/${t}/parts`,zn({body:s,...n},this._client))}}class _d extends ke{constructor(){super(...arguments),this.parts=new vg(this._client)}create(t,s){return this._client.post("/uploads",{body:t,...s})}cancel(t,s){return this._client.post(ne`/uploads/${t}/cancel`,s)}complete(t,s,n){return this._client.post(ne`/uploads/${t}/complete`,{body:s,...n})}}_d.Parts=vg;const OS=async e=>{const t=await Promise.allSettled(e),s=t.filter(o=>o.status==="rejected");if(s.length){for(const o of s)console.error(o.reason);throw new Error(`${s.length} promise(s) failed - see the above errors`)}const n=[];for(const o of t)o.status==="fulfilled"&&n.push(o.value);return n};class Sg extends ke{create(t,s,n){return this._client.post(ne`/vector_stores/${t}/file_batches`,{body:s,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,s,n){const{vector_store_id:o}=s;return this._client.get(ne`/vector_stores/${o}/file_batches/${t}`,{...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(t,s,n){const{vector_store_id:o}=s;return this._client.post(ne`/vector_stores/${o}/file_batches/${t}/cancel`,{...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(t,s,n){const o=await this.create(t,s);return await this.poll(t,o.id,n)}listFiles(t,s,n){const{vector_store_id:o,...a}=s;return this._client.getAPIList(ne`/vector_stores/${o}/file_batches/${t}/files`,at,{query:a,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async poll(t,s,n){var a;const o=be([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=n==null?void 0:n.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const{data:i,response:l}=await this.retrieve(s,{vector_store_id:t},{...n,headers:o}).withResponse();switch(i.status){case"in_progress":let c=5e3;if(n!=null&&n.pollIntervalMs)c=n.pollIntervalMs;else{const d=l.headers.get("openai-poll-after-ms");if(d){const u=parseInt(d);isNaN(u)||(c=u)}}await aa(c);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(t,{files:s,fileIds:n=[]},o){if(s==null||s.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const a=(o==null?void 0:o.maxConcurrency)??5,i=Math.min(a,s.length),l=this._client,c=s.values(),d=[...n];async function u(p){for(let y of p){const g=await l.files.create({file:y,purpose:"assistants"},o);d.push(g.id)}}const h=Array(i).fill(c).map(u);return await OS(h),await this.createAndPoll(t,{file_ids:d})}}class wg extends ke{create(t,s,n){return this._client.post(ne`/vector_stores/${t}/files`,{body:s,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,s,n){const{vector_store_id:o}=s;return this._client.get(ne`/vector_stores/${o}/files/${t}`,{...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,s,n){const{vector_store_id:o,...a}=s;return this._client.post(ne`/vector_stores/${o}/files/${t}`,{body:a,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s={},n){return this._client.getAPIList(ne`/vector_stores/${t}/files`,at,{query:s,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,s,n){const{vector_store_id:o}=s;return this._client.delete(ne`/vector_stores/${o}/files/${t}`,{...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(t,s,n){const o=await this.create(t,s,n);return await this.poll(t,o.id,n)}async poll(t,s,n){var a;const o=be([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=n==null?void 0:n.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const i=await this.retrieve(s,{vector_store_id:t},{...n,headers:o}).withResponse(),l=i.data;switch(l.status){case"in_progress":let c=5e3;if(n!=null&&n.pollIntervalMs)c=n.pollIntervalMs;else{const d=i.response.headers.get("openai-poll-after-ms");if(d){const u=parseInt(d);isNaN(u)||(c=u)}}await aa(c);break;case"failed":case"completed":return l}}}async upload(t,s,n){const o=await this._client.files.create({file:s,purpose:"assistants"},n);return this.create(t,{file_id:o.id},n)}async uploadAndPoll(t,s,n){const o=await this.upload(t,s,n);return await this.poll(t,o.id,n)}content(t,s,n){const{vector_store_id:o}=s;return this._client.getAPIList(ne`/vector_stores/${o}/files/${t}/content`,$i,{...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class Oi extends ke{constructor(){super(...arguments),this.files=new wg(this._client),this.fileBatches=new Sg(this._client)}create(t,s){return this._client.post("/vector_stores",{body:t,...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,s){return this._client.get(ne`/vector_stores/${t}`,{...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,s,n){return this._client.post(ne`/vector_stores/${t}`,{body:s,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t={},s){return this._client.getAPIList("/vector_stores",at,{query:t,...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}delete(t,s){return this._client.delete(ne`/vector_stores/${t}`,{...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}search(t,s,n){return this._client.getAPIList(ne`/vector_stores/${t}/search`,$i,{body:s,method:"post",...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}Oi.Files=wg;Oi.FileBatches=Sg;var er,_g,qa;class Tg extends ke{constructor(){super(...arguments),er.add(this)}async unwrap(t,s,n=this._client.webhookSecret,o=300){return await this.verifySignature(t,s,n,o),JSON.parse(t)}async verifySignature(t,s,n=this._client.webhookSecret,o=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");N(this,er,"m",_g).call(this,n);const a=be([s]).values,i=N(this,er,"m",qa).call(this,a,"webhook-signature"),l=N(this,er,"m",qa).call(this,a,"webhook-timestamp"),c=N(this,er,"m",qa).call(this,a,"webhook-id"),d=parseInt(l,10);if(isNaN(d))throw new jo("Invalid webhook timestamp format");const u=Math.floor(Date.now()/1e3);if(u-d>o)throw new jo("Webhook timestamp is too old");if(d>u+o)throw new jo("Webhook timestamp is too new");const h=i.split(" ").map(f=>f.startsWith("v1,")?f.substring(3):f),p=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),y=c?`${c}.${l}.${t}`:`${l}.${t}`,g=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const f of h)try{const b=Buffer.from(f,"base64");if(await crypto.subtle.verify("HMAC",g,b,new TextEncoder().encode(y)))return}catch{continue}throw new jo("The given webhook signature does not match the expected signature")}}er=new WeakSet,_g=function(t){if(typeof t!="string"||t.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},qa=function(t,s){if(!t)throw new Error("Headers are required");const n=t.get(s);if(n==null)throw new Error(`Missing required header: ${s}`);return n};var mc,Td,Ha,kg;class Ee{constructor({baseURL:t=qn("OPENAI_BASE_URL"),apiKey:s=qn("OPENAI_API_KEY"),organization:n=qn("OPENAI_ORG_ID")??null,project:o=qn("OPENAI_PROJECT_ID")??null,webhookSecret:a=qn("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(mc.add(this),Ha.set(this,void 0),this.completions=new og(this),this.chat=new ud(this),this.embeddings=new ig(this),this.files=new cg(this),this.images=new fg(this),this.audio=new la(this),this.moderations=new yg(this),this.models=new gg(this),this.fineTuning=new br(this),this.graders=new vd(this),this.vectorStores=new Oi(this),this.webhooks=new Tg(this),this.beta=new ca(this),this.batches=new Zf(this),this.uploads=new _d(this),this.responses=new wd(this),this.evals=new gd(this),this.containers=new pd(this),s===void 0)throw new _e("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const l={apiKey:s,organization:n,project:o,webhookSecret:a,...i,baseURL:t||"https://api.openai.com/v1"};if(!l.dangerouslyAllowBrowser&&Dv())throw new _e(`It looks like you're running in a browser-like environment.
|
|
26
|
+
|
|
27
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
28
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
29
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
30
|
+
|
|
31
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
32
|
+
|
|
33
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
34
|
+
`);this.baseURL=l.baseURL,this.timeout=l.timeout??Td.DEFAULT_TIMEOUT,this.logger=l.logger??console;const c="warn";this.logLevel=c,this.logLevel=Su(l.logLevel,"ClientOptions.logLevel",this)??Su(qn("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??Uv(),we(this,Ha,Hv),this._options=l,this.apiKey=s,this.organization=n,this.project=o,this.webhookSecret=a}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...t})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:s}){}async authHeaders(t){return be([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return Jv(t,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Qn}`}defaultIdempotencyKey(){return`stainless-node-retry-${sf()}`}makeStatusError(t,s,n,o){return vt.generate(t,s,n,o)}buildURL(t,s,n){const o=!N(this,mc,"m",kg).call(this)&&n||this.baseURL,a=Av(t)?new URL(t):new URL(o+(o.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),i=this.defaultQuery();return $v(i)||(s={...i,...s}),typeof s=="object"&&s&&!Array.isArray(s)&&(a.search=this.stringifyQuery(s)),a.toString()}async prepareOptions(t){}async prepareRequest(t,{url:s,options:n}){}get(t,s){return this.methodRequest("get",t,s)}post(t,s){return this.methodRequest("post",t,s)}patch(t,s){return this.methodRequest("patch",t,s)}put(t,s){return this.methodRequest("put",t,s)}delete(t,s){return this.methodRequest("delete",t,s)}methodRequest(t,s,n){return this.request(Promise.resolve(n).then(o=>({method:t,path:s,...o})))}request(t,s=null){return new Ii(this,this.makeRequest(t,s,void 0))}async makeRequest(t,s,n){var x,S;const o=await t,a=o.maxRetries??this.maxRetries;s==null&&(s=a),await this.prepareOptions(o);const{req:i,url:l,timeout:c}=await this.buildRequest(o,{retryCount:a-s});await this.prepareRequest(i,{url:l,options:o});const d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,h=Date.now();if(yt(this).debug(`[${d}] sending request`,wn({retryOfRequestLogID:n,method:o.method,url:l,options:o,headers:i.headers})),(x=o.signal)!=null&&x.aborted)throw new Xt;const p=new AbortController,y=await this.fetchWithTimeout(l,i,c,p).catch(tc),g=Date.now();if(y instanceof Error){const w=`retrying, ${s} attempts remaining`;if((S=o.signal)!=null&&S.aborted)throw new Xt;const C=ec(y)||/timed? ?out/i.test(String(y)+("cause"in y?String(y.cause):""));if(s)return yt(this).info(`[${d}] connection ${C?"timed out":"failed"} - ${w}`),yt(this).debug(`[${d}] connection ${C?"timed out":"failed"} (${w})`,wn({retryOfRequestLogID:n,url:l,durationMs:g-h,message:y.message})),this.retryRequest(o,s,n??d);throw yt(this).info(`[${d}] connection ${C?"timed out":"failed"} - error; no more retries left`),yt(this).debug(`[${d}] connection ${C?"timed out":"failed"} (error; no more retries left)`,wn({retryOfRequestLogID:n,url:l,durationMs:g-h,message:y.message})),C?new rd:new Ri({cause:y})}const f=[...y.headers.entries()].filter(([w])=>w==="x-request-id").map(([w,C])=>", "+w+": "+JSON.stringify(C)).join(""),b=`[${d}${u}${f}] ${i.method} ${l} ${y.ok?"succeeded":"failed"} with status ${y.status} in ${g-h}ms`;if(!y.ok){const w=await this.shouldRetry(y);if(s&&w){const k=`retrying, ${s} attempts remaining`;return await qv(y.body),yt(this).info(`${b} - ${k}`),yt(this).debug(`[${d}] response error (${k})`,wn({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,durationMs:g-h})),this.retryRequest(o,s,n??d,y.headers)}const C=w?"error; no more retries left":"error; not retryable";yt(this).info(`${b} - ${C}`);const _=await y.text().catch(k=>tc(k).message),T=Ov(_),j=T?void 0:_;throw yt(this).debug(`[${d}] response error (${C})`,wn({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,message:j,durationMs:Date.now()-h})),this.makeStatusError(y.status,T,j,y.headers)}return yt(this).info(b),yt(this).debug(`[${d}] response start`,wn({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,durationMs:g-h})),{response:y,options:o,controller:p,requestLogID:d,retryOfRequestLogID:n,startTime:h}}getAPIList(t,s,n){return this.requestAPIList(s,{method:"get",path:t,...n})}requestAPIList(t,s){const n=this.makeRequest(s,null,void 0);return new aS(this,n,t)}async fetchWithTimeout(t,s,n,o){const{signal:a,method:i,...l}=s||{};a&&a.addEventListener("abort",()=>o.abort());const c=setTimeout(()=>o.abort(),n),d=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,u={signal:o.signal,...d?{duplex:"half"}:{},method:"GET",...l};i&&(u.method=i.toUpperCase());try{return await this.fetch.call(void 0,t,u)}finally{clearTimeout(c)}}async shouldRetry(t){const s=t.headers.get("x-should-retry");return s==="true"?!0:s==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,s,n,o){let a;const i=o==null?void 0:o.get("retry-after-ms");if(i){const c=parseFloat(i);Number.isNaN(c)||(a=c)}const l=o==null?void 0:o.get("retry-after");if(l&&!a){const c=parseFloat(l);Number.isNaN(c)?a=Date.parse(l)-Date.now():a=c*1e3}if(!(a&&0<=a&&a<60*1e3)){const c=t.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(s,c)}return await aa(a),this.makeRequest(t,s-1,n)}calculateDefaultRetryTimeoutMillis(t,s){const a=s-t,i=Math.min(.5*Math.pow(2,a),8),l=1-Math.random()*.25;return i*l*1e3}async buildRequest(t,{retryCount:s=0}={}){const n={...t},{method:o,path:a,query:i,defaultBaseURL:l}=n,c=this.buildURL(a,i,l);"timeout"in n&&Lv("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:d,body:u}=this.buildBody({options:n}),h=await this.buildHeaders({options:t,method:o,bodyHeaders:d,retryCount:s});return{req:{method:o,headers:h,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:t,method:s,bodyHeaders:n,retryCount:o}){let a={};this.idempotencyHeader&&s!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=t.idempotencyKey);const i=be([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...Wv(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(t),this._options.defaultHeaders,n,t.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:t,headers:s}}){if(!t)return{bodyHeaders:void 0,body:void 0};const n=be([s]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:ff(t)}:N(this,Ha,"f").call(this,{body:t,headers:n})}}Td=Ee,Ha=new WeakMap,mc=new WeakSet,kg=function(){return this.baseURL!=="https://api.openai.com/v1"};Ee.OpenAI=Td;Ee.DEFAULT_TIMEOUT=6e5;Ee.OpenAIError=_e;Ee.APIError=vt;Ee.APIConnectionError=Ri;Ee.APIConnectionTimeoutError=rd;Ee.APIUserAbortError=Xt;Ee.NotFoundError=af;Ee.ConflictError=lf;Ee.RateLimitError=df;Ee.BadRequestError=nf;Ee.AuthenticationError=rf;Ee.InternalServerError=uf;Ee.PermissionDeniedError=of;Ee.UnprocessableEntityError=cf;Ee.InvalidWebhookSignatureError=jo;Ee.toFile=mS;Ee.Completions=og;Ee.Chat=ud;Ee.Embeddings=ig;Ee.Files=cg;Ee.Images=fg;Ee.Audio=la;Ee.Moderations=yg;Ee.Models=gg;Ee.FineTuning=br;Ee.Graders=vd;Ee.VectorStores=Oi;Ee.Webhooks=Tg;Ee.Beta=ca;Ee.Batches=Zf;Ee.Uploads=_d;Ee.Responses=wd;Ee.Evals=gd;Ee.Containers=pd;let Ta=null,ll=null;const DS=()=>{const e=yr().trim().replace(/\/+$/,"");if(e.endsWith("/openai/v1"))return e;const t="/v1";return`${e.endsWith(t)?e.slice(0,-t.length):e}/openai/v1`},Cg=()=>{const e=DS();return Ta?ll!==e&&(Ta=new Ee({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),ll=e):(Ta=new Ee({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),ll=e),Ta};function vr(){const e=Rt(n=>n.currentProvider),t=Rt(n=>n.providerConfig);return m.useMemo(()=>{const n=t.providers[e];if(n&&"model"in n&&n.model)return n.model},[e,t])}function jg(){const e=vr(),t=Rt(n=>n.currentProvider),s=Rt(n=>n.providerConfig);return m.useMemo(()=>{const n=s.providers[t];return n&&"fast_model"in n&&n.fast_model?n.fast_model:e},[t,s,e])}const cl="__BODHI_PROMPT_TITLE__",Ya=e=>e.trim().toLowerCase(),zS=(e,t)=>{let s=e;for(const n of t){if(!s||typeof s!="object"||!(n in s))return;s=s[n]}return typeof s=="string"?s:void 0},dl=e=>{const t=new Set,s=Kt.options.resources;return!s||typeof s!="object"?[]:(Object.values(s).forEach(n=>{if(!n||typeof n!="object")return;const o="translation"in n&&n.translation&&typeof n.translation=="object"?n.translation:n,a=zS(o,e);if(!a)return;const i=Ya(a);i&&t.add(i)}),Array.from(t))},NS=e=>{const t=new Set(["new session","new chat","main"]),s=new Set(["new session","new chat"]),n=[],o=i=>{const l=Ya(i);l&&(t.add(l),s.add(l))},a=i=>{const l=Ya(i);if(l){if(l.includes("{{prompt}}")){const[c,d]=l.split("{{prompt}}",2);n.push({prefix:c,suffix:d});return}if(l.includes(cl.toLowerCase())){const[c,d]=l.split(cl.toLowerCase(),2);n.push({prefix:c,suffix:d});return}s.add(l)}};return dl(["chat","sidebar","newSession"]).forEach(o),dl(["chat","session","defaultTitle"]).forEach(o),dl(["chat","sidebar","newSessionWithPrompt"]).forEach(a),o(e("chat.sidebar.newSession")),o(e("chat.session.defaultTitle")),a(e("chat.sidebar.newSessionWithPrompt",{prompt:cl})),i=>{if(!i)return!0;const l=Ya(i);if(!l||t.has(l))return!0;for(const c of s)if(c&&(l.startsWith(`${c} -`)||l.startsWith(`${c}-`)||l.startsWith(`${c}:`)||l.startsWith(`${c}:`)))return!0;for(const{prefix:c,suffix:d}of n){if(!l.startsWith(c)||!l.endsWith(d))continue;if(l.slice(c.length,l.length-d.length).trim().length>0)return!0}return!1}},kd=e=>{var t,s,n,o,a,i;if("content"in e&&typeof e.content=="string"){const l=e.content.trim();if(l)return l}if("displayText"in e&&typeof e.displayText=="string"){const l=e.displayText.trim();if(l)return l}if(e.role==="assistant"&&"type"in e){if(e.type==="tool_result"&&"result"in e){const l=(t=e.result)==null?void 0:t.result;if(typeof l=="string"&&l.trim())return l.trim()}if(e.type==="task_list"&&"taskList"in e){const l=((n=(s=e.taskList)==null?void 0:s.title)==null?void 0:n.trim())||"",c=(a=(o=e.taskList)==null?void 0:o.items)==null?void 0:a.find(h=>{var p;return(p=h==null?void 0:h.description)==null?void 0:p.trim()}),d=((i=c==null?void 0:c.description)==null?void 0:i.trim())||"",u=[l,d].filter(Boolean).join(" - ");if(u)return u}if(e.type==="tool_call"&&"toolCalls"in e){const l=(e.toolCalls||[]).map(c=>{var d;return(d=c==null?void 0:c.toolName)==null?void 0:d.trim()}).filter(c=>!!c);if(l.length>0)return`Tool calls: ${l.join(", ")}`}}if(e.role==="assistant"&&"metadata"in e&&e.metadata&&typeof e.metadata=="object"&&"reasoning"in e.metadata&&typeof e.metadata.reasoning=="string"){const l=e.metadata.reasoning.trim();if(l)return l}return""},Du=e=>e.filter(t=>t.role!=="user"&&t.role!=="assistant"?!1:kd(t).length>0);function Cd(e){const{message:t}=ts.useApp(),{t:s}=se(),n=z(f=>f.autoGenerateTitles),o=jg(),a=vr(),i=z(f=>f.setAutoGenerateTitlesPreference),l=z(f=>f.isUpdatingAutoTitlePreference),c=m.useRef(new Set),d=m.useRef(new Set),[u,h]=m.useState({}),p=m.useMemo(()=>NS((f,b)=>s(f,b)),[s]),y=m.useCallback(f=>p(f),[p]),g=m.useCallback(async(f,b)=>{var _,T;let x=e.chats.find(j=>j.id===f);if(!x)return!1;let S=Du(x.messages);if(b!=null&&b.force&&S.length===0){await z.getState().loadChatHistory(f,{mode:"replace"});const j=z.getState().chats.find(v=>v.id===f);j&&(x=j,S=Du(j.messages))}const w=!(b!=null&&b.force);if(w&&!n||w&&(d.current.has(f)||c.current.has(f)||!y(x.title)||S.length===0||S.length>6))return!1;d.current.add(f),h(j=>({...j,[f]:{status:"loading"}}));try{const j=(o==null?void 0:o.trim())||"",v=(a==null?void 0:a.trim())||"";let k,E="";if(j)try{E=await Nu(S,j)}catch(M){k=M}if(!E&&v&&v!==j)try{E=await Nu(S,v)}catch(M){k||(k=M)}if(E||(E=qS(S)),!E){if(w)return h(M=>({...M,[f]:{status:"idle"}})),!1;throw k instanceof Error?k:new Error(s("chat.title.generateFailed"))}return e.updateSession(f,{title:E}),(!w||E.toLowerCase()!=="new chat")&&c.current.add(f),h(M=>({...M,[f]:{status:"idle"}})),b!=null&&b.force&&((_=t==null?void 0:t.success)==null||_.call(t,s("chat.title.updated"))),!0}catch(j){const v=j instanceof Error?j.message:s("chat.title.generateFailed");throw h(k=>({...k,[f]:{status:"error",error:v}})),b!=null&&b.force?(T=t==null?void 0:t.error)==null||T.call(t,v):console.warn("[ChatTitleGeneration] Auto title generation failed:",v),j instanceof Error?j:new Error(v)}finally{d.current.delete(f)}},[t,n,y,o,a,e,s]);return{titleGenerationState:u,autoGenerateTitles:n,isUpdatingAutoTitlePreference:l,generateChatTitle:g,setAutoGenerateTitlesPreference:i,isDefaultTitle:y}}const hc=60,BS=20,WS=8,zu=220,US=e=>e.slice(0,WS).map(n=>{const o=n.role==="user"?"User":"Assistant",a=kd(n);if(!a)return"";const i=a.length>zu?`${a.slice(0,zu-3)}...`:a;return`${o}: ${i}`}).filter(n=>n.length>0).join(`
|
|
35
|
+
`),qS=e=>{const t=[...e.filter(s=>s.role==="user"),...e.filter(s=>s.role!=="user")];for(const s of t){const n=kd(s).replace(/\s+/g," ").trim();if(!n)continue;const o=Mg(n);if(o)return o}return""},Mg=e=>{var n;const s=(((n=e.split(/\r?\n/)[0])==null?void 0:n.trim())??"").replace(/^["']+|["']+$/g,"");return s.length<=hc?s:`${s.slice(0,hc-3)}...`},HS=e=>{if(!e||typeof e!="object")return"";const t=e,s=t.content;return typeof s=="string"?s:Array.isArray(s)?s.map(o=>{if(typeof o=="string")return o;if(!o||typeof o!="object")return"";const a=o;if(typeof a.text=="string")return a.text;if(a.text&&typeof a.text=="object"){const i=a.text;if(typeof i.value=="string")return i.value}return typeof a.content=="string"?a.content:""}).filter(o=>o.trim().length>0).join(`
|
|
36
|
+
`):typeof t.refusal=="string"?t.refusal:""},Nu=async(e,t)=>{var l,c;const s=US(e);if(!s)return"";const n=t==null?void 0:t.trim();if(!n)throw new Error("No model configured. Please select a default model in Provider Settings.");const a=await Cg().chat.completions.create({model:n,temperature:.2,max_tokens:BS,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 ${hc} characters) for this chat:
|
|
37
|
+
|
|
38
|
+
${s}`}]}),i=HS((c=(l=a.choices)==null?void 0:l[0])==null?void 0:c.message).trim();return Mg(i)},ka={THEME:"copilot_ui_theme_v1",LAYOUT:"copilot_ui_layout_v1"};class YS{getTheme(){try{return localStorage.getItem(ka.THEME)}catch(t){return console.error("Failed to get theme:",t),null}}setTheme(t){try{localStorage.setItem(ka.THEME,t)}catch(s){console.error("Failed to set theme:",s)}}getLayout(){try{return localStorage.getItem(ka.LAYOUT)}catch(t){return console.error("Failed to get layout:",t),null}}setLayout(t){try{localStorage.setItem(ka.LAYOUT,t)}catch(s){console.error("Failed to set layout:",s)}}getStorageStats(){let t=0;for(let s=0;s<localStorage.length;s++){const n=localStorage.key(s);if(n&&n.startsWith("copilot_ui_")){const o=localStorage.getItem(n);t+=(n.length+((o==null?void 0:o.length)||0))*2}}return{estimatedSize:`${(t/1024).toFixed(1)} KB`}}}const Pg=new YS,jd={collapsed:!1,widthPx:260,collapsedWidthPx:72,minWidthPx:180,maxWidthPx:520},Eg={v:2,sidebar:jd,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:null},splitSizesPx:{}},Bu=e=>{const t=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return`${e}-${t}`},zt=e=>e.type==="leaf"?[e.id]:[...zt(e.children[0]),...zt(e.children[1])],Jo=e=>e.type==="leaf"?[]:[e.id,...Jo(e.children[0]),...Jo(e.children[1])],XS=(e,t)=>{for(const[s,n]of Object.entries(e))if(n===t)return s;return null},VS=(e,t)=>{const s={},n=new Set;return e.forEach(o=>{const a=t[o]??null;if(!a||n.has(a)){s[o]=null;return}n.add(a),s[o]=a}),s},pc=(e,t,s,n,o)=>e.type==="leaf"?e.id!==t?e:{type:"split",id:n,layout:s,children:[e,{type:"leaf",id:o}]}:{...e,children:[pc(e.children[0],t,s,n,o),pc(e.children[1],t,s,n,o)]},fc=(e,t)=>{if(e.type==="leaf")return e.id===t?{node:null,removed:!0}:{node:e,removed:!1};const s=fc(e.children[0],t);if(s.removed)return s.node?{node:{...e,children:[s.node,e.children[1]]},removed:!0}:{node:e.children[1],removed:!0};const n=fc(e.children[1],t);return n.removed?n.node?{node:{...e,children:[e.children[0],n.node]},removed:!0}:{node:e.children[0],removed:!0}:{node:e,removed:!1}},KS=e=>({v:2,sidebar:e.sidebar,tree:e.tree,activeLeafId:e.activeLeafId,leafSessionIds:e.leafSessionIds,splitSizesPx:e.splitSizesPx}),GS=e=>{try{Pg.setLayout(JSON.stringify(e))}catch(t){console.warn("[uiLayoutStore] Failed to persist layout:",t)}},Is=e=>{const t=KS(e);return GS(t),t},JS=e=>{var p,y,g,f,b,x,S,w,C,_,T;const t={...jd,...e.sidebar||{}},s=((p=e.view)==null?void 0:p.mode)??"single",n=((y=e.view)==null?void 0:y.twoDirection)??"horizontal",o={...((g=e.panes)==null?void 0:g.sessionIds)||{}},a=((f=e.panes)==null?void 0:f.activePaneId)??"lt",i={};if(s==="single")return{v:2,sidebar:t,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:o.lt??null},splitSizesPx:{}};if(s==="two"){const j="split-root",v=n,k=v==="horizontal"?{type:"split",id:j,layout:v,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"rt"}]}:{type:"split",id:j,layout:v,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},E=v==="horizontal"?((b=e.split)==null?void 0:b.twoHorizontalPx)||((x=e.split)==null?void 0:x.columnsPx)||null:((S=e.split)==null?void 0:S.twoVerticalPx)||((w=e.split)==null?void 0:w.leftRowsPx)||null;E&&(i[j]=E);const M=zt(k);return{v:2,sidebar:t,tree:k,activeLeafId:M.includes(a)?a:M[0],leafSessionIds:Object.fromEntries(M.map(R=>[R,o[R]??null])),splitSizesPx:i}}const l="split-root",c="split-left",d="split-right",u={type:"split",id:l,layout:"horizontal",children:[{type:"split",id:c,layout:"vertical",children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},{type:"split",id:d,layout:"vertical",children:[{type:"leaf",id:"rt"},{type:"leaf",id:"rb"}]}]};(C=e.split)!=null&&C.columnsPx&&(i[l]=e.split.columnsPx),(_=e.split)!=null&&_.leftRowsPx&&(i[c]=e.split.leftRowsPx),(T=e.split)!=null&&T.rightRowsPx&&(i[d]=e.split.rightRowsPx);const h=zt(u);return{v:2,sidebar:t,tree:u,activeLeafId:h.includes(a)?a:h[0],leafSessionIds:Object.fromEntries(h.map(j=>[j,o[j]??null])),splitSizesPx:i}},QS=e=>{if(!e)return null;try{const t=JSON.parse(e);if(!t||typeof t!="object")return null;if(t.v===2){const s={...jd,...t.sidebar||{}},n=t.tree||Eg.tree,o=zt(n),a=Jo(n),i={};o.forEach(u=>{var h;i[u]=typeof((h=t.leafSessionIds)==null?void 0:h[u])=="string"?t.leafSessionIds[u]:null});const l={};a.forEach(u=>{var p;const h=(p=t.splitSizesPx)==null?void 0:p[u];Array.isArray(h)&&h.length>=2&&(l[u]=[Number(h[0]),Number(h[1])])});const c=typeof t.activeLeafId=="string"&&o.includes(t.activeLeafId)?t.activeLeafId:o[0],d=VS(o,i);return{v:2,sidebar:s,tree:n,activeLeafId:c,leafSessionIds:d,splitSizesPx:l}}return t.v===1?JS(t):null}catch{return null}},ZS=()=>QS(Pg.getLayout())??Eg,Ae=un(e=>({...ZS(),setSidebarCollapsed:t=>{e(s=>s.sidebar.collapsed===t?s:Is({sidebar:{...s.sidebar,collapsed:t},tree:s.tree,activeLeafId:s.activeLeafId,leafSessionIds:s.leafSessionIds,splitSizesPx:s.splitSizesPx}))},setSidebarWidthPx:t=>{e(s=>{const n=Math.max(s.sidebar.minWidthPx,Math.min(s.sidebar.maxWidthPx,t));return s.sidebar.widthPx===n?s:Is({sidebar:{...s.sidebar,widthPx:n},tree:s.tree,activeLeafId:s.activeLeafId,leafSessionIds:s.leafSessionIds,splitSizesPx:s.splitSizesPx})})},setActiveLeafId:t=>{e(s=>s.activeLeafId===t||!zt(s.tree).includes(t)?s:(Yt("setActiveLeafId",{from:s.activeLeafId,to:t}),Is({sidebar:s.sidebar,tree:s.tree,activeLeafId:t,leafSessionIds:s.leafSessionIds,splitSizesPx:s.splitSizesPx})))},setLeafSessionId:(t,s)=>{e(n=>{const o=zt(n.tree);if(!o.includes(t)||(n.leafSessionIds[t]??null)===s)return n;const a=[];Yt("setLeafSessionId",{leafId:t,fromSessionId:n.leafSessionIds[t]??null,toSessionId:s,mode:"unique_session_per_leaf"});const i={...n.leafSessionIds,[t]:s};if(s)for(const l of o)l!==t&&i[l]===s&&(i[l]=null,a.push(l));return a.length>0&&Yt("setLeafSessionId dedupe",{sessionId:s,clearedLeafIds:a,assignedLeafId:t}),o.forEach(l=>{l in i||(i[l]=null)}),Is({sidebar:n.sidebar,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:i,splitSizesPx:n.splitSizesPx})})},clearSessionFromAllLeaves:t=>{e(s=>{const n={...s.leafSessionIds};let o=!1;for(const[a,i]of Object.entries(n))i===t&&(n[a]=null,o=!0);return o?Is({sidebar:s.sidebar,tree:s.tree,activeLeafId:s.activeLeafId,leafSessionIds:n,splitSizesPx:s.splitSizesPx}):s})},splitLeaf:(t,s)=>{e(n=>{const o=zt(n.tree);if(!o.includes(t)||o.length>=4)return n;const a=Bu("split"),i=Bu("pane"),l=pc(n.tree,t,s,a,i),c={...n.leafSessionIds,[i]:null};return Is({sidebar:n.sidebar,tree:l,activeLeafId:i,leafSessionIds:c,splitSizesPx:n.splitSizesPx})})},closeLeaf:t=>{e(s=>{const n=zt(s.tree);if(!n.includes(t)||n.length<=1)return s;const o=fc(s.tree,t);if(!o.removed||!o.node)return s;const a=o.node,i=zt(a),l=Jo(a),c={};i.forEach(h=>{c[h]=s.leafSessionIds[h]??null});const d={};l.forEach(h=>{const p=s.splitSizesPx[h];p&&(d[h]=p)});const u=s.activeLeafId===t?i[0]:i.includes(s.activeLeafId)?s.activeLeafId:i[0];return Is({sidebar:s.sidebar,tree:a,activeLeafId:u,leafSessionIds:c,splitSizesPx:d})})},setSplitSizesPx:(t,s)=>{e(n=>{const o=n.splitSizesPx[t];return o&&o[0]===s[0]&&o[1]===s[1]?n:Is({sidebar:n.sidebar,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:{...n.splitSizesPx,[t]:s}})})},pruneSplitSizes:()=>{e(t=>{const s=new Set(Jo(t.tree)),n={};for(const[i,l]of Object.entries(t.splitSizesPx))s.has(i)&&(n[i]=l);const o=Object.keys(t.splitSizesPx),a=Object.keys(n);return o.length===a.length&&o.every(i=>i in n)?t:Is({sidebar:t.sidebar,tree:t.tree,activeLeafId:t.activeLeafId,leafSessionIds:t.leafSessionIds,splitSizesPx:n})})}})),ew=async(e,t)=>{var i;const s=z.getState(),n=!s.chats.some(l=>l.id===e);if(t!=null&&t.forceRefreshIndex||n)try{await s.refreshChats()}catch(l){console.warn("[openSession] refreshChats failed:",l)}const o=z.getState().chats.find(l=>l.id===e);if(!o)return;if(t!=null&&t.forceLoadHistory||n||(((i=o.messages)==null?void 0:i.length)||0)===0&&(o.messageCount||0)>0)try{await s.loadChatHistory(e)}catch(l){console.warn("[openSession] loadChatHistory failed:",l)}if(t!=null&&t.forceSubscribe){s.setSessionProcessing(e,!0);return}((t==null?void 0:t.subscribeIfRunning)??!0)&&o.isRunning&&s.setSessionProcessing(e,!0)},Di=(e,t)=>{const{activeLeafId:s,leafSessionIds:n,setLeafSessionId:o,setActiveLeafId:a}=Ae.getState(),i=XS(n,e),l=n[s]??null;Yt("openSession (input)",{activeLeafId:s,activeLeafSessionId:l,sessionId:e,existingLeafId:i}),i?i===s?Yt("openSession (decision)",{action:"noop_already_active",leafId:s,sessionId:e}):(a(i),Yt("openSession (decision)",{action:"focus_existing_leaf",leafId:i,sessionId:e})):(o(s,e),Yt("openSession (decision)",{action:"assign_to_active_leaf",leafId:s,sessionId:e})),z.getState().selectSession(e),ew(e,t)},ul=(e,t)=>{if(!t)return!0;const s=[e.title,e.id,e.kind||"root",e.config.workspacePath||"",e.config.systemPromptId||"",e.updatedAt||"",e.createdByScheduleId||"",e.lastRunStatus||"",e.lastRunError||"",...e.messages.filter(o=>o.role==="user"&&"content"in o).slice(0,3).map(o=>"content"in o?o.content:"")].join(" ").toLowerCase();return t.split(/\s+/).filter(Boolean).every(o=>s.includes(o))},ml=(e,t)=>{switch(t){case"pinned":return!!e.pinned;case"running":return!!e.isRunning;case"child":return e.kind==="child";case"all":default:return!0}},tw=()=>{const{t:e}=se(),t=z(V=>V.chats),s=z(V=>V.currentSessionId),n=z(V=>V.deleteSession),o=z(V=>V.deleteSessions),a=z(V=>V.pinSession),i=z(V=>V.unpinSession),l=z(V=>V.updateSession),c=z(V=>V.addChat),d=z(V=>V.lastSelectedPromptId),u=z(V=>V.systemPrompts),h=Ae(V=>V.sidebar.collapsed),p=Ae(V=>V.setSidebarCollapsed),y=Ae(V=>V.clearSessionFromAllLeaves),{generateChatTitle:g,titleGenerationState:f}=Cd({chats:t,updateSession:l}),b=m.useCallback(async(V,ge)=>{var tt,st;const oe=u.find(rt=>rt.id===d),ce=(oe==null?void 0:oe.id)||(u.length>0?((tt=u.find(rt=>rt.id==="general_assistant"))==null?void 0:tt.id)||u[0].id:""),Me={title:V||e("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:ce,baseSystemPrompt:(oe==null?void 0:oe.content)||(u.length>0?((st=u.find(rt=>rt.id==="general_assistant"))==null?void 0:st.content)||u[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null,...ge},It=await c(Me),{activeLeafId:St}=Ae.getState();Ae.getState().setLeafSessionId(St,It),Ae.getState().setActiveLeafId(St)},[c,d,u,e]),[x,S]=m.useState(!1),[w,C]=m.useState(new Set(["Today"])),[_,T]=m.useState(""),[j,v]=m.useState("all"),k=z(xr(s)),E=m.useMemo(()=>k?lu(k):null,[k]),M=m.useMemo(()=>{const V=new Set(w);return E&&V.add(E),Array.from(V)},[E,w]),R=V=>{const ge=new Set(Array.isArray(V)?V:[V]);C(oe=>{if(oe.size!==ge.size)return ge;for(const ce of ge)if(!oe.has(ce))return ge;return oe})},I=_.trim().toLowerCase(),P=I.length>0||j!=="all",L=m.useMemo(()=>t.filter(V=>V.kind!=="child"),[t]),O=m.useMemo(()=>{const V={};for(const ge of t){if(ge.kind!=="child")continue;const oe=ge.parentSessionId||ge.rootSessionId;oe&&(V[oe]||(V[oe]=[]),V[oe].push(ge))}return Object.keys(V).forEach(ge=>{V[ge].sort((oe,ce)=>{if(oe.pinned!==ce.pinned)return oe.pinned?-1:1;const Me=Date.parse(oe.updatedAt||"")||oe.createdAt||0;return(Date.parse(ce.updatedAt||"")||ce.createdAt||0)-Me})}),V},[t]),A=m.useMemo(()=>P?L.filter(V=>ul(V,I)&&ml(V,j)?!0:(O[V.id]||[]).some(ce=>ul(ce,I)&&ml(ce,j))):L,[O,P,I,L,j]),$=m.useMemo(()=>{if(!P)return O;const V={};for(const ge of A){const oe=O[ge.id]||[];V[ge.id]=oe.filter(ce=>ul(ce,I)&&ml(ce,j))}return V},[O,A,P,I,j]),W=Sv(A),F=wv(W),H=m.useCallback(V=>{a(V),C(ge=>{if(ge.has("Pinned"))return ge;const oe=new Set(ge);return oe.add("Pinned"),oe})},[a]),D=m.useCallback(V=>{const ge=t.find(ce=>ce.id===V),oe=ge?lu({...ge,pinned:!1}):null;i(V),oe&&C(ce=>{if(ce.has(oe))return ce;const Me=new Set(ce);return Me.add(oe),Me})},[t,i]),U=V=>{Et.confirm({title:e("chat.sidebar.delete.title"),content:e("chat.sidebar.delete.confirm"),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{y(V),n(V)}})},Q=qs(V=>V.open),Y=()=>{Q("chat")},he=m.useCallback(V=>{T(V)},[]),ve=m.useCallback(V=>{v(V)},[]),ue=(V,ge)=>{l(V,{title:ge})},ie=async V=>{try{await g(V,{force:!0})}catch(ge){console.error("Failed to generate title:",ge)}},Re=V=>{const ge=_v(W,V),oe=tf(W,V);Et.confirm({title:e("chat.sidebar.deleteByDate.title",{date:V}),content:e("chat.sidebar.deleteByDate.confirm",{count:oe,date:V}),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{ge.forEach(ce=>y(ce)),o(ge)}})},Le=()=>{S(!0)},Ze=()=>{S(!1)},et=async V=>{try{await b(e("chat.sidebar.newSessionWithPrompt",{prompt:V.name}),{config:{systemPromptId:V.id,baseSystemPrompt:V.content,lastUsedEnhancedPrompt:null}}),S(!1)}catch(ge){console.error("Failed to create chat:",ge),Et.error({title:e("chat.sidebar.createFailedTitle"),content:ge instanceof Error?ge.message:e("chat.sidebar.createFailedUnknown")})}},Ct=m.useCallback(V=>Di(V),[]),[pt,At]=m.useState(new Set),re=m.useMemo(()=>{var oe;const V=new Set(pt),ge=t.find(ce=>ce.id===s);if(ge){const ce=ge.kind==="child"?ge.parentSessionId||ge.rootSessionId:ge.id;ce&&V.add(ce)}for(const ce of t)if(ce.kind==="child"&&ce.pinned){const Me=ce.parentSessionId||ce.rootSessionId;Me&&V.add(Me)}if(P)for(const ce of A)(((oe=$[ce.id])==null?void 0:oe.length)??0)>0&&V.add(ce.id);return V},[t,$,s,pt,A,P]),$e=m.useCallback(V=>{At(ge=>{const oe=new Set(ge);return oe.has(V)?oe.delete(V):oe.add(V),oe})},[]);return{chats:A,childrenByRoot:$,expandedRootIds:re,toggleRootExpanded:$e,collapsed:h,currentSessionId:s,expandedKeys:M,groupedChatsByDate:W,hasActiveFilters:P,handleCollapseChange:R,handleDelete:U,handleDeleteByDate:Re,handleEditTitle:ue,handleGenerateTitle:ie,handleNewChat:Le,handleNewChatSelectorClose:Ze,handleOpenSettings:Y,handleSearchQueryChange:he,handleStatusFilterChange:ve,handleSystemPromptSelect:et,isNewChatSelectorOpen:x,pinSession:H,searchQuery:_,selectSession:Ct,setCollapsed:p,sortedDateKeys:F,statusFilter:j,systemPrompts:u,titleGenerationState:f,unpinSession:D}},{useBreakpoint:sw}=_i,{useToken:nw}=xe,rw=()=>{const{token:e}=nw(),{t}=se(),s=sw(),{childrenByRoot:n,expandedRootIds:o,toggleRootExpanded:a,collapsed:i,currentSessionId:l,expandedKeys:c,groupedChatsByDate:d,handleCollapseChange:u,handleDelete:h,handleDeleteByDate:p,handleEditTitle:y,handleGenerateTitle:g,handleNewChat:f,handleNewChatSelectorClose:b,handleOpenSettings:x,handleSearchQueryChange:S,handleStatusFilterChange:w,handleSystemPromptSelect:C,hasActiveFilters:_,isNewChatSelectorOpen:T,pinSession:j,searchQuery:v,selectSession:k,setCollapsed:E,sortedDateKeys:M,statusFilter:R,systemPrompts:I,titleGenerationState:P,unpinSession:L}=tw(),{xs:O,sm:A}=s;return m.useEffect(()=>{typeof O!="boolean"||typeof A!="boolean"||O===!1&&A===!1&&E(!0)},[A,O,E]),i?null:r.jsxs("nav",{"aria-label":t("chat.sidebar.title","Chat sidebar"),style:{width:"100%",height:"100%",background:"transparent",borderRight:`1px solid ${e.colorBorderSecondary}`,position:"relative",overflow:"hidden",display:"flex",flexDirection:"column",minHeight:0},children:[r.jsx(K,{justify:"flex-end",style:{flexShrink:0,padding:"10px 12px 2px 12px",minHeight:40},children:r.jsx(B,{type:"text",icon:r.jsx(Cp,{}),onClick:()=>E(!0),size:s.xs?"small":"middle",className:"lotus-toolbar-icon","aria-label":t("chat.sidebar.collapse","Collapse sidebar")})}),r.jsxs(K,{vertical:!0,gap:"small",style:{flexShrink:0,padding:"10px 12px 8px 12px"},children:[r.jsx(ye,{allowClear:!0,value:v,onChange:$=>S($.target.value),prefix:r.jsx(Ho,{style:{color:e.colorTextTertiary}}),placeholder:t("chat.sidebar.searchPlaceholder","Search sessions"),"aria-label":t("chat.sidebar.searchPlaceholder","Search sessions"),size:s.xs?"middle":"large",style:{borderRadius:e.borderRadiusLG}}),r.jsx(xx,{block:!0,size:s.xs?"middle":"small",value:R,onChange:$=>w($),options:[{label:t("chat.sidebar.filters.all","All"),value:"all"},{label:t("chat.sidebar.filters.pinned","Pinned"),value:"pinned"},{label:t("chat.sidebar.filters.running","Running"),value:"running"},{label:t("chat.sidebar.filters.child","Child"),value:"child"}]})]}),r.jsx(K,{vertical:!0,role:"list","aria-label":t("chat.sidebar.chatList","Chat list"),style:{flex:1,minHeight:0,overflowY:"auto",padding:"0 12px 0 12px"},children:r.jsx(Tv,{groupedChatsByDate:d,childrenByRoot:n,expandedRootIds:o,onToggleRootExpanded:a,sortedDateKeys:M,expandedKeys:c,onCollapseChange:u,currentSessionId:l,onSelectChat:k,onDeleteChat:h,onDeleteByDate:p,onPinChat:j,onUnpinChat:L,onEditTitle:y,onGenerateTitle:g,titleGenerationState:P,token:e,hasActiveFilters:_})}),r.jsx(Ev,{collapsed:!1,onNewChat:f,onOpenSettings:x,screens:s,token:e}),r.jsx(xv,{open:T,onClose:b,onSelect:C,prompts:I,title:t("chat.prompt.newSessionSelectorTitle"),showCancelButton:!0})]})},Wu=e=>Symbol.iterator in e,Uu=e=>"entries"in e,qu=(e,t)=>{const s=e instanceof Map?e:new Map(e.entries()),n=t instanceof Map?t:new Map(t.entries());if(s.size!==n.size)return!1;for(const[o,a]of s)if(!Object.is(a,n.get(o)))return!1;return!0},ow=(e,t)=>{const s=e[Symbol.iterator](),n=t[Symbol.iterator]();let o=s.next(),a=n.next();for(;!o.done&&!a.done;){if(!Object.is(o.value,a.value))return!1;o=s.next(),a=n.next()}return!!o.done&&!!a.done};function aw(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:Wu(e)&&Wu(t)?Uu(e)&&Uu(t)?qu(e,t):ow(e,t):qu({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function iw(e){const t=dt.useRef(void 0);return s=>{const n=e(s);return aw(t.current,n)?t.current:t.current=n}}function lw(){const{chats:e,currentSessionId:t,currentChat:s,addMessage:n,selectSession:o,deleteSession:a,deleteSessions:i,deleteMessage:l,updateSession:c,pinSession:d,unpinSession:u,loadChats:h,processingChats:p,setSessionProcessing:y}=z(iw(w=>({chats:w.chats,currentSessionId:w.currentSessionId,currentChat:cv(w),addMessage:w.addMessage,selectSession:w.selectSession,deleteSession:w.deleteSession,deleteSessions:w.deleteSessions,deleteMessage:w.deleteMessage,updateSession:w.updateSession,pinSession:w.pinSession,unpinSession:w.unpinSession,loadChats:w.loadChats,processingChats:w.processingChats,setSessionProcessing:w.setSessionProcessing}))),g=t?p.has(t):!1,f=m.useMemo(()=>(s==null?void 0:s.messages)||[],[s]),b=m.useMemo(()=>e.filter(w=>w.pinned),[e]),x=m.useMemo(()=>e.filter(w=>!w.pinned),[e]),S=e.length;return{chats:e,currentSessionId:t,currentChat:s,isProcessing:g,baseMessages:f,pinnedChats:b,unpinnedChats:x,chatCount:S,addMessage:n,deleteMessage:l,selectSession:o,deleteSession:a,deleteSessions:i,pinSession:d,unpinSession:u,updateSession:c,loadChats:h,setSessionProcessing:y}}function cw(e){const t=z(p=>p.addChat),s=z(p=>p.lastSelectedPromptId),n=z(p=>p.systemPrompts),o=hs.getInstance(),a=m.useCallback(async(p,y)=>{var x,S;const g=n.find(w=>w.id===s),f=(g==null?void 0:g.id)||(n.length>0?((x=n.find(w=>w.id==="general_assistant"))==null?void 0:x.id)||n[0].id:""),b={title:p||"New Session",createdAt:Date.now(),messages:[],config:{systemPromptId:f,baseSystemPrompt:(g==null?void 0:g.content)||(n.length>0?((S=n.find(w=>w.id==="general_assistant"))==null?void 0:S.content)||n[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null,...y};await t(b)},[t,s,n]),i=m.useCallback(async p=>{He("[ChatOps]","[useChatOperations] createChatWithSystemPrompt started with prompt:",p);const y={title:`New Session - ${p.name}`,createdAt:Date.now(),messages:[],config:{systemPromptId:p.id,baseSystemPrompt:p.content,lastUsedEnhancedPrompt:null},currentInteraction:null};He("[ChatOps]","[useChatOperations] Calling addChat with newChatData.config:",y.config),await t(y)},[t]),l=m.useCallback(p=>{const y=e.chats.find(g=>g.id===p);y&&(y.pinned?e.unpinSession(p):e.pinSession(p))},[e]),c=m.useCallback((p,y)=>{e.updateSession(p,{title:y})},[e]),d=m.useCallback(async()=>{await o.cleanupSessions("empty",!0),await z.getState().loadChats()},[o]),u=m.useCallback(async()=>{await o.cleanupSessions("all",!0),await z.getState().loadChats()},[o]),h=m.useCallback(async()=>{await o.cleanupSessions("all",!1),await z.getState().loadChats()},[o]);return{createNewChat:a,createChatWithSystemPrompt:i,toggleChatPin:l,updateChatTitle:c,deleteEmptyChats:d,deleteAllUnpinnedChats:u,deleteAllChats:h}}const Lo=new Map,Xa=new Set,Yn=new Map,Wo=new Map;let gc=null;const Rg=(e,t)=>{const s=Lo.get(e);s&&s.forEach(n=>n(t))},dw=()=>{if(gc=null,Wo.size===0)return;const e=Array.from(Wo.values());Wo.clear(),e.forEach(t=>{Rg(t.messageId,t.content),Xa.forEach(s=>s(t))})},Fe={getLatest(e){return Yn.get(e)??null},subscribeMessage(e,t){let s=Lo.get(e);return s||(s=new Set,Lo.set(e,s)),s.add(t),Yn.has(e)&&t(Yn.get(e)??null),()=>{const n=Lo.get(e);n&&(n.delete(t),n.size===0&&Lo.delete(e))}},subscribe(e){return Xa.add(e),()=>{Xa.delete(e)}},publish(e){e.content===null?Yn.delete(e.messageId):Yn.set(e.messageId,e.content),Wo.set(e.messageId,e),gc===null&&(gc=requestAnimationFrame(dw))},clear(e,t){Yn.delete(t),Wo.delete(t),Rg(t,null),Xa.forEach(s=>s({sessionId:e,messageId:t,content:null}))}},Ag="mermaid_enhancement_enabled",yc=()=>localStorage.getItem(Ag)!=="false",uw=e=>{localStorage.setItem(Ag,e.toString())},mw=()=>`
|
|
39
|
+
|
|
40
|
+
## 📊 Visual Representation Guidelines
|
|
41
|
+
|
|
42
|
+
When explaining concepts, processes, relationships, or data structures, use Mermaid diagrams to enhance understanding. Choose appropriate diagram types:
|
|
43
|
+
|
|
44
|
+
- **Flowcharts** (graph TD/LR) - processes, workflows, decision trees
|
|
45
|
+
- **Sequence Diagrams** - API interactions, communication flows
|
|
46
|
+
- **Class Diagrams** - object relationships, data models
|
|
47
|
+
- **State Diagrams** - state machines, status flows
|
|
48
|
+
- **Gantt Charts** - project timelines
|
|
49
|
+
- **ER Diagrams** - database schemas
|
|
50
|
+
- **Git Graphs** - version control workflows
|
|
51
|
+
|
|
52
|
+
**Syntax Notes:**
|
|
53
|
+
- Mermaid diagram definitions MUST be inside a fenced code block (never inline). Example:
|
|
54
|
+
\`\`\`mermaid
|
|
55
|
+
graph TD
|
|
56
|
+
A --> B
|
|
57
|
+
\`\`\`
|
|
58
|
+
- Avoid nested brackets: use \`A[Text]\` or \`A(Text)\`, NOT \`A[Text()]\`
|
|
59
|
+
- Use HTML entities for special chars: # for #, ; for ;, " for quotes
|
|
60
|
+
- Keep participant names simple (no spaces): \`participant UserService\`
|
|
61
|
+
- Arrow syntax: \`-->\` (solid), \`-.->\` (dotted), \`==>\` (thick), \`-->|label|\` (labeled)
|
|
62
|
+
|
|
63
|
+
Include relevant diagrams when discussing architecture, workflows, data flow, or relationships.`,xc="task_enhancement_enabled",Hu="todo_enhancement_enabled",hw=e=>e==="false",bc=()=>{let e=localStorage.getItem(xc);if(e===null){const t=localStorage.getItem(Hu);t!==null&&(e=t,localStorage.setItem(xc,t),localStorage.removeItem(Hu))}return!hw(e)},pw=e=>{localStorage.setItem(xc,e.toString())},fw=()=>`
|
|
64
|
+
|
|
65
|
+
## Task Management Rules
|
|
66
|
+
|
|
67
|
+
Use the Task tool for non-trivial or multi-step tasks.
|
|
68
|
+
Task updates are shared across the current root session and all child sessions.
|
|
69
|
+
Keep exactly one item in \`in_progress\` state whenever possible.
|
|
70
|
+
Update Task immediately when a step starts or completes; do not batch status updates.
|
|
71
|
+
Do not use Markdown checkbox lists as a substitute for Task.
|
|
72
|
+
Skip Task only for simple one-step requests.
|
|
73
|
+
Use SubSession only when the user explicitly requests delegated/parallel sub-session work.
|
|
74
|
+
`,Ig=()=>{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"},gw=e=>{switch(e){case"windows":return"Windows";case"macos":return"macOS";case"linux":return"Linux";default:return"Unknown OS"}},yw=()=>{const e=Ig(),s=`## 🖥️ Operating System Information
|
|
75
|
+
|
|
76
|
+
You are running on **${gw(e)}**.`;return e==="windows"?s+`
|
|
77
|
+
|
|
78
|
+
### Windows-Specific Notes:
|
|
79
|
+
|
|
80
|
+
- **Configuration Directory**: Application configuration and data are stored in the user's home directory at \`.bamboo\` (e.g., \`C:\\Users\\[Username]\\.bamboo\`)
|
|
81
|
+
- Note: When accessing this directory programmatically, use the expanded path rather than the ~ shorthand
|
|
82
|
+
|
|
83
|
+
- **Home Directory Paths with Tilde (~)**: On Windows, a leading tilde (~) in file paths is NOT automatically expanded to the user's home directory by most Windows-native APIs and tools. When you encounter paths starting with ~, ~/, or ~\\, you MUST replace them with the Windows absolute path before using them.
|
|
84
|
+
- Example: \`~/Documents/file.txt\` should be expanded to \`C:\\Users\\[Username]\\Documents\\file.txt\`
|
|
85
|
+
- Use tools to get the actual home directory path when needed
|
|
86
|
+
- Note: This applies to leading tilde only. Windows short paths like \`C:\\PROGRA~1\\\` are valid and should NOT be modified
|
|
87
|
+
- Some Windows shells (PowerShell, Git Bash, WSL) may support ~ in specific contexts, but Windows-native paths/APIs generally do not
|
|
88
|
+
|
|
89
|
+
- **Path Separators**: Windows uses backslashes (\\) as path separators, but forward slashes (/) are also accepted in most contexts
|
|
90
|
+
- **Case Insensitivity**: Windows file paths are case-insensitive (file.txt and FILE.TXT refer to the same file)
|
|
91
|
+
- **Drive Letters**: Windows paths typically start with a drive letter (C:\\, D:\\, etc.)`:e==="macos"?s+`
|
|
92
|
+
|
|
93
|
+
### macOS-Specific Notes:
|
|
94
|
+
|
|
95
|
+
- **Configuration Directory**: Application configuration and data are stored in \`~/.bamboo\` (expands to \`/Users/[Username]/.bamboo\`)
|
|
96
|
+
|
|
97
|
+
- **File Paths**: macOS uses Unix-style paths with forward slashes (/)
|
|
98
|
+
- **Home Directory**: The tilde (~) expands to /Users/[Username]
|
|
99
|
+
- **Case Sensitivity**: macOS file system may be case-sensitive or case-insensitive depending on format (APFS is case-insensitive by default)`:e==="linux"?s+`
|
|
100
|
+
|
|
101
|
+
### Linux-Specific Notes:
|
|
102
|
+
|
|
103
|
+
- **Configuration Directory**: Application configuration and data are stored in \`~/.bamboo\` (expands to \`/home/[username]/.bamboo\`)
|
|
104
|
+
|
|
105
|
+
- **File Paths**: Linux uses Unix-style paths with forward slashes (/)
|
|
106
|
+
- **Home Directory**: The tilde (~) expands to /home/[username]
|
|
107
|
+
- **Case Sensitivity**: Linux file systems are case-sensitive (File.txt and file.txt are different files)`:s},$g="copilot_conclusion_with_options_enhancement_enabled",pi=()=>localStorage.getItem($g)==="true",xw=e=>{try{localStorage.setItem($g,e.toString())}catch(t){console.error("[copilotConclusionWithOptionsEnhancement] Failed to persist setting:",t)}},bw=()=>"\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",vw=()=>["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(" "),Fg="bamboo_system_prompt_enhancement",Sw=()=>["## Bamboo Operational Guidance","","- For recurring or delayed tasks, use the `schedule_tasks` tool to create and manage schedule jobs instead of only describing manual steps.","- The `schedule_tasks` tool supports: `list`, `create`, `patch`, `delete`, `run_now`, and `list_sessions`.","- Bamboo configuration is stored in `${BAMBOO_DATA_DIR}/config.json`.","- Default config path: `~/.bamboo/config.json` (macOS/Linux) or `%USERPROFILE%\\\\.bamboo\\\\config.json` (Windows)."].join(`
|
|
108
|
+
`),ww=e=>e.map(s=>s.trim()).filter(s=>s.length>0).join(`
|
|
109
|
+
|
|
110
|
+
`),Lg=()=>{try{return localStorage.getItem(Fg)??""}catch(e){return console.error("Failed to load system prompt enhancement:",e),""}},_w=e=>{try{const t=e.trim()?e:"";localStorage.setItem(Fg,t)}catch(t){console.error("Failed to save system prompt enhancement:",t)}},Tw=e=>{const t=[];t.push(yw().trim()),t.push(Sw().trim());const s=Lg().trim();return s&&t.push(s),yc()&&t.push(mw().trim()),bc()&&t.push(fw().trim()),(e??"").trim().toLowerCase()==="copilot"&&pi()&&t.push(bw().trim()),t},kw=e=>ww(Tw(e)),vc=e=>{const t=(e??"").trim().toLowerCase();return t.includes("completion policy violation")&&t.includes("conclusion_with_options")},Sc=e=>{const t=(e??"").trim(),s=t?`
|
|
111
|
+
|
|
112
|
+
Raw error: ${t}`:"";return["Bamboo stopped this completion because Copilot conclusion_with_options confirmation is enabled for this session.","The assistant tried to finish with plain text instead of calling conclusion_with_options.","Next steps: retry the request, shorten or clarify the prompt, or temporarily disable the Copilot conclusion_with_options enhancement for this session if you do not want enforced confirmation."].join(" ")+s};function Og(e){const{modal:t,message:s}=ts.useApp(),{t:n}=se(),o=m.useRef(null),a=m.useRef(null),i=m.useRef(""),l=m.useRef(new hs),c=z(v=>v.agentAvailability),d=z(v=>v.setAgentAvailability),u=z(v=>v.checkAgentAvailability),h=z(v=>v.startAgentHealthCheck),p=vr(),y=Rt(v=>v.currentProvider),g=z(v=>e.sessionId&&v.chats.find(k=>k.id===e.sessionId)||null);m.useEffect(()=>{h()},[h]);const f=m.useCallback(()=>{var k;(k=o.current)==null||k.abort();const v=g==null?void 0:g.id;v&&l.current.stopGeneration(v).catch(E=>{console.error("[useMessageStreaming] Failed to stop generation:",E)})},[g==null?void 0:g.id]),b=m.useCallback(v=>{var A;const k=z.getState(),M=(Array.isArray(k.chats)?k.chats:[]).find($=>$.id===v),R=k.pendingQuestionRespond,I=(R==null?void 0:R.sessionId)===v?R:null,P=(A=M==null?void 0:M.config)==null?void 0:A.syncCursor,L=!!I||!!(P!=null&&P.hasPendingQuestion),O=(I==null?void 0:I.toolCallId)??(P==null?void 0:P.pendingQuestionToolCallId)??null;return{client_message_count:(P==null?void 0:P.messageCount)??(M==null?void 0:M.messageCount)??0,client_last_message_id:(P==null?void 0:P.lastMessageId)??null,client_has_pending_question:L,client_pending_question_tool_call_id:O}},[]),x=m.useCallback((v,k)=>{const E=k.sync;if(!E)return;const M=z.getState(),I=(Array.isArray(M.chats)?M.chats:[]).find(P=>P.id===v);I&&e.updateSession(v,{messageCount:E.server_message_count,config:{...I.config||{},syncCursor:{messageCount:E.server_message_count,lastMessageId:E.server_last_message_id??null,hasPendingQuestion:E.has_pending_question,pendingQuestionToolCallId:E.pending_question_tool_call_id??null}}})},[e]),S=m.useCallback(async v=>{try{return await Se.get(`respond/${v}/pending`)}catch(k){return console.warn(`[useMessageStreaming] Failed to fetch pending question for ${v}:`,k),{has_pending_question:!1}}},[]),w=m.useCallback(async(v,k,E,M)=>{var A,$;e.setSessionProcessing(v,!1),await z.getState().loadChatHistory(v,{mode:"replace"});const R=await S(v),I=z.getState().setPendingQuestionRespond,P=z.getState().clearPendingQuestionRespondForSession;if(R.has_pending_question){I({sessionId:v,question:R.question||"",options:R.options||[],allowCustom:R.allow_custom??!0,toolCallId:R.tool_call_id??null});const W=z.getState().chats.find(F=>F.id===v);return W&&e.updateSession(v,{config:{...W.config||{},syncCursor:{messageCount:W.messageCount??W.messages.length,lastMessageId:(($=(A=W.config)==null?void 0:A.syncCursor)==null?void 0:$.lastMessageId)??null,hasPendingQuestion:!0,pendingQuestionToolCallId:R.tool_call_id??null}}}),null}if(P(v),!((E==null?void 0:E.has_pending_user_message)??!1))return null;e.setSessionProcessing(v,!0),await new Promise(W=>setTimeout(W,0));const O=M?await l.current.execute(v,k,M,b(v)):await l.current.execute(v,k,void 0,b(v));return x(v,O),O},[x,b,e,S]),C=m.useCallback(async(v,k,E,M)=>{var L,O;let R=k;x(v,R);const I=2;let P=0;for(;(L=R.sync)!=null&&L.need_sync&&P<I;){const A=await w(v,E,R.sync,M);if(P+=1,!A){e.setSessionProcessing(v,!1);return}R=A,x(v,R)}if((O=R.sync)!=null&&O.need_sync){console.warn(`[useMessageStreaming] Execute remains out-of-sync after ${I} recovery attempt(s) for session ${v}.`,R.sync),e.setSessionProcessing(v,!1);return}if(!["started","already_running"].includes(R.status)){if(R.status==="completed"){He("[Streaming]","[Agent] Session already completed"),e.setSessionProcessing(v,!1);return}throw console.error("[Agent] Execute failed:",R.status),e.setSessionProcessing(v,!1),new Error(`Execute failed: ${R.status}`)}},[x,e,w]),_=m.useCallback(async(v,k,E,M,R)=>{var P,L;if(!p)throw new Error(n("chat.model.noModelSelected"));const I=new AbortController;o.current=I;try{const O=kw(y).trim(),A=(y??"").trim().toLowerCase()==="copilot"&&pi(),W=(((P=g==null?void 0:g.config)==null?void 0:P.workspacePath)||"").trim().replace(/\/+$/,"").replace(/\\+$/,""),F=await l.current.sendMessage({message:v,session_id:k,enhance_prompt:O||void 0,copilot_conclusion_with_options_enhancement_enabled:A,workspace_path:W||void 0,selected_skill_ids:R&&R.length>0?R:void 0,images:(L=E.images)==null?void 0:L.filter(U=>!!U.base64).map(U=>({base64:U.base64,name:U.name,size:U.size,type:U.type})),model:p}),{session_id:H}=F;H!==k&&console.warn(`[useMessageStreaming] Backend returned unexpected session_id=${H} for sessionId=${k}`),await z.getState().loadChatHistory(k,{mode:"replace"}),e.setSessionProcessing(k,!0),await new Promise(U=>setTimeout(U,0));const D=M?await l.current.execute(k,p,M,b(k)):await l.current.execute(k,p,void 0,b(k));He("[Streaming]","[Agent] Execute status:",D.status),await C(k,D,p,M)}catch(O){throw O}},[p,b,g,y,e,C,n]),T=m.useCallback(async(v,k,E,M)=>{if(!g){t.info({title:n("chat.streaming.noActiveChatTitle"),content:n("chat.streaming.noActiveChatSendContent")});return}if(!e.sessionId){t.info({title:n("chat.streaming.noChatIdTitle"),content:n("chat.streaming.noChatIdSendContent")});return}if(!p){t.error({title:n("chat.model.noModelSelected"),content:n("chat.model.selectModelBeforeSend")});return}let R=c;if(R===null&&(R=await u()),!R){s.error(n("chat.streaming.agentUnavailable"));return}if(!p){s.error(n("chat.streaming.modelConfigNotLoaded"));return}const I=e.sessionId,P=(k==null?void 0:k.map(O=>({id:O.id,base64:O.base64,name:O.name,size:O.size,type:O.type})))||[],L={role:"user",content:v,id:crypto.randomUUID(),createdAt:new Date().toISOString(),images:P};await e.addMessage(I,L);try{He("[Streaming]","[useChatStreaming] Using Agent Server"),await _(v,I,L,E,M)}catch(O){if(a.current&&Fe.clear(I,a.current),a.current=null,i.current="",O instanceof Error&&O.name==="AbortError")s.info(n("chat.streaming.requestCancelled"));else{console.error("[useChatStreaming] Failed to send message:",O);const A=O instanceof Error?O.message:String(O??"");vc(A)?s.error(Sc(A)):(s.error(n("chat.streaming.sendFailed")),d(!1))}e.setSessionProcessing(I,!1)}finally{o.current=null,a.current&&Fe.clear(I,a.current),a.current=null,i.current=""}},[c,s,u,g,e,t,_,d,p,n]),j=m.useCallback(async(v,k="regenerate")=>{if(!g){t.info({title:n("chat.streaming.noActiveChatTitle"),content:n("chat.streaming.noActiveChatRetryContent")});return}if(!e.sessionId){t.info({title:n("chat.streaming.noChatIdTitle"),content:n("chat.streaming.noChatIdRetryContent")});return}if(!p){t.error({title:n("chat.model.noModelSelected"),content:n("chat.model.selectModelBeforeRetry")});return}let E=c;if(E===null&&(E=await u()),!E){s.error(n("chat.streaming.agentUnavailable"));return}const M=e.sessionId;a.current&&Fe.clear(M,a.current),a.current=null,i.current="";try{const R=k==="error_retry"?"error_retry":"after_last_user",I=await l.current.truncateSessionMessages(M,{mode:R});(k==="regenerate"||(I.messages_removed??0)>0)&&await z.getState().loadChatHistory(M,{mode:"replace"}),e.setSessionProcessing(M,!0);const P=v?await l.current.execute(M,p,v,b(M)):await l.current.execute(M,p,void 0,b(M));await C(M,P,p,v)}catch(R){console.error("[useMessageStreaming] Retry failed:",R);const I=R instanceof Error?R.message:String(R??"");vc(I)?s.error(Sc(I)):s.error(n("chat.streaming.retryFailed")),e.setSessionProcessing(M,!1)}finally{o.current=null}},[p,c,s,b,u,g,e,C,t,n]);return{sendMessage:T,retryLastTurn:j,cancel:f,agentAvailable:c}}function Cw(e,t){const s=m.useMemo(()=>e.baseMessages,[e.baseMessages]),n=m.useCallback(async()=>{var d;if(!e.currentSessionId||!e.currentChat)return;const o=[...e.baseMessages];if(o.length===0)return;const a=o[o.length-1];let i=o;if((a==null?void 0:a.role)==="assistant"){if(!(await e.deleteMessage(e.currentSessionId,a.id)).success)return;i=o.slice(0,-1)}const l=[...i].reverse().find(u=>u.role==="user");if(!l)return;const c="content"in l?l.content:l.displayText;typeof c=="string"&&await((d=t==null?void 0:t.onRetry)==null?void 0:d.call(t,c))},[e,t]);return{currentMessages:s,retryLastMessage:n}}const jw=()=>{const e=lw(),t=Cd(e),s=cw(e),n=Og({sessionId:e.currentSessionId,addMessage:e.addMessage,setSessionProcessing:e.setSessionProcessing,updateSession:e.updateSession}),o=Cw(e,{onRetry:n.sendMessage});return{chats:e.chats,currentSessionId:e.currentSessionId,currentChat:e.currentChat,pinnedChats:e.pinnedChats,unpinnedChats:e.unpinnedChats,chatCount:e.chatCount,currentMessages:o.currentMessages,agentAvailable:n.agentAvailable,titleGenerationState:t.titleGenerationState,autoGenerateTitles:t.autoGenerateTitles,isUpdatingAutoTitlePreference:t.isUpdatingAutoTitlePreference,addMessage:e.addMessage,deleteMessage:e.deleteMessage,selectSession:e.selectSession,deleteSession:e.deleteSession,deleteSessions:e.deleteSessions,pinSession:e.pinSession,unpinSession:e.unpinSession,updateSession:e.updateSession,loadChats:e.loadChats,generateChatTitle:t.generateChatTitle,setAutoGenerateTitlesPreference:t.setAutoGenerateTitlesPreference,createNewChat:s.createNewChat,createChatWithSystemPrompt:s.createChatWithSystemPrompt,toggleChatPin:s.toggleChatPin,updateChatTitle:s.updateChatTitle,deleteEmptyChats:s.deleteEmptyChats,deleteAllUnpinnedChats:s.deleteAllUnpinnedChats,deleteAllChats:s.deleteAllChats,retryLastMessage:o.retryLastMessage,sendMessage:n.sendMessage,cancelMessage:n.cancel}},{Text:Ca}=le,{useToken:Mw}=xe,Pw=({httpProxy:e,httpsProxy:t,onHttpProxyChange:s,onHttpsProxyChange:n,onReload:o,onSave:a,isLoading:i})=>{const{t:l}=se(),{token:c}=Mw(),d=ds(C=>C.proxyAuthStatus),u=ds(C=>C.isLoadingProxyAuthStatus),h=ds(C=>C.loadProxyAuthStatus),p=ds(C=>C.applyProxyAuth),y=ds(C=>C.clearProxyAuth),[g,f]=m.useState({username:"",password:""}),[b,x]=m.useState(!1);m.useEffect(()=>{h()},[]);const S=async()=>{const C=g.username.trim();if(C){x(!0);try{await p({username:C,password:g.password}),f({username:"",password:""})}catch(_){console.error("Failed to apply proxy auth:",_)}finally{x(!1)}}},w=async()=>{x(!0);try{await y()}catch(C){console.error("Failed to clear proxy auth:",C)}finally{x(!1)}};return r.jsx(te,{size:"small",title:r.jsx(Ca,{strong:!0,children:l("settings.networkCard.title")}),className:"lotus-settings-card",children:r.jsxs(q,{direction:"vertical",size:c.marginSM,style:{width:"100%"},children:[r.jsxs(q,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[r.jsx(Ca,{type:"secondary",children:l("settings.networkCard.httpProxy")}),r.jsx(ye,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:C=>s(C.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),r.jsxs(q,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[r.jsx(Ca,{type:"secondary",children:l("settings.networkCard.httpsProxy")}),r.jsx(ye,{style:{width:"100%"},value:t,onChange:C=>n(C.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),r.jsx(te,{size:"small",title:l("settings.networkCard.proxyAuthTitle"),className:"lotus-settings-card",style:{marginTop:c.marginSM},children:d!=null&&d.configured?r.jsxs(q,{direction:"vertical",style:{width:"100%"},children:[r.jsx(Ne,{type:"success",message:l("settings.networkCard.proxyConfiguredForUser",{username:d.username??""}),showIcon:!0}),r.jsx(B,{onClick:w,loading:b||u,danger:!0,children:l("settings.networkCard.clearCredentials")})]}):r.jsxs(q,{direction:"vertical",size:c.marginXS,style:{width:"100%"},children:[r.jsx(ye,{placeholder:l("settings.networkCard.username"),value:g.username,onChange:C=>f(_=>({..._,username:C.target.value}))}),r.jsx(ye.Password,{placeholder:l("settings.networkCard.password"),value:g.password,onChange:C=>f(_=>({..._,password:C.target.value}))}),r.jsx(B,{type:"primary",onClick:S,loading:b||u,disabled:!g.username.trim(),children:l("settings.networkCard.apply")})]})}),r.jsx(Ca,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("settings.networkCard.credentialsStorageNote")}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:c.marginSM},children:[r.jsx(B,{onClick:()=>Promise.resolve(o()).finally(()=>h({force:!0})),disabled:i,children:l("settings.networkCard.reload")}),r.jsx(B,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(a()).finally(()=>h({force:!0})),disabled:i,children:l("settings.networkCard.save")})]})]})})},{Text:Nt}=le,{useToken:Ew}=xe,Rw=5*60*1e3,Aw=()=>{const{t:e}=se(),{token:t}=Ew(),[s,n]=m.useState({}),[o,a]=m.useState([]),[i,l]=m.useState(!1),[c,d]=m.useState(""),[u,h]=m.useState(null),[p,y]=pe.useMessage(),[g,f]=m.useState({}),[b,x]=m.useState(!1),[S,w]=m.useState(""),[C,_]=m.useState("");m.useEffect(()=>{(async()=>{try{const L=await bt.getProviderConfig();d(L.provider||"copilot")}catch(L){console.error("Failed to load provider config:",L),h(e("settings.modelMappingCard.loadProviderFailed"))}})()},[e]),m.useEffect(()=>{const L=setInterval(async()=>{try{const A=(await bt.getProviderConfig()).provider||"copilot";A!==c&&c!==""&&(He("[ModelMapping]",`Provider changed from ${c} to ${A}`),d(A),h(null))}catch(O){console.error("Failed to check provider change:",O)}},1e4);return()=>clearInterval(L)},[c]),m.useEffect(()=>{(async()=>{try{const L=await Ye.getAnthropicModelMapping();n(L.mappings||{})}catch(L){console.error("Failed to load model mappings:",L),p.error(e("settings.modelMappingCard.loadMappingsFailed"))}})()},[p,e]);const T=m.useCallback(async(P=!1)=>{if(c){if(!P&&g[c]){const L=g[c];if(Date.now()-L.timestamp<Rw){He("[ModelMapping]",`Using cached models for ${c}`),a(L.models),h(null);return}}l(!0),h(null);try{let L;if(c==="copilot"){const{modelService:O}=await kt(async()=>{const{modelService:A}=await Promise.resolve().then(()=>Ob);return{modelService:A}},void 0,import.meta.url);L=await O.getModels()}else L=await bt.fetchProviderModels(c);a(L),f(O=>({...O,[c]:{models:L,timestamp:Date.now()}})),He("[ModelMapping]",`Fetched ${L.length} models for ${c}`)}catch(L){console.error("Failed to fetch models:",L);const O=L instanceof Error?L.message:e("settings.modelMappingCard.loadModelsFailed");h(O),p.error(e("settings.modelMappingCard.loadModelsHint")),a([])}finally{l(!1)}}},[c,g,p,e]);m.useEffect(()=>{c&&T()},[c,T]);const j=async(P,L)=>{if(L==="__custom__"){w(P),_(""),x(!0);return}if(!L)return;const O={...s,[P]:L};n(O);try{await Ye.setAnthropicModelMapping({mappings:O}),p.success(e("settings.modelMappingCard.mappingSaved"))}catch(A){console.error("Failed to save model mapping:",A),p.error(e("settings.modelMappingCard.mappingSaveFailed"))}},v=async()=>{if(!C.trim()){p.warning(e("settings.modelMappingCard.enterModelName"));return}const P={...s,[S]:C.trim()};n(P);try{await Ye.setAnthropicModelMapping({mappings:P}),p.success(e("settings.modelMappingCard.customMappingSaved")),x(!1),_("")}catch(L){console.error("Failed to save custom model mapping:",L),p.error(e("settings.modelMappingCard.customMappingSaveFailed"))}},k=()=>{T(!0)},E=P=>{const L=s[P];return L?o.includes(L):!0},M=[{key:"opus",label:e("settings.modelMappingCard.modelTypeOpus"),description:e("settings.modelMappingCard.modelTypeOpusDescription")},{key:"sonnet",label:e("settings.modelMappingCard.modelTypeSonnet"),description:e("settings.modelMappingCard.modelTypeSonnetDescription")},{key:"haiku",label:e("settings.modelMappingCard.modelTypeHaiku"),description:e("settings.modelMappingCard.modelTypeHaikuDescription")}],R=c.charAt(0).toUpperCase()+c.slice(1),I=[{key:"1",label:e("settings.modelMappingCard.collapseTitle"),children:r.jsxs(q,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(Nt,{type:"secondary",children:e("settings.modelMappingCard.description",{provider:R})}),u&&r.jsx(Ne,{type:"error",message:e("settings.modelMappingCard.loadModelsErrorTitle"),description:u,showIcon:!0,action:r.jsx(B,{size:"small",icon:r.jsx(Cs,{}),onClick:k,loading:i,children:e("settings.modelMappingCard.retry")})}),i&&!u&&r.jsx("div",{style:{textAlign:"center",padding:t.paddingMD},children:r.jsx(ct,{tip:e("settings.modelMappingCard.loadingModels")})}),!i&&!u&&M.map(({key:P,label:L,description:O})=>{const A=E(P),$=s[P];return r.jsxs(q,{direction:"vertical",size:t.marginXXS,style:{width:"100%"},children:[r.jsxs(Nt,{type:"secondary",children:[L," (",O,")"]}),r.jsx(Oe,{style:{width:"100%"},value:$||void 0,onChange:W=>j(P,W),placeholder:e("settings.modelMappingCard.selectModelPlaceholder",{label:L}),loading:i,disabled:i||o.length===0,showSearch:!0,allowClear:!0,optionFilterProp:"children",options:[...o.map(W=>({label:W,value:W})),{label:r.jsxs("span",{children:[r.jsx(pr,{style:{marginRight:6}}),e("settings.modelMappingCard.customModelOption")]}),value:"__custom__"}],status:A?void 0:"warning",filterOption:(W,F)=>((F==null?void 0:F.label)??"").toString().toLowerCase().includes(W.toLowerCase())}),!A&&$&&r.jsx(Nt,{type:"warning",style:{fontSize:t.fontSizeSM},children:e("settings.modelMappingCard.mappedModelNotFound",{model:$})})]},P)}),r.jsx(Dt,{style:{margin:`${t.marginSM} 0`}}),r.jsx(q,{style:{width:"100%",justifyContent:"flex-end"},children:r.jsx(B,{size:"small",icon:r.jsx(Cs,{}),onClick:k,loading:i,disabled:!c,children:e("settings.modelMappingCard.refreshModels")})}),r.jsxs(q,{direction:"vertical",size:t.marginXXS,style:{width:"100%"},children:[r.jsxs(Nt,{type:"secondary",style:{fontSize:t.fontSizeSM},children:[e("settings.modelMappingCard.currentProvider"),":"," ",r.jsx(Nt,{strong:!0,children:c||e("settings.modelMappingCard.loadingProvider")})]}),r.jsxs(Nt,{type:"secondary",style:{fontSize:t.fontSizeSM},children:[e("settings.modelMappingCard.availableModels"),":"," ",r.jsx(Nt,{strong:!0,children:o.length}),g[c]&&r.jsx(Nt,{type:"secondary",style:{marginLeft:t.marginXXS},children:e("settings.modelMappingCard.cached")})]}),r.jsxs(Nt,{type:"secondary",style:{fontSize:t.fontSizeSM},children:[e("settings.modelMappingCard.storedIn"),":"," ",r.jsx(Nt,{code:!0,children:"~/.bamboo/anthropic-model-mapping.json"})]})]})]})}];return r.jsxs(r.Fragment,{children:[y,r.jsx(js,{size:"small",items:I,className:"lotus-settings-card",style:{marginBottom:t.marginSM}}),r.jsx(Et,{title:e("settings.modelMappingCard.customModalTitle"),open:b,onOk:v,onCancel:()=>{x(!1),_("")},okText:e("settings.modelMappingCard.save"),cancelText:e("settings.modelMappingCard.cancel"),children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},children:[r.jsx(Nt,{type:"secondary",children:e("settings.modelMappingCard.customModalDescription",{modelType:S})}),r.jsx(ye,{placeholder:e("settings.modelMappingCard.customModalPlaceholder"),value:C,onChange:P=>_(P.target.value),onPressEnter:v,autoFocus:!0}),r.jsx(Nt,{type:"secondary",style:{fontSize:t.fontSizeSM},children:e("settings.modelMappingCard.customModalNote")})]})})]})},{Text:Xn}=le,{useToken:Iw}=xe,Yu="http://127.0.0.1:9562/v1",Oo=e=>[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort(),$w=e=>{var s;const t=(s=e.tools)==null?void 0:s.disabled;return Array.isArray(t)?Oo(t.filter(n=>typeof n=="string")):[]},Fw=({msgApi:e,locale:t,onLocaleChange:s})=>{const{t:n}=se(),{token:o}=Iw(),[a,i]=m.useState({http_proxy:"",https_proxy:""}),[l,c]=m.useState(Yu),[d,u]=m.useState([]),[h,p]=m.useState([]),[y,g]=m.useState([]),[f,b]=m.useState(!1),[x,S]=m.useState(!1),w=m.useCallback(async()=>{b(!0);try{const[P,L]=await Promise.all([Ye.getBambooConfig(),Ye.getBambooTools()]);i({http_proxy:P.http_proxy||"",https_proxy:P.https_proxy||""});const O=$w(P);p(O),g(O),u(Oo(L.tools||[]))}catch(P){console.error("Failed to load config:",P),e.error(n("settings.configTab.loadConfigFailed"))}finally{b(!1)}},[e,n]);m.useEffect(()=>{w()},[w]);const C=P=>{i(L=>({...L,http_proxy:P}))},_=P=>{i(L=>({...L,https_proxy:P}))},T=async()=>{var P,L;b(!0);try{const O=await Ye.validateBambooConfigPatch(a);if(!O.valid){const $=((L=(P=O.errors)==null?void 0:P.proxy)==null?void 0:L[0])??Object.values(O.errors||{}).flat().filter(Boolean)[0];e.error(($==null?void 0:$.message)||n("settings.configTab.invalidConfig"));return}await Ye.setBambooConfig(a),e.success(n("settings.configTab.saveConfigSuccess"))}catch(O){console.error("Failed to save config:",O);const A=O instanceof Error&&O.message.trim()?O.message:n("settings.configTab.saveConfigFailed");e.error(A)}finally{b(!1)}},j=async()=>{e.success(n("settings.configTab.backendSaved"))},v=()=>{c(Yu),e.success(n("settings.configTab.backendResetDefault"))},k=(P,L)=>{p(O=>{const A=new Set(O);return L?A.delete(P):A.add(P),Oo([...A])})},E=async()=>{S(!0);try{const P=await Ye.getBambooTools();u(Oo(P.tools||[])),e.success(n("settings.configTab.toolsReloadSuccess"))}catch(P){console.error("Failed to reload tools:",P),e.error(n("settings.configTab.toolsLoadFailed"))}finally{S(!1)}},M=async()=>{S(!0);try{const P=Oo(h);await Ye.setBambooConfig({tools:{disabled:P}}),p(P),g(P),e.success(n("settings.configTab.toolsSaveSuccess"))}catch(P){console.error("Failed to save tool settings:",P),e.error(n("settings.configTab.toolsSaveFailed"))}finally{S(!1)}},R=JSON.stringify(h)!==JSON.stringify(y),I=new Set(h);return r.jsx(ct,{spinning:f,tip:n("settings.common.loading"),children:r.jsx(ei,{items:[{key:"general",label:n("settings.configTab.tabs.general"),children:r.jsxs(q,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(Ne,{message:n("settings.configTab.providerMovedTitle"),description:n("settings.configTab.providerMovedDescription"),type:"info",showIcon:!0,closable:!0}),r.jsx(Pw,{httpProxy:a.http_proxy,httpsProxy:a.https_proxy,onHttpProxyChange:C,onHttpsProxyChange:_,onReload:w,onSave:T,isLoading:f}),r.jsx(Aw,{}),r.jsx(te,{size:"small",className:"lotus-settings-card",title:r.jsx(Xn,{strong:!0,children:n("settings.configTab.language")}),children:r.jsx(Oe,{value:t,style:{width:260},options:[{label:n("settings.configTab.languageEnglish"),value:"en-US"},{label:n("settings.configTab.languageChinese"),value:"zh-CN"},{label:n("settings.configTab.languageTraditionalChinese"),value:"zh-TW"},{label:n("settings.configTab.languageFrench"),value:"fr-FR"},{label:n("settings.configTab.languageJapanese"),value:"ja-JP"},{label:n("settings.configTab.languageHindi"),value:"hi-IN"}],onChange:P=>s(P)})}),r.jsx(te,{size:"small",title:r.jsx(Xn,{strong:!0,children:n("settings.configTab.backendApiBaseUrlTitle")}),children:r.jsxs(q,{direction:"vertical",size:o.marginSM,style:{width:"100%"},children:[r.jsx(q,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:r.jsx(ye,{style:{width:"100%"},value:l,onChange:P=>c(P.target.value),placeholder:n("settings.configTab.backendApiPlaceholder")})}),r.jsx(Xn,{type:"secondary",style:{fontSize:o.fontSizeSM},children:n("settings.configTab.backendApiHint")}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:o.marginSM},children:[r.jsx(B,{"data-testid":"reset-to-defaults",onClick:v,children:n("settings.configTab.resetToDefault")}),r.jsx(B,{"data-testid":"save-api-settings",type:"primary",onClick:j,children:n("settings.configTab.save")})]})]})})]})},{key:"tools",label:n("settings.configTab.tabs.tools"),children:r.jsx(te,{size:"small",title:r.jsx(Xn,{strong:!0,children:n("settings.configTab.toolsTitle")}),children:r.jsxs(q,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(Xn,{type:"secondary",children:n("settings.configTab.toolsDescription")}),d.length===0?r.jsx(Ne,{type:"info",showIcon:!0,message:n("settings.configTab.toolsEmpty")}):r.jsx(Ge,{bordered:!0,dataSource:d,renderItem:P=>r.jsx(Ge.Item,{actions:[r.jsx(ot,{checked:!I.has(P),onChange:L=>k(P,L)},`${P}-switch`)],children:r.jsx(Xn,{code:!0,children:P})})}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:o.marginSM},children:[r.jsx(B,{onClick:E,loading:x,children:n("settings.configTab.reloadTools")}),r.jsx(B,{type:"primary",onClick:M,loading:x,disabled:!R,children:n("settings.configTab.save")})]})]})})}]})})},Xu={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},Md=un()(Sb(e=>({settings:Xu,updateSettings:t=>e(s=>({settings:{...s.settings,...t}})),resetSettings:()=>e({settings:Xu})}),{name:"mermaid-settings"})),zi=()=>Md(t=>t.settings),Lw=()=>Md(e=>e.updateSettings),Ow=()=>Md(e=>e.resetSettings),{Title:Dw,Text:hl}=le,{useToken:zw}=xe,Nw=()=>{const{t:e}=se(),{token:t}=zw(),s=zi(),n=Lw(),o=Ow(),[a]=ee.useForm();dt.useEffect(()=>{a.setFieldsValue(s)},[s,a]);const i=c=>{n(c)},l=()=>{o(),a.resetFields()};return r.jsxs("div",{style:{padding:"24px",maxWidth:"1200px",margin:"0 auto"},children:[r.jsx(Dw,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),r.jsx(hl,{type:"secondary",style:{display:"block",marginBottom:"24px"},children:e("settings.mermaidTab.description")}),r.jsxs(ee,{form:a,layout:"vertical",initialValues:s,onValuesChange:i,children:[r.jsxs(te,{title:e("settings.mermaidTab.themeCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[r.jsx(zs,{gutter:16,children:r.jsx(Qe,{span:24,children:r.jsx(ee.Item,{name:"theme",label:r.jsxs(q,{children:[e("settings.mermaidTab.themeLabel"),r.jsx(je,{title:e("settings.mermaidTab.themeTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsxs(Oe,{children:[r.jsx(Oe.Option,{value:"default",children:e("settings.mermaidTab.themeOptions.default")}),r.jsx(Oe.Option,{value:"neutral",children:e("settings.mermaidTab.themeOptions.neutral")}),r.jsx(Oe.Option,{value:"dark",children:e("settings.mermaidTab.themeOptions.dark")}),r.jsx(Oe.Option,{value:"forest",children:e("settings.mermaidTab.themeOptions.forest")}),r.jsx(Oe.Option,{value:"base",children:e("settings.mermaidTab.themeOptions.base")})]})})})}),r.jsxs(hl,{type:"secondary",style:{display:"block",marginTop:"8px"},children:[r.jsx("strong",{children:e("settings.mermaidTab.themeDescriptionsTitle")}),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.default"),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.neutral"),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.dark"),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.forest"),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.base")]})]}),r.jsxs(te,{title:e("settings.mermaidTab.globalCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[r.jsxs(zs,{gutter:16,children:[r.jsx(Qe,{span:12,children:r.jsx(ee.Item,{name:"fontSize",label:r.jsxs(q,{children:[e("settings.mermaidTab.fontSizeLabel"),r.jsx(je,{title:e("settings.mermaidTab.fontSizeTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(Tt,{min:10,max:32,step:1,style:{width:"100%"},addonAfter:"px"})})}),r.jsx(Qe,{span:12,children:r.jsx(ee.Item,{name:"defaultScale",label:r.jsxs(q,{children:[e("settings.mermaidTab.defaultZoomLabel"),r.jsx(je,{title:e("settings.mermaidTab.defaultZoomTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(Tt,{min:.1,max:3,step:.1,style:{width:"100%"}})})})]}),r.jsx(ee.Item,{name:"useMaxWidth",label:r.jsxs(q,{children:[e("settings.mermaidTab.responsiveWidthLabel"),r.jsx(je,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),valuePropName:"checked",children:r.jsx(ot,{})})]}),r.jsx(te,{title:e("settings.mermaidTab.flowchartCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(zs,{gutter:16,children:[r.jsx(Qe,{span:8,children:r.jsx(ee.Item,{name:"flowchartNodeSpacing",label:r.jsxs(q,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),r.jsx(je,{title:e("settings.mermaidTab.flowchartNodeSpacingTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(Tt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Qe,{span:8,children:r.jsx(ee.Item,{name:"flowchartRankSpacing",label:r.jsxs(q,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),r.jsx(je,{title:e("settings.mermaidTab.flowchartRankSpacingTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(Tt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Qe,{span:8,children:r.jsx(ee.Item,{name:"flowchartCurve",label:r.jsxs(q,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),r.jsx(je,{title:e("settings.mermaidTab.flowchartCurveTypeTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsxs(Oe,{children:[r.jsx(Oe.Option,{value:"basis",children:e("settings.mermaidTab.flowchartCurveOptions.basis")}),r.jsx(Oe.Option,{value:"linear",children:e("settings.mermaidTab.flowchartCurveOptions.linear")}),r.jsx(Oe.Option,{value:"cardinal",children:e("settings.mermaidTab.flowchartCurveOptions.cardinal")})]})})})]})}),r.jsx(te,{title:e("settings.mermaidTab.sequenceCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(zs,{gutter:16,children:[r.jsx(Qe,{span:6,children:r.jsx(ee.Item,{name:"sequenceActorMargin",label:r.jsxs(q,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),r.jsx(je,{title:e("settings.mermaidTab.sequenceActorMarginTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(Tt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Qe,{span:6,children:r.jsx(ee.Item,{name:"sequenceMessageMargin",label:r.jsxs(q,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),r.jsx(je,{title:e("settings.mermaidTab.sequenceMessageMarginTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(Tt,{min:10,max:100,step:5,style:{width:"100%"}})})}),r.jsx(Qe,{span:6,children:r.jsx(ee.Item,{name:"sequenceWidth",label:r.jsxs(q,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),r.jsx(je,{title:e("settings.mermaidTab.sequenceActorWidthTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(Tt,{min:100,max:300,step:10,style:{width:"100%"}})})}),r.jsx(Qe,{span:6,children:r.jsx(ee.Item,{name:"sequenceHeight",label:r.jsxs(q,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),r.jsx(je,{title:e("settings.mermaidTab.sequenceActorHeightTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(Tt,{min:40,max:150,step:5,style:{width:"100%"}})})})]})}),r.jsx(te,{title:e("settings.mermaidTab.ganttCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(zs,{gutter:16,children:[r.jsx(Qe,{span:12,children:r.jsx(ee.Item,{name:"ganttBarHeight",label:r.jsxs(q,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),r.jsx(je,{title:e("settings.mermaidTab.ganttBarHeightTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(Tt,{min:10,max:50,step:5,style:{width:"100%"},addonAfter:"px"})})}),r.jsx(Qe,{span:12,children:r.jsx(ee.Item,{name:"ganttTopPadding",label:r.jsxs(q,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),r.jsx(je,{title:e("settings.mermaidTab.ganttTopPaddingTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(Tt,{min:20,max:100,step:10,style:{width:"100%"}})})})]})}),r.jsx(q,{children:r.jsx(B,{icon:r.jsx(bx,{}),onClick:l,children:e("settings.mermaidTab.resetToDefaults")})}),r.jsx(Dt,{}),r.jsx(te,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsx(hl,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},Bw=m.lazy(()=>kt(()=>import("./index-DN4T64sQ.js"),__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url)),{Text:fn}=le,{useToken:Ww}=xe,Uw=({promptEnhancement:e,onPromptEnhancementChange:t,mermaidEnhancementEnabled:s,taskEnhancementEnabled:n,showCopilotConclusionWithOptionsEnhancement:o,copilotConclusionWithOptionsEnhancementEnabled:a,onMermaidToggle:i,onTaskToggle:l,onCopilotConclusionWithOptionsToggle:c,onSaveEnhancement:d})=>{const{t:u}=se(),{token:h}=Ww(),p=h.marginLG;return r.jsxs(K,{vertical:!0,gap:p,children:[r.jsx(te,{size:"small",className:"lotus-settings-card",children:r.jsx(m.Suspense,{fallback:r.jsx(ct,{size:"small"}),children:r.jsx(Bw,{})})}),r.jsx(te,{size:"small",className:"lotus-settings-card",children:r.jsxs(q,{direction:"vertical",size:h.marginXS,style:{width:"100%"},children:[r.jsx(fn,{strong:!0,children:u("settings.promptsTab.title")}),r.jsxs(K,{align:"center",gap:h.marginSM,children:[r.jsx(fn,{strong:!0,children:u("settings.promptsTab.mermaidEnhancement")}),r.jsx(ot,{checked:s,onChange:i})]}),r.jsxs(K,{align:"center",gap:h.marginSM,children:[r.jsx(fn,{strong:!0,children:u("settings.promptsTab.taskListRules")}),r.jsx(ot,{checked:n,onChange:l})]}),o&&r.jsxs(q,{direction:"vertical",size:h.marginXXS,style:{width:"100%"},children:[r.jsxs(K,{align:"center",gap:h.marginSM,children:[r.jsx(fn,{strong:!0,children:u("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),r.jsx(ot,{checked:a,onChange:c})]}),r.jsx(fn,{type:"secondary",style:{fontSize:h.fontSizeSM},children:u("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:vw()})})]}),r.jsx(ye.TextArea,{rows:6,placeholder:u("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:y=>t(y.target.value)}),r.jsx(K,{justify:"flex-end",children:r.jsx(B,{type:"primary",onClick:d,children:u("settings.promptsTab.saveEnhancement")})}),r.jsx(fn,{type:"secondary",style:{fontSize:h.fontSizeSM},children:u("settings.promptsTab.description")})]})}),s&&r.jsx(js,{size:"small",items:[{key:"mermaid",label:r.jsx(fn,{strong:!0,children:u("settings.mermaidTab.title")}),children:r.jsx(Nw,{})}]})]})},{Text:Js}=le,{useToken:qw}=xe,Hw=({autoGenerateTitles:e,isUpdatingAutoTitlePreference:t,onAutoTitleToggle:s,themeMode:n,onThemeModeChange:o,onClearLocalStorage:a,onResetApp:i,isResetting:l,darkModeKey:c})=>{const{t:d}=se(),{token:u}=qw();return r.jsx(te,{size:"small",className:"lotus-settings-card",children:r.jsxs(q,{direction:"vertical",size:u.marginSM,style:{width:"100%"},children:[r.jsxs(K,{align:"center",gap:u.marginSM,children:[r.jsx(Js,{strong:!0,children:d("settings.appTab.autoGenerateTitle")}),r.jsx(ot,{checked:e,loading:t,onChange:s})]}),r.jsx(Js,{type:"secondary",style:{fontSize:u.fontSizeSM},children:d("settings.appTab.autoGenerateTitleDesc")}),r.jsxs(K,{align:"center",justify:"space-between",gap:u.marginSM,children:[r.jsx(Js,{strong:!0,children:d("settings.appTab.runningVersion","Running version")}),r.jsxs(Js,{code:!0,"data-testid":"settings-app-version",children:["v",nd]})]}),r.jsx(Js,{type:"secondary",style:{fontSize:u.fontSizeSM},children:d("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),r.jsxs(K,{align:"center",gap:u.marginSM,children:[r.jsx(Js,{strong:!0,children:d("settings.appTab.darkMode")}),r.jsx(ot,{"data-testid":"dark-mode-toggle",checked:n==="dark",onChange:h=>{const p=h?"dark":"light";o(p),localStorage.setItem(c,p)}})]}),r.jsx(ti,{title:d("settings.appTab.clearLocalStorageTitle"),description:d("settings.appTab.clearLocalStorageDescription"),onConfirm:a,okText:d("settings.appTab.confirmClear"),cancelText:d("settings.appTab.cancel"),placement:"top",children:r.jsx(B,{danger:!0,block:!0,icon:r.jsx(cn,{}),children:d("settings.appTab.clearLocalStorageButton")})}),r.jsx(Dt,{style:{margin:`${u.marginSM}px 0`}}),r.jsxs(K,{align:"center",gap:u.marginSM,children:[r.jsx(gr,{style:{color:u.colorError}}),r.jsx(Js,{strong:!0,style:{color:u.colorError},children:d("settings.appTab.dangerZone")})]}),r.jsx(Js,{type:"secondary",style:{fontSize:u.fontSizeSM},children:d("settings.appTab.dangerDescription")}),r.jsx(ti,{title:d("settings.appTab.resetApplicationTitle"),description:r.jsxs("div",{children:[r.jsx("p",{children:d("settings.appTab.resetApplicationIntro")}),r.jsxs("ul",{style:{margin:0,paddingLeft:16},children:[r.jsx("li",{children:d("settings.appTab.resetStepDeleteAllSessions")}),r.jsx("li",{children:d("settings.appTab.resetStepClearStorage")}),r.jsx("li",{children:d("settings.appTab.resetStepResetConfig")}),r.jsx("li",{children:d("settings.appTab.resetStepSetupFlow")}),r.jsx("li",{children:d("settings.appTab.resetStepReload")})]})]}),onConfirm:i,okText:d("settings.appTab.resetConfirm"),cancelText:d("settings.appTab.cancel"),placement:"top",okButtonProps:{danger:!0},children:r.jsx(B,{"data-testid":"reset-to-defaults",danger:!0,block:!0,type:"primary",icon:r.jsx(jp,{}),loading:l,children:d("settings.appTab.resetButton")})})]})})},{Text:gn}=le,{useToken:Yw}=xe,Vu=[{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,}"}],Xw=(e,t,s)=>{if(!t)return{masked:e};if(s==="exact")return{masked:e.split(t).join("[MASKED]")};try{const n=new RegExp(t,"g");return{masked:e.replace(n,"[MASKED]")}}catch(n){return{masked:e,error:n instanceof Error?n.message:Kt.t("settings.keywordMaskingTab.invalidRegexPattern")}}},Vw=()=>{const{t:e}=se(),{token:t}=Yw(),[s,n]=m.useState([]),[o,a]=m.useState(!1),[i,l]=m.useState(null),[c,d]=m.useState(""),[u,h]=m.useState("exact"),[p,y]=m.useState(!0),[g,f]=m.useState(),[b,x]=m.useState("My token is sk-123"),S=m.useCallback(async()=>{try{a(!0);const R=await Pt.getInstance().getKeywordMaskingConfig();n(R.entries)}catch(M){pe.error(e("settings.keywordMaskingTab.loadFailed")),console.error(M)}finally{a(!1)}},[e]);m.useEffect(()=>{S()},[S]);const w=async M=>{try{const R=Pt.getInstance(),I=await R.validateKeywordEntries(M);if(!I.valid&&I.errors){const L=I.errors.map(O=>`Entry ${O.index+1}: ${O.message}`).join("; ");return pe.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${L}`),!1}const P=await R.updateKeywordMaskingConfig(M);return n(P.entries),pe.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch(R){return pe.error(R instanceof Error?R.message:e("settings.keywordMaskingTab.saveFailed")),!1}},C=async()=>{const M={pattern:"",match_type:"exact",enabled:!0},R=[...s,M];n(R),l(R.length-1),d(""),h("exact"),y(!0),f(void 0)},_=M=>{const R=s[M];l(M),d(R.pattern),h(R.match_type),y(R.enabled),f(void 0)},T=async()=>{if(i===null)return;if(!c.trim()){pe.error(e("settings.keywordMaskingTab.patternRequired"));return}const M=[...s];M[i]={pattern:c.trim(),match_type:u,enabled:p},await w(M)&&l(null)},j=()=>{var M;i!==null&&!((M=s[i])!=null&&M.pattern)&&n(s.filter((R,I)=>I!==i)),l(null)},v=async M=>{const R=s.filter((I,P)=>P!==M);await w(R)},k=async(M,R)=>{const I=[...s];I[M]={...I[M],enabled:R},await w(I)},E=Xw(b,c,u);return r.jsx(te,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:r.jsx(B,{"data-testid":"add-keyword",type:"primary",icon:r.jsx(ks,{}),onClick:C,loading:o,children:e("settings.keywordMaskingTab.addKeyword")}),children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:"large",children:[r.jsx(gn,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),r.jsx(Ge,{loading:o,dataSource:s,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(M,R)=>r.jsx(Ge.Item,{style:{backgroundColor:t.colorFillAlter,marginBottom:8,borderRadius:t.borderRadius,padding:12},actions:i===R?[r.jsx(B,{"data-testid":"save-keyword",type:"primary",icon:r.jsx(Ti,{}),onClick:T,"aria-label":e("settings.keywordMaskingTab.save")},"save"),r.jsx(B,{onClick:j,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[r.jsx(B,{icon:r.jsx(pr,{}),onClick:()=>_(R),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),r.jsx(B,{"data-testid":`delete-keyword-${R}`,danger:!0,icon:r.jsx(cn,{}),onClick:()=>v(R),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:r.jsx(K,{vertical:!0,style:{width:"100%"},gap:8,children:i===R?r.jsxs(r.Fragment,{children:[r.jsx(ye,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:c,onChange:I=>d(I.target.value),autoFocus:!0}),r.jsxs(K,{gap:8,align:"center",wrap:"wrap",children:[r.jsx(Oe,{"data-testid":"keyword-examples-select","aria-label":e("settings.keywordMaskingTab.examples"),placeholder:e("settings.keywordMaskingTab.examples"),value:g,onChange:I=>{f(I);const P=Vu.find(L=>L.value===I);P&&(d(P.pattern),h(P.match_type))},options:Vu.map(I=>({value:I.value,label:e(I.labelKey)})),style:{minWidth:220}}),r.jsx(Oe,{value:u,onChange:h,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),r.jsx(ot,{checked:p,onChange:y})]}),r.jsxs(K,{vertical:!0,gap:6,children:[r.jsx(gn,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),r.jsx(ye,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:b,onChange:I=>x(I.target.value)}),r.jsx(gn,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),r.jsx(ye,{readOnly:!0,value:E.masked,status:E.error?"error":void 0}),E.error&&r.jsx(gn,{type:"danger",children:E.error})]})]}):r.jsxs(K,{justify:"space-between",align:"center",children:[r.jsxs(K,{vertical:!0,gap:4,children:[r.jsx(gn,{strong:!0,children:M.pattern||e("settings.keywordMaskingTab.emptyPattern")}),r.jsxs(K,{gap:8,children:[r.jsx(gn,{type:"secondary",style:{fontSize:12},children:M.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!M.enabled&&r.jsx(gn,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),r.jsx(ot,{checked:M.enabled,onChange:I=>k(R,I),size:"small"})]})})})})]})})},{Text:Vn,Paragraph:Kw}=le,Gw=/^[A-Za-z_][A-Za-z0-9_]*$/,Jw=()=>{const{t:e}=se(),[t,s]=m.useState([]),[n,o]=m.useState(!1),[a,i]=m.useState(!1),[l,c]=m.useState(null),[d]=ee.useForm(),u=m.useCallback(async()=>{o(!0);try{const x=await bt.getEnvVars();s(x.entries)}catch{pe.error(e("settings.envVars.fetchError","Failed to load environment variables"))}finally{o(!1)}},[e]);m.useEffect(()=>{u()},[u]);const h=async x=>{var w;const S={name:x.name.trim(),value:x.value,secret:x.secret??!1,description:((w=x.description)==null?void 0:w.trim())||void 0};try{const C=await bt.upsertEnvVar(S);s(C.entries),pe.success(l?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),f()}catch(C){pe.error((C instanceof Error?C.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},p=async x=>{try{const S=await bt.deleteEnvVar(x);s(S.entries),pe.success(e("settings.envVars.deleted","Variable deleted"))}catch(S){pe.error((S instanceof Error?S.message:void 0)||e("settings.envVars.deleteError","Failed to delete variable"))}},y=()=>{c(null),d.resetFields(),d.setFieldsValue({secret:!1}),i(!0)},g=x=>{c(x.name),d.setFieldsValue({name:x.name,value:"",secret:x.secret,description:x.description??""}),i(!0)},f=()=>{i(!1),c(null),d.resetFields()},b=[{title:e("settings.envVars.name","Name"),dataIndex:"name",key:"name",render:x=>r.jsx(Vn,{code:!0,children:x})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(x,S)=>S.secret?r.jsxs(Vn,{type:"secondary",children:[r.jsx(Bd,{style:{marginRight:4}}),S.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):r.jsx(Vn,{children:x||r.jsx(Vn,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(x,S)=>S.secret?r.jsx(fe,{color:"warning",icon:r.jsx(Bd,{}),children:e("settings.envVars.secret","Secret")}):r.jsx(fe,{color:"processing",children:e("settings.envVars.plain","Plain")})},{title:e("settings.envVars.descriptionCol","Description"),dataIndex:"description",key:"description",ellipsis:!0,render:x=>x?r.jsx(Vn,{type:"secondary",children:x}):r.jsx(Vn,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(x,S)=>r.jsxs(q,{size:"small",children:[r.jsx(B,{type:"text",size:"small",icon:r.jsx(pr,{}),onClick:()=>g(S),"aria-label":e("settings.envVars.edit","Edit")}),r.jsx(ti,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>p(S.name),okText:e("settings.envVars.yes","Yes"),cancelText:e("settings.envVars.no","No"),children:r.jsx(B,{type:"text",size:"small",danger:!0,icon:r.jsx(cn,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return r.jsxs("div",{style:{maxWidth:900},children:[r.jsxs(te,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:r.jsx(B,{type:"primary",icon:r.jsx(ks,{}),onClick:y,children:e("settings.envVars.addButton","Add Variable")}),children:[r.jsx(Kw,{type:"secondary",style:{marginBottom:16},children:e("settings.envVars.description","Variables are injected into Bash tool processes. Secret variables are encrypted at rest.")}),r.jsx(dn,{dataSource:t,columns:b,rowKey:"name",size:"small",pagination:!1,loading:n,locale:{emptyText:e("settings.envVars.noVars","No environment variables configured")}})]}),r.jsx(Et,{title:l?e("settings.envVars.editTitle","Edit Variable"):e("settings.envVars.addTitle","Add Environment Variable"),open:a,onCancel:f,onOk:()=>d.submit(),okText:e("settings.envVars.save","Save"),cancelText:e("settings.envVars.cancel","Cancel"),destroyOnClose:!0,children:r.jsxs(ee,{form:d,layout:"vertical",onFinish:h,initialValues:{secret:!1},children:[r.jsx(ee.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:Gw,message:e("settings.envVars.nameInvalid","Must start with a letter or underscore, followed by letters, digits, or underscores")}],children:r.jsx(ye,{placeholder:"GITHUB_TOKEN",disabled:l!==null,autoFocus:l===null})}),r.jsx(ee.Item,{name:"value",label:e("settings.envVars.value","Value"),rules:[{required:l===null,message:e("settings.envVars.valueRequired","Value is required for new variables")}],extra:l?e("settings.envVars.valueEditHint","Leave empty to keep the existing value"):void 0,children:r.jsx(ye.Password,{placeholder:l?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),r.jsx(ee.Item,{name:"secret",label:e("settings.envVars.secret","Secret"),valuePropName:"checked",extra:e("settings.envVars.secretHint","Secret variables are encrypted on disk and masked in the UI"),children:r.jsx(ot,{})}),r.jsx(ee.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:r.jsx(ye,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},En=class En{constructor(){}static getInstance(){return En.instance||(En.instance=new En),En.instance}async listWorkflows(){try{He("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const t=await Te.get("bamboo/workflows"),s=Array.isArray(t)?t:[];return He("[WorkflowManager]","[WorkflowManagerService] Listed workflows:",s),s.map(n=>({name:String(n.name||""),filename:String(n.filename||(n.name||"workflow")+".md"),size:Number(n.size||0),modified_at:typeof n.modified_at=="string"?n.modified_at:void 0,source:"global"}))}catch(t){throw console.error("[WorkflowManagerService] Failed to list workflows:",t),t}}async getWorkflow(t){try{He("[WorkflowManager]","[WorkflowManagerService] Getting workflow: "+t);const s=await Te.get("bamboo/workflows/"+encodeURIComponent(t)),n=s!=null&&s.name?String(s.name):t,o={name:n,filename:String((s==null?void 0:s.filename)||n+".md"),size:Number((s==null?void 0:s.size)||0),modified_at:s==null?void 0:s.modified_at,source:"global"};return He("[WorkflowManager]","[WorkflowManagerService] Got workflow:",s),{name:n,content:String((s==null?void 0:s.content)||""),metadata:o}}catch(s){throw console.error("[WorkflowManagerService] Failed to get workflow "+t+":",s),Cb(s)&&s.status===404?new Error("Workflow '"+t+"' not found"):s instanceof Error&&s.message.includes("404")?new Error("Workflow '"+t+"' not found"):s}}};We(En,"instance");let wc=En;const{Text:pl}=le,{TextArea:Qw}=ye,{useToken:Zw}=xe,e_=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),t_=()=>{const{t:e}=se(),{token:t}=Zw(),[s,n]=pe.useMessage(),[o,a]=m.useState([]),[i,l]=m.useState(!1),[c,d]=m.useState(!1),[u,h]=m.useState(!1),[p,y]=m.useState(null),[g,f]=m.useState(""),[b,x]=m.useState(""),[S,w]=m.useState(!1),C=m.useMemo(()=>wc.getInstance(),[]),_=m.useCallback(async()=>{l(!0);try{const E=await C.listWorkflows();return a(E),E}catch{return s.error(e("settings.workflowsTab.loadFailed")),[]}finally{l(!1)}},[s,e,C]);m.useEffect(()=>{_()},[_]);const T=m.useCallback(async E=>{y(E),f(E.name),w(!1),d(!0);try{const M=await C.getWorkflow(E.name);x(M.content??"")}catch{s.error(e("settings.workflowsTab.loadContentFailed")),x("")}finally{d(!1)}},[s,e,C]),j=()=>{y(null),f(""),x(""),w(!1)},v=m.useCallback(async()=>{if(!e_(g)){s.error(e("settings.workflowsTab.invalidName"));return}const E=o.some(M=>M.name===g);if(!p&&E){s.error(e("settings.workflowsTab.nameAlreadyExists"));return}h(!0);try{await Pt.getInstance().saveWorkflow(g,b),s.success(e("settings.workflowsTab.saved")),w(!1);const I=(await _()).find(P=>P.name===g);I&&y(I)}catch(M){s.error(M instanceof Error?M.message:e("settings.workflowsTab.saveFailed"))}finally{h(!1)}},[b,g,_,s,p,e,o]),k=m.useCallback(async E=>{try{await Pt.getInstance().deleteWorkflow(E.name),s.success(e("settings.workflowsTab.deleted")),(p==null?void 0:p.name)===E.name&&j(),await _()}catch(M){s.error(M instanceof Error?M.message:e("settings.workflowsTab.deleteFailed"))}},[_,s,p,e]);return r.jsxs("div",{style:{padding:"24px"},children:[n,r.jsxs(te,{title:e("settings.workflowsTab.title"),extra:r.jsxs(q,{children:[r.jsx(B,{icon:r.jsx(Cs,{}),onClick:_,loading:i,children:e("settings.workflowsTab.refresh")}),r.jsx(B,{"data-testid":"create-workflow",icon:r.jsx(ks,{}),onClick:j,children:e("settings.workflowsTab.newWorkflow")}),r.jsx(B,{"data-testid":"save-workflow",type:"primary",icon:r.jsx(Ti,{}),onClick:v,loading:u,disabled:!S,children:e("settings.workflowsTab.save")})]}),children:[r.jsx(pl,{type:"secondary",children:e("settings.workflowsTab.description")}),r.jsxs(K,{gap:t.marginLG,style:{marginTop:t.marginLG},children:[r.jsx("div",{style:{width:320,flexShrink:0},children:r.jsx(Ge,{loading:i,dataSource:o,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:E=>r.jsx(Ge.Item,{style:{cursor:"pointer",backgroundColor:(p==null?void 0:p.name)===E.name?t.colorFillSecondary:"transparent",borderRadius:t.borderRadius,padding:t.paddingSM},onClick:()=>T(E),actions:[r.jsx(B,{"data-testid":`delete-workflow-${E.name}`,type:"text",danger:!0,size:"small",icon:r.jsx(cn,{}),onClick:M=>{M.stopPropagation(),k(E)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:r.jsxs(q,{direction:"vertical",size:0,children:[r.jsxs(pl,{strong:!0,children:["/",E.name]}),r.jsx(pl,{type:"secondary",style:{fontSize:12},children:E.filename})]})})})}),r.jsx("div",{style:{flex:1},children:r.jsxs(q,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(ye,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:g,onChange:E=>{f(E.target.value),w(!0)},disabled:!!p,prefix:r.jsx(pr,{})}),r.jsx(Qw,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:b,onChange:E=>{x(E.target.value),w(!0)},autoSize:{minRows:12},disabled:c})]})})]})]})]})};var me=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))(me||{});const da=6e4,ua=3e4,Qo=2e4,fi=1e4,Ni=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:Qo},request_timeout_ms:da,healthcheck_interval_ms:ua,allowed_tools:[],denied_tools:[]}),s_=()=>({status:"stopped",tool_count:0,restart_count:0}),n_=e=>{switch(typeof e=="string"?e.trim().toLowerCase():""){case me.Connecting:return me.Connecting;case me.Ready:return me.Ready;case me.Degraded:return me.Degraded;case me.Error:return me.Error;case me.Stopped:default:return me.Stopped}},Ns=(e,t)=>{if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Number(e);if(Number.isFinite(s))return s}return t},r_=(e,t)=>{if(!e||typeof e!="object")return t;const s=e;if(s.type==="sse"){const a=Array.isArray(s.headers)?s.headers.map(i=>{if(!i||typeof i!="object")return null;const l=i;return typeof l.name!="string"||typeof l.value!="string"?null:{name:l.name,value:l.value}}).filter(i=>!!i):[];return{type:"sse",url:typeof s.url=="string"?s.url:"",headers:a,connect_timeout_ms:Ns(s.connect_timeout_ms,fi)}}const n=Array.isArray(s.args)?s.args.filter(a=>typeof a=="string"):[],o=s.env&&typeof s.env=="object"?Object.entries(s.env):[];return{type:"stdio",command:typeof s.command=="string"?s.command:"",args:n,cwd:typeof s.cwd=="string"?s.cwd:void 0,env:o.reduce((a,[i,l])=>(typeof l=="string"&&(a[i]=l),a),{}),startup_timeout_ms:Ns(s.startup_timeout_ms,Qo)}},o_=(e,t)=>{const s=Ni(e.id),n=t??{};return{...s,...n,id:e.id,name:typeof n.name=="string"?n.name:typeof e.name=="string"?e.name:void 0,enabled:typeof e.enabled=="boolean"?e.enabled:typeof n.enabled=="boolean"?n.enabled:!0,request_timeout_ms:Ns(n.request_timeout_ms,da),healthcheck_interval_ms:Ns(n.healthcheck_interval_ms,ua),allowed_tools:Array.isArray(n.allowed_tools)?n.allowed_tools.filter(a=>typeof a=="string"):[],denied_tools:Array.isArray(n.denied_tools)?n.denied_tools.filter(a=>typeof a=="string"):[],reconnect:n.reconnect&&typeof n.reconnect=="object"?{enabled:typeof n.reconnect.enabled=="boolean"?n.reconnect.enabled:!0,initial_backoff_ms:Ns(n.reconnect.initial_backoff_ms,1e3),max_backoff_ms:Ns(n.reconnect.max_backoff_ms,3e4),max_attempts:Ns(n.reconnect.max_attempts,0)}:void 0,transport:r_(n.transport,s.transport)}},a_=e=>{const t=s_(),n=e.runtime??{},o=n.status??e.status;return{status:n_(o),last_error:typeof n.last_error=="string"?n.last_error:typeof e.last_error=="string"?e.last_error:void 0,connected_at:typeof n.connected_at=="string"?n.connected_at:void 0,disconnected_at:typeof n.disconnected_at=="string"?n.disconnected_at:void 0,tool_count:Ns(n.tool_count??e.tool_count,t.tool_count),restart_count:Ns(n.restart_count??e.restart_count,t.restart_count),last_ping_at:typeof n.last_ping_at=="string"?n.last_ping_at:void 0}},i_=e=>{const t=o_(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:a_(e)}},l_=(e,t)=>`mcp__${e}__${t}`,c_=e=>{if(!e.startsWith("mcp__"))return null;const t=e.slice(5),s=t.indexOf("__");if(s<=0)return null;const n=t.slice(0,s),o=t.slice(s+2);return!n||!o?null:{server_id:n,original_name:o}},d_=(e,t,s=0)=>{if(!e||typeof e!="object")return null;const n=e,o=typeof n.alias=="string"?n.alias:typeof n.name=="string"&&n.name.startsWith("mcp__")?n.name:void 0,a=o&&typeof o=="string"?c_(o):null,i=(typeof n.server_id=="string"?n.server_id:void 0)??(typeof n.serverId=="string"?n.serverId:void 0)??(a==null?void 0:a.server_id)??t??"",l=(typeof n.original_name=="string"?n.original_name:void 0)??(typeof n.originalName=="string"?n.originalName:void 0)??(a==null?void 0:a.original_name)??(typeof n.name=="string"?n.name:void 0)??"",c=o??(i&&l?l_(i,l):""),d=typeof n.description=="string"?n.description:"",u=n,h="parameters"in u?u.parameters:"inputSchema"in u?u.inputSchema:"input_schema"in u?u.input_schema:void 0,p=c||l||`mcp_tool_${s}`;return{alias:p,server_id:i||"unknown",original_name:l||p,description:d,parameters:h}};class u_{async getServers(){const t=await Se.get("mcp/servers");return Array.isArray(t.servers)?t.servers.map(i_):[]}async addServer(t){return Se.post("mcp/servers",t)}async updateServer(t,s){const n={...s,id:t};return Se.put(`mcp/servers/${t}`,n)}async deleteServer(t){return Se.delete(`mcp/servers/${t}`)}async connectServer(t){return Se.post(`mcp/servers/${t}/connect`)}async disconnectServer(t){return Se.post(`mcp/servers/${t}/disconnect`)}async refreshTools(t){return Se.post(`mcp/servers/${t}/refresh`)}async getTools(t){const s=t?`mcp/servers/${t}/tools`:"mcp/tools",n=await Se.get(s);return(Array.isArray(n.tools)?n.tools:[]).map((a,i)=>d_(a,t,i)).filter(a=>!!a)}async importServers(t){return Se.post("mcp/servers/import",t)}}const Dg=new u_,m_=5e3,$s=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,Ku=(e,t)=>`${e}:${t}`,h_=(e={})=>{const{service:t=Dg,autoRefreshMs:s=m_,autoRefreshEnabled:n=!0}=e,[o,a]=m.useState([]),[i,l]=m.useState(null),[c,d]=m.useState({}),[u,h]=m.useState({}),[p,y]=m.useState({}),[g,f]=m.useState(!1),[b,x]=m.useState(!1),[S,w]=m.useState(!1),[C,_]=m.useState(null),T=m.useRef({}),j=m.useCallback(D=>{const U=new Set(D.map(Y=>Y.id)),Q=D.map(Y=>{const ve=T.current[Y.id]??Y.config,ue={...ve,id:Y.id,name:ve.name??Y.name};return T.current[Y.id]=ue,{...Y,name:Y.name||ue.name||Y.id,enabled:Y.enabled??ue.enabled,config:ue}});return Object.keys(T.current).forEach(Y=>{U.has(Y)||delete T.current[Y]}),Q},[]),v=m.useCallback(async({silent:D=!1}={})=>{D||f(!0);try{const U=await t.getServers(),Q=j(U);a(Q),l(Y=>{var he;return Y&&Q.some(ve=>ve.id===Y)?Y:((he=Q[0])==null?void 0:he.id)??null}),_(null)}catch(U){throw _($s(U,"Failed to load MCP servers")),U}finally{D||f(!1)}},[j,t]),k=m.useCallback(async(D,U=!1)=>{if(!D)return[];if(!U&&c[D])return c[D];h(Q=>({...Q,[D]:!0}));try{const Q=await t.getTools(D);return d(Y=>({...Y,[D]:Q})),_(null),Q}catch(Q){throw _($s(Q,"Failed to load MCP tools")),Q}finally{h(Q=>({...Q,[D]:!1}))}},[t,c]),E=m.useCallback((D,U,Q)=>{const Y=Ku(D,U);y(he=>({...he,[Y]:Q}))},[]),M=m.useCallback(async D=>{x(!0);try{await t.addServer(D),T.current[D.id]=D,await v()}catch(U){throw _($s(U,"Failed to add MCP server")),U}finally{x(!1)}},[v,t]),R=m.useCallback(async(D,U)=>{x(!0);try{const Q={...U,id:D};await t.updateServer(D,Q),T.current[D]=Q,await v()}catch(Q){throw _($s(Q,"Failed to update MCP server")),Q}finally{x(!1)}},[v,t]),I=m.useCallback(async D=>{E(D,"delete",!0);try{await t.deleteServer(D),d(U=>{const Q={...U};return delete Q[D],Q}),delete T.current[D],await v()}catch(U){throw _($s(U,"Failed to delete MCP server")),U}finally{E(D,"delete",!1)}},[v,t,E]),P=m.useCallback(async D=>{E(D,"connect",!0);try{await t.connectServer(D),await v({silent:!0})}catch(U){throw _($s(U,"Failed to connect MCP server")),U}finally{E(D,"connect",!1)}},[v,t,E]),L=m.useCallback(async D=>{E(D,"disconnect",!0);try{await t.disconnectServer(D),await v({silent:!0})}catch(U){throw _($s(U,"Failed to disconnect MCP server")),U}finally{E(D,"disconnect",!1)}},[v,t,E]),O=m.useCallback(async D=>{E(D,"refresh",!0);try{await t.refreshTools(D),await k(D,!0),await v({silent:!0})}catch(U){throw _($s(U,"Failed to refresh MCP tools")),U}finally{E(D,"refresh",!1)}},[k,v,t,E]),A=m.useCallback(async()=>{w(!0);try{const D=o.map(U=>U.id);await Promise.all(D.map(async U=>{try{await t.refreshTools(U)}catch{}})),await v(),i&&await k(i,!0)}catch(D){throw _($s(D,"Failed to refresh MCP status")),D}finally{w(!1)}},[k,v,i,o,t]),$=m.useCallback(D=>{l(D)},[]),W=m.useCallback((D,U)=>!!p[Ku(D,U)],[p]),F=m.useMemo(()=>i?c[i]??[]:[],[i,c]),H=m.useMemo(()=>i?!!u[i]:!1,[i,u]);return m.useEffect(()=>{v().catch(()=>{})},[v]),m.useEffect(()=>{if(!n||s<=0)return;const D=window.setInterval(()=>{v({silent:!0}).catch(()=>{})},s);return()=>{window.clearInterval(D)}},[n,s,v]),m.useEffect(()=>{i&&k(i).catch(()=>{})},[k,i]),{servers:o,selectedServerId:i,selectedServerTools:F,isLoadingServers:g,isMutatingConfig:b,isRefreshingAll:S,isSelectedServerToolsLoading:H,error:C,setSelectedServerId:$,refreshServers:v,addServer:M,updateServer:R,deleteServer:I,connectServer:P,disconnectServer:L,refreshServerTools:O,refreshAll:A,isServerActionLoading:W}},p_={[me.Connecting]:"blue",[me.Ready]:"green",[me.Degraded]:"orange",[me.Stopped]:"default",[me.Error]:"red"},f_=e=>e===me.Connecting||e===me.Ready||e===me.Degraded,g_=e=>{if(!e)return;const t=e.replace(/\s+/g," ").trim();if(t)return t.length>180?`${t.slice(0,180)}...`:t},y_=({servers:e,loading:t=!1,selectedServerId:s,onSelectServer:n,onEditServer:o,onDeleteServer:a,onConnectServer:i,onDisconnectServer:l,onRefreshTools:c,isServerActionLoading:d})=>{const{t:u}=se(),{token:h}=xe.useToken(),p=m.useMemo(()=>({[me.Connecting]:u("settings.mcpTab.statusHelp.connecting"),[me.Ready]:u("settings.mcpTab.statusHelp.ready"),[me.Degraded]:u("settings.mcpTab.statusHelp.degraded"),[me.Stopped]:u("settings.mcpTab.statusHelp.stopped"),[me.Error]:u("settings.mcpTab.statusHelp.error")}),[u]),y=m.useMemo(()=>[{key:"name",title:u("settings.mcpServerTable.columns.name"),render:(g,f)=>f.name||f.id},{key:"transport",title:u("settings.mcpServerTable.columns.transportType"),render:(g,f)=>f.config.transport.type==="sse"?u("settings.mcpServerTable.transportOptions.sse"):u("settings.mcpServerTable.transportOptions.stdio"),width:140},{key:"status",title:u("settings.mcpServerTable.columns.status"),render:(g,f)=>{var C,_;const b=((C=f.runtime)==null?void 0:C.status)??me.Stopped,x=g_((_=f.runtime)==null?void 0:_.last_error),S=p[b],w={[me.Connecting]:u("settings.mcpTab.status.connecting"),[me.Ready]:u("settings.mcpTab.status.ready"),[me.Degraded]:u("settings.mcpTab.status.degraded"),[me.Stopped]:u("settings.mcpTab.status.stopped"),[me.Error]:u("settings.mcpTab.status.error")};return r.jsx(je,{title:x?`${S} ${u("settings.mcpTab.statusLastError",{error:x})}`:S,children:r.jsx(fe,{color:b===me.Stopped?void 0:p_[b],style:{marginInlineEnd:0,cursor:"help",...b===me.Stopped?{background:h.colorFillSecondary,borderColor:h.colorBorderSecondary,color:h.colorTextSecondary}:void 0},children:w[b]})})},width:120},{key:"toolCount",title:u("settings.mcpServerTable.columns.toolCount"),render:(g,f)=>{var b;return((b=f.runtime)==null?void 0:b.tool_count)??0},width:100},{key:"actions",title:u("settings.mcpServerTable.columns.actions"),width:360,render:(g,f)=>{var S;const b=((S=f.runtime)==null?void 0:S.status)??me.Stopped,x=f_(b);return r.jsxs(q,{size:h.marginXS,children:[r.jsx(B,{size:"small",onClick:w=>{w.stopPropagation(),o==null||o(f)},children:u("settings.mcpServerTable.actions.edit")}),r.jsx(ti,{title:u("settings.mcpServerTable.deleteTitle"),description:u("settings.mcpServerTable.deleteDescription",{name:f.name||f.id}),onConfirm:()=>a==null?void 0:a(f),okText:u("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:d==null?void 0:d(f.id,"delete")},children:r.jsx(B,{size:"small",danger:!0,loading:d==null?void 0:d(f.id,"delete"),onClick:w=>w.stopPropagation(),children:u("settings.mcpServerTable.actions.delete")})}),x?r.jsx(B,{size:"small",onClick:w=>{w.stopPropagation(),l==null||l(f)},loading:d==null?void 0:d(f.id,"disconnect"),children:u("settings.mcpServerTable.actions.disconnect")}):r.jsx(B,{size:"small",type:"primary",ghost:!0,onClick:w=>{w.stopPropagation(),i==null||i(f)},loading:d==null?void 0:d(f.id,"connect"),children:u("settings.mcpServerTable.actions.connect")}),r.jsx(B,{size:"small",onClick:w=>{w.stopPropagation(),c==null||c(f)},loading:d==null?void 0:d(f.id,"refresh"),children:u("settings.mcpServerTable.actions.refreshTools")})]})}}],[d,i,a,l,o,c,p,u,h.colorBorderSecondary,h.colorFillSecondary,h.colorTextSecondary,h.marginXS]);return r.jsx(dn,{rowKey:"id",columns:y,dataSource:e,loading:t,pagination:!1,locale:{emptyText:u("settings.mcpServerTable.empty")},onRow:g=>({onClick:()=>n==null?void 0:n(g.id),style:{cursor:n?"pointer":"default",backgroundColor:s===g.id?h.colorFillSecondary:void 0}})})},{Text:Gu}=le,{TextArea:x_}=ye,Ju=e=>{const t=e??Ni(""),s=t.transport,n=s.type==="stdio"?Object.entries(s.env??{}).map(([a,i])=>({key:a,value:i})):[],o=s.type==="sse"?s.headers.map(a=>({name:a.name,value:a.value})):[];return{id:t.id,name:t.name,enabled:t.enabled,transportType:s.type,command:s.type==="stdio"?s.command:void 0,args:s.type==="stdio"?s.args:[],envEntries:n,url:s.type==="sse"?s.url:void 0,headerEntries:o,requestTimeoutMs:t.request_timeout_ms||da,healthcheckIntervalMs:t.healthcheck_interval_ms||ua,allowedTools:t.allowed_tools||[],deniedTools:t.denied_tools||[]}},b_=e=>e.reduce((t,s)=>{var o;const n=(o=s.key)==null?void 0:o.trim();return n&&(t[n]=s.value??""),t},{}),v_=e=>e.filter(t=>{var s;return(s=t.name)==null?void 0:s.trim()}).map(t=>{var s;return{name:((s=t.name)==null?void 0:s.trim())||"",value:t.value??""}}),Qu=(e,t,s)=>{var u,h,p;const n=t==="edit"&&(s==null?void 0:s.id)||e.id,o=(u=e.name)==null?void 0:u.trim(),a=typeof e.requestTimeoutMs=="number"?e.requestTimeoutMs:(s==null?void 0:s.request_timeout_ms)??da,i=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(s==null?void 0:s.healthcheck_interval_ms)??ua,l=Array.isArray(e.allowedTools)?e.allowedTools:(s==null?void 0:s.allowed_tools)??[],c=Array.isArray(e.deniedTools)?e.deniedTools:(s==null?void 0:s.denied_tools)??[],d=e.transportType==="sse"?{type:"sse",url:((h=e.url)==null?void 0:h.trim())||"",headers:v_(e.headerEntries||[]),connect_timeout_ms:(s==null?void 0:s.transport.type)==="sse"?s.transport.connect_timeout_ms??fi:fi}:{type:"stdio",command:((p=e.command)==null?void 0:p.trim())||"",args:e.args||[],env:b_(e.envEntries||[]),cwd:(s==null?void 0:s.transport.type)==="stdio"?s.transport.cwd:void 0,startup_timeout_ms:(s==null?void 0:s.transport.type)==="stdio"?s.transport.startup_timeout_ms??Qo:Qo};return{id:n,name:o||void 0,enabled:e.enabled,transport:d,request_timeout_ms:a,healthcheck_interval_ms:i,allowed_tools:l,denied_tools:c,reconnect:s==null?void 0:s.reconnect}},Zu=e=>JSON.stringify(e||Ni(""),null,2),fl=(e,t)=>{try{const s=JSON.parse(e);if(!s||typeof s!="object")return{valid:!1,error:t("settings.mcpServerForm.jsonMustBeObject")};const n=s;if(n.mcpServers&&typeof n.mcpServers=="object")return{valid:!1,error:t("settings.mcpServerForm.detectedBulkConfig")};const o=typeof n.id=="string"?n.id:"";if(!o.trim())return{valid:!1,error:t("settings.mcpServerForm.missingIdField")};if(n.transport&&typeof n.transport=="object"){const h=n;return!h.transport||typeof h.transport!="object"?{valid:!1,error:t("settings.mcpServerForm.missingTransportField")}:{valid:!0,config:h}}const a=typeof n.enabled=="boolean"?n.enabled:typeof n.disabled=="boolean"?!n.disabled:!0,i=typeof n.request_timeout_ms=="number"?n.request_timeout_ms:da,l=typeof n.healthcheck_interval_ms=="number"?n.healthcheck_interval_ms:ua,c=Array.isArray(n.allowed_tools)?n.allowed_tools.filter(h=>typeof h=="string"):[],d=Array.isArray(n.denied_tools)?n.denied_tools.filter(h=>typeof h=="string"):[],u=typeof n.name=="string"?n.name:void 0;if(typeof n.url=="string"){const h=n.headers,p=Array.isArray(h)?h.map(g=>{if(!g||typeof g!="object")return null;const f=g,b=typeof f.name=="string"?f.name:"",x=typeof f.value=="string"?f.value:"";return b.trim()?{name:b,value:x}:null}).filter(g=>!!g):h&&typeof h=="object"?Object.entries(h).filter(([g])=>g.trim()).map(([g,f])=>({name:g,value:typeof f=="string"?f:""})):[],y=typeof n.connect_timeout_ms=="number"?n.connect_timeout_ms:fi;return{valid:!0,config:{id:o,name:u,enabled:a,transport:{type:"sse",url:n.url,headers:p,connect_timeout_ms:y},request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:d,reconnect:void 0}}}if(typeof n.command=="string"){const h=Array.isArray(n.args)?n.args.filter(f=>typeof f=="string"):[],p=n.env,y=p&&typeof p=="object"?Object.entries(p).reduce((f,[b,x])=>(typeof x=="string"&&(f[b]=x),f),{}):{},g=typeof n.startup_timeout_ms=="number"?n.startup_timeout_ms:Qo;return{valid:!0,config:{id:o,name:u,enabled:a,transport:{type:"stdio",command:n.command,args:h,cwd:typeof n.cwd=="string"?n.cwd:void 0,env:y,startup_timeout_ms:g},request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:d,reconnect:void 0}}}return{valid:!1,error:t("settings.mcpServerForm.missingTransportInfo")}}catch(s){return{valid:!1,error:t("settings.mcpServerForm.invalidJson",{message:s instanceof Error?s.message:t("settings.mcpServerForm.unknownError")})}}},S_=({open:e,mode:t,initialConfig:s,confirmLoading:n=!1,onCancel:o,onSubmit:a})=>{const{t:i}=se(),[l]=ee.useForm(),[c,d]=m.useState("form"),[u,h]=m.useState(""),[p,y]=m.useState(null),g=m.useMemo(()=>Ju(s),[s]),f=ee.useWatch("transportType",l)??"stdio";m.useEffect(()=>{e&&(l.setFieldsValue(g),h(Zu(s)),y(null),d("form"))},[l,g,s,e]);const b=()=>{l.resetFields(),h(""),y(null),o()},x=async()=>{if(c==="json"){const C=fl(u,i);if(!C.valid){y(C.error);return}y(null);try{await a(C.config),h("")}catch(_){console.error("MCP server JSON submission error:",_)}return}try{const C=await l.validateFields(),_=Qu(C,t,s);await a(_),l.resetFields()}catch(C){console.error("MCP server form submission error:",C)}},S=C=>{h(C),p&&fl(C,i).valid&&y(null)},w=C=>{if(C==="json")try{const _=l.getFieldsValue(),T=Qu(_,t,s);h(JSON.stringify(T,null,2))}catch{h(Zu(s))}else{const _=fl(u,i);_.valid&&l.setFieldsValue(Ju(_.config))}d(C),y(null)};return r.jsxs(Et,{title:i(t==="edit"?"settings.mcpServerForm.editTitle":"settings.mcpServerForm.addTitle"),open:e,onCancel:b,onOk:()=>{x()},okText:i("settings.mcpServerForm.save"),destroyOnClose:!0,confirmLoading:n,width:720,children:[r.jsx("div",{style:{marginBottom:16},children:r.jsxs(Gt.Group,{value:c,onChange:C=>w(C.target.value),optionType:"button",buttonStyle:"solid",children:[r.jsxs(Gt.Button,{value:"form",children:[r.jsx(vx,{})," ",i("settings.mcpServerForm.modeForm")]}),r.jsxs(Gt.Button,{value:"json",children:[r.jsx(ki,{})," ",i("settings.mcpServerForm.modeJson")]})]})}),c==="json"&&p&&r.jsx(Ne,{type:"error",message:i("settings.mcpServerForm.jsonError"),description:p,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>y(null)}),c==="json"?r.jsx(x_,{value:u,onChange:C=>S(C.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(Ni("example-server"),null,2)}):r.jsxs(ee,{layout:"vertical",form:l,preserve:!0,initialValues:g,children:[r.jsx(ee.Item,{name:"id",label:i("settings.mcpServerForm.serverId"),rules:[{required:!0,message:i("settings.mcpServerForm.serverIdRequired")},{pattern:/^[a-zA-Z0-9_-]+$/,message:i("settings.mcpServerForm.serverIdPatternError")}],children:r.jsx(ye,{placeholder:"filesystem",disabled:t==="edit",autoComplete:"off"})}),r.jsx(ee.Item,{name:"name",label:i("settings.mcpServerForm.displayName"),children:r.jsx(ye,{placeholder:"Filesystem MCP",autoComplete:"off"})}),r.jsx(ee.Item,{name:"enabled",label:i("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:i("settings.mcpServerForm.enabledHelp"),children:r.jsx(ot,{})}),r.jsx(ee.Item,{name:"transportType",label:i("settings.mcpServerForm.transportType"),rules:[{required:!0,message:i("settings.mcpServerForm.transportTypeRequired")}],children:r.jsx(Oe,{options:[{label:i("settings.mcpServerForm.transportOptions.stdio"),value:"stdio"},{label:i("settings.mcpServerForm.transportOptions.sse"),value:"sse"}]})}),f==="stdio"?r.jsxs(r.Fragment,{children:[r.jsx(ee.Item,{name:"command",label:i("settings.mcpServerForm.command"),rules:[{required:!0,message:i("settings.mcpServerForm.commandRequired")}],children:r.jsx(ye,{placeholder:"npx",autoComplete:"off"})}),r.jsx(ee.Item,{name:"args",label:i("settings.mcpServerForm.arguments"),children:r.jsx(Oe,{mode:"tags",tokenSeparators:[","],placeholder:i("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),r.jsx(ee.List,{name:"envEntries",children:(C,{add:_,remove:T})=>r.jsxs(q,{direction:"vertical",style:{width:"100%"},children:[r.jsxs(q,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[r.jsx(Gu,{strong:!0,children:i("settings.mcpServerForm.envVars")}),r.jsx(B,{icon:r.jsx(ks,{}),onClick:()=>_({key:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addEnv")})]}),C.map(j=>r.jsxs(q,{align:"baseline",style:{display:"flex"},children:[r.jsx(ee.Item,{...j,name:[j.name,"key"],rules:[{required:!0,message:i("settings.mcpServerForm.keyRequired")}],children:r.jsx(ye,{placeholder:"MCP_ROOT",autoComplete:"off"})}),r.jsx(ee.Item,{...j,name:[j.name,"value"],children:r.jsx(ye,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),r.jsx(B,{danger:!0,type:"text",icon:r.jsx(Kl,{}),onClick:()=>T(j.name),"aria-label":i("settings.mcpServerForm.removeEnv","Remove environment variable")})]},j.key))]})})]}):r.jsxs(r.Fragment,{children:[r.jsx(ee.Item,{name:"url",label:i("settings.mcpServerForm.sseUrl"),rules:[{required:!0,message:i("settings.mcpServerForm.sseUrlRequired")},{validator:async(C,_)=>{if(_)try{new URL(_)}catch{throw new Error(i("settings.mcpServerForm.validUrlRequired"))}}}],children:r.jsx(ye,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),r.jsx(ee.List,{name:"headerEntries",children:(C,{add:_,remove:T})=>r.jsxs(q,{direction:"vertical",style:{width:"100%"},children:[r.jsxs(q,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[r.jsx(Gu,{strong:!0,children:i("settings.mcpServerForm.headers")}),r.jsx(B,{icon:r.jsx(ks,{}),onClick:()=>_({name:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addHeader")})]}),C.map(j=>r.jsxs(q,{align:"baseline",style:{display:"flex"},children:[r.jsx(ee.Item,{...j,name:[j.name,"name"],rules:[{required:!0,message:i("settings.mcpServerForm.headerNameRequired")}],children:r.jsx(ye,{placeholder:"Authorization",autoComplete:"off"})}),r.jsx(ee.Item,{...j,name:[j.name,"value"],children:r.jsx(ye,{placeholder:"Bearer token",autoComplete:"off"})}),r.jsx(B,{danger:!0,type:"text",icon:r.jsx(Kl,{}),onClick:()=>T(j.name),"aria-label":i("settings.mcpServerForm.removeHeader","Remove header")})]},j.key))]})})]})]})]})},w_={maxLines:8,maxCharacters:500},or=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qs=e=>typeof e=="string"?e:void 0,Er=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,em=e=>typeof e=="boolean"?e:void 0,zg=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const s=JSON.parse(t);return or(s)?s:null}catch{return null}},Ng=e=>/\\u[0-9a-fA-F]{4}|\\n|\\t|\\r/.test(e)?e.replace(/\\u([0-9a-fA-F]{4})/g,(t,s)=>String.fromCharCode(parseInt(s,16))).replace(/\\n/g,`
|
|
113
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r"):e,Zo=e=>Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>Ng(t).trim()).filter(Boolean):[],ms=e=>{if(typeof e!="string")return;const t=Ng(e).trim();return t.length>0?t:void 0},__=e=>{if(!or(e))return;const t=ms(e.graph);if(t)return{title:ms(e.title),graph:t}},T_=e=>{if(!or(e))return;const t=ms(e.summary)??ms(e.conclusion);if(t)return{title:ms(e.title)||"Conclusion",summary:t,key_points:Zo(e.key_points),next_steps:Zo(e.next_steps),confidence:ms(e.confidence),mermaid:__(e.mermaid)}},k_=e=>{const t=zg(e);if(!t)return null;const s=ms(t.conclusion);return!s||t.type!=null&&t.type!=="conclusion"?null:{type:"conclusion",title:ms(t.title)||"Conclusion",conclusion:s,key_points:Zo(t.key_points),next_steps:Zo(t.next_steps),confidence:ms(t.confidence)}},C_=e=>{const t=zg(e);if(!t)return null;const s=ms(t.question);if(!s)return null;const n=ms(t.status);return n&&n!=="awaiting_user_input"&&n!=="awaiting_permission_approval"?null:{question:s,options:Zo(t.options),allow_custom:typeof t.allow_custom=="boolean"?t.allow_custom:!0,conclusion:T_(t.conclusion)}},j_=e=>{var s;if(!e)return null;const t=[`## ${e.title}`,e.summary];if(e.confidence&&t.push(`**Confidence:** ${e.confidence}`),e.key_points.length>0&&t.push(["**Key points**",...e.key_points.map(n=>`- ${n}`)].join(`
|
|
114
|
+
`)),e.next_steps.length>0&&t.push(["**Next steps**",...e.next_steps.map((n,o)=>`${o+1}. ${n}`)].join(`
|
|
115
|
+
`)),(s=e.mermaid)!=null&&s.graph){const n=e.mermaid.title?`**${e.mermaid.title}**
|
|
116
|
+
|
|
117
|
+
`:`**Flow**
|
|
118
|
+
|
|
119
|
+
`;t.push(`${n}\`\`\`mermaid
|
|
120
|
+
${e.mermaid.graph}
|
|
121
|
+
\`\`\``)}return t.join(`
|
|
122
|
+
|
|
123
|
+
`)},Bg=e=>{const t=k_(e);if(!t)return null;const s=[`## ${t.title}`,t.conclusion];return t.confidence&&s.push(`**Confidence:** ${t.confidence}`),t.key_points.length>0&&s.push(["**Key points**",...t.key_points.map(n=>`- ${n}`)].join(`
|
|
124
|
+
`)),t.next_steps.length>0&&s.push(["**Next steps**",...t.next_steps.map((n,o)=>`${o+1}. ${n}`)].join(`
|
|
125
|
+
`)),s.join(`
|
|
126
|
+
|
|
127
|
+
`)},ma=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const s=JSON.parse(t);if(!or(s))return null;const n=Qs(s.file_path),o=Qs(s.operation),a=s.diff;if(!n||!o||!or(a))return null;const i=Qs(a.unified);if(!i)return null;const l=s.checkpoint,c=or(l)?{created:em(l.created)??!1,id:Qs(l.id),path:Qs(l.path),size_bytes:Er(l.size_bytes),reason:Qs(l.reason)}:void 0;return{operation:o,message:Qs(s.message),file_path:n,workspace:Qs(s.workspace),checkpoint:c,diff:{unified:i,old_line_count:Er(a.old_line_count),new_line_count:Er(a.new_line_count),added_lines:Er(a.added_lines),removed_lines:Er(a.removed_lines),truncated:em(a.truncated)}}}catch{return null}},_c=e=>e.startsWith("-")&&!e.startsWith("---"),Tc=e=>e.startsWith("+")&&!e.startsWith("+++"),Wg=e=>{const t=e.split(`
|
|
128
|
+
`),s=[];let n=0;for(;n<t.length;){const o=t[n]??"";if(o.startsWith("--- ")||o.startsWith("+++ ")){s.push({kind:"meta",text:o}),n+=1;continue}if(o.startsWith("@@")){s.push({kind:"hunk",text:o}),n+=1;continue}if(_c(o)){const a=[];for(;n<t.length&&_c(t[n]??"");)a.push(t[n]??""),n+=1;const i=[];for(;n<t.length&&Tc(t[n]??"");)i.push(t[n]??""),n+=1;i.length>0?(a.forEach(l=>s.push({kind:"modified_remove",text:l})),i.forEach(l=>s.push({kind:"modified_add",text:l}))):a.forEach(l=>s.push({kind:"remove",text:l}));continue}if(Tc(o)){s.push({kind:"add",text:o}),n+=1;continue}s.push({kind:"context",text:o}),n+=1}return s},M_=e=>{let t=0,s=0;for(const n of e.split(`
|
|
129
|
+
`)){if(Tc(n)){t+=1;continue}_c(n)&&(s+=1)}return{added:t,removed:s}},kc=e=>{const t=ma(e);if(!t)return null;const s=M_(t.diff.unified);return{added:t.diff.added_lines??s.added,removed:t.diff.removed_lines??s.removed}},Cc=e=>{if(typeof e=="string")return e.replace(/\\n/g,`
|
|
130
|
+
`).replace(/\\t/g," ");if(Array.isArray(e))return e.map(Cc);if(e!==null&&typeof e=="object"){const t={};for(const[s,n]of Object.entries(e))t[s]=Cc(n);return t}return e},jc=e=>{if(!e)return{isJson:!1,formattedText:""};const t=e.trim();if(!t)return{isJson:!1,formattedText:""};if(!(t.startsWith("{")&&t.endsWith("}"))&&!(t.startsWith("[")&&t.endsWith("]")))return{isJson:!1,formattedText:e};try{const s=JSON.parse(t);if(s&&typeof s=="object"&&!Array.isArray(s)&&Object.keys(s).length===1){const o=Object.keys(s)[0];if((o==="content"||o==="result"||o==="output")&&typeof s[o]=="string")return{isJson:!1,formattedText:s[o].replace(/\\n/g,`
|
|
131
|
+
`).replace(/\\t/g," "),parsedJson:s}}const n=Cc(s);return{isJson:!0,formattedText:JSON.stringify(n,null,2),parsedJson:n}}catch{return{isJson:!1,formattedText:e}}},P_=(e,t={})=>{const s={...w_,...t};return e?e.split(/\r?\n/).length>s.maxLines?!0:e.length>s.maxCharacters:!1},E_=(e,t=320)=>e?e.length<=t?{preview:e,isTruncated:!1}:{preview:e.substring(0,t).trimEnd()+"…",isTruncated:!0}:{preview:"",isTruncated:!1},R_=e=>{if(!e)return"No content";const t=60,s=e.trim(),n=ma(s);if(n){const o=n.file_path.split(/[\\/]/).pop()||n.file_path,a=`${n.operation}: ${o}`;return a.length<=t?a:a.substring(0,t).trimEnd()+"…"}if(s.length<=t)return s;if(s.startsWith("{")||s.startsWith("["))try{const o=JSON.parse(s);if(typeof o=="object"&&o!==null){if(o.type==="mermaid"&&typeof o.chart=="string"&&o.chart.trim().length>0){const c=`Diagram: ${typeof o.title=="string"&&o.title.trim().length>0?o.title.trim():"Mermaid diagram"}`;return c.length<=t?c:c.substring(0,t).trimEnd()+"…"}if(o.type==="conclusion"&&typeof o.conclusion=="string"&&o.conclusion.trim().length>0){const l=o.conclusion.trim();return l.length<=t?l:l.substring(0,t).trimEnd()+"…"}const a=["content","result","output","message","data"].find(l=>l in o&&typeof o[l]=="string");if(a){const l=o[a];return l.length<=t?l:l.substring(0,t).trimEnd()+"…"}if(Array.isArray(o))return`Array with ${o.length} items`;const i=Object.keys(o);return`Object with ${i.length} propert${i.length===1?"y":"ies"}`}}catch{}return s.substring(0,t).trimEnd()+"…"},Ug=e=>{switch(e){case"success":return"green";case"error":return"red";case"warning":return"orange";default:return"blue"}},ur=(e,t=2)=>{if(typeof e=="string")return e;try{return JSON.stringify(e,null,t)}catch(s){return console.error("[resultFormatters] Failed to stringify value:",s),String(e)}},Va=e=>!!e&&typeof e=="object"&&!Array.isArray(e),yn=(e,t)=>{const s=e[t];return typeof s=="string"?s:void 0},tm=(e,t)=>{const s=e[t];return typeof s=="boolean"?s:void 0},A_=(e,t)=>{const s=e[t];return Array.isArray(s)?s:void 0},Do=e=>{if(!Va(e))return"any";const t=e.type;if(typeof t=="string"){if(t==="array"){const a=e.items;return`array<${Do(a)}>`}return t==="object"?"object":t}if(Array.isArray(t)){const a=t.filter(i=>typeof i=="string").map(i=>i==="array"?"array<any>":i);return a.length>0?a.join(" | "):"any"}const s=Array.isArray(e.oneOf)?e.oneOf:null;if(s)return s.map(Do).join(" | ")||"any";const n=Array.isArray(e.anyOf)?e.anyOf:null;if(n)return n.map(Do).join(" | ")||"any";const o=Array.isArray(e.allOf)?e.allOf:null;return o&&o.map(Do).join(" & ")||"any"},I_=e=>{if(!Va(e))return null;const t=e.properties;if(!Va(t))return{schemaUri:yn(e,"$schema"),title:yn(e,"title"),description:yn(e,"description"),additionalProperties:tm(e,"additionalProperties"),fields:[]};const s=new Set((A_(e,"required")??[]).filter(o=>typeof o=="string").map(o=>o)),n=Object.entries(t).map(([o,a])=>{const i=Va(a)?a:void 0;return{name:o,type:Do(a),required:s.has(o),description:i?yn(i,"description"):void 0,defaultValue:i?i.default:void 0,enumValues:i&&Array.isArray(i.enum)?i.enum:void 0}});return n.sort((o,a)=>o.required!==a.required?o.required?-1:1:o.name.localeCompare(a.name)),{schemaUri:yn(e,"$schema"),title:yn(e,"title"),description:yn(e,"description"),additionalProperties:tm(e,"additionalProperties"),fields:n}},{Text:xs}=le,$_=e=>e===void 0?"":e===null?"null":typeof e=="string"?e:ur(e,0),F_=({schema:e})=>{const{token:t}=xe.useToken(),{t:s}=se(),n=m.useMemo(()=>I_(e),[e]);if(!n)return r.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:ur(e,2)});const o=[{title:s("components.jsonSchema.field"),dataIndex:"name",key:"name",width:180,render:i=>r.jsx(xs,{code:!0,children:i})},{title:s("components.jsonSchema.type"),dataIndex:"type",key:"type",width:140,render:i=>r.jsx(xs,{children:i})},{title:s("components.jsonSchema.required"),dataIndex:"required",key:"required",width:110,render:i=>i?r.jsx(xs,{strong:!0,style:{color:t.colorError},children:s("components.jsonSchema.yes")}):r.jsx(xs,{type:"secondary",children:s("components.jsonSchema.no")})},{title:s("components.jsonSchema.default"),dataIndex:"defaultValue",key:"default",width:160,render:i=>i===void 0?r.jsx(xs,{type:"secondary",children:"-"}):r.jsx(xs,{children:$_(i)})},{title:s("components.jsonSchema.description"),dataIndex:"description",key:"description",render:i=>i?r.jsx(xs,{style:{whiteSpace:"pre-wrap"},children:i}):r.jsx(xs,{type:"secondary",children:"-"})}],a=(n.fields??[]).map(i=>({...i,key:i.name}));return r.jsxs("div",{style:{width:"100%"},children:[r.jsx(Os,{size:"small",column:1,items:[n.schemaUri?{key:"schema",label:"$schema",children:r.jsx(xs,{code:!0,children:n.schemaUri})}:null,typeof n.additionalProperties=="boolean"?{key:"additionalProperties",label:"additionalProperties",children:r.jsx(xs,{children:n.additionalProperties?"true":"false"})}:null].filter(Boolean)}),r.jsx(dn,{size:"small",pagination:!1,columns:o,dataSource:a,locale:{emptyText:s("components.jsonSchema.noProperties")},style:{marginTop:t.marginSM}})]})},{Text:Rr}=le,L_=(e,t)=>`mcp__${e}__${t}`,O_=({server:e,tools:t,loading:s=!1})=>{const{t:n}=se();return r.jsx(te,{title:n("settings.mcpToolList.title"),size:"small",children:e?r.jsx(Ge,{loading:s,dataSource:t,locale:{emptyText:n("settings.mcpToolList.empty")},renderItem:o=>{const a=L_(o.server_id,o.original_name);return r.jsx(Ge.Item,{children:r.jsxs(q,{direction:"vertical",size:2,style:{width:"100%"},children:[r.jsx(Rr,{strong:!0,children:o.original_name}),r.jsx(Rr,{type:"secondary",children:o.description||n("settings.mcpToolList.noDescription")}),r.jsx(Rr,{code:!0,children:o.alias}),r.jsxs(Rr,{type:"secondary",children:[n("settings.mcpToolList.aliasMapping"),": ",r.jsx(Rr,{code:!0,children:a})]}),o.parameters!==void 0&&r.jsx(js,{size:"small",items:[{key:"schema",label:n("settings.mcpToolList.parametersSchema"),children:r.jsx(F_,{schema:o.parameters})}]})]})})}}):r.jsx(Qt,{image:Qt.PRESENTED_IMAGE_SIMPLE,description:n("settings.mcpToolList.selectServerHint")})})},{Text:Ar}=le,{useToken:D_}=xe,{TextArea:z_}=ye,sm={[me.Connecting]:"processing",[me.Ready]:"success",[me.Degraded]:"warning",[me.Stopped]:"default",[me.Error]:"error"},N_=()=>({[me.Connecting]:0,[me.Ready]:0,[me.Degraded]:0,[me.Stopped]:0,[me.Error]:0}),xn=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,B_=e=>{var s,n,o;const t={};for(const a of e){const i=(s=a.id)==null?void 0:s.trim();if(!i)continue;const c=!(a.enabled??a.config.enabled),d=a.config.transport;if(d.type==="sse"){const h={};for(const y of d.headers??[]){const g=(n=y.name)==null?void 0:n.trim();g&&(h[g]=y.value??"")}const p={url:d.url};c&&(p.disabled=!0),Object.keys(h).length&&(p.headers=h),t[i]=p;continue}const u={command:d.command};c&&(u.disabled=!0),(o=d.args)!=null&&o.length&&(u.args=d.args),d.cwd&&(u.cwd=d.cwd),d.env&&Object.keys(d.env).length&&(u.env=d.env),t[i]=u}return{mcpServers:t}},W_=()=>{const{t:e}=se(),{token:t}=D_(),[s,n]=pe.useMessage(),{servers:o,selectedServerId:a,selectedServerTools:i,isLoadingServers:l,isMutatingConfig:c,isRefreshingAll:d,isSelectedServerToolsLoading:u,error:h,setSelectedServerId:p,addServer:y,updateServer:g,deleteServer:f,connectServer:b,disconnectServer:x,refreshServerTools:S,refreshAll:w,isServerActionLoading:C}=h_(),_=m.useMemo(()=>({[me.Connecting]:e("settings.mcpTab.status.connecting"),[me.Ready]:e("settings.mcpTab.status.ready"),[me.Degraded]:e("settings.mcpTab.status.degraded"),[me.Stopped]:e("settings.mcpTab.status.stopped"),[me.Error]:e("settings.mcpTab.status.error")}),[e]),T=m.useMemo(()=>({[me.Connecting]:e("settings.mcpTab.statusHelp.connecting"),[me.Ready]:e("settings.mcpTab.statusHelp.ready"),[me.Degraded]:e("settings.mcpTab.statusHelp.degraded"),[me.Stopped]:e("settings.mcpTab.statusHelp.stopped"),[me.Error]:e("settings.mcpTab.statusHelp.error")}),[e]),[j,v]=m.useState(!1),[k,E]=m.useState("create"),[M,R]=m.useState(null),[I,P]=m.useState(!1),[L,O]=m.useState("merge"),[A,$]=m.useState(""),[W,F]=m.useState(null),[H,D]=m.useState(!1),U=m.useMemo(()=>a?o.find(re=>re.id===a)??null:null,[a,o]),Q=m.useMemo(()=>{const re=N_();let $e=0;return o.forEach(V=>{var oe,ce;const ge=((oe=V.runtime)==null?void 0:oe.status)??me.Stopped;re[ge]+=1,$e+=((ce=V.runtime)==null?void 0:ce.tool_count)??0}),{byStatus:re,totalServers:o.length,totalTools:$e}},[o]),Y={background:t.colorFillSecondary,borderColor:t.colorBorderSecondary,color:t.colorTextSecondary},he=async re=>{try{await f(re.id),s.success(e("settings.mcpTab.serverDeleted"))}catch($e){s.error(xn($e,e("settings.mcpTab.deleteServerFailed")))}},ve=async re=>{try{await b(re.id),s.success(e("settings.mcpTab.connectedTo",{name:re.name||re.id}))}catch($e){s.error(xn($e,e("settings.mcpTab.connectServerFailed")))}},ue=async re=>{try{await x(re.id),s.success(e("settings.mcpTab.disconnected",{name:re.name||re.id}))}catch($e){s.error(xn($e,e("settings.mcpTab.disconnectServerFailed")))}},ie=async re=>{try{await S(re.id),s.success(e("settings.mcpTab.toolsRefreshedFor",{name:re.name||re.id}))}catch($e){s.error(xn($e,e("settings.mcpTab.refreshToolsFailed")))}},Re=async()=>{try{await w(),s.success(e("settings.mcpTab.statusRefreshed"))}catch(re){s.error(xn(re,e("settings.mcpTab.refreshStatusFailed")))}},Le=()=>{R(null),E("create"),v(!0)},Ze=re=>{R(re),E("edit"),v(!0)},et=async re=>{try{if(k==="edit"){if(!M){s.error(e("settings.mcpTab.noServerForEditing"));return}await g(M.id,re),s.success(e("settings.mcpTab.savedServer",{name:M.name||M.id}))}else await y(re),s.success(e("settings.mcpTab.addedServer",{name:re.name||re.id}));v(!1),R(null)}catch($e){s.error(xn($e,e("settings.mcpTab.saveServerFailed")))}},Ct=()=>{P(!0),F(null),O("merge"),$("")},pt=async()=>{const re=B_(o),$e=JSON.stringify(re,null,2);try{await es($e),s.success(e("settings.mcpTab.copiedConfig"))}catch{P(!0),F(null),O("merge"),$($e),s.warning(e("settings.mcpTab.clipboardUnavailable"))}},At=async()=>{var ge;F(null);let re;try{re=JSON.parse(A)}catch(oe){F(`${e("settings.mcpTab.invalidJsonPrefix")}: ${oe instanceof Error?oe.message:e("settings.mcpTab.unknownError")}`);return}if(!re||typeof re!="object"){F(e("settings.mcpTab.jsonMustBeObject"));return}const V=re.mcpServers;if(!V||typeof V!="object"){F(e("settings.mcpTab.missingMcpServers"));return}D(!0);try{const oe=await Dg.importServers({mcpServers:V,mode:L}),ce=((ge=oe.start_errors)==null?void 0:ge.length)??0;s.success(e("settings.mcpTab.importSummary",{count:oe.server_ids.length,added:oe.added,updated:oe.updated,removed:oe.removed,failed:ce})),ce&&s.warning(e("settings.mcpTab.importStartFailures")),P(!1),$(""),await Re()}catch(oe){F(xn(oe,e("settings.mcpTab.importFailed")))}finally{D(!1)}};return r.jsxs(q,{direction:"vertical",size:t.marginMD,style:{width:"100%"},children:[n,h?r.jsx(Ne,{type:"error",showIcon:!0,message:h}):null,r.jsx(te,{size:"small",title:e("settings.mcpTab.overviewTitle"),children:r.jsxs(q,{direction:"vertical",size:t.marginXS,style:{width:"100%"},children:[r.jsx(Ar,{type:"secondary",children:e("settings.mcpTab.overviewDescription")}),r.jsxs(q,{wrap:!0,children:[r.jsx(fe,{style:Y,children:e("settings.mcpTab.totalServers",{count:Q.totalServers})}),r.jsx(fe,{style:Y,children:e("settings.mcpTab.totalTools",{count:Q.totalTools})}),Object.values(me).map(re=>r.jsx(je,{title:T[re],children:r.jsxs(fe,{color:re===me.Stopped?void 0:sm[re],style:{cursor:"help",...re===me.Stopped?Y:void 0},children:[_[re],": ",Q.byStatus[re]]})},re))]}),r.jsx(Ar,{type:"secondary",children:e("settings.mcpTab.statusGuideTitle")}),r.jsx(q,{direction:"vertical",size:2,style:{width:"100%"},children:Object.values(me).map(re=>r.jsxs(Ar,{type:"secondary",children:[r.jsx(fe,{color:re===me.Stopped?void 0:sm[re],style:{marginInlineEnd:8,...re===me.Stopped?Y:void 0},children:_[re]}),T[re]]},`guide-${re}`))})]})}),r.jsx(te,{size:"small",title:e("settings.mcpTab.serversTitle"),extra:r.jsxs(q,{children:[r.jsx(B,{type:"primary",onClick:Le,children:e("settings.mcpTab.addServer")}),r.jsx(B,{icon:r.jsx(Cs,{}),loading:d,onClick:()=>{Re()},children:e("settings.mcpTab.refreshAll")}),r.jsx(B,{icon:r.jsx(Jt,{}),onClick:()=>void pt(),children:e("settings.mcpTab.export")}),r.jsx(B,{icon:r.jsx(Sx,{}),onClick:Ct,children:e("settings.mcpTab.import")})]}),children:r.jsx(y_,{servers:o,loading:l,selectedServerId:a,onSelectServer:p,onEditServer:Ze,onDeleteServer:he,onConnectServer:ve,onDisconnectServer:ue,onRefreshTools:ie,isServerActionLoading:C})}),r.jsx(O_,{server:U,tools:i,loading:u}),r.jsx(S_,{open:j,mode:k,initialConfig:(M==null?void 0:M.config)??null,confirmLoading:c,onCancel:()=>{c||(v(!1),R(null))},onSubmit:re=>void et(re)}),r.jsx(Et,{open:I,title:e("settings.mcpTab.importModalTitle"),okText:e("settings.mcpTab.import"),onOk:()=>void At(),okButtonProps:{loading:H},onCancel:()=>{H||(P(!1),F(null))},width:800,destroyOnClose:!1,children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:"middle",children:[r.jsxs(Ar,{type:"secondary",children:[e("settings.mcpTab.importHint"),r.jsx("br",{}),r.jsx(Ar,{code:!0,children:'{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "..."] } } }'})]}),r.jsxs(Gt.Group,{value:L,onChange:re=>O(re.target.value),optionType:"button",buttonStyle:"solid",children:[r.jsx(Gt.Button,{value:"merge",children:e("settings.mcpTab.importModeMerge")}),r.jsx(Gt.Button,{value:"replace",children:e("settings.mcpTab.importModeReplace")})]}),L==="replace"?r.jsx(Ne,{type:"warning",showIcon:!0,message:e("settings.mcpTab.replaceWarning")}):null,W?r.jsx(Ne,{type:"error",showIcon:!0,message:W}):null,r.jsx(z_,{value:A,onChange:re=>$(re.target.value),rows:14,placeholder:'{"mcpServers": { "filesystem": { "command": "...", "args": [], "env": {} } }}',spellCheck:!1})]})})]})},Fs=e=>{const t=new URLSearchParams;Object.entries(e).forEach(([n,o])=>{o===void 0||o===""||t.set(n,String(o))});const s=t.toString();return s?`?${s}`:""};class U_{async getSummary(t={}){const s=Fs({start_date:t.startDate,end_date:t.endDate});return Se.get(`metrics/summary${s}`)}async getByModel(t={}){const s=Fs({start_date:t.startDate,end_date:t.endDate});return Se.get(`metrics/by-model${s}`)}async getSessions(t={}){const s=Fs({start_date:t.startDate,end_date:t.endDate,model:t.model,limit:t.limit});return Se.get(`metrics/sessions${s}`)}async getSessionDetail(t){try{return await Se.get(`metrics/sessions/${encodeURIComponent(t)}`)}catch(s){if(s instanceof Error&&s.message.includes("not found"))return null;throw s}}async getDaily(t={}){const s=Fs({days:t.days,end_date:t.endDate,granularity:t.granularity});return Se.get(`metrics/daily${s}`)}async getForwardSummary(t={}){const s=Fs({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return Se.get(`metrics/forward/summary${s}`)}async getForwardByEndpoint(t={}){const s=Fs({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return Se.get(`metrics/forward/by-endpoint${s}`)}async getForwardRequests(t={}){const s=Fs({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return Se.get(`metrics/forward/requests${s}`)}async getUnifiedSummary(t={}){const s=Fs({start_date:t.startDate,end_date:t.endDate});return Se.get(`metrics/v2/summary${s}`)}async getUnifiedTimeline(t={}){const s=Fs({days:t.days,end_date:t.endDate,granularity:t.granularity});return Se.get(`metrics/v2/timeline${s}`)}}const Ka=new U_,qg=1,q_=365,Hg=e=>Number.isFinite(e)?Math.min(q_,Math.max(qg,Math.floor(e??30))):30,gl=e=>{if(!e)return null;const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const s=Number(t[1]),n=Number(t[2]),o=Number(t[3]),a=new Date(Date.UTC(s,n-1,o));return a.getUTCFullYear()!==s||a.getUTCMonth()!==n-1||a.getUTCDate()!==o?null:a},Ir=e=>e.toISOString().slice(0,10),H_=(e,t)=>{const s=new Date(e.getTime());return s.setUTCDate(s.getUTCDate()+t),s},Y_=(e,t)=>{const s=t.getTime()-e.getTime(),n=Math.floor(s/864e5)+1;return Hg(n)},Yg=(e,t=new Date)=>{const s=Hg(e.days),n=Ir(t),o=gl(e.endDate)??gl(n);if(!o)return{startDate:n,endDate:n,days:qg};const a=gl(e.startDate);if(a){const l=o<a?a:o;return{startDate:Ir(a),endDate:Ir(l),days:Y_(a,l)}}const i=H_(o,-(s-1));return{startDate:Ir(i),endDate:Ir(o),days:s}},X_=15e3,nm=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,V_=(e={})=>{const{filters:t,autoRefreshMs:s=X_,service:n=Ka}=e,o=m.useMemo(()=>({startDate:t==null?void 0:t.startDate,endDate:t==null?void 0:t.endDate,model:t==null?void 0:t.model,days:(t==null?void 0:t.days)??30,granularity:(t==null?void 0:t.granularity)??"daily",sessionLimit:(t==null?void 0:t.sessionLimit)??200}),[t==null?void 0:t.startDate,t==null?void 0:t.endDate,t==null?void 0:t.model,t==null?void 0:t.days,t==null?void 0:t.granularity,t==null?void 0:t.sessionLimit]),a=m.useMemo(()=>Yg({startDate:o.startDate,endDate:o.endDate,days:o.days}),[o.days,o.endDate,o.startDate]),[i,l]=m.useState(null),[c,d]=m.useState([]),[u,h]=m.useState([]),[p,y]=m.useState([]),[g,f]=m.useState(null),[b,x]=m.useState(!1),[S,w]=m.useState(!1),[C,_]=m.useState(!1),[T,j]=m.useState(null),v=m.useCallback(async R=>{R?w(!0):_(!0);try{const[I,P,L,O]=await Promise.all([n.getSummary({startDate:a.startDate,endDate:a.endDate}),n.getByModel({startDate:a.startDate,endDate:a.endDate}),n.getSessions({startDate:a.startDate,endDate:a.endDate,model:o.model,limit:o.sessionLimit}),n.getDaily({days:a.days,endDate:a.endDate,granularity:o.granularity})]);l(I),d(P),h(L),y(O),j(null)}catch(I){j(nm(I,"Failed to load metrics"))}finally{R?w(!1):_(!1)}},[o.granularity,o.model,o.sessionLimit,a.days,a.endDate,a.startDate,n]),k=m.useCallback(async()=>{await v(!1)},[v]),E=m.useCallback(async R=>{x(!0);try{const I=await n.getSessionDetail(R);f(I)}catch(I){j(nm(I,"Failed to load session detail"))}finally{x(!1)}},[n]),M=m.useCallback(()=>{f(null)},[]);return m.useEffect(()=>{v(!0)},[v]),m.useEffect(()=>{if(s<=0)return;const R=window.setInterval(()=>{v(!1)},s);return()=>{window.clearInterval(R)}},[s,v]),{summary:i,modelMetrics:c,sessions:u,timeline:p,sessionDetail:g,isLoading:S,isRefreshing:C,isSessionDetailLoading:b,error:T,refresh:k,loadSessionDetail:E,clearSessionDetail:M}},K_=15e3,G_=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,J_=(e={})=>{const{filters:t,autoRefreshMs:s=K_}=e,n=m.useMemo(()=>({startDate:t==null?void 0:t.startDate,endDate:t==null?void 0:t.endDate,days:(t==null?void 0:t.days)??30,endpoint:t==null?void 0:t.endpoint,model:t==null?void 0:t.model,limit:(t==null?void 0:t.limit)??100}),[t==null?void 0:t.startDate,t==null?void 0:t.endDate,t==null?void 0:t.days,t==null?void 0:t.endpoint,t==null?void 0:t.model,t==null?void 0:t.limit]),o=m.useMemo(()=>Yg({startDate:n.startDate,endDate:n.endDate,days:n.days}),[n.days,n.endDate,n.startDate]),[a,i]=m.useState(null),[l,c]=m.useState([]),[d,u]=m.useState([]),[h,p]=m.useState(!1),[y,g]=m.useState(!1),[f,b]=m.useState(null),x=m.useCallback(async w=>{w?p(!0):g(!0);try{const C={startDate:o.startDate,endDate:o.endDate,endpoint:n.endpoint,model:n.model,limit:n.limit},[_,T,j]=await Promise.all([Ka.getForwardSummary(C),Ka.getForwardByEndpoint(C),Ka.getForwardRequests(C)]);i(_),c(T),u(j),b(null)}catch(C){b(G_(C,"Failed to load forward metrics"))}finally{w?p(!1):g(!1)}},[n.endpoint,n.model,n.limit,o.endDate,o.startDate]),S=m.useCallback(async()=>{await x(!1)},[x]);return m.useEffect(()=>{x(!0)},[x]),m.useEffect(()=>{if(s<=0)return;const w=window.setInterval(()=>{x(!1)},s);return()=>{window.clearInterval(w)}},[s,x]),{summary:a,endpointMetrics:l,requests:d,isLoading:h,isRefreshing:y,error:f,refresh:S}},{useToken:Q_}=xe,Z_=e=>{const t=Math.floor(e/1e3),s=Math.floor(t/60),n=t%60;return s>0?`${s}m ${n}s`:`${n}s`},e0=e=>{const t=e.filter(n=>typeof n.duration_ms=="number"&&n.duration_ms>0);if(t.length===0)return 0;const s=t.reduce((n,o)=>n+(o.duration_ms??0),0);return Math.floor(s/t.length)},t0=({summary:e,sessions:t,loading:s})=>{const{t:n}=se(),{token:o}=Q_();if(s)return r.jsx(na,{active:!0,paragraph:{rows:1}});const a=e0(t);return r.jsxs(zs,{gutter:[o.marginSM,o.marginSM],children:[r.jsx(Qe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(_s,{title:n("settings.metricsCards.syncMismatches",{defaultValue:"Sync Mismatches"}),value:(e==null?void 0:e.total_sync_mismatches)??0,precision:0,valueStyle:{color:((e==null?void 0:e.total_sync_mismatches)??0)>0?"var(--lotus-chart-danger)":"var(--lotus-chart-secondary)"}})})}),r.jsx(Qe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(_s,{title:n("settings.metricsCards.totalSessions"),value:(e==null?void 0:e.total_sessions)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),r.jsx(Qe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(_s,{title:n("settings.metricsCards.chatTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),r.jsx(Qe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(_s,{title:n("settings.metricsCards.totalToolCalls"),value:(e==null?void 0:e.total_tool_calls)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),r.jsx(Qe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(_s,{title:n("settings.metricsCards.avgSessionDuration"),value:a>0?Z_(a):"-",valueStyle:{color:"var(--lotus-chart-accent)"}})})})]})},{Text:s0}=le,rm=["var(--lotus-chart-primary)","var(--lotus-chart-secondary)","var(--lotus-chart-accent)","var(--lotus-chart-purple)","var(--lotus-chart-cyan)"],n0=({data:e,loading:t})=>{const{t:s}=se();if(t)return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.modelDistribution"),children:r.jsx(na,{active:!0,paragraph:{rows:5}})});const n=e.map(o=>({name:o.model,value:o.tokens.total_tokens}));return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.modelDistribution"),children:n.length===0?r.jsx(Qt,{image:Qt.PRESENTED_IMAGE_SIMPLE,description:s("settings.charts.noModelMetrics")}):r.jsxs(r.Fragment,{children:[r.jsx(s0,{type:"secondary",children:s("settings.charts.modelDistributionDescription")}),r.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:r.jsx(ra,{children:r.jsxs(sb,{children:[r.jsx(nb,{data:n,cx:"50%",cy:"50%",outerRadius:90,fill:"var(--lotus-chart-primary)",dataKey:"value",nameKey:"name",label:!0,children:n.map((o,a)=>r.jsx(rb,{fill:rm[a%rm.length]},`${o.name}-${a}`))}),r.jsx(oa,{})]})})})]})})},r0=e=>{if(!e)return"-";const t=new Date(e);return Number.isNaN(t.getTime())?"-":t.toLocaleString()},o0=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),s=Math.floor(t/60),n=t%60;if(s>=60){const o=Math.floor(s/60),a=s%60;return`${o}h ${a}m`}return s>0?`${s}m ${n}s`:`${n}s`},a0=e=>{switch(e){case"completed":return"success";case"running":return"processing";case"error":return"error";case"cancelled":return"warning";default:return"default"}},i0=({sessions:e,loading:t,onSelectSession:s})=>{const{t:n}=se(),o=[{title:n("settings.metricsTable.session.columns.session"),dataIndex:"session_id",key:"session_id",render:a=>r.jsx(je,{title:a,children:r.jsxs("span",{children:[a.slice(0,8),"..."]})}),width:120},{title:n("settings.metricsTable.session.columns.model"),dataIndex:"model",key:"model",width:160},{title:n("settings.metricsTable.session.columns.status"),dataIndex:"status",key:"status",width:120,render:a=>r.jsx(fe,{color:a0(a),children:a})},{title:n("settings.metricsTable.session.columns.started"),dataIndex:"started_at",key:"started_at",render:a=>r0(a),width:200,sorter:(a,i)=>new Date(a.started_at).getTime()-new Date(i.started_at).getTime(),defaultSortOrder:"descend"},{title:n("settings.metricsTable.session.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",render:a=>o0(a),width:120},{title:n("settings.metricsTable.session.columns.tokens"),key:"tokens",render:(a,i)=>i.total_token_usage.total_tokens.toLocaleString(),width:120,sorter:(a,i)=>a.total_token_usage.total_tokens-i.total_token_usage.total_tokens},{title:n("settings.metricsTable.session.columns.toolCalls"),dataIndex:"tool_call_count",key:"tool_call_count",width:120,sorter:(a,i)=>a.tool_call_count-i.tool_call_count},{title:n("settings.metricsTable.session.columns.messages"),dataIndex:"message_count",key:"message_count",width:120,sorter:(a,i)=>a.message_count-i.message_count},{title:n("settings.metricsTable.session.columns.action"),key:"action",fixed:"right",width:120,render:(a,i)=>r.jsx(B,{type:"link",onClick:()=>{s(i.session_id)},children:n("settings.metricsTable.session.view")})}];return r.jsx(dn,{rowKey:"session_id",size:"small",className:"lotus-metric-table",columns:o,loading:t,dataSource:e,pagination:{pageSize:10,showSizeChanger:!1},scroll:{x:1100}})},{Text:l0}=le,c0=({data:e,loading:t})=>{const{t:s}=se();return t?r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.tokenUsageOverTime"),children:r.jsx(na,{active:!0,paragraph:{rows:5}})}):r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.tokenUsageOverTime"),children:e.length===0?r.jsx(Qt,{image:Qt.PRESENTED_IMAGE_SIMPLE,description:s("settings.charts.noTokenUsage")}):r.jsxs(r.Fragment,{children:[r.jsx(l0,{type:"secondary",children:s("settings.charts.tokenUsageDescription")}),r.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:r.jsx(ra,{children:r.jsxs(ob,{data:e,children:[r.jsx(ji,{strokeDasharray:"3 3"}),r.jsx(Mi,{dataKey:"label",minTickGap:24}),r.jsx(Pi,{allowDecimals:!1}),r.jsx(oa,{}),r.jsx(Dp,{}),r.jsx(Hi,{type:"monotone",dataKey:"totalTokens",name:s("settings.charts.total"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),r.jsx(Hi,{type:"monotone",dataKey:"promptTokens",name:s("settings.charts.prompt"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),r.jsx(Hi,{type:"monotone",dataKey:"completionTokens",name:s("settings.charts.completion"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{useToken:d0}=xe,u0=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),s=Math.floor(t/60),n=t%60;if(s>=60){const o=Math.floor(s/60),a=s%60;return`${o}h ${a}m`}return s>0?`${s}m ${n}s`:`${n}s`},m0=({summary:e,loading:t})=>{const{t:s}=se(),{token:n}=d0();if(t)return r.jsx(na,{active:!0,paragraph:{rows:1}});const o=e&&e.total_requests>0?(e.successful_requests/e.total_requests*100).toFixed(1):"0.0";return r.jsxs(zs,{gutter:[n.marginSM,n.marginSM],children:[r.jsx(Qe,{xs:24,sm:12,xl:6,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(_s,{title:s("settings.forwardMetricsCards.totalForwardRequests"),value:(e==null?void 0:e.total_requests)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),r.jsx(Qe,{xs:24,sm:12,xl:6,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(_s,{title:s("settings.forwardMetricsCards.successRate"),value:o,suffix:"%",valueStyle:{color:Number(o)>=95?"var(--lotus-chart-secondary)":Number(o)>=80?"var(--lotus-chart-accent)":"var(--lotus-chart-danger)"}})})}),r.jsx(Qe,{xs:24,sm:12,xl:6,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(_s,{title:s("settings.forwardMetricsCards.forwardTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),r.jsx(Qe,{xs:24,sm:12,xl:6,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(_s,{title:s("settings.forwardMetricsCards.avgResponseTime"),value:u0(e==null?void 0:e.avg_duration_ms),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{useToken:h0}=xe,p0=({data:e,loading:t})=>{const{t:s}=se(),{token:n}=h0();if(t)return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.endpointDistribution"),children:r.jsx("div",{style:{width:"100%",height:240},children:r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100%",color:n.colorTextSecondary},children:s("settings.common.loading")})})});if(e.length===0)return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.endpointDistribution"),children:r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:240,color:n.colorTextSecondary},children:s("settings.charts.noForwardMetrics")})});const o=e.map(a=>({endpoint:a.endpoint.split(".").pop()||a.endpoint,requests:a.requests,successful:a.successful,failed:a.failed}));return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.endpointDistribution"),children:r.jsx("div",{style:{width:"100%",height:240},children:r.jsx(ra,{children:r.jsxs(Gc,{data:o,children:[r.jsx(ji,{strokeDasharray:"3 3"}),r.jsx(Mi,{dataKey:"endpoint"}),r.jsx(Pi,{}),r.jsx(oa,{formatter:(a,i)=>[`${a}`,i.charAt(0).toUpperCase()+i.slice(1)]}),r.jsx(Dp,{}),r.jsx(si,{dataKey:"successful",fill:"var(--lotus-chart-secondary)",name:s("settings.common.successful"),fillOpacity:.9,radius:[4,4,0,0]}),r.jsx(si,{dataKey:"failed",fill:"var(--lotus-chart-danger)",name:s("settings.common.failed"),fillOpacity:.9,radius:[4,4,0,0]})]})})})})},{Text:bn}=le,f0=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),s=Math.floor(t/60),n=t%60;return s>0?`${s}m ${n}s`:`${n}s`},g0=e=>new Date(e).toLocaleString(),y0=({requests:e,loading:t})=>{const{t:s}=se(),n=[{title:s("settings.metricsTable.forward.columns.id"),dataIndex:"forward_id",key:"forward_id",width:120,render:o=>r.jsxs(bn,{style:{fontSize:12},copyable:!0,children:[o.slice(0,8),"..."]})},{title:s("settings.metricsTable.forward.columns.endpoint"),dataIndex:"endpoint",key:"endpoint",width:150,render:o=>r.jsx(fe,{color:"processing",children:o.split(".").pop()||o})},{title:s("settings.metricsTable.forward.columns.model"),dataIndex:"model",key:"model",width:120},{title:s("settings.metricsTable.forward.columns.type"),dataIndex:"is_stream",key:"is_stream",width:80,render:o=>r.jsx(fe,{color:o?"purple":"processing",children:s(o?"settings.metricsTable.forward.typeStream":"settings.metricsTable.forward.typeSync")})},{title:s("settings.metricsTable.forward.columns.status"),key:"status",width:100,render:(o,a)=>{const i=a.status==="success"?"success":a.status==="error"?"error":"default";return r.jsx(Hc,{status:i,text:a.status_code?r.jsxs("span",{children:[a.status,r.jsxs(bn,{type:"secondary",style:{marginLeft:4},children:["(",a.status_code,")"]})]}):a.status||"-"})}},{title:s("settings.metricsTable.forward.columns.tokens"),key:"tokens",width:100,render:(o,a)=>a.token_usage?r.jsx(bn,{children:a.token_usage.total_tokens.toLocaleString()}):r.jsx(bn,{type:"secondary",children:"-"})},{title:s("settings.metricsTable.forward.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",width:100,render:o=>f0(o)},{title:s("settings.metricsTable.forward.columns.started"),dataIndex:"started_at",key:"started_at",width:160,render:o=>r.jsx(bn,{type:"secondary",style:{fontSize:12},children:g0(o)})},{title:s("settings.metricsTable.forward.columns.error"),dataIndex:"error",key:"error",width:200,render:o=>o?r.jsx(bn,{type:"danger",ellipsis:!0,style:{maxWidth:180},children:o}):r.jsx(bn,{type:"secondary",children:"-"})}];return r.jsx(dn,{rowKey:"forward_id",className:"lotus-metric-table",columns:n,dataSource:e,loading:t,size:"small",pagination:{pageSize:10,showSizeChanger:!0,showTotal:o=>s("settings.metricsTable.forward.totalRequests",{total:o}),pageSizeOptions:["10","20","50","100"]},scroll:{x:1200},locale:{emptyText:s("settings.metricsTable.forward.empty")}})},{Text:x0}=le,om={message_count:"Message Count",last_message_id:"Last Message",pending_question:"Pending Question"},b0=e=>om[e]?om[e]:e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" "),v0=({breakdown:e,loading:t})=>{const{t:s}=se();if(t)return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),children:r.jsx(na,{active:!0,paragraph:{rows:5}})});const n=Object.entries(e??{}).map(([o,a])=>({reason:o,label:s(`settings.syncMismatchReasons.${o}`,{defaultValue:b0(o)}),count:a})).sort((o,a)=>a.count-o.count);return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),extra:r.jsx(x0,{type:"secondary",children:s("settings.metricsDashboard.syncMismatchBreakdownSubtitle",{defaultValue:"Grouped by execute sync mismatch reason"})}),children:n.length===0?r.jsx(Qt,{image:Qt.PRESENTED_IMAGE_SIMPLE,description:s("settings.metricsDashboard.noSyncMismatchBreakdown",{defaultValue:"No sync mismatches recorded for the selected range"})}):r.jsx("div",{style:{width:"100%",minWidth:0,height:280,minHeight:280},children:r.jsx(ra,{children:r.jsxs(Gc,{data:n,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[r.jsx(ji,{strokeDasharray:"3 3"}),r.jsx(Mi,{type:"number",allowDecimals:!1}),r.jsx(Pi,{dataKey:"label",type:"category",width:110}),r.jsx(oa,{formatter:o=>[o.toLocaleString(),s("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})],labelFormatter:o=>s("settings.metricsDashboard.syncMismatchReasonLabel",{defaultValue:"Reason: {{label}}",label:o})}),r.jsx(si,{dataKey:"count",fill:"var(--lotus-chart-danger)",radius:[0,6,6,0],name:s("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})})]})})})})},{Text:vn}=le,{useToken:S0}=xe,am=70,im=130,lm=2,cm=1.2,dm=.65,um=45,mm=1.8,hm=e=>"date"in e?e.date:e.label,w0=(e,t)=>{if(t<=0||e<=0)return"var(--lotus-heat-0)";const s=e/t;return s>=.8?"var(--lotus-heat-4)":s>=.6?"var(--lotus-heat-3)":s>=.4?"var(--lotus-heat-2)":s>=.2?"var(--lotus-heat-1)":"var(--lotus-heat-0)"},ja=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),s=Math.floor(t/60),n=t%60;if(s>=60){const o=Math.floor(s/60),a=s%60;return`${o}h ${a}m`}return s>0?`${s}m ${n}s`:`${n}s`},_0=()=>{const{t:e}=se(),{token:t}=S0(),s=Dn(Y=>Y.themeMode)==="dark",[n,o]=m.useState(void 0),[a,i]=m.useState(void 0),[l,c]=m.useState(void 0),[d,u]=m.useState(30),[h,p]=m.useState("daily"),{summary:y,modelMetrics:g,sessions:f,timeline:b,sessionDetail:x,isLoading:S,isRefreshing:w,isSessionDetailLoading:C,error:_,refresh:T,loadSessionDetail:j,clearSessionDetail:v}=V_({filters:{startDate:n,endDate:a,model:l,days:d,granularity:h}}),{summary:k,endpointMetrics:E,requests:M,isLoading:R,isRefreshing:I,error:P,refresh:L}=J_({filters:{startDate:n,endDate:a,days:d,model:l}}),O=m.useMemo(()=>b.map(Y=>({label:hm(Y),promptTokens:Y.total_token_usage.prompt_tokens,completionTokens:Y.total_token_usage.completion_tokens,totalTokens:Y.total_token_usage.total_tokens})),[b]),A=m.useMemo(()=>g.map(Y=>({label:Y.model,value:Y.model})),[g]),$=m.useMemo(()=>{const Y=new Map;return f.forEach(he=>{Object.entries(he.tool_breakdown).forEach(([ve,ue])=>{Y.set(ve,(Y.get(ve)??0)+ue)})}),Array.from(Y.entries()).map(([he,ve])=>({tool:he,count:ve})).sort((he,ve)=>ve.count-he.count).slice(0,10)},[f]),W=m.useMemo(()=>{const Y=b.map(ve=>({label:hm(ve),sessions:ve.total_sessions,tokens:ve.total_token_usage.total_tokens})),he=Y.reduce((ve,ue)=>Math.max(ve,ue.sessions),0);return{points:Y,maxSessions:he}},[b]),F=m.useMemo(()=>{const Y=M.map(ve=>ve.duration_ms).filter(ve=>typeof ve=="number"&&ve>0).sort((ve,ue)=>ve-ue);if(Y.length===0)return null;const he=Math.ceil(Y.length*.95)-1;return Y[Math.max(0,Math.min(he,Y.length-1))]},[M]),H=m.useMemo(()=>[{title:e("settings.metricsDashboard.roundColumns.round"),dataIndex:"round_id",key:"round_id",render:Y=>`${Y.slice(0,8)}...`},{title:e("settings.metricsDashboard.roundColumns.status"),dataIndex:"status",key:"status"},{title:e("settings.metricsDashboard.roundColumns.duration"),dataIndex:"duration_ms",key:"duration_ms",render:Y=>ja(Y)},{title:e("settings.metricsDashboard.roundColumns.tokens"),key:"tokens",render:(Y,he)=>he.token_usage.total_tokens.toLocaleString()},{title:e("settings.metricsDashboard.roundColumns.toolCalls"),key:"tool_calls",render:(Y,he)=>he.tool_calls.length}],[e]),D=m.useMemo(()=>{const Y=(y==null?void 0:y.total_sessions)??0,he=(y==null?void 0:y.total_tokens.total_tokens)??0,ve=(y==null?void 0:y.total_tool_calls)??0,ue=(y==null?void 0:y.active_sessions)??0,ie=f.reduce((st,rt)=>st+rt.total_rounds,0),Re=(k==null?void 0:k.total_requests)??0,Le=(k==null?void 0:k.total_tokens.total_tokens)??0,Ze=(k==null?void 0:k.failed_requests)??0,et=he+Le,Ct=M.filter(st=>st.is_stream).length,pt=Y>0?ue/Y*100:0,At=Re>0?Ze/Re*100:0,re=M.length>0?Ct/M.length*100:0,$e=he/am+ve*lm,V=he/im+ve*cm,oe=Math.max(0,$e-V)*dm,ce=Math.max(V,$e-oe),Me=ja(oe*6e4),It=Number((oe/(8*60)).toFixed(2)),St=$e>0?Math.min(um,Number((oe/$e*100).toFixed(1))):0,tt=ce>0?Math.min(mm,Number(($e/ce).toFixed(2))):1;return[{title:e("settings.metricsDashboard.compactStats.combinedTokens"),value:et},{title:e("settings.metricsDashboard.compactStats.chatTokens"),value:he},{title:e("settings.metricsDashboard.compactStats.forwardTokens"),value:Le},{title:e("settings.metricsDashboard.compactStats.avgTokensPerSession"),value:Y>0?Math.round(he/Y):0},{title:e("settings.metricsDashboard.compactStats.estimatedTimeSaved"),value:Me},{title:e("settings.metricsDashboard.compactStats.estimatedEfficiencyLift"),value:St,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.estimatedSpeedMultiplier"),value:tt,suffix:e("settings.metricsDashboard.multiplierSuffix")},{title:e("settings.metricsDashboard.compactStats.estimatedSavedWorkdays"),value:It},{title:e("settings.metricsDashboard.compactStats.avgRoundsPerSession"),value:Y>0?Number((ie/Y).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.toolCallsPerSession"),value:Y>0?Number((ve/Y).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.activeSessionRate"),value:Number(pt.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.avgTokensPerForward"),value:Re>0?Math.round(Le/Re):0},{title:e("settings.metricsDashboard.compactStats.forwardErrorRate"),value:Number(At.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.streamingRatio"),value:Number(re.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.p95ForwardLatency"),value:ja(F)},{title:e("settings.metricsDashboard.compactStats.modelCoverage"),value:g.length},{title:e("settings.metricsDashboard.compactStats.endpointCoverage"),value:E.length}]},[E.length,M,k,g.length,F,f,y,e]),U=x==null?void 0:x.session,Q=w||I;return r.jsxs(q,{direction:"vertical",size:t.marginMD,style:{width:"100%"},children:[_?r.jsx(Ne,{type:"error",showIcon:!0,message:_}):null,P?r.jsx(Ne,{type:"error",showIcon:!0,message:P}):null,r.jsx(te,{size:"small",title:e("settings.metricsDashboard.filtersTitle"),extra:r.jsx(B,{icon:r.jsx(Cs,{}),loading:Q,onClick:()=>{T(),L()},children:e("settings.metricsDashboard.refresh")}),children:r.jsxs(q,{wrap:!0,children:[r.jsx(Wd,{placeholder:e("settings.metricsDashboard.startDate"),onChange:Y=>{o(Y?Y.format("YYYY-MM-DD"):void 0)}}),r.jsx(Wd,{placeholder:e("settings.metricsDashboard.endDate"),onChange:Y=>{i(Y?Y.format("YYYY-MM-DD"):void 0)}}),r.jsx(Oe,{allowClear:!0,style:{minWidth:180},placeholder:e("settings.metricsDashboard.model"),value:l,options:A,onChange:Y=>{c(Y)}}),r.jsx(Oe,{style:{width:120},value:d,options:[7,14,30,90].map(Y=>({label:e("settings.metricsDashboard.daysOption",{value:Y}),value:Y})),onChange:Y=>{u(Y)}}),r.jsx(Oe,{style:{width:140},value:h,options:[{label:e("settings.metricsDashboard.granularity.daily"),value:"daily"},{label:e("settings.metricsDashboard.granularity.weekly"),value:"weekly"},{label:e("settings.metricsDashboard.granularity.monthly"),value:"monthly"}],onChange:Y=>{p(Y)}})]})}),r.jsx(te,{size:"small",title:e("settings.metricsDashboard.dashboardTitle"),children:r.jsx(ei,{size:"small",destroyInactiveTabPane:!0,items:[{key:"overview",label:e("settings.metricsDashboard.tabs.overview"),children:r.jsxs(q,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(t0,{summary:y,sessions:f,loading:S}),r.jsx(v0,{breakdown:y==null?void 0:y.sync_mismatch_breakdown,loading:S}),r.jsx(m0,{summary:k,loading:R}),r.jsxs(te,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.derivedMetricsTitle"),extra:r.jsx(vn,{type:"secondary",children:e("settings.metricsDashboard.derivedMetricsSubtitle")}),children:[r.jsx(zs,{gutter:[t.marginSM,t.marginSM],children:D.map(Y=>r.jsx(Qe,{xs:24,sm:12,md:8,xl:6,children:r.jsx("div",{style:{borderRadius:t.borderRadiusSM,padding:t.paddingXS,background:s?"rgba(255, 255, 255, 0.05)":"rgba(255, 255, 255, 0.82)",border:s?"1px solid rgba(255,255,255,0.08)":"1px solid rgba(148,163,184,0.18)"},children:r.jsx(_s,{title:Y.title,value:Y.value,suffix:Y.suffix,valueStyle:{fontSize:t.fontSizeHeading4}})})},Y.title))}),r.jsx(vn,{type:"secondary",style:{display:"block",marginTop:t.marginXS},children:e("settings.metricsDashboard.efficiencyHint",{manualTpm:am,manualToolMinutes:lm,assistedTpm:im,assistedToolMinutes:cm,realization:Math.round(dm*100),maxLift:um,maxMultiplier:mm})})]})]})},{key:"analysis",label:e("settings.metricsDashboard.tabs.analysis"),children:r.jsxs(q,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsxs("div",{style:{width:"100%",display:"grid",gridTemplateColumns:"minmax(0, 2fr) minmax(0, 1fr)",gap:t.marginSM},children:[r.jsx(c0,{data:O,loading:S}),r.jsx(n0,{data:g,loading:S})]}),r.jsxs("div",{style:{width:"100%",display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",gap:t.marginSM},children:[r.jsx(te,{size:"small",title:e("settings.metricsDashboard.toolUsageTitle"),children:$.length===0?r.jsx(vn,{type:"secondary",children:e("settings.metricsDashboard.noToolUsage")}):r.jsx("div",{style:{width:"100%",height:240},children:r.jsx(ra,{children:r.jsxs(Gc,{data:$,children:[r.jsx(ji,{strokeDasharray:"3 3"}),r.jsx(Mi,{dataKey:"tool",interval:0,angle:-20,textAnchor:"end",height:70}),r.jsx(Pi,{allowDecimals:!1}),r.jsx(oa,{}),r.jsx(si,{dataKey:"count",fill:"var(--lotus-chart-primary)",name:e("settings.metricsDashboard.calls"),radius:[6,6,0,0]})]})})})}),r.jsx(te,{size:"small",title:e("settings.metricsDashboard.activityHeatmapTitle"),children:W.points.length===0?r.jsx(vn,{type:"secondary",children:e("settings.metricsDashboard.noActivity")}):r.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))",gap:t.marginXS},children:W.points.map(Y=>r.jsxs("div",{style:{borderRadius:t.borderRadiusSM,padding:t.paddingXS,background:w0(Y.sessions,W.maxSessions),minHeight:64,color:Y.sessions>0?"var(--lotus-metric-text-strong)":t.colorTextSecondary},children:[r.jsx("div",{style:{fontSize:12,lineHeight:1.2},children:Y.label}),r.jsx("div",{style:{fontWeight:600,marginTop:4},children:e("settings.metricsDashboard.sessionsCount",{count:Y.sessions})}),r.jsx("div",{style:{fontSize:12},children:e("settings.metricsDashboard.tokensAmount",{value:Y.tokens.toLocaleString()})})]},Y.label))})})]}),r.jsx(p0,{data:E,loading:R})]})},{key:"records",label:e("settings.metricsDashboard.tabs.records"),children:r.jsx(ei,{size:"small",destroyInactiveTabPane:!0,items:[{key:"sessions",label:e("settings.metricsDashboard.sessionsTabLabel",{count:f.length}),children:r.jsx(te,{size:"small",extra:r.jsx(vn,{type:"secondary",children:e("settings.metricsDashboard.sessionsHint")}),children:r.jsx(i0,{sessions:f,loading:S,onSelectSession:Y=>{j(Y)}})})},{key:"forward-requests",label:e("settings.metricsDashboard.forwardTabLabel",{count:M.length}),children:r.jsx(te,{size:"small",children:r.jsx(y0,{requests:M,loading:R})})}]})}]})}),r.jsx(Et,{title:e("settings.metricsDashboard.sessionMetricsTitle"),open:!!x,onCancel:v,onOk:v,width:960,destroyOnClose:!0,children:C?r.jsx(vn,{children:e("settings.metricsDashboard.loadingSessionDetails")}):U?r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:t.marginMD,children:[r.jsxs(Os,{size:"small",bordered:!0,column:2,children:[r.jsx(Os.Item,{label:e("settings.metricsDashboard.sessionDetail.sessionId"),span:2,children:U.session_id}),r.jsx(Os.Item,{label:e("settings.metricsDashboard.sessionDetail.model"),children:U.model}),r.jsx(Os.Item,{label:e("settings.metricsDashboard.sessionDetail.status"),children:U.status}),r.jsx(Os.Item,{label:e("settings.metricsDashboard.sessionDetail.duration"),children:ja(U.duration_ms)}),r.jsx(Os.Item,{label:e("settings.metricsDashboard.sessionDetail.messages"),children:U.message_count}),r.jsx(Os.Item,{label:e("settings.metricsDashboard.sessionDetail.totalTokens"),children:U.total_token_usage.total_tokens.toLocaleString()}),r.jsx(Os.Item,{label:e("settings.metricsDashboard.sessionDetail.toolCalls"),children:U.tool_call_count})]}),r.jsx(dn,{rowKey:"round_id",size:"small",columns:H,dataSource:x.rounds,pagination:{pageSize:6,showSizeChanger:!1}})]}):r.jsx(vn,{type:"secondary",children:e("settings.metricsDashboard.noDetail")})})]})},{Text:Ma}=le,{useToken:T0}=xe,k0=e=>{const t=e==null?void 0:e.hooks,s=t==null?void 0:t.image_fallback,n=String((s==null?void 0:s.mode)||"placeholder").trim().toLowerCase();return n==="error"||n==="ocr"||n==="vision"?n:"placeholder"},C0=e=>{const t=e==null?void 0:e.hooks,s=t==null?void 0:t.image_fallback,n=s==null?void 0:s.enabled;return typeof n=="boolean"?n:!1},j0=()=>{const{t:e}=se(),{token:t}=T0(),[s,n]=pe.useMessage(),[o,a]=m.useState(!1),[i,l]=m.useState(!0),[c,d]=m.useState("placeholder"),u=m.useMemo(()=>[{label:e("settings.hooksTab.mode.placeholder"),value:"placeholder"},{label:e("settings.hooksTab.mode.error"),value:"error"},{label:e("settings.hooksTab.mode.ocr"),value:"ocr"},{label:e("settings.hooksTab.mode.vision"),value:"vision"}],[e]),h=m.useCallback(async()=>{a(!0);try{const f=await Ye.getBambooConfig();l(C0(f)),d(k0(f))}catch(f){s.error(f instanceof Error?f.message:e("settings.hooksTab.loadFailed"))}finally{a(!1)}},[s,e]),p=m.useCallback(async(f,b)=>{await Ye.setBambooConfig({hooks:{image_fallback:{enabled:f,mode:b}}})},[]),y=m.useCallback(async f=>{a(!0);try{await p(f,c),s.success(e(f?"settings.hooksTab.enabled":"settings.hooksTab.disabled")),await h()}catch(b){s.error(b instanceof Error?b.message:e("settings.hooksTab.updateFailed"))}finally{a(!1)}},[h,c,s,p,e]),g=m.useCallback(async f=>{var b;a(!0);try{await p(i,f),s.success(e("settings.hooksTab.modeUpdated",{mode:((b=u.find(x=>x.value===f))==null?void 0:b.label)??f})),await h()}catch(x){s.error(x instanceof Error?x.message:e("settings.hooksTab.modeUpdateFailed"))}finally{a(!1)}},[i,h,u,s,p,e]);return m.useEffect(()=>{h()},[h]),r.jsxs(K,{vertical:!0,gap:t.marginLG,children:[n,r.jsx(te,{size:"small",loading:o,children:r.jsxs(K,{vertical:!0,gap:t.marginXS,children:[r.jsx(Ma,{strong:!0,children:e("settings.hooksTab.title")}),r.jsxs(K,{align:"center",justify:"space-between",children:[r.jsx(Ma,{children:e("settings.hooksTab.enableImagePreflight")}),r.jsx(ot,{checked:i,onChange:y})]}),r.jsxs(K,{align:"center",justify:"space-between",children:[r.jsx(Ma,{children:e("settings.hooksTab.modeLabel")}),r.jsx(Oe,{style:{width:180},value:c,options:u,onChange:g,disabled:!i})]}),r.jsx(Ma,{type:"secondary",style:{fontSize:t.fontSizeSM},children:e("settings.hooksTab.description")})]})})]})},{Text:Zs}=le,en=hs.getInstance();function M0(){const{t:e}=se(),[t,s]=pe.useMessage(),[n,o]=m.useState(!1),[a,i]=m.useState([]),[l,c]=m.useState({open:!1,scheduleId:null,sessions:[],loading:!1}),[d,u]=m.useState({open:!1,schedule:null,saving:!1}),h=qs(b=>b.close),[p]=ee.useForm(),[y]=ee.useForm(),g=async()=>{o(!0);try{const b=await en.listSchedules();i(b.schedules||[])}catch(b){console.error("[Schedules] Failed to load schedules:",b),t.error(e("settings.schedulesTab.loadFailed"))}finally{o(!1)}};m.useEffect(()=>{g()},[]);const f=m.useMemo(()=>[{title:e("settings.schedulesTab.columns.name"),dataIndex:"name",key:"name"},{title:e("settings.schedulesTab.columns.autoExecute"),key:"auto_execute",render:(b,x)=>{var S,w;return r.jsx(Zs,{type:(S=x.run_config)!=null&&S.auto_execute?void 0:"secondary",children:(w=x.run_config)!=null&&w.auto_execute?e("settings.schedulesTab.yes"):e("settings.schedulesTab.no")})}},{title:e("settings.schedulesTab.columns.model"),key:"model",render:(b,x)=>{var S;return r.jsx(Zs,{type:"secondary",children:(S=x.run_config)!=null&&S.model?String(x.run_config.model):"-"})}},{title:e("settings.schedulesTab.columns.enabled"),key:"enabled",render:(b,x)=>r.jsx(ot,{checked:x.enabled,onChange:async S=>{try{await en.patchSchedule(x.id,{enabled:S}),await g()}catch(w){console.error("[Schedules] Failed to toggle:",w),t.error(e("settings.schedulesTab.updateFailed"))}}})},{title:e("settings.schedulesTab.columns.intervalSeconds"),key:"interval_seconds",render:(b,x)=>r.jsx(Tt,{min:1,value:x.interval_seconds,onChange:async S=>{const w=typeof S=="number"?S:null;if(!(!w||w<=0))try{await en.patchSchedule(x.id,{interval_seconds:w}),await g()}catch(C){console.error("[Schedules] Failed to patch interval:",C),t.error(e("settings.schedulesTab.updateFailed"))}}})},{title:e("settings.schedulesTab.columns.nextRun"),dataIndex:"next_run_at",key:"next_run_at",render:b=>r.jsx(Zs,{type:"secondary",children:String(b)})},{title:e("settings.schedulesTab.columns.lastRun"),dataIndex:"last_run_at",key:"last_run_at",render:b=>r.jsx(Zs,{type:"secondary",children:b?String(b):"-"})},{title:e("settings.schedulesTab.columns.actions"),key:"actions",render:(b,x)=>r.jsxs(K,{gap:8,wrap:"wrap",children:[r.jsx(B,{size:"small",onClick:()=>{var S,w,C,_,T,j;u({open:!0,schedule:x,saving:!1}),y.setFieldsValue({name:x.name,enabled:x.enabled,interval_seconds:x.interval_seconds,system_prompt:((S=x.run_config)==null?void 0:S.system_prompt)||"",task_message:((w=x.run_config)==null?void 0:w.task_message)||"",model:((C=x.run_config)==null?void 0:C.model)||"",workspace_path:((_=x.run_config)==null?void 0:_.workspace_path)||"",enhance_prompt:((T=x.run_config)==null?void 0:T.enhance_prompt)||"",auto_execute:!!((j=x.run_config)!=null&&j.auto_execute)})},children:e("settings.schedulesTab.actions.edit")}),r.jsx(B,{size:"small",onClick:async()=>{try{await en.runScheduleNow(x.id),t.success(e("settings.schedulesTab.enqueuedRun")),await g()}catch(S){console.error("[Schedules] Failed to run now:",S),t.error(e("settings.schedulesTab.runNowFailed"))}},children:e("settings.schedulesTab.actions.runNow")}),r.jsx(B,{size:"small",onClick:async()=>{c(S=>({...S,open:!0,scheduleId:x.id,loading:!0,sessions:[]}));try{const S=await en.listScheduleSessions(x.id);c(w=>({...w,open:!0,scheduleId:x.id,loading:!1,sessions:(S.sessions||[]).map(C=>({id:C.id,title:C.title,updated_at:C.updated_at}))}))}catch(S){console.error("[Schedules] Failed to list sessions:",S),t.error(e("settings.schedulesTab.loadSessionsFailed")),c(w=>({...w,loading:!1}))}},children:e("settings.schedulesTab.actions.sessions")}),r.jsx(B,{danger:!0,size:"small",onClick:async()=>{try{await en.deleteSchedule(x.id),t.success(e("settings.schedulesTab.deleted")),await g()}catch(S){console.error("[Schedules] Failed to delete:",S),t.error(e("settings.schedulesTab.deleteFailed"))}},children:e("settings.schedulesTab.actions.delete")})]})}],[t,e]);return r.jsxs(K,{vertical:!0,gap:16,children:[s,r.jsx(te,{title:e("settings.schedulesTab.createTitle"),className:"lotus-settings-card",children:r.jsxs(ee,{form:p,layout:"vertical",initialValues:{name:e("settings.schedulesTab.defaultName"),interval_seconds:3600,enabled:!1,task_message:"",model:"",auto_execute:!0},onFinish:async b=>{try{const x=!!b.auto_execute,S=String(b.task_message||"").trim(),w=String(b.model||"").trim();if(x&&!S){t.error(e("settings.schedulesTab.taskMessageRequired"));return}await en.createSchedule({name:String(b.name||"").trim(),interval_seconds:Number(b.interval_seconds||0),enabled:!!b.enabled,run_config:{task_message:S||void 0,model:w||void 0,auto_execute:x}}),t.success(e("settings.schedulesTab.created")),p.resetFields(),await g()}catch(x){console.error("[Schedules] Failed to create schedule:",x),t.error(e("settings.schedulesTab.createFailed"))}},children:[r.jsxs(K,{gap:12,wrap:"wrap",children:[r.jsx(ee.Item,{label:e("settings.schedulesTab.form.name"),name:"name",rules:[{required:!0,message:e("settings.schedulesTab.validation.nameRequired")}],style:{flex:"1 1 280px"},children:r.jsx(ye,{})}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.intervalSeconds"),name:"interval_seconds",rules:[{required:!0,message:e("settings.schedulesTab.validation.intervalRequired")}],style:{width:200},children:r.jsx(Tt,{min:1,style:{width:"100%"}})}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",children:r.jsx(ot,{})})]}),r.jsxs(K,{gap:12,wrap:"wrap",children:[r.jsx(ee.Item,{label:e("settings.schedulesTab.form.taskMessage"),name:"task_message",style:{flex:"1 1 480px"},children:r.jsx(ye.TextArea,{rows:3,placeholder:e("settings.schedulesTab.form.taskMessagePlaceholder")})}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.model"),name:"model",style:{width:240},children:r.jsx(ye,{placeholder:e("settings.schedulesTab.form.modelPlaceholder")})}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.autoExecute"),name:"auto_execute",valuePropName:"checked",children:r.jsx(ot,{})})]}),r.jsx(B,{type:"primary",htmlType:"submit",children:e("settings.schedulesTab.actions.create")})]})}),r.jsx(te,{title:e("settings.schedulesTab.listTitle"),className:"lotus-settings-card",extra:r.jsx(B,{onClick:()=>g(),loading:n,children:e("settings.schedulesTab.actions.refresh")}),children:r.jsx(dn,{rowKey:"id",columns:f,dataSource:a,loading:n,pagination:{pageSize:10}})}),r.jsx(Et,{title:e("settings.schedulesTab.scheduleSessionsTitle"),open:l.open,onCancel:()=>c(b=>({...b,open:!1,scheduleId:null})),footer:null,children:l.loading?r.jsx(Zs,{type:"secondary",children:e("settings.schedulesTab.loading")}):r.jsx(K,{vertical:!0,gap:8,children:l.sessions.length===0?r.jsx(Zs,{type:"secondary",children:e("settings.schedulesTab.noSessionsYet")}):l.sessions.map(b=>r.jsxs(K,{justify:"space-between",align:"center",children:[r.jsxs(K,{vertical:!0,style:{minWidth:0},children:[r.jsx(Zs,{strong:!0,ellipsis:!0,children:b.title}),r.jsxs(Zs,{type:"secondary",ellipsis:!0,children:[b.id," • ",b.updated_at]})]}),r.jsx(B,{size:"small",onClick:()=>{Di(b.id,{forceRefreshIndex:!0,forceLoadHistory:!0,subscribeIfRunning:!0,forceSubscribe:!0}),h()},children:e("settings.schedulesTab.actions.open")})]},b.id))})}),r.jsx(Et,{title:e("settings.schedulesTab.editTitle"),open:d.open,onCancel:()=>u({open:!1,schedule:null,saving:!1}),okText:e("settings.schedulesTab.actions.save"),confirmLoading:d.saving,onOk:()=>y.submit(),children:r.jsxs(ee,{form:y,layout:"vertical",onFinish:async b=>{const x=d.schedule;if(!x)return;const S=!!b.auto_execute,w=String(b.task_message||"").trim(),C=String(b.model||"").trim();if(S&&!w){t.error(e("settings.schedulesTab.taskMessageRequired"));return}u(_=>({..._,saving:!0}));try{await en.patchSchedule(x.id,{name:String(b.name||"").trim()||void 0,enabled:!!b.enabled,interval_seconds:Number(b.interval_seconds||0)||void 0,run_config:{system_prompt:String(b.system_prompt||"").trim()||void 0,task_message:w||void 0,model:C||void 0,workspace_path:String(b.workspace_path||"").trim()||void 0,enhance_prompt:String(b.enhance_prompt||"").trim()||void 0,auto_execute:S}}),t.success(e("settings.schedulesTab.updated")),u({open:!1,schedule:null,saving:!1}),await g()}catch(_){console.error("[Schedules] Failed to patch schedule:",_),t.error(e("settings.schedulesTab.updateFailed")),u(T=>({...T,saving:!1}))}},children:[r.jsxs(K,{gap:12,wrap:"wrap",children:[r.jsx(ee.Item,{label:e("settings.schedulesTab.form.name"),name:"name",rules:[{required:!0,message:e("settings.schedulesTab.validation.nameRequired")}],style:{flex:"1 1 280px"},children:r.jsx(ye,{})}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.intervalSeconds"),name:"interval_seconds",rules:[{required:!0,message:e("settings.schedulesTab.validation.intervalRequired")}],style:{width:220},children:r.jsx(Tt,{min:1,style:{width:"100%"}})}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",children:r.jsx(ot,{})})]}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.systemPrompt"),name:"system_prompt",children:r.jsx(ye.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.taskMessage"),name:"task_message",children:r.jsx(ye.TextArea,{rows:3,placeholder:e("settings.schedulesTab.optional")})}),r.jsxs(K,{gap:12,wrap:"wrap",children:[r.jsx(ee.Item,{label:e("settings.schedulesTab.form.model"),name:"model",style:{flex:"1 1 260px"},children:r.jsx(ye,{placeholder:e("settings.schedulesTab.form.modelRequiredIfAuto")})}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.autoExecute"),name:"auto_execute",valuePropName:"checked",children:r.jsx(ot,{})})]}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.workspacePath"),name:"workspace_path",children:r.jsx(ye,{placeholder:e("settings.schedulesTab.optional")})}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.enhancePrompt"),name:"enhance_prompt",children:r.jsx(ye.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})})]})})]})}const{Text:$r}=le,Fr=hs.getInstance();function P0(){const{t:e}=se(),{modal:t,message:s}=ts.useApp(),n=z(g=>g.chats),o=z(g=>g.currentSessionId),a=z(g=>g.refreshChats),i=z(g=>g.loadChats),l=z(g=>g.loadChatHistory),[c,d]=m.useState(!0),[u,h]=m.useState(!1),p=m.useMemo(()=>o?n.find(g=>g.id===o)??null:null,[n,o]),y=async g=>{if(!u){h(!0);try{await g()}finally{h(!1)}}};return r.jsxs(K,{vertical:!0,gap:16,children:[r.jsx(te,{size:"small",title:e("settings.sessionsTab.currentSessionTitle"),children:p?r.jsxs(K,{vertical:!0,gap:4,children:[r.jsx($r,{strong:!0,ellipsis:!0,children:p.title}),r.jsxs($r,{type:"secondary",ellipsis:!0,children:[e("settings.sessionsTab.id"),": ",p.id," ","•"," ",e("settings.sessionsTab.kind"),": ",p.kind]}),r.jsx(K,{gap:8,wrap:"wrap",style:{marginTop:8},children:r.jsx(B,{danger:!0,loading:u,onClick:()=>{t.confirm({title:e("settings.sessionsTab.clearMessagesTitle"),content:e("settings.sessionsTab.clearMessagesContent"),okText:e("settings.sessionsTab.clear"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await y(async()=>{await Fr.clearSession(p.id),await l(p.id),await a(),s.success(e("settings.sessionsTab.sessionCleared"))})}})},children:e("settings.sessionsTab.clearMessages")})})]}):r.jsx($r,{type:"secondary",children:e("settings.sessionsTab.noActiveSession")})}),r.jsxs(te,{size:"small",title:e("settings.sessionsTab.bulkCleanupTitle"),children:[r.jsxs(K,{align:"center",gap:8,style:{marginBottom:12},children:[r.jsx($r,{children:e("settings.sessionsTab.keepPinned")}),r.jsx(ot,{checked:c,onChange:d})]}),r.jsxs(K,{gap:8,wrap:"wrap",children:[r.jsx(B,{danger:!0,loading:u,onClick:()=>{t.confirm({title:e("settings.sessionsTab.deleteAllTitle"),content:e(c?"settings.sessionsTab.deleteAllKeepPinned":"settings.sessionsTab.deleteAllIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await y(async()=>{await Fr.cleanupSessions("all",c),await i(),s.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteAll")}),r.jsx(B,{danger:!0,loading:u,onClick:()=>{t.confirm({title:e("settings.sessionsTab.deleteEmptyTitle"),content:e(c?"settings.sessionsTab.deleteEmptyKeepPinned":"settings.sessionsTab.deleteEmptyIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await y(async()=>{await Fr.cleanupSessions("empty",c),await i(),s.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteEmpty")}),r.jsx(B,{danger:!0,loading:u,onClick:()=>{t.confirm({title:e("settings.sessionsTab.deleteChildrenTitle"),content:e(c?"settings.sessionsTab.deleteChildrenKeepPinned":"settings.sessionsTab.deleteChildrenIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await y(async()=>{await Fr.cleanupSessions("children",c),await i(),s.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteChildren")})]})]}),r.jsxs(te,{size:"small",title:e("settings.sessionsTab.devResetTitle"),children:[r.jsx($r,{type:"secondary",children:e("settings.sessionsTab.devResetDescription")}),r.jsx(K,{style:{marginTop:12},children:r.jsx(B,{danger:!0,type:"primary",loading:u,onClick:()=>{t.confirm({title:e("settings.sessionsTab.devResetConfirmTitle"),content:e("settings.sessionsTab.devResetConfirmContent"),okText:e("settings.sessionsTab.reset"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await y(async()=>{await Fr.devResetSessions(),await i(),s.success(e("settings.sessionsTab.devResetDone"))})}})},children:e("settings.sessionsTab.devResetAction")})})]})]})}const{Text:Pa,Paragraph:E0}=le,R0=({open:e,onCancel:t,onComplete:s,onCopyCode:n,completingAuth:o,copiedUserCode:a,deviceCodeInfo:i,timeRemaining:l,token:c})=>{const{t:d}=se();return r.jsx(Et,{title:d("settings.providerTab.copilotAuthModalTitle"),open:e,onCancel:t,footer:[r.jsx(B,{onClick:t,children:d("settings.providerTab.cancel")},"cancel"),r.jsx(B,{type:"primary",onClick:s,loading:o,children:d("settings.providerTab.completedAuthorization")},"complete")],children:i&&r.jsxs(q,{direction:"vertical",size:"large",style:{width:"100%"},children:[r.jsx(Ne,{message:d("settings.providerTab.browserOpened"),description:r.jsxs("ol",{children:[r.jsx("li",{children:d("settings.providerTab.authStep1")}),r.jsx("li",{children:d("settings.providerTab.authStep2")}),r.jsx("li",{children:d("settings.providerTab.authStep3")})]}),type:"info"}),r.jsx(te,{size:"small",className:"lotus-settings-card",children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},children:[r.jsx(Pa,{type:"secondary",children:d("settings.providerTab.visitUrl")}),r.jsx(q,{children:r.jsx(Pa,{copyable:{text:i.verification_uri},children:i.verification_uri})})]})}),r.jsx(te,{style:{textAlign:"center",background:c.colorFillTertiary,borderColor:c.colorBorderSecondary},children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},children:[r.jsx(Pa,{type:"secondary",children:d("settings.providerTab.enterCode")}),r.jsxs(q,{children:[r.jsx(Pa,{style:{color:c.colorText,fontSize:"32px",fontFamily:"monospace",fontWeight:"bold",letterSpacing:"4px"},children:i.user_code}),r.jsx(B,{icon:a?r.jsx(Ws,{}):r.jsx(Jt,{}),onClick:n,type:a?"default":"primary",children:d(a?"settings.providerTab.copied":"settings.providerTab.copyCode")})]}),r.jsx("div",{style:{marginTop:8},children:r.jsxs(fe,{color:l<60?"error":l<180?"warning":"success",children:[r.jsx(Us,{style:{marginRight:4}}),"Expires in ",Math.floor(l/60),":",(l%60).toString().padStart(2,"0")]})})]})}),r.jsx(E0,{type:"secondary",children:d("settings.providerTab.afterContinueHint")})]})})},yl={copilot:"GitHub Copilot",openai:"OpenAI",anthropic:"Anthropic",gemini:"Google Gemini"},Mc=[{value:"gpt-4o-mini",label:"GPT-4o Mini"},{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4-turbo",label:"GPT-4 Turbo"},{value:"gpt-4-turbo-preview",label:"GPT-4 Turbo Preview"},{value:"gpt-4",label:"GPT-4"},{value:"gpt-3.5-turbo",label:"GPT-3.5 Turbo"}],Pc=[{value:"claude-3-5-sonnet-20241022",label:"Claude 3.5 Sonnet"},{value:"claude-3-5-sonnet-20240620",label:"Claude 3.5 Sonnet (Legacy)"},{value:"claude-3-opus-20240229",label:"Claude 3 Opus"},{value:"claude-3-sonnet-20240229",label:"Claude 3 Sonnet"},{value:"claude-3-haiku-20240307",label:"Claude 3 Haiku"}],Ec=[{value:"gemini-pro",label:"Gemini Pro"},{value:"gemini-pro-vision",label:"Gemini Pro Vision"},{value:"gemini-1.5-pro",label:"Gemini 1.5 Pro"},{value:"gemini-1.5-flash",label:"Gemini 1.5 Flash"}],Xg=[{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4o-mini",label:"GPT-4o Mini"}],{Option:Sn}=Oe,{Password:pm}=ye,{Text:Ht,Paragraph:xl}=le,fm=e=>r.jsxs(q,{direction:"vertical",size:4,children:[r.jsxs(Ht,{type:"secondary",children:[e("settings.providerTab.responsesOnlyHelp1")," ",r.jsx(Ht,{code:!0,children:"/responses"}),"."]}),r.jsx(Ht,{type:"secondary",children:e("settings.providerTab.responsesOnlyHelp2")})]}),gm=["openai","anthropic","gemini","copilot"],A0=e=>e.map(t=>({value:t,label:t})),I0=()=>{const{t:e}=se(),{token:t}=xe.useToken(),[s]=ee.useForm(),[n,o]=m.useState(!1),[a,i]=m.useState(!1),[l,c]=m.useState("copilot"),[d,u]=m.useState(!1),[h,p]=m.useState(null),[y,g]=m.useState(!1),[f,b]=m.useState(!1),[x,S]=m.useState(null),[w,C]=m.useState(!1),[_,T]=m.useState(!1),[j,v]=m.useState(0),[k,E]=m.useState(!1),[M,R]=m.useState(!1),[I,P]=m.useState([]),[L,O]=m.useState(null),[A,$]=m.useState(!1),[W,F]=m.useState([]),[H,D]=m.useState("idle"),[U,Q]=m.useState(null);m.useEffect(()=>{if(H!=="success")return;const X=setTimeout(()=>{D("idle"),Q(null)},2e3);return()=>clearTimeout(X)},[H]);const Y=ee.useWatch(["providers","openai","api_key"],s),he=ee.useWatch(["providers","openai","base_url"],s),ve=ee.useWatch(["providers","anthropic","api_key"],s),ue=ee.useWatch(["providers","anthropic","base_url"],s),ie=ee.useWatch(["providers","gemini","api_key"],s),Re=ee.useWatch(["providers","gemini","base_url"],s);m.useEffect(()=>{l==="openai"&&(P([]),O(null),$(!1))},[l,Y,he]),m.useEffect(()=>{l==="anthropic"&&(P([]),O(null),$(!1))},[l,ve,ue]),m.useEffect(()=>{l==="gemini"&&(P([]),O(null),$(!1))},[l,ie,Re]),m.useEffect(()=>{if(!w||!x){v(0);return}v(x.expires_in);const X=setInterval(()=>{v(G=>G<=1?(clearInterval(X),0):G-1)},1e3);return()=>clearInterval(X)},[w,x]);const Le=m.useCallback(async()=>{try{o(!0);const X=await bt.getProviderConfig(),G={provider:X.provider,providers:X.providers||{}};if(G.provider==="copilot"){const ae=G.providers.copilot??{};ae.model||(G.providers.copilot={...ae,model:"gpt-4o"})}He("[Provider]","Loaded provider config:",G);const de={...G.providers||{}};gm.forEach(ae=>{const Pe=de[ae];Pe&&Pe.request_overrides&&typeof Pe.request_overrides=="object"&&(Pe.request_overrides_json=JSON.stringify(Pe.request_overrides,null,2))}),c(G.provider),s.setFieldsValue({...G,providers:de}),u(!0)}catch(X){pe.error(e("settings.providerTab.loadConfigFailed")),console.error("Failed to load provider config:",X)}finally{o(!1)}},[s,e]),Ze=m.useCallback(async()=>{try{const X=await bt.getEnvVars();F(X.entries||[])}catch(X){console.warn("Failed to load env vars for provider overrides:",X)}},[]),et=m.useCallback(async()=>{try{g(!0);const X=await bt.getCopilotAuthStatus();p(X)}catch(X){console.error("Failed to check Copilot auth status:",X),p({authenticated:!1,message:e("settings.providerTab.checkStatusFailed")})}finally{g(!1)}},[e]);m.useEffect(()=>{Le(),Ze()},[Le,Ze]),m.useEffect(()=>{l==="copilot"&&et()},[l,et]);const Ct=async()=>{try{b(!0);const X=await bt.startCopilotAuth();S(X),C(!0)}catch(X){pe.error(e("settings.providerTab.startCopilotAuthFailed")),console.error("Failed to start Copilot authentication:",X)}finally{b(!1)}},pt=async()=>{if(x)try{T(!0),await bt.completeCopilotAuth({device_code:x.device_code,interval:x.interval||5,expires_in:x.expires_in}),pe.success(e("settings.providerTab.copilotAuthSuccess")),C(!1),S(null),await et()}catch(X){pe.error(e("settings.providerTab.completeAuthFailed")),console.error("Authentication completion failed:",X)}finally{T(!1)}},At=async()=>{if(x)try{await es(x.user_code),E(!0),pe.success(e("settings.providerTab.userCodeCopied")),setTimeout(()=>E(!1),2e3)}catch{pe.error(`${e("settings.providerTab.copyCodeFailedPrefix")} ${x.user_code}`)}},re=async()=>{try{b(!0),await bt.logoutCopilot(),pe.success(e("settings.providerTab.logoutSuccess")),await et()}catch(X){pe.error(e("settings.providerTab.logoutFailed")),console.error("Failed to logout:",X)}finally{b(!1)}},$e=X=>{c(X),s.setFieldsValue({provider:X}),P([]),O(null),$(!1),D("idle"),Q(null)},V=X=>kb(X)||X instanceof Error?X.message:e("settings.providerTab.unknownError"),ge=X=>{s.setFields([{name:["provider"],errors:[]},{name:["providers",X,"api_key"],errors:[]},{name:["providers",X,"model"],errors:[]}])},oe=X=>{const G=X.trim();return G?G.includes(".")?G.split(".").filter(Boolean):G==="provider"?["provider"]:G==="provider/providers"?["provider"]:null:null},ce=(X,G)=>{if(!X.length)return;const de=X.map(ae=>{const Pe=oe(ae.path);return Pe?{name:Pe,errors:[ae.message]}:ae.message.toLowerCase().includes("api key")?{name:["providers",G,"api_key"],errors:[ae.message]}:{name:["provider"],errors:[ae.message]}}).filter((ae,Pe,Xe)=>Xe.findIndex(Je=>JSON.stringify(Je.name)===JSON.stringify(ae.name))===Pe);de.length&&s.setFields(de)},Me=async X=>{var de;const G=X.provider||l;ge(G);try{const Pe=await Pt.getInstance().validateBambooConfigPatch({provider:X.provider,providers:X.providers||{}});if(Pe.valid)return{valid:!0};const Xe=((de=Pe.errors)==null?void 0:de.provider)||[];ce(Xe,G);const Je=Xe[0];return{valid:!1,message:(Je==null?void 0:Je.message)||e("settings.providerTab.invalidConfig")}}catch(ae){return console.warn("Config validation failed, falling back to save:",ae),{valid:!0}}},It=async(X,G)=>{const de={openai:e("settings.providerTab.providerNames.openai"),anthropic:e("settings.providerTab.providerNames.anthropic"),gemini:e("settings.providerTab.providerNames.gemini"),copilot:e("settings.providerTab.providerNames.copilot")},ae=e(X==="copilot"?"settings.providerTab.fetchModelsCopilotFailed":"settings.providerTab.fetchModelsFailed");if(!(!(G!=null&&G.force)&&I.length>0))try{R(!0),O(null),$(!0);const Pe=X==="copilot"?await Ei.getModels():await bt.fetchProviderModels(X),Xe=A0(Pe);if(P(Xe),X==="copilot"&&Xe.length===0){const Je=e("settings.providerTab.noModelsReturned");O(Je),(G==null?void 0:G.showMessage)!==!1&&pe.warning(Je);return}(G==null?void 0:G.showMessage)!==!1&&pe.success(e("settings.providerTab.foundModels",{count:Xe.length}))}catch(Pe){const Xe=V(Pe);O(Xe),(G==null?void 0:G.showMessage)!==!1&&pe.error(Xe?`${e("settings.providerTab.fetchModelsErrorPrefix")}: ${Xe}`:ae),console.error(`Failed to fetch ${de[X]} models:`,Pe)}finally{R(!1)}},St=async(X,G)=>{try{o(!0);const de={provider:X.provider,providers:{...X.providers||{}}},ae=de.providers;for(const Je of gm){const rs=ae[Je];if(!rs)continue;const Z=rs.request_overrides_json;if(typeof Z!="string")continue;const Ce=Z.trim();if(!Ce)delete rs.request_overrides;else try{rs.request_overrides=JSON.parse(Ce)}catch(Ie){const Be=`Invalid request_overrides JSON for ${Je}: ${Ie.message}`;if(s.setFields([{name:["providers",Je,"request_overrides_json"],errors:[Be]}]),(G==null?void 0:G.showMessage)!==!1&&pe.error(Be),G!=null&&G.throwOnError)throw Ie;return}delete rs.request_overrides_json}const Pe={provider:de.provider,providers:de.providers||{}},Xe=await Me(de);if(!Xe.valid){const Je=Xe.message||e("settings.providerTab.invalidConfig");if((G==null?void 0:G.showMessage)!==!1&&pe.error(`${e("settings.providerTab.invalidConfigPrefix")}: ${Je}`),G!=null&&G.throwOnError)throw new Error(Je);return}He("[Provider]","Saving provider config:",Pe),await bt.saveProviderConfig(Pe),(G==null?void 0:G.showMessage)!==!1&&pe.success(e("settings.providerTab.saveConfigSuccess"))}catch(de){const ae=V(de);if((G==null?void 0:G.showMessage)!==!1&&pe.error(ae?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${ae}`:e("settings.providerTab.saveConfigFailed")),console.error("Failed to save configuration:",de),G!=null&&G.throwOnError)throw de}finally{o(!1)}},tt=async X=>{try{i(!0);const{useProviderStore:G}=await kt(async()=>{const{useProviderStore:de}=await Promise.resolve().then(()=>Pb);return{useProviderStore:de}},void 0,import.meta.url);await G.getState().loadProviderConfig(),(X==null?void 0:X.showMessage)!==!1&&pe.success(e("settings.providerTab.applyConfigSuccess"))}catch(G){const de=V(G);if((X==null?void 0:X.showMessage)!==!1&&pe.error(de?`${e("settings.providerTab.applyConfigErrorPrefix")}: ${de}`:e("settings.providerTab.applyConfigFailed")),console.error("Failed to apply configuration:",G),X!=null&&X.throwOnError)throw G}finally{i(!1)}},st=async X=>{try{await St(X,{throwOnError:!0}),await tt({throwOnError:!0})}catch{}},rt=async(X,G)=>{if(!(!(G!=null&&G.force)&&I.length>0)){try{const de=s.getFieldsValue(!0);await St(de,{showMessage:!1,throwOnError:!0})}catch(de){const ae=V(de);O(ae),$(!0),pe.error(ae?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${ae}`:e("settings.providerTab.saveConfigFailed"));return}await It(X,{force:G==null?void 0:G.force})}},ss=async(X,G)=>{G&&(M||I.length>0||A&&L||await rt(X))},Ms=async(X,G)=>{if(G&&H!=="saving"){D("saving"),Q(null);try{const de=s.getFieldsValue(!0),ae=de.providers||{},Pe=ae;Pe[X]={...Pe[X]??{},model:G},de.providers=ae,await St(de,{showMessage:!1,throwOnError:!0}),await tt({showMessage:!1,throwOnError:!0}),D("success"),pe.success(e("settings.providerTab.modelUpdated"))}catch(de){const ae=V(de);D("error"),Q(ae),pe.error(ae?`${e("settings.providerTab.updateModelErrorPrefix")}: ${ae}`:e("settings.providerTab.updateModelFailed"))}}},Hs=async(X,G,de)=>{if(H!=="saving"){D("saving"),Q(null);try{const ae=s.getFieldsValue(!0),Pe=ae.providers||{},Xe=Pe;Xe[X]={...Xe[X]??{},[G]:de||void 0},ae.providers=Pe,await St(ae,{showMessage:!1,throwOnError:!0}),await tt({showMessage:!1,throwOnError:!0}),D("success"),pe.success(e("settings.providerTab.modelUpdated"))}catch(ae){const Pe=V(ae);D("error"),Q(Pe),pe.error(Pe?`${e("settings.providerTab.updateModelErrorPrefix")}: ${Pe}`:e("settings.providerTab.updateModelFailed"))}}},ns=(X,G)=>{const de=I.length>0?I:G;return r.jsxs(r.Fragment,{children:[r.jsx(ee.Item,{name:["providers",X,"fast_model"],label:e("settings.providerTab.fastModel"),extra:r.jsx(Ht,{type:"secondary",children:e("settings.providerTab.fastModelHelp")}),children:r.jsx(Oe,{placeholder:e("settings.providerTab.sameAsDefault"),allowClear:!0,showSearch:!0,loading:M,disabled:H==="saving",notFoundContent:M?r.jsx(ct,{size:"small"}):null,onDropdownVisibleChange:ae=>ss(X,ae),onChange:ae=>Hs(X,"fast_model",ae),children:de.map(ae=>r.jsx(Sn,{value:ae.value,children:ae.label},ae.value))})}),r.jsx(ee.Item,{name:["providers",X,"vision_model"],label:e("settings.providerTab.visionModel"),extra:r.jsx(Ht,{type:"secondary",children:e("settings.providerTab.visionModelHelp")}),children:r.jsx(Oe,{placeholder:e("settings.providerTab.sameAsDefault"),allowClear:!0,showSearch:!0,loading:M,disabled:H==="saving",notFoundContent:M?r.jsx(ct,{size:"small"}):null,onDropdownVisibleChange:ae=>ss(X,ae),onChange:ae=>Hs(X,"vision_model",ae),children:de.map(ae=>r.jsx(Sn,{value:ae.value,children:ae.label},ae.value))})})]})},Ys=(X,G)=>r.jsxs(q,{direction:"vertical",size:4,children:[r.jsxs(q,{size:"small",children:[r.jsx(B,{type:"link",size:"small",onClick:()=>rt(X,{force:!0}),loading:M,style:{padding:0},children:M?e("settings.providerTab.fetchingModels"):I.length>0?e("settings.providerTab.refreshModelsFrom",{source:G}):e("settings.providerTab.fetchModelsFrom",{source:G})}),H==="saving"&&r.jsx(ct,{size:"small"}),H==="success"&&r.jsx(Ws,{style:{color:"var(--lotus-chart-secondary)"}}),H==="error"&&r.jsx(je,{title:U||e("settings.providerTab.saveModelChangeFailed"),children:r.jsx(Gl,{style:{color:"var(--lotus-chart-danger)"}})})]}),L&&r.jsxs(q,{size:"small",children:[r.jsx(je,{title:L,children:r.jsx(Ht,{type:"danger",children:e("settings.providerTab.fetchModelsFailedShort")})}),r.jsx(B,{size:"small",onClick:()=>rt(X,{force:!0}),loading:M,children:e("settings.providerTab.retry")})]})]}),Ps=X=>{const G=W.map(ae=>ae.name);return r.jsx(ee.Item,{name:["providers",X,"request_overrides_json"],label:"Advanced Request Overrides (JSON)",extra:r.jsxs(q,{direction:"vertical",size:4,children:[r.jsx(Ht,{type:"secondary",children:"Customize provider request headers/body patch rules. Supports endpoint scoping and model-based rules."}),r.jsxs(Ht,{type:"secondary",children:["Env var injection:"," ",r.jsx(Ht,{code:!0,children:'{ "type": "env_ref", "name": "YOUR_ENV_NAME" }'})]}),G.length>0&&r.jsx(q,{wrap:!0,size:[6,6],children:G.map(ae=>r.jsx(fe,{children:ae},ae))})]}),children:r.jsx(ye.TextArea,{autoSize:{minRows:8,maxRows:20},placeholder:`{
|
|
132
|
+
"common": {
|
|
133
|
+
"headers": {
|
|
134
|
+
"x-request-id": { "type": "generated", "generator": "uuid" },
|
|
135
|
+
"x-tenant": { "type": "env_ref", "name": "TENANT_ID" }
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
"rules": [
|
|
139
|
+
{
|
|
140
|
+
"model_pattern": "gpt-5*",
|
|
141
|
+
"scope": {
|
|
142
|
+
"body_patch": [
|
|
143
|
+
{ "path": "metadata.trace_id", "op": "set", "value": { "type": "generated", "generator": "uuid" } }
|
|
144
|
+
]
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
]
|
|
148
|
+
}`,style:{fontFamily:"SFMono-Regular, Menlo, Monaco, Consolas, monospace"}})})},Bn=()=>{switch(l){case"openai":return r.jsxs(r.Fragment,{children:[r.jsx(Ne,{message:e("settings.providerTab.openaiConfigTitle"),description:e("settings.providerTab.openaiConfigDescription"),type:"info",showIcon:!0,style:{marginBottom:16}}),r.jsx(ee.Item,{name:["providers","openai","api_key"],label:e("settings.providerTab.openaiApiKey"),rules:[{required:!0,message:e("settings.providerTab.openaiApiKeyRequired")}],children:r.jsx(ye.Password,{"data-testid":"api-key-input",placeholder:"sk-...",prefix:r.jsx(qi,{})})}),r.jsx(ee.Item,{name:["providers","openai","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.openaiBaseUrlHelp"),children:r.jsx(ye,{placeholder:"https://api.openai.com/v1"})}),r.jsx(ee.Item,{name:["providers","openai","model"],label:e("settings.providerTab.defaultModel"),rules:[{required:!0,message:e("settings.providerTab.selectModelRequired")}],extra:Ys("openai","API"),children:r.jsx(Oe,{placeholder:e("settings.providerTab.selectModel"),allowClear:!0,showSearch:!0,loading:M,disabled:H==="saving",notFoundContent:M?r.jsx(ct,{size:"small"}):null,onDropdownVisibleChange:X=>ss("openai",X),onChange:X=>Ms("openai",X),children:(I.length>0?I:Mc).map(X=>r.jsx(Sn,{value:X.value,children:X.label},X.value))})}),r.jsx(ee.Item,{name:["providers","openai","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:fm(e),children:r.jsx(Oe,{mode:"tags",placeholder:'e.g. "gpt-5.3-codex", "gpt-5*"',tokenSeparators:[","," ",`
|
|
149
|
+
`," "]})}),r.jsx(Dt,{dashed:!0}),ns("openai",Mc),Ps("openai")]});case"anthropic":return r.jsxs(r.Fragment,{children:[r.jsx(Ne,{message:e("settings.providerTab.anthropicConfigTitle"),description:e("settings.providerTab.anthropicConfigDescription"),type:"info",showIcon:!0,style:{marginBottom:16}}),r.jsx(ee.Item,{name:["providers","anthropic","api_key"],label:e("settings.providerTab.anthropicApiKey"),rules:[{required:!0,message:e("settings.providerTab.anthropicApiKeyRequired")}],children:r.jsx(pm,{placeholder:"sk-ant-...",prefix:r.jsx(qi,{})})}),r.jsx(ee.Item,{name:["providers","anthropic","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.anthropicBaseUrlHelp"),children:r.jsx(ye,{placeholder:"https://api.anthropic.com/v1"})}),r.jsx(ee.Item,{name:["providers","anthropic","model"],label:e("settings.providerTab.defaultModel"),rules:[{required:!0,message:e("settings.providerTab.selectModelRequired")}],extra:Ys("anthropic","API"),children:r.jsx(Oe,{placeholder:e("settings.providerTab.selectModel"),allowClear:!0,showSearch:!0,loading:M,disabled:H==="saving",notFoundContent:M?r.jsx(ct,{size:"small"}):null,onDropdownVisibleChange:X=>ss("anthropic",X),onChange:X=>Ms("anthropic",X),children:(I.length>0?I:Pc).map(X=>r.jsx(Sn,{value:X.value,children:X.label},X.value))})}),r.jsx(ee.Item,{name:["providers","anthropic","max_tokens"],label:e("settings.providerTab.maxTokensOptional"),extra:e("settings.providerTab.maxTokensHelp"),children:r.jsx(ye,{type:"number",placeholder:"4096",min:1,max:1e5})}),r.jsx(Dt,{dashed:!0}),ns("anthropic",Pc),Ps("anthropic")]});case"gemini":return r.jsxs(r.Fragment,{children:[r.jsx(Ne,{message:e("settings.providerTab.geminiConfigTitle"),description:e("settings.providerTab.geminiConfigDescription"),type:"info",showIcon:!0,style:{marginBottom:16}}),r.jsx(ee.Item,{name:["providers","gemini","api_key"],label:e("settings.providerTab.geminiApiKey"),rules:[{required:!0,message:e("settings.providerTab.geminiApiKeyRequired")}],children:r.jsx(pm,{placeholder:"AIza...",prefix:r.jsx(qi,{})})}),r.jsx(ee.Item,{name:["providers","gemini","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.geminiBaseUrlHelp"),children:r.jsx(ye,{placeholder:"https://generativelanguage.googleapis.com/v1beta"})}),r.jsx(ee.Item,{name:["providers","gemini","model"],label:e("settings.providerTab.defaultModel"),rules:[{required:!0,message:e("settings.providerTab.selectModelRequired")}],extra:Ys("gemini","API"),children:r.jsx(Oe,{placeholder:e("settings.providerTab.selectModel"),allowClear:!0,showSearch:!0,loading:M,disabled:H==="saving",notFoundContent:M?r.jsx(ct,{size:"small"}):null,onDropdownVisibleChange:X=>ss("gemini",X),onChange:X=>Ms("gemini",X),children:(I.length>0?I:Ec).map(X=>r.jsx(Sn,{value:X.value,children:X.label},X.value))})}),r.jsx(Dt,{dashed:!0}),ns("gemini",Ec),Ps("gemini")]});case"copilot":{const X=s.getFieldValue(["providers","copilot","model"]),G=I.length>0?I:X?[{value:X,label:X}]:[];return r.jsxs(r.Fragment,{children:[r.jsx(Ne,{message:e("settings.providerTab.copilotConfigTitle"),description:e("settings.providerTab.copilotConfigDescription"),type:"info",showIcon:!0}),r.jsxs(te,{size:"small",style:{marginTop:16,marginBottom:16},title:e("settings.providerTab.authStatusTitle"),extra:y?r.jsx(ct,{size:"small"}):h!=null&&h.authenticated?r.jsx(fe,{icon:r.jsx(Ws,{}),color:"success",children:e("settings.providerTab.authenticated")}):r.jsx(fe,{icon:r.jsx(Gl,{}),color:"error",children:e("settings.providerTab.notAuthenticated")}),children:[(h==null?void 0:h.message)&&r.jsx(xl,{type:"secondary",style:{marginBottom:16},children:h.message}),r.jsxs(q,{children:[h!=null&&h.authenticated?r.jsx(B,{danger:!0,icon:r.jsx(wx,{}),onClick:re,loading:f,children:e("settings.providerTab.logoutCopilot")}):r.jsx(B,{type:"primary",icon:r.jsx(_x,{}),onClick:Ct,loading:f,children:e("settings.providerTab.authenticateCopilot")}),r.jsx(B,{onClick:et,loading:y,children:e("settings.providerTab.refreshStatus")})]})]}),r.jsx(ee.Item,{name:["providers","copilot","headless_auth"],label:e("settings.providerTab.headlessAuth"),valuePropName:"checked",extra:e("settings.providerTab.headlessAuthHelp"),children:r.jsx(ot,{})}),r.jsx(ee.Item,{name:["providers","copilot","model"],label:e("settings.providerTab.defaultModel"),rules:[{required:!0,message:e("settings.providerTab.selectModelRequired")}],extra:Ys("copilot","backend"),children:r.jsx(Oe,{placeholder:e("settings.providerTab.selectModel"),allowClear:!0,showSearch:!0,loading:M,disabled:H==="saving",notFoundContent:M?r.jsx(ct,{size:"small"}):r.jsx(Ht,{type:"secondary",children:h!=null&&h.authenticated?e("settings.providerTab.noModelsLoaded"):e("settings.providerTab.authFirstThenFetch")}),onDropdownVisibleChange:de=>ss("copilot",de),onChange:de=>Ms("copilot",de),children:G.map(de=>r.jsx(Sn,{value:de.value,children:de.label},de.value))})}),r.jsx(ee.Item,{name:["providers","copilot","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:fm(e),children:r.jsx(Oe,{mode:"tags",placeholder:'e.g. "gpt-5.3-codex", "gpt-5*"',tokenSeparators:[","," ",`
|
|
150
|
+
`," "]})}),r.jsx(Dt,{dashed:!0}),ns("copilot",Xg),Ps("copilot"),r.jsxs(xl,{type:"secondary",children:[e("settings.providerTab.copilotUsageTitle"),r.jsxs("ul",{style:{marginTop:8,marginBottom:0},children:[r.jsx("li",{children:e("settings.providerTab.copilotUsageStep1")}),r.jsx("li",{children:e("settings.providerTab.copilotUsageStep2")}),r.jsx("li",{children:e("settings.providerTab.copilotUsageStep3")})]})]})]})}default:return null}};return r.jsxs(te,{title:e("settings.providerTab.title"),loading:n&&!d,className:"lotus-settings-card",extra:r.jsxs(Ht,{type:"secondary",children:[e("settings.providerTab.currentProvider"),":"," ",r.jsx(Ht,{strong:!0,children:yl[l]})]}),children:[r.jsx(xl,{type:"secondary",children:e("settings.providerTab.description")}),r.jsx(Dt,{}),r.jsxs(ee,{form:s,layout:"vertical",onFinish:st,disabled:n&&!d,children:[r.jsx(ee.Item,{name:"provider",label:e("settings.providerTab.activeProvider"),rules:[{required:!0,message:e("settings.providerTab.selectProviderRequired")}],children:r.jsx(Oe,{"data-testid":"provider-select",onChange:$e,size:"large",children:Object.keys(yl).map(X=>r.jsx(Sn,{value:X,children:yl[X]},X))})}),r.jsx(Dt,{}),Bn(),r.jsx(Dt,{}),r.jsx(q,{size:"middle",children:r.jsx(B,{"data-testid":"save-api-settings",type:"primary",htmlType:"submit",icon:r.jsx(Ti,{}),loading:n||a,size:"large",children:e("settings.providerTab.saveAndApply")})})]}),r.jsx(R0,{open:w,onCancel:()=>C(!1),onComplete:pt,onCopyCode:At,completingAuth:_,copiedUserCode:k,deviceCodeInfo:x,timeRemaining:j,token:t})]})},{Text:ym}=le,$0=({skill:e,disabled:t=!1,busy:s=!1,onToggleDisabled:n})=>{const{t:o}=se(),{token:a}=xe.useToken();return r.jsx(te,{title:r.jsxs(q,{size:a.marginXS,wrap:!0,style:{width:"100%",justifyContent:"space-between"},children:[r.jsxs(q,{size:a.marginXS,wrap:!0,children:[r.jsx("span",{children:e.name}),t&&r.jsx(fe,{color:"default",children:o("components.skillManager.disabledTag")}),e.license&&r.jsxs(fe,{color:"processing",children:["License: ",e.license]})]}),n&&r.jsx(ot,{checked:!t,loading:s,onChange:i=>n(e.id,!i),checkedChildren:o("components.skillManager.switchEnabled"),unCheckedChildren:o("components.skillManager.switchDisabled")})]}),styles:{body:{padding:a.paddingMD}},style:{opacity:t?.72:1},children:r.jsxs(q,{direction:"vertical",size:a.marginXS,style:{width:"100%"},children:[r.jsx(ym,{type:"secondary",children:e.description}),e.compatibility&&r.jsxs(ym,{type:"secondary",children:["Compatibility: ",e.compatibility]}),e.tool_refs.length>0&&r.jsx(q,{size:a.marginXXS,wrap:!0,children:e.tool_refs.map(i=>r.jsx(fe,{style:{background:a.colorFillSecondary,borderColor:a.colorBorderSecondary,color:a.colorText},children:i},i))})]})})},F0=3e4,L0=()=>{const{t:e}=se(),t=ds(T=>T.config),s=ds(T=>T.loadConfig),n=ds(T=>T.saveConfig),[o,a]=m.useState([]),[i,l]=m.useState(!1),[c,d]=m.useState(null),[u,h]=m.useState(null),[p,y]=m.useState(""),[g,f]=m.useState(new Date),b=m.useMemo(()=>{var T;return new Set((((T=t==null?void 0:t.skills)==null?void 0:T.disabled)??[]).map(j=>j.trim()).filter(Boolean))},[t]),x=m.useCallback(async(T=!0)=>{l(!0),d(null);try{const[j]=await Promise.all([Ql.listSkills({includeDisabled:!0},T),s({force:T})]);a(j.skills),f(new Date)}catch(j){const v=j instanceof Error?j.message:e("components.skillManager.loadFailed");d(v)}finally{l(!1)}},[s,e]);m.useEffect(()=>{x(!0);const T=setInterval(()=>{x(!0)},F0);return()=>clearInterval(T)},[x]),m.useEffect(()=>{const T=()=>{x(!0)};return window.addEventListener("focus",T),()=>window.removeEventListener("focus",T)},[x]);const S=m.useCallback(async()=>{await x(!0),pe.success(e("components.skillManager.skillsRefreshed"))},[x,e]);m.useEffect(()=>{c&&(pe.error(c),d(null))},[c]);const w=m.useCallback(async(T,j)=>{var v;h(T);try{const k=await s({force:!0}),E=((v=k==null?void 0:k.skills)==null?void 0:v.disabled)??[],M=Array.from(new Set((j?[...E,T]:E.filter(R=>R!==T)).map(R=>R.trim()).filter(Boolean))).sort();await n({...k??{},skills:{...(k==null?void 0:k.skills)??{},disabled:M}}),pe.success(e("components.skillManager.skillStateSaved"))}catch(k){pe.error(k instanceof Error?k.message:e("components.skillManager.saveFailed"))}finally{h(null)}},[s,n,e]),C=o.filter(T=>{const j=p.trim().toLowerCase();return!(j&&![T.name,T.description,T.license??"",T.compatibility??"",...T.tool_refs].join(" ").toLowerCase().includes(j))}),_=()=>{const j=new Date().getTime()-g.getTime(),v=Math.floor(j/1e3);if(v<5)return e("components.skillManager.justNow");if(v<60)return e("components.skillManager.secondsAgo",{count:v});const k=Math.floor(v/60);return k<60?e("components.skillManager.minutesAgo",{count:k}):g.toLocaleTimeString()};return r.jsx("div",{style:{padding:"24px"},children:r.jsxs(te,{className:"lotus-settings-card",title:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[r.jsx("span",{children:e("components.skillManager.title")}),r.jsx(B,{icon:r.jsx(Cs,{spin:i}),onClick:S,loading:i,size:"small",children:e("components.skillManager.refresh")}),r.jsx("span",{className:"lotus-settings-note",style:{fontSize:"12px",marginLeft:"auto"},children:e("components.skillManager.lastUpdated",{value:_()})})]}),children:[r.jsx("div",{className:"lotus-settings-note",style:{marginBottom:"16px"},children:e("components.skillManager.readOnlyHint")}),r.jsx("div",{className:"lotus-settings-note",style:{marginBottom:"16px"},children:e("components.skillManager.disabledHint")}),r.jsx(zs,{style:{marginBottom:"24px"},children:r.jsx(ye,{placeholder:e("components.skillManager.searchPlaceholder"),prefix:r.jsx(Ho,{}),value:p,onChange:T=>y(T.target.value),allowClear:!0})}),r.jsx(ct,{spinning:i,children:C.length===0?r.jsx(Qt,{description:e(p?"components.skillManager.noMatch":"components.skillManager.noSkillsFound")}):r.jsx(Ge,{grid:{gutter:16,xs:1,sm:2,md:3,lg:3,xl:4},dataSource:C,renderItem:T=>r.jsx(Ge.Item,{children:r.jsx($0,{skill:T,disabled:b.has(T.id),busy:u===T.id,onToggleDisabled:w})})})})]})})},{Title:O0,Text:bl,Paragraph:D0}=le,xm="model_limits",Rc="modelLimitsConfigs",bm="defaultBudgetStrategy",qt=1e3;function vm(e){return[{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5.4-thinking",max_context_tokens:1e6,max_output_tokens:128e3,safety_margin:qt,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:qt,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:qt,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:qt,note:e("settings.modelLimits.defaults.gpt5Mini")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4.1",max_context_tokens:128e3,max_output_tokens:16384,safety_margin:qt,note:e("settings.modelLimits.defaults.gpt41")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4o",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:qt,note:e("settings.modelLimits.defaults.gpt4o")},{vendor:"Google",model_pattern:"gemini-2.5-pro",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:qt,note:e("settings.modelLimits.defaults.gemini25Pro")},{vendor:"Moonshot",model_pattern:"kimi-k2.5",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:qt,note:e("settings.modelLimits.defaults.kimiK25")},{vendor:"Moonshot",model_pattern:"kimi-for-coding",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:qt,note:e("settings.modelLimits.defaults.kimiCoding")},{vendor:"Zhipu",model_pattern:"glm-5",max_context_tokens:2e5,max_output_tokens:128e3,safety_margin:qt,note:e("settings.modelLimits.defaults.glm5")}]}function z0(e){return Array.isArray(e)?Pd(e):[]}function Sm(e,t){if(typeof e!="number"||!Number.isFinite(e))return t;const s=Math.floor(e);return s>0?s:t}function N0(e,t){if(typeof e!="number"||!Number.isFinite(e))return t;const s=Math.floor(e);return s>=0?s:t}function B0(e){if(!e||typeof e!="object")return null;const t=e,s=t.model_pattern??t.model;if(typeof s!="string"||!s.trim())return null;const n=Sm(t.max_context_tokens??t.maxContextTokens,128e3),o=Sm(t.max_output_tokens??t.maxOutputTokens,Math.min(4096,Math.floor(n/4))),a=N0(t.safety_margin??t.safetyMargin,qt);return{vendor:typeof t.vendor=="string"&&t.vendor.trim()?t.vendor.trim():"",model_pattern:s.trim(),max_context_tokens:n,max_output_tokens:o,safety_margin:a,note:typeof t.note=="string"?t.note:""}}function Pd(e){return Array.isArray(e)?e.map(t=>B0(t)).filter(t=>!!t):[]}function W0(){const e=localStorage.getItem(Rc);if(!e)return[];try{const t=JSON.parse(e);return Pd(t)}catch{return[]}}function U0(e){const t=Object.prototype.hasOwnProperty.call(e,xm);return t?{hasModelLimitsKey:t,modelLimits:Pd(e[xm])}:{hasModelLimitsKey:!1,modelLimits:[]}}function q0(e,t){if(e.length===0)return t("settings.modelLimits.validation.atLeastOneRow");const s=new Set;for(const n of e){const o=n.model_pattern.trim();if(!o)return t("settings.modelLimits.validation.modelPatternEmpty");const a=o.toLowerCase();if(s.has(a))return t("settings.modelLimits.validation.duplicateModelPattern",{pattern:o});if(s.add(a),n.max_context_tokens<1e3)return t("settings.modelLimits.validation.contextWindowMin",{pattern:o});if(n.max_output_tokens<1)return t("settings.modelLimits.validation.maxOutputMin",{pattern:o});if(n.max_output_tokens>n.max_context_tokens)return t("settings.modelLimits.validation.maxOutputExceedsContext",{pattern:o});if(n.safety_margin<0)return t("settings.modelLimits.validation.safetyMarginNegative",{pattern:o});if(n.safety_margin>=n.max_context_tokens)return t("settings.modelLimits.validation.safetyMarginTooLarge",{pattern:o})}return null}const H0=()=>{const{t:e}=se(),[t,s]=m.useState(()=>vm(e)),[n,o]=m.useState(!1),[a,i]=pe.useMessage(),l=m.useCallback((f,b)=>{s(x=>x.map((S,w)=>w===f?{...S,...b}:S))},[]),c=m.useCallback(()=>{s(f=>[...f,{vendor:"",model_pattern:"",max_context_tokens:128e3,max_output_tokens:4096,safety_margin:qt,note:""}])},[]),d=m.useCallback(f=>{s(b=>b.filter((x,S)=>S!==f))},[]),u=m.useCallback(async()=>{const f=vm(e),b=await Ye.getModelLimitDefaults(),x=z0(b.model_limits);return x.length>0?x:f},[e]),h=m.useCallback(async()=>{o(!0);try{const f=await Ye.getBambooConfig(),{hasModelLimitsKey:b,modelLimits:x}=U0(f);if(x.length>0){s(x);return}if(b){s(await u());return}const S=W0();if(S.length>0){await Ye.setBambooConfig({model_limits:S}),localStorage.removeItem(Rc),localStorage.removeItem(bm),s(S),a.info(e("settings.modelLimits.migratedFromLocalStorage"));return}s(await u())}catch(f){console.error("Failed to load model limits settings:",f),a.error(e("settings.modelLimits.loadFailed")),s(await u())}finally{o(!1)}},[u,a,e]);m.useEffect(()=>{h()},[h]);const p=async()=>{const f=q0(t,e);if(f){a.error(f);return}o(!0);try{await Ye.setBambooConfig({model_limits:t}),a.success(e("settings.modelLimits.saveSuccess"))}catch(b){console.error("Failed to save model limits settings:",b),a.error(e("settings.modelLimits.saveFailed"))}finally{o(!1)}},y=async()=>{o(!0);try{const f=await u();await Ye.setBambooConfig({model_limits:f}),s(f),localStorage.removeItem(Rc),localStorage.removeItem(bm),a.success(e("settings.modelLimits.resetSuccess"))}catch(f){console.error("Failed to reset model limits settings:",f),a.error(e("settings.modelLimits.resetFailed"))}finally{o(!1)}},g=m.useMemo(()=>[{title:e("settings.modelLimits.columns.vendor"),dataIndex:"vendor",key:"vendor",width:170,render:(f,b,x)=>r.jsx(ye,{value:f,placeholder:e("settings.modelLimits.placeholders.vendor"),onChange:S=>l(x,{vendor:S.target.value})})},{title:e("settings.modelLimits.columns.model"),dataIndex:"model_pattern",key:"model_pattern",width:220,render:(f,b,x)=>r.jsx(ye,{value:f,placeholder:e("settings.modelLimits.placeholders.model"),onChange:S=>l(x,{model_pattern:S.target.value})})},{title:e("settings.modelLimits.columns.contextWindow"),dataIndex:"max_context_tokens",key:"max_context_tokens",width:180,render:(f,b,x)=>r.jsx(Tt,{value:f,onChange:S=>l(x,{max_context_tokens:Math.max(1e3,Number(S)||128e3)}),min:1e3,max:2e6,step:1e3,style:{width:"100%"}})},{title:e("settings.modelLimits.columns.maxOutput"),dataIndex:"max_output_tokens",key:"max_output_tokens",width:160,render:(f,b,x)=>r.jsx(Tt,{value:f,onChange:S=>l(x,{max_output_tokens:Math.max(1,Number(S)||4096)}),min:1,max:2e6,step:256,style:{width:"100%"}})},{title:e("settings.modelLimits.columns.notes"),dataIndex:"note",key:"note",width:240,render:(f,b,x)=>r.jsx(ye,{value:f,placeholder:e("settings.modelLimits.placeholders.optional"),onChange:S=>l(x,{note:S.target.value})})},{title:e("settings.modelLimits.columns.actions"),key:"actions",width:100,render:(f,b,x)=>r.jsx(B,{danger:!0,size:"small",onClick:()=>d(x),children:e("settings.modelLimits.actions.remove")})}],[d,e,l]);return r.jsxs("div",{className:"model-limits-settings",children:[i,r.jsxs(te,{children:[r.jsx(O0,{level:4,children:e("settings.modelLimits.title")}),r.jsxs(D0,{type:"secondary",children:[e("settings.modelLimits.descriptionPrefix")," ",r.jsx(bl,{code:!0,children:"config.json"})," ",e("settings.modelLimits.descriptionSuffix")]}),r.jsx(Dt,{}),r.jsxs(q,{direction:"vertical",size:"small",style:{width:"100%"},children:[r.jsx(bl,{strong:!0,children:e("settings.modelLimits.defaultsTitle")}),r.jsx(bl,{type:"secondary",children:e("settings.modelLimits.defaultsDescription")})]}),r.jsx(dn,{dataSource:t,columns:g,rowKey:(f,b)=>`${f.model_pattern}-${b}`,pagination:!1,size:"small",style:{margin:"16px 0"},scroll:{x:1150}}),r.jsxs(q,{children:[r.jsx(B,{onClick:c,children:e("settings.modelLimits.actions.addRow")}),r.jsx(B,{type:"primary",icon:r.jsx(Ti,{}),onClick:()=>void p(),loading:n,children:e("settings.modelLimits.actions.save")}),r.jsx(B,{icon:r.jsx(Cs,{}),onClick:()=>void y(),loading:n,children:e("settings.modelLimits.actions.resetToDefaults")}),r.jsx(B,{onClick:()=>void h(),loading:n,children:e("settings.modelLimits.actions.reload")})]})]})]})},Ac="lotus_experience_mode_v1",Vg=new Set(["skills","hooks","masking","env-vars","metrics","sessions","config"]);function wm(){try{const e=localStorage.getItem(Ac);if(e==="simple"||e==="advanced")return e}catch{}return"advanced"}const gi=un(e=>({mode:wm(),isAdvanced:wm()==="advanced",setMode:t=>{try{localStorage.setItem(Ac,t)}catch{}e({mode:t,isAdvanced:t==="advanced"})},toggleMode:()=>e(t=>{const s=t.mode==="simple"?"advanced":"simple";try{localStorage.setItem(Ac,s)}catch{}return{mode:s,isAdvanced:s==="advanced"}})})),{Text:vl}=le,{useToken:Y0}=xe,X0="bamboo_dark_mode",V0=({themeMode:e,onThemeModeChange:t,locale:s,onLocaleChange:n,onBack:o})=>{const{t:a}=se(),{token:i}=Y0(),{deleteAllChats:l,autoGenerateTitles:c,setAutoGenerateTitlesPreference:d,isUpdatingAutoTitlePreference:u}=jw(),[h,p]=m.useState(!1),[y,g]=pe.useMessage(),[f,b]=m.useState(""),[x,S]=m.useState(yc()),[w,C]=m.useState(bc()),[_,T]=m.useState(pi()),v=Rt(D=>D.currentProvider)==="copilot",k=qs(D=>D.activeTabKey),E=qs(D=>D.setActiveTabKey),M=gi(D=>D.isAdvanced),R=i.paddingSM,I=(D,U)=>({key:D,label:r.jsx(vl,{type:"secondary",style:{fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em",cursor:"default",userSelect:"none"},children:U}),disabled:!0,children:null}),P=(D,U)=>r.jsx("span",{"data-testid":`settings-tab-${D}`,children:U}),L=()=>{localStorage.clear(),y.success(a("settings.notifications.localStorageCleared"))},O=async()=>{p(!0);try{await l(),await Ye.resetSetupStatus(),await Ye.resetBambooConfig(),localStorage.clear(),y.success(a("settings.notifications.resetSuccessReloading")),setTimeout(()=>{window.location.reload()},1500)}catch(D){console.error("Failed to reset application:",D),y.error(D instanceof Error?D.message:a("settings.notifications.resetFailed")),p(!1)}},A=async D=>{try{await d(D),y.success(a(D?"settings.notifications.autoTitleEnabled":"settings.notifications.autoTitleDisabled"))}catch{y.error(a("settings.notifications.autoTitleUpdateFailed"))}},$=()=>{_w(f),y.success(a("settings.notifications.promptEnhancementSaved"))},W=D=>{S(D),uw(D)},F=D=>{C(D),pw(D)},H=D=>{T(D),xw(D)};return m.useEffect(()=>{b(Lg()),S(yc()),C(bc()),T(pi())},[]),r.jsxs(K,{vertical:!0,role:"region","aria-label":a("settings.page.title"),style:{height:"100vh",overflow:"hidden",background:i.colorBgContainer},children:[g,r.jsxs(K,{align:"center",justify:"space-between",style:{padding:i.padding,paddingTop:i.padding+R,borderBottom:`1px solid ${i.colorBorderSecondary}`},children:[r.jsxs(K,{align:"center",gap:i.marginSM,children:[r.jsx(B,{icon:r.jsx(Tx,{}),onClick:o,"aria-label":a("settings.page.back"),children:a("settings.page.back")}),r.jsx(vl,{strong:!0,"data-testid":"settings-page-title",children:a("settings.page.title")})]}),r.jsxs(vl,{type:"secondary","data-testid":"settings-page-version",children:[a("settings.appTab.runningVersion","Running version"),": v",nd]})]}),r.jsx(nr.Content,{style:{flex:1,minHeight:0,overflow:"auto",padding:i.padding},children:r.jsx(ei,{tabPosition:"left",activeKey:k,onChange:D=>E(D),items:[I("group-ai",a("settings.page.groups.ai")),{key:"provider",label:P("provider",a("settings.page.tabs.provider")),children:r.jsx(I0,{})},{key:"model-limits",label:P("model-limits",a("settings.page.tabs.modelLimits")),children:r.jsx(H0,{})},{key:"prompts",label:P("prompts",a("settings.page.tabs.prompts")),children:r.jsx(Uw,{promptEnhancement:f,onPromptEnhancementChange:b,mermaidEnhancementEnabled:x,taskEnhancementEnabled:w,showCopilotConclusionWithOptionsEnhancement:v,copilotConclusionWithOptionsEnhancementEnabled:_,onMermaidToggle:W,onTaskToggle:F,onCopilotConclusionWithOptionsToggle:H,onSaveEnhancement:$})},I("group-tools",a("settings.page.groups.toolsAndExtensions")),{key:"skills",label:P("skills",a("settings.page.tabs.skills")),children:r.jsx(L0,{})},{key:"mcp",label:P("mcp",a("settings.page.tabs.mcp")),children:r.jsx(W_,{})},{key:"workflows",label:P("workflows",a("settings.page.tabs.workflows")),children:r.jsx(t_,{})},{key:"hooks",label:P("hooks",a("settings.page.tabs.hooks")),children:r.jsx(j0,{})},I("group-security",a("settings.page.groups.securityAndPrivacy")),{key:"masking",label:P("masking",a("settings.page.tabs.masking")),children:r.jsx(Vw,{})},{key:"env-vars",label:P("env-vars",a("settings.page.tabs.envVars")),children:r.jsx(Jw,{})},I("group-monitoring",a("settings.page.groups.monitoring")),{key:"metrics",label:P("metrics",a("settings.page.tabs.metrics")),children:r.jsx(_0,{})},{key:"sessions",label:P("sessions",a("settings.page.tabs.sessions")),children:r.jsx(P0,{})},I("group-system",a("settings.page.groups.system")),{key:"config",label:P("config",a("settings.page.tabs.config")),children:r.jsx(Fw,{msgApi:y,locale:s,onLocaleChange:n})},{key:"schedules",label:P("schedules",a("settings.page.tabs.schedules")),children:r.jsx(M0,{})},{key:"app",label:P("app",a("settings.page.tabs.app")),children:r.jsx(Hw,{autoGenerateTitles:c,isUpdatingAutoTitlePreference:u,onAutoTitleToggle:A,themeMode:e,onThemeModeChange:t,onClearLocalStorage:L,onResetApp:O,isResetting:h,darkModeKey:X0})}].filter(D=>!(!M&&D.key&&Vg.has(D.key)||!M&&(D.key==="group-security"||D.key==="group-monitoring")))})})]})},{Text:_m,Paragraph:K0}=le;class yi extends m.Component{constructor(s){super(s);We(this,"handleReset",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,n){var a,i;const o=this.props.name??"ErrorBoundary";console.error(`[${o}] Uncaught error:`,s,n),(i=(a=this.props).onError)==null||i.call(a,s,n)}render(){if(!this.state.hasError)return this.props.children;const{fallback:s}=this.props,n=this.state.error;return typeof s=="function"?s(n,this.handleReset):s!==void 0?s:r.jsx(G0,{error:n,onReset:this.handleReset})}}const G0=({error:e,onReset:t})=>{const{token:s}=xe.useToken(),[n,o]=dt.useState(!1);return r.jsxs("div",{role:"alert",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:s.paddingLG,minHeight:200,textAlign:"center"},children:[r.jsx(Mp,{style:{fontSize:36,color:s.colorWarning}}),r.jsx(_m,{strong:!0,style:{fontSize:16},children:"Something went wrong"}),r.jsx(_m,{type:"secondary",style:{maxWidth:420},children:"An unexpected error occurred in this section. You can try again or reload the page if the issue persists."}),r.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[r.jsx(B,{type:"primary",icon:r.jsx(Cs,{}),onClick:t,"aria-label":"Retry rendering this section",children:"Try Again"}),r.jsx(B,{type:"text",size:"small",onClick:()=>o(a=>!a),"aria-expanded":n,"aria-label":"Toggle error details",children:n?"Hide Details":"Show Details"})]}),n&&r.jsxs(K0,{code:!0,copyable:!0,style:{maxWidth:560,maxHeight:200,overflow:"auto",fontSize:12,textAlign:"left",marginTop:8,background:s.colorFillTertiary,padding:s.paddingSM,borderRadius:s.borderRadius},children:[e.message,e.stack?`
|
|
151
|
+
|
|
152
|
+
${e.stack}`:""]})]})},J0=15e3,Q0=()=>{const e=z(a=>a.chats),t=z(a=>a.updateSession),{generateChatTitle:s}=Cd({chats:e,updateSession:t}),n=m.useRef(new Map),o=m.useRef(new Map);return m.useEffect(()=>{e.forEach(a=>{const i=a.id,l=a.messages;if(l.length===0)return;const c=l[l.length-1];if(c.role!=="assistant")return;const d=n.current.get(i);if(c.id===d)return;const u=o.current.get(i);u&&u.messageId===c.id&&Date.now()-u.at<J0||s(i).then(h=>{h&&(n.current.set(i,c.id),o.current.delete(i))}).catch(h=>{o.current.set(i,{messageId:c.id,at:Date.now()}),console.warn("Auto title generation failed for chat",i,":",h)})})},[e,s]),m.useEffect(()=>{const a=new Set(e.map(l=>l.id));Array.from(n.current.keys()).forEach(l=>{a.has(l)||(n.current.delete(l),o.current.delete(l))})},[e]),null},Z0=()=>{const{token:e}=xe.useToken(),t=zi(),s=m.useRef("");m.useEffect(()=>{const n=eT(e.colorBgContainer),o=`${n}-${t.theme}-${JSON.stringify(t.themeVariables)}`;if(s.current===o)return;s.current=o;let a=t.theme;(t.theme==="default"||t.theme==="neutral")&&(a=n?"dark":t.theme),Jc.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 eT(e){if(e.startsWith("#")){const s=e.slice(1),n=parseInt(s.substr(0,2),16),o=parseInt(s.substr(2,2),16),a=parseInt(s.substr(4,2),16);return(.299*n+.587*o+.114*a)/255<.5}const t=e.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(t){const s=parseInt(t[1]),n=parseInt(t[2]),o=parseInt(t[3]);return(.299*s+.587*n+.114*o)/255<.5}return!1}Jc.initialize({startOnLoad:!1,theme:"dark",securityLevel:"loose",suppressErrorRendering:!0});Jc.parseError=function(e){console.warn("Mermaid parse error (handled gracefully):",e)};const Tm=new Map,tT=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,sT=e=>e.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),nT=e=>(tT.test(e)?sT(e):e).replace(/\[([\s\S]*?)\]/g,(s,n)=>{const o=String(n),a=/\r?\n/.test(o),i=/[()]/.test(o),l=/@/.test(o);if(!a&&!i&&!l)return s;const c=o.trim(),d=c.startsWith("(")&&c.endsWith(")")&&c.length>=2;let u=o;return a&&(u=u.replace(/\r?\n/g,"<br/>")),i&&!d&&(u=u.replace(/\(/g,"(").replace(/\)/g,")")),l&&(u=u.replace(/@/g,"@")),u===o?s:`[${u}]`}),rT=200,Ss=new Map,Ga=new Map;let Sl=null;const oT=e=>{const s=new DOMParser().parseFromString(e,"image/svg+xml");return Array.from(s.querySelectorAll("rect")).reduce((o,a)=>{const i=Number(a.getAttribute("width"));return Number.isFinite(i)&&i<0?o+1:o},0)};async function aT(){Sl||(Sl=kt(()=>import("./vendor-mermaid-BD0lXko3.js").then(t=>t.bd),__vite__mapDeps([7,1,2,3,6]),import.meta.url));const e=await Sl;return e.default??e}function iT(e,t){if(Ss.has(e)&&Ss.delete(e),Ss.set(e,t),Ss.size>rT){const s=Ss.keys().next().value;s&&Ss.delete(s)}}function Ja(e){const t=Ss.get(e);return t?(Ss.delete(e),Ss.set(e,t),t):null}function km(){Ss.clear(),Ga.clear()}function lT(e,t){const s=Ja(e);if(s)return Promise.resolve(s);const n=Ga.get(e);if(n)return n;const o=(async()=>{var S,w;const a=await aT();await a.parse(t);const i=`mermaid-${e}`,l=document.createElement("div"),c=Math.max(1600,window.innerWidth||0,((S=document.documentElement)==null?void 0:S.clientWidth)||0);l.style.cssText=["position:absolute","left:-9999px","top:-9999px",`width:${c}px`,`min-width:${c}px`,"visibility:hidden","pointer-events:none","overflow:visible"].join(";"),document.body.appendChild(l);let d;try{d=await a.render(i,t,l)}finally{document.body.removeChild(l)}const u=typeof d=="object"&&"svg"in d?d.svg:String(d),h=oT(u);if(h>0)throw new Error(`Mermaid rendered invalid SVG (${h} rect widths < 0)`);const g=new DOMParser().parseFromString(u,"image/svg+xml").querySelector("svg");let f=800,b=300;if(g){const C=g.getAttribute("viewBox");if(C){const _=C.split(/\s+/).map(Number);_.length===4&&(f=_[2]||800,b=_[3]||300)}if(f===800&&b===300){const _=document.createElement("div");_.style.cssText="position:absolute;visibility:hidden;width:800px;",_.innerHTML=u,document.body.appendChild(_);const T=(w=_.querySelector("svg"))==null?void 0:w.getBoundingClientRect();T&&(f=T.width,b=T.height),document.body.removeChild(_)}}const x={svg:u,width:f,height:b};return iT(e,x),x})().finally(()=>{Ga.delete(e)});return Ga.set(e,o),o}const cT=e=>{const t=e;return(t==null?void 0:t.name)==="AbortError"||(t==null?void 0:t.code)===20},Cm=220,jm=e=>{const t=e.replace(/\s+/g," ").trim();return t.length<=Cm?t:`${t.slice(0,Cm)}...`},dT=e=>e==="pending"||e==="in_progress"||e==="completed"||e==="blocked";function uT(){const e=z(v=>v.processingChats),t=z(v=>v.addMessage),s=z(v=>v.setSessionProcessing),n=z(v=>v.updateTokenUsage),o=z(v=>v.setTruncationInfo),a=z(v=>v.updateSession),i=z(v=>v.updateMessage),l=z(v=>v.setTaskList),c=z(v=>v.updateTaskListDelta),d=z(v=>v.setEvaluationState),u=z(v=>v.upsertSubSessionProgress),h=z(v=>v.refreshChats),p=m.useRef(new hs),y=m.useRef(new Map),g=m.useRef(new Map),f=m.useRef(new Map),b=m.useRef(new Map),x=m.useRef(new Map),S=m.useRef(new Set),w=m.useRef(new Map),C=m.useCallback(v=>{const k=w.current.get(v);k!=null&&k.timer&&clearTimeout(k.timer),w.current.delete(v)},[]),_=m.useCallback((v,k)=>{C(v),S.current.delete(v);const E=y.current.get(v);if(!E)return;y.current.delete(v),E.controller.abort();const M=g.current.get(E.sessionId);M?(k!=null&&k.clearDraft&&(Fe.clear(M.sessionId,M.messageId),Fe.clear(M.sessionId,M.reasoningMessageId),Fe.clear(M.sessionId,M.statusMessageId)),g.current.delete(E.sessionId)):k!=null&&k.clearDraft&&(Fe.clear(v,`streaming-${v}`),Fe.clear(v,`streaming-reasoning-${v}`),Fe.clear(v,`streaming-status-${v}`))},[C]),T=m.useCallback(v=>{C(v);const k=new AbortController;y.current.set(v,{sessionId:v,controller:k});const E=`streaming-${v}`,M=`streaming-reasoning-${v}`,R=`streaming-status-${v}`,I=Fe.getLatest(E),P=Fe.getLatest(M),L=Fe.getLatest(R);g.current.set(v,{sessionId:v,messageId:E,content:I??"",reasoningMessageId:M,reasoningContent:P??"",statusMessageId:R,status:L??""}),I===null&&Fe.publish({sessionId:v,messageId:E,content:""});const O=()=>{const A=w.current.get(v),$=(A==null?void 0:A.attempt)??0,W=Math.min(5e3,250*Math.pow(2,$));_(v,{clearDraft:!1});const F=setTimeout(()=>{var U;if(w.current.delete(v),!z.getState().processingChats.has(v))return;const H=z.getState().chats.find(Q=>Q.id===v),D=(U=H==null?void 0:H.id)==null?void 0:U.trim();D&&T(D)},W);w.current.set(v,{attempt:$+1,timer:F})};p.current.subscribeToEvents(v,{onToken:A=>{const $=g.current.get(v);$&&($.status&&($.status="",Fe.clear($.sessionId,$.statusMessageId)),$.content+=A,Fe.publish({sessionId:$.sessionId,messageId:$.messageId,content:$.content}))},onReasoningToken:A=>{const $=g.current.get(v);$&&($.status&&($.status="",Fe.clear($.sessionId,$.statusMessageId)),$.reasoningContent+=A,Fe.publish({sessionId:$.sessionId,messageId:$.reasoningMessageId,content:$.reasoningContent}))},onToolStart:(A,$,W)=>{var he,ve;const F=g.current.get(v),H=(F==null?void 0:F.content)||"",D=(F==null?void 0:F.reasoningContent)||"",U=H.trim().length>0,Q=D.trim().length>0;if(U||Q){const ue=z.getState().chats.find(Ze=>Ze.id===v),ie=(he=ue==null?void 0:ue.messages)==null?void 0:he[ue.messages.length-1],Re=typeof((ve=ie==null?void 0:ie.metadata)==null?void 0:ve.reasoning)=="string"?ie.metadata.reasoning:"";(ie==null?void 0:ie.role)==="assistant"&&(ie==null?void 0:ie.type)==="text"&&typeof(ie==null?void 0:ie.content)=="string"&&ie.content===H&&Re===D||t(v,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:H,createdAt:new Date().toISOString(),metadata:{sessionId:v,model:"agent",...Q?{reasoning:D}:{}}}),F&&(F.content="",F.reasoningContent="",F.status&&(F.status="",Fe.clear(F.sessionId,F.statusMessageId)),Fe.publish({sessionId:F.sessionId,messageId:F.messageId,content:""}),Fe.publish({sessionId:F.sessionId,messageId:F.reasoningMessageId,content:""}))}b.current.set(A,$);const Y=crypto.randomUUID();x.current.set(A,Y),t(v,{id:Y,role:"assistant",type:"tool_call",toolCalls:[{toolCallId:A,toolName:$,parameters:W||{},streamingOutput:""}],metadata:{},createdAt:new Date().toISOString()})},onToolToken:(A,$)=>{const W=x.current.get(A);if(!W)return;const F=z.getState().chats.find(U=>U.id===v);if(!F)return;const H=F==null?void 0:F.messages.find(U=>U.id===W);if(!H||!("type"in H)||H.type!=="tool_call"||!("toolCalls"in H)||!Array.isArray(H.toolCalls))return;const D=H.toolCalls.map(U=>{if(U.toolCallId!==A)return U;const Q=(U.streamingOutput||"")+($||"");return{...U,streamingOutput:Q}});i(v,W,{toolCalls:D})},onToolComplete:(A,$)=>{const W=b.current.get(A)||"unknown";b.current.delete(A),x.current.delete(A);const F=($==null?void 0:$.display_preference)||"Default";t(v,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:W,toolCallId:A,result:{tool_name:W,result:($==null?void 0:$.result)??"",display_preference:F},isError:!($!=null&&$.success),createdAt:new Date().toISOString()})},onToolError:(A,$)=>{b.current.delete(A),x.current.delete(A),t(v,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:"unknown",toolCallId:A,result:{tool_name:"unknown",result:$,display_preference:"Default"},isError:!0,createdAt:new Date().toISOString()})},onToolLifecycle:(A,$,W,F,H)=>{if(W==="finished"||W==="error"){const D=x.current.get(A);D&&i(v,D,{metadata:{elapsed_ms:F,is_mutating:H}})}},onContextCompressionStatus:(A,$)=>{const W=g.current.get(v);if(W){if($==="started"){W.status="context_compacting",Fe.publish({sessionId:W.sessionId,messageId:W.statusMessageId,content:W.status});return}W.status&&(W.status=""),Fe.clear(W.sessionId,W.statusMessageId)}},onTokenBudgetUpdated:A=>{const $=typeof A.max_context_tokens=="number"&&A.max_context_tokens>0?A.max_context_tokens:void 0,W={systemTokens:A.system_tokens,summaryTokens:A.summary_tokens,windowTokens:A.window_tokens,totalTokens:A.total_tokens,budgetLimit:A.budget_limit,...$?{maxContextTokens:$}:{},...typeof A.prompt_cached_tool_outputs=="number"&&A.prompt_cached_tool_outputs>0?{promptCachedToolOutputs:A.prompt_cached_tool_outputs}:{}};n(v,W),o(v,A.truncation_occurred,A.segments_removed);const F=z.getState().chats.find(H=>H.id===v);F&&a(v,{config:{...F.config,tokenUsage:W,truncationOccurred:A.truncation_occurred,segmentsRemoved:A.segments_removed}})},onContextSummarized:A=>{const $=g.current.get(v);$!=null&&$.status&&($.status="",Fe.clear($.sessionId,$.statusMessageId)),pe.info(`Conversation summarized: ${A.messages_summarized} messages compressed, saved ${A.tokens_saved.toLocaleString()} tokens`,5)},onTaskListUpdated:A=>{A.session_id&&l(A.session_id,A)},onTaskListItemProgress:A=>{A.session_id&&c(A.session_id,A)},onTaskListCompleted:(A,$,W)=>{pe.success(`All tasks completed! Total rounds: ${$}, Tool calls: ${W}`,3)},onTaskEvaluationStarted:(A,$)=>{d(A,{isEvaluating:!0,reasoning:null,timestamp:Date.now()}),pe.info(`Evaluating ${$} task(s)...`,2)},onTaskEvaluationCompleted:(A,$,W)=>{const F=jm(W);d(A,{isEvaluating:!1,reasoning:$>0?F:null,timestamp:Date.now()}),$>0?pe.success(`Evaluation complete: ${$} task(s) updated.`,3):pe.info("Evaluation complete: No updates needed",2)},onComplete:()=>{const A=k;(async()=>{var Y,he,ve;const $=()=>{const ue=y.current.get(v);return ue!=null&&ue.controller!==A};if($())return;const W=g.current.get(v),F=(W==null?void 0:W.content)||"",H=(W==null?void 0:W.reasoningContent)||"",D=F.trim().length>0,U=H.trim().length>0;if(D||U){const ue=z.getState().chats.find(Ze=>Ze.id===v),ie=(Y=ue==null?void 0:ue.messages)==null?void 0:Y[ue.messages.length-1],Re=typeof((he=ie==null?void 0:ie.metadata)==null?void 0:he.reasoning)=="string"?ie.metadata.reasoning:"";(ie==null?void 0:ie.role)==="assistant"&&(ie==null?void 0:ie.type)==="text"&&typeof(ie==null?void 0:ie.content)=="string"&&ie.content===F&&Re===H||await t(v,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:F,createdAt:new Date().toISOString(),metadata:{sessionId:v,model:"agent",...U?{reasoning:H}:{}}})}if($()||(await z.getState().loadChatHistory(v,{mode:"monotonic",retries:4,retryDelayMs:200,waitForAssistant:!0}),$()))return;if(U){const ue=z.getState().chats.find(Le=>Le.id===v),ie=[...(ue==null?void 0:ue.messages)||[]].reverse().find(Le=>(Le==null?void 0:Le.role)==="assistant"&&(Le==null?void 0:Le.type)==="text"),Re=typeof((ve=ie==null?void 0:ie.metadata)==null?void 0:ve.reasoning)=="string"&&ie.metadata.reasoning.trim().length>0;ie!=null&&ie.id&&!Re&&i(v,ie.id,{metadata:{...ie.metadata||{},reasoning:H}})}if($())return;const Q=f.current.get(v)??{children:new Set};if(f.current.set(v,{children:new Set(Q.children),parentDone:!0}),Q.children.size===0)_(v,{clearDraft:!0}),s(v,!1);else{const ue=y.current.get(v);ue&&(Fe.clear(v,`streaming-${v}`),Fe.clear(v,`streaming-reasoning-${v}`),Fe.clear(v,`streaming-status-${v}`),g.current.delete(ue.sessionId))}})()},onError:async A=>{const $=g.current.get(v);$!=null&&$.status&&($.status="",Fe.clear($.sessionId,$.statusMessageId));const W=vc(A)?Sc(A):A;await t(v,{id:`error-${Date.now()}`,role:"assistant",type:"text",content:`❌ **Error**: ${W}`,createdAt:new Date().toISOString(),finishReason:"error"});const F=f.current.get(v)??{children:new Set};f.current.set(v,{children:new Set(F.children),parentDone:!0}),F.children.size===0&&(_(v,{clearDraft:!0}),s(v,!1))},onSubSessionStarted:(A,$,W)=>{const F=f.current.get(A)??{children:new Set,parentDone:!1},H=new Set(F.children);H.add($),f.current.set(A,{children:H,parentDone:F.parentDone}),s(v,!0),u(A,$,{title:W,status:"pending",lastEventAt:new Date().toISOString()}),h()},onSubSessionEvent:(A,$,W)=>{var F,H,D;if(W.type==="task_list_updated"&&W.task_list){const U=W.task_list.session_id||A;l(U,W.task_list);return}if(W.type==="task_list_item_progress"){const U=W.session_id||A;typeof W.item_id=="string"&&dT(W.status)&&typeof W.tool_calls_count=="number"&&typeof W.version=="number"&&c(U,{session_id:U,item_id:W.item_id,status:W.status,tool_calls_count:W.tool_calls_count,version:W.version});return}if(W.type==="task_evaluation_started"){const U=W.session_id||A;d(U,{isEvaluating:!0,reasoning:null,timestamp:Date.now()});return}if(W.type==="task_evaluation_completed"){const U=W.session_id||A,Q=W.updates_count??0;d(U,{isEvaluating:!1,reasoning:Q>0?jm(W.reasoning??""):null,timestamp:Date.now()});return}if(W.type==="token"&&typeof W.content=="string"){const Q=((((D=(H=(F=z.getState().subSessionsByParent)==null?void 0:F[A])==null?void 0:H[$])==null?void 0:D.outputPreview)||"")+W.content).slice(-2e3);u(A,$,{status:"running",outputPreview:Q,lastEventAt:new Date().toISOString()})}else u(A,$,{status:"running",lastEventAt:new Date().toISOString()})},onSubSessionHeartbeat:(A,$,W)=>{u(A,$,{status:"running",lastHeartbeatAt:W})},onSubSessionCompleted:(A,$,W,F)=>{const H=f.current.get(A)??{children:new Set,parentDone:!1},D=new Set(H.children);D.delete($),f.current.set(A,{children:D,parentDone:H.parentDone}),u(A,$,{status:W,error:F,lastEventAt:new Date().toISOString()}),H.parentDone&&D.size===0&&(_(v,{clearDraft:!0}),s(v,!1)),h()}},k).then(()=>{if(k.signal.aborted)return;const A=y.current.get(v);if(A&&A.controller!==k)return;if(!z.getState().processingChats.has(v)){_(v,{clearDraft:!0});return}O()}).catch(A=>{if(!k.signal.aborted){if(cT(A)){if(!z.getState().processingChats.has(v)){_(v,{clearDraft:!0});return}O();return}console.error("[useAgentEventSubscription] Subscription error:",A),_(v,{clearDraft:!0}),s(v,!1)}})},[t,_,C,h,d,s,l,o,i,a,c,n,u]),j=m.useCallback(v=>{const k=v.trim();if(!k)return;S.current.delete(k);const E=y.current.get(k);(E==null?void 0:E.sessionId)===k&&!E.controller.signal.aborted||(E&&_(k,{clearDraft:!1}),T(k))},[_,T]);m.useEffect(()=>{e.forEach(v=>j(v));for(const v of Array.from(y.current.keys()))e.has(v)||_(v,{clearDraft:!0});for(const v of Array.from(S.current))e.has(v)||S.current.delete(v)},[e,j,_]),m.useEffect(()=>z.subscribe(v=>v.chats,()=>{if(S.current.size!==0)for(const v of Array.from(S.current)){if(!z.getState().processingChats.has(v)){S.current.delete(v);continue}j(v)}}),[j]),m.useEffect(()=>{const v=y.current;return()=>{const k=Array.from(v.keys());for(const E of k)_(E,{clearDraft:!0})}},[_])}const Kg=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_result",mT=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_call",hT=e=>e.role==="assistant"&&"type"in e&&e.type==="workflow_result",pT=e=>e.role==="user"&&"type"in e&&e.type==="file_reference",fT=e=>e.role==="assistant"&&"type"in e&&e.type==="task_list",xi=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/bmp"],Mm=10*1024*1024,gT=2048,yT=2048,xT=.82,bT=512*1024,vT=e=>xi.includes(e.type)?e.size>Mm?{isValid:!1,error:`Image size too large: ${(e.size/1024/1024).toFixed(2)}MB. Maximum size: ${Mm/1024/1024}MB`}:{isValid:!0}:{isValid:!1,error:`Unsupported image type: ${e.type}. Supported types: ${xi.join(", ")}`},ST=e=>new Promise((t,s)=>{const n=new Image;n.onload=()=>t(n),n.onerror=()=>s(new Error("Failed to load image")),n.src=e}),Pm=e=>new Promise((t,s)=>{const n=new FileReader;n.onload=()=>{typeof n.result=="string"?t(n.result):s(new Error("Failed to convert file to base64"))},n.onerror=()=>s(new Error("Failed to read file")),n.readAsDataURL(e)}),wT=e=>URL.createObjectURL(e),_T=(e,t,s,n)=>{let{width:o,height:a}=t;if(o>s||a>n){const l=o/a;o>a?(o=s,a=Math.round(o/l)):(a=n,o=Math.round(a*l))}e.width=o,e.height=a;const i=e.getContext("2d");i&&(i.fillStyle="#ffffff",i.fillRect(0,0,o,a),i.drawImage(t,0,0,o,a))},TT=async(e,t)=>{const s=await ST(e),n=document.createElement("canvas");return _T(n,s,gT,yT),jT(n,t)},kT=async e=>{const t=vT(e);if(!t.isValid)throw new Error(t.error);const s=wT(e);try{let n;if(e.type==="image/gif"||e.size<bT)n=await Pm(e);else try{n=await TT(s,xT)}catch(a){console.warn("[imageUtils] Failed to re-encode image, using original:",a),n=await Pm(e)}const o=`img_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return{file:e,base64:n,preview:s,id:o,name:e.name,size:e.size,type:e.type}}catch(n){throw Gg(s),n}},CT=async e=>{const t=Array.from(e),s=[];for(const n of t)try{const o=await kT(n);s.push(o)}catch(o){console.error(`Failed to process image ${n.name}:`,o)}return s},jT=(e,t=.8)=>e.toDataURL("image/jpeg",t),Gg=e=>{e.startsWith("blob:")&&URL.revokeObjectURL(e)},Em=e=>{e.forEach(t=>Gg(t.preview))},MT=e=>{if(e===0)return"0 Bytes";const t=1024,s=["Bytes","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,n)).toFixed(2))+" "+s[n]},PT=e=>!e.files||e.files.length===0?!1:Array.from(e.files).some(t=>xi.includes(t.type)),ET=e=>e.files?Array.from(e.files).filter(t=>xi.includes(t.type)):[],{Text:RT,Title:AT}=le,IT=({visible:e,images:t,currentIndex:s=0,onClose:n,onDownload:o})=>{const{token:a}=xe.useToken(),[i,l]=m.useState(s);if(!t||t.length===0)return null;const c=t[i],d=()=>{if(o&&c)o(c);else{const p=document.createElement("a");p.href=c.base64,p.download=c.name,document.body.appendChild(p),p.click(),document.body.removeChild(p)}},u=()=>{l(p=>p>0?p-1:t.length-1)},h=()=>{l(p=>p<t.length-1?p+1:0)};return r.jsxs(Et,{open:e,onCancel:n,footer:null,width:"90vw",style:{top:20},styles:{body:{padding:0,height:"80vh",display:"flex",flexDirection:"column"}},closeIcon:r.jsx(fr,{style:{color:a.colorTextLightSolid}}),children:[r.jsx("div",{style:{padding:a.paddingMD,borderBottom:`1px solid ${a.colorBorder}`,background:a.colorBgContainer},children:r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",width:"100%"},children:[r.jsxs("div",{children:[r.jsx(AT,{level:5,style:{margin:0},children:c.name}),r.jsxs(RT,{type:"secondary",style:{fontSize:a.fontSizeSM},children:[MT(c.size)," • ",c.type,t.length>1&&` • ${i+1} of ${t.length}`]})]}),r.jsxs(q,{children:[t.length>1&&r.jsxs(r.Fragment,{children:[r.jsx(B,{icon:r.jsx(Ud,{}),onClick:u,disabled:t.length<=1}),r.jsx(B,{icon:r.jsx(Bs,{}),onClick:h,disabled:t.length<=1})]}),r.jsx(B,{icon:r.jsx(cr,{}),onClick:d,children:"Download"})]})]})}),r.jsxs("div",{style:{flex:1,display:"flex",justifyContent:"center",alignItems:"center",background:a.colorBgLayout,position:"relative",overflow:"hidden"},children:[t.length===1?r.jsx("img",{src:c.preview,alt:c.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}}):r.jsx(kx,{dots:!1,arrows:!0,infinite:!0,afterChange:l,style:{width:"100%",height:"100%"},children:t.map(p=>r.jsx("div",{children:r.jsx("div",{style:{height:"70vh",display:"flex",justifyContent:"center",alignItems:"center"},children:r.jsx("img",{src:p.preview,alt:p.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}})})},p.id))}),t.length>1&&r.jsxs(r.Fragment,{children:[r.jsx(B,{type:"primary",shape:"circle",icon:r.jsx(Ud,{}),onClick:u,style:{position:"absolute",left:20,top:"50%",transform:"translateY(-50%)",zIndex:10}}),r.jsx(B,{type:"primary",shape:"circle",icon:r.jsx(Bs,{}),onClick:h,style:{position:"absolute",right:20,top:"50%",transform:"translateY(-50%)",zIndex:10}})]})]}),t.length>1&&r.jsx("div",{style:{padding:a.paddingSM,borderTop:`1px solid ${a.colorBorder}`,background:a.colorBgContainer,display:"flex",gap:a.marginXS,overflowX:"auto",maxHeight:80},children:t.map((p,y)=>r.jsx("div",{style:{minWidth:60,height:60,border:y===i?`2px solid ${a.colorPrimary}`:`1px solid ${a.colorBorder}`,borderRadius:a.borderRadius,overflow:"hidden",cursor:"pointer",opacity:y===i?1:.7},onClick:()=>l(y),children:r.jsx("img",{src:p.preview,alt:p.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},p.id))})]})},Lr=e=>/\s/.test(e),$T=e=>{if(!e)return[{text:"",type:"text"}];const t=[],s=e.length;let n=0;for(;n<s;){const o=e[n],a=n>0?e[n-1]:"",i=o==="/"&&(n===0||Lr(a)),l=o==="@"&&(n===0||Lr(a));if(!i&&!l){let u=n;for(;n<s&&!((e[n]==="/"||e[n]==="@")&&(n===0||Lr(e[n-1])));)n+=1;t.push({text:e.slice(u,n),type:"text"});continue}let c=n+1;for(;c<s&&!Lr(e[c]);)c+=1;const d=e.slice(n,c);i?c===s||Lr(e[c])?t.push({text:d,type:"workflow"}):t.push({text:d,type:"text"}):l&&t.push({text:d,type:"file"}),n=c}return t.length>0?t:[{text:"",type:"text"}]},FT=/(\/)([a-zA-Z0-9_-]*)$/,LT=e=>{if(!e)return{command:null,isTriggerActive:!1,searchText:""};const t=e.match(FT);if(!t)return{command:null,isTriggerActive:!1,searchText:""};const s=t[2]||"",n=!s.includes(" ")&&t.index!==void 0;return{command:s||null,isTriggerActive:n,searchText:s}},OT=/@([a-zA-Z0-9._\-\/\\]*)$/,DT=e=>{if(!e)return{isTriggerActive:!1,searchText:"",tokenStart:null};const t=e.match(OT);if(!t||t.index===void 0)return{isTriggerActive:!1,searchText:"",tokenStart:null};const s=t[1]||"",n=t.index;return{isTriggerActive:!s.includes(" "),searchText:s,tokenStart:n}},zT=(e,t=80)=>{const[s,n]=m.useState(e);return m.useEffect(()=>{const o=window.setTimeout(()=>{n(e)},t);return()=>{window.clearTimeout(o)}},[e,t]),s},{Text:NT}=le,BT=({visible:e,token:t})=>e?r.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:t.colorPrimaryBg,borderRadius:t.borderRadius,zIndex:10,pointerEvents:"none"},children:r.jsxs(q,{direction:"vertical",align:"center",children:[r.jsx(Cx,{style:{fontSize:32,color:t.colorPrimary}}),r.jsx(NT,{style:{color:t.colorPrimary,fontWeight:500},children:"Drop images here"})]})}):null,{Text:Rm}=le,WT=({images:e,token:t,allowImages:s,onPreview:n,onClear:o})=>{const{t:a}=se();return!s||e.length===0?null:r.jsx("div",{style:{marginBottom:t.marginSM,padding:`${t.paddingXXS}px ${t.paddingXS}px`,borderRadius:999,border:`1px solid ${t.colorBorderSecondary}`,background:t.colorFillSecondary},children:r.jsxs(K,{align:"center",wrap:"wrap",gap:t.marginXS,children:[r.jsx(Rm,{type:"secondary",style:{fontSize:t.fontSizeSM,minWidth:"fit-content"},children:e.length>1?a("chat.input.imageCountPlural",{count:e.length}):a("chat.input.imageCountSingular",{count:e.length})}),e.slice(0,3).map(i=>r.jsx("div",{style:{position:"relative",width:32,height:32,borderRadius:999,overflow:"hidden",border:`1px solid ${t.colorBorderSecondary}`,cursor:"pointer"},onClick:()=>n(i),children:r.jsx("img",{src:i.preview,alt:i.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},i.id)),e.length>3&&r.jsx(Rm,{type:"secondary",style:{fontSize:t.fontSizeSM},children:a("chat.input.moreImages",{count:e.length-3})}),r.jsx(B,{type:"text",size:"small",icon:r.jsx(fr,{}),onClick:o,style:{marginLeft:"auto",minWidth:"auto",padding:"0 4px",height:24},title:a("chat.input.clearAllImages")})]})})},{TextArea:UT}=ye,qT=({value:e,placeholder:t,disabled:s,token:n,highlightSegments:o,textAreaRef:a,highlightOverlayRef:i,onChange:l,onKeyDown:c,onPaste:d,onScrollSync:u})=>{const h=e.length>0&&o.some(f=>f.type!=="text"),p="6px 4px",y=1.65,g=s?n.colorTextDisabled:n.colorText;return r.jsxs("div",{style:{position:"relative",flex:1},children:[h?r.jsxs("div",{ref:i,"aria-hidden":!0,style:{position:"absolute",top:0,left:0,right:0,bottom:0,padding:p,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflow:"hidden",pointerEvents:"none",color:"transparent",fontSize:n.fontSize,lineHeight:y,fontFamily:"inherit",fontWeight:400,letterSpacing:"normal",transform:"translate(0, 0)",zIndex:0},children:[o.map((f,b)=>{let x;return f.type==="workflow"?x={backgroundColor:n.colorPrimaryBg,color:"transparent",WebkitTextFillColor:"transparent",fontWeight:400,textDecoration:"underline",textDecorationStyle:"dotted",textDecorationColor:n.colorPrimary}:f.type==="file"&&(x={backgroundColor:n.colorSuccessBg,color:"transparent",WebkitTextFillColor:"transparent"}),r.jsx("span",{style:x,children:f.text},`segment-${b}`)}),e.endsWith(`
|
|
153
|
+
`)?`
|
|
154
|
+
`:null]}):null,r.jsx(UT,{"data-testid":"chat-input",ref:a,value:e,onChange:f=>l(f.target.value),onKeyDown:c,onPaste:d,placeholder:t,disabled:s,autoSize:{minRows:3,maxRows:8},variant:"borderless",onScroll:u,className:"lotus-message-input-field",style:{resize:"none",flex:1,fontSize:n.fontSize,padding:p,lineHeight:y,border:"none",outline:"none",background:"transparent",color:g,WebkitTextFillColor:g,caretColor:g,position:"relative",zIndex:1,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflowY:"auto"}})]})},HT=({allowImages:e,disabled:t,isStreaming:s,token:n,fileInputRef:o,onFileInputChange:a,onFileReferenceButtonClick:i,extraControl:l})=>{const{t:c}=se();return r.jsxs(K,{align:"center",style:{minWidth:0,gap:0},children:[e&&r.jsxs(r.Fragment,{children:[r.jsx("input",{ref:o,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:a}),r.jsx(B,{type:"text",icon:r.jsx(ks,{}),onClick:()=>{var d;return(d=o.current)==null?void 0:d.click()},disabled:t||s,size:"small",style:{minWidth:36,padding:"0 8px",height:36,borderRadius:18,color:n.colorTextSecondary},title:c("chat.input.addAttachments"),"aria-label":c("chat.input.addAttachments")})]}),i&&r.jsx(B,{type:"text",icon:r.jsx(dr,{}),onClick:i,disabled:t||s,size:"small",style:{minWidth:36,padding:"0 8px",height:36,borderRadius:18,color:n.colorTextSecondary},title:c("chat.input.referenceWorkspaceFiles"),"aria-label":c("chat.input.referenceWorkspaceFiles")}),l]})},YT=({allowRetry:e,hasMessages:t,isStreaming:s,disabled:n,onRetry:o,onCancel:a,onSubmit:i,value:l,images:c,isOverCharLimit:d,token:u,statusIndicator:h,submitButtonLabel:p})=>{const{t:y}=se(),g=!l.trim()&&c.length===0,f=s||n||!o,b=p??y("chat.actions.sendMessage");return r.jsxs(K,{align:"center",style:{flex:"0 0 auto",gap:u.marginXS},children:[h?r.jsx("span",{style:{flex:"0 0 auto"},children:h}):null,e&&t&&r.jsx(lr,{trigger:["click"],menu:{items:[{key:"regenerate",label:y("chat.actions.regenerate"),icon:r.jsx(Cs,{})},{key:"error_retry",label:y("chat.actions.retryFailed"),icon:r.jsx(Ci,{})}],onClick:({key:x})=>o==null?void 0:o(x)},disabled:f,children:r.jsx(B,{"data-testid":"regenerate-button",type:"text",icon:r.jsx(Yc,{spin:s}),disabled:f,title:y("chat.actions.retryOptions"),"aria-label":y("chat.actions.retryOptions"),size:"small",className:"lotus-secondary-button",style:{minWidth:38,padding:"0 8px",height:38,width:38,borderRadius:19,color:u.colorTextSecondary}})}),r.jsx(B,{"data-testid":s?"cancel-button":"send-button",type:"primary",icon:s?r.jsx(jx,{}):r.jsx(Mx,{}),onClick:s?a:i,loading:s&&!a,disabled:s?!a||n:g||n||d,size:"small",danger:s,className:s?"message-input-send-button":"message-input-send-button lotus-primary-cta",style:{minWidth:50,padding:0,height:50,width:50,borderRadius:25,display:"inline-flex",alignItems:"center",justifyContent:"center",background:s?void 0:"linear-gradient(135deg, var(--lotus-primary) 0%, var(--lotus-accent-secondary) 100%)",border:s?void 0:"none",boxShadow:s?void 0:"var(--lotus-send-btn-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",transform:"scale(1)"},title:s?y("chat.actions.cancelRequest"):b,"aria-label":s?y("chat.actions.cancelRequest"):b})]})},{Text:Am}=le,XT=({charCount:e,maxCharCount:t,isOverCharLimit:s,isNearCharLimit:n,isProcessingAttachments:o,token:a})=>{const i=typeof t=="number"&&Number.isFinite(t)&&t>0;return!o&&!n&&!s?null:r.jsxs(r.Fragment,{children:[i&&r.jsx(K,{justify:"flex-end",style:{marginTop:a.marginXXS},children:r.jsxs(Am,{type:s?"danger":n?"warning":"secondary",style:{fontSize:a.fontSizeSM},children:[e.toLocaleString()," / ",t.toLocaleString()]})}),o&&r.jsxs(q,{size:"small",style:{marginTop:a.marginXS},children:[r.jsx(ct,{size:"small"}),r.jsx(Am,{type:"secondary",children:"Processing files…"})]})]})},VT=({onFiles:e,mode:t="images"})=>{const[s,n]=m.useState(!1),o=m.useCallback(l=>{var d,u;l.preventDefault(),l.stopPropagation(),(t==="images"?PT(l.dataTransfer):((u=(d=l.dataTransfer)==null?void 0:d.files)==null?void 0:u.length)>0)&&n(!0)},[t]),a=m.useCallback(l=>{l.preventDefault(),l.stopPropagation(),n(!1)},[]),i=m.useCallback(l=>{if(l.preventDefault(),l.stopPropagation(),n(!1),t==="images"){const d=ET(l.dataTransfer);d.length>0&&e(d);return}const c=Array.from(l.dataTransfer.files||[]);c.length>0&&e(c)},[t,e]);return{isDragOver:s,handleDragOver:o,handleDragLeave:a,handleDrop:i}},KT=e=>{const{message:t}=ts.useApp(),[s,n]=m.useState([]),[o,a]=m.useState(!1),[i,l]=m.useState(0),c=m.useCallback(async p=>{if(e)try{const y=await CT(p);y.length>0&&(n(g=>[...g,...y]),t.success(`Added ${y.length} image(s)`))}catch(y){t.error(`Failed to process images: ${y}`)}},[e,t]),d=m.useCallback(p=>{const y=s.find(g=>g.id===p);y&&Em([y]),n(g=>g.filter(f=>f.id!==p))},[s]),u=m.useCallback(p=>{const y=s.findIndex(g=>g.id===p.id);l(y>=0?y:0),a(!0)},[s]),h=m.useCallback(()=>{Em(s),n([])},[s]);return{images:s,setImages:n,previewModalVisible:o,setPreviewModalVisible:a,previewImageIndex:i,handleImageFiles:c,handleRemoveImage:d,handleImagePreview:u,clearImages:h}},GT=({onImages:e,onAttachments:t,allowImages:s})=>({handlePaste:m.useCallback(o=>{if(!o.clipboardData)return;const a=Array.from(o.clipboardData.items),i=[],l=[];a.forEach(c=>{if(c.kind==="file"){const d=c.getAsFile();if(!d)return;d.type.startsWith("image/")?i.push(d):l.push(d)}}),i.length>0&&s&&(o.preventDefault(),e(i)),l.length>0&&t&&(o.preventDefault(),t(l))},[s,e,t])}),gt=[];for(let e=0;e<256;++e)gt.push((e+256).toString(16).slice(1));function JT(e,t=0){return(gt[e[t+0]]+gt[e[t+1]]+gt[e[t+2]]+gt[e[t+3]]+"-"+gt[e[t+4]]+gt[e[t+5]]+"-"+gt[e[t+6]]+gt[e[t+7]]+"-"+gt[e[t+8]]+gt[e[t+9]]+"-"+gt[e[t+10]]+gt[e[t+11]]+gt[e[t+12]]+gt[e[t+13]]+gt[e[t+14]]+gt[e[t+15]]).toLowerCase()}let wl;const QT=new Uint8Array(16);function ZT(){if(!wl){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");wl=crypto.getRandomValues.bind(crypto)}return wl(QT)}const ek=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Im={randomUUID:ek};function $m(e,t,s){var o;if(Im.randomUUID&&!e)return Im.randomUUID();e=e||{};const n=e.random??((o=e.rng)==null?void 0:o.call(e))??ZT();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,JT(n)}const tk=["text/","application/json","application/xml"],sk=[".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"],nk=200*1024,Jg=e=>e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`,Fm=e=>{const t=e.toLowerCase();return sk.some(s=>t.endsWith(s))},rk=e=>!e.type&&Fm(e.name)?!0:tk.some(t=>e.type.startsWith(t))||Fm(e.name),ok=e=>new Promise((t,s)=>{const n=new FileReader;n.onerror=()=>s(n.error),n.onload=()=>t(n.result),n.readAsText(e)}),Lm=async(e,t)=>{const s=nk,n=[],o=[];for(const a of e)try{if(rk(a)&&a.size<=s){const i=await ok(a);n.push({id:$m(),file:a,name:a.name,size:a.size,type:a.type||"text/plain",kind:"text",content:i,preview:i.length>400?`${i.slice(0,400)}…`:i,lastModified:a.lastModified})}else n.push({id:$m(),file:a,name:a.name,size:a.size,type:a.type||"application/octet-stream",kind:"binary",preview:`(${Jg(a.size)}) Preview unavailable for this file type.`,lastModified:a.lastModified})}catch(i){console.error("[fileUtils] Failed to process file",a.name,i),o.push(`Failed to process ${a.name}: ${i.message}`)}return{processed:n,errors:o}},ak=e=>{const t=[],s=[];return e.forEach(n=>{n.type.startsWith("image/")?t.push(n):s.push(n)}),{images:t,others:s}},ik=e=>e.length===0?"":e.map(t=>{const s=`### File: ${t.name}`,n=`(_${Jg(t.size)}_, ${t.type||"unknown"})`;return t.kind==="text"&&t.content?`${s}
|
|
155
|
+
${n}
|
|
156
|
+
|
|
157
|
+
\`\`\`
|
|
158
|
+
${t.content}
|
|
159
|
+
\`\`\``:`${s}
|
|
160
|
+
${n}
|
|
161
|
+
|
|
162
|
+
> Preview unavailable for this file type.`}).join(`
|
|
163
|
+
|
|
164
|
+
`),lk=({allowImages:e,onAttachmentsAdded:t,messageApi:s})=>{const[n,o]=m.useState(!1),{images:a,setImages:i,previewModalVisible:l,setPreviewModalVisible:c,previewImageIndex:d,handleImageFiles:u,handleImagePreview:h,clearImages:p}=KT(e),y=m.useCallback(async C=>{if(!C||C.length===0)return;const{images:_,others:T}=ak(C);if(_.length>0&&await u(_),T.length>0&&t){o(!0);const{processed:j,errors:v}=await Lm(T);j.length>0&&(t(j),s.success(`Added ${j.length} file(s)`)),v.forEach(k=>s.error(k)),o(!1)}},[u,s,t]),{isDragOver:g,handleDragOver:f,handleDragLeave:b,handleDrop:x}=VT({onFiles:y,mode:"any"}),{handlePaste:S}=GT({onImages:u,onAttachments:t?async C=>{o(!0);const{processed:_,errors:T}=await Lm(C);_.length>0&&(t(_),s.success(`Attached ${_.length} file(s)`)),T.forEach(j=>s.error(j)),o(!1)}:void 0,allowImages:e}),w=m.useCallback(C=>{const _=C.target.files;_&&_.length>0&&u(_),C.target.value=""},[u]);return{images:a,setImages:i,previewModalVisible:l,setPreviewModalVisible:c,previewImageIndex:d,handleImageFiles:u,handleImagePreview:h,clearImages:p,isProcessingAttachments:n,isDragOver:g,handleDragOver:f,handleDragLeave:b,handleDrop:x,handlePaste:S,handleFileInputChange:w}},ck=({value:e,debouncedValue:t,onWorkflowCommandChange:s,onFileReferenceChange:n,onImagesChange:o,images:a,propImages:i,setImages:l,syncOverlayScroll:c})=>{m.useEffect(()=>{c()},[e,c]),m.useEffect(()=>{s&&s(LT(t))},[t,s]),m.useEffect(()=>{n&&n(DT(t))},[t,n]),m.useEffect(()=>{o&&o(a)},[a,o]),m.useEffect(()=>{i&&l(i)},[i,l])},dk=({value:e,images:t,isStreaming:s,disabled:n,isWorkflowSelectorVisible:o,onChange:a,onSubmit:i,onRetry:l,onHistoryNavigate:c,validateMessage:d,isOverCharLimit:u,maxCharCount:h,messageApi:p,clearImages:y,textAreaRef:g})=>{const f=m.useCallback(()=>{const S=e.trim();if(!(!S&&t.length===0||s||n)){if(u){const w=typeof h=="number"?h.toLocaleString():"configured";p.error(`Message exceeds the maximum length of ${w} characters.`);return}if(d){const w=d(S);if(!w.isValid){p.error(w.errorMessage||"Message format is incorrect");return}}i(S,t.length>0?t:void 0),y()}},[y,n,t,u,s,h,p,i,d,e]),b=m.useCallback(S=>{if(c&&!n&&!s&&!S.shiftKey&&(S.key==="ArrowUp"||S.key==="ArrowDown")){const w=S.key==="ArrowUp"?"previous":"next",C=c(w,e);if(C!=null){S.preventDefault(),a(C),requestAnimationFrame(()=>{var T,j;const _=((j=(T=g.current)==null?void 0:T.resizableTextArea)==null?void 0:j.textArea)||null;if(_){const v=C.length;_.setSelectionRange(v,v)}});return}}S.key==="Enter"&&!S.shiftKey&&!s&&!n&&!o&&(S.preventDefault(),f())},[n,f,s,o,a,c,g,e]),x=m.useCallback((S="regenerate")=>{s||n||!l||l(S)},[n,s,l]);return{handleKeyDown:b,handleSubmit:f,handleRetry:x}},uk=({value:e,onChange:t,onSubmit:s,interaction:n,placeholder:o,disabled:a=!1,images:i,onImagesChange:l,allowImages:c=!0,isWorkflowSelectorVisible:d=!1,textAreaRef:u,statusIndicator:h,validateMessage:p,onAttachmentsAdded:y,onWorkflowCommandChange:g,onFileReferenceChange:f,onFileReferenceButtonClick:b,maxCharCount:x,leftControlsExtra:S,submitButtonLabel:w})=>{const{t:C}=se(),{isStreaming:_,hasMessages:T,allowRetry:j=!0,onRetry:v,onCancel:k,onHistoryNavigate:E}=n,M=m.useRef(null),R=m.useRef(null),I=u||R,P=m.useRef(null),{token:L}=xe.useToken(),[O,A]=pe.useMessage(),$=e.length,W=typeof x=="number"&&Number.isFinite(x)&&x>0,F=W?$>x:!1,H=W?!F&&$>=x*.9:!1,{images:D,setImages:U,previewModalVisible:Q,setPreviewModalVisible:Y,previewImageIndex:he,handleImagePreview:ve,clearImages:ue,isProcessingAttachments:ie,isDragOver:Re,handleDragOver:Le,handleDragLeave:Ze,handleDrop:et,handlePaste:Ct,handleFileInputChange:pt}=lk({allowImages:c,onAttachmentsAdded:y,messageApi:O}),At=zT(e,80),re=m.useMemo(()=>$T(e),[e]),$e=()=>{var tt,st;const Me=(st=(tt=I.current)==null?void 0:tt.resizableTextArea)==null?void 0:st.textArea;if(!Me||!P.current)return;const It=Me.scrollTop,St=Me.scrollLeft;P.current.style.transform=`translate(${-St}px, ${-It}px)`};ck({value:e,debouncedValue:At,onWorkflowCommandChange:g,onFileReferenceChange:f,onImagesChange:l,images:D,propImages:i,setImages:U,syncOverlayScroll:$e});const{handleKeyDown:V,handleSubmit:ge,handleRetry:oe}=dk({value:e,images:D,isStreaming:_,disabled:a,isWorkflowSelectorVisible:d,onChange:t,onSubmit:s,onRetry:v,onHistoryNavigate:E,validateMessage:p,isOverCharLimit:F,maxCharCount:x,messageApi:O,clearImages:ue,textAreaRef:I}),ce=o??C("chat.input.placeholder");return r.jsxs(r.Fragment,{children:[A,r.jsxs("div",{className:`message-input-container lotus-message-input-shell ${Re?"is-drag-over":""}`,role:"group","aria-label":C("chat.input.messageComposer","Message composer"),style:{position:"relative",border:`1px solid ${Re?"var(--lotus-input-border-active)":"var(--lotus-input-border)"}`,borderRadius:26,background:Re?"var(--lotus-input-bg-active)":"var(--lotus-input-bg)",backdropFilter:"blur(18px)",WebkitBackdropFilter:"blur(18px)",boxShadow:"var(--lotus-input-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",width:"100%",padding:`${L.paddingSM}px`,overflow:"hidden"},onDragOver:Le,onDragLeave:Ze,onDrop:et,children:[r.jsx(WT,{images:D,token:L,allowImages:c,onPreview:ve,onClear:ue}),r.jsx(BT,{visible:Re,token:L}),r.jsxs(K,{vertical:!0,style:{gap:L.marginXS,minHeight:132,width:"100%"},children:[r.jsx(qT,{value:e,placeholder:ce,disabled:a,token:L,highlightSegments:re,textAreaRef:I,highlightOverlayRef:P,onChange:t,onKeyDown:V,onPaste:Ct,onScrollSync:$e}),r.jsxs(K,{align:"center",justify:"space-between",gap:L.marginSM,children:[r.jsx(K,{align:"center",gap:L.marginXS,style:{minWidth:0,flex:1},children:r.jsx(HT,{allowImages:c,disabled:a,isStreaming:_,token:L,fileInputRef:M,onFileInputChange:pt,onFileReferenceButtonClick:b,extraControl:S})}),r.jsx(YT,{allowRetry:j,hasMessages:T,isStreaming:_,disabled:a,onRetry:oe,onCancel:k,onSubmit:ge,value:e,images:D,isOverCharLimit:F,token:L,statusIndicator:h,submitButtonLabel:w})]})]})]}),r.jsx(XT,{charCount:$,maxCharCount:x,isOverCharLimit:F,isNearCharLimit:H,isProcessingAttachments:ie,token:L}),c&&r.jsx(IT,{visible:Q,images:D,currentIndex:he,onClose:()=>Y(!1)})]})},{Text:Om}=le,{useToken:mk}=xe,hk=({text:e,onClose:t})=>{const{token:s}=mk(),o=(e.length>150?e.substring(0,147)+"...":e).replace(/^> |^>/gm,"");return r.jsx("div",{style:{marginBottom:s.marginSM,background:s.colorFillSecondary,borderRadius:999,border:`1px solid ${s.colorBorderSecondary}`,padding:`${s.paddingXXS}px ${s.paddingSM}px`},children:r.jsxs(q,{style:{width:"100%",justifyContent:"space-between",alignItems:"flex-start"},children:[r.jsxs("div",{style:{flex:1},children:[r.jsx(Om,{style:{fontSize:s.fontSizeSM,color:s.colorPrimary},children:"Referencing"}),r.jsx(Om,{style:{fontSize:s.fontSizeSM,color:s.colorTextSecondary,marginLeft:s.marginSM},ellipsis:!0,children:o})]}),r.jsx(B,{type:"text",size:"small",icon:r.jsx(fr,{}),onClick:t,style:{marginLeft:s.marginXS,color:s.colorTextSecondary,borderRadius:999}})]})})},pk=e=>{const t=m.useRef(new Map),s=m.useRef(!1),[n,o]=m.useState(null);m.useEffect(()=>{o(null),s.current=!1},[e]);const a=m.useCallback(d=>{if(!e)return;const u=d.trim();if(!u)return;const h=t.current.get(e)??[];if(h[h.length-1]===u)return;const p=[...h,u].slice(-50);t.current.set(e,p),o(null),s.current=!1},[e]),i=m.useCallback((d,u)=>{if(!e)return{value:null,applied:!1};const h=t.current.get(e)??[];if(h.length===0)return{value:null,applied:!1};const p=u.trim();if(d==="previous"){if(p.length>0&&n===null)return{value:null,applied:!1};const g=n??h.length,f=Math.max(0,g-1);return f===n?{value:null,applied:!1}:(o(f),s.current=!0,{value:h[f]??null,applied:!0})}if(n===null)return{value:null,applied:!1};const y=n+1;return y>=h.length?(o(null),s.current=!0,{value:"",applied:!0}):(o(y),s.current=!0,{value:h[y]??null,applied:!0})},[e,n]),l=m.useCallback(()=>{if(s.current){s.current=!1;return}n!==null&&o(null)},[n]),c=m.useCallback(()=>{e&&(t.current.delete(e),o(null),s.current=!1)},[e]);return{recordEntry:a,navigate:i,acknowledgeManualInput:l,clearHistory:c}},Rn=class Rn{constructor(){We(this,"cache",null);We(this,"cacheTime",0);We(this,"CACHE_TTL",3e4)}static getInstance(){return Rn.instance||(Rn.instance=new Rn),Rn.instance}async listCommands(t=!1){const s=Date.now();if(!t&&this.cache&&s-this.cacheTime<this.CACHE_TTL)return this.cache;try{const n=await Te.get("commands");if(!Array.isArray(n.commands))throw new Error("Invalid command list response");return this.cache=n.commands,this.cacheTime=s,He("[CommandService]","[CommandService] Loaded commands:",this.cache.length),this.cache}catch(n){throw console.error("[CommandService] Failed to list commands:",n),n}}async getCommand(t,s){try{return await Te.get(`commands/${t}/${s}`)}catch(n){throw console.error(`[CommandService] Failed to get command ${t}/${s}:`,n),n}}clearCache(){this.cache=null,this.cacheTime=0}};We(Rn,"instance");let Uo=Rn;const Nn=e=>{if(typeof e!="string"||!e.startsWith("mcp__"))return null;const t=e.slice(5),s=t.indexOf("__");if(s<=0)return null;const n=t.slice(0,s),o=t.slice(s+2);return!n||!o?null:{serverId:n,toolName:o}},fk=({setContent:e,onWorkflowDraftChange:t,acknowledgeManualInput:s,currentSessionId:n,textAreaRef:o,content:a})=>{const[i,l]=m.useState(!1),[c,d]=m.useState(""),[u,h]=m.useState(null);m.useEffect(()=>{h(null),t==null||t(null)},[n,t]);const p=m.useCallback((_,T)=>{const j=_.trimStart(),v=`/${T}`;if(!j.startsWith(v))return!1;const k=j.charAt(v.length);return!k||/\s/.test(k)},[]),y=m.useCallback(()=>{h(null),t==null||t(null)},[t]),g=m.useCallback((_,T)=>{if(!p(_,T.name))return;const j=`/${T.name}`,k=_.trim().slice(j.length).trim(),E=[T.content,k].filter(Boolean).join(`
|
|
165
|
+
|
|
166
|
+
`);t==null||t({...T,content:E})},[p,t]),f=m.useCallback(_=>{s(),u&&!p(_,u.name)&&y(),u&&p(_,u.name)&&g(_,u),e(_)},[s,y,p,u,g,e]),b=m.useCallback(_=>{l(_.isTriggerActive),d(_.isTriggerActive?_.searchText:"")},[]),x=m.useCallback(async _=>{var L,O,A,$,W,F;l(!1);const j=(H=>{var Q;if(H.type!=="mcp")return H.name;const D=(Q=H.metadata)==null?void 0:Q.originalName;if(typeof D=="string"&&D.trim())return D.trim();const U=Nn(H.name);return U!=null&&U.toolName?U.toolName:H.displayName||H.name})(_),v=(O=(L=o.current)==null?void 0:L.resizableTextArea)==null?void 0:O.textArea,k=(v==null?void 0:v.selectionStart)??a.length;let E,M;const I=a.substring(0,k).match(/\/([a-zA-Z0-9_-]*)$/);if(I){const H=k-I[0].length,D=a.substring(0,H),U=a.substring(k);E=`${D}/${j} ${U}`,M=`${D}/${j} `.length}else if(a.trim()==="")E=`/${j} `,M=E.length;else{const H=a.substring(0,k),D=a.substring(k);E=`${H}/${j} ${D}`,M=`${H}/${j} `.length}if(e(E),setTimeout(()=>{v&&(v.selectionStart=M,v.selectionEnd=M,v.focus())},0),_.type!=="workflow"){const H={id:`command-draft-${_.id}`,name:j,content:"",createdAt:new Date().toISOString(),type:_.type,displayName:_.displayName,mcpAlias:_.type==="mcp"?_.name:void 0,mcpServerId:_.type==="mcp"?(A=_.metadata)==null?void 0:A.serverId:void 0,mcpServerName:_.type==="mcp"?($=_.metadata)==null?void 0:$.serverName:void 0,mcpOriginalName:_.type==="mcp"?(W=_.metadata)==null?void 0:W.originalName:void 0};h(H),t==null||t(H);return}const P=Uo.getInstance();try{const H=_.id.startsWith("workflow-")?_.id.slice(9):_.id,U=((F=(await P.getCommand(_.type,H)).content)==null?void 0:F.trim())||"";if(U){const Q={id:`command-draft-${_.id}`,name:_.name,content:U,createdAt:new Date().toISOString(),type:_.type,displayName:_.displayName};h(Q),t==null||t(Q)}else y()}catch(H){console.error(`[InputContainer] Failed to apply command '${_.name}':`,H),y()}},[y,t,e,a,o]),S=m.useCallback(async _=>{try{const v=(await Uo.getInstance().listCommands()).find(k=>k.id===_.id&&k.type===_.type);if(!v){console.error(`[InputContainer] Command '${_.id}' of type '${_.type}' not found`),e(`/${_.name} `),y();return}await x(v)}catch(T){console.error(`[InputContainer] Failed to select command '${_.name}':`,T),e(`/${_.name} `),y()}},[x,y,e]),w=m.useCallback(()=>{l(!1)},[]),C=m.useCallback(async _=>{l(!1);try{const v=(await Uo.getInstance().listCommands()).find(k=>k.name===_);v?await x(v):(console.error(`[InputContainer] Command '${_}' not found in auto-complete`),e(`/${_} `),y())}catch(T){console.error(`[InputContainer] Failed to load command '${_}' in auto-complete:`,T),e(`/${_} `),y()}},[x,y,e]);return{selectedCommand:u,showCommandSelector:i,commandSearchText:c,clearCommandDraft:y,matchesCommandToken:p,handleInputChange:f,handleCommandChange:b,handleCommandSelect:S,handleCommandSelectorCancel:w,handleAutoComplete:C,setShowCommandSelector:l}};class gk{constructor(t={}){We(this,"cache",null);We(this,"options");We(this,"validateWorkspacePath",this.validatePath.bind(this));We(this,"getRecentWorkspaces",this.getRecent.bind(this));We(this,"addRecentWorkspace",this.addRecent.bind(this));We(this,"removeRecentWorkspace",this.removeRecent.bind(this));We(this,"clearRecentWorkspaces",this.clearRecent.bind(this));We(this,"getWorkspaceSuggestions",this.getCombinedSuggestions.bind(this));We(this,"getHealthStatus",this.healthCheck.bind(this));this.options={maxRecentWorkspaces:t.maxRecentWorkspaces??10,cacheTimeoutMs:t.cacheTimeoutMs??5*60*1e3,requestTimeoutMs:t.requestTimeoutMs??1e4}}async validatePath(t){return Te.post("workspace/validate",{path:t})}async getRecent(){var t;if(this.isCacheValid())return this.cache.recentWorkspaces;try{const s=await Te.get("workspace/recent",{signal:AbortSignal.timeout(this.options.requestTimeoutMs)});return this.cache={recentWorkspaces:s,timestamp:Date.now()},s}catch(s){if(console.error("Failed to get recent workspaces:",s),(t=this.cache)!=null&&t.recentWorkspaces)return this.cache.recentWorkspaces;throw s}}async addRecent(t,s){await Te.post("workspace/recent",{path:t,metadata:s}),this.invalidateCache()}async removeRecent(t){const n=(await this.getRecent()).filter(o=>o.path!==t);this.cache={recentWorkspaces:n,timestamp:Date.now()}}async clearRecent(){this.cache=null}async getPathSuggestions(){return Te.get("workspace/suggestions")}async browseFolder(t){return Te.post("workspace/browse-folder",{path:t})}async getCombinedSuggestions(){const[t,s]=await Promise.all([this.getPathSuggestions().catch(()=>({suggestions:[]})),this.getRecent().catch(()=>[])]),o=[...t.suggestions.map(i=>({path:i.path,is_valid:!0,workspace_name:i.name})),...s];return this.deduplicateByPath(o).sort((i,l)=>{const c=s.findIndex(u=>u.path===i.path),d=s.findIndex(u=>u.path===l.path);return c!==-1&&d!==-1?c-d:c!==-1?-1:d!==-1?1:(i.workspace_name||"").localeCompare(l.workspace_name||"")})}async healthCheck(){var s,n,o;const t=Date.now();try{await Te.get("workspace/recent",{signal:AbortSignal.timeout(2e3)});const a=((s=this.cache)==null?void 0:s.recentWorkspaces)||await this.getRecent();return{available:!0,cacheValid:this.isCacheValid(),recentCount:a.length,latency:Date.now()-t}}catch(a){return{available:!1,cacheValid:this.isCacheValid(),recentCount:((o=(n=this.cache)==null?void 0:n.recentWorkspaces)==null?void 0:o.length)||0,error:a instanceof Error?a.message:"Unknown error"}}}async listWorkspaceFiles(t,s){return Te.post("workspace/files",{path:t,max_depth:(s==null?void 0:s.max_depth)??3,max_entries:(s==null?void 0:s.max_entries)??500,include_hidden:(s==null?void 0:s.include_hidden)??!1})}isCacheValid(){return this.cache?!(Date.now()-this.cache.timestamp>this.options.cacheTimeoutMs):!1}invalidateCache(){this.cache=null}deduplicateByPath(t){const s=new Set;return t.filter(n=>s.has(n.path)?!1:(s.add(n.path),!0))}}const yk=new gk,xk=({content:e,setContent:t,currentSessionId:s,currentChat:n,updateSession:o,messageApi:a})=>{const[i,l]=m.useState(new Map),[c,d]=m.useState([]),[u,h]=m.useState(!1),[p,y]=m.useState(""),[g,f]=m.useState(!1),[b,x]=m.useState(""),[S,w]=m.useState(!1),[C,_]=m.useState(null),[T,j]=m.useState(!1),v=m.useRef(null);m.useEffect(()=>{g&&x((n==null?void 0:n.config.workspacePath)??"")},[g,n==null?void 0:n.config.workspacePath]),m.useEffect(()=>{h(!1),y(""),d([]),l(new Map),v.current=(n==null?void 0:n.config.workspacePath)??null},[s,n==null?void 0:n.config.workspacePath]);const k=m.useCallback(async(O,A)=>{w(!0),d([]),_(null);try{const $=await yk.listWorkspaceFiles(A);d($),v.current=A}catch($){console.error("Failed to load workspace files:",$),_($ instanceof Error?$.message:"Workspace file browsing is unavailable.")}finally{w(!1)}},[]),E=m.useCallback(O=>{if(y(O.searchText),!O.isTriggerActive){h(!1);return}if(!s||!n){h(!1);return}const A=n.config.workspacePath;if(!A){x(""),f(!0),h(!1);return}h(!0),(v.current!==A||c.length===0)&&k(s,A)},[n,s,k,c.length]),M=m.useCallback(O=>{const A=e.lastIndexOf("@");let $;A>=0&&e.substring(A).match(/^@[a-zA-Z0-9._\\-\\/\\\\]*$/)?$=`${e.slice(0,A)}@${O.name} `:$=e.trim()?`${e.trim()} @${O.name} `:`@${O.name} `,t($),l(W=>{const F=new Map(W);return F.set(O.name,O),F}),h(!1),y("")},[e,t]),R=m.useCallback(()=>{h(!1)},[]),I=m.useCallback(()=>{if(!s||!n)return;const O=n.config.workspacePath;if(!O){x(""),f(!0),h(!1);return}y(""),h(!0),(v.current!==O||c.length===0)&&k(s,O)},[n,s,k,c.length]),P=m.useCallback(()=>{f(!1),x("")},[]),L=m.useCallback(async O=>{if(!n||!s)return;const A=O.trim();if(!A){a.error("Workspace path cannot be empty");return}j(!0);try{o(s,{config:{...n.config,workspacePath:A}}),f(!1),x(""),h(!1),_(null)}catch($){const W=$ instanceof Error?$.message:"Unable to save workspace path";a.error(W)}finally{j(!1)}},[n,s,a,o]);return{fileReferences:i,setFileReferences:l,workspaceFiles:c,showFileSelector:u,setShowFileSelector:h,fileSearchText:p,isWorkspaceLoading:S,workspaceError:C,isWorkspaceModalVisible:g,workspacePathInput:b,isSavingWorkspace:T,setWorkspacePathInput:x,setIsWorkspaceModalVisible:f,handleFileReferenceChange:E,handleFileReferenceSelect:M,handleFileSelectorCancel:R,handleFileReferenceButtonClick:I,handleWorkspaceModalCancel:P,handleWorkspaceModalSubmit:L,fetchWorkspaceFiles:k}},bk=()=>{const[e,t]=m.useState([]),s=m.useCallback(a=>{t(i=>[...i,...a])},[]),n=m.useCallback(a=>{t(i=>i.filter(l=>l.id!==a))},[]),o=m.useCallback(()=>{t([])},[]);return{attachments:e,setAttachments:t,handleAttachmentsAdded:s,handleAttachmentRemove:n,handleClearAttachments:o}},vk=({attachments:e,referenceText:t,selectedWorkflow:s,matchesWorkflowToken:n,fileReferences:o,reasoningEffort:a,sendMessage:i,recordEntry:l,clearWorkflowDraft:c,setContent:d,setReferenceText:u,setAttachments:h,setFileReferences:p})=>({handleSubmit:m.useCallback(async(g,f)=>{const b=g.trim(),x=ik(e),S=(t==null?void 0:t.trim())??"";let w=b,C;if(s!=null&&s.content&&s.type==="workflow"){const T=`/${s.name}`;if(n(b,s.name)){const v=b.slice(T.length).trim();w=[s.content,v].filter(Boolean).join(`
|
|
167
|
+
|
|
168
|
+
`)}}else if((s==null?void 0:s.type)==="skill"){const T=`/${s.name}`;if(n(b,s.name)){const v=b.slice(T.length).trim();w=[`[User explicitly selected skill: ${s.displayName||s.name} (ID: ${s.name})]`,v].filter(Boolean).join(`
|
|
169
|
+
|
|
170
|
+
`),C=[s.name]}}else if((s==null?void 0:s.type)==="mcp"){const T=`/${s.name}`;if(n(b,s.name)){const v=b.slice(T.length).trim();w=[`[User explicitly selected MCP tool: ${s.mcpAlias||s.displayName||s.name}]`,v].filter(Boolean).join(`
|
|
171
|
+
|
|
172
|
+
`)}}if(!w&&!x&&(!f||f.length===0))return;const _=[S,w,x].filter(Boolean).join(`
|
|
173
|
+
|
|
174
|
+
`);if(l(_),d(""),c(),o.size>0){const T=Array.from(_.matchAll(/@([^\\s]+)/g));if(T.length>0){const j=[];for(const v of T){const k=v[1],E=o.get(k);E&&j.push(E)}if(j.length>0){const v=JSON.stringify({type:"file_reference",paths:j.map(k=>k.path),display_text:_});await i(v,f,a,C)}else await i(_,f,a,C)}else await i(_,f,a,C)}else await i(_,f,a,C);u(null),h([]),p(new Map)},[e,c,o,n,l,a,s,i,h,d,p,u,t])}),Sk=({currentSessionId:e,currentChat:t,currentMessages:s,reasoningEffort:n,retryLastTurn:o,navigate:a})=>{const i=m.useCallback(async(c="regenerate")=>{if(!e||!t)return;const d=[...s];d.length===0||[...d].reverse().findIndex(h=>h.role==="user")===-1||await o(n,c)},[t,e,s,n,o]),l=m.useCallback((c,d)=>{const u=a(c,d);return u.applied?u.value:null},[a]);return{retryLastMessage:i,handleHistoryNavigate:l}},wk=({referenceText:e,isToolSpecificMode:t,isRestrictConversation:s,allowedTools:n,autoToolPrefix:o,t:a})=>a(e?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows"),Ic="chat-toggle-batch-export-selection",$c="chat-focus-input",ar="chat-pending-question-resolved",_k=m.lazy(()=>kt(()=>import("./index-eDRjOrKd.js"),__vite__mapDeps([8,1,2,3]),import.meta.url)),Tk=m.lazy(()=>kt(()=>import("./index-Ds0z78TD.js"),__vite__mapDeps([9,1,2,3,4,5,6,7,10]),import.meta.url)),kk=m.lazy(()=>kt(()=>import("./index-Df-GVUQB.js"),__vite__mapDeps([11,1,2,3,4,5,6,7]),import.meta.url)),Ck=m.lazy(()=>kt(()=>import("./index-DMfxTHKB.js"),__vite__mapDeps([12,1,2,3]),import.meta.url)),{useToken:jk}=xe,Dm="chat-send-message",zm="reference-text",Mk="chat-model-options-cache-v1",Pk=24*60*60*1e3,Ek=["low","medium","high","xhigh","max"],Qg=e=>`${Mk}:${e}`,Rk=e=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(Qg(e));if(!t)return null;const s=JSON.parse(t);return!s||!Array.isArray(s.options)||Date.now()-s.timestamp>Pk?null:s.options.filter(n=>n&&typeof n.value=="string"&&n.value.trim().length>0&&typeof n.label=="string").map(n=>({value:n.value,label:n.label}))}catch{return null}},Ak=(e,t)=>{if(!(typeof window>"u"))try{const s={timestamp:Date.now(),options:t};localStorage.setItem(Qg(e),JSON.stringify(s))}catch{}},Ik=({sessionId:e,onWorkflowDraftChange:t,statusIndicator:s})=>{const{t:n}=se(),o=m.useRef(null),{token:a}=jk(),i=qs(J=>J.open),l=z(J=>e??J.currentSessionId),c=z(J=>J.currentSessionId),d=z(xr(l)),u=(d==null?void 0:d.messages)||[],h=z(J=>J.addMessage),p=z(J=>J.updateSession),y=z(J=>J.processingChats),g=z(J=>J.setSessionProcessing),f=z(J=>J.pendingQuestionRespond),b=z(J=>J.clearPendingQuestionRespondForSession),x=vr(),S=z(J=>l?J.inputStates[l]:void 0),w=z(J=>J.setInputContent),C=z(J=>J.setReferenceText),_=z(J=>J.setInputReasoningEffort),T=Rt(J=>J.currentProvider),j=Rt(J=>J.providerConfig),[v,k]=m.useState([]),[E,M]=m.useState(!1),[R,I]=m.useState(null),[P,L]=m.useState(!1),O=(S==null?void 0:S.content)||"",A=(S==null?void 0:S.referenceText)||null,$=m.useMemo(()=>{var J;return(J=j.providers[T])==null?void 0:J.reasoning_effort},[j,T]),W=m.useMemo(()=>l?sd(l):void 0,[l]),F=(S==null?void 0:S.reasoningEffort)??W??$??"medium",H=m.useCallback(J=>{l&&w(l,J)},[l,w]),D=m.useCallback(J=>{l&&C(l,J)},[l,C]),U=m.useCallback(J=>{l&&_(l,J)},[l,_]),Q=l?y.has(l):!1,{sendMessage:Y,retryLastTurn:he,cancel:ve}=Og({sessionId:l,addMessage:h,setSessionProcessing:g,updateSession:p});m.useEffect(()=>{if(typeof window>"u")return;const J=ft=>ft?l===ft:l!==null&&l===c,De=ft=>{const nt=ft;if(!nt.detail||typeof nt.detail.text!="string")return;const os=typeof nt.detail.sessionId=="string"?nt.detail.sessionId:null;if(!J(os))return;const as=nt.detail.text.trim();as&&(nt.detail.handled=!0,D(as),requestAnimationFrame(()=>{var gs;(gs=o.current)==null||gs.focus()}))},Ue=ft=>{var as;const nt=ft,os=typeof((as=nt.detail)==null?void 0:as.sessionId)=="string"?nt.detail.sessionId:null;J(os)&&(nt.detail&&(nt.detail.handled=!0),requestAnimationFrame(()=>{var gs;(gs=o.current)==null||gs.focus()}))};return window.addEventListener(zm,De),window.addEventListener($c,Ue),()=>{window.removeEventListener(zm,De),window.removeEventListener($c,Ue)}},[c,l,D]);const ue=Q,{message:ie}=ts.useApp(),Re=!1,Le=!1,Ze=[],et=void 0,{recordEntry:Ct,navigate:pt,acknowledgeManualInput:At}=pk(l),{attachments:re,setAttachments:$e,handleAttachmentsAdded:V,handleAttachmentRemove:ge,handleClearAttachments:oe}=bk(),ce=fk({setContent:H,onWorkflowDraftChange:t,acknowledgeManualInput:At,currentSessionId:l,textAreaRef:o,content:O}),Me=xk({content:O,setContent:H,currentSessionId:l,currentChat:d,updateSession:p,messageApi:ie}),{setShowFileSelector:It}=Me;m.useEffect(()=>{ce.showCommandSelector&&It(!1)},[ce.showCommandSelector,It]);const{handleSubmit:St}=vk({attachments:re,referenceText:A,selectedWorkflow:ce.selectedCommand,matchesWorkflowToken:ce.matchesCommandToken,fileReferences:Me.fileReferences,reasoningEffort:F,sendMessage:Y,recordEntry:Ct,clearWorkflowDraft:ce.clearCommandDraft,setContent:H,setReferenceText:D,setAttachments:$e,setFileReferences:Me.setFileReferences}),tt=f&&f.sessionId===l?f:null,st=!!tt,rt=(tt==null?void 0:tt.options)||[],ss=(tt==null?void 0:tt.allowCustom)??!0,Ms=m.useCallback(J=>{if(!J)return!1;const De=z.getState().pendingQuestionRespond;return(De==null?void 0:De.sessionId)===J},[]),Hs=m.useCallback(async J=>{const De=J.trim();if(!De||!l)return;const Ue=z.getState().pendingQuestionRespond,ft=(Ue==null?void 0:Ue.sessionId)===l?Ue:null;if(ft&&!ft.allowCustom&&ft.options.length>0&&!ft.options.includes(De)){ie.warning(n("components.questionDialog.selectOptionWarning"));return}try{const nt=x==null?void 0:x.trim(),os=await Se.post(`respond/${l}`,{response:De,model:nt||void 0,reasoning_effort:F});ie.success(n("components.questionDialog.responseSubmittedContinue")),H(""),b(l),typeof window<"u"&&window.dispatchEvent(new CustomEvent(ar,{detail:{sessionId:l}}));const as=os==null?void 0:os.auto_resume_status;as&&["started","already_running"].includes(as)&&g(l,!0)}catch(nt){console.error("[InputContainer] Failed to submit respond:",nt),ie.error(nt instanceof Error?nt.message:n("components.questionDialog.submitFailed"))}},[l,x,F,ie,H,b,g,n]),ns=m.useCallback(async(J,De)=>{if(Ms(l)){await Hs(J);return}await St(J,De)},[l,Ms,Hs,St]),Ys=m.useCallback(async(J,De)=>{await ns(J,De)},[ns]);m.useEffect(()=>{if(typeof window>"u")return;const J=De=>{var as,gs,zd;const Ue=De;if(!Ue.detail)return;const ft=typeof Ue.detail.sessionId=="string"?Ue.detail.sessionId:null;if(!(ft?l===ft:l!==null&&l===c))return;Ue.detail.handled=!0;const os=(as=Ue.detail)==null?void 0:as.content;if(typeof os!="string"||os.trim().length===0){(zd=(gs=Ue.detail)==null?void 0:gs.reject)==null||zd.call(gs,new Error("External send message content is empty"));return}ns(os,void 0).then(()=>{var Wn,pn;(pn=(Wn=Ue.detail)==null?void 0:Wn.resolve)==null||pn.call(Wn)}).catch(Wn=>{var pn,Nd;(Nd=(pn=Ue.detail)==null?void 0:pn.reject)==null||Nd.call(pn,Wn)})};return window.addEventListener(Dm,J),()=>{window.removeEventListener(Dm,J)}},[c,l,ns]);const{retryLastMessage:Ps,handleHistoryNavigate:Bn}=Sk({currentSessionId:l,currentChat:d,currentMessages:u,reasoningEffort:F,retryLastTurn:he,navigate:pt}),X=()=>D(null),G=m.useMemo(()=>{var J;return(J=j.providers)==null?void 0:J[T]},[j,T]),de=m.useMemo(()=>!G||typeof G!="object"?!1:T==="copilot"?Object.keys(G).length>0:typeof G.api_key=="string"&&G.api_key.trim().length>0,[T,G]),ae=m.useCallback(()=>de?!1:(i("chat"),ie.warning("Please configure provider first"),!0),[de,ie,i]);m.useEffect(()=>{const J=Rk(T);k(J??[]),I(null)},[T]);const Pe=m.useCallback(J=>J instanceof Error&&J.message.trim()?J.message:"Unknown error",[]),Xe=m.useMemo(()=>({openai:[...Mc],anthropic:[...Pc],gemini:[...Ec],copilot:[...Xg]})[T]||[],[T]),Je=m.useMemo(()=>{const De=[...v.length>0?v:Xe];return x&&!De.some(Ue=>Ue.value===x)&&De.unshift({value:x,label:x}),De},[v,Xe,x]),rs=m.useCallback(async(J,De)=>{if(!(!(De!=null&&De.force)&&v.length>0))try{M(!0),I(null);const ft=(J==="copilot"?await Ei.getModels():await bt.fetchProviderModels(J)).map(nt=>({value:nt,label:nt}));k(ft),Ak(J,ft)}catch(Ue){I(Pe(Ue))}finally{M(!1)}},[Pe,v.length]),Z=m.useCallback(J=>{J&&(ae()||E||v.length>0||rs(T))},[T,rs,E,v.length,ae]),Ce=m.useCallback(async J=>{if(!(!J||J===x)&&!P)try{if(ae())return;L(!0);const De=Rt.getState(),Ue={...De.providerConfig.providers||{}};Ue[T]={...Ue[T]||{},model:J},await bt.saveProviderConfig({provider:T,providers:Ue}),await De.loadProviderConfig(),ie.success(n("settings.providerTab.modelUpdated"))}catch(De){ie.error(`${n("settings.providerTab.updateModelErrorPrefix")}: ${Pe(De)}`)}finally{L(!1)}},[x,T,Pe,P,ie,ae,n]),Ie=m.useMemo(()=>wk({referenceText:A,isToolSpecificMode:Re,isRestrictConversation:Le,allowedTools:Ze,autoToolPrefix:et,t:n}),[A,Re,Le,Ze,et,n]),Be=st&&ss?n("chat.respond.customAnswerPlaceholder"):st?n("components.questionDialog.selectOptionWarning"):Ie,mt=m.useMemo(()=>st?r.jsx(fe,{color:"processing",style:{marginInlineEnd:0},children:n("chat.respond.modeLabel","Tool response mode")}):null,[st,n]),hn=m.useMemo(()=>mt?s?r.jsxs(q,{size:6,align:"center",children:[mt,s]}):mt:s??null,[mt,s]),Xs=st?n("chat.respond.submitToolResult","Submit tool result"):void 0,$t=m.useMemo(()=>({low:n("chat.input.reasoning.low"),medium:n("chat.input.reasoning.medium"),high:n("chat.input.reasoning.high"),xhigh:n("chat.input.reasoning.xhigh"),max:n("chat.input.reasoning.max")}),[n]),fs=m.useMemo(()=>$t[F]??F,[F,$t]),Es=r.jsx(lr,{trigger:["click"],placement:"topLeft",disabled:!x||ue,menu:{selectable:!0,selectedKeys:[F],items:Ek.map(J=>({key:J,label:$t[J]})),onClick:({key:J})=>{U(J)}},children:r.jsx(B,{type:"text",size:"small",disabled:!x||ue,style:{minWidth:88,padding:"0 12px",height:36,borderRadius:18,color:F==="medium"?a.colorTextSecondary:a.colorPrimary},title:n("chat.input.reasoningTitle",{label:fs}),children:r.jsxs(q,{size:6,children:[r.jsx(Pp,{}),r.jsx("span",{children:fs}),r.jsx(Zt,{style:{fontSize:10}})]})})}),Rs=x||n(de?"chat.model.selectModel":"chat.model.configureProvider"),rx=m.useMemo(()=>Je.length>0?Je.map(J=>({key:J.value,label:J.label})):[{key:"__no_models__",label:R||n("chat.model.noModelsAvailable"),disabled:!0}],[Je,R,n]),Dd=r.jsx(B,{type:"text",size:"small",disabled:ue||P,onClick:()=>{de||ae()},style:{minWidth:146,padding:"0 12px",height:36,borderRadius:18,color:R?a.colorError:a.colorTextSecondary},title:Rs,children:r.jsxs(q,{size:6,children:[E?r.jsx(ta,{}):r.jsx(Xc,{}),r.jsx("span",{style:{maxWidth:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Rs}),r.jsx(Zt,{style:{fontSize:10}})]})}),ox=de?r.jsx(lr,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:x?[x]:[],items:rx,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:J})=>{J!=="__no_models__"&&Ce(String(J))}},onOpenChange:Z,disabled:ue||P,children:Dd}):Dd;return r.jsxs("div",{style:{padding:`${a.paddingXXS}px ${a.paddingXS}px`,background:"transparent",borderTop:"none",boxShadow:"none",width:"100%",position:"relative",overflow:"visible"},children:[!x&&r.jsx(Ne,{type:"warning",showIcon:!0,icon:r.jsx(sa,{}),message:n(de?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:n(de?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:de?void 0:r.jsx(q,{children:r.jsx("a",{onClick:()=>i("chat"),children:n("chat.model.openSettings")})}),style:{marginBottom:a.marginSM}}),Re,A&&r.jsx(hk,{text:A,onClose:X}),re.length>0&&r.jsx(m.Suspense,{fallback:r.jsx(ct,{size:"small"}),children:r.jsx(_k,{files:re,onRemove:ge,onClear:oe})}),st&&rt.length>0&&r.jsx("div",{style:{marginBottom:a.marginSM},children:r.jsx(q,{wrap:!0,size:[8,8],children:rt.map(J=>r.jsx(B,{size:"small",onClick:()=>{Hs(J)},disabled:ue,children:J},J))})}),r.jsx(uk,{value:O,onChange:ce.handleInputChange,onSubmit:Ys,placeholder:Be,allowImages:!0,disabled:!x||st&&!ss&&rt.length>0,statusIndicator:hn,submitButtonLabel:Xs,isWorkflowSelectorVisible:ce.showCommandSelector,textAreaRef:o,validateMessage:J=>({isValid:!0}),onAttachmentsAdded:V,onWorkflowCommandChange:ce.handleCommandChange,onFileReferenceChange:Me.handleFileReferenceChange,onFileReferenceButtonClick:Me.handleFileReferenceButtonClick,leftControlsExtra:r.jsxs(q,{size:0,wrap:!0,children:[ox,Es]}),interaction:{isStreaming:ue,hasMessages:u.some(J=>J.role==="user"),allowRetry:!0,onRetry:Ps,onCancel:ve,onHistoryNavigate:Bn}}),r.jsx(m.Suspense,{fallback:null,children:r.jsx(Tk,{visible:ce.showCommandSelector,onSelect:ce.handleCommandSelect,onCancel:ce.handleCommandSelectorCancel,onAutoComplete:ce.handleAutoComplete,searchText:ce.commandSearchText})}),Me.showFileSelector&&r.jsx(m.Suspense,{fallback:r.jsx(ct,{size:"small"}),children:r.jsx(Ck,{visible:Me.showFileSelector,files:Me.workspaceFiles,searchText:Me.fileSearchText,loading:Me.isWorkspaceLoading,error:Me.workspaceError,onSelect:Me.handleFileReferenceSelect,onCancel:Me.handleFileSelectorCancel,onChangeWorkspace:()=>{Me.setWorkspacePathInput((d==null?void 0:d.config.workspacePath)??""),Me.setIsWorkspaceModalVisible(!0)}})}),r.jsx(m.Suspense,{fallback:null,children:r.jsx(kk,{open:Me.isWorkspaceModalVisible,initialPath:Me.workspacePathInput,loading:Me.isSavingWorkspace,onSubmit:Me.handleWorkspaceModalSubmit,onCancel:Me.handleWorkspaceModalCancel})})]})},{Text:Ls}=le,$k=220,Fk="chat-session-diff-collapse:",Lk=e=>e.split(/[\\/]/).pop()||e,Zg=e=>`${Fk}${e??"default"}`,_l=e=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Zg(e));if(!t)return null;const s=JSON.parse(t);if(!s||typeof s!="object")return null;const n="isExpanded"in s&&typeof s.isExpanded=="boolean"?s.isExpanded:!0,o="expandedFiles"in s&&Array.isArray(s.expandedFiles)?s.expandedFiles.filter(a=>typeof a=="string"):[];return{isExpanded:n,expandedFiles:o}}catch{return null}},Ok=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Zg(e),JSON.stringify(t))}catch{}},Dk=({sessionDiffSummary:e,sessionId:t})=>{const{token:s}=xe.useToken(),n=!!(e&&e.files.length>0),[o,a]=m.useState(n),[i,l]=m.useState(n),[c,d]=m.useState(()=>{var g;return((g=_l(t))==null?void 0:g.isExpanded)??!0}),[u,h]=m.useState(()=>{var g;return new Set(((g=_l(t))==null?void 0:g.expandedFiles)??[])});m.useEffect(()=>{if(n){a(!0);const f=window.setTimeout(()=>l(!0),0);return()=>window.clearTimeout(f)}l(!1);const g=window.setTimeout(()=>a(!1),$k);return()=>window.clearTimeout(g)},[n]);const p=m.useMemo(()=>e?e.files:[],[e]),y=m.useMemo(()=>{const g=new Map;return e&&e.files.forEach(f=>{g.set(f.filePath,Wg(f.unifiedDiff))}),g},[e]);return m.useEffect(()=>{const g=_l(t);d((g==null?void 0:g.isExpanded)??!0),h(new Set((g==null?void 0:g.expandedFiles)??[]))},[t]),m.useEffect(()=>{Ok(t,{isExpanded:c,expandedFiles:Array.from(u)})},[t,c,u]),m.useEffect(()=>{if(!e||e.files.length===0)return;const g=new Set(e.files.map(f=>f.filePath));h(f=>{const b=new Set;let x=!1;return f.forEach(S=>{g.has(S)?b.add(S):x=!0}),!x&&b.size===f.size?f:b})},[e]),!o||!e?null:r.jsx("div",{className:`active-tool-card-wrapper ${i?"visible":""}`,"aria-hidden":!i,"data-testid":"session-diff-card",children:r.jsx(te,{size:"small",style:{width:"100%",borderRadius:s.borderRadiusLG,border:`1px solid ${s.colorBorderSecondary}`,background:s.colorBgContainer,boxShadow:s.boxShadowSecondary},bodyStyle:{padding:`${s.paddingXS}px ${s.paddingSM}px`},children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:6,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.marginSM,cursor:"pointer"},onClick:()=>d(g=>!g),"data-testid":"session-diff-toggle",children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.marginSM,minWidth:0},children:[r.jsx(Ep,{style:{color:s.colorPrimary}}),r.jsx(Ls,{strong:!0,style:{whiteSpace:"nowrap"},children:"Session diffs"}),r.jsxs(Ls,{type:"secondary",style:{fontSize:s.fontSizeSM,whiteSpace:"nowrap"},children:["(",e.files.length," files / ",e.changedTools," tools)"]}),r.jsxs(q,{size:4,style:{marginInlineStart:s.marginXS},children:[r.jsxs(Ls,{style:{color:s.colorSuccess,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",e.totalAdded]}),r.jsxs(Ls,{style:{color:s.colorError,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",e.totalRemoved]})]})]}),r.jsx("div",{style:{color:s.colorTextSecondary},children:c?r.jsx(Zt,{}):r.jsx(Bs,{})})]}),c&&r.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr",gap:6,maxHeight:280,overflowY:"auto"},"data-testid":"session-diff-file-list",children:p.map(g=>{const f=u.has(g.filePath),b=y.get(g.filePath)??[];return r.jsxs("div",{style:{border:`1px solid ${s.colorBorderSecondary}`,borderRadius:s.borderRadiusSM,overflow:"hidden",background:s.colorBgContainer},"data-testid":"session-diff-file-item","data-file-path":g.filePath,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.marginSM,padding:"4px 8px",borderRadius:s.borderRadiusSM,background:s.colorFillTertiary,cursor:"pointer"},onClick:()=>{h(x=>{const S=new Set(x);return S.has(g.filePath)?S.delete(g.filePath):S.add(g.filePath),S})},"data-testid":"session-diff-file-header","data-file-path":g.filePath,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.marginXS,minWidth:0,flex:1},children:[r.jsx("span",{style:{color:s.colorTextSecondary},children:f?r.jsx(Zt,{}):r.jsx(Bs,{})}),r.jsx(Ls,{ellipsis:{tooltip:g.filePath},style:{flex:1,minWidth:0,fontSize:s.fontSizeSM},children:Lk(g.filePath)})]}),r.jsxs(q,{size:4,children:[r.jsxs(Ls,{style:{color:s.colorSuccess,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",g.added]}),r.jsxs(Ls,{style:{color:s.colorError,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",g.removed]})]})]}),f&&r.jsxs("div",{style:{borderTop:`1px solid ${s.colorBorderSecondary}`,maxHeight:220,overflow:"auto",background:s.colorBgContainer},"data-testid":"session-diff-file-panel","data-file-path":g.filePath,children:[b.length>0?b.map((x,S)=>{const w={margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:s.fontSizeSM,lineHeight:1.5,padding:"0 8px",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"};return x.kind==="add"?w.background=s.colorSuccessBg:x.kind==="remove"?w.background=s.colorErrorBg:x.kind==="modified_add"?(w.background=s.colorWarningBg,w.borderLeft=`3px solid ${s.colorSuccess}`):x.kind==="modified_remove"?(w.background=s.colorWarningBg,w.borderLeft=`3px solid ${s.colorError}`):x.kind==="hunk"?(w.background=s.colorFillSecondary,w.color=s.colorTextSecondary):x.kind==="meta"&&(w.background=s.colorFillTertiary,w.color=s.colorTextSecondary),r.jsx("pre",{style:w,"data-testid":"session-diff-line","data-kind":x.kind,children:x.text||" "},`${g.filePath}-${S}`)}):r.jsx(Ls,{type:"secondary",style:{display:"block",padding:"8px",fontSize:s.fontSizeSM},children:"No diff preview available."}),g.truncated&&r.jsx(Ls,{type:"secondary",style:{display:"block",padding:"6px 8px 8px",fontSize:s.fontSizeSM},children:"Diff truncated for display."})]})]},g.filePath)})})]})})})},zk=e=>{if(!e)return;const{activeLeafId:t,setLeafSessionId:s,setActiveLeafId:n}=Ae.getState();s(t,e),n(t),z.getState().selectSession(e)},Nk=["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(" "),Bk=["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(" "),Wk=["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(" "),Uk=["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(" "),qk=["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(" "),Hk=["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(" "),Yk=["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(" "),Xk=["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(" "),Vk=["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(" "),Kk=["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(" "),Gk=["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(" "),Jk=["You are Bodhi operating in session review mode.","Help inspect and analyze past session history for patterns, insights, or issues.","Summarize key decisions, outcomes, and areas that may need follow-up."].join(" "),Qk=["You are Bodhi operating in context diagnostics mode.","Help analyze token usage, prompt bloat, context growth, truncation, and compression behavior.","Quantify likely causes when possible and recommend concrete, prioritized fixes.","Keep the output practical for engineers improving prompt and session efficiency."].join(" "),Zk=["development","debugging","analysis","documentation","operations"],eC={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"}},tC=(e,t)=>{const s=e.find(o=>o.id===t),n=e.find(o=>o.id==="general_assistant")||e[0];return{systemPromptId:(s==null?void 0:s.id)||(n==null?void 0:n.id)||"",baseSystemPrompt:(s==null?void 0:s.content)||(n==null?void 0:n.content)||""}},sC=({sessionId:e,embedded:t=!1})=>{const{t:s}=se(),{token:n}=xe.useToken(),{message:o}=ts.useApp(),a=z(xr(e)),i=z(j=>j.addChat),l=z(j=>j.lastSelectedPromptId),c=z(j=>j.setInputContent),d=z(j=>j.systemPrompts),[u,h]=m.useState(null),[p,y]=m.useState(""),g=a==null?void 0:a.config.workspacePath,f=m.useMemo(()=>[{id:"blank",icon:r.jsx(ks,{}),title:s("chat.emptyLauncher.actions.blank.title","Blank session"),description:s("chat.emptyLauncher.actions.blank.description","Start from scratch with the default assistant and an empty composer."),sessionTitle:s("chat.emptyLauncher.actions.blank.sessionTitle","New Session"),prefill:s("chat.emptyLauncher.actions.blank.prefill",""),category:"development"},{id:"codeReview",icon:r.jsx(ki,{}),title:s("chat.emptyLauncher.actions.codeReview.title","Code review"),description:s("chat.emptyLauncher.actions.codeReview.description","Open a review-focused session with an editable review brief."),sessionTitle:s("chat.emptyLauncher.actions.codeReview.sessionTitle","Code Review"),prefill:s("chat.emptyLauncher.actions.codeReview.prefill","Review the relevant code changes in this workspace or repository. Start with the overall scope, then list risks, notable diffs, and the most important fixes."),baseSystemPrompt:Nk,category:"development",recommendWorkspace:!0},{id:"implementFeature",icon:r.jsx(hr,{}),title:s("chat.emptyLauncher.actions.implementFeature.title","Implement feature"),description:s("chat.emptyLauncher.actions.implementFeature.description","Plan and build a feature step by step following existing code conventions."),sessionTitle:s("chat.emptyLauncher.actions.implementFeature.sessionTitle","Implement Feature"),prefill:s("chat.emptyLauncher.actions.implementFeature.prefill","Help me implement a new feature in this workspace. Start by understanding the codebase structure, then propose an implementation plan before writing code."),baseSystemPrompt:Wk,category:"development",recommendWorkspace:!0},{id:"refactor",icon:r.jsx(Ep,{}),title:s("chat.emptyLauncher.actions.refactor.title","Refactor code"),description:s("chat.emptyLauncher.actions.refactor.description","Get targeted suggestions for improving code quality and maintainability."),sessionTitle:s("chat.emptyLauncher.actions.refactor.sessionTitle","Refactor Suggestion"),prefill:s("chat.emptyLauncher.actions.refactor.prefill","Suggest refactoring improvements for the code in this workspace. Focus on readability, maintainability, and performance. Propose incremental changes with clear rationale."),baseSystemPrompt:Yk,category:"development",recommendWorkspace:!0},{id:"bugInvestigation",icon:r.jsx(Mp,{}),title:s("chat.emptyLauncher.actions.bugInvestigation.title","Bug investigation"),description:s("chat.emptyLauncher.actions.bugInvestigation.description","Diagnose issues by analyzing code, logs, and runtime behavior."),sessionTitle:s("chat.emptyLauncher.actions.bugInvestigation.sessionTitle","Bug Investigation"),prefill:s("chat.emptyLauncher.actions.bugInvestigation.prefill","Help me investigate a bug. I'll describe the symptoms and share relevant code or logs. Trace the root cause and suggest targeted fixes."),baseSystemPrompt:Bk,category:"debugging",recommendWorkspace:!0},{id:"explainError",icon:r.jsx(Rp,{}),title:s("chat.emptyLauncher.actions.explainError.title","Explain error"),description:s("chat.emptyLauncher.actions.explainError.description","Understand what went wrong from an error message or stack trace."),sessionTitle:s("chat.emptyLauncher.actions.explainError.sessionTitle","Explain Error"),prefill:s("chat.emptyLauncher.actions.explainError.prefill","Help me understand the following error. Explain the root cause, suggest fixes, and share prevention tips."),baseSystemPrompt:qk,category:"debugging"},{id:"tokenUsage",icon:r.jsx(Px,{}),title:s("chat.emptyLauncher.actions.tokenUsage.title","Token usage investigation"),description:s("chat.emptyLauncher.actions.tokenUsage.description","Diagnose context growth, truncation risk, and token budget pressure."),sessionTitle:s("chat.emptyLauncher.actions.tokenUsage.sessionTitle","Token Usage Investigation"),prefill:s("chat.emptyLauncher.actions.tokenUsage.prefill","Help me investigate token usage, context growth, and truncation risk for this session or workflow. Summarize the likely drivers and recommend concrete next fixes."),baseSystemPrompt:Qk,category:"debugging"},{id:"architectureReview",icon:r.jsx(Ex,{}),title:s("chat.emptyLauncher.actions.architectureReview.title","Read repo architecture"),description:s("chat.emptyLauncher.actions.architectureReview.description","Analyze repository structure, modules, and architectural patterns."),sessionTitle:s("chat.emptyLauncher.actions.architectureReview.sessionTitle","Architecture Review"),prefill:s("chat.emptyLauncher.actions.architectureReview.prefill","Analyze the architecture of this repository. Map the key modules, data flow, abstractions, and dependency patterns. Identify strengths and potential improvements."),baseSystemPrompt:Uk,category:"analysis",recommendWorkspace:!0},{id:"compareFiles",icon:r.jsx(Rx,{}),title:s("chat.emptyLauncher.actions.compareFiles.title","Compare files"),description:s("chat.emptyLauncher.actions.compareFiles.description","Diff and understand differences between files or code sections."),sessionTitle:s("chat.emptyLauncher.actions.compareFiles.sessionTitle","Compare Files"),prefill:s("chat.emptyLauncher.actions.compareFiles.prefill","Compare the following files or code sections. Highlight key differences, their implications, and any potential risks."),baseSystemPrompt:Hk,category:"analysis",recommendWorkspace:!0},{id:"releaseNotes",icon:r.jsx(dr,{}),title:s("chat.emptyLauncher.actions.releaseNotes.title","Generate release notes"),description:s("chat.emptyLauncher.actions.releaseNotes.description","Create structured release notes from git history and code changes."),sessionTitle:s("chat.emptyLauncher.actions.releaseNotes.sessionTitle","Release Notes"),prefill:s("chat.emptyLauncher.actions.releaseNotes.prefill","Generate release notes for the latest changes in this workspace. Categorize into features, fixes, improvements, and breaking changes."),baseSystemPrompt:Xk,category:"documentation",recommendWorkspace:!0},{id:"summarizeWork",icon:r.jsx(Ax,{}),title:s("chat.emptyLauncher.actions.summarizeWork.title","Summarize work"),description:s("chat.emptyLauncher.actions.summarizeWork.description","Create a work summary for standups or weekly status reports."),sessionTitle:s("chat.emptyLauncher.actions.summarizeWork.sessionTitle","Work Summary"),prefill:s("chat.emptyLauncher.actions.summarizeWork.prefill","Help me summarize my recent work for a status update. Pull key accomplishments, blockers, and next steps."),baseSystemPrompt:Vk,category:"documentation"},{id:"writeDocs",icon:r.jsx(dr,{}),title:s("chat.emptyLauncher.actions.writeDocs.title","Write documentation"),description:s("chat.emptyLauncher.actions.writeDocs.description","Create or improve technical documentation from code and context."),sessionTitle:s("chat.emptyLauncher.actions.writeDocs.sessionTitle","Write Documentation"),prefill:s("chat.emptyLauncher.actions.writeDocs.prefill","Help me write technical documentation for this project. Analyze the code and produce clear, well-structured Markdown documentation."),baseSystemPrompt:Kk,category:"documentation",recommendWorkspace:!0},{id:"createSchedule",icon:r.jsx(Us,{}),title:s("chat.emptyLauncher.actions.createSchedule.title","Create scheduled task"),description:s("chat.emptyLauncher.actions.createSchedule.description","Set up a recurring task that runs automatically on a schedule."),sessionTitle:s("chat.emptyLauncher.actions.createSchedule.sessionTitle","Create Schedule"),prefill:s("chat.emptyLauncher.actions.createSchedule.prefill","Help me set up a recurring scheduled task. I'll describe what I want it to do, and you guide me through the configuration."),baseSystemPrompt:Gk,category:"operations"},{id:"sessionReview",icon:r.jsx(Ho,{}),title:s("chat.emptyLauncher.actions.sessionReview.title","Review session history"),description:s("chat.emptyLauncher.actions.sessionReview.description","Inspect and analyze past sessions for patterns and insights."),sessionTitle:s("chat.emptyLauncher.actions.sessionReview.sessionTitle","Session Review"),prefill:s("chat.emptyLauncher.actions.sessionReview.prefill","Help me review my recent session history. Summarize key decisions, outcomes, and areas that need follow-up."),baseSystemPrompt:Jk,category:"operations"}],[s]),b=p.trim().toLowerCase(),x=m.useMemo(()=>b?f.filter(j=>j.title.toLowerCase().includes(b)||j.description.toLowerCase().includes(b)):f,[b,f]),S=m.useMemo(()=>{const j={};for(const v of x)j[v.category]||(j[v.category]=[]),j[v.category].push(v);return j},[x]),w=m.useCallback(j=>{typeof window>"u"||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent($c,{detail:{sessionId:j}}))},0)},[]),C=m.useCallback(async j=>{if(!u){h(j.id);try{const v=tC(d,l),k=await i({title:j.sessionTitle,createdAt:Date.now(),messages:[],config:{systemPromptId:v.systemPromptId,baseSystemPrompt:j.baseSystemPrompt??v.baseSystemPrompt,lastUsedEnhancedPrompt:null,...g?{workspacePath:g}:{}},currentInteraction:null});zk(k),j.prefill.trim().length>0&&c(k,j.prefill),w(k)}catch(v){console.error("[EmptyTaskLauncher] Failed to create session",v),o.error(v instanceof Error?v.message:s("chat.emptyLauncher.errors.createFailed","Failed to create session"))}finally{h(null)}}},[i,l,o,u,w,c,d,s,g]),_=m.useMemo(()=>({"--lotus-empty-launcher-border":n.colorBorderSecondary,"--lotus-empty-launcher-border-hover":n.colorPrimaryBorder,"--lotus-empty-launcher-bg":n.colorBgElevated,"--lotus-empty-launcher-icon-bg":n.colorPrimaryBg,"--lotus-empty-launcher-icon-color":n.colorPrimary,"--lotus-empty-launcher-text":n.colorText,"--lotus-empty-launcher-text-secondary":n.colorTextSecondary,"--lotus-empty-launcher-shadow":n.boxShadowSecondary,"--lotus-empty-launcher-shadow-hover":n.boxShadow,"--lotus-empty-launcher-category-border":n.colorBorderSecondary,"--lotus-empty-launcher-search-bg":n.colorBgContainer,"--lotus-empty-launcher-badge-bg":n.colorPrimaryBg,"--lotus-empty-launcher-badge-text":n.colorPrimary}),[n]),T=!!g;return r.jsxs("div",{className:`lotus-empty-task-launcher ${t?"is-embedded":""}`,style:_,children:[r.jsxs("div",{className:"lotus-empty-task-launcher__header",children:[r.jsx(le.Title,{level:t?4:3,style:{margin:0},children:s("chat.emptyLauncher.title","Start with a task")}),r.jsx(le.Paragraph,{type:"secondary",className:"lotus-empty-task-launcher__subtitle",children:s("chat.emptyLauncher.subtitle","Create a focused session in this pane and prefill the first message before you send it.")}),r.jsx(le.Text,{type:"secondary",className:"lotus-empty-task-launcher__hint",children:s("chat.emptyLauncher.hint","Nothing is sent automatically — you can edit the prompt first.")})]}),r.jsx("div",{className:"lotus-empty-task-launcher__search",children:r.jsx(ye,{placeholder:s("chat.emptyLauncher.searchPlaceholder","Search templates..."),prefix:r.jsx(Ho,{style:{color:n.colorTextQuaternary}}),value:p,onChange:j=>y(j.target.value),allowClear:!0,size:"middle",variant:"filled"})}),r.jsxs("div",{className:"lotus-empty-task-launcher__categories",children:[Zk.map(j=>{const v=S[j];if(!v||v.length===0)return null;const k=eC[j];return r.jsxs("div",{className:"lotus-empty-task-launcher__category",children:[r.jsx(le.Text,{type:"secondary",className:"lotus-empty-task-launcher__category-label",children:s(k.titleKey,k.fallback)}),r.jsx("div",{className:"lotus-empty-task-launcher__grid",children:v.map(E=>{const M=u===E.id,R=E.recommendWorkspace&&T;return r.jsxs("button",{type:"button",className:"lotus-empty-task-card",onClick:()=>{C(E)},disabled:u!==null,"aria-busy":M,"aria-label":E.title,children:[r.jsx("div",{className:"lotus-empty-task-card__icon","aria-hidden":!0,children:M?r.jsx(ta,{}):E.icon}),r.jsxs("div",{className:"lotus-empty-task-card__body",children:[r.jsxs("div",{className:"lotus-empty-task-card__titleRow",children:[r.jsx("span",{className:"lotus-empty-task-card__title",children:E.title}),r.jsx(Ix,{className:"lotus-empty-task-card__arrow","aria-hidden":!0})]}),r.jsx("p",{className:"lotus-empty-task-card__description",children:E.description}),R&&r.jsx("div",{className:"lotus-empty-task-card__badges",children:r.jsxs("span",{className:"lotus-empty-task-card__badge",title:g,children:["📂 ",s("chat.emptyLauncher.badges.workspace","workspace")]})})]})]},E.id)})})]},j)}),x.length===0&&r.jsx("div",{className:"lotus-empty-task-launcher__no-results",children:r.jsx(le.Text,{type:"secondary",children:s("chat.emptyLauncher.noResults","No templates match your search. Try a different keyword or start a blank session.")})})]})]})},nC=({sessionId:e,isCenteredLayout:t,maxWidth:s,onWorkflowDraftChange:n,showMessagesView:o,sessionDiffSummary:a,contextUsageIndicator:i})=>r.jsx(K,{justify:"center",className:`chat-view-input-container-wrapper ${o?"messages-view":"centered-view"}`,children:r.jsxs("div",{style:{width:"100%",maxWidth:o?"clamp(720px, 68vw, 1240px)":s,margin:o?"0 auto":void 0,position:"relative",paddingBottom:o?12:0,display:"flex",flexDirection:"column",gap:o?0:24},children:[o&&r.jsx(Dk,{sessionDiffSummary:a,sessionId:e}),!o&&e&&r.jsx(sC,{sessionId:e}),r.jsx(Ik,{sessionId:e,isCenteredLayout:t,onWorkflowDraftChange:n,statusIndicator:i})]})});function Kn(e,t,s){let n=s.initialDeps??[],o;function a(){var i,l,c,d;let u;s.key&&((i=s.debug)!=null&&i.call(s))&&(u=Date.now());const h=e();if(!(h.length!==n.length||h.some((g,f)=>n[f]!==g)))return o;n=h;let y;if(s.key&&((l=s.debug)!=null&&l.call(s))&&(y=Date.now()),o=t(...h),s.key&&((c=s.debug)!=null&&c.call(s))){const g=Math.round((Date.now()-u)*100)/100,f=Math.round((Date.now()-y)*100)/100,b=f/16,x=(S,w)=>{for(S=String(S);S.length<w;)S=" "+S;return S};console.info(`%c⏱ ${x(f,5)} /${x(g,5)} ms`,`
|
|
175
|
+
font-size: .6rem;
|
|
176
|
+
font-weight: bold;
|
|
177
|
+
color: hsl(${Math.max(0,Math.min(120-120*b,120))}deg 100% 31%);`,s==null?void 0:s.key)}return(d=s==null?void 0:s.onChange)==null||d.call(s,o),o}return a.updateDeps=i=>{n=i},a}function Nm(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const rC=(e,t)=>Math.abs(e-t)<1.01,oC=(e,t,s)=>{let n;return function(...o){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,o),s)}},Bm=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},aC=e=>e,iC=e=>{const t=Math.max(e.startIndex-e.overscan,0),s=Math.min(e.endIndex+e.overscan,e.count-1),n=[];for(let o=t;o<=s;o++)n.push(o);return n},lC=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;const o=i=>{const{width:l,height:c}=i;t({width:Math.round(l),height:Math.round(c)})};if(o(Bm(s)),!n.ResizeObserver)return()=>{};const a=new n.ResizeObserver(i=>{const l=()=>{const c=i[0];if(c!=null&&c.borderBoxSize){const d=c.borderBoxSize[0];if(d){o({width:d.inlineSize,height:d.blockSize});return}}o(Bm(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(s,{box:"border-box"}),()=>{a.unobserve(s)}},Wm={passive:!0},Um=typeof window>"u"?!0:"onscrollend"in window,cC=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;let o=0;const a=e.options.useScrollendEvent&&Um?()=>{}:oC(n,()=>{t(o,!1)},e.options.isScrollingResetDelay),i=u=>()=>{const{horizontal:h,isRtl:p}=e.options;o=h?s.scrollLeft*(p&&-1||1):s.scrollTop,a(),t(o,u)},l=i(!0),c=i(!1);c(),s.addEventListener("scroll",l,Wm);const d=e.options.useScrollendEvent&&Um;return d&&s.addEventListener("scrollend",c,Wm),()=>{s.removeEventListener("scroll",l),d&&s.removeEventListener("scrollend",c)}},dC=(e,t,s)=>{if(t!=null&&t.borderBoxSize){const n=t.borderBoxSize[0];if(n)return Math.round(n[s.options.horizontal?"inlineSize":"blockSize"])}return e[s.options.horizontal?"offsetWidth":"offsetHeight"]},uC=(e,{adjustments:t=0,behavior:s},n)=>{var o,a;const i=e+t;(a=(o=n.scrollElement)==null?void 0:o.scrollTo)==null||a.call(o,{[n.options.horizontal?"left":"top"]:i,behavior:s})};class mC{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.measurementsCache=[],this.itemSizeCache=new Map,this.pendingMeasuredCacheIndexes=[],this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.observer=(()=>{let s=null;const n=()=>s||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:s=new this.targetWindow.ResizeObserver(o=>{o.forEach(a=>{const i=()=>{this._measureElement(a.target,a)};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var o;(o=n())==null||o.disconnect(),s=null},observe:o=>{var a;return(a=n())==null?void 0:a.observe(o,{box:"border-box"})},unobserve:o=>{var a;return(a=n())==null?void 0:a.unobserve(o)}}})(),this.range=null,this.setOptions=s=>{Object.entries(s).forEach(([n,o])=>{typeof o>"u"&&delete s[n]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:aC,rangeExtractor:iC,onChange:()=>{},measureElement:dC,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,...s}},this.notify=s=>{var n,o;(o=(n=this.options).onChange)==null||o.call(n,this,s)},this.maybeNotify=Kn(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),s=>{this.notify(s)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(s=>s()),this.unsubs=[],this.observer.disconnect(),this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var s;const n=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==n){if(this.cleanup(),!n){this.maybeNotify();return}this.scrollElement=n,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((s=this.scrollElement)==null?void 0:s.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,a)=>{this.scrollAdjustments=0,this.scrollDirection=a?this.getScrollOffset()<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=a,this.maybeNotify()}))}},this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(s,n)=>{const o=new Map,a=new Map;for(let i=n-1;i>=0;i--){const l=s[i];if(o.has(l.lane))continue;const c=a.get(l.lane);if(c==null||l.end>c.end?a.set(l.lane,l):l.end<c.end&&o.set(l.lane,!0),o.size===this.options.lanes)break}return a.size===this.options.lanes?Array.from(a.values()).sort((i,l)=>i.end===l.end?i.index-l.index:i.end-l.end)[0]:void 0},this.getMeasurementOptions=Kn(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled],(s,n,o,a,i)=>(this.pendingMeasuredCacheIndexes=[],{count:s,paddingStart:n,scrollMargin:o,getItemKey:a,enabled:i}),{key:!1}),this.getMeasurements=Kn(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:s,paddingStart:n,scrollMargin:o,getItemKey:a,enabled:i},l)=>{if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),[];this.measurementsCache.length===0&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(u=>{this.itemSizeCache.set(u.key,u.size)}));const c=this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[];const d=this.measurementsCache.slice(0,c);for(let u=c;u<s;u++){const h=a(u),p=this.options.lanes===1?d[u-1]:this.getFurthestMeasurement(d,u),y=p?p.end+this.options.gap:n+o,g=l.get(h),f=typeof g=="number"?g:this.options.estimateSize(u),b=y+f,x=p?p.lane:u%this.options.lanes;d[u]={index:u,start:y,size:f,end:b,key:h,lane:x}}return this.measurementsCache=d,d},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Kn(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,n,o,a)=>this.range=s.length>0&&n>0?hC({measurements:s,outerSize:n,scrollOffset:o,lanes:a}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Kn(()=>{let s=null,n=null;const o=this.calculateRange();return o&&(s=o.startIndex,n=o.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,n]},(s,n,o,a,i)=>a===null||i===null?[]:s({startIndex:a,endIndex:i,overscan:n,count:o}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const n=this.options.indexAttribute,o=s.getAttribute(n);return o?parseInt(o,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this._measureElement=(s,n)=>{const o=this.indexFromElement(s),a=this.measurementsCache[o];if(!a)return;const i=a.key,l=this.elementsCache.get(i);l!==s&&(l&&this.observer.unobserve(l),this.observer.observe(s),this.elementsCache.set(i,s)),s.isConnected&&this.resizeItem(o,this.options.measureElement(s,n,this))},this.resizeItem=(s,n)=>{const o=this.measurementsCache[s];if(!o)return;const a=this.itemSizeCache.get(o.key)??o.size,i=n-a;i!==0&&((this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(o,i,this):o.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=i,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(o.index),this.itemSizeCache=new Map(this.itemSizeCache.set(o.key,n)),this.notify(!1))},this.measureElement=s=>{if(!s){this.elementsCache.forEach((n,o)=>{n.isConnected||(this.observer.unobserve(n),this.elementsCache.delete(o))});return}this._measureElement(s,void 0)},this.getVirtualItems=Kn(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,n)=>{const o=[];for(let a=0,i=s.length;a<i;a++){const l=s[a],c=n[l];o.push(c)}return o},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=s=>{const n=this.getMeasurements();if(n.length!==0)return Nm(n[ey(0,n.length-1,o=>Nm(n[o]).start,s)])},this.getOffsetForAlignment=(s,n,o=0)=>{const a=this.getSize(),i=this.getScrollOffset();n==="auto"&&(n=s>=i+a?"end":"start"),n==="center"?s+=(o-a)/2:n==="end"&&(s-=a);const l=this.getTotalSize()+this.options.scrollMargin-a;return Math.max(Math.min(l,s),0)},this.getOffsetForIndex=(s,n="auto")=>{s=Math.max(0,Math.min(s,this.options.count-1));const o=this.measurementsCache[s];if(!o)return;const a=this.getSize(),i=this.getScrollOffset();if(n==="auto")if(o.end>=i+a-this.options.scrollPaddingEnd)n="end";else if(o.start<=i+this.options.scrollPaddingStart)n="start";else return[i,n];const l=n==="end"?o.end+this.options.scrollPaddingEnd:o.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,n,o.size),n]},this.isDynamicMode=()=>this.elementsCache.size>0,this.scrollToOffset=(s,{align:n="start",behavior:o}={})=>{o==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getOffsetForAlignment(s,n),{adjustments:void 0,behavior:o})},this.scrollToIndex=(s,{align:n="auto",behavior:o}={})=>{o==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),s=Math.max(0,Math.min(s,this.options.count-1));let a=0;const i=10,l=d=>{if(!this.targetWindow)return;const u=this.getOffsetForIndex(s,d);if(!u){console.warn("Failed to get offset for index:",s);return}const[h,p]=u;this._scrollToOffset(h,{adjustments:void 0,behavior:o}),this.targetWindow.requestAnimationFrame(()=>{const y=this.getScrollOffset(),g=this.getOffsetForIndex(s,p);if(!g){console.warn("Failed to get offset for index:",s);return}rC(g[0],y)||c(p)})},c=d=>{this.targetWindow&&(a++,a<i?this.targetWindow.requestAnimationFrame(()=>l(d)):console.warn(`Failed to scroll to index ${s} after ${i} attempts.`))};l(n)},this.scrollBy=(s,{behavior:n}={})=>{n==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getScrollOffset()+s,{adjustments:void 0,behavior:n})},this.getTotalSize=()=>{var s;const n=this.getMeasurements();let o;if(n.length===0)o=this.options.paddingStart;else if(this.options.lanes===1)o=((s=n[n.length-1])==null?void 0:s.end)??0;else{const a=Array(this.options.lanes).fill(null);let i=n.length-1;for(;i>=0&&a.some(l=>l===null);){const l=n[i];a[l.lane]===null&&(a[l.lane]=l.end),i--}o=Math.max(...a.filter(l=>l!==null))}return Math.max(o-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(s,{adjustments:n,behavior:o})=>{this.options.scrollToFn(s,{behavior:o,adjustments:n},this)},this.measure=()=>{this.itemSizeCache=new Map,this.notify(!1)},this.setOptions(t)}}const ey=(e,t,s,n)=>{for(;e<=t;){const o=(e+t)/2|0,a=s(o);if(a<n)e=o+1;else if(a>n)t=o-1;else return o}return e>0?e-1:0};function hC({measurements:e,outerSize:t,scrollOffset:s,lanes:n}){const o=e.length-1,a=c=>e[c].start;if(e.length<=n)return{startIndex:0,endIndex:o};let i=ey(0,o,a,s),l=i;if(n===1)for(;l<o&&e[l].end<s+t;)l++;else if(n>1){const c=Array(n).fill(0);for(;l<o&&c.some(u=>u<s+t);){const u=e[l];c[u.lane]=u.end,l++}const d=Array(n).fill(s+t);for(;i>=0&&d.some(u=>u>=s);){const u=e[i];d[u.lane]=u.start,i--}i=Math.max(0,i-i%n),l=Math.min(o,l+(n-1-l%n))}return{startIndex:i,endIndex:l}}const qm=typeof document<"u"?m.useLayoutEffect:m.useEffect;function pC(e){const t=m.useReducer(()=>({}),{})[1],s={...e,onChange:(o,a)=>{var i;a?$x.flushSync(t):t(),(i=e.onChange)==null||i.call(e,o,a)}},[n]=m.useState(()=>new mC(s));return n.setOptions(s),qm(()=>n._didMount(),[]),qm(()=>n._willUpdate()),n}function fC(e){return pC({observeElementRect:lC,observeElementOffset:cC,scrollToFn:uC,...e})}const{Text:Hm,Paragraph:gC}=le,yC=({content:e,token:t,headingColor:s})=>r.jsx(us,{components:{p:({children:n})=>r.jsx(gC,{style:{marginBottom:t.marginSM},children:n}),ol:({children:n})=>r.jsx("ol",{style:{marginBottom:t.marginSM,paddingLeft:20},children:n}),ul:({children:n})=>r.jsx("ul",{style:{marginBottom:t.marginSM,paddingLeft:20},children:n}),li:({children:n})=>r.jsx("li",{style:{marginBottom:t.marginXS},children:n}),h1:({children:n})=>r.jsx(Hm,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block",color:s},children:n}),h2:({children:n})=>r.jsx(Hm,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block",color:s},children:n})},children:e}),xC=m.memo(yC),bC=({currentChat:e,message:t,systemPrompts:s})=>{var j;const[n,o]=m.useState(null),[a,i]=m.useState(null),[l,c]=m.useState(!1),[d,u]=m.useState(!1),h=m.useMemo(()=>ai.getInstance(),[]),p=m.useMemo(()=>hs.getInstance(),[]),y=t.role==="system"&&typeof t.content=="string"?t.content:"",g=t.role==="system"&&!t.id.startsWith("system-prompt-")&&y.trim().length>0;m.useEffect(()=>{t.role==="system"&&(i(null),u(!1))},[t.id,t.role,y]);const f=(e==null?void 0:e.id)??null,b=((j=e==null?void 0:e.config)==null?void 0:j.systemPromptId)??null,x=m.useMemo(()=>b?s.find(v=>v.id===b)??null:null,[b,s]),S=(x==null?void 0:x.content)??(n==null?void 0:n.content)??"",w=(x==null?void 0:x.description)??(n==null?void 0:n.description)??"",C=m.useRef(null);m.useEffect(()=>{o(null),C.current=null},[f,b]),m.useEffect(()=>{if(!b)return;const v=b;if(x!=null&&x.content)return;const k=`${f??"no-chat"}:${v}`;if(C.current===k)return;C.current=k;let E=!1;return(async()=>{try{const R=await h.findPresetById(v);if(E)return;const I=R?{content:R.content,description:R.description}:null;o(P=>!P&&!I||P&&I&&P.content===I.content&&P.description===I.description?P:I)}catch(R){console.error("Failed to load preset prompt:",R)}})(),()=>{E=!0}},[f,b,h,x==null?void 0:x.content]);const _=m.useCallback(async()=>{var v;if(!l){c(!0);try{if(f)try{const E=(v=(await p.getSessionSystemPrompt(f)).effective_system_prompt)==null?void 0:v.trim();if(E){i(E),u(!0);return}}catch(k){console.warn("Failed to load backend prompt snapshot:",k)}if(g){i(y),u(!0);return}console.warn("Enhanced prompt snapshot unavailable; keeping base prompt view.")}catch(k){console.error("Failed to load enhanced prompt:",k)}finally{c(!1)}}},[p,f,g,l,y]),T=m.useMemo(()=>d&&a?a:S||w||(t.role==="system"?y:"System prompt is being prepared..."),[d,a,S,w,t.role,y]);return{basePrompt:S,categoryDescription:w,enhancedPrompt:a,loadingEnhanced:l,loadEnhancedPrompt:_,promptToDisplay:T,showEnhanced:d,setShowEnhanced:u,systemMessageContent:y}},{Text:vC}=le,{useToken:SC}=xe,wC=({currentChat:e,message:t})=>{const{token:s}=SC(),n=z(h=>h.systemPrompts),{basePrompt:o,loadingEnhanced:a,loadEnhancedPrompt:i,promptToDisplay:l,showEnhanced:c,setShowEnhanced:d}=bC({currentChat:e,message:t,systemPrompts:n}),u=m.useCallback(async h=>{try{await es(h)}catch(p){console.error("Failed to copy text:",p)}},[]);return r.jsx(te,{style:{width:"100%",maxWidth:"100%",background:s.colorBgContainer,borderRadius:s.borderRadiusLG,boxShadow:"none"},children:r.jsxs(q,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[r.jsxs(K,{justify:"space-between",align:"center",children:[r.jsx(K,{align:"center",gap:s.marginXS,children:r.jsx(vC,{type:"secondary",strong:!0,style:{fontSize:s.fontSizeSM},children:"System Prompt"})}),r.jsxs(q,{children:[o&&!c?r.jsx(B,{type:"text",size:"small",icon:r.jsx(qc,{}),onClick:i,loading:a,children:"View Enhanced"}):null,o&&c?r.jsx(B,{type:"text",size:"small",onClick:()=>d(!1),children:"View Base"}):null,r.jsx(B,{type:"text",size:"small",icon:r.jsx(Jt,{}),onClick:()=>u(l),children:"Copy"})]})]}),r.jsx(K,{vertical:!0,style:{maxHeight:c?400:300,overflowY:"auto",paddingRight:s.paddingXS},children:r.jsx(xC,{content:l,token:s,headingColor:s.colorPrimary})})]})})},ty=m.memo(wC);ty.displayName="SystemMessageCard";const sy=6048e5,_C=864e5,Ym=Symbol.for("constructDateFrom");function an(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&Ym in e?e[Ym](t):e instanceof Date?new e.constructor(t):new Date(t)}function ps(e,t){return an(t||e,e)}let TC={};function Bi(){return TC}function ea(e,t){var l,c,d,u;const s=Bi(),n=(t==null?void 0:t.weekStartsOn)??((c=(l=t==null?void 0:t.locale)==null?void 0:l.options)==null?void 0:c.weekStartsOn)??s.weekStartsOn??((u=(d=s.locale)==null?void 0:d.options)==null?void 0:u.weekStartsOn)??0,o=ps(e,t==null?void 0:t.in),a=o.getDay(),i=(a<n?7:0)+a-n;return o.setDate(o.getDate()-i),o.setHours(0,0,0,0),o}function bi(e,t){return ea(e,{...t,weekStartsOn:1})}function ny(e,t){const s=ps(e,t==null?void 0:t.in),n=s.getFullYear(),o=an(s,0);o.setFullYear(n+1,0,4),o.setHours(0,0,0,0);const a=bi(o),i=an(s,0);i.setFullYear(n,0,4),i.setHours(0,0,0,0);const l=bi(i);return s.getTime()>=a.getTime()?n+1:s.getTime()>=l.getTime()?n:n-1}function Xm(e){const t=ps(e),s=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return s.setUTCFullYear(t.getFullYear()),+e-+s}function kC(e,...t){const s=an.bind(null,t.find(n=>typeof n=="object"));return t.map(s)}function Vm(e,t){const s=ps(e,t==null?void 0:t.in);return s.setHours(0,0,0,0),s}function CC(e,t,s){const[n,o]=kC(s==null?void 0:s.in,e,t),a=Vm(n),i=Vm(o),l=+a-Xm(a),c=+i-Xm(i);return Math.round((l-c)/_C)}function jC(e,t){const s=ny(e,t),n=an(e,0);return n.setFullYear(s,0,4),n.setHours(0,0,0,0),bi(n)}function MC(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function PC(e){return!(!MC(e)&&typeof e!="number"||isNaN(+ps(e)))}function EC(e,t){const s=ps(e,t==null?void 0:t.in);return s.setFullYear(s.getFullYear(),0,1),s.setHours(0,0,0,0),s}const RC={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"}},AC=(e,t,s)=>{let n;const o=RC[e];return typeof o=="string"?n=o:t===1?n=o.one:n=o.other.replace("{{count}}",t.toString()),s!=null&&s.addSuffix?s.comparison&&s.comparison>0?"in "+n:n+" ago":n};function Tl(e){return(t={})=>{const s=t.width?String(t.width):e.defaultWidth;return e.formats[s]||e.formats[e.defaultWidth]}}const IC={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},$C={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},FC={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},LC={date:Tl({formats:IC,defaultWidth:"full"}),time:Tl({formats:$C,defaultWidth:"full"}),dateTime:Tl({formats:FC,defaultWidth:"full"})},OC={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},DC=(e,t,s,n)=>OC[e];function Or(e){return(t,s)=>{const n=s!=null&&s.context?String(s.context):"standalone";let o;if(n==="formatting"&&e.formattingValues){const i=e.defaultFormattingWidth||e.defaultWidth,l=s!=null&&s.width?String(s.width):i;o=e.formattingValues[l]||e.formattingValues[i]}else{const i=e.defaultWidth,l=s!=null&&s.width?String(s.width):e.defaultWidth;o=e.values[l]||e.values[i]}const a=e.argumentCallback?e.argumentCallback(t):t;return o[a]}}const zC={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},NC={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},BC={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"]},WC={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"]},UC={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"}},qC={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"}},HC=(e,t)=>{const s=Number(e),n=s%100;if(n>20||n<10)switch(n%10){case 1:return s+"st";case 2:return s+"nd";case 3:return s+"rd"}return s+"th"},YC={ordinalNumber:HC,era:Or({values:zC,defaultWidth:"wide"}),quarter:Or({values:NC,defaultWidth:"wide",argumentCallback:e=>e-1}),month:Or({values:BC,defaultWidth:"wide"}),day:Or({values:WC,defaultWidth:"wide"}),dayPeriod:Or({values:UC,defaultWidth:"wide",formattingValues:qC,defaultFormattingWidth:"wide"})};function Dr(e){return(t,s={})=>{const n=s.width,o=n&&e.matchPatterns[n]||e.matchPatterns[e.defaultMatchWidth],a=t.match(o);if(!a)return null;const i=a[0],l=n&&e.parsePatterns[n]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(l)?VC(l,h=>h.test(i)):XC(l,h=>h.test(i));let d;d=e.valueCallback?e.valueCallback(c):c,d=s.valueCallback?s.valueCallback(d):d;const u=t.slice(i.length);return{value:d,rest:u}}}function XC(e,t){for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)&&t(e[s]))return s}function VC(e,t){for(let s=0;s<e.length;s++)if(t(e[s]))return s}function KC(e){return(t,s={})=>{const n=t.match(e.matchPattern);if(!n)return null;const o=n[0],a=t.match(e.parsePattern);if(!a)return null;let i=e.valueCallback?e.valueCallback(a[0]):a[0];i=s.valueCallback?s.valueCallback(i):i;const l=t.slice(o.length);return{value:i,rest:l}}}const GC=/^(\d+)(th|st|nd|rd)?/i,JC=/\d+/i,QC={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},ZC={any:[/^b/i,/^(a|c)/i]},ej={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},tj={any:[/1/i,/2/i,/3/i,/4/i]},sj={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},nj={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]},rj={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},oj={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]},aj={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},ij={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}},lj={ordinalNumber:KC({matchPattern:GC,parsePattern:JC,valueCallback:e=>parseInt(e,10)}),era:Dr({matchPatterns:QC,defaultMatchWidth:"wide",parsePatterns:ZC,defaultParseWidth:"any"}),quarter:Dr({matchPatterns:ej,defaultMatchWidth:"wide",parsePatterns:tj,defaultParseWidth:"any",valueCallback:e=>e+1}),month:Dr({matchPatterns:sj,defaultMatchWidth:"wide",parsePatterns:nj,defaultParseWidth:"any"}),day:Dr({matchPatterns:rj,defaultMatchWidth:"wide",parsePatterns:oj,defaultParseWidth:"any"}),dayPeriod:Dr({matchPatterns:aj,defaultMatchWidth:"any",parsePatterns:ij,defaultParseWidth:"any"})},cj={code:"en-US",formatDistance:AC,formatLong:LC,formatRelative:DC,localize:YC,match:lj,options:{weekStartsOn:0,firstWeekContainsDate:1}};function dj(e,t){const s=ps(e,t==null?void 0:t.in);return CC(s,EC(s))+1}function uj(e,t){const s=ps(e,t==null?void 0:t.in),n=+bi(s)-+jC(s);return Math.round(n/sy)+1}function ry(e,t){var u,h,p,y;const s=ps(e,t==null?void 0:t.in),n=s.getFullYear(),o=Bi(),a=(t==null?void 0:t.firstWeekContainsDate)??((h=(u=t==null?void 0:t.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??o.firstWeekContainsDate??((y=(p=o.locale)==null?void 0:p.options)==null?void 0:y.firstWeekContainsDate)??1,i=an((t==null?void 0:t.in)||e,0);i.setFullYear(n+1,0,a),i.setHours(0,0,0,0);const l=ea(i,t),c=an((t==null?void 0:t.in)||e,0);c.setFullYear(n,0,a),c.setHours(0,0,0,0);const d=ea(c,t);return+s>=+l?n+1:+s>=+d?n:n-1}function mj(e,t){var l,c,d,u;const s=Bi(),n=(t==null?void 0:t.firstWeekContainsDate)??((c=(l=t==null?void 0:t.locale)==null?void 0:l.options)==null?void 0:c.firstWeekContainsDate)??s.firstWeekContainsDate??((u=(d=s.locale)==null?void 0:d.options)==null?void 0:u.firstWeekContainsDate)??1,o=ry(e,t),a=an((t==null?void 0:t.in)||e,0);return a.setFullYear(o,0,n),a.setHours(0,0,0,0),ea(a,t)}function hj(e,t){const s=ps(e,t==null?void 0:t.in),n=+ea(s,t)-+mj(s,t);return Math.round(n/sy)+1}function ze(e,t){const s=e<0?"-":"",n=Math.abs(e).toString().padStart(t,"0");return s+n}const tn={y(e,t){const s=e.getFullYear(),n=s>0?s:1-s;return ze(t==="yy"?n%100:n,t.length)},M(e,t){const s=e.getMonth();return t==="M"?String(s+1):ze(s+1,2)},d(e,t){return ze(e.getDate(),t.length)},a(e,t){const s=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return s.toUpperCase();case"aaa":return s;case"aaaaa":return s[0];case"aaaa":default:return s==="am"?"a.m.":"p.m."}},h(e,t){return ze(e.getHours()%12||12,t.length)},H(e,t){return ze(e.getHours(),t.length)},m(e,t){return ze(e.getMinutes(),t.length)},s(e,t){return ze(e.getSeconds(),t.length)},S(e,t){const s=t.length,n=e.getMilliseconds(),o=Math.trunc(n*Math.pow(10,s-3));return ze(o,t.length)}},Gn={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Km={G:function(e,t,s){const n=e.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return s.era(n,{width:"abbreviated"});case"GGGGG":return s.era(n,{width:"narrow"});case"GGGG":default:return s.era(n,{width:"wide"})}},y:function(e,t,s){if(t==="yo"){const n=e.getFullYear(),o=n>0?n:1-n;return s.ordinalNumber(o,{unit:"year"})}return tn.y(e,t)},Y:function(e,t,s,n){const o=ry(e,n),a=o>0?o:1-o;if(t==="YY"){const i=a%100;return ze(i,2)}return t==="Yo"?s.ordinalNumber(a,{unit:"year"}):ze(a,t.length)},R:function(e,t){const s=ny(e);return ze(s,t.length)},u:function(e,t){const s=e.getFullYear();return ze(s,t.length)},Q:function(e,t,s){const n=Math.ceil((e.getMonth()+1)/3);switch(t){case"Q":return String(n);case"QQ":return ze(n,2);case"Qo":return s.ordinalNumber(n,{unit:"quarter"});case"QQQ":return s.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return s.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return s.quarter(n,{width:"wide",context:"formatting"})}},q:function(e,t,s){const n=Math.ceil((e.getMonth()+1)/3);switch(t){case"q":return String(n);case"qq":return ze(n,2);case"qo":return s.ordinalNumber(n,{unit:"quarter"});case"qqq":return s.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return s.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return s.quarter(n,{width:"wide",context:"standalone"})}},M:function(e,t,s){const n=e.getMonth();switch(t){case"M":case"MM":return tn.M(e,t);case"Mo":return s.ordinalNumber(n+1,{unit:"month"});case"MMM":return s.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return s.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return s.month(n,{width:"wide",context:"formatting"})}},L:function(e,t,s){const n=e.getMonth();switch(t){case"L":return String(n+1);case"LL":return ze(n+1,2);case"Lo":return s.ordinalNumber(n+1,{unit:"month"});case"LLL":return s.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return s.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return s.month(n,{width:"wide",context:"standalone"})}},w:function(e,t,s,n){const o=hj(e,n);return t==="wo"?s.ordinalNumber(o,{unit:"week"}):ze(o,t.length)},I:function(e,t,s){const n=uj(e);return t==="Io"?s.ordinalNumber(n,{unit:"week"}):ze(n,t.length)},d:function(e,t,s){return t==="do"?s.ordinalNumber(e.getDate(),{unit:"date"}):tn.d(e,t)},D:function(e,t,s){const n=dj(e);return t==="Do"?s.ordinalNumber(n,{unit:"dayOfYear"}):ze(n,t.length)},E:function(e,t,s){const n=e.getDay();switch(t){case"E":case"EE":case"EEE":return s.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return s.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return s.day(n,{width:"short",context:"formatting"});case"EEEE":default:return s.day(n,{width:"wide",context:"formatting"})}},e:function(e,t,s,n){const o=e.getDay(),a=(o-n.weekStartsOn+8)%7||7;switch(t){case"e":return String(a);case"ee":return ze(a,2);case"eo":return s.ordinalNumber(a,{unit:"day"});case"eee":return s.day(o,{width:"abbreviated",context:"formatting"});case"eeeee":return s.day(o,{width:"narrow",context:"formatting"});case"eeeeee":return s.day(o,{width:"short",context:"formatting"});case"eeee":default:return s.day(o,{width:"wide",context:"formatting"})}},c:function(e,t,s,n){const o=e.getDay(),a=(o-n.weekStartsOn+8)%7||7;switch(t){case"c":return String(a);case"cc":return ze(a,t.length);case"co":return s.ordinalNumber(a,{unit:"day"});case"ccc":return s.day(o,{width:"abbreviated",context:"standalone"});case"ccccc":return s.day(o,{width:"narrow",context:"standalone"});case"cccccc":return s.day(o,{width:"short",context:"standalone"});case"cccc":default:return s.day(o,{width:"wide",context:"standalone"})}},i:function(e,t,s){const n=e.getDay(),o=n===0?7:n;switch(t){case"i":return String(o);case"ii":return ze(o,t.length);case"io":return s.ordinalNumber(o,{unit:"day"});case"iii":return s.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return s.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return s.day(n,{width:"short",context:"formatting"});case"iiii":default:return s.day(n,{width:"wide",context:"formatting"})}},a:function(e,t,s){const o=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return s.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"aaa":return s.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return s.dayPeriod(o,{width:"narrow",context:"formatting"});case"aaaa":default:return s.dayPeriod(o,{width:"wide",context:"formatting"})}},b:function(e,t,s){const n=e.getHours();let o;switch(n===12?o=Gn.noon:n===0?o=Gn.midnight:o=n/12>=1?"pm":"am",t){case"b":case"bb":return s.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"bbb":return s.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return s.dayPeriod(o,{width:"narrow",context:"formatting"});case"bbbb":default:return s.dayPeriod(o,{width:"wide",context:"formatting"})}},B:function(e,t,s){const n=e.getHours();let o;switch(n>=17?o=Gn.evening:n>=12?o=Gn.afternoon:n>=4?o=Gn.morning:o=Gn.night,t){case"B":case"BB":case"BBB":return s.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"BBBBB":return s.dayPeriod(o,{width:"narrow",context:"formatting"});case"BBBB":default:return s.dayPeriod(o,{width:"wide",context:"formatting"})}},h:function(e,t,s){if(t==="ho"){let n=e.getHours()%12;return n===0&&(n=12),s.ordinalNumber(n,{unit:"hour"})}return tn.h(e,t)},H:function(e,t,s){return t==="Ho"?s.ordinalNumber(e.getHours(),{unit:"hour"}):tn.H(e,t)},K:function(e,t,s){const n=e.getHours()%12;return t==="Ko"?s.ordinalNumber(n,{unit:"hour"}):ze(n,t.length)},k:function(e,t,s){let n=e.getHours();return n===0&&(n=24),t==="ko"?s.ordinalNumber(n,{unit:"hour"}):ze(n,t.length)},m:function(e,t,s){return t==="mo"?s.ordinalNumber(e.getMinutes(),{unit:"minute"}):tn.m(e,t)},s:function(e,t,s){return t==="so"?s.ordinalNumber(e.getSeconds(),{unit:"second"}):tn.s(e,t)},S:function(e,t){return tn.S(e,t)},X:function(e,t,s){const n=e.getTimezoneOffset();if(n===0)return"Z";switch(t){case"X":return Jm(n);case"XXXX":case"XX":return _n(n);case"XXXXX":case"XXX":default:return _n(n,":")}},x:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"x":return Jm(n);case"xxxx":case"xx":return _n(n);case"xxxxx":case"xxx":default:return _n(n,":")}},O:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+Gm(n,":");case"OOOO":default:return"GMT"+_n(n,":")}},z:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+Gm(n,":");case"zzzz":default:return"GMT"+_n(n,":")}},t:function(e,t,s){const n=Math.trunc(+e/1e3);return ze(n,t.length)},T:function(e,t,s){return ze(+e,t.length)}};function Gm(e,t=""){const s=e>0?"-":"+",n=Math.abs(e),o=Math.trunc(n/60),a=n%60;return a===0?s+String(o):s+String(o)+t+ze(a,2)}function Jm(e,t){return e%60===0?(e>0?"-":"+")+ze(Math.abs(e)/60,2):_n(e,t)}function _n(e,t=""){const s=e>0?"-":"+",n=Math.abs(e),o=ze(Math.trunc(n/60),2),a=ze(n%60,2);return s+o+t+a}const Qm=(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"})}},oy=(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"})}},pj=(e,t)=>{const s=e.match(/(P+)(p+)?/)||[],n=s[1],o=s[2];if(!o)return Qm(e,t);let a;switch(n){case"P":a=t.dateTime({width:"short"});break;case"PP":a=t.dateTime({width:"medium"});break;case"PPP":a=t.dateTime({width:"long"});break;case"PPPP":default:a=t.dateTime({width:"full"});break}return a.replace("{{date}}",Qm(n,t)).replace("{{time}}",oy(o,t))},fj={p:oy,P:pj},gj=/^D+$/,yj=/^Y+$/,xj=["D","DD","YY","YYYY"];function bj(e){return gj.test(e)}function vj(e){return yj.test(e)}function Sj(e,t,s){const n=wj(e,t,s);if(console.warn(n),xj.includes(e))throw new RangeError(n)}function wj(e,t,s){const n=e[0]==="Y"?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${n} to the input \`${s}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const _j=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Tj=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,kj=/^'([^]*?)'?$/,Cj=/''/g,jj=/[a-zA-Z]/;function Mj(e,t,s){var u,h,p,y;const n=Bi(),o=n.locale??cj,a=n.firstWeekContainsDate??((h=(u=n.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??1,i=n.weekStartsOn??((y=(p=n.locale)==null?void 0:p.options)==null?void 0:y.weekStartsOn)??0,l=ps(e,s==null?void 0:s.in);if(!PC(l))throw new RangeError("Invalid time value");let c=t.match(Tj).map(g=>{const f=g[0];if(f==="p"||f==="P"){const b=fj[f];return b(g,o.formatLong)}return g}).join("").match(_j).map(g=>{if(g==="''")return{isToken:!1,value:"'"};const f=g[0];if(f==="'")return{isToken:!1,value:Pj(g)};if(Km[f])return{isToken:!0,value:g};if(f.match(jj))throw new RangeError("Format string contains an unescaped latin alphabet character `"+f+"`");return{isToken:!1,value:g}});o.localize.preprocessor&&(c=o.localize.preprocessor(l,c));const d={firstWeekContainsDate:a,weekStartsOn:i,locale:o};return c.map(g=>{if(!g.isToken)return g.value;const f=g.value;(vj(f)||bj(f))&&Sj(f,t,String(e));const b=Km[f[0]];return b(l,f,o.localize,d)}).join("")}function Pj(e){const t=e.match(kj);return t?t[1].replace(Cj,"'"):e}const{useToken:Ej}=xe,{Text:Ea}=le,Rj=({images:e,className:t,style:s,maxHeight:n={single:400,multiple:200}})=>{const{token:o}=Ej(),{t:a}=se();return!e||e.length===0?null:r.jsx(te,{className:t,style:{marginBottom:o.marginMD,...s},styles:{body:{padding:0}},variant:"borderless",children:r.jsx(K,{wrap:"wrap",gap:o.marginSM,style:{width:"100%"},children:e.map(i=>r.jsxs(te,{size:"small",style:{flex:e.length===1?"1 1 100%":"1 1 200px",overflow:"hidden",borderRadius:o.borderRadius,border:`1px solid ${o.colorBorderSecondary}`,backgroundColor:o.colorBgLayout},styles:{body:{padding:0}},children:[r.jsxs("div",{style:{position:"relative"},children:[r.jsx(Fx,{src:i.url||i.base64,alt:i.name,style:{width:"100%",height:"auto",maxHeight:e.length===1?n.single:n.multiple,objectFit:"cover"},preview:{mask:r.jsxs(K,{align:"center",justify:"center",gap:o.marginXS,style:{color:o.colorTextLightSolid},children:[r.jsx(qc,{}),r.jsx(Ea,{style:{color:o.colorTextLightSolid},children:a("components.imageGrid.preview")})]})}}),r.jsxs(K,{vertical:!0,style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(transparent, rgba(0,0,0,0.7))",color:o.colorTextLightSolid,padding:`${o.paddingXS}px ${o.paddingSM}px`,fontSize:o.fontSizeSM},children:[r.jsx(Ea,{style:{color:o.colorTextLightSolid},strong:!0,children:i.name}),i.size&&r.jsxs(Ea,{style:{fontSize:o.fontSizeSM*.85,opacity:.8,color:o.colorTextLightSolid},children:[(i.size/1024).toFixed(1)," KB",i.width&&i.height&&` • ${i.width}×${i.height}`]})]})]}),(i.ocrText||i.ocrError)&&r.jsx("div",{style:{padding:o.paddingSM},children:r.jsx(js,{ghost:!0,size:"small",items:[{key:"ocr",label:a("components.imageGrid.ocr"),children:r.jsxs(r.Fragment,{children:[i.ocrError&&r.jsx(Ea,{type:"danger",children:i.ocrError}),i.ocrText&&r.jsx(le.Paragraph,{style:{marginTop:i.ocrError?o.marginXS:0,marginBottom:0,whiteSpace:"pre-wrap"},children:i.ocrText})]})}]})})]},i.id))})})},{useToken:Aj}=xe,{useBreakpoint:Ij}=_i,$j=({buttons:e,isVisible:t,className:s,style:n,position:o={bottom:"8px",right:"8px"}})=>{const{token:a}=Aj(),i=Ij(),l=()=>(i.xs,"small");return r.jsx(K,{justify:"flex-end",gap:a.marginXS,className:s,style:{marginTop:a.marginXS,position:"absolute",bottom:o.bottom,right:o.right,top:o.top,left:o.left,background:"transparent",zIndex:1,opacity:t?1:0,transition:"opacity 0.2s ease",pointerEvents:t?"auto":"none",...n},children:e.map(c=>r.jsx(je,{title:c.title,children:r.jsx(B,{"data-testid":c["data-testid"]||c.key,icon:c.icon,size:l(),type:"text",onClick:c.onClick,disabled:c.disabled,style:{background:a.colorBgElevated,borderRadius:a.borderRadiusSM}})},c.key))})},Fj=(e,t)=>({key:"copy","data-testid":"copy-message",icon:r.jsx(Jt,{}),title:t||"Copy message",onClick:e}),Lj=(e,t)=>({key:"reference",icon:r.jsx(Ap,{}),title:t||"Reference message",onClick:e}),{Title:Zm,Text:Bt,Paragraph:eh}=le,{useToken:Oj}=xe,Dj=({plan:e,contextId:t,onExecute:s,onRefine:n,timestamp:o})=>{const{t:a}=se(),{token:i}=Oj(),[l,c]=m.useState(!1),[d,u]=m.useState(""),h=()=>{d.trim()&&(n(d),u(""),c(!1))};return r.jsxs(te,{style:{marginBottom:i.marginMD,borderColor:i.colorPrimary,borderWidth:2,backgroundColor:i.colorPrimaryBg},title:r.jsxs(q,{children:[r.jsx(Ws,{style:{color:i.colorPrimary}}),r.jsx(Bt,{strong:!0,style:{color:i.colorPrimary},children:a("components.plan.executionPlan")})]}),extra:o?r.jsx(Bt,{type:"secondary",style:{fontSize:i.fontSizeSM},children:o}):void 0,children:[r.jsxs(K,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(Zm,{level:5,style:{marginBottom:i.marginXS},children:a("components.plan.goal")}),r.jsx(eh,{style:{fontSize:15,marginBottom:0},children:e.goal})]}),r.jsxs(K,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(Zm,{level:5,style:{marginBottom:i.marginMD},children:a("components.plan.steps")}),r.jsx(Ip,{direction:"vertical",current:-1,items:e.steps.map(p=>({title:r.jsxs(Bt,{strong:!0,children:[a("components.plan.stepTitle",{number:p.step_number}),": ",p.action]}),description:r.jsxs(K,{vertical:!0,children:[r.jsxs(eh,{style:{marginBottom:i.marginXS},children:[r.jsxs(Bt,{type:"secondary",children:[a("components.plan.reason"),":"]})," ",p.reason]}),r.jsxs(q,{wrap:!0,children:[r.jsxs(Bt,{type:"secondary",children:[r.jsx(hr,{})," ",a("components.plan.tools"),":"]}),p.tools_needed.map((y,g)=>r.jsx(fe,{color:"processing",children:y},g))]}),r.jsx(K,{style:{marginTop:i.marginXS},children:r.jsxs(Bt,{type:"secondary",children:[r.jsx(Us,{})," ",a("components.plan.estimated"),": ",p.estimated_time]})})]}),icon:r.jsx(Bt,{children:p.step_number})}))})]}),r.jsxs(q,{direction:"vertical",style:{width:"100%",marginBottom:i.marginLG},children:[r.jsxs(K,{align:"center",gap:i.marginXS,wrap:"wrap",children:[r.jsxs(Bt,{type:"secondary",children:[r.jsx(Us,{})," ",a("components.plan.totalEstimatedTime")," "]}),r.jsx(fe,{color:"processing",children:e.estimated_total_time})]}),e.prerequisites&&e.prerequisites.length>0&&r.jsxs(K,{vertical:!0,children:[r.jsxs(Bt,{type:"secondary",children:[a("components.plan.prerequisites"),":"]}),r.jsx(Ge,{size:"small",dataSource:e.prerequisites,renderItem:(p,y)=>r.jsx(Ge.Item,{style:{padding:0},children:r.jsx(Bt,{children:p})},`${p}-${y}`)})]})]}),e.risks&&e.risks.length>0&&r.jsx(js,{ghost:!0,style:{marginBottom:i.marginLG},items:[{key:"risks",label:r.jsxs(q,{children:[r.jsx(gr,{style:{color:i.colorWarning}}),r.jsx(Bt,{strong:!0,children:a("components.plan.potentialRisks",{count:e.risks.length})})]}),children:r.jsx(Ge,{size:"small",dataSource:e.risks,renderItem:(p,y)=>r.jsx(Ge.Item,{style:{padding:0},children:r.jsx(Bt,{children:p})},`${p}-${y}`)})}]}),r.jsx(q,{style:{width:"100%",justifyContent:"flex-end"},children:l?r.jsxs(r.Fragment,{children:[r.jsx(B,{onClick:()=>c(!1),children:a("common.cancel")}),r.jsx(B,{type:"primary",onClick:h,disabled:!d.trim(),children:a("components.plan.sendFeedback")})]}):r.jsxs(r.Fragment,{children:[r.jsx(B,{onClick:()=>c(!0),children:a("components.plan.refinePlan")}),r.jsx(B,{type:"primary",icon:r.jsx(La,{}),onClick:s,children:a("components.plan.executePlan")})]})}),l&&r.jsx(K,{vertical:!0,style:{marginTop:i.marginMD},children:r.jsx(ye.TextArea,{value:d,onChange:p=>u(p.target.value),placeholder:a("components.plan.feedbackPlaceholder"),autoSize:{minRows:4,maxRows:10}})})]})},ay=m.memo(Dj);ay.displayName="PlanMessageCard";const{Title:zj,Text:Jn,Paragraph:Nj}=le,{useToken:Bj}=xe,Wj=({question:e,contextId:t,onAnswer:s,disabled:n=!1,timestamp:o})=>{const{t:a}=se(),{token:i}=Bj(),[l,c]=m.useState(e.default),[d,u]=m.useState(!1),h=async()=>{if(l){u(!0);try{await s(l)}catch(f){console.error("Failed to submit answer:",f)}finally{u(!1)}}},p=()=>{switch(e.severity){case"critical":return r.jsx(Ci,{style:{color:i.colorError}});case"major":return r.jsx(gr,{style:{color:i.colorWarning}});case"minor":return r.jsx(jt,{style:{color:i.colorInfo}});default:return r.jsx(Rp,{style:{color:i.colorPrimary}})}},y=()=>{switch(e.severity){case"critical":return i.colorErrorBg;case"major":return i.colorWarningBg;case"minor":return i.colorInfoBg;default:return i.colorPrimaryBg}},g=()=>{switch(e.severity){case"critical":return i.colorError;case"major":return i.colorWarning;case"minor":return i.colorInfo;default:return i.colorPrimary}};return r.jsxs(te,{style:{marginBottom:i.marginMD,borderColor:g(),borderWidth:2,backgroundColor:y()},title:r.jsxs(q,{children:[p(),r.jsx(Jn,{strong:!0,style:{color:g()},children:a("components.question.agentQuestion")}),r.jsxs(Jn,{type:"secondary",style:{fontSize:12},children:["(",e.severity,")"]})]}),extra:o?r.jsx(Jn,{type:"secondary",style:{fontSize:i.fontSizeSM},children:o}):void 0,children:[r.jsx(K,{vertical:!0,style:{marginBottom:i.marginLG},children:r.jsx(zj,{level:5,style:{marginBottom:i.marginXS},children:e.question})}),e.context&&r.jsx(Ne,{message:a("components.question.context"),description:e.context,type:"info",showIcon:!0,style:{marginBottom:i.marginLG}}),r.jsxs(K,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(Jn,{strong:!0,style:{display:"block",marginBottom:i.marginSM},children:a("components.question.chooseOption")}),r.jsx(Gt.Group,{value:l,onChange:f=>c(f.target.value),disabled:n||d,style:{width:"100%"},children:r.jsx(q,{direction:"vertical",style:{width:"100%"},children:e.options.map(f=>r.jsx(te,{size:"small",hoverable:!n&&!d,style:{borderColor:l===f.value?i.colorPrimary:i.colorBorder,backgroundColor:l===f.value?i.colorPrimaryBg:i.colorBgContainer,cursor:n||d?"not-allowed":"pointer"},onClick:()=>!n&&!d&&c(f.value),children:r.jsx(Gt,{value:f.value,style:{width:"100%"},children:r.jsxs(K,{vertical:!0,children:[r.jsxs(K,{align:"center",gap:i.marginXS,wrap:"wrap",children:[r.jsx(Jn,{strong:!0,children:f.label}),f.value===e.default&&r.jsx(fe,{color:"processing",style:{marginLeft:i.marginXS},children:a("components.question.recommended")})]}),r.jsx(Nj,{type:"secondary",style:{marginTop:i.marginXXS,marginBottom:0},children:f.description})]})})},f.value))})})]}),e.allow_custom&&r.jsxs(K,{vertical:!0,style:{marginBottom:i.marginMD},children:[r.jsx(Jn,{type:"secondary",style:{fontSize:12},children:a("components.question.customAnswerHint")}),r.jsx(ye.TextArea,{value:l&&!e.options.find(f=>f.value===l)?l:"",onChange:f=>c(f.target.value),placeholder:a("components.question.customAnswerPlaceholder"),disabled:n||d,autoSize:{minRows:3,maxRows:8},style:{marginTop:i.marginXS}})]}),r.jsx(K,{justify:"flex-end",children:r.jsx(B,{type:"primary",icon:r.jsx(Ws,{}),onClick:h,loading:d,disabled:n||!l,children:a("components.question.submitAnswer")})})]})},iy=m.memo(Wj);iy.displayName="QuestionMessageCard";const{Text:th}=le,Uj=({paths:e,displayText:t})=>{const{token:s}=xe.useToken(),n=t.replace(/@[^\s]+/g,"").trim();return r.jsxs(te,{size:"small",styles:{body:{padding:`${s.paddingSM}px ${s.paddingMD}px`}},style:{maxWidth:"100%"},children:[r.jsx(q,{direction:"vertical",size:s.marginXXS,children:e.map((o,a)=>{const i=o.split("/").pop()||o,l=o.substring(0,o.lastIndexOf("/"))||"",c=!i.includes(".");return r.jsxs(K,{vertical:!0,children:[r.jsxs(q,{size:s.marginXS,align:"center",wrap:!0,children:[c?r.jsx(Yo,{style:{color:s.colorWarning,fontSize:s.fontSizeLG}}):r.jsx(dr,{style:{color:s.colorPrimary,fontSize:s.fontSizeLG}}),r.jsx(fe,{color:c?"warning":"processing",style:{margin:0,fontFamily:s.fontFamilyCode,fontSize:s.fontSize},children:i})]}),l&&r.jsx(je,{title:o,children:r.jsxs(q,{size:4,align:"center",style:{marginTop:4},children:[r.jsx(Yo,{style:{color:s.colorTextTertiary,fontSize:s.fontSizeSM}}),r.jsx(th,{type:"secondary",style:{fontSize:s.fontSizeSM,fontFamily:s.fontFamilyCode,maxWidth:"400px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},copyable:{text:o},children:l})]})})]},a)})}),n&&r.jsx(th,{style:{fontSize:s.fontSize,color:s.colorText,marginTop:s.marginXS,paddingTop:s.marginXS,borderTop:`1px solid ${s.colorBorderSecondary}`},children:n})]})},ly=m.memo(Uj);ly.displayName="FileReferenceCard";const qj=({taskList:e})=>{const{token:t}=xe.useToken(),{Text:s}=le,n=l=>{switch(l){case"pending":return r.jsx(fe,{icon:r.jsx(Us,{}),color:"default",children:"Pending"});case"in_progress":return r.jsx(fe,{icon:r.jsx(ta,{spin:!0}),color:"processing",children:"In Progress"});case"completed":return r.jsx(fe,{icon:r.jsx(Ws,{}),color:"success",children:"Completed"});case"skipped":return r.jsx(fe,{icon:r.jsx(Kl,{}),color:"default",children:"Skipped"});case"failed":return r.jsx(fe,{icon:r.jsx(Gl,{}),color:"error",children:"Failed"});default:return null}},o=()=>{switch(e.status){case"active":return r.jsx(fe,{color:"processing",children:"Active"});case"completed":return r.jsx(fe,{color:"success",children:"Completed"});case"abandoned":return r.jsx(fe,{color:"error",children:"Abandoned"});default:return null}},a=dt.useMemo(()=>{if(e.items.length===0)return 0;const l=e.items.filter(c=>c.status==="completed").length;return Math.round(l/e.items.length*100)},[e.items]),i=dt.useMemo(()=>e.items.find(l=>l.status==="in_progress"),[e.items]);return r.jsx(te,{size:"small",styles:{body:{padding:t.paddingSM}},style:{borderRadius:t.borderRadiusLG},children:r.jsxs(K,{vertical:!0,gap:t.marginSM,children:[r.jsxs(K,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[r.jsxs(q,{direction:"vertical",size:2,children:[r.jsx(s,{strong:!0,children:e.title}),e.description?r.jsx(s,{type:"secondary",children:e.description}):null]}),o()]}),r.jsxs(q,{direction:"vertical",size:4,children:[r.jsx(Vc,{percent:a,status:e.status==="completed"?"success":e.status==="abandoned"?"exception":"active",showInfo:!0}),r.jsxs(s,{type:"secondary",children:[a,"% Complete"]})]}),r.jsx(Ge,{size:"small",dataSource:e.items,renderItem:l=>{var d;const c=(i==null?void 0:i.id)===l.id;return r.jsx(Ge.Item,{style:{borderRadius:t.borderRadius,padding:t.paddingXS,background:c?t.colorPrimaryBg:"transparent",border:"1px solid",borderColor:c?t.colorPrimaryBorder:t.colorBorderSecondary},children:r.jsxs(K,{vertical:!0,style:{width:"100%"},gap:4,children:[r.jsxs(K,{align:"center",justify:"space-between",wrap:"wrap",gap:8,children:[r.jsx(s,{children:l.description}),n(l.status)]}),l.status==="failed"&&((d=l.metadata)!=null&&d.error)?r.jsx(s,{type:"danger",style:{fontSize:12},children:l.metadata.error}):null]})})}}),r.jsxs(K,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[r.jsxs(s,{type:"secondary",style:{fontSize:12},children:[e.items.filter(l=>l.status==="completed").length," /"," ",e.items.length," tasks completed"]}),i?r.jsxs(s,{type:"secondary",style:{fontSize:12},children:["Current: ",i.description]}):null]})]})})},Hj=100,Tn=new Set;function Yj(e){if(Tn.has(e)&&Tn.delete(e),Tn.add(e),Tn.size>Hj){const t=Tn.values().next().value;t&&Tn.delete(t)}}function Xj(e){let t=2166136261;for(let s=0;s<e.length;s++)t=(t^e.charCodeAt(s))*16777619;return(t>>>0).toString(36)}const Vj=e=>{const{t}=se(),s=Xj(e.chart),[n,o]=m.useState(()=>Tn.has(s)),a=m.useRef(null);return m.useEffect(()=>{if(n)return;const i=a.current;if(!i)return;const l=new IntersectionObserver(c=>{c.some(d=>d.isIntersecting)&&(Yj(s),o(!0),l.disconnect())},{rootMargin:"50px",threshold:.01});return l.observe(i),()=>l.disconnect()},[n,s]),r.jsx("div",{ref:a,style:{minHeight:n?"auto":"200px"},children:n?r.jsx(dt.Suspense,{fallback:r.jsx(ct,{size:"small",tip:t("components.mermaid.loadingDiagram")}),children:r.jsx(Kj,{...e})}):r.jsx("div",{style:{minHeight:"200px"}})})},Kj=e=>{const{t}=se(),[s,n]=m.useState(null);return m.useEffect(()=>{let o=!1;return kt(()=>Promise.resolve().then(()=>wP),void 0,import.meta.url).then(a=>{o||n(()=>a.MermaidChart)}),()=>{o=!0}},[]),s?r.jsx(s,{...e}):r.jsx(ct,{size:"small",tip:t("components.mermaid.loadingDiagram")})},Gj=dt.memo(Vj),Jj=({error:e,className:t,style:s,token:n,onFix:o,isFixing:a,fixError:i})=>{const{t:l}=se(),c=e.split(`
|
|
178
|
+
|
|
179
|
+
`);return r.jsxs("div",{className:t,style:{color:n.colorError,padding:`${n.paddingXS}px ${n.paddingSM}px`,fontSize:n.fontSizeSM,background:n.colorErrorBg,borderRadius:n.borderRadiusSM,border:`1px solid ${n.colorErrorBorder}`,margin:`${n.marginXS}px 0`,minHeight:"60px",maxHeight:"120px",display:"flex",flexDirection:"column",alignItems:"flex-start",justifyContent:"flex-start",overflow:"auto",position:"relative",maxWidth:"100%",boxSizing:"border-box",...s},title:`${l("components.mermaid.errorTitlePrefix")}: ${e}
|
|
180
|
+
|
|
181
|
+
${l("components.mermaid.checkConsoleHint")}`,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:n.marginXXS},children:[r.jsx("span",{style:{marginRight:n.marginXS,fontSize:"14px",flexShrink:0,lineHeight:1},children:r.jsx(gr,{})}),r.jsx("span",{style:{fontWeight:600,color:n.colorError},children:l("components.mermaid.diagramError")})]}),r.jsx("div",{style:{fontSize:n.fontSizeSM,lineHeight:1.4,wordBreak:"break-word",flex:1,width:"100%"},children:c.map((d,u)=>r.jsx("div",{style:{marginBottom:u<c.length-1?n.marginXS:0,...d.startsWith("💡")?{backgroundColor:n.colorInfoBg,border:`1px solid ${n.colorInfoBorder}`,borderRadius:n.borderRadiusSM,padding:n.paddingXS,marginTop:n.marginXS,color:n.colorInfo,fontWeight:500}:{}},children:d},`${u}-${d.substring(0,12)}`))}),o&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:n.marginXS,marginTop:n.marginXS,width:"100%"},children:[r.jsx(B,{size:"small",type:"primary",onClick:o,loading:a,children:l("components.mermaid.fixMermaid")}),i&&r.jsx("span",{style:{color:n.colorError,fontSize:n.fontSizeSM,wordBreak:"break-word",flex:1},children:i})]}),r.jsxs("div",{style:{fontSize:n.fontSizeSM,color:n.colorTextSecondary,marginTop:n.marginXS,fontStyle:"italic"},children:[r.jsx(kp,{style:{marginRight:4}})," ",l("components.mermaid.checkConsoleHint")]})]})};var Vt=function(e,t){return Number(e.toFixed(t))},Qj=function(e,t){return typeof e=="number"?e:t},Ve=function(e,t,s){s&&typeof s=="function"&&s(e,t)},Zj=function(e){return-Math.cos(e*Math.PI)/2+.5},eM=function(e){return e},tM=function(e){return e*e},sM=function(e){return e*(2-e)},nM=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},rM=function(e){return e*e*e},oM=function(e){return--e*e*e+1},aM=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},iM=function(e){return e*e*e*e},lM=function(e){return 1- --e*e*e*e},cM=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},dM=function(e){return e*e*e*e*e},uM=function(e){return 1+--e*e*e*e*e},mM=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},cy={easeOut:Zj,linear:eM,easeInQuad:tM,easeOutQuad:sM,easeInOutQuad:nM,easeInCubic:rM,easeOutCubic:oM,easeInOutCubic:aM,easeInQuart:iM,easeOutQuart:lM,easeInOutQuart:cM,easeInQuint:dM,easeOutQuint:uM,easeInOutQuint:mM},dy=function(e){typeof e=="number"&&cancelAnimationFrame(e)},cs=function(e){e.mounted&&(dy(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function uy(e,t,s,n){if(e.mounted){var o=new Date().getTime(),a=1;cs(e),e.animation=function(){if(!e.mounted)return dy(e.animation);var i=new Date().getTime()-o,l=i/s,c=cy[t],d=c(l);i>=s?(n(a),e.animation=null):e.animation&&(n(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function hM(e){var t=e.scale,s=e.positionX,n=e.positionY;return!(Number.isNaN(t)||Number.isNaN(s)||Number.isNaN(n))}function mn(e,t,s,n){var o=hM(t);if(!(!e.mounted||!o)){var a=e.setTransformState,i=e.transformState,l=i.scale,c=i.positionX,d=i.positionY,u=t.scale-l,h=t.positionX-c,p=t.positionY-d;s===0?a(t.scale,t.positionX,t.positionY):uy(e,n,s,function(y){var g=l+u*y,f=c+h*y,b=d+p*y;a(g,f,b)})}}function pM(e,t,s){var n=e.offsetWidth,o=e.offsetHeight,a=t.offsetWidth,i=t.offsetHeight,l=a*s,c=i*s,d=n-l,u=o-c;return{wrapperWidth:n,wrapperHeight:o,newContentWidth:l,newDiffWidth:d,newContentHeight:c,newDiffHeight:u}}var fM=function(e,t,s,n,o,a,i){var l=e>t?s*(i?1:.5):0,c=n>o?a*(i?1:.5):0,d=e-t-l,u=l,h=n-o-c,p=c;return{minPositionX:d,maxPositionX:u,minPositionY:h,maxPositionY:p}},Ed=function(e,t){var s=e.wrapperComponent,n=e.contentComponent,o=e.setup.centerZoomedOut;if(!s||!n)throw new Error("Components are not mounted");var a=pM(s,n,t),i=a.wrapperWidth,l=a.wrapperHeight,c=a.newContentWidth,d=a.newDiffWidth,u=a.newContentHeight,h=a.newDiffHeight,p=fM(i,c,d,l,u,h,!!o);return p},Fc=function(e,t,s,n){return n?e<t?Vt(t,2):e>s?Vt(s,2):Vt(e,2):Vt(e,2)},Fn=function(e,t){var s=Ed(e,t);return e.bounds=s,s};function ha(e,t,s,n,o,a,i){var l=s.minPositionX,c=s.minPositionY,d=s.maxPositionX,u=s.maxPositionY,h=0,p=0;i&&(h=o,p=a);var y=Fc(e,l-h,d+h,n),g=Fc(t,c-p,u+p,n);return{x:y,y:g}}function Wi(e,t,s,n,o,a){var i=e.transformState,l=i.scale,c=i.positionX,d=i.positionY,u=n-l;if(typeof t!="number"||typeof s!="number")return console.error("Mouse X and Y position were not provided!"),{x:c,y:d};var h=c-t*u,p=d-s*u,y=ha(h,p,o,a,0,0,null);return y}function pa(e,t,s,n,o){var a=o?n:0,i=t-a;return!Number.isNaN(s)&&e>=s?s:!Number.isNaN(t)&&e<=i?i:e}var sh=function(e,t){var s=e.setup.panning.excluded,n=e.isInitialized,o=e.wrapperComponent,a=t.target,i="shadowRoot"in a&&"composedPath"in t,l=i?t.composedPath().some(function(u){return u instanceof Element?o==null?void 0:o.contains(u):!1}):o==null?void 0:o.contains(a),c=n&&a&&l;if(!c)return!1;var d=Ui(a,s);return!d},nh=function(e){var t=e.isInitialized,s=e.isPanning,n=e.setup,o=n.panning.disabled,a=t&&s&&!o;return!!a},gM=function(e,t){var s=e.transformState,n=s.positionX,o=s.positionY;e.isPanning=!0;var a=t.clientX,i=t.clientY;e.startCoords={x:a-n,y:i-o}},yM=function(e,t){var s=t.touches,n=e.transformState,o=n.positionX,a=n.positionY;e.isPanning=!0;var i=s.length===1;if(i){var l=s[0].clientX,c=s[0].clientY;e.startCoords={x:l-o,y:c-a}}};function xM(e){var t=e.transformState,s=t.positionX,n=t.positionY,o=t.scale,a=e.setup,i=a.disabled,l=a.limitToBounds,c=a.centerZoomedOut,d=e.wrapperComponent;if(!(i||!d||!e.bounds)){var u=e.bounds,h=u.maxPositionX,p=u.minPositionX,y=u.maxPositionY,g=u.minPositionY,f=s>h||s<p,b=n>y||n<g,x=s>h?d.offsetWidth:e.setup.minPositionX||0,S=n>y?d.offsetHeight:e.setup.minPositionY||0,w=Wi(e,x,S,o,e.bounds,l||c),C=w.x,_=w.y;return{scale:o,positionX:f?C:s,positionY:b?_:n}}}function my(e,t,s,n,o){var a=e.setup.limitToBounds,i=e.wrapperComponent,l=e.bounds,c=e.transformState,d=c.scale,u=c.positionX,h=c.positionY;if(!(i===null||l===null||t===u&&s===h)){var p=ha(t,s,l,a,n,o,i),y=p.x,g=p.y;e.setTransformState(d,y,g)}}var bM=function(e,t,s){var n=e.startCoords,o=e.transformState,a=e.setup.panning,i=a.lockAxisX,l=a.lockAxisY,c=o.positionX,d=o.positionY;if(!n)return{x:c,y:d};var u=t-n.x,h=s-n.y,p=i?c:u,y=l?d:h;return{x:p,y}},ln=function(e,t){var s=e.setup,n=e.transformState,o=n.scale,a=s.minScale,i=s.disablePadding;return t>0&&o>=a&&!i?t:0},vM=function(e){var t=e.mounted,s=e.setup,n=s.disabled,o=s.velocityAnimation,a=e.transformState.scale,i=o.disabled,l=!i||a>1||!n||t;return!!l},SM=function(e){var t=e.mounted,s=e.velocity,n=e.bounds,o=e.setup,a=o.disabled,i=o.velocityAnimation,l=e.transformState.scale,c=i.disabled,d=!c||l>1||!a||t;return!(!d||!s||!n)};function wM(e,t){var s=e.setup.velocityAnimation,n=s.equalToMove,o=s.animationTime,a=s.sensitivity;return n?o*t*a:o}function rh(e,t,s,n,o,a,i,l,c,d){if(o){if(t>i&&s>i){var u=i+(e-i)*d;return u>c?c:u<i?i:u}if(t<a&&s<a){var u=a+(e-a)*d;return u<l?l:u>a?a:u}}return n?t:Fc(e,a,i,o)}function _M(e,t){var s=1;return t?Math.min(s,e.offsetWidth/window.innerWidth):s}function TM(e,t){var s=vM(e);if(s){var n=e.lastMousePosition,o=e.velocityTime,a=e.setup,i=e.wrapperComponent,l=a.velocityAnimation.equalToMove,c=Date.now();if(n&&o&&i){var d=_M(i,l),u=t.x-n.x,h=t.y-n.y,p=u/d,y=h/d,g=c-o,f=u*u+h*h,b=Math.sqrt(f)/g;e.velocity={velocityX:p,velocityY:y,total:b}}e.lastMousePosition=t,e.velocityTime=c}}function kM(e){var t=e.velocity,s=e.bounds,n=e.setup,o=e.wrapperComponent,a=SM(e);if(!(!a||!t||!s||!o)){var i=t.velocityX,l=t.velocityY,c=t.total,d=s.maxPositionX,u=s.minPositionX,h=s.maxPositionY,p=s.minPositionY,y=n.limitToBounds,g=n.alignmentAnimation,f=n.zoomAnimation,b=n.panning,x=b.lockAxisY,S=b.lockAxisX,w=f.animationType,C=g.sizeX,_=g.sizeY,T=g.velocityAlignmentTime,j=T,v=wM(e,c),k=Math.max(v,j),E=ln(e,C),M=ln(e,_),R=E*o.offsetWidth/100,I=M*o.offsetHeight/100,P=d+R,L=u-R,O=h+I,A=p-I,$=e.transformState,W=new Date().getTime();uy(e,w,k,function(F){var H=e.transformState,D=H.scale,U=H.positionX,Q=H.positionY,Y=new Date().getTime()-W,he=Y/j,ve=cy[g.animationType],ue=1-ve(Math.min(1,he)),ie=1-F,Re=U+i*ie,Le=Q+l*ie,Ze=rh(Re,$.positionX,U,S,y,u,d,L,P,ue),et=rh(Le,$.positionY,Q,x,y,p,h,A,O,ue);(U!==Re||Q!==Le)&&e.setTransformState(D,Ze,et)})}}function oh(e,t){var s=e.transformState.scale;cs(e),Fn(e,s),window.TouchEvent!==void 0&&t instanceof TouchEvent?yM(e,t):gM(e,t)}function Rd(e,t){var s=e.transformState.scale,n=e.setup,o=n.minScale,a=n.alignmentAnimation,i=a.disabled,l=a.sizeX,c=a.sizeY,d=a.animationTime,u=a.animationType,h=i||s<o||!l&&!c;if(!h){var p=xM(e);p&&mn(e,p,t??d,u)}}function ah(e,t,s){var n=e.startCoords,o=e.setup,a=o.alignmentAnimation,i=a.sizeX,l=a.sizeY;if(n){var c=bM(e,t,s),d=c.x,u=c.y,h=ln(e,i),p=ln(e,l);TM(e,{x:d,y:u}),my(e,d,u,h,p)}}function CM(e){if(e.isPanning){var t=e.setup.panning.velocityDisabled,s=e.velocity,n=e.wrapperComponent,o=e.contentComponent;e.isPanning=!1,e.animate=!1,e.animation=null;var a=n==null?void 0:n.getBoundingClientRect(),i=o==null?void 0:o.getBoundingClientRect(),l=(a==null?void 0:a.width)||0,c=(a==null?void 0:a.height)||0,d=(i==null?void 0:i.width)||0,u=(i==null?void 0:i.height)||0,h=l<d||c<u,p=!t&&s&&(s==null?void 0:s.total)>.1&&h;p?kM(e):Rd(e)}}function Ad(e,t,s,n){var o=e.setup,a=o.minScale,i=o.maxScale,l=o.limitToBounds,c=pa(Vt(t,2),a,i,0,!1),d=Fn(e,c),u=Wi(e,s,n,c,d,l),h=u.x,p=u.y;return{scale:c,positionX:h,positionY:p}}function hy(e,t,s){var n=e.transformState.scale,o=e.wrapperComponent,a=e.setup,i=a.minScale,l=a.limitToBounds,c=a.zoomAnimation,d=c.disabled,u=c.animationTime,h=c.animationType,p=d||n>=i;if((n>=1||l)&&Rd(e),!(p||!o||!e.mounted)){var y=t||o.offsetWidth/2,g=s||o.offsetHeight/2,f=Ad(e,i,y,g);f&&mn(e,f,u,h)}}var on=function(){return on=Object.assign||function(t){for(var s,n=1,o=arguments.length;n<o;n++){s=arguments[n];for(var a in s)Object.prototype.hasOwnProperty.call(s,a)&&(t[a]=s[a])}return t},on.apply(this,arguments)};function ih(e,t,s){for(var n=0,o=t.length,a;n<o;n++)(a||!(n in t))&&(a||(a=Array.prototype.slice.call(t,0,n)),a[n]=t[n]);return e.concat(a||Array.prototype.slice.call(t))}var Ra={scale:1,positionX:0,positionY:0},zr={disabled:!1,minPositionX:null,maxPositionX:null,minPositionY:null,maxPositionY:null,minScale:1,maxScale:8,limitToBounds:!0,centerZoomedOut:!1,centerOnInit:!1,disablePadding:!1,smooth:!0,wheel:{step:.2,disabled:!1,smoothStep:.001,wheelDisabled:!1,touchPadDisabled:!1,activationKeys:[],excluded:[]},panning:{disabled:!1,velocityDisabled:!1,lockAxisX:!1,lockAxisY:!1,allowLeftClickPan:!0,allowMiddleClickPan:!0,allowRightClickPan:!0,wheelPanning:!1,activationKeys:[],excluded:[]},pinch:{step:5,disabled:!1,excluded:[]},doubleClick:{disabled:!1,step:.7,mode:"zoomIn",animationType:"easeOut",animationTime:200,excluded:[]},zoomAnimation:{disabled:!1,size:.4,animationTime:200,animationType:"easeOut"},alignmentAnimation:{disabled:!1,sizeX:100,sizeY:100,animationTime:200,velocityAlignmentTime:400,animationType:"easeOut"},velocityAnimation:{disabled:!1,sensitivity:1,animationTime:400,animationType:"easeOut",equalToMove:!0}},Lc={wrapperClass:"react-transform-wrapper",contentClass:"react-transform-component"},py=function(e){var t,s,n,o;return{previousScale:(t=e.initialScale)!==null&&t!==void 0?t:Ra.scale,scale:(s=e.initialScale)!==null&&s!==void 0?s:Ra.scale,positionX:(n=e.initialPositionX)!==null&&n!==void 0?n:Ra.positionX,positionY:(o=e.initialPositionY)!==null&&o!==void 0?o:Ra.positionY}},lh=function(e){var t=on({},zr);return Object.keys(e).forEach(function(s){var n=typeof e[s]<"u",o=typeof zr[s]<"u";if(o&&n){var a=Object.prototype.toString.call(zr[s]),i=a==="[object Object]",l=a==="[object Array]";i?t[s]=on(on({},zr[s]),e[s]):l?t[s]=ih(ih([],zr[s],!0),e[s]):t[s]=e[s]}}),t},fy=function(e,t,s){var n=e.transformState.scale,o=e.wrapperComponent,a=e.setup,i=a.maxScale,l=a.minScale,c=a.zoomAnimation,d=a.smooth,u=c.size;if(!o)throw new Error("Wrapper is not mounted");var h=d?n*Math.exp(t*s):n+t*s,p=pa(Vt(h,3),l,i,u,!1);return p};function gy(e,t,s,n,o){var a=e.wrapperComponent,i=e.transformState,l=i.scale,c=i.positionX,d=i.positionY;if(!a)return console.error("No WrapperComponent found");var u=a.offsetWidth,h=a.offsetHeight,p=(u/2-c)/l,y=(h/2-d)/l,g=fy(e,t,s),f=Ad(e,g,p,y);if(!f)return console.error("Error during zoom event. New transformation state was not calculated.");mn(e,f,n,o)}function yy(e,t,s,n){var o=e.setup,a=e.wrapperComponent,i=o.limitToBounds,l=py(e.props),c=e.transformState,d=c.scale,u=c.positionX,h=c.positionY;if(a){var p=Ed(e,l.scale),y=ha(l.positionX,l.positionY,p,i,0,0,a),g={scale:l.scale,positionX:y.x,positionY:y.y};d===l.scale&&u===l.positionX&&h===l.positionY||(n==null||n(),mn(e,g,t,s))}}function jM(e,t,s,n){var o=e.getBoundingClientRect(),a=t.getBoundingClientRect(),i=s.getBoundingClientRect(),l=a.x*n.scale,c=a.y*n.scale;return{x:(o.x-i.x+l)/n.scale,y:(o.y-i.y+c)/n.scale}}function MM(e,t,s){var n=e.wrapperComponent,o=e.contentComponent,a=e.transformState,i=e.setup,l=i.limitToBounds,c=i.minScale,d=i.maxScale;if(!n||!o)return a;var u=n.getBoundingClientRect(),h=t.getBoundingClientRect(),p=jM(t,n,o,a),y=p.x,g=p.y,f=h.width/a.scale,b=h.height/a.scale,x=n.offsetWidth/f,S=n.offsetHeight/b,w=pa(s||Math.min(x,S),c,d,0,!1),C=(u.width-f*w)/2,_=(u.height-b*w)/2,T=(u.left-y)*w+C,j=(u.top-g)*w+_,v=Ed(e,w),k=ha(T,j,v,l,0,0,n),E=k.x,M=k.y;return{positionX:E,positionY:M,scale:w}}var PM=function(e){return function(t,s,n){t===void 0&&(t=.5),s===void 0&&(s=300),n===void 0&&(n="easeOut"),gy(e,1,t,s,n)}},EM=function(e){return function(t,s,n){t===void 0&&(t=.5),s===void 0&&(s=300),n===void 0&&(n="easeOut"),gy(e,-1,t,s,n)}},RM=function(e){return function(t,s,n,o,a){o===void 0&&(o=300),a===void 0&&(a="easeOut");var i=e.transformState,l=i.positionX,c=i.positionY,d=i.scale,u=e.wrapperComponent,h=e.contentComponent,p=e.setup.disabled;if(!(p||!u||!h)){var y={positionX:Number.isNaN(t)?l:t,positionY:Number.isNaN(s)?c:s,scale:Number.isNaN(n)?d:n};mn(e,y,o,a)}}},AM=function(e){return function(t,s){t===void 0&&(t=200),s===void 0&&(s="easeOut"),yy(e,t,s)}},IM=function(e){return function(t,s,n){s===void 0&&(s=200),n===void 0&&(n="easeOut");var o=e.transformState,a=e.wrapperComponent,i=e.contentComponent;if(a&&i){var l=xy(t||o.scale,a,i);mn(e,l,s,n)}}},$M=function(e){return function(t,s,n,o){n===void 0&&(n=600),o===void 0&&(o="easeOut"),cs(e);var a=e.wrapperComponent,i=typeof t=="string"?document.getElementById(t):t;if(a&&i&&a.contains(i)){var l=MM(e,i,s);mn(e,l,n,o)}}},Oc=function(e){return{instance:e,zoomIn:PM(e),zoomOut:EM(e),setTransform:RM(e),resetTransform:AM(e),centerView:IM(e),zoomToElement:$M(e)}},FM=function(e){return{instance:e,state:e.transformState}},qe=function(e){var t={};return Object.assign(t,FM(e)),Object.assign(t,Oc(e)),t},kl=!1;function Cl(){try{var e={get passive(){return kl=!0,!1}};return e}catch{return kl=!1,kl}}var Aa=".".concat(Lc.wrapperClass),Ui=function(e,t){return t.some(function(s){return e.matches("".concat(Aa," ").concat(s,", ").concat(Aa," .").concat(s,", ").concat(Aa," ").concat(s," *, ").concat(Aa," .").concat(s," *"))})},Dc=function(e){e&&clearTimeout(e)},LM=function(e,t,s){return"translate(".concat(e,"px, ").concat(t,"px) scale(").concat(s,")")},xy=function(e,t,s){var n=s.offsetWidth*e,o=s.offsetHeight*e,a=(t.offsetWidth-n)/2,i=(t.offsetHeight-o)/2;return{scale:e,positionX:a,positionY:i}};function OM(e){return function(t){e.forEach(function(s){typeof s=="function"?s(t):s!=null&&(s.current=t)})}}var DM=function(e,t){var s=e.setup.wheel,n=s.disabled,o=s.wheelDisabled,a=s.touchPadDisabled,i=s.excluded,l=e.isInitialized,c=e.isPanning,d=t.target,u=l&&!c&&!n&&d;if(!u||o&&!t.ctrlKey||a&&t.ctrlKey)return!1;var h=Ui(d,i);return!h},zM=function(e){return e?e.deltaY<0?1:-1:0};function NM(e,t){var s=zM(e),n=Qj(t,s);return n}function by(e,t,s){var n=t.getBoundingClientRect(),o=0,a=0;if("clientX"in e)o=(e.clientX-n.left)/s,a=(e.clientY-n.top)/s;else{var i=e.touches[0];o=(i.clientX-n.left)/s,a=(i.clientY-n.top)/s}return(Number.isNaN(o)||Number.isNaN(a))&&console.error("No mouse or touch offset found"),{x:o,y:a}}var BM=function(e,t,s,n,o){var a=e.transformState.scale,i=e.wrapperComponent,l=e.setup,c=l.maxScale,d=l.minScale,u=l.zoomAnimation,h=l.disablePadding,p=u.size,y=u.disabled;if(!i)throw new Error("Wrapper is not mounted");var g=a+t*s,f=n?!1:!y,b=pa(Vt(g,3),d,c,p,f&&!h);return b},WM=function(e,t){var s=e.previousWheelEvent,n=e.transformState.scale,o=e.setup,a=o.maxScale,i=o.minScale;return s?n<a||n>i||Math.sign(s.deltaY)!==Math.sign(t.deltaY)||s.deltaY>0&&s.deltaY<t.deltaY||s.deltaY<0&&s.deltaY>t.deltaY||Math.sign(s.deltaY)!==Math.sign(t.deltaY):!1},UM=function(e,t){var s=e.setup.pinch,n=s.disabled,o=s.excluded,a=e.isInitialized,i=t.target,l=a&&!n&&i;if(!l)return!1;var c=Ui(i,o);return!c},qM=function(e){var t=e.setup.pinch.disabled,s=e.isInitialized,n=e.pinchStartDistance,o=s&&!t&&n;return!!o},HM=function(e,t,s){var n=s.getBoundingClientRect(),o=e.touches,a=Vt(o[0].clientX-n.left,5),i=Vt(o[0].clientY-n.top,5),l=Vt(o[1].clientX-n.left,5),c=Vt(o[1].clientY-n.top,5);return{x:(a+l)/2/t,y:(i+c)/2/t}},vy=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))},YM=function(e,t){var s=e.pinchStartScale,n=e.pinchStartDistance,o=e.setup,a=o.maxScale,i=o.minScale,l=o.zoomAnimation,c=o.disablePadding,d=l.size,u=l.disabled;if(!s||n===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var h=t/n,p=h*s;return pa(Vt(p,2),i,a,d,!u&&!c)},XM=160,VM=100,KM=function(e,t){var s=e.props,n=s.onWheelStart,o=s.onZoomStart;e.wheelStopEventTimer||(cs(e),Ve(qe(e),t,n),Ve(qe(e),t,o))},GM=function(e,t){var s=e.props,n=s.onWheel,o=s.onZoom,a=e.contentComponent,i=e.setup,l=e.transformState,c=l.scale,d=i.limitToBounds,u=i.centerZoomedOut,h=i.zoomAnimation,p=i.wheel,y=i.disablePadding,g=i.smooth,f=h.size,b=h.disabled,x=p.step,S=p.smoothStep;if(!a)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var w=NM(t,null),C=g?S*Math.abs(t.deltaY):x,_=BM(e,w,C,!t.ctrlKey);if(c!==_){var T=Fn(e,_),j=by(t,a,c),v=b||f===0||u||y,k=d&&v,E=Wi(e,j.x,j.y,_,T,k),M=E.x,R=E.y;e.previousWheelEvent=t,e.setTransformState(_,M,R),Ve(qe(e),t,n),Ve(qe(e),t,o)}},JM=function(e,t){var s=e.props,n=s.onWheelStop,o=s.onZoomStop;Dc(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(hy(e,t.x,t.y),e.wheelAnimationTimer=null)},VM);var a=WM(e,t);a&&(Dc(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Ve(qe(e),t,n),Ve(qe(e),t,o))},XM))},Sy=function(e){for(var t=0,s=0,n=0;n<2;n+=1)t+=e.touches[n].clientX,s+=e.touches[n].clientY;var o=t/2,a=s/2;return{x:o,y:a}},QM=function(e,t){var s=vy(t);e.pinchStartDistance=s,e.lastDistance=s,e.pinchStartScale=e.transformState.scale,e.isPanning=!1;var n=Sy(t);e.pinchLastCenterX=n.x,e.pinchLastCenterY=n.y,cs(e)},ZM=function(e,t){var s=e.contentComponent,n=e.pinchStartDistance,o=e.wrapperComponent,a=e.transformState.scale,i=e.setup,l=i.limitToBounds,c=i.centerZoomedOut,d=i.zoomAnimation,u=i.alignmentAnimation,h=d.disabled,p=d.size;if(!(n===null||!s)){var y=HM(t,a,s);if(!(!Number.isFinite(y.x)||!Number.isFinite(y.y))){var g=vy(t),f=YM(e,g),b=Sy(t),x=b.x-(e.pinchLastCenterX||0),S=b.y-(e.pinchLastCenterY||0);if(!(f===a&&x===0&&S===0)){e.pinchLastCenterX=b.x,e.pinchLastCenterY=b.y;var w=Fn(e,f),C=h||p===0||c,_=l&&C,T=Wi(e,y.x,y.y,f,w,_),j=T.x,v=T.y;e.pinchMidpoint=y,e.lastDistance=g;var k=u.sizeX,E=u.sizeY,M=ln(e,k),R=ln(e,E),I=j+x,P=v+S,L=ha(I,P,w,l,M,R,o),O=L.x,A=L.y;e.setTransformState(f,O,A)}}}},eP=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,hy(e,t==null?void 0:t.x,t==null?void 0:t.y)},wy=function(e,t){var s=e.props.onZoomStop,n=e.setup.doubleClick.animationTime;Dc(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Ve(qe(e),t,s)},n)},tP=function(e,t){var s=e.props,n=s.onZoomStart,o=s.onZoom,a=e.setup.doubleClick,i=a.animationTime,l=a.animationType;Ve(qe(e),t,n),yy(e,i,l,function(){return Ve(qe(e),t,o)}),wy(e,t)};function sP(e,t){return e==="toggle"?t===1?1:-1:e==="zoomOut"?-1:1}function nP(e,t){var s=e.setup,n=e.doubleClickStopEventTimer,o=e.transformState,a=e.contentComponent,i=o.scale,l=e.props,c=l.onZoomStart,d=l.onZoom,u=s.doubleClick,h=u.disabled,p=u.mode,y=u.step,g=u.animationTime,f=u.animationType;if(!h&&!n){if(p==="reset")return tP(e,t);if(!a)return console.error("No ContentComponent found");var b=sP(p,e.transformState.scale),x=fy(e,b,y);if(i!==x){Ve(qe(e),t,c);var S=by(t,a,i),w=Ad(e,x,S.x,S.y);if(!w)return console.error("Error during zoom event. New transformation state was not calculated.");Ve(qe(e),t,d),mn(e,w,g,f),wy(e,t)}}}var rP=function(e,t){var s=e.isInitialized,n=e.setup,o=e.wrapperComponent,a=n.doubleClick,i=a.disabled,l=a.excluded,c=t.target,d=o==null?void 0:o.contains(c),u=s&&c&&d&&!i;if(!u)return!1;var h=Ui(c,l);return!h},oP=function(){function e(t){var s=this;this.mounted=!0,this.pinchLastCenterX=null,this.pinchLastCenterY=null,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.isWheelPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){s.initializeWindowEvents()},this.unmount=function(){s.cleanupWindowEvents()},this.update=function(n){s.props=n,Fn(s,s.transformState.scale),s.setup=lh(n)},this.initializeWindowEvents=function(){var n,o,a=Cl(),i=(n=s.wrapperComponent)===null||n===void 0?void 0:n.ownerDocument,l=i==null?void 0:i.defaultView;(o=s.wrapperComponent)===null||o===void 0||o.addEventListener("wheel",s.onWheelPanning,a),l==null||l.addEventListener("mousedown",s.onPanningStart,a),l==null||l.addEventListener("mousemove",s.onPanning,a),l==null||l.addEventListener("mouseup",s.onPanningStop,a),i==null||i.addEventListener("mouseleave",s.clearPanning,a),l==null||l.addEventListener("keyup",s.setKeyUnPressed,a),l==null||l.addEventListener("keydown",s.setKeyPressed,a)},this.cleanupWindowEvents=function(){var n,o,a=Cl(),i=(n=s.wrapperComponent)===null||n===void 0?void 0:n.ownerDocument,l=i==null?void 0:i.defaultView;l==null||l.removeEventListener("mousedown",s.onPanningStart,a),l==null||l.removeEventListener("mousemove",s.onPanning,a),l==null||l.removeEventListener("mouseup",s.onPanningStop,a),i==null||i.removeEventListener("mouseleave",s.clearPanning,a),l==null||l.removeEventListener("keyup",s.setKeyUnPressed,a),l==null||l.removeEventListener("keydown",s.setKeyPressed,a),document.removeEventListener("mouseleave",s.clearPanning,a),cs(s),(o=s.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(n){var o=Cl();n.addEventListener("wheel",s.onWheelZoom,o),n.addEventListener("dblclick",s.onDoubleClick,o),n.addEventListener("touchstart",s.onTouchPanningStart,o),n.addEventListener("touchmove",s.onTouchPanning,o),n.addEventListener("touchend",s.onTouchPanningStop,o)},this.handleInitialize=function(n,o){var a=!1,i=s.setup.centerOnInit,l=function(c,d){for(var u=0,h=c;u<h.length;u++){var p=h[u];if(p.target===d)return!0}return!1};s.applyTransformation(),s.onInitCallbacks.forEach(function(c){c(qe(s))}),s.observer=new ResizeObserver(function(c){if(l(c,n)||l(c,o))if(i&&!a){var d=o.offsetWidth,u=o.offsetHeight;(d>0||u>0)&&(a=!0,s.setCenter())}else cs(s),Fn(s,s.transformState.scale),Rd(s,0)}),s.observer.observe(n),s.observer.observe(o)},this.onWheelZoom=function(n){var o=s.setup.disabled;if(!o){var a=DM(s,n);if(a){var i=s.isPressingKeys(s.setup.wheel.activationKeys);i&&(KM(s,n),GM(s,n),JM(s,n))}}},this.onWheelPanning=function(n){var o=s.setup,a=o.disabled,i=o.wheel,l=o.panning;if(!(!s.wrapperComponent||!s.contentComponent||a||!i.wheelDisabled||l.disabled||!l.wheelPanning||n.ctrlKey)){n.preventDefault(),n.stopPropagation();var c=s.transformState,d=c.positionX,u=c.positionY,h=d-n.deltaX,p=u-n.deltaY,y=l.lockAxisX?d:h,g=l.lockAxisY?u:p,f=s.setup.alignmentAnimation,b=f.sizeX,x=f.sizeY,S=ln(s,b),w=ln(s,x);y===d&&g===u||my(s,y,g,S,w)}},this.onPanningStart=function(n){var o=s.setup.disabled,a=s.props.onPanningStart;if(!o){var i=sh(s,n);if(i){var l=s.isPressingKeys(s.setup.panning.activationKeys);l&&(n.button===0&&!s.setup.panning.allowLeftClickPan||n.button===1&&!s.setup.panning.allowMiddleClickPan||n.button===2&&!s.setup.panning.allowRightClickPan||(n.preventDefault(),n.stopPropagation(),cs(s),oh(s,n),Ve(qe(s),n,a)))}}},this.onPanning=function(n){var o=s.setup.disabled,a=s.props.onPanning;if(!o){var i=nh(s);if(i){var l=s.isPressingKeys(s.setup.panning.activationKeys);l&&(n.preventDefault(),n.stopPropagation(),ah(s,n.clientX,n.clientY),Ve(qe(s),n,a))}}},this.onPanningStop=function(n){var o=s.props.onPanningStop;s.isPanning&&(CM(s),Ve(qe(s),n,o))},this.onPinchStart=function(n){var o=s.setup.disabled,a=s.props,i=a.onPinchingStart,l=a.onZoomStart;if(!o){var c=UM(s,n);c&&(QM(s,n),cs(s),Ve(qe(s),n,i),Ve(qe(s),n,l))}},this.onPinch=function(n){var o=s.setup.disabled,a=s.props,i=a.onPinching,l=a.onZoom;if(!o){var c=qM(s);c&&(n.preventDefault(),n.stopPropagation(),ZM(s,n),Ve(qe(s),n,i),Ve(qe(s),n,l))}},this.onPinchStop=function(n){var o=s.props,a=o.onPinchingStop,i=o.onZoomStop;s.pinchStartScale&&(eP(s),Ve(qe(s),n,a),Ve(qe(s),n,i))},this.onTouchPanningStart=function(n){var o=s.setup.disabled,a=s.props.onPanningStart;if(!o){var i=sh(s,n);if(i){var l=s.lastTouch&&+new Date-s.lastTouch<200&&n.touches.length===1;if(!l){s.lastTouch=+new Date,cs(s);var c=n.touches,d=c.length===1,u=c.length===2;d&&(cs(s),oh(s,n),Ve(qe(s),n,a)),u&&s.onPinchStart(n)}}}},this.onTouchPanning=function(n){var o=s.setup.disabled,a=s.props.onPanning;if(s.isPanning&&n.touches.length===1){if(o)return;var i=nh(s);if(!i)return;n.preventDefault(),n.stopPropagation();var l=n.touches[0];ah(s,l.clientX,l.clientY),Ve(qe(s),n,a)}else n.touches.length>1&&s.onPinch(n)},this.onTouchPanningStop=function(n){s.onPanningStop(n),s.onPinchStop(n)},this.onDoubleClick=function(n){var o=s.setup.disabled;if(!o){var a=rP(s,n);a&&nP(s,n)}},this.clearPanning=function(n){s.isPanning&&s.onPanningStop(n)},this.setKeyPressed=function(n){s.pressedKeys[n.key]=!0},this.setKeyUnPressed=function(n){s.pressedKeys[n.key]=!1},this.isPressingKeys=function(n){return n.length?!!n.find(function(o){return s.pressedKeys[o]}):!0},this.setTransformState=function(n,o,a){var i=s.props.onTransformed;if(!Number.isNaN(n)&&!Number.isNaN(o)&&!Number.isNaN(a)){n!==s.transformState.scale&&(s.transformState.previousScale=s.transformState.scale,s.transformState.scale=n),s.transformState.positionX=o,s.transformState.positionY=a,s.applyTransformation();var l=qe(s);s.onChangeCallbacks.forEach(function(c){return c(l)}),Ve(l,{scale:n,positionX:o,positionY:a},i)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(s.wrapperComponent&&s.contentComponent){var n=xy(s.transformState.scale,s.wrapperComponent,s.contentComponent);s.setTransformState(n.scale,n.positionX,n.positionY)}},this.handleTransformStyles=function(n,o,a){return s.props.customTransform?s.props.customTransform(n,o,a):LM(n,o,a)},this.applyTransformation=function(){if(!(!s.mounted||!s.contentComponent)){var n=s.transformState,o=n.scale,a=n.positionX,i=n.positionY,l=s.handleTransformStyles(a,i,o);s.contentComponent.style.transform=l}},this.getContext=function(){return qe(s)},this.onChange=function(n){return s.onChangeCallbacks.has(n)||s.onChangeCallbacks.add(n),function(){s.onChangeCallbacks.delete(n)}},this.onInit=function(n){return s.onInitCallbacks.has(n)||s.onInitCallbacks.add(n),function(){s.onInitCallbacks.delete(n)}},this.init=function(n,o){s.cleanupWindowEvents(),s.wrapperComponent=n,s.contentComponent=o,Fn(s,s.transformState.scale),s.handleInitializeWrapperEvents(n),s.handleInitialize(n,o),s.initializeWindowEvents(),s.isInitialized=!0;var a=qe(s);Ve(a,void 0,s.props.onInit)},this.props=t,this.setup=lh(this.props),this.transformState=py(this.props)}return e}(),Id=dt.createContext(null),aP=function(e,t){return typeof e=="function"?e(t):e},iP=dt.forwardRef(function(e,t){var s=m.useRef(new oP(e)).current,n=aP(e.children,Oc(s));return m.useImperativeHandle(t,function(){return Oc(s)},[s]),m.useEffect(function(){s.update(e)},[s,e]),dt.createElement(Id.Provider,{value:s},n)});dt.forwardRef(function(e,t){var s=m.useRef(null),n=m.useContext(Id);return m.useEffect(function(){return n.onChange(function(o){if(s.current){var a=0,i=0;s.current.style.transform=n.handleTransformStyles(a,i,1/o.instance.transformState.scale)}})},[n]),dt.createElement("div",on({},e,{ref:OM([s,t])}))});function lP(e,t){t===void 0&&(t={});var s=t.insertAt;if(!(typeof document>"u")){var n=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",s==="top"&&n.firstChild?n.insertBefore(o,n.firstChild):n.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var cP=`.transform-component-module_wrapper__SPB86 {
|
|
182
|
+
position: relative;
|
|
183
|
+
width: -moz-fit-content;
|
|
184
|
+
width: fit-content;
|
|
185
|
+
height: -moz-fit-content;
|
|
186
|
+
height: fit-content;
|
|
187
|
+
overflow: hidden;
|
|
188
|
+
-webkit-touch-callout: none; /* iOS Safari */
|
|
189
|
+
-webkit-user-select: none; /* Safari */
|
|
190
|
+
-khtml-user-select: none; /* Konqueror HTML */
|
|
191
|
+
-moz-user-select: none; /* Firefox */
|
|
192
|
+
-ms-user-select: none; /* Internet Explorer/Edge */
|
|
193
|
+
user-select: none;
|
|
194
|
+
margin: 0;
|
|
195
|
+
padding: 0;
|
|
196
|
+
transform: translate3d(0, 0, 0);
|
|
197
|
+
}
|
|
198
|
+
.transform-component-module_content__FBWxo {
|
|
199
|
+
display: flex;
|
|
200
|
+
flex-wrap: wrap;
|
|
201
|
+
width: -moz-fit-content;
|
|
202
|
+
width: fit-content;
|
|
203
|
+
height: -moz-fit-content;
|
|
204
|
+
height: fit-content;
|
|
205
|
+
margin: 0;
|
|
206
|
+
padding: 0;
|
|
207
|
+
transform-origin: 0% 0%;
|
|
208
|
+
}
|
|
209
|
+
.transform-component-module_content__FBWxo img {
|
|
210
|
+
pointer-events: none;
|
|
211
|
+
}
|
|
212
|
+
`,ch={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};lP(cP);var dP=function(e){var t=e.children,s=e.wrapperClass,n=s===void 0?"":s,o=e.contentClass,a=o===void 0?"":o,i=e.wrapperStyle,l=e.contentStyle,c=e.wrapperProps,d=c===void 0?{}:c,u=e.contentProps,h=u===void 0?{}:u,p=m.useContext(Id),y=p.init,g=p.cleanupWindowEvents,f=m.useRef(null),b=m.useRef(null);return m.useEffect(function(){var x=f.current,S=b.current;return x!==null&&S!==null&&y&&(y==null||y(x,S)),function(){g==null||g()}},[]),dt.createElement("div",on({},d,{ref:f,className:"".concat(Lc.wrapperClass," ").concat(ch.wrapper," ").concat(n),style:i}),dt.createElement("div",on({},h,{ref:b,className:"".concat(Lc.contentClass," ").concat(ch.content," ").concat(a),style:l}),t))};const _y=()=>typeof window<"u"&&!!window.__TAURI_INTERNALS__;class uP{async saveFile(t){const{content:s,filters:n,defaultPath:o}=t,{save:a}=await kt(async()=>{const{save:d}=await import("./index-BmjFP0ha.js");return{save:d}},__vite__mapDeps([13,14]),import.meta.url),{writeFile:i,writeTextFile:l}=await kt(async()=>{const{writeFile:d,writeTextFile:u}=await import("./index-_XI0Qq6F.js");return{writeFile:d,writeTextFile:u}},__vite__mapDeps([15,14]),import.meta.url),c=await a({filters:n.map(d=>({name:d.name,extensions:[...d.extensions]})),defaultPath:o});if(!c)throw new Error("User cancelled save operation");return typeof s=="string"?await l(c,s):await i(c,s),{filename:Ty(c,o),success:!0}}}class mP{async saveFile(t){const{content:s,filters:n,defaultPath:o}=t,a=Ty(o,o);if(typeof window>"u"||typeof document>"u")throw new Error("File save is unavailable in this environment");const i=fP(n,s),l=typeof s=="string"?new Blob([s],{type:`${i};charset=utf-8`}):new Blob([s],{type:i}),c=URL.createObjectURL(l);try{const d=document.createElement("a");d.href=c,d.download=a,d.style.display="none",document.body.appendChild(d),d.click(),document.body.removeChild(d)}finally{URL.revokeObjectURL(c)}return{filename:a,success:!0}}}const hP=new uP,pP=new mP,Ty=(e,t)=>e.split(/[/\\]/).pop()||t,fP=(e,t)=>{var n,o,a;switch(((a=(o=(n=e[0])==null?void 0:n.extensions)==null?void 0:o[0])==null?void 0:a.toLowerCase())||""){case"md":return"text/markdown";case"txt":return"text/plain";case"json":return"application/json";case"pdf":return"application/pdf";case"svg":return"image/svg+xml";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";default:return typeof t=="string"?"text/plain":"application/octet-stream"}},gP=()=>_y()?hP:pP;class ws{static async saveFile(t){try{return await gP().saveFile(t)}catch(s){return{filename:"",success:!1,error:s instanceof Error?s.message:"Unknown error occurred"}}}static async saveTextFile(t,s,n){return this.saveFile({content:t,filters:s,defaultPath:n})}static async saveBinaryFile(t,s,n){return this.saveFile({content:t,filters:s,defaultPath:n})}static generateTimestampedFilename(t,s){const n=new Date().toISOString().slice(0,19).replace(/:/g,"-");return`${t}-${n}.${s}`}}We(ws,"FILTERS",{MARKDOWN:[{name:"Markdown",extensions:["md"]}],PDF:[{name:"PDF",extensions:["pdf"]}],SVG:[{name:"SVG",extensions:["svg"]}],PNG:[{name:"PNG",extensions:["png"]}],TEXT:[{name:"Text",extensions:["txt"]}],JSON:[{name:"JSON",extensions:["json"]}],ALL:[{name:"All Files",extensions:["*"]}]});const yP=e=>{const n=new DOMParser().parseFromString(e,"image/svg+xml").querySelector("svg");return n?(n.getAttribute("xmlns")||n.setAttribute("xmlns","http://www.w3.org/2000/svg"),n.getAttribute("xmlns:xlink")||n.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink"),`<?xml version="1.0" encoding="UTF-8"?>
|
|
213
|
+
${new XMLSerializer().serializeToString(n)}`):e},xP=({svg:e,height:t,isLoading:s,initialScale:n,chartKey:o,className:a,style:i,token:l,containerRef:c})=>{const{t:d}=se(),{message:u}=ts.useApp(),[h,p]=m.useState(!1),y=m.useCallback(async()=>{var f;if(!(!e||h)){p(!0);try{const b=yP(e),x=new TextEncoder().encode(b),S=o?`mermaid-${o.slice(0,8)}`:"mermaid-graph",w=ws.generateTimestampedFilename(S,"svg"),C=await ws.saveBinaryFile(x,ws.FILTERS.SVG,w);if(C.success){u.success(d("chat.messageActions.savedFile",{filename:C.filename}));return}if((f=C.error)!=null&&f.toLowerCase().includes("cancel"))return;u.error(C.error||d("chat.messageActions.exportFailed"))}catch(b){const x=b instanceof Error?b.message:d("components.mermaid.exportFailed");u.error(x)}finally{p(!1)}}},[u,o,h,e,d]),g=s||!e||h;return r.jsxs("div",{ref:c,"data-mermaid-loading":s?"true":"false",className:a,style:{textAlign:"center",margin:`${l.marginXS}px 0`,padding:l.padding,background:l.colorBgContainer,borderRadius:l.borderRadiusSM,border:`1px solid ${l.colorBorder}`,overflow:"hidden",height:`${Math.min(t,800)}px`,minHeight:"300px",maxHeight:"80vh",display:"flex",alignItems:"center",justifyContent:"center",position:"relative",willChange:"auto",contain:"layout style paint",...i},children:[s&&r.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:l.colorTextSecondary,fontSize:l.fontSizeSM,zIndex:2},children:d("components.mermaid.renderingDiagram")}),r.jsx("div",{style:{width:"100%",height:"100%",opacity:s?0:1,position:"relative"},children:r.jsx(iP,{initialScale:n,minScale:.1,maxScale:10,centerOnInit:!0,limitToBounds:!1,wheel:{step:.1},panning:{disabled:!1},pinch:{disabled:!1},doubleClick:{disabled:!1,mode:"zoomIn",step:.5},children:({zoomIn:f,zoomOut:b,resetTransform:x})=>r.jsxs(r.Fragment,{children:[r.jsxs("div",{"data-mermaid-controls":"true",style:{position:"absolute",top:8,right:8,zIndex:10,display:"flex",flexDirection:"column",gap:4,background:l.colorBgContainer,borderRadius:l.borderRadiusSM,border:`1px solid ${l.colorBorder}`,padding:4,boxShadow:l.boxShadowSecondary},children:[r.jsx(B,{size:"small",type:"text",onClick:()=>f(),style:{fontSize:12,padding:"2px 6px"},children:"+"}),r.jsx(B,{size:"small",type:"text",onClick:()=>b(),style:{fontSize:12,padding:"2px 6px"},children:"-"}),r.jsx(B,{size:"small",type:"text",onClick:()=>x(),style:{fontSize:10,padding:"2px 6px"},children:"⌂"}),r.jsx(je,{title:d("components.mermaid.exportSvg"),children:r.jsx(B,{size:"small",type:"text",icon:r.jsx(cr,{}),"aria-label":"Download chart",disabled:g,loading:h,onClick:()=>{y()},style:{fontSize:11,padding:"2px 6px"}})})]}),r.jsx(dP,{wrapperStyle:{width:"100%",height:"100%"},contentStyle:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%"},children:r.jsx("div",{style:{display:"inline-block",lineHeight:0},dangerouslySetInnerHTML:{__html:e.replace(/<svg([^>]*)>/,'<svg$1 style="display: block; max-width: 100%; max-height: 100%;">')}})})]})})})]})};function bP(e){let t=2166136261;for(let s=0;s<e.length;s++)t=(t^e.charCodeAt(s))*16777619;return(t>>>0).toString(36)}const vP=(e,t)=>{const s=m.useMemo(()=>nT(e),[e]),n=m.useMemo(()=>bP(s),[s]),[o,a]=m.useState(()=>{const i=Ja(n);return i?{svg:i.svg,height:i.height+80,svgWidth:i.width,svgHeight:i.height,error:"",isLoading:!1}:{svg:"",height:200,svgWidth:800,svgHeight:200,error:"",isLoading:t}});return m.useEffect(()=>{const i=Ja(n);a(i?{svg:i.svg,height:i.height+80,svgWidth:i.width,svgHeight:i.height,error:"",isLoading:!1}:{svg:"",height:200,svgWidth:800,svgHeight:200,error:"",isLoading:!1})},[n]),m.useEffect(()=>{if(Ja(n))return;let l=!1;return a(c=>({...c,isLoading:!0})),lT(n,s).then(c=>{l||a({svg:c.svg,height:c.height+80,svgWidth:c.width,svgHeight:c.height,error:"",isLoading:!1})}).catch(c=>{if(!l){console.error("[MermaidState] Render error:",c);const d=c instanceof Error?c.message:String(c);a(u=>({...u,error:d||"Failed to render Mermaid diagram",isLoading:!1}))}}),()=>{l=!0}},[n,s,t]),{renderState:o,chartKey:n}},{useToken:SP}=xe,vi=dt.memo(({chart:e,id:t,className:s,style:n,onFix:o})=>{const{token:a}=SP(),i=zi(),[l,c]=m.useState(!1),[d,u]=m.useState(""),h=m.useRef(null),{renderState:p,chartKey:y}=vP(e,!0),{svg:g,height:f,svgWidth:b,error:x,isLoading:S}=p,C=(()=>{const T=i.defaultScale;return b>1200?T*.8:b>800?T*1:T*1.2})(),_=async()=>{if(!(!o||l)){c(!0),u("");try{await o(e,x)}catch(T){const j=T instanceof Error?T.message:String(T);u(j||"Failed to fix Mermaid diagram")}finally{c(!1)}}};return x?r.jsx(Jj,{error:x,className:s,style:n,token:a,onFix:o?_:void 0,isFixing:l,fixError:d}):r.jsx(xP,{svg:g,height:f,isLoading:S,initialScale:C,chartKey:y,className:s,style:n,token:a,containerRef:h})});vi.displayName="MermaidChart";const wP=Object.freeze(Object.defineProperty({__proto__:null,MermaidChart:vi,default:vi},Symbol.toStringTag,{value:"Module"}));ut.registerLanguage("javascript",xp);ut.registerLanguage("js",xp);ut.registerLanguage("typescript",bp);ut.registerLanguage("ts",bp);ut.registerLanguage("python",vp);ut.registerLanguage("py",vp);ut.registerLanguage("json",lx);ut.registerLanguage("bash",Bc);ut.registerLanguage("shell",Bc);ut.registerLanguage("sh",Bc);ut.registerLanguage("css",cx);ut.registerLanguage("html",Sp);ut.registerLanguage("xml",Sp);ut.registerLanguage("sql",dx);ut.registerLanguage("yaml",wp);ut.registerLanguage("yml",wp);ut.registerLanguage("markdown",_p);ut.registerLanguage("md",_p);const _P=()=>On,TP=["javascript","js","typescript","ts","python","py","json","bash","shell","sh","css","html","xml","sql","yaml","yml","markdown","md"],kP=({language:e,codeString:t,token:s})=>{const{t:n}=se(),[o,a]=m.useState(!1),i=async()=>{try{await es(t),pe.success(n("components.markdown.codeCopiedSuccess"))}catch(d){console.error("Copy failed:",d),pe.error(n("components.markdown.copyFailed"))}},l=e.toLowerCase(),c=TP.includes(l);return r.jsxs(te,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto"},onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[r.jsx(ut,{style:_P(),language:c?l:"text",PreTag:"div",customStyle:{margin:`${s.marginXS}px 0`,borderRadius:s.borderRadiusSM,fontSize:s.fontSizeSM,maxWidth:"100%",paddingRight:"50px"},showLineNumbers:t.split(`
|
|
214
|
+
`).length>10,wrapLines:!0,wrapLongLines:!0,children:t}),o&&r.jsx(B,{type:"text",size:"small",icon:r.jsx(Jt,{}),onClick:i,"aria-label":"Copy code",style:{position:"absolute",top:s.paddingSM,right:s.paddingSM,backgroundColor:"var(--lotus-code-copy-btn-bg, rgba(0, 0, 0, 0.6))",color:"var(--lotus-code-copy-btn-color, white)",border:"none",borderRadius:s.borderRadiusSM,opacity:.8,transition:"opacity 0.2s",zIndex:10},onMouseEnter:d=>{const u=d.currentTarget;u.style.opacity="1"},onMouseLeave:d=>{const u=d.currentTarget;u.style.opacity="0.8"}})]})},CP=({codeString:e,token:t})=>{const{t:s}=se();return r.jsxs(te,{size:"small",styles:{body:{padding:0}},style:{position:"relative",margin:`${t.marginXS}px 0`},onMouseEnter:n=>{const o=n.currentTarget.querySelector(".fallback-copy-btn");o&&(o.style.display="block")},onMouseLeave:n=>{const o=n.currentTarget.querySelector(".fallback-copy-btn");o&&(o.style.display="none")},children:[r.jsx("pre",{style:{backgroundColor:t.colorBgContainer,border:`1px solid ${t.colorBorder}`,padding:t.padding,borderRadius:t.borderRadiusSM,overflow:"auto",fontSize:t.fontSizeSM,paddingRight:"50px",margin:0},children:r.jsx("code",{style:{color:t.colorText},children:e})}),r.jsx(B,{type:"text",size:"small",icon:r.jsx(Jt,{}),"aria-label":"Copy code",className:"fallback-copy-btn",onClick:async()=>{try{await es(e),pe.success(s("components.markdown.codeCopiedSuccess"))}catch(n){console.error("Copy failed:",n),pe.error(s("components.markdown.copyFailed"))}},style:{position:"absolute",top:t.paddingSM,right:t.paddingSM,backgroundColor:"var(--lotus-code-copy-btn-bg, rgba(0, 0, 0, 0.6))",color:"var(--lotus-code-copy-btn-color, white)",border:"none",borderRadius:t.borderRadiusSM,display:"none",zIndex:10}})]})},jP={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"},ky=/^(\s*%%\{[\s\S]*?\}%%\s*)+/,MP=/^(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,PP=e=>e.replace(ky,"").trimStart(),EP=(e,t)=>{const s=e.match(ky);if(!s)return`${t}
|
|
215
|
+
${e}`.trim();const n=s[0].trimEnd(),o=e.slice(s[0].length).trimStart();return o?`${n}
|
|
216
|
+
${t}
|
|
217
|
+
${o}`:`${n}
|
|
218
|
+
${t}`},RP=(e,t)=>{const s=jP[e];if(!s)return null;const n=t.trim();if(!n)return"";if(e==="mermaid")return n;const o=PP(n);return MP.test(o)?n:EP(n,s)},Cy=(e,t,s,n,o="lazy")=>{try{if(!t||typeof t!="string")return console.warn("Invalid codeString provided to renderCodeBlock:",t),null;const a=e.toLowerCase().trim(),i=RP(a,t);if(i!==null){const l=i.trim();return l?o==="eager"?r.jsx(vi,{chart:l,onFix:n}):r.jsx(Gj,{chart:l,onFix:n}):(console.warn("Empty Mermaid chart content"),null)}return r.jsx(kP,{language:a,codeString:t,token:s})}catch(a){return console.warn("Syntax highlighting failed:",a),r.jsx(CP,{codeString:t,token:s})}},dh=(e,t)=>{if(typeof window>"u")return;const s=window.open(e,"_blank","noopener,noreferrer");if(s){s.opener=null;return}((t==null?void 0:t.allowLocationFallback)??!0)&&window.location.assign(e)},jy=async e=>{const t=e.trim();if(!t)return;if(_y()){const n=window.__TAURI_INTERNALS__,o=n==null?void 0:n.invoke;if(typeof o=="function")try{await o("plugin:shell|open",{path:t});return}catch(a){console.warn("[openExternalLink] Failed to open via Tauri shell plugin, falling back to browser open.",a)}dh(t,{allowLocationFallback:!1});return}dh(t)},{Text:uh}=le,My=(e,t)=>({p:({children:s})=>r.jsx(uh,{style:{marginBottom:e.marginSM,display:"block"},children:s}),ol:({children:s})=>r.jsx("ol",{style:{marginBottom:e.marginSM,paddingLeft:20},children:s}),ul:({children:s})=>r.jsx("ul",{style:{marginBottom:e.marginSM,paddingLeft:20},children:s}),li:({children:s})=>r.jsx("li",{style:{marginBottom:e.marginXS},children:s}),code({className:s,children:n,inline:o,...a}){const i=/language-([^\s]+)/i.exec(s||""),l=i?i[1]:"",c=o??(!i&&!s),d=n?String(n).replace(/\n$/,""):"";return c?r.jsx(uh,{code:!0,className:s,...a,children:n}):d.trim()?Cy(l,d,e,t==null?void 0:t.onFixMermaid,t==null?void 0:t.mermaidRenderMode):null},blockquote:({children:s})=>r.jsx(te,{size:"small",styles:{body:{padding:`${e.paddingXS}px ${e.padding}px`}},style:{borderLeft:`3px solid ${e.colorPrimary}`,background:e.colorPrimaryBg,margin:`${e.marginXS}px 0`,color:e.colorTextSecondary,fontStyle:"italic"},children:s}),a:({children:s,href:n})=>{const o=typeof n=="string"?n.trim():"";return o?r.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",onClick:a=>{a.preventDefault(),a.stopPropagation(),jy(o)},style:{color:e.colorLink,textDecoration:"underline",overflowWrap:"anywhere"},children:s}):r.jsx(r.Fragment,{children:s})},table:({children:s})=>r.jsx(te,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${e.marginSM}px 0`},children:r.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${e.colorBorder}`},children:s})}),thead:({children:s})=>r.jsx("thead",{style:{backgroundColor:e.colorFillTertiary,color:e.colorText},children:s}),tbody:({children:s})=>r.jsx("tbody",{children:s}),tr:({children:s})=>r.jsx("tr",{style:{borderBottom:`1px solid ${e.colorBorder}`},children:s}),th:({children:s})=>r.jsx("th",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,textAlign:"left",fontWeight:"bold",borderRight:`1px solid ${e.colorBorder}`},children:s}),td:({children:s})=>r.jsx("td",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,borderRight:`1px solid ${e.colorBorder}`},children:s}),input:({type:s,checked:n,disabled:o})=>s==="checkbox"?r.jsx("input",{type:"checkbox",checked:n,disabled:o,style:{marginRight:e.marginXS,accentColor:e.colorPrimary},readOnly:!0}):r.jsx("input",{type:s,checked:n,disabled:o})}),{Text:wt}=le,AP=({content:e,toolName:t,status:s="success",timestamp:n,defaultCollapsed:o=!0,isLoading:a,errorMessage:i})=>{var b;const{t:l}=se(),{token:c}=xe.useToken(),d=m.useMemo(()=>jc(e),[e]),u=m.useMemo(()=>typeof a=="boolean"?a:d.formattedText.trim().length===0,[d.formattedText,a]),h=m.useMemo(()=>R_(d.formattedText),[d.formattedText]),p=m.useMemo(()=>ma(e),[e]),y=m.useMemo(()=>p?Wg(p.diff.unified):[],[p]),g=async()=>{try{const x=d.isJson?ur(d.parsedJson):d.formattedText;await es(x)}catch(x){console.error("[ToolResultCard] Failed to copy result:",x)}},f=m.useMemo(()=>{const x=e?e.slice(0,50).replace(/[^a-zA-Z0-9]/g,""):"empty";return`tool-result-${t}-${x}`},[t,e]);return r.jsx(js,{defaultActiveKey:o?[]:[f],style:{backgroundColor:c.colorBgContainer,borderColor:c.colorBorderSecondary,borderWidth:1,borderStyle:"solid",borderRadius:c.borderRadiusLG},items:[{key:f,label:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:c.marginSM,width:"100%"},children:[r.jsx(Xc,{style:{color:c.colorPrimary,flexShrink:0}}),r.jsx(wt,{strong:!0,style:{color:c.colorText,flexShrink:0},children:t}),r.jsx(wt,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:c.fontSizeSM},children:u?l("components.toolResult.waiting"):h}),r.jsx(fe,{color:Ug(s),style:{flexShrink:0,margin:0},children:s})]}),children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:c.marginSM,children:[n&&r.jsx(wt,{type:"secondary",style:{fontSize:c.fontSizeSM},children:new Date(n).toLocaleString()}),i&&r.jsx(Ne,{type:"error",message:l("components.toolResult.executionFailed"),description:i,showIcon:!0}),r.jsxs("div",{style:{position:"relative"},children:[r.jsx(je,{title:l("components.toolResult.copyResult"),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(Jt,{}),"aria-label":l("components.toolResult.copyResult"),onClick:x=>{x.stopPropagation(),g()},style:{position:"absolute",top:8,right:8,zIndex:1}})}),u?r.jsx(wt,{type:"secondary",children:l("components.toolResult.waitingForResult")}):p?r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:8,children:[p.message&&r.jsx(wt,{style:{fontSize:c.fontSizeSM},children:p.message}),r.jsxs(wt,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(wt,{strong:!0,children:[l("common.file"),":"]})," ",r.jsx(wt,{code:!0,children:p.file_path})]}),p.workspace&&r.jsxs(wt,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(wt,{strong:!0,children:[l("common.workspace"),":"]})," ",r.jsx(wt,{code:!0,children:p.workspace})]}),(b=p.checkpoint)!=null&&b.created?r.jsxs(wt,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(wt,{strong:!0,children:[l("components.toolResult.checkpoint"),":"]})," ",r.jsx(wt,{code:!0,children:p.checkpoint.path})]}):r.jsx(wt,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("components.toolResult.checkpointNone")}),r.jsx("div",{style:{border:`1px solid ${c.colorBorderSecondary}`,borderRadius:c.borderRadiusSM,maxHeight:400,overflow:"auto",background:c.colorBgContainer},children:y.map((x,S)=>{const w={margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:c.fontSizeSM,lineHeight:1.5,padding:"0 8px",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"};return x.kind==="add"?w.background=c.colorSuccessBg:x.kind==="remove"?w.background=c.colorErrorBg:x.kind==="modified_add"?(w.background=c.colorWarningBg,w.borderLeft=`3px solid ${c.colorSuccess}`):x.kind==="modified_remove"?(w.background=c.colorWarningBg,w.borderLeft=`3px solid ${c.colorError}`):x.kind==="hunk"?(w.background=c.colorFillSecondary,w.color=c.colorTextSecondary):x.kind==="meta"&&(w.background=c.colorFillTertiary,w.color=c.colorTextSecondary),r.jsx("pre",{style:w,children:x.text||" "},`${S}-${x.kind}`)})}),p.diff.truncated&&r.jsx(wt,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("components.toolResult.diffTruncated")})]}):d.isJson?r.jsx(ir,{language:"json",style:On,wrapLongLines:!0,customStyle:{margin:0,borderRadius:c.borderRadiusSM,backgroundColor:c.colorBgContainer,fontSize:c.fontSizeSM,maxHeight:400,overflow:"auto"},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:d.formattedText}):r.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:c.fontSizeSM,backgroundColor:c.colorBgContainer,padding:c.paddingSM,borderRadius:c.borderRadiusSM,margin:0,maxHeight:400,overflow:"auto"},children:d.formattedText})]})]})}]})},$d=m.memo(AP);$d.displayName="ToolResultCard";const{Text:bs}=le;function IP(e,t){const s=Nn(e);if(s)return`MCP ${s.serverId}: ${s.toolName}`;const n=(i,l)=>{const c=typeof i=="string"?i:String(i??"");return!c||c.length<=l?c:c.substring(0,l).trimEnd()+"…"},o={file_read:i=>`Reading: ${n(i.path||i.file_path||"file",40)}`,file_write:i=>`Writing to: ${n(i.path||i.file_path||"file",35)}`,file_edit:i=>`Editing: ${n(i.path||i.file_path||"file",40)}`,bash:i=>`Executing: ${n(i.command,40)}`,grep:i=>`Searching: "${n(i.pattern,30)}"`,glob:i=>`Finding files: "${i.pattern}"`,conclusion:i=>`Presenting conclusion: "${n(i.conclusion||i.title||"",30)}"`,read:i=>`Reading: ${i.file_path||"file"}`,write:i=>`Writing: ${i.file_path||"file"}`,edit:i=>`Editing: ${i.file_path||"file"}`,search:i=>`Searching: "${n(i.query||i.pattern,30)}"`,default:()=>`Calling ${e}`};return(o[e]||o.default)(t)}const $P=({toolName:e,parameters:t,toolCallId:s,streamingOutput:n,defaultExpanded:o=!1,metadata:a})=>{const{t:i}=se(),{token:l}=xe.useToken(),c=m.useMemo(()=>Nn(e),[e]),[d,u]=m.useState(o?[s]:[]),h=m.useRef(!1),p=m.useRef(null);m.useEffect(()=>{h.current||!n||n.trim().length===0||(u(x=>x.includes(s)?x:[s]),h.current=!0)},[n,s]),m.useEffect(()=>{if(!n||n.trim().length===0||!d.includes(s))return;const x=p.current;x&&(x.scrollTop=x.scrollHeight)},[n,d,s]);const y=m.useMemo(()=>IP(e,t),[e,t]),g=m.useMemo(()=>ur(t,2),[t]),f=async()=>{try{await es(g)}catch(x){console.error("[ToolCallCard] Failed to copy parameters:",x)}},b=m.useMemo(()=>{const x=["path","file_path","command","pattern","query","limit"];return Object.entries(t).sort((C,_)=>{const T=x.indexOf(C[0]),j=x.indexOf(_[0]);return T!==-1&&j!==-1?T-j:T!==-1?-1:j!==-1?1:0}).slice(0,3)},[t]);return r.jsx(js,{activeKey:d,onChange:x=>{const S=Array.isArray(x)?x.map(String):x==null?[]:[String(x)];u(S),S.includes(s)&&(h.current=!0)},style:{background:"var(--lotus-tool-card-bg)",borderColor:"var(--lotus-tool-card-border)",borderWidth:1,borderStyle:"solid",borderRadius:l.borderRadiusLG,boxShadow:"var(--lotus-tool-card-shadow)",transition:"all 0.3s ease",overflow:"hidden"},className:"tool-call-card-collapse",items:[{key:s,label:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:l.marginSM,width:"100%"},children:[r.jsx("div",{style:{width:34,height:34,borderRadius:12,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,background:"var(--lotus-tool-badge-bg)",border:"var(--lotus-tool-badge-border)",boxShadow:"var(--lotus-tool-badge-shadow)"},children:r.jsx(hr,{style:{color:l.colorPrimary,flexShrink:0}})}),c?r.jsxs(q,{size:"small",wrap:!1,children:[r.jsx(fe,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:8,fontWeight:700,boxShadow:"var(--lotus-purple-shadow)"},children:"MCP"}),r.jsx(bs,{strong:!0,style:{color:l.colorText},children:c.toolName}),r.jsx(bs,{type:"secondary",style:{fontSize:l.fontSizeSM},children:r.jsx(bs,{code:!0,style:{fontSize:l.fontSizeSM},children:c.serverId})})]}):r.jsx(bs,{strong:!0,style:{color:l.colorText,flexShrink:0},children:e}),r.jsx(bs,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:l.fontSizeSM},children:y}),(a==null?void 0:a.elapsed_ms)!=null&&r.jsx(je,{title:a.is_mutating?"Mutating tool":"Read-only tool",children:r.jsx(fe,{color:a.is_mutating?"orange":"green",style:{marginInlineEnd:0,borderRadius:999,paddingInline:6,fontSize:l.fontSizeSM-1,lineHeight:"18px",flexShrink:0},children:a.elapsed_ms<1e3?`${a.elapsed_ms}ms`:`${(a.elapsed_ms/1e3).toFixed(1)}s`})})]}),children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:l.marginSM,children:[n&&n.trim().length>0&&r.jsxs("div",{children:[r.jsx(bs,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolCall.liveOutput")}),r.jsx("div",{ref:p,className:"lotus-code-surface",style:{marginTop:l.marginXS,borderRadius:l.borderRadiusSM,backgroundColor:l.colorBgContainer,maxHeight:240,overflow:"auto"},children:r.jsx(ir,{language:"text",style:On,wrapLongLines:!0,customStyle:{margin:0,backgroundColor:"transparent",fontSize:l.fontSizeSM},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:n})})]}),b.length>0&&r.jsxs("div",{children:[r.jsx(bs,{strong:!0,style:{fontSize:l.fontSizeSM,marginBottom:l.marginXS,display:"block"},children:i("components.toolCall.keyParameters")}),r.jsx("ul",{style:{margin:0,paddingLeft:l.paddingLG,fontSize:l.fontSizeSM},children:b.map(([x,S])=>r.jsxs("li",{children:[r.jsx(bs,{code:!0,style:{fontSize:l.fontSizeSM},children:x}),r.jsxs(bs,{style:{fontSize:l.fontSizeSM},children:[": ",typeof S=="string"?S:JSON.stringify(S)]})]},x))})]}),r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:l.marginXS},children:[r.jsx(bs,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolCall.fullParameters")}),r.jsx(je,{title:i("components.toolCall.copyParameters"),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(Jt,{}),"aria-label":i("components.toolCall.copyParameters"),onClick:x=>{x.stopPropagation(),f()}})})]}),r.jsx(ir,{language:"json",style:On,wrapLongLines:!0,customStyle:{margin:0,borderRadius:l.borderRadiusSM,backgroundColor:l.colorBgContainer,fontSize:l.fontSizeSM,maxHeight:400,overflow:"auto"},className:"lotus-code-surface",codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:g})]})]})}]})},Fd=m.memo($P);Fd.displayName="ToolCallCard";const{Text:jl}=le,FP=({content:e,workflowName:t,parameters:s,status:n="success",timestamp:o,onRetry:a,isLoading:i,errorMessage:l})=>{const{t:c}=se(),{token:d}=xe.useToken(),[u,h]=m.useState(!1),p=m.useMemo(()=>jc(e),[e]),y=m.useMemo(()=>typeof i=="boolean"?i:p.formattedText.trim().length===0,[p.formattedText,i]),g=m.useMemo(()=>P_(p.formattedText),[p.formattedText]),f=p.isJson||g,b=!f||u,x=m.useMemo(()=>E_(p.formattedText),[p.formattedText]),S=m.useMemo(()=>{if(s==null)return null;if(typeof s=="string")return jc(s);try{return{isJson:!0,formattedText:JSON.stringify(s,null,2),parsedJson:s}}catch(_){return console.error("[WorkflowResultCard] Failed to stringify parameters:",_),{isJson:!1,formattedText:String(s)}}},[s]),w=async()=>{try{const _=p.isJson?ur(p.parsedJson):p.formattedText;await es(_)}catch(_){console.error("[WorkflowResultCard] Failed to copy content:",_)}},C=async()=>{if(S)try{const _=S.isJson?ur(S.parsedJson):S.formattedText;await es(_)}catch(_){console.error("[WorkflowResultCard] Failed to copy parameters:",_)}};return r.jsx(te,{size:"small",variant:"outlined",style:{borderRadius:d.borderRadiusLG,borderColor:d.colorBorderSecondary,backgroundColor:d.colorBgContainer},bodyStyle:{padding:d.paddingMD},children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:d.marginSM,children:[r.jsxs(K,{align:"center",justify:"space-between",children:[r.jsxs(q,{size:d.marginXS,align:"center",children:[r.jsx(Lx,{style:{color:d.colorWarning}}),r.jsx(jl,{strong:!0,children:c("components.workflowResult.userWorkflow")}),r.jsx(fe,{color:d.colorWarning,children:t}),r.jsx(fe,{color:Ug(n),children:n})]}),r.jsxs(q,{size:"small",children:[r.jsx(je,{title:c(u?"components.workflowResult.collapseResult":"components.workflowResult.expandResult"),children:f&&r.jsx(B,{type:"text",size:"small",icon:u?r.jsx(Ox,{}):r.jsx(Dx,{}),onClick:()=>h(_=>!_)})}),r.jsx(je,{title:c("components.workflowResult.copyResult"),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(Jt,{}),onClick:w,"aria-label":c("components.workflowResult.copyContent")})}),a&&r.jsx(je,{title:c("components.workflowResult.retryWorkflow"),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(Cs,{}),onClick:a,"aria-label":c("components.workflowResult.retryWorkflow")})})]})]}),o&&r.jsx(jl,{type:"secondary",style:{fontSize:d.fontSizeSM},children:new Date(o).toLocaleString()}),r.jsx(Dt,{style:{margin:`${d.marginXS}px 0`}}),l&&r.jsx(Ne,{type:"error",message:c("components.workflowResult.executionFailed"),description:l,showIcon:!0,style:{marginBottom:d.marginXS}}),r.jsx(K,{vertical:!0,style:{width:"100%"},children:y?r.jsx(ct,{tip:c("components.workflowResult.waitingForResult")}):p.isJson?r.jsx(ir,{language:"json",style:On,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:b?"none":280,overflow:b?"auto":"hidden"},children:p.formattedText}):r.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,maxHeight:b?"none":280,overflow:b?"visible":"hidden",marginBottom:0},children:[b?p.formattedText:x.preview,!b&&x.isTruncated&&`
|
|
219
|
+
…`]})}),S&&r.jsxs(K,{vertical:!0,style:{width:"100%"},children:[r.jsx(Dt,{style:{margin:`${d.marginXS}px 0`},children:r.jsxs(q,{size:"small",children:[r.jsx(jl,{strong:!0,children:c("common.parameters")}),r.jsx(je,{title:c("components.workflowResult.copyParameters"),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(Jt,{}),onClick:C,"aria-label":c("components.workflowResult.copyParameters")})})]})}),S.isJson?r.jsx(ir,{language:"json",style:On,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:220,overflow:"auto"},children:S.formattedText}):r.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,marginBottom:0},children:S.formattedText})]})]})})},Py=m.memo(FP);Py.displayName="WorkflowResultCard";const{Text:Ml}=le,LP=({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o,conclusionMarkdown:a,markdownComponents:i,markdownPlugins:l,rehypePlugins:c})=>{const{t:d}=se(),[u,h]=m.useState(!1),p=z(g=>g.setPendingQuestionRespond),y=z(g=>g.clearPendingQuestionRespondForSession);return m.useEffect(()=>{if(typeof window>"u")return;const g=f=>{var S;const x=((S=f.detail)==null?void 0:S.sessionId)??null;!e||x!==e||(h(!0),y(e))};return window.addEventListener(ar,g),()=>{window.removeEventListener(ar,g)}},[e,y]),m.useEffect(()=>{if(!(!e||u))return p({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o??null}),()=>{y(e)}},[e,u,o,t,s,n,p,y]),r.jsxs(q,{direction:"vertical",size:"middle",style:{width:"100%"},children:[a?r.jsx(us,{remarkPlugins:l,rehypePlugins:c,components:i,children:a}):null,r.jsxs("div",{children:[r.jsx(Ml,{strong:!0,children:d("components.questionDialog.questionLabel","Question")}),r.jsx("div",{style:{marginTop:8},children:r.jsx(us,{remarkPlugins:l,rehypePlugins:c,components:i,children:t})})]}),u?r.jsx(Ml,{type:"secondary",children:d("components.questionDialog.responseSubmittedContinue","Response submitted. Continuing...")}):r.jsx(Ml,{type:"secondary",children:n?d("components.questionDialog.responseInInputHint","Use the options or input box below to respond."):d("components.questionDialog.responseByOptionHint","Please respond using the options below the input box.")})]})},{Text:is}=le,OP=e=>{var a;if(!e)return{cleanText:e,hints:[]};const t=e.split(`
|
|
220
|
+
`),s=[],n=[];for(const i of t){const l=i.trim(),c=l.match(/^\[User explicitly selected MCP tool:\s*(.+?)\s*\]$/);if(c){const u=c[1]??"",h=Nn(u);s.push({type:"mcp",label:u,serverId:h==null?void 0:h.serverId,toolName:h==null?void 0:h.toolName});continue}const d=l.match(/^\[User explicitly selected skill:\s*(.+?)\s*\]$/);if(d){const u=d[1]??"",h=u.match(/\(ID:\s*([^)]+)\)\s*$/i),p=(a=h==null?void 0:h[1])==null?void 0:a.trim(),y=h?u.replace(/\(ID:\s*([^)]+)\)\s*$/i,"").trim():u;s.push({type:"skill",label:y||u,skillId:p});continue}n.push(i)}return{cleanText:n.join(`
|
|
221
|
+
`).trimStart(),hints:s}},DP=({sessionId:e,message:t,messageText:s,isUserToolCall:n,formatUserToolCall:o,markdownComponents:a,markdownPlugins:i,rehypePlugins:l})=>{var g;const{t:c}=se(),d=f=>(f??"").trim().toLowerCase()==="conclusion";if(Kg(t)){const f=t.result.result??"",b=t.isError?f||c("components.toolResult.executionFailed"):void 0,x=!b&&f.trim().length===0;if(t.result.display_preference==="Hidden")return null;const S=(t.toolName??"").trim().toLowerCase(),w=S==="conclusion",C=C_(f),_=(S==="conclusion_with_options"||S==="exitplanmode"||S==="request_permissions")&&!t.isError&&C,T=S==="conclusion"?Bg(f):null;return _&&C?r.jsx(LP,{sessionId:e,question:C.question,options:C.options,allowCustom:C.allow_custom,toolCallId:t.toolCallId,conclusionMarkdown:j_(C.conclusion),markdownComponents:a,markdownPlugins:i,rehypePlugins:l}):T?r.jsx(q,{direction:"vertical",style:{width:"100%"},size:"small",children:r.jsx(us,{remarkPlugins:i,rehypePlugins:l,components:a,children:T})}):r.jsx($d,{content:f,toolName:t.toolName,status:t.isError?"error":x?"warning":"success",timestamp:t.createdAt,defaultCollapsed:!w,isLoading:x,errorMessage:b})}if(hT(t)){const f=t.content??"",b=t.status==="error"?f||c("components.workflowResult.executionFailed"):void 0,x=!b&&f.trim().length===0;return r.jsx(Py,{content:f,workflowName:t.workflowName,parameters:t.parameters,status:x?"warning":t.status??"success",timestamp:t.createdAt,isLoading:x,errorMessage:b})}if(mT(t)){const f=t.toolCalls.filter(b=>!d(b.toolName));return f.length===0?null:r.jsx(q,{direction:"vertical",style:{width:"100%"},children:f.map(b=>r.jsx(Fd,{toolName:b.toolName,parameters:b.parameters,toolCallId:b.toolCallId,streamingOutput:b.streamingOutput,defaultExpanded:!1,metadata:t.metadata},b.toolCallId))})}if(t.isAuthError)return r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:"middle",children:[r.jsx(Ne,{message:c("chat.messageCard.authRequired"),description:r.jsx(us,{remarkPlugins:i,rehypePlugins:l,components:a,children:s}),type:"error",showIcon:!0}),r.jsx(B,{type:"primary",icon:r.jsx(sa,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:u,hints:h}=t.role==="user"?OP(s):{cleanText:s,hints:[]},p=t.role==="assistant"&&"type"in t&&t.type==="text"&&"metadata"in t&&typeof((g=t.metadata)==null?void 0:g.reasoning)=="string"?t.metadata.reasoning:"",y=p.trim().length>0;return t.role==="assistant"&&!s&&!y?r.jsx(is,{italic:!0,children:c("chat.messageCard.assistantThinking")}):r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:"small",children:[y?r.jsx(js,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:r.jsx(is,{strong:!0,children:c("chat.messageCard.reasoning")}),children:r.jsx(us,{remarkPlugins:i,rehypePlugins:l,components:a,children:p})}]}):null,h.map((f,b)=>f.type==="mcp"?r.jsx(Ne,{type:"info",showIcon:!1,message:r.jsxs(q,{wrap:!0,size:"small",children:[r.jsx(fe,{color:"purple",children:"MCP"}),r.jsx(is,{strong:!0,children:c("chat.messageCard.selectedTool")}),f.serverId&&r.jsx(is,{type:"secondary",children:r.jsx(is,{code:!0,children:f.serverId})}),f.toolName&&r.jsx(is,{type:"secondary",children:r.jsx(is,{code:!0,children:f.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${b}`):r.jsx(Ne,{type:"success",showIcon:!1,message:r.jsxs(q,{wrap:!0,size:"small",children:[r.jsx(fe,{color:"success",children:"Skill"}),r.jsx(is,{strong:!0,children:c("chat.messageCard.selected")}),f.label&&r.jsx(is,{children:f.label}),f.skillId&&r.jsx(is,{type:"secondary",children:r.jsx(is,{code:!0,children:f.skillId})})]}),style:{marginBottom:0}},`hint-skill-${b}`)),u?r.jsx(us,{remarkPlugins:i,rehypePlugins:l,components:a,children:n?o(u):u}):null]})},zP=m.memo(DP),{Text:Pl}=le,NP=({role:e,formattedTimestamp:t,token:s})=>{const n=e==="user",o=e==="assistant",a=n?"You":o?"Bodhi":e,i=n?"Y":o?"B":e.slice(0,1).toUpperCase();return r.jsxs(K,{align:"center",justify:"space-between",gap:s.marginXS,style:{marginBottom:s.marginXS},children:[r.jsxs(K,{align:"center",gap:10,children:[r.jsx("div",{style:{width:30,height:30,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:700,letterSpacing:"0.3px",background:n?"var(--lotus-avatar-user-bg)":o?"var(--lotus-avatar-assistant-bg)":"var(--lotus-avatar-system-bg)",color:"white",boxShadow:n?"var(--lotus-avatar-user-shadow)":o?"var(--lotus-avatar-assistant-shadow)":"var(--lotus-avatar-system-shadow)",border:"var(--lotus-avatar-border)"},children:i}),r.jsxs(K,{vertical:!0,gap:0,children:[r.jsx(Pl,{strong:!0,style:{fontSize:13,color:n?"var(--lotus-primary)":s.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:a}),r.jsx(Pl,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:n?"Prompt":o?"Assistant":"System"})]})]}),t&&r.jsx(Pl,{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})]})},Ld=e=>{if(e.includes("```json")){const t=e.indexOf("```json")+7,s=e.indexOf("```",t);if(s>t)return e.substring(t,s).trim()}else if(e.includes("{")){const t=e.indexOf("{"),s=e.lastIndexOf("}");if(s>t)return e.substring(t,s+1).trim()}return null},BP=e=>e==="text"||e==="plan"||e==="question"||e==="tool_call"||e==="tool_result",WP=(e,t)=>{if(t)return t;if("message_type"in e&&e.message_type){const s=e.message_type;if(BP(s))return s}if(e.role==="assistant"&&e.type==="text"){const s=typeof e.content=="string"?e.content:"";try{const n=Ld(s);if(n){const o=JSON.parse(n);if(o.goal&&o.steps&&Array.isArray(o.steps))return"plan";if(o.type==="question"&&o.question)return"question"}}catch{return"text"}}return"text"},UP=(e,t)=>{if(t!=="plan"||e.role!=="assistant"||e.type!=="text")return null;const s=e.content??"";try{const n=Ld(s);if(n){const o=JSON.parse(n);if(o.goal&&o.steps)return{goal:o.goal,steps:o.steps.map(a=>({step_number:a.step_number||a.stepNumber||0,action:a.action||"",reason:a.reason||a.rationale||"",tools_needed:a.tools_needed||a.tools||[],estimated_time:a.estimated_time||a.estimatedTime||""})),estimated_total_time:o.estimated_total_time||o.estimatedTotalTime||"",risks:o.risks||[],prerequisites:o.prerequisites||[]}}}catch(n){console.error("Failed to parse plan:",n)}return null},qP=(e,t)=>{if(t!=="question"||e.role!=="assistant"||e.type!=="text")return null;const s=e.content??"";try{const n=Ld(s);if(n){const o=JSON.parse(n);if(o.type==="question"&&o.question)return{type:"question",question:o.question,context:o.context||"",severity:o.severity||"minor",options:o.options||[],default:o.default,allow_custom:o.allow_custom||!1}}}catch(n){console.error("Failed to parse question:",n)}return null},Ey=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"?Bg(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""},HP=e=>{if(!e.startsWith("/"))return e;const t=e.split(" "),s=t[0].substring(1),n=t.slice(1).join(" ");if(s.startsWith("mcp__")){const a=s.slice(5),i=a.indexOf("__");if(i>0){const l=a.slice(0,i),c=a.slice(i+2);if(l&&c)return`🔌 MCP ${l}/${c}: ${n}`}}return`🔧 ${s.replace(/_/g," ").replace(/\b\w/g,a=>a.toUpperCase())}: ${n}`},mh=e=>e.map(t=>({name:t.name,extensions:[...t.extensions]})),hh=e=>e.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",YP={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"},XP='[data-mermaid-loading="true"]';class Ry{static async exportMessageText(t){const{format:s,content:n,sessionId:o=null,messageId:a=null,filenamePrefix:i}=t,l=i||["chat-message",o?hh(o.slice(0,8)):null,a?hh(a.slice(0,8)):null].filter(Boolean).join("-"),c=s==="markdown"?ws.generateTimestampedFilename(l,"md"):ws.generateTimestampedFilename(l,"pdf");if(s==="markdown"){const d=await ws.saveTextFile(n,mh(ws.FILTERS.MARKDOWN),c);return d.success?{success:!0,filename:d.filename}:{success:!1,error:d.error}}try{const d=await this.generatePdfFromText(n),u=await ws.saveBinaryFile(d,mh(ws.FILTERS.PDF),c);return u.success?{success:!0,filename:u.filename}:{success:!1,error:u.error}}catch(d){return{success:!1,error:d instanceof Error?d.message:Kt.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(t){if(typeof document>"u")throw new Error(Kt.t("chat.messageActions.pdfUnavailable"));const s=(await kt(async()=>{const{default:y}=await import("./vendor-pdf-Du4-g8Ia.js").then(g=>g.h);return{default:y}},__vite__mapDeps([16,1,2,3]),import.meta.url)).default,{jsPDF:n}=await kt(async()=>{const{jsPDF:y}=await import("./vendor-pdf-Du4-g8Ia.js").then(g=>g.j);return{jsPDF:y}},__vite__mapDeps([16,1,2,3]),import.meta.url),{createRoot:o}=await kt(async()=>{const{createRoot:y}=await import("./main-fT0cr1NN.js").then(g=>g.c);return{createRoot:y}},__vite__mapDeps([4,1,2,3,5]),import.meta.url),{flushSync:a}=await kt(async()=>{const{flushSync:y}=await import("./vendor-antd-CQLaBms0.js").then(g=>g.R);return{flushSync:y}},__vite__mapDeps([3,2]),import.meta.url),i=My(YP,{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=Kt.t("chat.messageActions.exportingPdf"),l.appendChild(c);const d=document.createElement("div");d.style.position="fixed",d.style.left="0",d.style.top="0",d.style.zIndex="2147483646",d.style.pointerEvents="none",d.style.width="794px",d.style.background="#fff",d.style.color="#111",d.style.padding="24px",d.style.boxSizing="border-box",d.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",d.style.fontSize="14px",d.style.lineHeight="1.35";const u=document.createElement("style");u.textContent=`
|
|
222
|
+
.md-export { color: #111; }
|
|
223
|
+
.md-export h1 { font-size: 24px; margin: 0 0 16px; }
|
|
224
|
+
.md-export h2 { font-size: 18px; margin: 18px 0 12px; }
|
|
225
|
+
.md-export h3 { font-size: 16px; margin: 14px 0 10px; }
|
|
226
|
+
.md-export [data-mermaid-controls="true"] { display: none !important; }
|
|
227
|
+
`,d.appendChild(u);const h=document.createElement("div");h.className="md-export",d.appendChild(h),document.body.appendChild(d),document.body.appendChild(l);const p=o(h);a(()=>{p.render(dt.createElement(us,{remarkPlugins:[wi,Uc],rehypePlugins:[Wc],components:i},t||""))});try{await this.waitForExportRenderReady(d);const y=await this.renderCanvasWithFallback(s,d),g=new n({unit:"pt",format:"a4",orientation:"portrait"}),f=g.internal.pageSize.getWidth(),b=g.internal.pageSize.getHeight(),x=24,S=f-x*2,w=b-x*2,C=y.width/S,_=Math.max(1,Math.floor(w*C));let T=0,j=0;for(;T<y.height;){const k=this.computeSmartSliceHeight(y,T,_),E=Math.max(1,Math.min(k,y.height-T)),M=document.createElement("canvas");M.width=y.width,M.height=E;const R=M.getContext("2d");if(!R)throw new Error("PDF render failed (no canvas context)");R.fillStyle="#ffffff",R.fillRect(0,0,M.width,M.height),R.drawImage(y,0,T,y.width,E,0,0,y.width,E);const I=M.toDataURL("image/jpeg",.92),P=E/C;j>0&&g.addPage(),g.addImage(I,"JPEG",x,x,S,P),T+=E,j+=1}const v=g.output("arraybuffer");return new Uint8Array(v)}finally{p.unmount(),l.remove(),d.remove()}}static async waitForExportRenderReady(t){var o,a,i;await new Promise(l=>requestAnimationFrame(()=>requestAnimationFrame(()=>l()))),await((i=(a=(o=document.fonts)==null?void 0:o.ready)==null?void 0:a.catch)==null?void 0:i.call(a,()=>{}));const s=Date.now(),n=6e3;for(;Date.now()-s<n;){if(!t.querySelector(XP)){await new Promise(c=>requestAnimationFrame(()=>c()));return}await new Promise(c=>setTimeout(c,50))}}static async renderCanvasWithFallback(t,s){const n={backgroundColor:"#ffffff",scale:2,useCORS:!0,allowTaint:!0};try{const a=await t(s,{...n,foreignObjectRendering:!0});if(a.width&&a.height)return a}catch(a){console.warn("PDF capture with foreignObjectRendering=true failed:",a)}const o=await t(s,{...n,foreignObjectRendering:!1});if(!o.width||!o.height)throw new Error("PDF render failed (empty canvas)");return o}static computeSmartSliceHeight(t,s,n){const o=t.height-s;if(o<=n)return o;const a=s+n,i=Math.max(1,Math.floor(n*.72)),l=Math.max(8,Math.floor(n*.12)),c=Math.max(s+i,a-l),d=Math.min(t.height-1,a+l),u=this.findWhitespaceBreakY(t,a,c,d);return u===null||u<=s?n:u-s}static findWhitespaceBreakY(t,s,n,o){if(n>o||t.width<=0)return null;try{const a=t.getContext("2d",{willReadFrequently:!0});if(!a||typeof a.getImageData!="function")return null;const i=o-n+1,l=a.getImageData(0,n,t.width,i).data,c=t.width*4,d=Math.max(1,Math.floor(t.width/320)),u=245,h=16,p=.03;let y=null,g=Number.POSITIVE_INFINITY,f=Number.POSITIVE_INFINITY;for(let b=0;b<i;b+=1){let x=0,S=0;const w=b*c;for(let v=0;v<t.width;v+=d){const k=w+v*4,E=l[k+3];if(S+=1,E<=h)continue;const M=l[k],R=l[k+1],I=l[k+2];(M<u||R<u||I<u)&&(x+=1)}if(S===0)continue;const C=x/S,_=n+b,T=Math.abs(_-s);(C<g||C===g&&T<f)&&(g=C,f=T,y=_)}return y===null||g>p?null:y}catch{return null}}}const VP=({messageText:e,messageId:t,currentSessionId:s,onDelete:n,onRestoreChat:o,onRestoreFilesAndChat:a,cardRef:i})=>{const{message:l}=ts.useApp(),{t:c}=se(),[d,u]=m.useState(""),h=m.useCallback(async x=>{try{await es(x)}catch(S){console.error("Failed to copy text:",S)}},[]),p=m.useCallback(x=>`> ${x.replace(/\n/g,`
|
|
228
|
+
> `)}`,[]),y=m.useCallback(()=>{if(!s)return;const x=p(d||e),S=new CustomEvent("reference-text",{detail:{text:x,sessionId:s}});window.dispatchEvent(S)},[p,s,e,d]),g=m.useCallback(async x=>{var C;const S=d||e;if(!S){l.warning(c("chat.messageActions.nothingToExport"));return}const w=await Ry.exportMessageText({format:x,content:S,sessionId:s??null,messageId:t??null});if(w.success)l.success(c("chat.messageActions.savedFile",{filename:w.filename}));else{if((C=w.error)!=null&&C.toLowerCase().includes("cancel"))return;l.error(w.error||c("chat.messageActions.exportFailed"))}},[l,s,t,e,d,c]),f=m.useCallback(x=>{x.preventDefault(),x.stopPropagation();const S=window.getSelection(),w=S?S.toString():"";w&&i.current&&S&&i.current.contains(S.anchorNode)?u(w):u("")},[i]);return{contextMenuItems:m.useMemo(()=>{const x=[...o&&a&&s&&t?[{key:"restore-chat",label:c("chat.messageActions.restoreChat"),icon:r.jsx(zx,{}),onClick:()=>{o()}},{key:"restore-chat-files",label:c("chat.messageActions.restoreFilesAndChat"),icon:r.jsx(jp,{}),onClick:()=>{a()}},{type:"divider"}]:[],{key:"copy",label:c("chat.messageActions.copy"),icon:r.jsx(Jt,{}),onClick:()=>{h(d||e)}},{key:"reference",label:c("chat.actions.referenceMessage"),icon:r.jsx(Ap,{}),onClick:y},{type:"divider"},{key:"export-md",label:c("chat.messageActions.exportMarkdown"),icon:r.jsx(cr,{}),onClick:()=>g("markdown")},{key:"export-pdf",label:c("chat.messageActions.exportPdf"),icon:r.jsx(cr,{}),onClick:()=>g("pdf")}];return n&&t&&x.push({key:"delete",label:c("chat.messageActions.deleteMessage"),icon:r.jsx(cn,{}),onClick:()=>n(t),danger:!0}),x},[h,g,t,e,n,o,a,y,d,s,c]),handleMouseUp:f,copyToClipboard:h,referenceMessage:y}},KP=({currentSessionId:e,updateSession:t,sendMessage:s})=>{const n=m.useCallback(async()=>{if(!e)return;const l=z.getState().chats.find(c=>c.id===e);if(l)try{t(e,{config:{...l.config,agentRole:"actor"}})}catch(c){console.error("Failed to switch to Actor role:",c)}},[e,t]),o=m.useCallback(async i=>{if(i.trim())try{await s(i.trim())}catch(l){console.error("Failed to send plan refinement:",l)}},[s]),a=m.useCallback(async i=>{if(i)try{await s(i)}catch(l){throw console.error("Failed to send answer:",l),l}},[s]);return{handleExecutePlan:n,handleRefinePlan:o,handleQuestionAnswer:a}},Ay=e=>{const t=e.match(/```mermaid\s*([\s\S]*?)```/i);return t?t[1].trim():e.trim()},GP=(e,t,s)=>{const n=t.trim(),o=Ay(s),a=/```mermaid\s*([\s\S]*?)```/gi;let i=!1;const l=e.replace(a,(d,u)=>i||u.trim()!==n?d:(i=!0,`\`\`\`mermaid
|
|
229
|
+
${o}
|
|
230
|
+
\`\`\``));return i?l:e.match(a)?e.replace(a,d=>i?d:(i=!0,`\`\`\`mermaid
|
|
231
|
+
${o}
|
|
232
|
+
\`\`\``)):null},ph="_text",Si=e=>!!(e&&e.role==="assistant"&&"type"in e&&e.type==="text"),fh=(e,t,s)=>{var o;const n=typeof((o=t.metadata)==null?void 0:o.backendMessageId)=="string"?t.metadata.backendMessageId.trim():"";if(n)return n;if(e.endsWith(ph)){const a=e.slice(0,-ph.length);if(a&&s.some(i=>i.id===a))return a}return e},JP=(e,t)=>{const s=t.trim();if(!s)return!1;const n=e.matchAll(/```mermaid\s*([\s\S]*?)```/gi);for(const o of n)if((o[1]||"").trim()===s)return!0;return!1},QP=e=>(e instanceof Error?e.message:String(e)).toLowerCase().includes("message not found"),ZP=(e,t,s,n)=>{const o=e.find(a=>a.id===t);return Si(o)?o:e.find(a=>Si(a)&&(a.content===s||JP(a.content,n)))},eE=(e,t)=>{const s=(t??"").trim(),n=["Original Mermaid code:","```mermaid",e.trim(),"```"];return s&&n.push("","Mermaid parser/render error:",s),n.push("","Please fix the Mermaid syntax while preserving the original meaning and labels."),n.join(`
|
|
233
|
+
`)},tE=async(e,t,s)=>{var l,c,d;const n=t==null?void 0:t.trim();if(!n)throw new Error("No model configured. Please select a default model in Provider Settings.");const i=((d=(c=(l=(await Cg().chat.completions.create({model:n,messages:[{role:"system",content:"You fix Mermaid diagrams using the parser/render error context. Return only corrected Mermaid code without markdown fences or extra text."},{role:"user",content:eE(e,s)}],temperature:0})).choices)==null?void 0:l[0])==null?void 0:c.message)==null?void 0:d.content)??"";return Ay(i)},sE=(e,t)=>{const s=jg();return m.useCallback(async(n,o)=>{const a=z.getState(),i=t??a.currentSessionId,l=a.chats.find(b=>b.id===i);if(!i||!l)throw new Error("No active chat available");const c=l.messages.find(b=>b.id===e);if(!Si(c))throw new Error("Mermaid fix is only available for assistant text messages");const d=await tE(n,s,o);if(!d)throw new Error("AI did not return a Mermaid fix");const u=GP(c.content,n,d);if(!u)throw new Error("Unable to locate Mermaid block to update");let h=fh(e,c,l.messages);try{await Ko.patchSessionMessage(i,h,{content:u})}catch(b){if(!QP(b))throw b;await a.loadChatHistory(i,{mode:"replace",retries:2,retryDelayMs:150,waitForAssistant:!0});const S=z.getState().chats.find(C=>C.id===i);if(!S)throw b;const w=ZP(S.messages,e,c.content,n);if(!w)throw b;h=fh(w.id,w,S.messages),await Ko.patchSessionMessage(i,h,{content:u})}const p=z.getState(),y=p.chats.find(b=>b.id===i);if(!y)throw new Error("No active chat available");const g=new Set([e,h]),f=y.messages.map(b=>!g.has(b.id)||!Si(b)?b:{...b,content:u});p.updateSession(i,{messages:f})},[e,t,s])},nE=e=>e.xs?"100%":e.sm?"95%":"800px",rE=[{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:"}],oE=({messageId:e,isVisible:t,onRetryWithVariation:s})=>{const{t:n}=se(),[o,a]=m.useState(null),[i,l]=m.useState(!1),c=m.useCallback(()=>{a(y=>y==="like"?null:"like"),l(!1)},[]),d=m.useCallback(()=>{a(y=>{const g=y==="dislike"?null:"dislike";return l(g==="dislike"),g})},[]),u=m.useCallback(y=>{s&&s(y.prefix)},[s]),p=["lotus-msg-feedback",t?"is-visible":"",o!==null?"has-rating":""].filter(Boolean).join(" ");return r.jsxs("div",{className:p,"data-message-id":e,children:[r.jsx(je,{title:n("feedback.helpful","Helpful"),children:r.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${o==="like"?"is-liked":""}`,onClick:c,"aria-label":n("feedback.helpful","Helpful"),children:o==="like"?r.jsx(Nx,{}):r.jsx(Bx,{})})}),r.jsx(je,{title:n("feedback.notHelpful","Not helpful"),children:r.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${o==="dislike"?"is-disliked":""}`,onClick:d,"aria-label":n("feedback.notHelpful","Not helpful"),children:o==="dislike"?r.jsx(Wx,{}):r.jsx(Ux,{})})}),i&&s&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"lotus-msg-feedback-sep"}),r.jsx("span",{className:"lotus-msg-feedback-retry",children:rE.map(y=>r.jsx(fe,{color:y.color,bordered:!1,className:"lotus-msg-feedback-retry-tag",onClick:()=>u(y),children:n(y.labelKey,y.fallbackLabel)},y.key))})]})]})},{useToken:aE}=xe,{useBreakpoint:iE}=_i,lE="chat-send-message",cE=({sessionId:e,message:t,onDelete:s,messageType:n})=>{const{role:o,id:a}=t,{token:i}=aE(),{t:l}=se(),{message:c}=ts.useApp(),d=iE(),u=z(U=>U.updateSession),h=z(U=>U.loadChatHistory),p=z(U=>U.refreshChats),y=m.useRef(null),[g,f]=m.useState(!1),b=z(U=>e?U.processingChats.has(e):!1),x=m.useCallback(U=>typeof window>"u"?Promise.reject(new Error("window is unavailable")):new Promise((Q,Y)=>{const he={content:U,sessionId:e,handled:!1,resolve:Q,reject:Y};window.dispatchEvent(new CustomEvent(lE,{detail:he})),he.handled||Y(new Error("No chat message dispatcher available"))}),[e]),S=m.useMemo(()=>{if(!t.createdAt)return null;const U=new Date(t.createdAt);if(Number.isNaN(U.getTime()))return null;try{return Mj(U,"MMM d, yyyy HH:mm")}catch{return U.toLocaleString()}},[t.createdAt]),w=m.useMemo(()=>WP(t,n),[t,n]),C=m.useMemo(()=>UP(t,w),[t,w]),_=m.useMemo(()=>qP(t,w),[t,w]),T=m.useMemo(()=>Ey(t),[t]),j=sE(a,e),v=m.useCallback(async U=>{var Q;if(!e||!a){c.warning(l("chat.messageActions.cannotRestore"));return}try{const Y=await Ko.restoreSessionState(e,{target_message_id:a,restore_files:U});await h(e,{mode:"replace"}),await p();const he=((Q=Y.file_errors)==null?void 0:Q.length)??0;if(he>0){c.warning(l("chat.messageActions.restorePartial",{count:he}));return}U?c.success(l("chat.messageActions.restoreFilesSuccess",{count:Y.messages_removed})):c.success(l("chat.messageActions.restoreSuccess",{count:Y.messages_removed}))}catch(Y){const he=Y instanceof Error?Y.message:l("chat.messageActions.restoreFailed");c.error(he)}},[c,e,h,a,p,l]),k=m.useCallback(()=>{v(!1)},[v]),E=m.useCallback(()=>{v(!0)},[v]),{contextMenuItems:M,handleMouseUp:R,copyToClipboard:I,referenceMessage:P}=VP({messageText:T,messageId:a,currentSessionId:e,onDelete:s,onRestoreChat:k,onRestoreFilesAndChat:E,cardRef:y}),L=m.useMemo(()=>o==="user"&&T.startsWith("/"),[o,T]),O=m.useMemo(()=>My(i,{onFixMermaid:j}),[i,j]),A=m.useMemo(()=>[wi,Uc],[]),$=m.useMemo(()=>[Wc],[]),W=m.useMemo(()=>[Fj(()=>I(T),l("chat.actions.copyMessage")),Lj(P,l("chat.actions.referenceMessage"))],[T,I,P,l]),{handleExecutePlan:F,handleRefinePlan:H,handleQuestionAnswer:D}=KP({currentSessionId:e,updateSession:u,sendMessage:x});return w==="plan"&&C&&o==="assistant"?r.jsx(ay,{plan:C,contextId:e||"",onExecute:F,onRefine:H,timestamp:S??void 0}):w==="question"&&_&&o==="assistant"?r.jsx(iy,{question:_,contextId:e||"",onAnswer:D,disabled:b||!1,timestamp:S??void 0}):fT(t)?r.jsx(qj,{taskList:t.taskList}):pT(t)?(He("[MessageCard]","[MessageCard] Rendering FileReferenceCard for message:",t.id,"paths:",t.paths),r.jsx(K,{justify:"flex-end",style:{width:"100%"},children:r.jsx(ly,{paths:t.paths,displayText:t.displayText,timestamp:S??void 0})})):r.jsxs(K,{vertical:!0,onContextMenu:U=>R(U),style:{width:"100%"},children:[r.jsx(lr,{menu:{items:M},trigger:["contextMenu"],children:r.jsx(te,{"data-testid":o==="assistant"?"assistant-message":"user-message",id:a?`message-${a}`:void 0,ref:y,style:{width:"100%",minWidth:"100%",maxWidth:nE(d),margin:"0 auto",background:o==="user"?"var(--lotus-message-user-bg)":o==="assistant"?"var(--lotus-message-assistant-bg)":i.colorBgContainer,backdropFilter:"blur(14px)",WebkitBackdropFilter:"blur(14px)",border:o==="user"?"1px solid var(--lotus-message-user-border)":"1px solid var(--lotus-glass-border-subtle)",borderRadius:i.borderRadiusLG,boxShadow:g?"var(--lotus-card-hover-shadow)":"var(--lotus-shadow-soft)",position:"relative",wordWrap:"break-word",overflowWrap:"break-word",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",transform:g?"translateY(-2px) scale(1.002)":"none",overflow:"hidden"},bodyStyle:{padding:i.paddingMD},onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),children:r.jsxs(q,{direction:"vertical",size:i.marginXS,style:{width:"100%",maxWidth:"100%"},children:[r.jsx(NP,{role:o,formattedTimestamp:S,token:i}),t.role==="user"&&t.images&&r.jsx(Rj,{images:t.images}),r.jsx(K,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:r.jsx(zP,{sessionId:e,message:t,messageText:T,isUserToolCall:L,formatUserToolCall:HP,markdownComponents:O,markdownPlugins:A,rehypePlugins:$})}),r.jsx($j,{isVisible:g,position:{bottom:i.paddingXS,right:i.paddingXS},buttons:W})]})})}),o==="assistant"&&w==="text"&&a&&r.jsx(oE,{messageId:a,isVisible:g})]})},Iy=m.memo(cE,(e,t)=>e.message===t.message&&e.messageType===t.messageType&&e.onDelete===t.onDelete);Iy.displayName="MessageCard";const{Text:qo}=le,{useToken:dE}=xe,uE=e=>({p:({children:t})=>r.jsx(qo,{style:{marginBottom:e.marginSM,display:"block"},children:t}),ol:({children:t})=>r.jsx("ol",{style:{marginBottom:e.marginSM,paddingLeft:20},children:t}),ul:({children:t})=>r.jsx("ul",{style:{marginBottom:e.marginSM,paddingLeft:20},children:t}),li:({children:t})=>r.jsx("li",{style:{marginBottom:e.marginXS},children:t}),code({className:t,children:s,inline:n,...o}){const a=/language-([^\s]+)/i.exec(t||""),i=a?a[1]:"",l=n??(!a&&!t),c=s?String(s).replace(/\n$/,""):"";return l?r.jsx(qo,{code:!0,className:t,...o,children:s}):c.trim()?i.toLowerCase()==="mermaid"?r.jsx(te,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto",marginBottom:e.marginSM},children:r.jsx("pre",{style:{margin:0,padding:e.paddingSM,background:e.colorBgContainer,borderRadius:e.borderRadiusSM,fontSize:"13px"},children:r.jsx("code",{children:c})})}):Cy(i,c,e,void 0):null},blockquote:({children:t})=>r.jsx(te,{size:"small",styles:{body:{padding:`${e.paddingXS}px ${e.padding}px`}},style:{borderLeft:`3px solid ${e.colorPrimary}`,background:e.colorPrimaryBg,margin:`${e.marginXS}px 0`,color:e.colorTextSecondary,fontStyle:"italic"},children:t}),a:({children:t,href:s})=>{const n=typeof s=="string"?s.trim():"";return n?r.jsx("a",{href:n,target:"_blank",rel:"noopener noreferrer",onClick:o=>{o.preventDefault(),jy(n)},style:{color:e.colorLink,textDecoration:"underline",overflowWrap:"anywhere"},children:t}):r.jsx(r.Fragment,{children:t})},table:({children:t})=>r.jsx(te,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${e.marginSM}px 0`},children:r.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${e.colorBorder}`},children:t})}),thead:({children:t})=>r.jsx("thead",{style:{backgroundColor:e.colorBgContainer},children:t}),tbody:({children:t})=>r.jsx("tbody",{children:t}),tr:({children:t})=>r.jsx("tr",{style:{borderBottom:`1px solid ${e.colorBorder}`},children:t}),th:({children:t})=>r.jsx("th",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,textAlign:"left",fontWeight:"bold",borderRight:`1px solid ${e.colorBorder}`},children:t}),td:({children:t})=>r.jsx("td",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,borderRight:`1px solid ${e.colorBorder}`},children:t}),input:({type:t,checked:s,disabled:n})=>t==="checkbox"?r.jsx("input",{type:"checkbox",checked:s,disabled:n,style:{marginRight:e.marginXS,accentColor:e.colorPrimary},readOnly:!0}):r.jsx("input",{type:t,checked:s,disabled:n})}),$y=m.memo(({sessionId:e})=>{const{token:t}=dE(),{t:s}=se(),n=`streaming-${e}`,o=`streaming-reasoning-${e}`,a=`streaming-status-${e}`,[i,l]=m.useState(()=>Fe.getLatest(n)??""),[c,d]=m.useState(()=>Fe.getLatest(o)??""),[u,h]=m.useState(()=>Fe.getLatest(a)??"");m.useEffect(()=>Fe.subscribeMessage(n,b=>{l(b??"")}),[n]),m.useEffect(()=>Fe.subscribeMessage(o,b=>{d(b??"")}),[o]),m.useEffect(()=>Fe.subscribeMessage(a,b=>{h(b??"")}),[a]);const p=s(u==="context_compacting"?"chat.messageCard.assistantCompactingContext":"chat.messageCard.assistantThinking"),y=m.useMemo(()=>[wi,Uc],[]),g=m.useMemo(()=>[Wc],[]),f=m.useMemo(()=>uE(t),[t]);return r.jsx(te,{"data-testid":"streaming-indicator",role:"status","aria-live":"polite","aria-busy":!0,"aria-label":"AI is responding",style:{width:"100%",minWidth:"100%",maxWidth:"800px",margin:"0 auto",background:"var(--lotus-message-streaming-bg)",backdropFilter:"blur(14px)",WebkitBackdropFilter:"blur(14px)",borderRadius:t.borderRadiusLG,boxShadow:"none",position:"relative",wordWrap:"break-word",overflowWrap:"break-word"},children:r.jsxs(q,{direction:"vertical",size:t.marginXS,style:{width:"100%",maxWidth:"100%"},children:[r.jsx(K,{align:"baseline",justify:"space-between",gap:t.marginXS,children:r.jsx(qo,{type:"secondary",strong:!0,style:{fontSize:t.fontSizeSM},children:s("chat.streaming.assistant")})}),r.jsxs(K,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:[c?r.jsx(js,{size:"small",defaultActiveKey:["reasoning"],style:{marginBottom:t.marginSM,background:t.colorBgContainer,borderColor:t.colorBorderSecondary},items:[{key:"reasoning",label:r.jsx(qo,{strong:!0,children:s("chat.messageCard.reasoning")}),children:r.jsx(us,{remarkPlugins:y,rehypePlugins:g,components:f,children:c})}]}):null,i?r.jsx(us,{remarkPlugins:y,rehypePlugins:g,components:f,children:i}):r.jsx(qo,{italic:!0,className:"thinking-shimmer",children:p}),r.jsx("span",{className:"blinking-cursor",style:{display:"inline-block",marginLeft:"0.2em",color:t.colorText}})]})]})})});$y.displayName="StreamingMessageCard";const{Text:Wt}=le,mE="chat-session-tool-collapse:",Fy=(e,t)=>`${mE}${e}:${t}`,El=(e,t)=>{if(typeof window>"u")return null;try{const s=window.localStorage.getItem(Fy(e,t));if(!s)return null;const n=JSON.parse(s);if(!n||typeof n!="object")return null;const o="isExpanded"in n&&typeof n.isExpanded=="boolean"?n.isExpanded:!0,a="expandedTools"in n&&Array.isArray(n.expandedTools)?n.expandedTools.filter(i=>typeof i=="string"):[];return{isExpanded:o,expandedTools:a}}catch{return null}},hE=(e,t,s)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Fy(e,t),JSON.stringify(s))}catch{}},Rl=e=>{var n,o,a;const t=((o=(n=e.call.toolCalls)==null?void 0:n[0])==null?void 0:o.toolCallId)||"tool-call-missing";return`${e.callMessageId||e.call.id||e.resultMessageId||((a=e.result)==null?void 0:a.id)||"tool-message-missing"}:${t}`},pE=e=>{var t,s;return((s=(t=e.call.toolCalls)==null?void 0:t[0])==null?void 0:s.toolCallId)||e.call.id},fE="synthetic-tool-call:",gE=e=>{var s,n,o,a;const t=new Set;return(s=e.callMessageId)!=null&&s.trim()?t.add(e.callMessageId.trim()):e.call.id&&!e.call.id.includes(":")&&!e.call.id.startsWith(fE)&&t.add(e.call.id),(n=e.resultMessageId)!=null&&n.trim()?t.add(e.resultMessageId.trim()):(a=(o=e.result)==null?void 0:o.id)!=null&&a.trim()&&t.add(e.result.id.trim()),Array.from(t)};function yE(e,t,s){return e.result?e.result.isError?{icon:r.jsx(Ci,{style:{color:t.colorError}}),color:t.colorError,text:s("components.toolSession.error")}:{icon:r.jsx(Ws,{style:{color:t.colorSuccess}}),color:t.colorSuccess,text:s("components.toolSession.done")}:{icon:r.jsx(ta,{spin:!0,style:{color:t.colorPrimary}}),color:t.colorPrimary,text:s("components.toolSession.running")}}function xE(e,t){const s=Nn(e);if(s)return`MCP ${s.serverId}: ${s.toolName}`;const n=(i,l)=>{const c=typeof i=="string"?i:String(i??"");return!c||c.length<=l?c:c.substring(0,l).trimEnd()+"…"},o={file_read:i=>`Reading: ${n(i.path||i.file_path||"file",35)}`,file_write:i=>`Writing: ${n(i.path||i.file_path||"file",35)}`,file_edit:i=>`Editing: ${n(i.path||i.file_path||"file",35)}`,bash:i=>`Executing: ${n(i.command,35)}`,grep:i=>`Searching: "${n(i.pattern,25)}"`,glob:i=>`Finding: "${i.pattern}"`,conclusion:i=>`Conclusion: ${n(i.conclusion||i.title||"",28)}`,read:i=>`Reading: ${i.file_path||"file"}`,write:i=>`Writing: ${i.file_path||"file"}`,edit:i=>`Editing: ${i.file_path||"file"}`,search:i=>`Searching: "${n(i.query||i.pattern,25)}"`,default:()=>`${e}`};return(o[e]||o.default)(t)}const bE=({tools:e,sessionId:t,defaultExpanded:s=!1,onDeleteMessageIds:n})=>{const{t:o}=se(),{token:a}=xe.useToken(),i=e.length===1,l=m.useMemo(()=>{var k,E,M,R;const T=e[0],j=(E=(k=T==null?void 0:T.call)==null?void 0:k.toolCalls)==null?void 0:E[0];return`${(T==null?void 0:T.callMessageId)||((M=T==null?void 0:T.call)==null?void 0:M.id)||(T==null?void 0:T.resultMessageId)||((R=T==null?void 0:T.result)==null?void 0:R.id)||"tool-message-missing"}:${(j==null?void 0:j.toolCallId)||"tool-call-missing"}`},[e]),c=m.useMemo(()=>{const T=e[0];return T?Rl(T):null},[e]),[d,u]=m.useState(()=>{const T=El(t,l);return T?T.isExpanded:s}),[h,p]=m.useState(()=>{const T=El(t,l);return T?new Set(T.expandedTools):new Set(s&&c?[c]:[])});m.useEffect(()=>{const T=El(t,l);if(T){u(T.isExpanded),p(new Set(T.expandedTools));return}u(s),p(new Set(s&&c?[c]:[]))},[s,c,t,l]),m.useEffect(()=>{const T=new Set(e.map(j=>Rl(j)));p(j=>{const v=new Set;let k=!1;return j.forEach(E=>{T.has(E)?v.add(E):k=!0}),!k&&v.size===j.size?j:v})},[e]),m.useEffect(()=>{hE(t,l,{isExpanded:d,expandedTools:Array.from(h)})},[t,l,d,h]);const{completedCount:y,pendingCount:g,hasErrors:f}=m.useMemo(()=>{let T=0,j=0,v=!1;return e.forEach(k=>{k.result?(T++,k.result.isError&&(v=!0)):j++}),{completedCount:T,pendingCount:j,hasErrors:v}},[e]),b=m.useMemo(()=>g>0?{color:"processing",text:o("components.toolSession.completedProgress",{completed:y,total:e.length})}:f?{color:"warning",text:o("components.toolSession.completedWithErrors",{completed:y})}:{color:"success",text:o("components.toolSession.completedOnly",{completed:y})},[y,g,f,e.length,o]),x=m.useMemo(()=>{let T=0,j=0,v=0;return e.forEach(k=>{var R,I;const E=(I=(R=k.result)==null?void 0:R.result)==null?void 0:I.result;if(!E)return;const M=kc(E);M&&(T+=M.added,j+=M.removed,v+=1)}),{added:T,removed:j,changedTools:v}},[e]),S=m.useMemo(()=>{var v,k,E;if(e.length!==1)return o("components.toolSession.title");const T=(E=(k=(v=e[0])==null?void 0:v.call)==null?void 0:k.toolCalls)==null?void 0:E[0];if(!T)return o("components.toolSession.title");const j=Nn(T.toolName);return j?`MCP ${j.serverId}: ${j.toolName}`:T.toolName||o("components.toolSession.title")},[e,o]),w=m.useMemo(()=>e.map((T,j)=>{const v=T.call.toolCalls[0];if(!v)return null;const k=yE(T,a,o),E=xE(v.toolName,v.parameters),M=Nn(v.toolName),R=T.result?kc(T.result.result.result):null,I=T.result?ma(T.result.result.result):null,P=gE(T);return{key:Rl(T),label:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:a.marginSM,width:"100%"},children:[r.jsxs("span",{style:{fontSize:a.fontSizeSM,color:a.colorTextTertiary,minWidth:20},children:[j+1,"."]}),r.jsx("span",{style:{flexShrink:0},children:k.icon}),M?r.jsxs(q,{size:"small",wrap:!1,children:[r.jsx(fe,{color:"purple",style:{marginInlineEnd:0},children:"MCP"}),r.jsx(Wt,{strong:!0,style:{fontSize:a.fontSizeSM},children:M.toolName}),r.jsx(Wt,{type:"secondary",style:{fontSize:a.fontSizeSM},children:r.jsx(Wt,{code:!0,style:{fontSize:a.fontSizeSM},children:M.serverId})})]}):r.jsx(Wt,{strong:!0,style:{fontSize:a.fontSizeSM,flexShrink:0},children:v.toolName}),r.jsx(Wt,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:a.fontSizeSM},children:E}),I&&r.jsx(Wt,{type:"secondary",ellipsis:!0,style:{maxWidth:180,fontSize:a.fontSizeSM},children:I.file_path.split(/[\\/]/).pop()||I.file_path}),R&&r.jsxs(q,{size:4,style:{marginLeft:a.marginXS},children:[r.jsxs(Wt,{style:{color:a.colorSuccess,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",R.added]}),r.jsxs(Wt,{style:{color:a.colorError,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",R.removed]})]}),n&&r.jsx(je,{title:P.length>0?o("components.toolSession.deleteMessage"):o("components.toolSession.noPersistedMessage"),children:r.jsx(B,{type:"text",size:"small",danger:!0,icon:r.jsx(cn,{}),"aria-label":o("components.toolSession.deleteMessage"),"data-testid":`delete-tool-message-${pE(T)}`,disabled:P.length===0,onClick:L=>{L.preventDefault(),L.stopPropagation(),P.length!==0&&n(P)}})})]}),children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:a.marginSM,children:[r.jsx(Fd,{toolName:v.toolName,parameters:v.parameters,toolCallId:v.toolCallId,streamingOutput:v.streamingOutput,defaultExpanded:!1}),T.result&&T.result.result.display_preference!=="Hidden"&&r.jsx($d,{content:T.result.result.result,toolName:v.toolName,status:T.result.isError?"error":"success",timestamp:T.result.createdAt,defaultCollapsed:!1})]}),style:{borderBottom:j<e.length-1?`1px solid ${a.colorBorderSecondary}`:void 0}}}).filter(T=>T!==null),[n,o,a,e]),C=r.jsx("div",{style:{padding:a.paddingSM},children:r.jsx(js,{ghost:!0,activeKey:Array.from(h),onChange:T=>{const j=new Set(Array.isArray(T)?T:T?[T]:[]);p(j)},items:w})}),_={backgroundColor:a.colorBgElevated,border:`1px solid ${a.colorBorder}`,borderRadius:a.borderRadiusLG,overflow:"hidden"};return i?r.jsx("div",{style:{width:"100%"},children:r.jsx("div",{style:_,children:C})}):r.jsxs("div",{style:_,children:[r.jsxs("div",{style:{padding:`${a.paddingSM}px ${a.paddingMD}px`,backgroundColor:a.colorBgContainer,borderBottom:d?`1px solid ${a.colorBorder}`:void 0,cursor:"pointer",display:"flex",alignItems:"center",gap:a.marginSM},onClick:()=>u(!d),children:[r.jsx(hr,{style:{color:a.colorPrimary}}),r.jsx(Wt,{strong:!0,style:{flex:1},children:S}),r.jsx(Hc,{count:e.length,style:{backgroundColor:a.colorPrimary}}),x.changedTools>0&&r.jsxs(q,{size:4,style:{marginInlineStart:a.marginXS},children:[r.jsxs(Wt,{style:{color:a.colorSuccess,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",x.added]}),r.jsxs(Wt,{style:{color:a.colorError,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",x.removed]})]}),r.jsx(Wt,{type:"secondary",style:{fontSize:a.fontSizeSM},children:b.text}),r.jsx("div",{style:{marginLeft:a.marginXS},children:d?r.jsx(Zt,{style:{color:a.colorTextSecondary}}):r.jsx(Bs,{style:{color:a.colorTextSecondary}})})]}),d&&C]})},Ly=m.memo(bE);Ly.displayName="ToolSessionCard";const{Content:vE}=nr,{Text:gh}=le,SE=24,wE=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};function Al(e){return"type"in e&&(e.type==="tool_session"||e.type==="compression_divider")?e.id:e.message.id}const _E=({currentChat:e,currentSessionId:t,convertRenderableEntry:s,handleDeleteMessage:n,handleDeleteToolMessages:o,handleMessagesScroll:a,hasSystemPrompt:i,messagesListRef:l,renderableMessages:c,rowGap:d,showMessagesView:u,screens:h,workflowDraftId:p,interactionState:y,padding:g,selectionMode:f,selectedMessageIds:b,selectableMessageIds:x,onToggleMessageSelection:S})=>{const{t:w}=se(),C=m.useRef(c);C.current=c;const _=m.useCallback(R=>{const I=C.current[R];return I?Al(I):String(R)},[]),T=fC({count:c.length,getScrollElement:()=>l.current,estimateSize:()=>120,overscan:5,gap:d,getItemKey:_}),j=(R,I)=>{if(!f)return null;const P=x.has(R);return r.jsx(Fp,{checked:b.has(R),disabled:!P,onChange:()=>{P&&S(R)},style:{marginTop:8,marginLeft:I==="flex-end"?8:0,marginRight:I==="flex-start"?8:0}})},v=R=>{const I=s(R);if(I.type==="compression_divider"){const P=wE(I.createdAt);return r.jsx("div",{role:"note","aria-label":w("chat.compression.timelineAria",{detail:I.label,time:P,defaultValue:"{{detail}} at {{time}}"}),style:{margin:"6px 0 10px 0",borderRadius:10,border:"1px solid rgba(250, 173, 20, 0.45)",background:"rgba(250, 173, 20, 0.12)",padding:h.xs?"8px 10px":"10px 12px"},children:r.jsxs(K,{align:"center",justify:"space-between",gap:8,wrap:!0,children:[r.jsxs(K,{align:"center",gap:8,wrap:!0,children:[r.jsx(fe,{color:"gold",icon:r.jsx($p,{}),children:w("chat.compression.tag","Context compressed")}),r.jsx(gh,{strong:!0,style:{fontSize:12},children:I.label})]}),r.jsx(gh,{type:"secondary",style:{fontSize:11},children:P})]})})}return I.type==="tool_session"?r.jsx(K,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:r.jsx("div",{id:`message-${I.id}`,style:{width:"100%",maxWidth:h.xs?"100%":"90%"},children:r.jsx(Ly,{tools:I.tools,sessionId:I.sessionId,createdAt:I.createdAt,defaultExpanded:!1,onDeleteMessageIds:t?o:void 0})})}):I.message.role==="system"?r.jsxs(K,{align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[j(I.message.id,"flex-start"),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsx(ty,{currentChat:e,message:I.message})})]}):r.jsxs(K,{justify:I.align,align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[I.align==="flex-start"&&j(I.message.id,I.align),r.jsx("div",{style:{width:I.message.role==="user"?"85%":"100%",maxWidth:h.xs?"100%":"90%"},children:r.jsx(Iy,{sessionId:t,message:I.message,messageType:I.messageType,onDelete:I.message.id===p?void 0:n})}),I.align==="flex-end"&&j(I.message.id,I.align)]})},k=(u||i)&&c.length>0,E=T.getVirtualItems(),M=c.length>SE;return r.jsxs(vE,{role:"log","aria-live":"polite","aria-label":"Chat messages",className:`chat-view-messages-list ${u?"visible":"hidden"}`,style:{flex:1,minHeight:0,padding:g,overflowY:"auto",opacity:u?1:0,scrollbarWidth:"none",msOverflowStyle:"none"},ref:l,onScroll:a,children:[k&&(M?r.jsx("div",{style:{position:"relative",width:"100%",height:T.getTotalSize()},children:E.map(R=>{const I=c[R.index];if(!I)return null;const P=Al(I);return r.jsx("div",{"data-chat-entry-id":P,"data-index":R.index,ref:T.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${R.start}px)`},children:r.jsx("div",{className:"messageEnter",children:v(I)})},R.key)})}):r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:d,width:"100%"},children:c.map(R=>{const I=Al(R);return r.jsx("div",{"data-chat-entry-id":I,className:"messageEnter",children:v(R)},I)})})),y.matches("THINKING")&&t&&r.jsx("div",{className:"streaming-card-enter",style:{paddingTop:d},children:r.jsx(K,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:r.jsx("div",{style:{width:"100%",maxWidth:h.xs?"100%":"90%"},children:r.jsx($y,{sessionId:t})})})})]})},{Text:Nr}=le,TE=e=>({pending:{icon:r.jsx(Us,{}),color:e.colorTextTertiary,textKey:"components.todoList.status.pending",tagColor:"default"},in_progress:{icon:r.jsx(Yc,{spin:!0}),color:e.colorPrimary,textKey:"components.todoList.status.inProgress",tagColor:"processing"},completed:{icon:r.jsx(Ws,{}),color:e.colorSuccess,textKey:"components.todoList.status.completed",tagColor:"success"},blocked:{icon:r.jsx(Ci,{}),color:e.colorError,textKey:"components.todoList.status.blocked",tagColor:"error"}}),kE=({sessionId:e,initialCollapsed:t=!0})=>{const{t:s}=se(),{token:n}=xe.useToken(),o=dt.useMemo(()=>TE(n),[n]),a=z(j=>j.chats.find(v=>v.id===e)),i=(a==null?void 0:a.kind)==="child"&&(a.parentSessionId||a.rootSessionId)||e,l=z(j=>j.taskLists[i]),c=z(j=>j.activeItems[i]),d=z(j=>j.evaluationStates[i]),[u,h]=m.useState(t),[p,y]=m.useState(!1),g=(d==null?void 0:d.isEvaluating)||!1,f=(d==null?void 0:d.reasoning)||null,b=l?{session_id:l.session_id,title:l.title,items:l.items,progress:{completed:l.items.filter(j=>j.status==="completed").length,total:l.items.length,percentage:l.items.length>0?Math.round(l.items.filter(j=>j.status==="completed").length/l.items.length*100):0}}:null;if(!b)return null;const x=()=>{p||h(!u)},S=j=>{j.stopPropagation(),y(!p),p||h(!1)},{title:w,items:C,progress:_}=b,T=_.percentage===100;return r.jsx(te,{size:"small",style:{marginBottom:16,borderRadius:8,boxShadow:g?`0 0 0 2px ${n.colorPrimaryBorder}`:"0 2px 8px rgba(0, 0, 0, 0.06)",opacity:u&&!p?.9:1},styles:{body:{padding:u?"12px 16px":16}},title:r.jsxs(q,{onClick:x,style:{cursor:"pointer",width:"100%"},children:[r.jsx(Hx,{style:{color:n.colorPrimary}}),r.jsx(Nr,{strong:!0,style:{fontSize:15},children:w||s("components.todoList.title")}),g&&r.jsx(fe,{icon:r.jsx(Yc,{spin:!0}),color:"processing",children:s("components.todoList.evaluating")}),!u&&_.total>0&&r.jsx(Hc,{count:`${_.completed}/${_.total}`,style:{backgroundColor:T?n.colorSuccess:n.colorPrimary}})]}),extra:r.jsxs(q,{children:[_.total>0&&u&&r.jsxs(Nr,{type:"secondary",style:{fontSize:13},children:[_.completed,"/",_.total,T&&r.jsx(Ws,{style:{color:n.colorSuccess,marginLeft:4}})]}),r.jsx(je,{title:s(p?"components.todoList.unpin":"components.todoList.pin"),children:r.jsx("span",{onClick:S,style:{cursor:"pointer",color:p?n.colorPrimary:n.colorTextSecondary,fontSize:16},children:p?r.jsx(Vl,{}):r.jsx(Za,{})})}),!p&&r.jsx("span",{onClick:x,style:{cursor:"pointer",color:n.colorTextSecondary,fontSize:12,transform:u?"rotate(-90deg)":void 0,transition:"transform 0.2s"},children:u?r.jsx(Bs,{}):r.jsx(Zt,{})})]}),children:!u&&r.jsxs(r.Fragment,{children:[f&&r.jsx(Ne,{icon:r.jsx(Xc,{}),message:s("components.todoList.llmEvaluation"),description:f,type:"info",showIcon:!0,style:{marginBottom:16}}),_.total>0&&r.jsx("div",{style:{marginBottom:16},children:r.jsx(Vc,{percent:_.percentage,size:"small",status:T?"success":"active",format:j=>r.jsxs(Nr,{type:"secondary",children:[j,"%"]})})}),r.jsx(Ge,{size:"small",dataSource:C,renderItem:j=>{const v=o[j.status],k=c===j.id,E=s(v.textKey);return r.jsx(Ge.Item,{style:{padding:"12px 0",borderLeft:k?`3px solid ${n.colorPrimary}`:"3px solid transparent",paddingLeft:k?12:15,backgroundColor:k?n.colorPrimaryBg:"transparent",borderRadius:4,marginBottom:4},children:r.jsx("div",{style:{width:"100%"},children:r.jsxs(q,{align:"start",style:{width:"100%"},children:[r.jsx(je,{title:E,children:r.jsx("span",{style:{color:v.color,fontSize:16},children:v.icon})}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsx(Nr,{style:{textDecoration:j.status==="completed"?"line-through":"none",color:j.status==="completed"?n.colorTextSecondary:n.colorText,fontWeight:k?500:400},children:j.description}),r.jsx("div",{style:{marginTop:4},children:r.jsxs(q,{size:8,wrap:!0,children:[r.jsx(fe,{color:v.tagColor,children:E}),j.tool_calls_count!==void 0&&j.tool_calls_count>0&&r.jsxs(fe,{icon:r.jsx(hr,{}),color:"processing",children:[j.tool_calls_count," ",s("components.todoList.tools")]}),j.depends_on.length>0&&r.jsx(je,{title:s("components.todoList.dependsOn",{deps:j.depends_on.join(", ")}),children:r.jsxs(fe,{icon:r.jsx(qx,{}),children:[j.depends_on.length," ",s("components.todoList.dependencies")]})})]})}),j.notes&&r.jsx(Nr,{type:"secondary",style:{display:"block",marginTop:6,fontSize:12,padding:"4px 8px",backgroundColor:n.colorFillQuaternary,borderRadius:4},children:j.notes})]})]})})})}})]})})},CE="_questionCard_15meh_1",jE="_questionHeader_15meh_8",ME="_headerLeft_15meh_27",PE="_questionIcon_15meh_35",EE="_questionText_15meh_40",RE="_collapseBtn_15meh_52",AE="_questionBody_15meh_57",IE="_optionsGroup_15meh_61",$E="_optionItem_15meh_65",FE="_customHint_15meh_81",LE="_questionFooter_15meh_93",Ut={questionCard:CE,questionHeader:jE,headerLeft:ME,questionIcon:PE,questionText:EE,collapseBtn:RE,questionBody:AE,optionsGroup:IE,optionItem:$E,customHint:FE,questionFooter:LE},{Text:Ia}=le,{useToken:OE}=xe,DE=e=>{const t=(e||"").replace(/\\r\\n/g,`
|
|
234
|
+
`).replace(/\\n/g,`
|
|
235
|
+
`).replace(/\r\n?/g,`
|
|
236
|
+
`).trim();return t?t.includes(`
|
|
237
|
+
`)?t:t.replace(/\s+(?=\d+[).]\s)/g,`
|
|
238
|
+
`).replace(/\s+(?=[一二三四五六七八九十]+[、.]\s)/g,`
|
|
239
|
+
`).replace(/\s+(?=[-*•]\s)/g,`
|
|
240
|
+
`):""},zE=({sessionId:e,onResponseSubmitted:t,onQuestionAppeared:s})=>{const{t:n}=se(),{token:o}=OE(),[a,i]=m.useState(null),[l,c]=m.useState(null),[d,u]=m.useState(!1),[h,p]=m.useState(!0),[y,g]=m.useState(!1),f=m.useRef(0),b=m.useRef(s);b.current=s;const x=z(F=>F.setSessionProcessing),S=z(F=>F.setPendingQuestionRespond),w=z(F=>F.clearPendingQuestionRespondForSession),C=vr(),_=z(F=>{var H;return e?(H=F.inputStates)==null?void 0:H[e]:void 0}),T=Rt(F=>F.currentProvider),j=Rt(F=>F.providerConfig),v=m.useMemo(()=>{var F;return(F=j.providers[T])==null?void 0:F.reasoning_effort},[j,T]),k=m.useMemo(()=>e?sd(e):void 0,[e]),E=(_==null?void 0:_.reasoningEffort)??k??v??"medium",M=z(F=>e?F.isSessionProcessing(e):!1),R=m.useCallback(async()=>{try{const F=await Se.get(`respond/${e}/pending`);F.has_pending_question?(i(F),f.current=0):(i(null),f.current+=1)}catch(F){if(F instanceof Error&&F.message.includes("404")){i(null),f.current+=1;return}console.error("Failed to fetch pending question:",F)}finally{p(!1)}},[e]);m.useEffect(()=>{f.current=0,p(!0)},[e]),m.useEffect(()=>{var F;a!=null&&a.has_pending_question?(c(null),S({sessionId:e,question:(a==null?void 0:a.question)||"",options:(a==null?void 0:a.options)||[],allowCustom:(a==null?void 0:a.allow_custom)??!0,toolCallId:(a==null?void 0:a.tool_call_id)??null}),g(!1),(F=b.current)==null||F.call(b)):w(e)},[a==null?void 0:a.tool_call_id,e,a==null?void 0:a.question,S,w]);const I=a!=null&&a.has_pending_question||M?3e3:15e3;m.useEffect(()=>{R();const F=setInterval(()=>{d||R()},I);return()=>clearInterval(F)},[R,d,I]),m.useEffect(()=>{if(typeof window>"u")return;const F=H=>{var Q;const U=((Q=H.detail)==null?void 0:Q.sessionId)??null;!U||U!==e||(i(null),c(null),f.current=0,w(e))};return window.addEventListener(ar,F),()=>{window.removeEventListener(ar,F)}},[e,w]);const P=m.useCallback(F=>{c(F)},[]);m.useEffect(()=>()=>{w(e)},[w,e]);const L=async()=>{if(!l||l==="custom"){pe.warning(n("components.questionDialog.selectOptionWarning"));return}u(!0);try{const F=C==null?void 0:C.trim(),H=await Se.post(`respond/${e}`,{response:l,model:F||void 0,reasoning_effort:E});pe.success(n("components.questionDialog.responseSubmitted")),i(null),c(null),f.current=0,typeof window<"u"&&window.dispatchEvent(new CustomEvent(ar,{detail:{sessionId:e}}));const D=H==null?void 0:H.auto_resume_status;["started","already_running"].includes(D||"")?e&&x(e,!0):D==="invalid_model"||D==="not_requested"?pe.error(n("components.questionDialog.noModelConfigured")):D==="error"&&console.error("[QuestionDialog] Failed to auto-resume agent execution"),t==null||t()}catch(F){console.error("Failed to submit response:",F),pe.error(F instanceof Error?F.message:n("components.questionDialog.submitFailed"))}finally{u(!1)}};if(h||!(a!=null&&a.has_pending_question))return null;const{question:O,options:A,allow_custom:$}=a,W=DE(O);return r.jsxs("div",{className:Ut.questionCard,style:{background:o.colorBgContainer,borderColor:o.colorBorderSecondary,border:`1px solid ${o.colorBorderSecondary}`},children:[r.jsxs("div",{className:Ut.questionHeader,"data-collapsed":y?"true":"false",onClick:()=>g(F=>!F),role:"button",tabIndex:0,onKeyDown:F=>{(F.key==="Enter"||F.key===" ")&&g(H=>!H)},children:[r.jsxs("span",{className:Ut.headerLeft,children:[r.jsx("span",{className:Ut.questionIcon,children:"🤔"}),r.jsx(Ia,{strong:!0,className:Ut.questionText,style:{color:o.colorPrimary,whiteSpace:"pre-wrap"},title:y?W:void 0,children:W})]}),r.jsx(B,{type:"text",size:"small",icon:y?r.jsx(Zt,{}):r.jsx(Kc,{}),className:Ut.collapseBtn,tabIndex:-1})]}),!y&&r.jsxs("div",{className:Ut.questionBody,children:[r.jsx(Gt.Group,{className:Ut.optionsGroup,value:l,onChange:F=>P(F.target.value),children:r.jsxs(q,{direction:"vertical",size:4,style:{width:"100%"},children:[A==null?void 0:A.map((F,H)=>r.jsx(Gt,{value:F,className:Ut.optionItem,children:r.jsx(Ia,{style:{color:o.colorText},children:F})},H)),$&&r.jsx(Gt,{value:"custom",className:Ut.optionItem,children:r.jsxs(q,{size:4,children:[r.jsx(pr,{}),r.jsx(Ia,{style:{color:o.colorText},children:n("components.questionDialog.otherTypeBelow")})]})})]})}),l==="custom"&&r.jsx("div",{className:Ut.customHint,children:r.jsx(Ia,{type:"secondary",style:{fontSize:12},children:n("components.questionDialog.customAnswerTip")})}),l&&l!=="custom"&&r.jsx("div",{className:Ut.questionFooter,children:r.jsx(B,{type:"primary",size:"small",onClick:L,loading:d,children:n("components.questionDialog.confirm")})})]})]})};function Oy(e){return typeof e.maxContextTokens=="number"&&e.maxContextTokens>0?e.maxContextTokens:e.budgetLimit>0?e.budgetLimit:0}function Dy(e){const t=Oy(e);return t===0?0:e.totalTokens/t*100}function NE(e){const t=Dy(e);return t>=90?"error":t>=70?"warning":t>=50?"success":"default"}function Br(e){return e.toLocaleString()}const BE=({usage:e,showDetails:t=!0,size:s="small",className:n=""})=>{const{t:o}=se(),a=Oy(e),i=Dy(e),l=h=>{const p=Math.round(h*10)/10;return Number.isInteger(p)?p.toFixed(0):p.toFixed(1)},c=NE(e),d=()=>i>=90?"var(--lotus-chart-danger)":i>=70?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",u=r.jsxs("div",{style:{minWidth:180,color:"var(--lotus-metric-text-strong)"},children:[r.jsx("div",{style:{marginBottom:4,fontWeight:"bold"},children:o("components.tokenUsage.title")}),r.jsxs("div",{style:{fontSize:12},children:[o("components.tokenUsage.contextWindow"),":"," ",Br(e.totalTokens)," / ",Br(a)," ",o("components.tokenUsage.tokens")]}),r.jsx("div",{style:{fontSize:12,color:"var(--lotus-metric-text-muted)"},children:o("components.tokenUsage.usedPercent",{value:i.toFixed(1)})}),t&&r.jsxs("div",{style:{marginTop:6,borderTop:"1px solid var(--lotus-metric-tooltip-border)",paddingTop:6,fontSize:11},children:[r.jsxs("div",{children:[o("components.tokenUsage.system"),": ",Br(e.systemTokens)]}),e.summaryTokens>0&&r.jsxs("div",{children:[o("components.tokenUsage.summary"),": ",Br(e.summaryTokens)]}),r.jsxs("div",{children:[o("components.tokenUsage.messages"),": ",Br(e.windowTokens)]}),typeof e.promptCachedToolOutputs=="number"&&e.promptCachedToolOutputs>0&&r.jsx("div",{style:{color:"var(--lotus-metric-text-muted)"},children:o("components.tokenUsage.cachedToolOutputs",{count:e.promptCachedToolOutputs,defaultValue:"Prompt cache: {{count}} tool outputs summarized"})})]})]});return r.jsx(je,{title:u,placement:"top",arrow:!0,children:r.jsxs(q,{className:`token-usage-display ${n}`,size:4,align:"center",style:{lineHeight:1},children:[r.jsx(Vc,{type:"line",percent:Math.min(i,100),size:{height:s==="small"?6:8,width:80},strokeColor:d(),showInfo:!1,style:{margin:0,lineHeight:1}}),r.jsxs("span",{style:{fontSize:s==="small"?11:12,color:c==="error"?"var(--lotus-chart-danger)":c==="warning"?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",whiteSpace:"nowrap",fontWeight:600},children:[l(i),"%"]})]})})},An=class An{static getInstance(){return An.instance||(An.instance=new An),An.instance}parseUserCommand(t){He("[ToolService]",`[ToolService] parseUserCommand: Parsing content: "${t}"`);const s=t.trim();if(!s.startsWith("/"))return He("[ToolService]",'[ToolService] parseUserCommand: Content does not start with "/", not a tool command.'),null;const n=s.indexOf(" ");let o,a;if(n===-1?(o=s.substring(1),a=""):(o=s.substring(1,n),a=s.substring(n+1).trim()),o){const i={tool_name:o,user_description:a};return He("[ToolService]","[ToolService] parseUserCommand: Successfully parsed command:",i),i}return He("[ToolService]","[ToolService] parseUserCommand: Failed to parse tool name from content."),null}parseAIResponseToToolCall(t){return this.parseUserCommand(t)}async executeTool(t){He("[ToolService]","[ToolService] executeTool: Attempting to execute tool via HTTP with request:",t);try{const s=await Te.post("tools/execute",t),n=JSON.parse(s.result);return He("[ToolService]","[ToolService] executeTool: Parsed structured result:",n),n}catch(s){throw console.error("[ToolService] executeTool: HTTP tool execution failed:",s),s instanceof Ln?new Error(`Workflow execution failed: ${s.message}`):s}}};We(An,"instance");let zc=An;const WE=new zc,{Text:nn}=le,{useToken:zy}=xe,UE="chat-session-sub-sessions-collapsed:",qE=3,HE=600,Qa=e=>{const t=(e||"").trim().toLowerCase();return t?t==="started"||t==="already_running"?"running":t==="success"||t==="done"?"completed":t==="canceled"?"cancelled":t==="queued"||t==="created"?"pending":t:"pending"},YE=(e,t)=>{if(t&&t.trim())return t;if(e.isRunning)return"running";if(e.lastRunStatus&&e.lastRunStatus.trim())return e.lastRunStatus;const s=e.messageCount??0;return s>2?"completed":(s>0,"pending")},Ny=e=>`${UE}${e}`,Il=e=>{if(typeof window>"u")return!1;try{const t=window.localStorage.getItem(Ny(e));return t==="1"?!0:t==="0"?!1:null}catch{return null}},XE=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Ny(e),t?"1":"0")}catch{}},VE=({parentSessionId:e})=>{const{t}=se(),{token:s}=zy(),n=vr(),[o,a]=m.useState(()=>Il(e)??!1),[i,l]=m.useState(null),[c,d]=m.useState(null),[u,h]=m.useState(null),p=z(P=>P.subSessionsByParent),y=z(P=>P.chats),g=z(P=>P.loadChatHistory),f=z(P=>P.refreshChats),b=z(P=>P.setSessionProcessing),x=z(P=>P.pinSession),S=z(P=>P.unpinSession),w=z(P=>P.deleteSession),C=z(P=>P.upsertSubSessionProgress),_=z(P=>P.clearSubSessionProgress),T=m.useMemo(()=>{const P=p[e]||{};return Object.entries(P).map(([L,O])=>({childSessionId:L,...O}))},[e,p]),j=m.useMemo(()=>y.filter(P=>P.kind==="child"&&P.parentSessionId===e).sort((P,L)=>{const O=Date.parse(P.updatedAt||"")||0;return(Date.parse(L.updatedAt||"")||0)-O}),[y,e]),v=m.useMemo(()=>{const P=new Map(T.map(O=>[O.childSessionId,O])),L=[];for(const O of j){const A=P.get(O.id);L.push({childSessionId:O.id,title:(A==null?void 0:A.title)||O.title,status:Qa(YE(O,A==null?void 0:A.status)),error:(A==null?void 0:A.error)||O.lastRunError,lastHeartbeatAt:A==null?void 0:A.lastHeartbeatAt,lastEventAt:A==null?void 0:A.lastEventAt,outputPreview:A==null?void 0:A.outputPreview,pinned:O.pinned,updatedAt:O.updatedAt,isRunning:O.isRunning,messageCount:O.messageCount,lastRunStatus:O.lastRunStatus,lastRunError:O.lastRunError}),P.delete(O.id)}for(const O of P.values())L.push({childSessionId:O.childSessionId,title:O.title,status:Qa(O.status),error:O.error,lastHeartbeatAt:O.lastHeartbeatAt,lastEventAt:O.lastEventAt,outputPreview:O.outputPreview});return L},[j,T]);m.useEffect(()=>{a(Il(e)??!1)},[e]),m.useEffect(()=>{Il(e)===null&&a(v.length>qE)},[e,v.length]);const k=m.useCallback(()=>{a(P=>{const L=!P;return XE(e,L),L})},[e]),E=m.useCallback(P=>P instanceof Error&&P.message.trim()?P.message:"Failed to run child session",[]),M=m.useCallback(async(P,L="regenerate")=>{if(!n){C(e,P,{status:"error",error:"No model configured. Please select a model first.",lastEventAt:new Date().toISOString()});return}l(P),C(e,P,{status:"running",error:void 0,lastEventAt:new Date().toISOString()}),b(P,!0);try{const O=L==="error_retry"?"error_retry":"after_last_user",A=await Ko.truncateSessionMessages(P,{mode:O});(L==="regenerate"||(A.messages_removed??0)>0)&&await g(P,{mode:"replace"});const $=await Ko.execute(P,n);if($.status==="started"||$.status==="already_running")return;if($.status==="completed"){b(P,!1),C(e,P,{status:"completed",error:void 0,lastEventAt:new Date().toISOString()}),await f();return}throw new Error(`Execute failed: ${$.status}`)}catch(O){b(P,!1),C(e,P,{status:"error",error:E(O),lastEventAt:new Date().toISOString()})}finally{l(O=>O===P?null:O)}},[n,g,e,f,b,E,C]),R=m.useCallback(async P=>{const L=typeof window<"u"?window.prompt.bind(window):null;if(!L)return;const O=L("Send a follow-up message to this child session:","Continue from where you left off.");if(O===null)return;const A=O.trim();if(!A){C(e,P,{status:"error",error:"Follow-up message cannot be empty.",lastEventAt:new Date().toISOString()});return}d(P),C(e,P,{status:"running",error:void 0,lastEventAt:new Date().toISOString()}),b(P,!0);try{const $=await WE.executeTool({tool_name:"sub_session_manager",session_id:e,parameters:[{name:"action",value:"send_message"},{name:"child_session_id",value:P},{name:"message",value:A},{name:"auto_run",value:"true"}]});if(!$.success)throw new Error($.result||"Follow-up failed");let W="running";try{JSON.parse($.result).status==="pending"&&(W="pending")}catch{W="running"}C(e,P,{status:W,error:void 0,lastEventAt:new Date().toISOString()}),await f()}catch($){b(P,!1),C(e,P,{status:"error",error:$ instanceof Error&&$.message.trim()?$.message:"Failed to continue child session",lastEventAt:new Date().toISOString()})}finally{d($=>$===P?null:$)}},[e,f,b,C]),I=m.useCallback(async P=>{h(P);try{await w(P),_(e,P)}finally{h(L=>L===P?null:L)}},[_,w,e]);return v.length===0?null:r.jsxs(te,{size:"small",className:"lotus-settings-card",style:{marginBottom:s.marginMD},"data-testid":"sub-sessions-panel",title:r.jsxs(nn,{strong:!0,children:[t("chat.subSessions.title")," ",r.jsxs(nn,{type:"secondary",children:["(",v.length,")"]})]}),extra:r.jsx(B,{type:"text",size:"small",icon:o?r.jsx(Zt,{}):r.jsx(Kc,{}),onClick:k,"data-testid":"sub-sessions-toggle",children:t(o?"chat.subSessions.expand":"chat.subSessions.collapse")}),children:[o?r.jsx(nn,{type:"secondary","data-testid":"sub-sessions-collapsed-hint",children:t("chat.subSessions.hiddenHint",{count:v.length})}):r.jsx(K,{vertical:!0,gap:s.marginSM,"data-testid":"sub-sessions-list",style:{maxHeight:`${HE}px`,overflowY:"auto",paddingRight:s.paddingXS},children:v.map(P=>{const L=Qa(P.status),O=L==="running",A=i===P.childSessionId,$=c===P.childSessionId,W=u===P.childSessionId,F=A||$||W;return r.jsxs(K,{align:"flex-start",justify:"space-between",gap:s.marginSM,className:"lotus-settings-list-item",style:{padding:s.paddingSM,borderRadius:s.borderRadiusSM},children:[r.jsxs(K,{vertical:!0,style:{flex:1,minWidth:0},children:[r.jsxs(K,{align:"center",gap:s.marginXS,style:{minWidth:0},children:[r.jsx(nn,{strong:!0,ellipsis:!0,style:{minWidth:0},children:P.title||"Child Session"}),r.jsx(fe,{color:L==="running"?"processing":L==="completed"?"success":L==="error"||L==="failed"?"error":L==="cancelled"?"warning":"default",style:{marginInlineEnd:0,flex:"0 0 auto"},children:L}),P.pinned?r.jsx(fe,{color:"warning",style:{marginInlineEnd:0,flex:"0 0 auto"},children:"Pinned"}):null]}),r.jsxs(nn,{type:"secondary",style:{fontSize:12,marginTop:2},children:[P.childSessionId.slice(0,8),P.updatedAt?` • ${P.updatedAt}`:"",P.lastHeartbeatAt?` • heartbeat: ${P.lastHeartbeatAt}`:""]}),P.outputPreview?r.jsx(nn,{type:"secondary",style:{marginTop:s.marginXS,fontSize:13},ellipsis:!0,children:P.outputPreview}):null,P.error?r.jsx(nn,{type:"danger",style:{marginTop:s.marginXS},children:P.error}):null]}),r.jsxs(K,{gap:8,children:[r.jsx(B,{size:"small",disabled:F,onClick:()=>{Di(P.childSessionId),g(P.childSessionId)},children:t("chat.subSessions.open")}),r.jsx(B,{size:"small",loading:$,disabled:W||A||O,"data-testid":`sub-session-continue-${P.childSessionId}`,onClick:()=>{R(P.childSessionId)},children:t("chat.subSessions.continue")}),r.jsx(lr,{trigger:["click"],menu:{items:[{key:"regenerate",label:t("chat.actions.regenerate")},{key:"error_retry",label:t("chat.actions.retryFailed")}],onClick:({key:H})=>{M(P.childSessionId,H)}},disabled:W||O||$,children:r.jsx(B,{size:"small",loading:A,disabled:W||O||$,"data-testid":`sub-session-retry-${P.childSessionId}`,children:t("chat.subSessions.retry")})}),typeof P.pinned=="boolean"?r.jsx(B,{size:"small",disabled:F,onClick:()=>{P.pinned?S(P.childSessionId):x(P.childSessionId)},children:P.pinned?t("chat.actions.unpin"):t("chat.actions.pin")}):null,r.jsx(B,{danger:!0,size:"small",loading:W,disabled:A,"data-testid":`sub-session-delete-${P.childSessionId}`,onClick:()=>{I(P.childSessionId)},children:t("common.delete")})]})]},P.childSessionId)})}),!o&&v.length>1&&r.jsx(KE,{items:v})]})},KE=({items:e})=>{const{token:t}=zy(),s=e.reduce((o,a)=>{const i=Qa(a.status);return i==="completed"?o.completed++:i==="running"?o.running++:i==="error"||i==="failed"?o.error++:o.pending++,o},{completed:0,running:0,error:0,pending:0}),n=[];return s.completed>0&&n.push(`${s.completed} completed`),s.running>0&&n.push(`${s.running} running`),s.pending>0&&n.push(`${s.pending} pending`),s.error>0&&n.push(`${s.error} failed`),n.length===0?null:r.jsx(nn,{type:"secondary",style:{fontSize:11,marginTop:t.marginXS,display:"block"},children:n.join(" · ")})},{useToken:GE}=xe,JE=e=>{const t=e.replace(/\/$/,"").split("/").filter(Boolean);return t.length<=2?e:`~/${t.slice(-2).join("/")}`},QE=({sessionId:e})=>{const{t}=se(),{token:s}=GE(),n=z(xr(e)),o=z(u=>u.systemPrompts),a=n==null?void 0:n.config.workspacePath,i=n==null?void 0:n.config.systemPromptId,l=m.useMemo(()=>{if(!i)return null;const u=o.find(h=>h.id===i);return(u==null?void 0:u.name)||i},[i,o]),c=m.useMemo(()=>n!=null&&n.messages?n.messages.filter(u=>u.role==="user"&&"type"in u&&u.type==="file_reference").length:0,[n==null?void 0:n.messages]);return!n||!(a||l||c>0)?null:r.jsx("div",{className:"lotus-context-bar",style:{borderBottomColor:s.colorBorderSecondary,backgroundColor:s.colorBgContainer},children:r.jsxs(K,{align:"center",gap:6,wrap:"wrap",className:"lotus-context-bar__content",children:[a&&r.jsx(je,{title:a,children:r.jsx(fe,{className:"lotus-context-bar__tag",icon:r.jsx(Yo,{}),bordered:!1,children:JE(a)})}),c>0&&r.jsx(je,{title:t("chat.contextBar.fileRefsTooltip",{count:c,defaultValue:"{{count}} file reference(s) in this session"}),children:r.jsxs(fe,{className:"lotus-context-bar__tag",icon:r.jsx(Yx,{}),bordered:!1,children:[c," ",t("chat.contextBar.files","files")]})}),l&&r.jsx(je,{title:t("chat.contextBar.promptTooltip",{name:l,defaultValue:"System prompt: {{name}}"}),children:r.jsx(fe,{className:"lotus-context-bar__tag",icon:r.jsx(ki,{}),bordered:!1,children:l})})]})})},ZE=new Set(["Write","Edit","apply_patch","NotebookEdit"]),e1=e=>{const t=e.match(/(?:file_path|Wrote file|Edited file)[:\s]*["']?([^\s"',]+)/i);if(t){const s=t[1];return s.split("/").pop()||s}return null},t1=(e,t)=>{const s=t-e;if(s<0)return"";const n=Math.floor(s/1e3);if(n<60)return`${n}s`;const o=Math.floor(n/60);return o<60?`${o}m ${n%60}s`:`${Math.floor(o/60)}h ${o%60}m`},s1=e=>{var h,p;let t=0,s=0,n=0,o=0,a=!1,i=0,l="";const c=new Set;let d=0,u=0;for(const y of e){const g=y.createdAt?new Date(y.createdAt).getTime():0;if(g>0&&(d===0||g<d)&&(d=g),g>u&&(u=g),y.isCompressed){a=!0,i++;continue}if(y.role==="user"&&!("type"in y&&y.type==="file_reference")&&t++,y.role==="assistant"){if("type"in y&&y.type==="tool_call"&&(n+=((h=y.toolCalls)==null?void 0:h.length)??0),"type"in y&&y.type==="tool_result"){const f=y;if(f.isError&&o++,ZE.has(f.toolName)){const b=e1(((p=f.result)==null?void 0:p.result)??"");b&&c.add(b)}}if("type"in y&&y.type==="text"){s++;const f=y.content||"";f.length>0&&f.length>30&&(l=f.slice(0,300))}}}return{messageCount:e.length,userMessageCount:t,assistantMessageCount:s,toolCallCount:n,toolErrorCount:o,fileChanges:Array.from(c).slice(0,10),lastAssistantExcerpt:l,hasCompression:a,compressionCount:i,duration:d>0&&u>d?t1(d,u):""}},n1=({sessionId:e})=>{const{t}=se(),{token:s}=xe.useToken(),[n,o]=m.useState(!1),a=z(xr(e)),i=a==null?void 0:a.messages,l=m.useMemo(()=>!i||i.length===0?null:s1(i),[i]);if(!l||l.messageCount<3)return null;const c=l.fileChanges.length>0,d=l.lastAssistantExcerpt.length>0;return r.jsxs("div",{className:"lotus-session-summary",style:{borderColor:s.colorBorderSecondary,background:`${s.colorBgElevated}`},children:[r.jsxs("div",{className:"lotus-session-summary-header",onClick:()=>o(u=>!u),role:"button",tabIndex:0,onKeyDown:u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),o(h=>!h))},"aria-expanded":n,children:[r.jsx("span",{className:"lotus-session-summary-header-icon",style:{color:s.colorPrimary},children:r.jsx(Xx,{})}),r.jsx("span",{className:"lotus-session-summary-header-title",style:{color:s.colorText},children:t("sessionSummary.title","Session Summary")}),!n&&r.jsxs("span",{className:"lotus-session-summary-stats",children:[r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(Xo,{className:"lotus-session-summary-stat-icon"}),r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.messageCount})]}),l.toolCallCount>0&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(qd,{className:"lotus-session-summary-stat-icon"}),r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolCallCount})]}),c&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(dr,{className:"lotus-session-summary-stat-icon"}),r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.fileChanges.length})]})]}),r.jsx("span",{className:`lotus-session-summary-toggle ${n?"is-expanded":""}`,style:{color:s.colorTextTertiary},children:r.jsx(Zt,{})})]}),n&&r.jsxs("div",{className:"lotus-session-summary-body",children:[r.jsxs("div",{className:"lotus-session-summary-stats",children:[r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(Xo,{className:"lotus-session-summary-stat-icon"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.messageCount})," ",t("sessionSummary.messages","messages")]})]}),r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx("span",{className:"lotus-session-summary-stat-icon",children:"👤"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.userMessageCount})," ",t("sessionSummary.userTurns","user")]})]}),r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx("span",{className:"lotus-session-summary-stat-icon",children:"🤖"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.assistantMessageCount})," ",t("sessionSummary.assistantTurns","assistant")]})]}),l.toolCallCount>0&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(qd,{className:"lotus-session-summary-stat-icon"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolCallCount})," ",t("sessionSummary.toolCalls","tool calls")]})]}),l.toolErrorCount>0&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:"#ff4d4f"},children:[r.jsx(gr,{className:"lotus-session-summary-stat-icon"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolErrorCount})," ",t("sessionSummary.errors","errors")]})]}),l.duration&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(Us,{className:"lotus-session-summary-stat-icon"}),r.jsx("span",{children:l.duration})]}),l.hasCompression&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(ki,{className:"lotus-session-summary-stat-icon"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.compressionCount})," ",t("sessionSummary.compressions","compressions")]})]})]}),c&&r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:11,fontWeight:600,color:s.colorTextSecondary,marginBottom:4,textTransform:"uppercase",letterSpacing:.3},children:t("sessionSummary.filesChanged","Files Changed")}),r.jsx("div",{className:"lotus-session-summary-files",children:l.fileChanges.map(u=>r.jsx(je,{title:u,children:r.jsxs(fe,{bordered:!1,className:"lotus-session-summary-file-tag",children:[r.jsx(dr,{style:{marginRight:4}}),u]})},u))})]}),d&&r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:11,fontWeight:600,color:s.colorTextSecondary,marginBottom:4,textTransform:"uppercase",letterSpacing:.3},children:t("sessionSummary.lastResponse","Latest Response")}),r.jsx("div",{className:"lotus-session-summary-conclusion",style:{color:s.colorTextSecondary},children:l.lastAssistantExcerpt})]})]})]})},By="chat_scroll_anchors_v1";function r1(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 Wy(){try{const e=localStorage.getItem(By);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const s={};for(const[n,o]of Object.entries(t))r1(o)&&(s[n]=o);return s}catch{return{}}}function o1(e){try{localStorage.setItem(By,JSON.stringify(e))}catch(t){console.warn("[ScrollAnchor] Failed to write:",t)}}function a1(e){return Wy()[e]??null}function i1(e,t){const s=Wy();s[e]=t,o1(s)}const $l=1,l1=3,c1=2e3;function d1(e,t){const s=Math.max(0,e.scrollHeight-e.clientHeight);return Math.min(Math.max(0,t),s)}function u1(e){const{scrollEl:t,getAnchorElement:s,offsetPx:n,isCancelled:o}=e;return new Promise(a=>{const i=performance.now();let l=0,c=-1,d=Number.NaN;const u=()=>{if(o()){a();return}const h=s();if(!h){requestAnimationFrame(u);return}const p=t.getBoundingClientRect(),g=h.getBoundingClientRect().top-p.top,f=d1(t,t.scrollTop+(g-n));if(Math.abs(t.scrollTop-f)>$l)t.scrollTop=f,l=0;else{const x=Number.isFinite(d)?Math.abs(f-d)<=$l:!1,S=Math.abs(t.scrollTop-c)<=$l;l=x&&S?l+1:0}d=f,c=t.scrollTop;const b=performance.now()-i>c1;if(l>=l1||b){a();return}requestAnimationFrame(u)};requestAnimationFrame(u)})}const m1=300,h1=.5;function p1(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 Uy(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 yh(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function f1(e,t){const s=yh(e.createdAt);if(s!=null){let n=null,o=Number.POSITIVE_INFINITY;for(let a=0;a<t.length;a++){const i=yh(Uy(t[a]));if(i==null)continue;const l=Math.abs(i-s);l<o&&(o=l,n=a)}if(n!=null)return n}if(typeof e.indexHint=="number"){const n=Math.max(0,Math.min(t.length-1,e.indexHint));return Number.isFinite(n)?n:null}return null}function Od(e){return Array.from(e.querySelectorAll("[data-chat-entry-id]"))}function g1(e,t){const s=Od(e);for(const n of s)if(n.dataset.chatEntryId===t)return n;return null}function y1(e,t){const s=Od(e);if(s.length===0)return null;const n=Math.max(0,Math.min(s.length-1,t));return s[n]??null}function x1(e){const t=Od(e);if(t.length===0)return null;const s=e.getBoundingClientRect().top;for(const n of t)if(n.getBoundingClientRect().bottom>s)return n;return t[t.length-1]??null}function b1(e){const{currentSessionId:t,messagesListRef:s,renderableMessages:n}=e,o=m.useRef(new Set),a=m.useRef(!1),i=m.useRef(0),l=m.useRef(null),c=m.useRef(null),d=m.useRef(!1);m.useEffect(()=>{const g=s.current;if(!g)return;const f=()=>{d.current=!0};return g.addEventListener("wheel",f,{passive:!0}),g.addEventListener("touchmove",f,{passive:!0}),g.addEventListener("pointerdown",f),()=>{g.removeEventListener("wheel",f),g.removeEventListener("touchmove",f),g.removeEventListener("pointerdown",f)}},[s]);const u=m.useMemo(()=>{const g=new Map;for(let f=0;f<n.length;f++){const b=p1(n[f]);b&&g.set(b,f)}return g},[n]),h=m.useCallback(()=>{const g=s.current;if(!g||n.length===0)return null;const f=x1(g);if(!f)return null;const b=f.dataset.chatEntryId;if(!b)return null;const x=g.getBoundingClientRect(),S=f.getBoundingClientRect(),w=u.get(b),C=typeof w=="number"?n[w]:void 0;return{v:1,anchorId:b,offsetPx:S.top-x.top,ts:Date.now(),indexHint:w,createdAt:C?Uy(C):void 0}},[u,s,n]),p=m.useCallback(g=>{if(a.current)return;const f=h();if(!f)return;const b=c.current;b&&b.anchorId===f.anchorId&&Math.abs(b.offsetPx-f.offsetPx)<=h1||(i1(g,f),c.current=f)},[h]),y=m.useCallback(g=>{if(!t||a.current)return;l.current&&clearTimeout(l.current);const f=t;l.current=setTimeout(()=>{p(f)},m1)},[t,p]);return m.useEffect(()=>{const g=t;return()=>{g&&(l.current&&(clearTimeout(l.current),l.current=null),p(g))}},[t,p]),m.useLayoutEffect(()=>{if(!t)return;const g=s.current;if(!g||n.length===0||o.current.has(t))return;const f=a1(t);if(!f){o.current.add(t);return}const b=u.get(f.anchorId),x=typeof b=="number"?b:f1(f,n);if(x==null){o.current.add(t);return}l.current&&(clearTimeout(l.current),l.current=null);const S=++i.current;a.current=!0,d.current=!1,g.style.overflowAnchor="none";const w=()=>i.current!==S||d.current;return u1({scrollEl:g,getAnchorElement:()=>g1(g,f.anchorId)??y1(g,x),offsetPx:f.offsetPx,isCancelled:w}).finally(()=>{i.current===S&&(a.current=!1,o.current.add(t),g.style.overflowAnchor="",p(t))}),()=>{i.current===S&&i.current++}},[t,u,n,n.length,s,p]),{handleScroll:y}}const xh=2,bh=6,v1=({currentSessionId:e,interactionState:t,messagesListRef:s,renderableMessages:n})=>{const[o,a]=m.useState(!1),[i,l]=m.useState(!1),c=m.useRef(!1),d=m.useRef(!0),{handleScroll:u}=b1({currentSessionId:e,messagesListRef:s,renderableMessages:n}),h=m.useCallback(b=>{const x=s.current;if(!x)return;if(n.length===0){a(!1),l(!1);return}const S=x.scrollHeight-x.scrollTop-x.clientHeight,w=x.scrollTop,C=150,_=150,T=S<C,j=w<_;a(!T),l(!j&&n.length>3),S>C*2?c.current=!0:T&&(c.current=!1),u(b)},[s,n.length,u]),p=m.useCallback(()=>{if(!s.current||n.length===0)return;let x=0,S=-1;const w=()=>{const C=s.current;if(!C)return;const _=Math.max(0,C.scrollHeight-C.clientHeight),T=Math.max(0,C.scrollHeight-C.scrollTop-C.clientHeight),j=C.scrollHeight!==S,v=T>xh||j||x===0;v&&C.scrollTo({top:_,behavior:x===0?"smooth":"auto"}),S=C.scrollHeight,x+=1,x<bh&&v&&requestAnimationFrame(w)};requestAnimationFrame(w)},[s,n.length]),y=m.useCallback(()=>{if(!s.current)return;let x=0;const S=()=>{const w=s.current;if(!w)return;const C=w.scrollTop>xh||x===0;C&&w.scrollTo({top:0,behavior:"auto"}),x+=1,x<bh&&C&&requestAnimationFrame(S)};requestAnimationFrame(S)},[s]),g=m.useCallback(()=>{c.current=!1},[]);m.useEffect(()=>{const b=x=>{var E,M;const w=(E=x.detail)==null?void 0:E.messageId;if(!w){console.error("No messageId provided for navigation");return}const C=n.findIndex(R=>"message"in R&&R.message?R.message.id===w:"id"in R?R.id===w:!1);if(C===-1){console.warn("Message not found for navigation:",w);return}const _=n[C],T=_&&"message"in _?_.message.id:_&&"id"in _?_.id:w,j=document.getElementById(`message-${T}`),v=Array.from(((M=s.current)==null?void 0:M.querySelectorAll("[data-chat-entry-id]"))||[]),k=j||v.find(R=>R.dataset.chatEntryId===T);if(!k){console.warn("Message element not found for navigation:",w);return}k.scrollIntoView({behavior:"smooth",block:"center"}),k.classList.add("highlight-message"),setTimeout(()=>{k.classList.remove("highlight-message")},2e3)};return window.addEventListener("navigate-to-message",b),()=>{window.removeEventListener("navigate-to-message",b)}},[s,n]);const f=m.useRef(t.value);return m.useEffect(()=>{const b=t.value;f.current==="IDLE"&&b==="THINKING"&&(g(),p()),f.current=b},[t.value,g,p]),m.useEffect(()=>Fe.subscribe(b=>{b.sessionId===e&&(c.current||b.content&&p())}),[e,p]),m.useEffect(()=>{!c.current&&n.length>0&&!d.current&&p(),d.current=!1},[n.length,p]),m.useEffect(()=>{if(!s.current){a(!1),l(!1);return}if(n.length===0){a(!1),l(!1);return}const x=()=>{const w=s.current;if(!w)return;const C=w.scrollHeight-w.scrollTop-w.clientHeight,_=w.scrollTop,T=150,j=150,v=C<T,k=_<j;a(!v),l(!k&&n.length>3)};x();let S=requestAnimationFrame(()=>{x(),S=requestAnimationFrame(x)});return()=>cancelAnimationFrame(S)},[s,n.length,e]),m.useEffect(()=>{d.current=!0,c.current=!1},[e]),{handleMessagesScroll:h,resetUserScroll:g,scrollToBottom:p,scrollToTop:y,showScrollToBottom:o,showScrollToTop:i}};function S1(e){return"type"in e&&e.type==="tool_session"}function w1(e){return"type"in e&&e.type==="compression_divider"}const vh=e=>{const t=Date.parse(e||"");return Number.isFinite(t)?t:Number.MAX_SAFE_INTEGER},_1=e=>"type"in e?e.createdAt:e.message.createdAt,T1=e=>!("type"in e)&&e.message.role==="system";function k1(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_call"}function C1(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_result"}const Sh=e=>(e??"").trim().toLowerCase()==="conclusion",j1=e=>{const t=(e??"").trim().toLowerCase();return t==="conclusion_with_options"||t==="exitplanmode"||t==="request_permissions"},M1=e=>{var t,s,n;return((s=(t=e.call.toolCalls)==null?void 0:t[0])==null?void 0:s.toolCallId)||((n=e.result)==null?void 0:n.toolCallId)||"tool-call-missing"},P1=(e,t)=>{var s;return e.call.id||e.callMessageId||e.resultMessageId||((s=e.result)==null?void 0:s.id)||`tool-message-missing-${t}`},E1=(e,t)=>`tool-session-${P1(e,t)}:${M1(e)}`;function R1(e){const t=[],s=new Map,n=new Set,o=(i,l)=>{const c=s.get(i)||[];c.push(l),s.set(i,c)},a=i=>{const l=s.get(i);if(!l||l.length===0)return;let c;for(;l.length>0&&!c;){const d=l.shift();d&&!d.result&&(c=d)}return l.length===0?s.delete(i):s.set(i,l),c};for(const i of e){if(k1(i)){const l=i.toolCalls||[];if(l.length===0){t.push(i);continue}l.forEach((c,d)=>{const u=c.toolCallId||`${i.id}-${d}`;if(Sh(c.toolName)){n.add(u);return}if(j1(c.toolName)){n.add(u);const y={...i,id:`${i.id}:tool-call:${d}:${u}`,toolCalls:[{...c,toolCallId:u}]};t.push(y);return}const p={call:{...i,id:`${i.id}:tool-call:${d}:${u}`,toolCalls:[{...c,toolCallId:u}]},callMessageId:i.id};o(u,p),t.push([p])});continue}if(C1(i)){const l=i.toolCallId;if(l&&n.has(l)){n.delete(l),t.push(i);continue}if(Sh(i.toolName)){t.push(i);continue}const c=l?a(l):void 0;if(c)c.result=i,c.resultMessageId=i.id;else{const d=l||`orphan-tool-call:${i.id}`,h={call:{role:"assistant",type:"tool_call",id:`synthetic-tool-call:${i.id}`,createdAt:i.createdAt,toolCalls:[{toolCallId:d,toolName:(i.toolName||"").trim()||"tool",parameters:{},streamingOutput:""}],isCompressed:i.isCompressed,compressedEventId:i.compressedEventId},result:i,resultMessageId:i.id};t.push([h])}continue}t.push(i)}return t}const A1=(e,t)=>{var l;const{t:s}=se(),n=m.useMemo(()=>{var d;const c=t.find(u=>u.role==="system");return c||((d=e==null?void 0:e.config)!=null&&d.baseSystemPrompt?{id:`system-prompt-${e.id}`,role:"system",content:e.config.baseSystemPrompt,createdAt:new Date(e.createdAt).toISOString()}:null)},[e,t]),o=m.useCallback(c=>!1,[]),a=m.useCallback(c=>{if(w1(c))return{type:"compression_divider",id:c.id,createdAt:c.createdAt,label:c.label};if(S1(c))return{type:"tool_session",id:c.id,sessionId:c.sessionId,tools:c.tools,createdAt:c.createdAt};const d=c.message.role==="user"?"flex-end":"flex-start";let u=c.messageType;if(!u&&c.message.role==="assistant"&&"type"in c.message){const h="type"in c.message?c.message.type:void 0;(h==="text"||h==="plan"||h==="question"||h==="tool_call"||h==="tool_result")&&(u=h)}return{type:"message",message:c.message,align:d,messageType:u}},[]),i=m.useMemo(()=>{var f;const c=t.filter(b=>{const x=b.role;return!(x!=="user"&&x!=="assistant"&&x!=="system"&&x!=="tool"||o(b))}),d=R1(c),u=[];d.forEach((b,x)=>{var C,_;if(Array.isArray(b)){const T=b[0];u.push({type:"tool_session",id:T?E1(T,x):`tool-session-unknown-${x}`,sessionId:(e==null?void 0:e.id)||"default",tools:b,createdAt:((C=T==null?void 0:T.call)==null?void 0:C.createdAt)||((_=T==null?void 0:T.result)==null?void 0:_.createdAt)||new Date().toISOString()});return}const S=b;let w;if(S.role==="assistant"&&"type"in S){const T="type"in S?S.type:void 0;(T==="text"||T==="plan"||T==="question"||T==="tool_call"||T==="tool_result")&&(w=T)}u.push({message:S,messageType:w})}),!c.some(b=>b.role==="system")&&n&&u.unshift({message:n});const p=((f=e==null?void 0:e.config)==null?void 0:f.compressionEvents)||[],y=u.findIndex(b=>!T1(b)),g=y===-1?u.length:y;for(const b of p){const x={type:"compression_divider",id:`compression-divider-${b.id}`,createdAt:b.createdAt,label:s("chat.compression.timelineDetail",{count:b.messagesCompressed,defaultValue:"{{count}} messages archived"})},S=vh(b.createdAt),w=u.findIndex((C,_)=>_>=g&&vh(_1(C))>S);w===-1?u.push(x):u.splice(w,0,x)}return u},[(l=e==null?void 0:e.config)==null?void 0:l.compressionEvents,e==null?void 0:e.id,t,o,n,s]);return{systemPromptMessage:n,renderableMessages:i,convertRenderableEntry:a}},{useToken:I1}=xe,{useBreakpoint:$1}=_i,{Text:F1}=le,L1=e=>e.role==="user"?"You":e.role==="assistant"?"Assistant":e.role==="system"?"System":"Message",qy=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},O1=e=>e.map(({message:t,text:s},n)=>{const o=L1(t),a=qy(t.createdAt);return[`## ${n+1}. ${o} · ${a}`,"",s].join(`
|
|
241
|
+
`)}).join(`
|
|
242
|
+
|
|
243
|
+
---
|
|
244
|
+
|
|
245
|
+
`),D1=({sessionId:e,embedded:t=!1})=>{var Pe,Xe,Je,rs;const{message:s}=ts.useApp(),{t:n}=se(),o=gi(Z=>Z.isAdvanced),a=z(Z=>e??Z.currentSessionId),i=z(xr(a)),l=z(Z=>Z.deleteMessage),c=z(Z=>Z.loadChatHistory),d=z(Z=>Z.processingChats),u=z(Z=>Z.tokenUsages),h=z(Z=>Z.truncationOccurred),p=z(Z=>Z.segmentsRemoved),y=m.useMemo(()=>(i==null?void 0:i.messages)||[],[i]),g=m.useMemo(()=>!a||!i?a:i.kind==="child"&&(i.parentSessionId||i.rootSessionId)||a,[i,a]),f=z(Z=>g?!!Z.taskLists[g]:!1),b=z(Z=>{if(!a)return!1;const Ce=Z.subSessionsByParent[a];return Ce&&Object.keys(Ce).length>0?!0:Z.chats.some(Ie=>Ie.kind==="child"&&Ie.parentSessionId===a)});m.useEffect(()=>{if(!a)return;const Z=z.getState().chats.find(Ce=>Ce.id===a);Z&&Array.isArray(Z.messages)&&Z.messages.length>0||c(a)},[a,c]);const x=a?d.has(a):!1,S=m.useMemo(()=>{var hn;if(!y||y.length===0)return null;const Z=new Map;let Ce=0,Ie=0,Be=0;for(const Xs of y){if(!Kg(Xs))continue;const $t=((hn=Xs.result)==null?void 0:hn.result)??"",fs=ma($t),Es=kc($t);if(!fs||!Es)continue;Be+=1,Ce+=Es.added,Ie+=Es.removed;const Rs=Z.get(fs.file_path);Rs?(Rs.added+=Es.added,Rs.removed+=Es.removed,Rs.diffChunks.push(fs.diff.unified),Rs.truncated=Rs.truncated||!!fs.diff.truncated):Z.set(fs.file_path,{added:Es.added,removed:Es.removed,diffChunks:[fs.diff.unified],truncated:!!fs.diff.truncated})}if(Z.size===0)return null;const mt=Array.from(Z.entries()).map(([Xs,$t])=>({filePath:Xs,added:$t.added,removed:$t.removed,unifiedDiff:$t.diffChunks.join(`
|
|
246
|
+
|
|
247
|
+
`),truncated:$t.truncated})).sort((Xs,$t)=>Xs.filePath.localeCompare($t.filePath));return{totalAdded:Ce,totalRemoved:Ie,files:mt,changedTools:Be}},[y]),w=m.useMemo(()=>{const Z=x?"THINKING":"IDLE";return{value:Z,context:{streamingContent:null,toolCallRequest:null,parsedParameters:null},matches:Ce=>Ce===Z}},[x]),C=m.useCallback(Z=>{if(Z.success)return null;switch(Z.reason){case"session_not_found":case"message_not_found":case"backend_not_found":return n("chat.messageActions.deleteNotFound");case"session_running":return n("chat.messageActions.deleteConflict");default:return Z.errorMessage||n("chat.messageActions.deleteFailed")}},[n]),_=m.useCallback(async(Z,Ce)=>{if(!a){const Be={success:!1,sessionId:"",messageId:Z,reason:"session_not_found"};return(Ce==null?void 0:Ce.notify)!==!1&&s.error(C(Be)),Be}const Ie=await l(a,Z);return!Ie.success&&(Ce==null?void 0:Ce.notify)!==!1&&s.error(C(Ie)),Ie},[a,l,s,C]),T=m.useCallback(async Z=>{const Ce=Array.from(new Set(Z.map(mt=>mt.trim()).filter(Boolean)));if(Ce.length===0)return;const Be=(await Promise.all(Ce.map(mt=>_(mt,{notify:!1})))).filter(mt=>!mt.success);if(Be.length!==0){if(Be.length===1){s.error(C(Be[0]));return}s.error(n("chat.messageActions.deleteBatchFailed",{failed:Be.length,total:Ce.length}))}},[_,s,C,n]),j=m.useRef(null),{token:v}=I1(),k=$1(),[E,M]=m.useState(null),[R,I]=m.useState(!1),[P,L]=m.useState(new Set),O=Ae(Z=>Z.sidebar.collapsed),A=()=>t||k.xs||k.sm?"100%":k.md?"90%":k.lg?"85%":"1024px",$=()=>{let Z;return t?Z=v.paddingSM:k.xs?Z=v.paddingXS:k.sm?Z=v.paddingSM:Z=v.padding,!t&&O?Z+18:Z};m.useEffect(()=>{M(null),I(!1),L(new Set)},[a]);const{systemPromptMessage:W,renderableMessages:F,convertRenderableEntry:H}=A1(i,y),D=y.length>0,U=!!(E!=null&&E.content),Q=!!W,Y=!!a&&(D||U),he=t?190:0,ve=m.useMemo(()=>{if(!(E!=null&&E.content))return F;const Z={message:{id:E.id,role:"user",content:E.content,createdAt:E.createdAt},messageType:"text"};return[...F,Z]},[F,E]),ue=m.useMemo(()=>{const Z=[];for(const Ce of ve){if(!("message"in Ce))continue;const Ie=Ey(Ce.message).trim();Ie&&Z.push({id:Ce.message.id,message:Ce.message,text:Ie})}return Z},[ve]),ie=m.useMemo(()=>new Set(ue.map(Z=>Z.id)),[ue]);m.useEffect(()=>{L(Z=>{let Ce=!1;const Ie=new Set;for(const Be of Z)ie.has(Be)?Ie.add(Be):Ce=!0;return Ce?Ie:Z})},[ie]);const Re=m.useMemo(()=>ue.filter(Z=>P.has(Z.id)),[ue,P]),Le=ue.length>0,Ze=m.useCallback(Z=>{L(Ce=>{const Ie=new Set(Ce);return Ie.has(Z)?Ie.delete(Z):Ie.add(Z),Ie})},[]),et=m.useCallback(()=>{if(!Le){s.warning("No exportable messages");return}I(!0)},[s,Le]),Ct=m.useCallback(()=>{I(!1),L(new Set)},[]),pt=m.useCallback(()=>{if(R){Ct();return}et()},[et,Ct,R]),At=m.useCallback(()=>{L(new Set(ue.map(Z=>Z.id)))},[ue]),re=m.useCallback(()=>{L(new Set)},[]),$e=m.useCallback(async Z=>{var Be;if(!a){s.warning("No active chat");return}if(Re.length===0){s.warning("Please select at least one message");return}const Ce=O1(Re),Ie=await Ry.exportMessageText({format:Z,content:Ce,sessionId:a,filenamePrefix:`chat-messages-${Re.length}`});if(Ie.success){s.success(`Saved: ${Ie.filename}`);return}(Be=Ie.error)!=null&&Be.toLowerCase().includes("cancel")||s.error(Ie.error||"Export failed")},[s,a,Re]);m.useEffect(()=>{if(typeof window>"u")return;const Z=Ce=>{var mt;const Be=((mt=Ce.detail)==null?void 0:mt.sessionId)??null;!a||Be!==a||pt()};return window.addEventListener(Ic,Z),()=>{window.removeEventListener(Ic,Z)}},[a,pt]);const V=a?u[a]:null,ge=(Pe=i==null?void 0:i.config)==null?void 0:Pe.tokenUsage,oe=V||ge||null,ce=a?h[a]:!1,Me=(Xe=i==null?void 0:i.config)==null?void 0:Xe.truncationOccurred,It=ce||Me||!1,St=a?p[a]:0,tt=(Je=i==null?void 0:i.config)==null?void 0:Je.segmentsRemoved,st=St||tt||0,rt=m.useMemo(()=>{var Ce;const Z=(Ce=i==null?void 0:i.config)==null?void 0:Ce.compressionEvents;return!Z||Z.length===0?null:Z.reduce((Ie,Be)=>{const mt=Date.parse(Ie.createdAt),hn=Date.parse(Be.createdAt);return Number.isFinite(mt)?Number.isFinite(hn)&&hn>mt?Be:Ie:Be})},[(rs=i==null?void 0:i.config)==null?void 0:rs.compressionEvents]),ss=v.marginMD,{handleMessagesScroll:Ms,resetUserScroll:Hs,scrollToBottom:ns,scrollToTop:Ys,showScrollToBottom:Ps,showScrollToTop:Bn}=v1({currentSessionId:a,interactionState:w,messagesListRef:j,renderableMessages:ve}),X=()=>k.xs?16:32,G=!!Y&&Le&&(!t||R),de=rt?r.jsx(je,{title:n("chat.compression.tooltip",{count:rt.messagesCompressed,time:qy(rt.createdAt),defaultValue:"Latest compression at {{time}}: {{count}} messages archived"}),children:r.jsx(fe,{color:"gold",icon:r.jsx($p,{}),style:{marginInlineEnd:0,whiteSpace:"nowrap"},children:n("chat.compression.archivedShort",{count:rt.messagesCompressed,defaultValue:"{{count}} archived"})})}):null,ae=oe&&oe.budgetLimit>0?r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:v.marginXS},children:[r.jsx(BE,{usage:oe,showDetails:!0,size:"small"}),It&&r.jsxs("span",{style:{fontSize:11,color:v.colorTextSecondary,whiteSpace:"nowrap"},children:["(",st," truncated)"]}),de]}):de?r.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:v.marginXS},children:de}):null;return r.jsx(nr,{role:"region","aria-label":n("chat.view.chatRegion","Chat conversation"),style:{flex:1,minHeight:0,height:"100%",background:v.colorBgContainer,position:"relative",overflow:"hidden"},children:r.jsxs(K,{vertical:!0,style:{flex:1,minHeight:0,height:"100%"},children:[a&&r.jsx(QE,{sessionId:a}),o&&a&&Y&&r.jsx("div",{style:{paddingTop:v.paddingXS,paddingRight:$(),paddingBottom:0,paddingLeft:$(),maxWidth:A(),margin:"0 auto",width:"100%"},children:r.jsx(n1,{sessionId:a})}),a&&f&&r.jsx("div",{style:{paddingTop:$(),paddingRight:$(),paddingBottom:0,paddingLeft:$(),maxWidth:A(),margin:"0 auto",width:"100%"},children:r.jsx(kE,{sessionId:a,initialCollapsed:!0})}),a&&b&&r.jsx("div",{style:{paddingTop:v.paddingXS,paddingRight:$(),paddingBottom:0,paddingLeft:$(),maxWidth:A(),margin:"0 auto",width:"100%"},children:r.jsx(VE,{parentSessionId:a})}),G&&r.jsx("div",{style:{paddingTop:v.paddingXS,paddingRight:$()+he,paddingBottom:0,paddingLeft:$(),maxWidth:A(),margin:"0 auto",width:"100%"},children:R?r.jsxs(K,{align:"center",justify:"space-between",wrap:"wrap",gap:v.marginXS,children:[r.jsx(F1,{type:"secondary",children:n("chat.selectionToolbar.selectedCount",{selected:Re.length,total:ue.length})}),r.jsxs(q,{size:v.marginXS,wrap:!0,children:[r.jsx(B,{size:"small",onClick:At,children:n("chat.selectionToolbar.selectAll")}),r.jsx(B,{size:"small",onClick:re,children:n("chat.selectionToolbar.clear")}),r.jsx(B,{size:"small",icon:r.jsx(cr,{}),onClick:()=>{$e("markdown")},disabled:Re.length===0,children:n("chat.selectionToolbar.exportMarkdown")}),r.jsx(B,{size:"small",type:"primary",icon:r.jsx(cr,{}),onClick:()=>{$e("pdf")},disabled:Re.length===0,children:n("chat.selectionToolbar.exportPdf")}),r.jsx(B,{size:"small",icon:r.jsx(fr,{}),onClick:pt,children:n("chat.selectionToolbar.done")})]})]}):r.jsx(K,{justify:"flex-end",children:r.jsx(je,{title:n("chat.selectionToolbar.selectMessages"),children:r.jsx(B,{"aria-label":n("chat.selectionToolbar.selectMessages"),icon:r.jsx(Lp,{}),size:"small",onClick:pt})})})}),r.jsx(_E,{currentChat:i,currentSessionId:a,convertRenderableEntry:H,handleDeleteMessage:_,handleDeleteToolMessages:T,handleMessagesScroll:Ms,hasSystemPrompt:Q,messagesListRef:j,renderableMessages:ve,rowGap:ss,showMessagesView:!!Y,screens:k,workflowDraftId:E==null?void 0:E.id,interactionState:w,padding:$(),selectionMode:R,selectedMessageIds:P,selectableMessageIds:ie,onToggleMessageSelection:Ze}),(Bn||Ps)&&r.jsxs("div",{style:{position:"absolute",right:X(),bottom:k.xs?160:180,display:"flex",flexDirection:"column",gap:v.marginXS,zIndex:1e3},children:[Bn&&r.jsx(Hd,{type:"default",icon:r.jsx(Kc,{}),style:{position:"relative",inset:"unset"},onClick:()=>{Ys()}}),Ps&&r.jsx(Hd,{type:"primary",icon:r.jsx(Zt,{}),style:{position:"relative",inset:"unset"},onClick:()=>{Hs(),ns()}})]}),a&&r.jsx("div",{style:{paddingTop:v.paddingXS,paddingRight:$(),paddingBottom:0,paddingLeft:$(),maxWidth:A(),margin:"0 auto",width:"100%"},children:r.jsx(zE,{sessionId:a})}),r.jsx(nC,{sessionId:a,isCenteredLayout:!Y,maxWidth:Y?A():"100%",onWorkflowDraftChange:M,showMessagesView:!!Y,sessionDiffSummary:S,contextUsageIndicator:ae})]})})},z1=5,N1=5,B1=5,W1=e=>{if(!e)return"";try{const t=Date.now()-new Date(e).getTime();if(t<0)return"";const s=Math.floor(t/1e3);if(s<60)return"just now";const n=Math.floor(s/60);if(n<60)return`${n}m ago`;const o=Math.floor(n/60);if(o<24)return`${o}h ago`;const a=Math.floor(o/24);return a<30?`${a}d ago`:new Date(e).toLocaleDateString()}catch{return""}},U1=e=>e.isRunning?"is-running":e.lastRunStatus==="error"?"is-error":e.pinned?"is-pinned":"is-idle",Wr=({icon:e,value:t,label:s,iconBg:n,iconColor:o})=>r.jsxs("div",{className:"lotus-home-stat-card",children:[r.jsx("span",{className:"lotus-home-stat-icon",style:{background:n,color:o},children:e}),r.jsxs("span",{className:"lotus-home-stat-info",children:[r.jsx("span",{className:"lotus-home-stat-value",children:t}),r.jsx("span",{className:"lotus-home-stat-label",children:s})]})]}),Fl=({chat:e,onOpen:t,textSecondary:s})=>{const n=e.config.workspacePath?e.config.workspacePath.split("/").pop()||e.config.workspacePath:null;return r.jsxs("button",{type:"button",className:"lotus-home-session-item",onClick:()=>t(e.id),children:[r.jsx("span",{className:`lotus-home-session-status ${U1(e)}`}),r.jsxs("span",{className:"lotus-home-session-content",children:[r.jsx("span",{className:"lotus-home-session-title",children:e.title}),r.jsxs("span",{className:"lotus-home-session-meta",style:{color:s},children:[r.jsx("span",{children:W1(e.updatedAt)}),n?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"lotus-home-session-meta-sep"}),r.jsxs("span",{children:[r.jsx(Yo,{style:{marginRight:3}}),n]})]}):null,e.messageCount!=null?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"lotus-home-session-meta-sep"}),r.jsxs("span",{children:[r.jsx(Xo,{style:{marginRight:3}}),e.messageCount]})]}):null]})]}),e.isRunning?r.jsx(fe,{color:"green",bordered:!1,style:{margin:0,fontSize:11},children:"Running"}):null,r.jsx(Bs,{className:"lotus-home-session-arrow"})]})},q1=({onOpenSession:e,onCreateSession:t})=>{const{t:s}=se(),{token:n}=xe.useToken(),o=qs(p=>p.open),a=z(p=>p.chats),i=z(p=>p.processingChats),l=m.useMemo(()=>{const p=a.filter(x=>x.kind!=="child"),y=a.filter(x=>x.isRunning||i.has(x.id)),g=a.filter(x=>x.pinned),f=new Set(a.map(x=>x.config.workspacePath).filter(Boolean)),b=a.filter(x=>x.lastRunStatus==="error");return{totalSessions:p.length,runningCount:y.length,pinnedCount:g.length,workspaceCount:f.size,errorCount:b.length}},[a,i]),c=m.useMemo(()=>a.filter(p=>p.isRunning||i.has(p.id)).slice(0,N1),[a,i]),d=m.useMemo(()=>a.filter(p=>p.pinned&&!p.isRunning).slice(0,B1),[a]),u=m.useMemo(()=>{const p=new Set(c.map(g=>g.id)),y=new Set(d.map(g=>g.id));return a.filter(g=>g.kind!=="child"&&!p.has(g.id)&&!y.has(g.id)).sort((g,f)=>{const b=g.updatedAt?new Date(g.updatedAt).getTime():g.createdAt;return(f.updatedAt?new Date(f.updatedAt).getTime():f.createdAt)-b}).slice(0,z1)},[a,c,d]),h=m.useCallback(p=>{e(p)},[e]);return r.jsx("div",{className:"lotus-home-dashboard",children:r.jsxs("div",{className:"lotus-home-dashboard-inner",children:[r.jsxs("div",{className:"lotus-home-header",children:[r.jsx("span",{className:"lotus-home-header-icon",style:{background:`${n.colorPrimary}15`,color:n.colorPrimary},children:r.jsx(Vx,{})}),r.jsxs("div",{className:"lotus-home-header-text",children:[r.jsx("h2",{style:{color:n.colorText},children:s("home.title","Welcome to Lotus")}),r.jsx("p",{style:{color:n.colorTextSecondary},children:s("home.subtitle","Here's an overview of your workspace.")})]})]}),r.jsxs("div",{className:"lotus-home-stats",children:[r.jsx(Wr,{icon:r.jsx(Xo,{}),value:l.totalSessions,label:s("home.stats.sessions","Sessions"),iconBg:`${n.colorPrimary}15`,iconColor:n.colorPrimary}),r.jsx(Wr,{icon:r.jsx(La,{}),value:l.runningCount,label:s("home.stats.running","Running"),iconBg:l.runningCount>0?"#52c41a15":`${n.colorTextQuaternary}10`,iconColor:l.runningCount>0?"#52c41a":n.colorTextQuaternary}),r.jsx(Wr,{icon:r.jsx(Za,{}),value:l.pinnedCount,label:s("home.stats.pinned","Pinned"),iconBg:"#faad1415",iconColor:"#faad14"}),r.jsx(Wr,{icon:r.jsx(Yo,{}),value:l.workspaceCount,label:s("home.stats.workspaces","Workspaces"),iconBg:`${n.colorPrimary}10`,iconColor:n.colorPrimary}),l.errorCount>0?r.jsx(Wr,{icon:r.jsx(gr,{}),value:l.errorCount,label:s("home.stats.errors","Errors"),iconBg:"#ff4d4f15",iconColor:"#ff4d4f"}):null]}),c.length>0?r.jsxs("div",{className:"lotus-home-section",children:[r.jsxs("div",{className:"lotus-home-section-title",style:{color:n.colorTextSecondary},children:[r.jsx(La,{className:"lotus-home-section-icon",style:{color:"#52c41a"}}),r.jsx("span",{children:s("home.sections.running","Running Now")})]}),r.jsx("div",{className:"lotus-home-session-list",children:c.map(p=>r.jsx(Fl,{chat:p,onOpen:h,textSecondary:n.colorTextTertiary},p.id))})]}):null,d.length>0?r.jsxs("div",{className:"lotus-home-section",children:[r.jsxs("div",{className:"lotus-home-section-title",style:{color:n.colorTextSecondary},children:[r.jsx(Za,{className:"lotus-home-section-icon",style:{color:"#faad14"}}),r.jsx("span",{children:s("home.sections.pinned","Pinned")})]}),r.jsx("div",{className:"lotus-home-session-list",children:d.map(p=>r.jsx(Fl,{chat:p,onOpen:h,textSecondary:n.colorTextTertiary},p.id))})]}):null,u.length>0?r.jsxs("div",{className:"lotus-home-section",children:[r.jsxs("div",{className:"lotus-home-section-title",style:{color:n.colorTextSecondary},children:[r.jsx(Us,{className:"lotus-home-section-icon"}),r.jsx("span",{children:s("home.sections.recent","Recent Sessions")})]}),r.jsx("div",{className:"lotus-home-session-list",children:u.map(p=>r.jsx(Fl,{chat:p,onOpen:h,textSecondary:n.colorTextTertiary},p.id))})]}):null,r.jsxs("div",{className:"lotus-home-section",children:[r.jsxs("div",{className:"lotus-home-section-title",style:{color:n.colorTextSecondary},children:[r.jsx(La,{className:"lotus-home-section-icon"}),r.jsx("span",{children:s("home.sections.quickActions","Quick Actions")})]}),r.jsxs("div",{className:"lotus-home-quick-actions",children:[r.jsx(B,{icon:r.jsx(ks,{}),onClick:()=>void t(),children:s("home.actions.newSession","New Session")}),r.jsx(B,{icon:r.jsx(Kx,{}),onClick:()=>o("chat","schedules"),children:s("home.actions.schedules","Schedules")}),r.jsx(B,{icon:r.jsx(sa,{}),onClick:()=>o("chat","provider"),children:s("home.actions.settings","Settings")})]})]}),a.length===0?r.jsx("div",{className:"lotus-home-empty-hint",style:{color:n.colorTextTertiary},children:s("home.empty","No sessions yet. Create one to get started!")}):null]})})},sn=(e,t,s)=>Math.max(t,Math.min(s,e)),$a=(e,t)=>t==="horizontal"?e.clientWidth:e.clientHeight,Fa=(e,t,s)=>{const n=Math.max(0,Math.round(e)),o=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(s));return o+a>n?{minFirst:0,maxFirst:n,appliedMinFirst:0,appliedMinSecond:0}:{minFirst:o,maxFirst:n-a,appliedMinFirst:o,appliedMinSecond:a}},Hy=({layout:e,first:t,second:s,sizesPx:n,defaultSplitRatio:o=.5,minFirstPx:a=0,minSecondPx:i=0,handleSizePx:l=6,disabled:c=!1,onResizeEnd:d,style:u,className:h})=>{const p=m.useRef(null),y=m.useRef(null),[g,f]=m.useState(null),[b,x]=m.useState(0),[S,w]=m.useState(null),C=m.useMemo(()=>{if(!n)return null;const F=Number(n[0]);return Number.isFinite(F)?F:null},[n]),_=m.useMemo(()=>{if(!n)return null;const F=Number(n[0]),H=Number(n[1]);if(!Number.isFinite(F)||!Number.isFinite(H))return null;const D=F+H;return D<=0||H<=0?null:sn(F/D,0,1)},[n]);m.useLayoutEffect(()=>{const F=p.current;F&&x($a(F,e))},[e]),m.useEffect(()=>{const F=p.current;if(!F)return;const H=()=>{const D=$a(F,e);x(U=>U===D?U:D)};if(H(),typeof ResizeObserver<"u"){const D=new ResizeObserver(H);return D.observe(F),()=>D.disconnect()}return window.addEventListener("resize",H),()=>window.removeEventListener("resize",H)},[e]),m.useEffect(()=>{if(_!==null){w(_);return}w(F=>F??sn(o,.1,.9))},[o,_]);const T=m.useMemo(()=>Fa(b,a,i),[b,a,i]),j=sn(o,.1,.9),v=S??j,k=b>0?Math.round(b*v):null,E=g??(_!==null?k:null)??C??k??0,M=b>0?sn(E,T.minFirst,T.maxFirst):Math.max(0,Math.round(E)),R=m.useCallback(F=>{if(c)return;const H=p.current;if(!H)return;F.preventDefault(),F.stopPropagation();const D=e==="horizontal"?F.clientX:F.clientY,U=$a(H,e),Q=Fa(U,a,i),Y=sn(M||Math.round(U*j),Q.minFirst,Q.maxFirst);y.current={pointerId:F.pointerId,startPos:D,startFirstPx:Y,containerSize:U};try{F.currentTarget.setPointerCapture(F.pointerId)}catch{}},[c,M,j,e,a,i]),I=m.useCallback(F=>{const H=y.current;if(!H||F.pointerId!==H.pointerId)return;F.preventDefault(),F.stopPropagation();const U=(e==="horizontal"?F.clientX:F.clientY)-H.startPos,Q=H.containerSize,Y=Fa(Q,a,i),he=sn(Math.round(H.startFirstPx+U),Y.minFirst,Y.maxFirst);f(he)},[e,a,i]),P=m.useCallback(F=>{const H=y.current;if(!H||H.pointerId!==F)return;const D=p.current,U=D?$a(D,e):H.containerSize,Q=g??H.startFirstPx,Y=Fa(U,a,i),he=sn(Q,Y.minFirst,Y.maxFirst),ve=Math.max(0,U-he);f(null),U>0&&w(sn(he/U,0,1)),y.current=null,d==null||d([he,ve])},[e,g,a,i,d]),L=m.useCallback(F=>{F.preventDefault(),F.stopPropagation(),P(F.pointerId)},[P]),O=m.useCallback(F=>{F.preventDefault(),F.stopPropagation(),P(F.pointerId)},[P]),A=e==="horizontal",$=c?"default":A?"col-resize":"row-resize",W=Math.max(0,Math.round(l));return r.jsxs("div",{ref:p,className:h,style:{display:"flex",flexDirection:A?"row":"column",height:"100%",minHeight:0,minWidth:0,width:"100%",position:"relative",...u},children:[r.jsx("div",{style:{flex:`0 0 ${M}px`,minWidth:A?T.appliedMinFirst:0,minHeight:A?0:T.appliedMinFirst,overflow:"hidden",display:"flex"},children:r.jsx("div",{style:{flex:1,minHeight:0,minWidth:0},children:t})}),r.jsx("div",{style:{flex:"1 1 auto",minWidth:A?T.appliedMinSecond:0,minHeight:A?0:T.appliedMinSecond,overflow:"hidden",display:"flex"},children:r.jsx("div",{style:{flex:1,minHeight:0,minWidth:0},children:s})}),W>0?r.jsx("div",{role:"separator","aria-orientation":A?"vertical":"horizontal",onPointerDown:R,onPointerMove:I,onPointerUp:L,onPointerCancel:O,style:{position:"absolute",top:A?0:`${M-W/2}px`,left:A?`${M-W/2}px`:0,width:A?`${W}px`:"100%",height:A?"100%":`${W}px`,cursor:$,touchAction:"none",background:"transparent",zIndex:5}}):null]})},{useToken:H1}=xe,Y1=4,X1=({leafId:e})=>{const{token:t}=H1(),{t:s}=se(),n=Ae(v=>v.tree),o=Ae(v=>v.leafSessionIds),a=Ae(v=>v.activeLeafId),i=Ae(v=>v.setActiveLeafId),l=Ae(v=>v.splitLeaf),c=Ae(v=>v.closeLeaf),d=Ae(v=>v.setLeafSessionId),u=z(v=>v.selectSession),h=z(v=>v.addChat),p=z(v=>v.systemPrompts),y=z(v=>v.lastSelectedPromptId),g=o[e]??null,f=m.useMemo(()=>zt(n).length,[n]),b=f<Y1,x=f>1,w=x||!!g,C=f>1,_=a===e,T=m.useCallback(v=>{d(e,v),i(e),u(v)},[e,u,i,d]),j=m.useCallback(async()=>{var M,R;const v=p.find(I=>I.id===y),k=(v==null?void 0:v.id)||(p.length>0?((M=p.find(I=>I.id==="general_assistant"))==null?void 0:M.id)||p[0].id:""),E=await h({title:s("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:k,baseSystemPrompt:(v==null?void 0:v.content)||(p.length>0?((R=p.find(I=>I.id==="general_assistant"))==null?void 0:R.content)||p[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null});d(e,E),i(e)},[h,y,p,s,e,d,i]);return r.jsxs("div",{className:"chat-pane-shell",onMouseDownCapture:()=>{Yt("pane focus (mouse)",{leafId:e,sessionId:g,prevActiveLeafId:a}),i(e),g&&u(g)},onFocusCapture:()=>{Yt("pane focus (focus)",{leafId:e,sessionId:g,prevActiveLeafId:a}),i(e)},style:{height:"100%",minHeight:0,border:C?`1px solid ${_?t.colorPrimaryBorder:t.colorBorderSecondary}`:"none",borderRadius:C?t.borderRadiusLG:0,overflow:"hidden",background:t.colorBgContainer,position:"relative"},children:[r.jsx("div",{className:"chat-pane-actions",style:{background:t.colorBgElevated,border:`1px solid ${t.colorBorderSecondary}`,borderRadius:10,padding:"2px 4px"},children:r.jsxs(K,{gap:t.marginXS,children:[r.jsx(B,{size:"small",type:"text",icon:r.jsx(Gx,{}),disabled:!b,title:s("chat.multiPane.splitHorizontal"),"aria-label":s("chat.multiPane.splitHorizontal"),onClick:v=>{v.preventDefault(),v.stopPropagation(),Yt("pane split request",{leafId:e,layout:"horizontal"}),l(e,"horizontal");const k=Ae.getState(),E=k.leafSessionIds[k.activeLeafId]??null;E&&u(E)}}),r.jsx(B,{size:"small",type:"text",icon:r.jsx(Jx,{}),disabled:!b,title:s("chat.multiPane.splitVertical"),"aria-label":s("chat.multiPane.splitVertical"),onClick:v=>{v.preventDefault(),v.stopPropagation(),Yt("pane split request",{leafId:e,layout:"vertical"}),l(e,"vertical");const k=Ae.getState(),E=k.leafSessionIds[k.activeLeafId]??null;E&&u(E)}}),r.jsx(B,{size:"small",type:"text",icon:r.jsx(Lp,{}),disabled:!g,title:s("chat.multiPane.selectMessagesToExport"),"aria-label":s("chat.multiPane.selectMessagesToExport"),onClick:v=>{v.preventDefault(),v.stopPropagation(),g&&window.dispatchEvent(new CustomEvent(Ic,{detail:{sessionId:g}}))}}),r.jsx(B,{size:"small",type:"text",danger:!0,icon:r.jsx(fr,{}),disabled:!w,title:s("chat.multiPane.closePane"),"aria-label":s("chat.multiPane.closePane"),onClick:v=>{v.preventDefault(),v.stopPropagation(),Yt("pane close request",{leafId:e}),x?c(e):d(e,null);const k=Ae.getState(),E=k.leafSessionIds[k.activeLeafId]??null;u(E)}})]})}),g?r.jsx(yi,{name:"ChatView",children:r.jsx(D1,{sessionId:g,embedded:!0})}):r.jsx(yi,{name:"HomeDashboard",children:r.jsx(q1,{onOpenSession:T,onCreateSession:j})})]})},V1=({node:e})=>{const t=Ae(n=>n.splitSizesPx[e.id]??null),s=Ae(n=>n.setSplitSizesPx);return r.jsx(Hy,{layout:e.layout,sizesPx:t,defaultSplitRatio:.5,minFirstPx:240,minSecondPx:240,style:{height:"100%",minHeight:0},onResizeEnd:n=>{s(e.id,n)},first:r.jsx(Nc,{node:e.children[0]}),second:r.jsx(Nc,{node:e.children[1]})})},Nc=({node:e})=>e.type==="leaf"?r.jsx(X1,{leafId:e.id}):r.jsx(V1,{node:e}),K1=()=>{const e=Ae(h=>h.tree),t=Ae(h=>h.leafSessionIds),s=Ae(h=>h.activeLeafId),n=Ae(h=>h.setActiveLeafId),o=Ae(h=>h.setLeafSessionId),a=Ae(h=>h.clearSessionFromAllLeaves),i=z(h=>h.chats),l=z(h=>h.currentSessionId),c=m.useRef(!1),d=m.useMemo(()=>zt(e),[e]),u=m.useMemo(()=>new Set(i.map(h=>h.id)),[i]);return m.useEffect(()=>{d.length!==0&&(d.includes(s)||n(d[0]))},[s,d,n]),m.useEffect(()=>{for(const[h,p]of Object.entries(t))p&&!u.has(p)&&o(h,null)},[u,t,o]),m.useEffect(()=>{if(!l||c.current)return;if(!Object.values(t).some(Boolean)){o(s,l),c.current=!0;return}c.current=!0},[s,l,t,o]),m.useEffect(()=>{const h=new Set(Object.values(t).filter(Boolean));for(const p of h)u.has(p)||a(p)},[u,a,t]),r.jsx("div",{style:{height:"100%",minHeight:0,padding:0},children:r.jsx(Nc,{node:e})})},G1=[{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"]}],J1=e=>{const t=[e.title,e.id,e.kind||"root"];return e.pinned&&t.push("pinned","pin"),e.isRunning&&t.push("running","processing"),e.config.workspacePath&&t.push(e.config.workspacePath),e.updatedAt&&t.push(e.updatedAt),t.filter(Boolean)},Q1=(e,t,s)=>{const n=[];if(e.kind==="child"?n.push(t):n.push(s),e.config.workspacePath&&n.push(e.config.workspacePath),e.updatedAt)try{n.push(new Date(e.updatedAt).toLocaleString())}catch{n.push(e.updatedAt)}return n.join(" • ")},Z1=(e,t)=>{const s=t.trim().toLowerCase();return s?e.filter(n=>[n.title,n.subtitle||"",...n.keywords].join(" ").toLowerCase().includes(s)):e},eR=e=>{if(!(e instanceof HTMLElement))return!1;const t=e.tagName.toLowerCase();return e.isContentEditable?!0:t==="input"||t==="textarea"||t==="select"},tR=()=>{const{t:e}=se(),{token:t}=xe.useToken(),{message:s}=ts.useApp(),n=z(M=>M.chats),o=z(M=>M.addChat),a=z(M=>M.lastSelectedPromptId),i=z(M=>M.systemPrompts),[l,c]=m.useState(!1),[d,u]=m.useState(""),[h,p]=m.useState(0),y=m.useRef(null),g=m.useRef(null),f=qs(M=>M.open),b=Dn(M=>M.toggleTheme),x=Dn(M=>M.themeMode),S=Ae(M=>M.sidebar.collapsed),w=Ae(M=>M.setSidebarCollapsed),C=gi(M=>M.mode),_=gi(M=>M.toggleMode),T=m.useCallback(async()=>{var A,$;const M=i.find(W=>W.id===a),R=(M==null?void 0:M.id)||(i.length>0?((A=i.find(W=>W.id==="general_assistant"))==null?void 0:A.id)||i[0].id:""),I=await o({title:e("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:R,baseSystemPrompt:(M==null?void 0:M.content)||(i.length>0?(($=i.find(W=>W.id==="general_assistant"))==null?void 0:$.content)||i[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null}),{activeLeafId:P,setLeafSessionId:L,setActiveLeafId:O}=Ae.getState();L(P,I),O(P)},[o,a,i,e]),j=m.useMemo(()=>{const M=G1.filter(R=>!(C==="simple"&&Vg.has(R.tabKey))).map(R=>({id:R.id,kind:"action",title:e(R.titleKey,R.fallbackTitle),subtitle:e(R.subtitleKey||"commandPalette.groups.settings",R.fallbackSubtitle||"System settings"),keywords:[R.tabKey,R.badge||"","settings","config",...R.keywords||[]],icon:r.jsx(sa,{}),badge:R.badge,onSelect:()=>{f("chat",R.tabKey)}}));return[{id:"new-session",kind:"action",title:e("commandPalette.actions.newSession","Create New Session"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["new","create","session","chat","conversation"],icon:r.jsx(ks,{}),badge:e("commandPalette.badges.quickAction","Action"),onSelect:async()=>{await T()}},{id:"toggle-theme",kind:"action",title:x==="dark"?e("commandPalette.actions.switchToLight","Switch to Light Mode"):e("commandPalette.actions.switchToDark","Switch to Dark Mode"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["theme","dark","light","mode","appearance","toggle","color"],icon:r.jsx(Qx,{}),badge:x==="dark"?"☀️":"🌙",onSelect:()=>{b()}},{id:"toggle-sidebar",kind:"action",title:S?e("commandPalette.actions.showSidebar","Show Sidebar"):e("commandPalette.actions.hideSidebar","Hide Sidebar"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["sidebar","toggle","hide","show","panel","menu"],icon:S?r.jsx(Op,{}):r.jsx(Cp,{}),badge:"Layout",onSelect:()=>{w(!S)}},{id:"split-pane",kind:"action",title:e("commandPalette.actions.splitPane","Split Pane"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["split","pane","multi","dual","side","layout"],icon:r.jsx(Zx,{}),badge:"Layout",onSelect:()=>{const{tree:R,activeLeafId:I,splitLeaf:P}=Ae.getState();zt(R).length<4&&P(I,"vertical")}},...M,{id:"toggle-experience-mode",kind:"action",title:C==="simple"?e("commandPalette.actions.switchToAdvanced","Switch to Advanced Mode"):e("commandPalette.actions.switchToSimple","Switch to Simple Mode"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["mode","simple","advanced","beginner","expert","experience","complexity"],icon:r.jsx(Pp,{}),badge:C==="simple"?"Simple":"Advanced",onSelect:()=>{_()}}]},[T,f,b,x,S,w,C,_,e]),v=m.useMemo(()=>n.map(M=>({id:`session-${M.id}`,kind:"session",title:M.title,subtitle:Q1(M,e("commandPalette.badges.childSession","Child session"),e("commandPalette.badges.rootSession","Session")),keywords:J1(M),icon:r.jsx(Xo,{}),badge:M.pinned?e("commandPalette.badges.pinned","Pinned"):M.isRunning?e("commandPalette.badges.running","Running"):M.kind==="child"?e("commandPalette.badges.child","Child"):void 0,onSelect:()=>{Di(M.id)}})),[n,e]),k=m.useMemo(()=>[...j,...v],[j,v]),E=m.useMemo(()=>Z1(k,d).slice(0,40),[k,d]);return m.useEffect(()=>{p(M=>E.length===0?0:Math.min(M,E.length-1))},[E.length]),m.useEffect(()=>{if(!l)return;const M=window.setTimeout(()=>{var R,I;(R=y.current)==null||R.focus(),(I=y.current)==null||I.select()},0);return()=>window.clearTimeout(M)},[l]),m.useEffect(()=>{if(typeof window>"u")return;const M=R=>{if((R.metaKey||R.ctrlKey)&&R.key.toLowerCase()==="k"){R.preventDefault(),c(P=>!P);return}if(l){if(R.key==="Escape"){R.preventDefault(),c(!1);return}if(!(eR(R.target)&&R.key!=="ArrowUp"&&R.key!=="ArrowDown"&&R.key!=="Enter")){if(R.key==="ArrowDown"){R.preventDefault(),p(P=>E.length===0?0:(P+1)%E.length);return}if(R.key==="ArrowUp"){R.preventDefault(),p(P=>E.length===0?0:P===0?E.length-1:P-1);return}if(R.key==="Enter"){const P=E[h];if(!P)return;R.preventDefault(),(async()=>{try{await P.onSelect(),c(!1),u("")}catch(L){console.error("[CommandPalette] action failed",L),s.error(L instanceof Error?L.message:e("commandPalette.errors.actionFailed","Command failed"))}})()}}}};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[E,s,l,h,e]),m.useEffect(()=>{l||(u(""),p(0))},[l]),m.useEffect(()=>{const M=g.current;if(!M)return;const R=M.querySelector(`[data-command-index="${h}"]`);R==null||R.scrollIntoView({block:"nearest"})},[h]),r.jsx(Et,{open:l,onCancel:()=>c(!1),footer:null,centered:!0,width:680,destroyOnClose:!0,className:"lotus-command-palette-modal",title:null,closable:!1,styles:{content:{padding:12,borderRadius:t.borderRadiusLG,overflow:"hidden",background:t.colorBgElevated,backdropFilter:"blur(18px)",WebkitBackdropFilter:"blur(18px)"},body:{padding:0},mask:{backdropFilter:"blur(6px)",WebkitBackdropFilter:"blur(6px)"}},children:r.jsxs("div",{className:"lotus-command-palette-shell",children:[r.jsxs("div",{className:"lotus-command-palette-search",children:[r.jsx(Ho,{style:{color:t.colorTextTertiary,fontSize:16}}),r.jsx(ye,{ref:y,value:d,onChange:M=>u(M.target.value),variant:"borderless",placeholder:e("commandPalette.searchPlaceholder","Search sessions, settings, and actions"),"aria-label":e("commandPalette.searchPlaceholder","Search sessions, settings, and actions"),suffix:r.jsx(le.Text,{type:"secondary",style:{fontSize:12},children:"⌘K"})})]}),r.jsxs("div",{className:"lotus-command-palette-hint",children:[r.jsx(Us,{}),r.jsx("span",{children:e("commandPalette.navigationHint","Use ↑↓ to navigate, Enter to open, and Esc to close.")})]}),r.jsx("div",{ref:g,className:"lotus-command-palette-list",role:"listbox",children:E.length===0?r.jsxs("div",{className:"lotus-command-palette-empty",children:[r.jsx(eb,{}),r.jsx("span",{children:e("commandPalette.empty","No matching commands")})]}):E.map((M,R)=>{const I=R===h;return r.jsxs("button",{type:"button",className:`lotus-command-palette-item ${I?"is-selected":""}`,"data-command-index":R,onMouseEnter:()=>p(R),onClick:()=>{(async()=>{try{await M.onSelect(),c(!1),u("")}catch(P){console.error("[CommandPalette] action failed",P),s.error(P instanceof Error?P.message:e("commandPalette.errors.actionFailed","Command failed"))}})()},children:[r.jsx("span",{className:"lotus-command-palette-item-icon",children:M.icon}),r.jsxs("span",{className:"lotus-command-palette-item-content",children:[r.jsxs("span",{className:"lotus-command-palette-item-title-row",children:[r.jsx("span",{className:"lotus-command-palette-item-title",children:M.title}),M.badge?r.jsx(fe,{bordered:!1,children:M.badge}):null]}),M.subtitle?r.jsx("span",{className:"lotus-command-palette-item-subtitle",children:M.subtitle}):null]})]},M.id)})})]})})},sR=({themeMode:e,onThemeModeChange:t,locale:s,onLocaleChange:n})=>{const o=qs(k=>k.isOpen),a=qs(k=>k.close),{t:i}=se(),{token:l}=xe.useToken(),c=zi(),d=m.useMemo(()=>Ig()==="macos",[]),u=Rt(k=>k.loadProviderConfig);m.useEffect(()=>{u()},[u]),uT(),Z0(),m.useEffect(()=>{Tm.clear(),km()},[e]),m.useEffect(()=>{Tm.clear(),km()},[c]);const h=Ae(k=>k.sidebar.collapsed),p=Ae(k=>k.sidebar.widthPx),y=Ae(k=>k.sidebar.minWidthPx),g=Ae(k=>k.sidebar.maxWidthPx),f=Ae(k=>k.setSidebarCollapsed),b=Ae(k=>k.setSidebarWidthPx),x=18,S=0,C=!o&&h&&d?44:S,_=0,T=88,j=10,v="none";return r.jsxs(r.Fragment,{children:[r.jsx("a",{href:"#lotus-main-content",className:"lotus-skip-link",style:{position:"absolute",top:-9999,left:-9999,zIndex:1e4,padding:"8px 16px",background:"var(--lotus-main-surface, #fff)",color:"var(--ant-color-primary, #0d9488)",borderRadius:8,fontWeight:600,textDecoration:"none"},onFocus:k=>{k.currentTarget.style.top="8px",k.currentTarget.style.left="8px"},onBlur:k=>{k.currentTarget.style.top="-9999px",k.currentTarget.style.left="-9999px"},children:i("app.skipToContent","Skip to main content")}),r.jsx(tR,{}),r.jsx(nr,{style:{minHeight:"100vh",height:"100vh",overflow:"hidden",background:"transparent",display:"flex",flexDirection:"row",position:"relative"},children:r.jsxs("div",{style:{display:"flex",flex:1,minHeight:0,height:"100%",width:"100%",boxSizing:"border-box",paddingTop:C,paddingLeft:S,paddingRight:S,paddingBottom:S,background:"transparent"},children:[o?r.jsx(nr,{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:`${x}px 0 0 ${x}px`,border:v,overflow:"hidden"},children:r.jsx(yi,{name:"SystemSettings",children:r.jsx(V0,{themeMode:e,onThemeModeChange:t,locale:s,onLocaleChange:n,onBack:a})})}):r.jsxs(r.Fragment,{children:[r.jsx(Q0,{}),r.jsx(Hy,{layout:"horizontal",style:{flex:1,minHeight:0,height:"100%",background:"transparent"},sizesPx:[h?_:p,0],minFirstPx:h?_:y,minSecondPx:320,disabled:h,handleSizePx:h?0:2,onResizeEnd:([k])=>{if(h)return;const E=Math.max(y,Math.min(g,k));b(E)},first:r.jsx("div",{className:"lotus-shell-panel lotus-shell-sidebar",style:{height:"100%",minHeight:0,borderRadius:`${x}px 0 0 ${x}px`,border:v,overflow:"hidden",background:"var(--lotus-sidebar-bg)"},children:r.jsx(rw,{})}),second:r.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{height:"100%",minHeight:0,borderRadius:`0 ${x}px ${x}px 0`,border:v,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:r.jsx(nr,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:r.jsx(K1,{})})})})]}),!o&&h?r.jsx(B,{"data-testid":"show-sidebar",type:"text",size:"small",icon:r.jsx(Op,{}),onClick:()=>f(!1),title:i("layout.showSidebar"),"aria-label":i("layout.showSidebar"),className:"lotus-toolbar-icon lotus-floating-sidebar-toggle",style:{position:"absolute",top:j,left:T,zIndex:40,width:36,height:36,borderRadius:12,border:`1px solid ${l.colorBorderSecondary}`,background:l.colorBgElevated,boxShadow:l.boxShadowSecondary}}):null]})})]})},wh={httpProxy:"",httpsProxy:"",proxyUsername:"",proxyPassword:"",rememberProxyAuth:!0},Ll=e=>typeof e=="string"?e:"",nR=()=>{const{t:e}=se(),[t,s]=m.useState(0),[n,o]=m.useState(wh),[a,i]=m.useState(!1),[l,c]=m.useState(!1),[d,u]=m.useState(null),[h,p]=m.useState(!1),[y,g]=m.useState(null),[f,b]=m.useState(!1);m.useEffect(()=>{(async()=>{let v=!1;try{const k=Pt.getInstance(),E=await k.getBambooConfig(),M=Ll(E.http_proxy),R=Ll(E.https_proxy),I=await k.getProxyAuthStatus(),P=Ll(I.username);o({httpProxy:M,httpsProxy:R,proxyUsername:P,proxyPassword:"",rememberProxyAuth:wh.rememberProxyAuth}),v=M.trim().length>0||R.trim().length>0,i(v)}catch(k){console.error("Failed to check config:",k),i(!1)}c(!0);try{const E=await Pt.getInstance().getSetupStatus();u({needsProxy:E.has_proxy_env,message:E.message}),i(v||E.has_proxy_env)}catch(k){console.error("Failed to check setup status:",k),u({needsProxy:!0,message:e("setup.error.loadStatusFailed")})}finally{c(!1)}})()},[]);const S=n.httpProxy.trim().length>0||n.httpsProxy.trim().length>0||a,w=j=>{o(v=>({...v,...j}))},C=async()=>{var R,I;const j=n.httpProxy.trim(),v=n.httpsProxy.trim(),k=!!(j||v),E=n.proxyUsername.trim(),M=!!E;try{if(g(null),b(!0),k){const L=Pt.getInstance(),O=await L.validateBambooConfigPatch({http_proxy:j,https_proxy:v});if(!O.valid){const $=((I=(R=O.errors)==null?void 0:R.proxy)==null?void 0:I[0])??Object.values(O.errors||{}).flat().filter(Boolean)[0];g(($==null?void 0:$.message)||e("setup.error.invalidProxy"));return}if(n.rememberProxyAuth&&!M&&n.proxyPassword.trim()){g(e("setup.error.credentialsUsername"));return}await L.setBambooConfig({http_proxy:j,https_proxy:v}),n.rememberProxyAuth&&M?await L.setProxyAuth({username:E,password:n.proxyPassword||""}):await L.clearProxyAuth()}await Pt.getInstance().markSetupComplete(),p(!0)}catch(P){console.error("Failed to complete setup:",P);const L=P instanceof Error&&P.message.trim()?P.message:e(k?"setup.error.saveProxyFailed":"setup.error.completeFailed");g(L)}finally{b(!1)}},_=async()=>{try{g(null),b(!0),await Pt.getInstance().markSetupComplete(),p(!0)}catch(j){console.error("Failed to mark setup complete:",j),g(e("setup.error.completeFailed"))}finally{b(!1)}},T=m.useMemo(()=>[{title:e("setup.steps.welcome"),content:r.jsxs("div",{children:[r.jsx("h1",{children:e("setup.welcome.heading")}),r.jsx("p",{children:e("setup.welcome.description")}),r.jsx(Ne,{message:e("setup.welcome.skipInfo"),type:"info",showIcon:!0,style:{marginBottom:16}}),r.jsxs("div",{className:"setup-page__actions",children:[r.jsx(B,{"data-testid":"setup-next",type:"primary",onClick:()=>s(1),children:e("setup.button.next")}),r.jsx(B,{"data-testid":"setup-skip",onClick:()=>void _(),loading:f,children:e("setup.button.skipForNow")})]})]})},{title:e("setup.steps.proxy"),content:r.jsxs("div",{children:[r.jsx("h2",{children:e("setup.proxy.title")}),r.jsx(Ne,{message:e("setup.proxy.info"),type:"info",showIcon:!0}),r.jsx(Ne,{message:e("setup.proxy.providerInfo"),type:"info",showIcon:!0,style:{marginTop:16}}),l?r.jsx("div",{style:{marginTop:16},children:r.jsx(ct,{tip:e("setup.proxy.detecting")})}):null,d?r.jsx(Ne,{message:d.message,type:d.needsProxy?"warning":"success",showIcon:!0,style:{marginTop:16}}):null,!l&&!d&&!a?r.jsx(Ne,{message:e("setup.proxy.noProxyDetected"),type:"success",showIcon:!0,style:{marginTop:16}}):null,y?r.jsx(Ne,{message:y,type:"error",showIcon:!0,style:{marginTop:16}}):null,r.jsxs("div",{style:{marginTop:16},children:[r.jsx("label",{htmlFor:"setup-http-proxy",children:e("setup.proxy.httpProxyLabel")}),r.jsx(ye,{id:"setup-http-proxy",value:n.httpProxy,onChange:j=>w({httpProxy:j.target.value}),placeholder:e("setup.proxy.httpProxyPlaceholder")})]}),r.jsxs("div",{style:{marginTop:16},children:[r.jsx("label",{htmlFor:"setup-https-proxy",children:e("setup.proxy.httpsProxyLabel")}),r.jsx(ye,{id:"setup-https-proxy",value:n.httpsProxy,onChange:j=>w({httpsProxy:j.target.value}),placeholder:e("setup.proxy.httpsProxyPlaceholder")})]}),S?r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:{marginTop:16},children:[r.jsx("label",{htmlFor:"setup-proxy-username",children:e("setup.proxy.usernameLabel")}),r.jsx(ye,{id:"setup-proxy-username",value:n.proxyUsername,onChange:j=>w({proxyUsername:j.target.value})})]}),r.jsxs("div",{style:{marginTop:16},children:[r.jsx("label",{htmlFor:"setup-proxy-password",children:e("setup.proxy.passwordLabel")}),r.jsx(ye.Password,{id:"setup-proxy-password",value:n.proxyPassword,onChange:j=>w({proxyPassword:j.target.value})})]}),r.jsx("div",{style:{marginTop:16},children:r.jsx(Fp,{checked:n.rememberProxyAuth,onChange:j=>w({rememberProxyAuth:j.target.checked}),children:e("setup.proxy.rememberCredentials")})})]}):null,r.jsxs("div",{className:"setup-page__actions",style:{marginTop:24},children:[r.jsx(B,{"data-testid":"setup-back",onClick:()=>s(0),children:e("setup.button.back")}),r.jsx(B,{"data-testid":"setup-skip",onClick:()=>void _(),loading:f,children:e("setup.button.skipForNow")}),r.jsx(B,{"data-testid":"setup-complete",onClick:()=>void C(),type:"primary",loading:f,children:e("setup.button.completeSetup")})]})]})}],[n,d,y,l,f,a,S,e]);return h?r.jsxs("div",{"data-testid":"setup-complete",className:"setup-complete",children:[r.jsx("h1",{children:e("setup.complete.title")}),r.jsx("p",{children:e("setup.complete.restartMessage")}),r.jsx(B,{"data-testid":"setup-restart",onClick:()=>window.location.reload(),children:e("setup.button.restart")})]}):r.jsx("div",{className:"setup-page",children:r.jsxs(te,{style:{maxWidth:600,margin:"40px auto"},children:[r.jsx(Ip,{current:t,items:T.map(j=>({title:j.title}))}),r.jsx("div",{style:{marginTop:24},children:T[t].content})]})})};var Ur={},Ol={exports:{}},_h;function Ke(){return _h||(_h=1,function(e){function t(s){return s&&s.__esModule?s:{default:s}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}(Ol)),Ol.exports}var qr={},Th;function rR(){if(Th)return qr;Th=1,Object.defineProperty(qr,"__esModule",{value:!0}),qr.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 qr.default=e,qr}var Hr={},Yr={},Xr={},Dl={exports:{}},zl={exports:{}},Nl={exports:{}},Bl={exports:{}},kh;function oR(){return kh||(kh=1,function(e){var t=Tp().default;function s(n,o){if(t(n)!="object"||!n)return n;var a=n[Symbol.toPrimitive];if(a!==void 0){var i=a.call(n,o||"default");if(t(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(o==="string"?String:Number)(n)}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}(Bl)),Bl.exports}var Ch;function aR(){return Ch||(Ch=1,function(e){var t=Tp().default,s=oR();function n(o){var a=s(o,"string");return t(a)=="symbol"?a:a+""}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports}(Nl)),Nl.exports}var jh;function iR(){return jh||(jh=1,function(e){var t=aR();function s(n,o,a){return(o=t(o))in n?Object.defineProperty(n,o,{value:a,enumerable:!0,configurable:!0,writable:!0}):n[o]=a,n}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}(zl)),zl.exports}var Mh;function Sr(){return Mh||(Mh=1,function(e){var t=iR();function s(o,a){var i=Object.keys(o);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(o);a&&(l=l.filter(function(c){return Object.getOwnPropertyDescriptor(o,c).enumerable})),i.push.apply(i,l)}return i}function n(o){for(var a=1;a<arguments.length;a++){var i=arguments[a]!=null?arguments[a]:{};a%2?s(Object(i),!0).forEach(function(l){t(o,l,i[l])}):Object.getOwnPropertyDescriptors?Object.defineProperties(o,Object.getOwnPropertyDescriptors(i)):s(Object(i)).forEach(function(l){Object.defineProperty(o,l,Object.getOwnPropertyDescriptor(i,l))})}return o}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports}(Dl)),Dl.exports}var Vr={},Ph;function wr(){return Ph||(Ph=1,Object.defineProperty(Vr,"__esModule",{value:!0}),Vr.commonLocale=void 0,Vr.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0}),Vr}var Eh;function lR(){if(Eh)return Xr;Eh=1;var e=Ke().default;Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.default=void 0;var t=e(Sr()),s=wr(),n=(0,t.default)((0,t.default)({},s.commonLocale),{},{locale:"en_US",today:"Today",now:"Now",backToToday:"Back to today",ok:"OK",clear:"Clear",week:"Week",month:"Month",year:"Year",timeSelect:"select time",dateSelect:"select date",weekSelect:"Choose a week",monthSelect:"Choose a month",yearSelect:"Choose a year",decadeSelect:"Choose a decade",dateFormat:"M/D/YYYY",dateTimeFormat:"M/D/YYYY HH:mm:ss",previousMonth:"Previous month (PageUp)",nextMonth:"Next month (PageDown)",previousYear:"Last year (Control + left)",nextYear:"Next year (Control + right)",previousDecade:"Last decade",nextDecade:"Next decade",previousCentury:"Last century",nextCentury:"Next century"});return Xr.default=n,Xr}var Kr={},Rh;function Yy(){if(Rh)return Kr;Rh=1,Object.defineProperty(Kr,"__esModule",{value:!0}),Kr.default=void 0;const e={placeholder:"Select time",rangePlaceholder:["Start time","End time"]};return Kr.default=e,Kr}var Ah;function Xy(){if(Ah)return Yr;Ah=1;var e=Ke().default;Object.defineProperty(Yr,"__esModule",{value:!0}),Yr.default=void 0;var t=e(lR()),s=e(Yy());const n={lang:Object.assign({placeholder:"Select date",yearPlaceholder:"Select year",quarterPlaceholder:"Select quarter",monthPlaceholder:"Select month",weekPlaceholder:"Select week",rangePlaceholder:["Start date","End date"],rangeYearPlaceholder:["Start year","End year"],rangeQuarterPlaceholder:["Start quarter","End quarter"],rangeMonthPlaceholder:["Start month","End month"],rangeWeekPlaceholder:["Start week","End week"]},t.default),timePickerLocale:Object.assign({},s.default)};return Yr.default=n,Yr}var Ih;function cR(){if(Ih)return Hr;Ih=1;var e=Ke().default;Object.defineProperty(Hr,"__esModule",{value:!0}),Hr.default=void 0;var t=e(Xy());return Hr.default=t.default,Hr}var $h;function dR(){if($h)return Ur;$h=1;var e=Ke().default;Object.defineProperty(Ur,"__esModule",{value:!0}),Ur.default=void 0;var t=e(rR()),s=e(cR()),n=e(Xy()),o=e(Yy());const a="${label} is not a valid ${type}",i={locale:"en",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.default,global:{placeholder:"Please select"},Table:{filterTitle:"Filter menu",filterConfirm:"OK",filterReset:"Reset",filterEmptyText:"No filters",filterCheckAll:"Select all items",filterSearchPlaceholder:"Search in filters",emptyText:"No data",selectAll:"Select current page",selectInvert:"Invert current page",selectNone:"Clear all data",selectionAll:"Select all data",sortTitle:"Sort",expand:"Expand row",collapse:"Collapse row",triggerDesc:"Click to sort descending",triggerAsc:"Click to sort ascending",cancelSort:"Click to cancel sorting"},Tour:{Next:"Next",Previous:"Previous",Finish:"Finish"},Modal:{okText:"OK",cancelText:"Cancel",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Cancel"},Transfer:{titles:["",""],searchPlaceholder:"Search here",itemUnit:"item",itemsUnit:"items",remove:"Remove",selectCurrent:"Select current page",removeCurrent:"Remove current page",selectAll:"Select all data",deselectAll:"Deselect all data",removeAll:"Remove all data",selectInvert:"Invert current page"},Upload:{uploading:"Uploading...",removeFile:"Remove file",uploadError:"Upload error",previewFile:"Preview file",downloadFile:"Download file"},Empty:{description:"No data"},Icon:{icon:"icon"},Text:{edit:"Edit",copy:"Copy",copied:"Copied",expand:"Expand",collapse:"Collapse"},Form:{optional:"(optional)",defaultValidateMessages:{default:"Field validation error for ${label}",required:"Please enter ${label}",enum:"${label} must be one of [${enum}]",whitespace:"${label} cannot be a blank character",date:{format:"${label} date format is invalid",parse:"${label} cannot be converted to a date",invalid:"${label} is an invalid date"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"${label} must be ${len} characters",min:"${label} must be at least ${min} characters",max:"${label} must be up to ${max} characters",range:"${label} must be between ${min}-${max} characters"},number:{len:"${label} must be equal to ${len}",min:"${label} must be minimum ${min}",max:"${label} must be maximum ${max}",range:"${label} must be between ${min}-${max}"},array:{len:"Must be ${len} ${label}",min:"At least ${min} ${label}",max:"At most ${max} ${label}",range:"The amount of ${label} must be between ${min}-${max}"},pattern:{mismatch:"${label} does not match the pattern ${pattern}"}}},Image:{preview:"Preview"},QRCode:{expired:"QR code expired",refresh:"Refresh",scanned:"Scanned"},ColorPicker:{presetEmpty:"Empty",transparent:"Transparent",singleColor:"Single",gradientColor:"Gradient"}};return Ur.default=i,Ur}var Wl,Fh;function uR(){return Fh||(Fh=1,Wl=dR()),Wl}var mR=uR();const hR=mr(mR);var Gr={},Jr={},Lh;function pR(){if(Lh)return Jr;Lh=1,Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.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 Jr.default=e,Jr}var Qr={},Zr={},eo={},Oh;function fR(){if(Oh)return eo;Oh=1;var e=Ke().default;Object.defineProperty(eo,"__esModule",{value:!0}),eo.default=void 0;var t=e(Sr()),s=wr(),n=(0,t.default)((0,t.default)({},s.commonLocale),{},{locale:"fr_FR",today:"Aujourd'hui",now:"Maintenant",backToToday:"Aujourd'hui",ok:"OK",clear:"Rétablir",week:"Semaine",month:"Mois",year:"Année",timeSelect:"Sélectionner l'heure",dateSelect:"Sélectionner la date",monthSelect:"Choisissez un mois",yearSelect:"Choisissez une année",decadeSelect:"Choisissez une décennie",dateFormat:"DD/MM/YYYY",dayFormat:"DD",dateTimeFormat:"DD/MM/YYYY HH:mm:ss",previousMonth:"Mois précédent (PageUp)",nextMonth:"Mois suivant (PageDown)",previousYear:"Année précédente (Ctrl + gauche)",nextYear:"Année prochaine (Ctrl + droite)",previousDecade:"Décennie précédente",nextDecade:"Décennie suivante",previousCentury:"Siècle précédent",nextCentury:"Siècle suivant"});return eo.default=n,eo}var to={},Dh;function Vy(){if(Dh)return to;Dh=1,Object.defineProperty(to,"__esModule",{value:!0}),to.default=void 0;const e={placeholder:"Sélectionner l'heure",rangePlaceholder:["Heure de début","Heure de fin"]};return to.default=e,to}var zh;function Ky(){if(zh)return Zr;zh=1;var e=Ke().default;Object.defineProperty(Zr,"__esModule",{value:!0}),Zr.default=void 0;var t=e(fR()),s=e(Vy());const n={lang:Object.assign({placeholder:"Sélectionner une date",yearPlaceholder:"Sélectionner une année",quarterPlaceholder:"Sélectionner un trimestre",monthPlaceholder:"Sélectionner un mois",weekPlaceholder:"Sélectionner une semaine",rangePlaceholder:["Date de début","Date de fin"],rangeYearPlaceholder:["Année de début","Année de fin"],rangeMonthPlaceholder:["Mois de début","Mois de fin"],rangeWeekPlaceholder:["Semaine de début","Semaine de fin"]},t.default),timePickerLocale:Object.assign({},s.default)};return Zr.default=n,Zr}var Nh;function gR(){if(Nh)return Qr;Nh=1;var e=Ke().default;Object.defineProperty(Qr,"__esModule",{value:!0}),Qr.default=void 0;var t=e(Ky());return Qr.default=t.default,Qr}var Bh;function yR(){if(Bh)return Gr;Bh=1;var e=Ke().default;Object.defineProperty(Gr,"__esModule",{value:!0}),Gr.default=void 0;var t=e(pR()),s=e(gR()),n=e(Ky()),o=e(Vy());const a="La valeur du champ ${label} n'est pas valide pour le type ${type}",i={locale:"fr",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.default,Table:{filterTitle:"Filtrer",filterConfirm:"OK",filterReset:"Réinitialiser",filterEmptyText:"Aucun filtre",filterCheckAll:"Tout sélectionner",filterSearchPlaceholder:"Chercher dans les filtres",emptyText:"Aucune donnée",selectAll:"Sélectionner la page actuelle",selectInvert:"Inverser la sélection de la page actuelle",selectNone:"Désélectionner toutes les données",selectionAll:"Sélectionner toutes les données",sortTitle:"Trier",expand:"Développer la ligne",collapse:"Réduire la ligne",triggerDesc:"Trier par ordre décroissant",triggerAsc:"Trier par ordre croissant",cancelSort:"Annuler le tri"},Tour:{Next:"Étape suivante",Previous:"Étape précédente",Finish:"Fin de la visite guidée"},Modal:{okText:"OK",cancelText:"Annuler",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Annuler"},Transfer:{titles:["",""],searchPlaceholder:"Rechercher",itemUnit:"élément",itemsUnit:"éléments",remove:"Désélectionner",selectCurrent:"Sélectionner la page actuelle",removeCurrent:"Désélectionner la page actuelle",selectAll:"Sélectionner toutes les données",removeAll:"Désélectionner toutes les données",selectInvert:"Inverser la sélection de la page actuelle"},Upload:{uploading:"Téléchargement...",removeFile:"Effacer le fichier",uploadError:"Erreur de téléchargement",previewFile:"Fichier de prévisualisation",downloadFile:"Télécharger un fichier"},Empty:{description:"Aucune donnée"},Icon:{icon:"icône"},Text:{edit:"Éditer",copy:"Copier",copied:"Copie effectuée",expand:"Développer"},Form:{optional:"(optionnel)",defaultValidateMessages:{default:"Erreur de validation pour le champ ${label}",required:"Le champ ${label} est obligatoire",enum:"La valeur du champ ${label} doit être parmi [${enum}]",whitespace:"La valeur du champ ${label} ne peut pas être vide",date:{format:"La valeur du champ ${label} n'est pas au format date",parse:"La valeur du champ ${label} ne peut pas être convertie vers une date",invalid:"La valeur du champ ${label} n'est pas une date valide"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"La taille du champ ${label} doit être de ${len} caractères",min:"La taille du champ ${label} doit être au minimum de ${min} caractères",max:"La taille du champ ${label} doit être au maximum de ${max} caractères",range:"La taille du champ ${label} doit être entre ${min} et ${max} caractères"},number:{len:"La valeur du champ ${label} doit être égale à ${len}",min:"La valeur du champ ${label} doit être plus grande que ${min}",max:"La valeur du champ ${label} doit être plus petit que ${max}",range:"La valeur du champ ${label} doit être entre ${min} et ${max}"},array:{len:"La taille du tableau ${label} doit être de ${len}",min:"La taille du tableau ${label} doit être au minimum de ${min}",max:"La taille du tableau ${label} doit être au maximum de ${max}",range:"La taille du tableau ${label} doit être entre ${min}-${max}"},pattern:{mismatch:"La valeur du champ ${label} ne correspond pas au modèle ${pattern}"}}},Image:{preview:"Aperçu"}};return Gr.default=i,Gr}var Ul,Wh;function xR(){return Wh||(Wh=1,Ul=yR()),Ul}var bR=xR();const vR=mr(bR);var so={},no={},Uh;function SR(){if(Uh)return no;Uh=1,Object.defineProperty(no,"__esModule",{value:!0}),no.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 no.default=e,no}var ro={},oo={},ao={},qh;function wR(){if(qh)return ao;qh=1;var e=Ke().default;Object.defineProperty(ao,"__esModule",{value:!0}),ao.default=void 0;var t=e(Sr()),s=wr(),n=(0,t.default)((0,t.default)({},s.commonLocale),{},{locale:"hi_IN",today:"आज",now:"अभी",backToToday:"आज तक",ok:"ठीक",clear:"स्पष्ट",week:"सप्ताह",month:"महीना",year:"साल",timeSelect:"समय का चयन करें",dateSelect:"तारीख़ चुनें",weekSelect:"एक सप्ताह चुनें",monthSelect:"एक महीना चुनें",yearSelect:"एक वर्ष चुनें",decadeSelect:"एक दशक चुनें",dateFormat:"M/D/YYYY",dateTimeFormat:"M/D/YYYY HH:mm:ss",previousMonth:"पिछला महीना (पेजअप)",nextMonth:"अगले महीने (पेजडाउन)",previousYear:"पिछले साल (Ctrl + बाएं)",nextYear:"अगले साल (Ctrl + दाहिना)",previousDecade:"पिछला दशक",nextDecade:"अगले दशक",previousCentury:"पीछ्ली शताब्दी",nextCentury:"अगली सदी"});return ao.default=n,ao}var io={},Hh;function Gy(){if(Hh)return io;Hh=1,Object.defineProperty(io,"__esModule",{value:!0}),io.default=void 0;const e={placeholder:"समय का चयन करें",rangePlaceholder:["आरंभिक समय","अंत समय"]};return io.default=e,io}var Yh;function Jy(){if(Yh)return oo;Yh=1;var e=Ke().default;Object.defineProperty(oo,"__esModule",{value:!0}),oo.default=void 0;var t=e(wR()),s=e(Gy());const n={lang:Object.assign({placeholder:"तारीख़ चुनें",yearPlaceholder:"वर्ष चुनें",quarterPlaceholder:"तिमाही चुनें",monthPlaceholder:"महीना चुनिए",weekPlaceholder:"सप्ताह चुनें",rangePlaceholder:["प्रारंभ तिथि","समाप्ति तिथि"],rangeYearPlaceholder:["आरंभिक वर्ष","अंत वर्ष"],rangeMonthPlaceholder:["आरंभिक महीना","अंत महीना"],rangeWeekPlaceholder:["आरंभिक सप्ताह","अंत सप्ताह"]},t.default),timePickerLocale:Object.assign({},s.default)};return oo.default=n,oo}var Xh;function _R(){if(Xh)return ro;Xh=1;var e=Ke().default;Object.defineProperty(ro,"__esModule",{value:!0}),ro.default=void 0;var t=e(Jy());return ro.default=t.default,ro}var Vh;function TR(){if(Vh)return so;Vh=1;var e=Ke().default;Object.defineProperty(so,"__esModule",{value:!0}),so.default=void 0;var t=e(SR()),s=e(_R()),n=e(Jy()),o=e(Gy());const a="${label} मान्य ${type} नहीं है",i={locale:"hi",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.default,global:{placeholder:"कृपया चुनें"},Table:{filterTitle:"सूची बंद करें",filterConfirm:"अच्छी तरह से",filterReset:"रीसेट",filterEmptyText:"कोई फ़िल्टर नहीं",emptyText:"कोई जानकारी नहीं",selectAll:"वर्तमान पृष्ठ का चयन करें",selectInvert:"वर्तमान पृष्ठ घुमाएं",selectNone:"सभी डेटा साफ़ करें",selectionAll:"सभी डेटा का चयन करें",sortTitle:"द्वारा क्रमबद्ध करें",expand:"पंक्ति का विस्तार करें",collapse:"पंक्ति संक्षिप्त करें",triggerDesc:"अवरोही क्रमित करने के लिए क्लिक करें",triggerAsc:"आरोही क्रमित करने के लिए क्लिक करें",cancelSort:"छँटाई रद्द करने के लिए क्लिक करें"},Modal:{okText:"अच्छी तरह से",cancelText:"रद्द करना",justOkText:"अच्छी तरह से"},Popconfirm:{okText:"अच्छी तरह से",cancelText:"रद्द करना"},Transfer:{titles:["",""],searchPlaceholder:"यहां खोजें",itemUnit:"तत्त्व",itemsUnit:"विषय-वस्तु",remove:"हटाए",selectCurrent:"वर्तमान पृष्ठ का चयन करें",removeCurrent:"वर्तमान पृष्ठ हटाएं",selectAll:"सभी डेटा का चयन करें",removeAll:"सभी डेटा हटाएं",selectInvert:"वर्तमान पृष्ठ को उल्टा करें"},Upload:{uploading:"अपलोड हो रहा...",removeFile:"फ़ाइल निकालें",uploadError:"अपलोड में त्रुटि",previewFile:"फ़ाइल पूर्वावलोकन",downloadFile:"फ़ाइल डाउनलोड करें"},Empty:{description:"कोई आकड़ा उपलब्ध नहीं है"},Icon:{icon:"आइकन"},Text:{edit:"संपादित करें",copy:"प्रतिलिपि",copied:"कॉपी किया गया",expand:"विस्तार"},Form:{optional:"(ऐच्छिक)",defaultValidateMessages:{default:"${label} के लिए फील्ड सत्यापन त्रुटि",required:"कृपया ${label} दर्ज करें",enum:"${label} [${enum}] में से एक होना चाहिए",whitespace:"${label} एक खाली अक्षर नहीं हो सकता",date:{format:"${label} तिथि प्रारूप अमान्य है",parse:"${label} को तारीख में नहीं बदला जा सकता",invalid:"${label} एक अमान्य तिथि है"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"${label} ${len} अक्षर का होना चाहिए",min:"${label} कम से कम ${min} वर्णों का होना चाहिए",max:"${label} अधिकतम ${max} वर्णों का होना चाहिए",range:"${label} ${min}-${max} वर्णों के बीच होना चाहिए"},number:{len:"${label} ${len} के बराबर होना चाहिए",min:"${label} कम से कम ${min} होना चाहिए",max:"${label} अधिकतम ${max} होना चाहिए",range:"${label} ${min}-${max} के बीच होना चाहिए"},array:{len:"${len} ${label} होना चाहिए",min:"कम से कम ${min} ${label}",max:"ज्यादा से ज्यादा ${max} ${label}",range:"${label} की राशि ${min}-${max} के बीच होनी चाहिए"},pattern:{mismatch:"${label} ${pattern} पैटर्न से मेल नहीं खाता"}}},Image:{preview:"पूर्वावलोकन"}};return so.default=i,so}var ql,Kh;function kR(){return Kh||(Kh=1,ql=TR()),ql}var CR=kR();const jR=mr(CR);var lo={},co={},Gh;function MR(){if(Gh)return co;Gh=1,Object.defineProperty(co,"__esModule",{value:!0}),co.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 co.default=e,co}var uo={},mo={},ho={},Jh;function PR(){if(Jh)return ho;Jh=1;var e=Ke().default;Object.defineProperty(ho,"__esModule",{value:!0}),ho.default=void 0;var t=e(Sr()),s=wr(),n=(0,t.default)((0,t.default)({},s.commonLocale),{},{locale:"ja_JP",today:"今日",now:"現在時刻",backToToday:"今日に戻る",ok:"確定",timeSelect:"時間を選択",dateSelect:"日時を選択",weekSelect:"週を選択",clear:"クリア",week:"週",month:"月",year:"年",previousMonth:"前月 (ページアップキー)",nextMonth:"翌月 (ページダウンキー)",monthSelect:"月を選択",yearSelect:"年を選択",decadeSelect:"年代を選択",yearFormat:"YYYY年",dateFormat:"YYYY年M月D日",dateTimeFormat:"YYYY年M月D日 HH時mm分ss秒",previousYear:"前年 (Controlを押しながら左キー)",nextYear:"翌年 (Controlを押しながら右キー)",previousDecade:"前の年代",nextDecade:"次の年代",previousCentury:"前の世紀",nextCentury:"次の世紀",monthBeforeYear:!1});return ho.default=n,ho}var po={},Qh;function Qy(){if(Qh)return po;Qh=1,Object.defineProperty(po,"__esModule",{value:!0}),po.default=void 0;const e={placeholder:"時間を選択",rangePlaceholder:["開始時間","終了時間"]};return po.default=e,po}var Zh;function Zy(){if(Zh)return mo;Zh=1;var e=Ke().default;Object.defineProperty(mo,"__esModule",{value:!0}),mo.default=void 0;var t=e(PR()),s=e(Qy());const n={lang:Object.assign({placeholder:"日付を選択",yearPlaceholder:"年を選択",quarterPlaceholder:"四半期を選択",monthPlaceholder:"月を選択",weekPlaceholder:"週を選択",rangePlaceholder:["開始日付","終了日付"],rangeYearPlaceholder:["開始年","終了年"],rangeMonthPlaceholder:["開始月","終了月"],rangeQuarterPlaceholder:["開始四半期","終了四半期"],rangeWeekPlaceholder:["開始週","終了週"],shortWeekDays:["日","月","火","水","木","金","土"],shortMonths:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"]},t.default),timePickerLocale:Object.assign({},s.default)};return mo.default=n,mo}var ep;function ER(){if(ep)return uo;ep=1;var e=Ke().default;Object.defineProperty(uo,"__esModule",{value:!0}),uo.default=void 0;var t=e(Zy());return uo.default=t.default,uo}var tp;function RR(){if(tp)return lo;tp=1;var e=Ke().default;Object.defineProperty(lo,"__esModule",{value:!0}),lo.default=void 0;var t=e(MR()),s=e(ER()),n=e(Zy()),o=e(Qy());const a="${label}は有効な${type}ではありません",i={locale:"ja",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.default,global:{placeholder:"選んでください"},Table:{filterTitle:"フィルター",filterConfirm:"OK",filterReset:"リセット",filterEmptyText:"フィルターなし",filterCheckAll:"すべてを選択",filterSearchPlaceholder:"フィルターで検索",emptyText:"データなし",selectAll:"ページ単位で選択",selectInvert:"ページ単位で反転",selectNone:"クリア",selectionAll:"すべてを選択",sortTitle:"ソート",expand:"展開する",collapse:"折り畳む",triggerDesc:"クリックで降順にソート",triggerAsc:"クリックで昇順にソート",cancelSort:"ソートをキャンセル"},Tour:{Next:"次",Previous:"前の",Finish:"仕上げる"},Modal:{okText:"OK",cancelText:"キャンセル",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"キャンセル"},Transfer:{titles:["",""],searchPlaceholder:"ここを検索",itemUnit:"アイテム",itemsUnit:"アイテム",remove:"削除",selectCurrent:"現在のページを選択",removeCurrent:"現在のページを削除",selectAll:"ページ単位で選択",deselectAll:"すべてのデータの選択を解除する",removeAll:"ページ単位で削除",selectInvert:"ページ単位で反転"},Upload:{uploading:"アップロード中...",removeFile:"ファイルを削除",uploadError:"アップロードエラー",previewFile:"ファイルをプレビュー",downloadFile:"ダウンロードファイル"},Empty:{description:"データがありません"},Icon:{icon:"アイコン"},Text:{edit:"編集",copy:"コピー",copied:"コピーされました",expand:"拡大する",collapse:"崩壊"},Form:{optional:"(オプション)",defaultValidateMessages:{default:"${label}のフィールド検証エラー",required:"${label}を入力してください",enum:"${label}は[${enum}]のいずれかである必要があります",whitespace:"${label}は空白文字にすることはできません",date:{format:"${label}の日付形式は不正です",parse:"${label}は日付に変換できません",invalid:"${label}は不正な日付です"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"${label}は${len}文字である必要があります",min:"${label}は${min}文字以上である必要があります",max:"${label}は${max}文字以下である必要があります",range:"${label}は${min}-${max}文字の範囲である必要があります"},number:{len:"${label}は${len}と等しい必要があります",min:"${label}の最小値は${min}です",max:"${label}の最大値は${max}です",range:"${label}は${min}-${max}の範囲である必要があります"},array:{len:"${label}は${len}である必要があります",min:"${label}の最小は${min}です",max:"${label}の最大は${max}です",range:"${label}の合計は${min}-${max}の範囲である必要があります"},pattern:{mismatch:"${label}はパターン${pattern}と一致しません"}}},Image:{preview:"プレビュー"},QRCode:{expired:"QRコードの有効期限が切れました",refresh:"リフレッシュ",scanned:"スキャン済み"},ColorPicker:{presetEmpty:"空の",transparent:"透明",singleColor:"単色",gradientColor:"グラデーション"}};return lo.default=i,lo}var Hl,sp;function AR(){return sp||(sp=1,Hl=RR()),Hl}var IR=AR();const $R=mr(IR);var fo={},go={},np;function FR(){if(np)return go;np=1,Object.defineProperty(go,"__esModule",{value:!0}),go.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 go.default=e,go}var yo={},xo={},bo={},rp;function LR(){if(rp)return bo;rp=1;var e=Ke().default;Object.defineProperty(bo,"__esModule",{value:!0}),bo.default=void 0;var t=e(Sr()),s=wr(),n=(0,t.default)((0,t.default)({},s.commonLocale),{},{locale:"zh_CN",today:"今天",now:"此刻",backToToday:"返回今天",ok:"确定",timeSelect:"选择时间",dateSelect:"选择日期",weekSelect:"选择周",clear:"清除",week:"周",month:"月",year:"年",previousMonth:"上个月 (翻页上键)",nextMonth:"下个月 (翻页下键)",monthSelect:"选择月份",yearSelect:"选择年份",decadeSelect:"选择年代",previousYear:"上一年 (Control键加左方向键)",nextYear:"下一年 (Control键加右方向键)",previousDecade:"上一年代",nextDecade:"下一年代",previousCentury:"上一世纪",nextCentury:"下一世纪",yearFormat:"YYYY年",cellDateFormat:"D",monthBeforeYear:!1});return bo.default=n,bo}var vo={},op;function ex(){if(op)return vo;op=1,Object.defineProperty(vo,"__esModule",{value:!0}),vo.default=void 0;const e={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return vo.default=e,vo}var ap;function tx(){if(ap)return xo;ap=1;var e=Ke().default;Object.defineProperty(xo,"__esModule",{value:!0}),xo.default=void 0;var t=e(LR()),s=e(ex());const n={lang:Object.assign({placeholder:"请选择日期",yearPlaceholder:"请选择年份",quarterPlaceholder:"请选择季度",monthPlaceholder:"请选择月份",weekPlaceholder:"请选择周",rangePlaceholder:["开始日期","结束日期"],rangeYearPlaceholder:["开始年份","结束年份"],rangeMonthPlaceholder:["开始月份","结束月份"],rangeQuarterPlaceholder:["开始季度","结束季度"],rangeWeekPlaceholder:["开始周","结束周"]},t.default),timePickerLocale:Object.assign({},s.default)};return n.lang.ok="确定",xo.default=n,xo}var ip;function OR(){if(ip)return yo;ip=1;var e=Ke().default;Object.defineProperty(yo,"__esModule",{value:!0}),yo.default=void 0;var t=e(tx());return yo.default=t.default,yo}var lp;function DR(){if(lp)return fo;lp=1;var e=Ke().default;Object.defineProperty(fo,"__esModule",{value:!0}),fo.default=void 0;var t=e(FR()),s=e(OR()),n=e(tx()),o=e(ex());const a="${label}不是一个有效的${type}",i={locale:"zh-cn",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.default,global:{placeholder:"请选择"},Table:{filterTitle:"筛选",filterConfirm:"确定",filterReset:"重置",filterEmptyText:"无筛选项",filterCheckAll:"全选",filterSearchPlaceholder:"在筛选项中搜索",emptyText:"暂无数据",selectAll:"全选当页",selectInvert:"反选当页",selectNone:"清空所有",selectionAll:"全选所有",sortTitle:"排序",expand:"展开行",collapse:"关闭行",triggerDesc:"点击降序",triggerAsc:"点击升序",cancelSort:"取消排序"},Modal:{okText:"确定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"结束导览"},Popconfirm:{cancelText:"取消",okText:"确定"},Transfer:{titles:["",""],searchPlaceholder:"请输入搜索内容",itemUnit:"项",itemsUnit:"项",remove:"删除",selectCurrent:"全选当页",removeCurrent:"删除当页",selectAll:"全选所有",deselectAll:"取消全选",removeAll:"删除全部",selectInvert:"反选当页"},Upload:{uploading:"文件上传中",removeFile:"删除文件",uploadError:"上传错误",previewFile:"预览文件",downloadFile:"下载文件"},Empty:{description:"暂无数据"},Icon:{icon:"图标"},Text:{edit:"编辑",copy:"复制",copied:"复制成功",expand:"展开",collapse:"收起"},Form:{optional:"(可选)",defaultValidateMessages:{default:"字段验证错误${label}",required:"请输入${label}",enum:"${label}必须是其中一个[${enum}]",whitespace:"${label}不能为空字符",date:{format:"${label}日期格式无效",parse:"${label}不能转换为日期",invalid:"${label}是一个无效日期"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"${label}须为${len}个字符",min:"${label}最少${min}个字符",max:"${label}最多${max}个字符",range:"${label}须在${min}-${max}字符之间"},number:{len:"${label}必须等于${len}",min:"${label}最小值为${min}",max:"${label}最大值为${max}",range:"${label}须在${min}-${max}之间"},array:{len:"须为${len}个${label}",min:"最少${min}个${label}",max:"最多${max}个${label}",range:"${label}数量须在${min}-${max}之间"},pattern:{mismatch:"${label}与模式不匹配${pattern}"}}},Image:{preview:"预览"},QRCode:{expired:"二维码过期",refresh:"点击刷新",scanned:"已扫描"},ColorPicker:{presetEmpty:"暂无",transparent:"无色",singleColor:"单色",gradientColor:"渐变色"}};return fo.default=i,fo}var Yl,cp;function zR(){return cp||(cp=1,Yl=DR()),Yl}var NR=zR();const BR=mr(NR);var So={},wo={},dp;function WR(){if(dp)return wo;dp=1,Object.defineProperty(wo,"__esModule",{value:!0}),wo.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 wo.default=e,wo}var _o={},To={},ko={},up;function UR(){if(up)return ko;up=1;var e=Ke().default;Object.defineProperty(ko,"__esModule",{value:!0}),ko.default=void 0;var t=e(Sr()),s=wr(),n=(0,t.default)((0,t.default)({},s.commonLocale),{},{locale:"zh_TW",today:"今天",now:"此刻",backToToday:"返回今天",ok:"確定",timeSelect:"選擇時間",dateSelect:"選擇日期",weekSelect:"選擇周",clear:"清除",week:"週",month:"月",year:"年",previousMonth:"上個月 (翻頁上鍵)",nextMonth:"下個月 (翻頁下鍵)",monthSelect:"選擇月份",yearSelect:"選擇年份",decadeSelect:"選擇年代",yearFormat:"YYYY年",dateFormat:"YYYY年M月D日",dateTimeFormat:"YYYY年M月D日 HH時mm分ss秒",previousYear:"上一年 (Control鍵加左方向鍵)",nextYear:"下一年 (Control鍵加右方向鍵)",previousDecade:"上一年代",nextDecade:"下一年代",previousCentury:"上一世紀",nextCentury:"下一世紀",cellDateFormat:"D",monthBeforeYear:!1});return ko.default=n,ko}var Co={},mp;function sx(){if(mp)return Co;mp=1,Object.defineProperty(Co,"__esModule",{value:!0}),Co.default=void 0;const e={placeholder:"請選擇時間"};return Co.default=e,Co}var hp;function nx(){if(hp)return To;hp=1;var e=Ke().default;Object.defineProperty(To,"__esModule",{value:!0}),To.default=void 0;var t=e(UR()),s=e(sx());const n={lang:Object.assign({placeholder:"請選擇日期",yearPlaceholder:"請選擇年份",quarterPlaceholder:"請選擇季度",monthPlaceholder:"請選擇月份",weekPlaceholder:"請選擇周",rangePlaceholder:["開始日期","結束日期"],rangeYearPlaceholder:["開始年份","結束年份"],rangeMonthPlaceholder:["開始月份","結束月份"],rangeQuarterPlaceholder:["開始季度","結束季度"],rangeWeekPlaceholder:["開始周","結束周"]},t.default),timePickerLocale:Object.assign({},s.default)};return n.lang.ok="確 定",To.default=n,To}var pp;function qR(){if(pp)return _o;pp=1;var e=Ke().default;Object.defineProperty(_o,"__esModule",{value:!0}),_o.default=void 0;var t=e(nx());return _o.default=t.default,_o}var fp;function HR(){if(fp)return So;fp=1;var e=Ke().default;Object.defineProperty(So,"__esModule",{value:!0}),So.default=void 0;var t=e(WR()),s=e(qR()),n=e(nx()),o=e(sx());const a="${label}不是一個有效的${type}",i={locale:"zh-tw",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.default,global:{placeholder:"請選擇"},Table:{filterTitle:"篩選器",filterConfirm:"確定",filterReset:"重置",filterEmptyText:"無篩選項",filterCheckAll:"全選",filterSearchPlaceholder:"在篩選項中搜尋",emptyText:"暫無數據",selectAll:"全部選取",selectInvert:"反向選取",selectNone:"清空所有",selectionAll:"全選所有",sortTitle:"排序",expand:"展開行",collapse:"關閉行",triggerDesc:"點擊降序",triggerAsc:"點擊升序",cancelSort:"取消排序"},Modal:{okText:"確定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"結束導覽"},Popconfirm:{okText:"確定",cancelText:"取消"},Transfer:{titles:["",""],searchPlaceholder:"搜尋資料",itemUnit:"項目",itemsUnit:"項目",remove:"删除",selectCurrent:"全選當頁",removeCurrent:"删除當頁",selectAll:"全選所有",removeAll:"删除全部",selectInvert:"反選當頁"},Upload:{uploading:"正在上傳...",removeFile:"刪除檔案",uploadError:"上傳失敗",previewFile:"檔案預覽",downloadFile:"下载文件"},Empty:{description:"無此資料"},Icon:{icon:"圖標"},Text:{edit:"編輯",copy:"複製",copied:"複製成功",expand:"展開",collapse:"收起"},Form:{optional:"(可選)",defaultValidateMessages:{default:"字段驗證錯誤${label}",required:"請輸入${label}",enum:"${label}必須是其中一個[${enum}]",whitespace:"${label}不能為空字符",date:{format:"${label}日期格式無效",parse:"${label}不能轉換為日期",invalid:"${label}是一個無效日期"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"${label}須為${len}個字符",min:"${label}最少${min}個字符",max:"${label}最多${max}個字符",range:"${label}須在${min}-${max}字符之間"},number:{len:"${label}必須等於${len}",min:"${label}最小值為${min}",max:"${label}最大值為${max}",range:"${label}須在${min}-${max}之間"},array:{len:"須為${len}個${label}",min:"最少${min}個${label}",max:"最多${max}個${label}",range:"${label}數量須在${min}-${max}之間"},pattern:{mismatch:"${label}與模式不匹配${pattern}"}}},Image:{preview:"預覽"},QRCode:{expired:"二維碼過期",refresh:"點擊刷新",scanned:"已掃描"},ColorPicker:{presetEmpty:"暫無",transparent:"透明",singleColor:"單色",gradientColor:"漸變色"}};return So.default=i,So}var Xl,gp;function YR(){return gp||(gp=1,Xl=HR()),Xl}var XR=YR();const VR=mr(XR),KR=e=>{switch(e){case"zh-CN":return BR;case"zh-TW":return VR;case"fr-FR":return vR;case"ja-JP":return $R;case"hi-IN":return jR;default:return hR}},GR="copilot_ui_theme_v1",JR={colorPrimary:"#0d9488",colorPrimaryHover:"#14b8a6",colorPrimaryActive:"#0f766e",colorInfo:"#0d9488",colorLink:"#0d9488",colorLinkHover:"#14b8a6",colorLinkActive:"#0f766e",colorSuccess:"#10b981",colorWarning:"#f59e0b",colorError:"#ef4444",colorText:"#0f172a",colorTextSecondary:"#475569",colorTextTertiary:"#64748b",colorTextDisabled:"#94a3b8",colorTextLightSolid:"#ffffff",colorBorder:"#d1e3e0",colorBorderSecondary:"#e2f0ee",colorFill:"#f0fdfa",colorFillSecondary:"#f7fdfb",colorFillTertiary:"rgba(255, 255, 255, 0.82)",colorFillQuaternary:"transparent",colorBgLayout:"#f0fdfa",colorBgContainer:"rgba(255, 255, 255, 0.82)",colorBgElevated:"rgba(255, 255, 255, 0.9)",colorBgSpotlight:"rgba(13, 148, 136, 0.16)",colorPrimaryBg:"#f0fdfa",colorPrimaryBgHover:"#ccfbf1",colorPrimaryBorder:"#99f6e4",borderRadius:10,borderRadiusLG:18,borderRadiusSM:10,boxShadow:"0 12px 36px rgba(15, 118, 110, 0.10), 0 6px 18px rgba(15, 23, 42, 0.06)",boxShadowSecondary:"0 20px 48px rgba(15, 118, 110, 0.12), 0 8px 24px rgba(15, 23, 42, 0.08)"},QR={colorPrimary:"#2dd4bf",colorPrimaryHover:"#5eead4",colorPrimaryActive:"#0d9488",colorInfo:"#2dd4bf",colorLink:"#2dd4bf",colorLinkHover:"#5eead4",colorLinkActive:"#0d9488",colorSuccess:"#34d399",colorWarning:"#fbbf24",colorError:"#f87171",colorText:"#e5edf8",colorTextSecondary:"#b7c4d6",colorTextTertiary:"#8d9bb0",colorTextDisabled:"#627085",colorBorder:"rgba(255, 255, 255, 0.10)",colorBorderSecondary:"rgba(255, 255, 255, 0.06)",colorFill:"#0c1a17",colorFillSecondary:"#091412",colorFillTertiary:"rgba(15, 23, 42, 0.74)",colorFillQuaternary:"transparent",colorBgLayout:"#070e0c",colorBgContainer:"rgba(11, 22, 18, 0.76)",colorBgElevated:"rgba(15, 30, 25, 0.9)",colorBgSpotlight:"rgba(13, 148, 136, 0.20)",colorPrimaryBg:"rgba(13, 148, 136, 0.14)",colorPrimaryBgHover:"rgba(13, 148, 136, 0.18)",colorPrimaryBorder:"rgba(45, 212, 191, 0.28)",borderRadius:10,borderRadiusLG:18,borderRadiusSM:10,boxShadow:"0 16px 40px rgba(2, 6, 23, 0.42), 0 8px 20px rgba(15, 23, 42, 0.24)",boxShadowSecondary:"0 24px 56px rgba(2, 6, 23, 0.5), 0 10px 28px rgba(15, 23, 42, 0.28)"},ZR={Tag:{defaultBg:"rgba(13, 148, 136, 0.1)",defaultColor:"#0f766e"},Table:{bodySortBg:"rgba(13, 148, 136, 0.08)"}},eA={Tag:{defaultBg:"rgba(45, 212, 191, 0.18)",defaultColor:"#ccfbf1"},Table:{bodySortBg:"rgba(45, 212, 191, 0.14)"}};function tA(){const{t:e}=se(),t=Dn(p=>p.themeMode),s=Dn(p=>p.setThemeMode),[n,o]=m.useState(()=>ux()),[a,i]=m.useState(null),[l,c]=m.useState(null),[d,u]=m.useState(0);if(m.useEffect(()=>{localStorage.setItem(GR,t)},[t]),m.useEffect(()=>{localStorage.setItem(mx,n),Kt.changeLanguage(n)},[n]),m.useEffect(()=>{let p=!1;const y=Date.now(),g=async()=>{try{const b=await Pt.getInstance().getSetupStatus();if(p)return;c(null),i(b.is_complete)}catch(f){if(p)return;const b=Date.now()-y;if(b>=2e4){const w=yr(),C=f instanceof Error&&f.message.trim()?f.message:"Unknown error";c(e("app.backendNotReachable",{baseUrl:w,message:C}));return}const S=Math.min(500+Math.floor(b/2),2e3);setTimeout(()=>{p||g()},S)}};return g(),()=>{p=!0}},[d,e]),m.useEffect(()=>{document.body.setAttribute("data-theme",t)},[t]),m.useEffect(()=>{var y;const p=(y=window.__TAURI_INTERNALS__)==null?void 0:y.invoke;typeof p=="function"&&p("set_window_theme",{theme:t}).catch(g=>{console.warn("[App] Failed to sync native window theme:",g)})},[t]),m.useEffect(()=>{a&&uv()},[a]),a===null)return l?r.jsxs("div",{style:{padding:40,textAlign:"center"},children:[r.jsx("div",{style:{marginBottom:12},children:l}),r.jsx(B,{type:"primary",onClick:()=>{c(null),i(null),u(p=>p+1)},children:e("app.retry")})]}):r.jsx("div",{style:{padding:40,textAlign:"center"},children:e("app.loading")});const h=a?r.jsx(sR,{themeMode:t,onThemeModeChange:s,locale:n,onLocaleChange:o}):r.jsx(nR,{});return r.jsx(tb,{locale:KR(n),theme:{token:t==="dark"?QR:JR,algorithm:t==="dark"?xe.darkAlgorithm:xe.defaultAlgorithm,components:t==="dark"?eA:ZR},children:r.jsx(ts,{children:r.jsx(yi,{name:"App",children:r.jsx("div",{style:{position:"relative"},children:h})})})})}const yA=Object.freeze(Object.defineProperty({__proto__:null,default:tA},Symbol.toStringTag,{value:"Module"}));export{yA as A,Uo as C,Te as a,He as d,Nn as p,z as u,$m as v,yk as w};
|