@bigduu/lotus 2026.4.5 → 2026.4.24
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-B5iMQtsl.css +1 -0
- package/dist/assets/App-hwramX5g.js +247 -0
- package/dist/assets/{_basePickBy-Dqp2ckVn.js → _basePickBy-CAoCwABK.js} +1 -1
- package/dist/assets/{_baseUniq-BUM12Ss4.js → _baseUniq-Bq19xc1S.js} +1 -1
- package/dist/assets/{architectureDiagram-VXUJARFQ-BpD9cUnY.js → architectureDiagram-VXUJARFQ-DH9ObRiY.js} +1 -1
- package/dist/assets/{blockDiagram-VD42YOAC-DEjFbRgv.js → blockDiagram-VD42YOAC-CP3m28wi.js} +1 -1
- package/dist/assets/{c4Diagram-YG6GDRKO-0zi7mvhd.js → c4Diagram-YG6GDRKO-CbmYyM5L.js} +1 -1
- package/dist/assets/{chunk-4BX2VUAB-Ddghj6OV.js → chunk-4BX2VUAB-BJoIdufz.js} +1 -1
- package/dist/assets/{chunk-55IACEB6-DjZcM2Bg.js → chunk-55IACEB6-CmtUdzK-.js} +1 -1
- package/dist/assets/{chunk-B4BG7PRW-Co42sS8K.js → chunk-B4BG7PRW-qWjYh2LL.js} +1 -1
- package/dist/assets/{chunk-DI55MBZ5-LsurJteE.js → chunk-DI55MBZ5-eGANHkxs.js} +1 -1
- package/dist/assets/{chunk-FMBD7UC4-DiR6-e10.js → chunk-FMBD7UC4-BNsHHocw.js} +1 -1
- package/dist/assets/{chunk-QN33PNHL-CBDhq4-P.js → chunk-QN33PNHL-ChHOvjSW.js} +1 -1
- package/dist/assets/{chunk-QZHKN3VN-BcUNnjmn.js → chunk-QZHKN3VN-CITQwv7S.js} +1 -1
- package/dist/assets/{chunk-TZMSLE5B-CD1yZj6g.js → chunk-TZMSLE5B-CPsFUKG8.js} +1 -1
- package/dist/assets/classDiagram-2ON5EDUG-BLyCi-nw.js +1 -0
- package/dist/assets/classDiagram-v2-WZHVMYZB-BLyCi-nw.js +1 -0
- package/dist/assets/clone-ComhU-wZ.js +1 -0
- package/dist/assets/{cose-bilkent-S5V4N54A-B7QH9b8b.js → cose-bilkent-S5V4N54A-CcSYaFZc.js} +1 -1
- package/dist/assets/{dagre-6UL2VRFP-bN17fB73.js → dagre-6UL2VRFP-BkRz5nXH.js} +1 -1
- package/dist/assets/{diagram-PSM6KHXK-DKulEHRw.js → diagram-PSM6KHXK-un46d5rN.js} +1 -1
- package/dist/assets/{diagram-QEK2KX5R-j4St2Wso.js → diagram-QEK2KX5R-DnPF18nM.js} +1 -1
- package/dist/assets/{diagram-S2PKOQOG-DXlK8Mf9.js → diagram-S2PKOQOG-DSS2GWRd.js} +1 -1
- package/dist/assets/{erDiagram-Q2GNP2WA-BHcDHhwN.js → erDiagram-Q2GNP2WA-DpHD5U-k.js} +1 -1
- package/dist/assets/{flowDiagram-NV44I4VS-DNrm79Yr.js → flowDiagram-NV44I4VS-DrZ8ypai.js} +1 -1
- package/dist/assets/{ganttDiagram-JELNMOA3-DcHidoKj.js → ganttDiagram-JELNMOA3-B_xPgWyy.js} +1 -1
- package/dist/assets/{gitGraphDiagram-V2S2FVAM-CPCXl6MV.js → gitGraphDiagram-V2S2FVAM-epgjFrpG.js} +1 -1
- package/dist/assets/{graph-Cy2rLZk-.js → graph-DOJ-9LTd.js} +1 -1
- package/dist/assets/{index-oVXhS3BO.js → index-B9rhKJTy.js} +1 -1
- package/dist/assets/{index-BKrbsGr5.js → index-BAxa3Q-a.js} +1 -1
- package/dist/assets/{index-BAfth62E.js → index-BoZANqat.js} +1 -1
- package/dist/assets/{index-Cd0gm8C7.js → index-CYeT_vWc.js} +1 -1
- package/dist/assets/{index-Bd-pro36.js → index-Dx8glliP.js} +1 -1
- package/dist/assets/{index.es-CAbTTDez.js → index.es-DdtT3adr.js} +1 -1
- package/dist/assets/{infoDiagram-HS3SLOUP-BZqSW0xG.js → infoDiagram-HS3SLOUP-Bfqo6Soh.js} +1 -1
- package/dist/assets/{journeyDiagram-XKPGCS4Q--y_9wXpx.js → journeyDiagram-XKPGCS4Q-ds0fAcWY.js} +1 -1
- package/dist/assets/{kanban-definition-3W4ZIXB7-p0s79n5j.js → kanban-definition-3W4ZIXB7-Co5aVYyG.js} +1 -1
- package/dist/assets/{layout-BVyH__KO.js → layout-D1Yhgdei.js} +1 -1
- package/dist/assets/main-CNnWZQZu.js +10 -0
- package/dist/assets/{mindmap-definition-VGOIOE7T-gPtTWSZ4.js → mindmap-definition-VGOIOE7T-cNvtv2zC.js} +1 -1
- package/dist/assets/{pieDiagram-ADFJNKIX-DiMr3lFK.js → pieDiagram-ADFJNKIX-DngPz61w.js} +1 -1
- package/dist/assets/{quadrantDiagram-AYHSOK5B-CcRJwEm3.js → quadrantDiagram-AYHSOK5B-7leTLQVG.js} +1 -1
- package/dist/assets/{requirementDiagram-UZGBJVZJ-BJF8xk4W.js → requirementDiagram-UZGBJVZJ-DXj0BS3x.js} +1 -1
- package/dist/assets/{sankeyDiagram-TZEHDZUN-WtpnGB-d.js → sankeyDiagram-TZEHDZUN-qjguZnOp.js} +1 -1
- package/dist/assets/{sequenceDiagram-WL72ISMW-BFIpMf3h.js → sequenceDiagram-WL72ISMW-BwQcGTsb.js} +1 -1
- package/dist/assets/{stateDiagram-FKZM4ZOC-CPIa7zUD.js → stateDiagram-FKZM4ZOC-Cp9UZoea.js} +1 -1
- package/dist/assets/stateDiagram-v2-4FDKWEC3-21Xg0qMu.js +1 -0
- package/dist/assets/{timeline-definition-IT6M3QCI-D36RXKRq.js → timeline-definition-IT6M3QCI-wdWWliq4.js} +1 -1
- package/dist/assets/{treemap-GDKQZRPO-C5etdcHn.js → treemap-GDKQZRPO-bLv7ImbF.js} +1 -1
- package/dist/assets/vendor-antd-DzhFcYgt.js +502 -0
- package/dist/assets/{vendor-charts-JINLUr-T.js → vendor-charts-BvOlsian.js} +1 -1
- package/dist/assets/{vendor-markdown-BtOz1kLl.js → vendor-markdown-DYfLXXRA.js} +1 -1
- package/dist/assets/{vendor-mermaid-7RLh-Mwz.js → vendor-mermaid-DDHJCH-e.js} +4 -4
- package/dist/assets/{vendor-pdf-5uNnaI3-.js → vendor-pdf-Bg81_snq.js} +4 -4
- package/dist/assets/{xychartDiagram-PRI3JC2R-CHD9X5Zq.js → xychartDiagram-PRI3JC2R-B8RUcHm3.js} +1 -1
- package/dist/index.html +3 -3
- package/package.json +2 -1
- package/dist/assets/App-CdZyL2eF.js +0 -247
- package/dist/assets/App-D7QWpCG1.css +0 -1
- package/dist/assets/classDiagram-2ON5EDUG-XasLIOdg.js +0 -1
- package/dist/assets/classDiagram-v2-WZHVMYZB-XasLIOdg.js +0 -1
- package/dist/assets/clone-CHqNgpti.js +0 -1
- package/dist/assets/main-ik_6ertt.js +0 -10
- package/dist/assets/stateDiagram-v2-4FDKWEC3-C3L-LCup.js +0 -1
- package/dist/assets/vendor-antd-BlMATH2j.js +0 -502
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-BAxa3Q-a.js","./vendor-markdown-DYfLXXRA.js","./vendor-i18n-BNURlJ23.js","./vendor-antd-DzhFcYgt.js","./main-CNnWZQZu.js","./main-B6snAd4S.css","./vendor-charts-BvOlsian.js","./vendor-mermaid-DDHJCH-e.js","./index-CYeT_vWc.js","./index-Dx8glliP.js","./index-Bi-vGirQ.css","./index-BoZANqat.js","./index-B9rhKJTy.js","./index-BmjFP0ha.js","./core-Cfh-QHsP.js","./index-_XI0Qq6F.js","./vendor-pdf-Bg81_snq.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var Gb=Object.defineProperty;var Jb=(e,t,s)=>t in e?Gb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var He=(e,t,s)=>Jb(e,typeof t!="symbol"?t+"":t,s);import{j as r,M as hs,r as Ii,h as fr,_ as Dt,S as mt,a as lf,t as cf,p as df,b as Qb,c as Qc,d as Zb,m as uf,s as ex,y as mf,e as hf,f as Zc,g as ed,i as pf}from"./vendor-markdown-DYfLXXRA.js";import{a as m,R as ut,i as es,u as ne,g as vr}from"./vendor-i18n-BNURlJ23.js";import{r as tx,A as sx}from"./main-CNnWZQZu.js";import{S as X,B as Y,C as ee,n as le,L as nt,Y as ts,T as oe,Z as nx,$ as td,a0 as ss,l as fe,M as Lt,E as kt,a1 as Sr,t as he,a2 as sc,a3 as sd,j as ca,O as gr,a4 as ff,a5 as rx,k as dn,H as ox,p as wr,a6 as zn,a7 as ax,I as me,K as G,a8 as Wt,a9 as Ws,i as Us,aa as da,o as ke,ab as ix,ac as lx,ad as Ot,ae as gf,af as sa,ag as cx,ah as $i,A as Xe,F as Z,v as ps,ai as ui,aj as Pe,ak as it,al as Gt,am as Oe,an as At,ao as rt,ap as dx,V as Rt,aq as ns,ar as ux,as as nd,P as mi,at as ua,au as yf,av as Di,aw as lu,ax as qs,u as Ms,ay as mx,az as Li,aA as nc,aB as Pt,aC as hx,aD as Xs,aE as ot,aF as rd,aG as cu,Q as Hs,aH as Ys,aI as rc,aJ as ja,aK as px,aL as fx,G as gx,aM as Dn,aN as bf,aO as du,aP as yr,aQ as yx,aR as bx,m as br,aS as od,U as Oi,aT as xx,aU as vx,aV as xf,aW as ad,aX as vf,aY as Sx,aZ as wx,a_ as _x,a$ as Tx,b0 as kx,b1 as jx,b2 as Cx,b3 as Sf,b4 as Mx,x as wf,q as hi,b5 as id,w as Px,b6 as Ex,b7 as Rx,N as Ax,b8 as Ix,b9 as $x,ba as Dx,bb as Lx,bc as _f,bd as Ox,be as Fx,bf as zx,bg as ld,bh as Nx,bi as Bx,bj as pi,bk as uu,bl as Tf,bm as mu,bn as Wx,bo as Ux,bp as qx,bq as Hx,br as kf,bs as Yx,bt as Xx,bu as Vx,bv as hu,bw as pu}from"./vendor-antd-DzhFcYgt.js";import{Z as _r,_ as cd,$ as ma,a0 as ha,a1 as pa,a2 as Tr,a3 as dd,a4 as fi,a5 as jf,a6 as mr,a7 as Kx,a8 as Gx,a9 as Jx}from"./vendor-charts-BvOlsian.js";import{b9 as ud}from"./vendor-mermaid-DDHJCH-e.js";function Cf(e){const[t,s]=m.useState(()=>typeof window<"u"?window.matchMedia(e).matches:!1);return m.useEffect(()=>{if(typeof window>"u")return;const n=window.matchMedia(e);s(n.matches);const o=a=>{s(a.matches)};return n.addEventListener?n.addEventListener("change",o):n.addListener(o),()=>{n.removeEventListener?n.removeEventListener("change",o):n.removeListener(o)}},[e]),t}function md(){return Cf("(max-width: 768px)")}const Qx=({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(X,{...a,children:e.map(i=>r.jsx(Y,{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))})},Zx=(e,t)=>({key:"cancel",text:t||"Cancel",type:"default",onClick:e}),ev=(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}),fu=e=>{let t;const s=new Set,n=(d,u)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const p=t;t=u??(typeof h!="object"||h===null)?h:Object.assign({},t,h),s.forEach(g=>g(t,p))}},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},tv=e=>e?fu(e):fu,sv=e=>e;function nv(e,t=sv){const s=ut.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return ut.useDebugValue(s),s}const gu=e=>{const t=tv(e),s=n=>nv(t,n);return Object.assign(s,t),s},un=e=>e?gu(e):gu,yu={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},na=new Map,Ca=e=>{const t=na.get(e);return t?Object.fromEntries(Object.entries(t.stores).map(([s,n])=>[s,n.getState()])):{}},rv=(e,t,s)=>{if(e===void 0)return{type:"untracked",connection:t.connect(s)};const n=na.get(s.name);if(n)return{type:"tracked",store:e,...n};const o={connection:t.connect(s),stores:{}};return na.set(s.name,o),{type:"tracked",store:e,...o}},ov=(e,t)=>{if(t===void 0)return;const s=na.get(e);s&&(delete s.stores[t],Object.keys(s.stores).length===0&&na.delete(e))},av=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]},iv=(e,t={})=>(s,n,o)=>{const{enabled:a,anonymousActionType:i,store:l,...c}=t;let d;try{d=(a??(yu?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!d)return e(s,n,o);const{connection:u,...h}=rv(l,d,c);let p=!0;o.setState=(f,v,b)=>{const x=s(f,v);if(!p)return x;const _=b===void 0?{type:i||av(new Error().stack)||"anonymous"}:typeof b=="string"?{type:b}:b;return l===void 0?(u==null||u.send(_,n()),x):(u==null||u.send({..._,type:`${l}/${_.type}`},{...Ca(c.name),[l]:o.getState()}),x)},o.devtools={cleanup:()=>{u&&typeof u.unsubscribe=="function"&&u.unsubscribe(),ov(c.name,l)}};const g=(...f)=>{const v=p;p=!1,s(...f),p=v},y=e(o.setState,n,o);if(h.type==="untracked"?u==null||u.init(y):(h.stores[h.store]=o,u==null||u.init(Object.fromEntries(Object.entries(h.stores).map(([f,v])=>[f,f===h.store?y:v.getState()])))),o.dispatchFromDevtools&&typeof o.dispatch=="function"){let f=!1;const v=o.dispatch;o.dispatch=(...b)=>{(yu?"production":void 0)!=="production"&&b[0].type==="__setState"&&!f&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),f=!0),v(...b)}}return u.subscribe(f=>{var v;switch(f.type){case"ACTION":if(typeof f.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return Qi(f.payload,b=>{if(b.type==="__setState"){if(l===void 0){g(b.state);return}Object.keys(b.state).length!==1&&console.error(`
|
|
4
|
+
[zustand devtools middleware] Unsupported __setState action format.
|
|
5
|
+
When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
|
|
6
|
+
and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
|
|
7
|
+
`);const x=b.state[l];if(x==null)return;JSON.stringify(o.getState())!==JSON.stringify(x)&&g(x);return}o.dispatchFromDevtools&&typeof o.dispatch=="function"&&o.dispatch(b)});case"DISPATCH":switch(f.payload.type){case"RESET":return g(y),l===void 0?u==null?void 0:u.init(o.getState()):u==null?void 0:u.init(Ca(c.name));case"COMMIT":if(l===void 0){u==null||u.init(o.getState());return}return u==null?void 0:u.init(Ca(c.name));case"ROLLBACK":return Qi(f.state,b=>{if(l===void 0){g(b),u==null||u.init(o.getState());return}g(b[l]),u==null||u.init(Ca(c.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return Qi(f.state,b=>{if(l===void 0){g(b);return}JSON.stringify(o.getState())!==JSON.stringify(b[l])&&g(b[l])});case"IMPORT_STATE":{const{nextLiftedState:b}=f.payload,x=(v=b.computedStates.slice(-1)[0])==null?void 0:v.state;if(!x)return;g(l===void 0?x:x[l]),u==null||u.send(null,b);return}case"PAUSE_RECORDING":return p=!p}return}}),y},lv=iv,Qi=(e,t)=>{let s;try{s=JSON.parse(e)}catch(n){console.error("[zustand devtools middleware] Could not parse the received json",n)}s!==void 0&&t(s)},cv=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 g=i(p);if(!u(h,g)){const y=h;l(h=g,y)}},c!=null&&c.fireImmediately&&l(h,h)}return o(d)},e(t,s,n)},dv=cv;function uv(e,t){let s;try{s=e()}catch{return}return{getItem:o=>{var a;const i=c=>c===null?null:JSON.parse(c,void 0),l=(a=s.getItem(o))!=null?a:null;return l instanceof Promise?l.then(i):i(l)},setItem:(o,a)=>s.setItem(o,JSON.stringify(a,void 0)),removeItem:o=>s.removeItem(o)}}const oc=e=>t=>{try{const s=e(t);return s instanceof Promise?s:{then(n){return oc(n)(s)},catch(n){return this}}}catch(s){return{then(n){return this},catch(n){return oc(n)(s)}}}},mv=(e,t)=>(s,n,o)=>{let a={storage:uv(()=>localStorage),partialize:f=>f,version:0,merge:(f,v)=>({...v,...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,v)=>{h(f,v),u()};const p=e((...f)=>{s(...f),u()},n,o);o.getInitialState=()=>p;let g;const y=()=>{var f,v;if(!d)return;i=!1,l.forEach(x=>{var _;return x((_=n())!=null?_:p)});const b=((v=a.onRehydrateStorage)==null?void 0:v.call(a,(f=n())!=null?f:p))||void 0;return oc(d.getItem.bind(d))(a.name).then(x=>{if(x)if(typeof x.version=="number"&&x.version!==a.version){if(a.migrate){const _=a.migrate(x.state,x.version);return _ instanceof Promise?_.then(w=>[!0,w]):[!0,_]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,x.state];return[!1,void 0]}).then(x=>{var _;const[w,k]=x;if(g=a.merge(k,(_=n())!=null?_:p),s(g,!0),w)return u()}).then(()=>{b==null||b(g,void 0),g=n(),i=!0,c.forEach(x=>x(g))}).catch(x=>{b==null||b(void 0,x)})};return o.persist={setOptions:f=>{a={...a,...f},f.storage&&(d=f.storage)},clearStorage:()=>{d==null||d.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>y(),hasHydrated:()=>i,onHydrate:f=>(l.add(f),()=>{l.delete(f)}),onFinishHydration:f=>(c.add(f),()=>{c.delete(f)})},a.skipHydration||y(),g||p},hv=mv,Mf=()=>!1,Pf=e=>{if(!Mf())return!1;try{return localStorage.getItem(e)==="1"}catch{return!1}},pv=()=>Pf("bodhi_debug_ui_layout"),Jt=(e,t)=>{pv()&&console.log(`[ui-layout] ${e}`,t??"")},st=(e,t,...s)=>{Mf()&&Pf("bodhi_debug_verbose")&&console.log(`${e} ${t}`,...s)};var Zi={};const el="copilot_backend_base_url",Ef="http://127.0.0.1:9562/v1",fv=9562,Nn=e=>e.trim().replace(/\/+$/,""),gv=()=>{const t=Zi==null?void 0:Zi.VITE_BACKEND_BASE_URL;return t?Nn(t):null},fa=()=>{const e=globalThis.location;if(!e)return null;const t=typeof e.protocol=="string"?e.protocol:"",s=typeof e.hostname=="string"?e.hostname:"";return!t||!s?null:{protocol:t,hostname:s}},hd=e=>{const t=e.trim().toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="::1"},yv=(e=fa())=>(e==null?void 0:e.protocol.toLowerCase())==="https:",bv=e=>{try{return new URL(Nn(e)).protocol.toLowerCase()==="http:"}catch{return!1}},xv=e=>{try{const t=new URL(Nn(e));return hd(t.hostname)}catch{return!1}},vv=(e=fa())=>{if(!e)return null;const t=e.protocol.toLowerCase(),s=e.hostname.trim();return s?t==="https:"?Nn(`https://${s}/v1`):t==="http:"?Nn(`http://${s}/v1`):null:null},Sv=(e,t=fa())=>{if(!t)return!1;const s=t.hostname.trim();return s?yv(t)&&bv(e)?!0:hd(s)?!1:xv(e):!1},wv=(e=fa())=>{if(!e)return null;const t=e.protocol.toLowerCase();if(t!=="http:"&&t!=="https:")return null;const s=e.hostname.trim();return s?t==="https:"?vv(e):hd(s)?Ef:Nn(`http://${s}:${fv}/v1`):null},_v=()=>{const e=gv();return e||(wv()??Ef)},kr=()=>{const e=fa(),t=localStorage.getItem(el);if(t){const s=Nn(t);if(Sv(s,e))console.warn("Ignoring stored backend override because it is incompatible with the current page origin:",s),localStorage.removeItem(el);else try{return new URL(s),s}catch{console.warn("Invalid stored backend URL, using default:",s),localStorage.removeItem(el)}}return _v()};class Bn extends Error{constructor(t,s,n,o){super(t),this.status=s,this.statusText=n,this.body=o,this.name="ApiError"}}function Tv(e){return e instanceof Bn}class pd{constructor(t={}){He(this,"baseUrl");He(this,"defaultHeaders");this.baseUrl=t.baseUrl??this.resolveBaseUrl(),this.defaultHeaders=t.defaultHeaders??{"Content-Type":"application/json"}}resolveBaseUrl(){const t=kr().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 Bn(l,t.status,t.statusText,i)}return t.status===204?void 0:(((a=(o=t.headers)==null?void 0:o.get)==null?void 0:a.call(o,"content-type"))||"").includes("application/json")?t.json():typeof t.text=="function"?await t.text():t.json()}delay(t){return new Promise(s=>setTimeout(s,t))}async fetchWithRetry(t,s,n=3){let o=null;for(let a=0;a<n;a++)try{const i=await fetch(t,s);if(i.status>=500&&a<n-1){const l=1e3*Math.pow(2,a);console.warn(`Request failed with ${i.status}, retrying in ${l}ms (attempt ${a+1}/${n})`),await this.delay(l);continue}return i}catch(i){if(o=i,a<n-1){const l=1e3*Math.pow(2,a);console.warn(`Network error: ${o.message}, retrying in ${l}ms (attempt ${a+1}/${n})`),await this.delay(l)}}throw o||new Error("Max retries exceeded")}async get(t,s){const n=this.buildUrl(t),o=new AbortController,a=setTimeout(()=>o.abort(),3e4);try{const i=await this.fetchWithRetry(n,{...s,method:"GET",headers:{...this.defaultHeaders,...s==null?void 0:s.headers},credentials:"include",signal:o.signal},3);return this.handleResponse(i)}finally{clearTimeout(a)}}async post(t,s,n){const o=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(o,{...n,method:"POST",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",body:s?JSON.stringify(s):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async put(t,s,n){const o=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(o,{...n,method:"PUT",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",body:s?JSON.stringify(s):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async patch(t,s,n){const o=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(o,{...n,method:"PATCH",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",body:s?JSON.stringify(s):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async delete(t,s){const n=this.buildUrl(t),o=new AbortController,a=setTimeout(()=>o.abort(),3e4);try{const i=await this.fetchWithRetry(n,{...s,method:"DELETE",headers:{...this.defaultHeaders,...s==null?void 0:s.headers},credentials:"include",signal:o.signal},3);return this.handleResponse(i)}finally{clearTimeout(a)}}async request(t,s,n){const o=this.buildUrl(s),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(o,{...n,method:t,headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async fetchRaw(t,s){const n=this.buildUrl(t),o=await fetch(n,{...s,headers:{...this.defaultHeaders,...s==null?void 0:s.headers},credentials:"include"});if(!o.ok)throw new Bn(`API request failed: ${o.statusText}`,o.status,o.statusText);return o}}const xe=new pd,pe=new pd({baseUrl:(()=>{let e=kr().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`})()});function kv(e){return e instanceof Bn}const Pn=class Pn{static getInstance(){return Pn.instance||(Pn.instance=new Pn),Pn.instance}async sendMessage(t){return pe.post("chat",t)}async execute(t,s,n,o,a){const i={};return s&&(i.model=s),n&&(i.reasoning_effort=n),o&&(i.client_sync=o),a&&(i.model_ref=a,i.provider=a.provider),pe.post(`execute/${t}`,i)}async listSessions(){return pe.get("sessions")}async createSession(t){return pe.post("sessions",t)}async patchSession(t,s){const n=encodeURIComponent(t);await pe.patch(`sessions/${n}`,s)}async getSessionSystemPrompt(t){const s=encodeURIComponent(t);return pe.get(`sessions/${s}/system-prompt`)}async clearSession(t){const s=encodeURIComponent(t);await pe.post(`sessions/${s}/clear`)}async runProjectDream(t){const s=encodeURIComponent(t);return pe.post(`sessions/${s}/project-dream/run`)}async truncateSessionMessages(t,s){const n=encodeURIComponent(t);return pe.post(`sessions/${n}/messages/truncate`,s)}async restoreSessionState(t,s){const n=encodeURIComponent(t);return pe.post(`sessions/${n}/restore`,s)}async patchSessionMessage(t,s,n){const o=encodeURIComponent(t),a=encodeURIComponent(s);await pe.patch(`sessions/${o}/messages/${a}`,n)}async deleteSessionMessage(t,s){const n=encodeURIComponent(t),o=encodeURIComponent(s);await pe.delete(`sessions/${n}/messages/${o}`)}async cleanupSessions(t,s){await pe.post("sessions/cleanup",{mode:t,keep_pinned:s})}async devResetSessions(){await pe.post("dev/reset")}async listSchedules(){return pe.get("schedules")}async createSchedule(t){return pe.post("schedules",t)}async patchSchedule(t,s){const n=encodeURIComponent(t);return pe.patch(`schedules/${n}`,s)}async deleteSchedule(t){const s=encodeURIComponent(t);await pe.delete(`schedules/${s}`)}async runScheduleNow(t){const s=encodeURIComponent(t);await pe.post(`schedules/${s}/run`)}async listScheduleSessions(t){const s=encodeURIComponent(t);return pe.get(`schedules/${s}/sessions`)}async listScheduleRuns(t){const s=encodeURIComponent(t);return pe.get(`schedules/${s}/runs`)}async subscribeToEvents(t,s,n){var a;const o=n==null?void 0:n.signal;st("[AgentClient]","[AgentClient] Subscribing to events for session:",t);try{const i=await pe.fetchRaw(`events/${t}`,{signal:o});if(st("[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 g of p)if(g.startsWith("data: ")){const y=g.slice(6);if(y==="[DONE]")return;try{const f=JSON.parse(y);this.handleEvent(f,s)}catch(f){console.warn("Failed to parse event:",y,f)}}}}finally{l.releaseLock()}}catch(i){if(o!=null&&o.aborted){st("[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,g,y,f,v,b,x,_,w,k,C,E;switch(t.type){case"token":(n=s.onToken)==null||n.call(s,t.content||"");break;case"reasoning_token":(o=s.onReasoningToken)==null||o.call(s,t.content||"");break;case"tool_token":(a=s.onToolToken)==null||a.call(s,t.tool_call_id||"",t.content||"");break;case"tool_start":(i=s.onToolStart)==null||i.call(s,t.tool_call_id||"",t.tool_name||"",t.arguments||{});break;case"tool_complete":t.result&&((l=s.onToolComplete)==null||l.call(s,t.tool_call_id||"",t.result));break;case"tool_error":(c=s.onToolError)==null||c.call(s,t.tool_call_id||"",t.error||"");break;case"task_list_updated":t.task_list&&((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 j=t.status;if(!(j==="pending"||j==="in_progress"||j==="completed"||j==="blocked"))break;(u=s.onTaskListItemProgress)==null||u.call(s,{session_id:t.session_id,item_id:t.item_id,status:j,tool_calls_count:t.tool_calls_count,version:t.version})}break;case"task_list_completed":t.session_id&&t.total_rounds!==void 0&&t.total_tool_calls!==void 0&&((h=s.onTaskListCompleted)==null||h.call(s,t.session_id,t.total_rounds,t.total_tool_calls));break;case"task_evaluation_started":t.session_id&&t.items_count!==void 0&&((p=s.onTaskEvaluationStarted)==null||p.call(s,t.session_id,t.items_count));break;case"task_evaluation_completed":t.session_id&&t.updates_count!==void 0&&t.reasoning&&((g=s.onTaskEvaluationCompleted)==null||g.call(s,t.session_id,t.updates_count,t.reasoning));break;case"token_budget_updated":t.usage&&"system_tokens"in t.usage&&((y=s.onTokenBudgetUpdated)==null||y.call(s,t.usage));break;case"context_compression_status":typeof t.phase=="string"&&typeof t.status=="string"&&((f=s.onContextCompressionStatus)==null||f.call(s,t.phase,t.status));break;case"tool_lifecycle":(v=s.onToolLifecycle)==null||v.call(s,t.tool_call_id||"",t.tool_name||"",t.phase||"",t.elapsed_ms,t.is_mutating,t.auto_approved,t.summary,t.error);break;case"context_summarized":t.summary_info&&((b=s.onContextSummarized)==null||b.call(s,t.summary_info));break;case"sub_session_started":t.parent_session_id&&t.child_session_id&&((x=s.onSubSessionStarted)==null||x.call(s,t.parent_session_id,t.child_session_id,t.title));break;case"sub_session_event":t.parent_session_id&&t.child_session_id&&t.event&&((_=s.onSubSessionEvent)==null||_.call(s,t.parent_session_id,t.child_session_id,t.event));break;case"sub_session_heartbeat":t.parent_session_id&&t.child_session_id&&t.timestamp&&((w=s.onSubSessionHeartbeat)==null||w.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&&((k=s.onSubSessionCompleted)==null||k.call(s,t.parent_session_id,t.child_session_id,typeof t.status=="string"?t.status:"completed",t.error));break;case"complete":(C=s.onComplete)==null||C.call(s,t.usage);break;case"error":(E=s.onError)==null||E.call(s,t.message||t.error||"Unknown error");break;default:console.warn("Unknown event type:",t)}}async stopGeneration(t){await pe.post(`stop/${t}`)}async deleteSession(t){const s=encodeURIComponent(t);await pe.delete(`sessions/${s}`)}async getHistory(t){return pe.get(`history/${t}`)}async healthCheck(){try{return await pe.get("health"),!0}catch{return!1}}};He(Pn,"instance");let rs=Pn;const Wn=rs.getInstance(),jv=()=>({id:"general_assistant",name:"Bodhi",description:es.t("chat.prompt.defaultDescription"),content:`You are Bodhi, a highly capable AI assistant.
|
|
9
|
+
|
|
10
|
+
You help users solve problems quickly and correctly. Be concise, practical, and proactive.
|
|
11
|
+
If requirements are unclear, ask focused clarifying questions before proceeding.`,isDefault:!0}),gi=()=>[jv()];class Cv{async getProviderConfig(){return xe.get("/bamboo/settings/provider")}async saveProviderConfig(t){return xe.post("/bamboo/settings/provider",t)}async reloadConfig(){return xe.post("/bamboo/settings/reload")}async getCopilotAuthStatus(){return xe.post("/bamboo/copilot/auth/status")}async startCopilotAuth(){return xe.post("/bamboo/copilot/auth/start")}async completeCopilotAuth(t){return xe.post("/bamboo/copilot/auth/complete",t)}async authenticateCopilot(){return xe.post("/bamboo/copilot/authenticate")}async logoutCopilot(){return xe.post("/bamboo/copilot/logout")}async fetchProviderModels(t){return(await xe.post("/bamboo/settings/provider/models",{provider:t})).models}async getProviderCatalog(){return xe.get("/bamboo/provider-catalog")}async fetchCatalogModels(t){const s=t?{provider:t}:{};return xe.post("/bamboo/provider-catalog/fetch-models",s)}async getEnvVars(){return xe.get("/bamboo/env-vars")}async upsertEnvVar(t){return xe.post("/bamboo/env-vars",t)}async deleteEnvVar(t){return xe.delete(`/bamboo/env-vars/${encodeURIComponent(t)}`)}async replaceEnvVars(t){return xe.post("/bamboo/env-vars/replace",{entries:t})}}const It=new Cv,Ee=un((e,t)=>({currentProvider:"copilot",providerConfig:{provider:"copilot",providers:{}},isLoading:!1,error:null,selectedModelRef:null,catalog:null,isCatalogFetching:!1,loadProviderConfig:async()=>{e({isLoading:!0,error:null});try{const s=await It.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()},isProviderModelRefEnabled:()=>!0,setSelectedModelRef:s=>{e({selectedModelRef:s})},loadCatalog:async()=>{try{const s=await It.getProviderCatalog();e({catalog:s})}catch{}},fetchCatalogModels:async s=>{e({isCatalogFetching:!0});try{await It.fetchCatalogModels(s),await t().loadCatalog()}catch{}finally{e({isCatalogFetching:!1})}},getFastModelRef:()=>{const s=t(),n=s.providerConfig.providers[s.currentProvider];if(n&&"fast_model"in n&&n.fast_model)return{provider:s.currentProvider,model:n.fast_model};const o=s.getActiveModel();return o?{provider:s.currentProvider,model:o}:null},getVisionModelRef:()=>{const s=t(),n=s.providerConfig.providers[s.currentProvider];if(n&&"vision_model"in n&&n.vision_model)return{provider:s.currentProvider,model:n.vision_model};const o=s.getActiveModel();return o?{provider:s.currentProvider,model:o}:null},getModelsForProvider:s=>{const{catalog:n}=t();return n!=null&&n.models?n.models.filter(o=>o.reference.provider===s):[]}})),Mv=Object.freeze(Object.defineProperty({__proto__:null,useProviderStore:Ee},Symbol.toStringTag,{value:"Module"})),bu="copilot_auto_generate_titles",Gs=rs.getInstance(),hr=gi()[0],Pv=(hr==null?void 0:hr.id)||"general_assistant";var af;const Rf=((af=hr==null?void 0:hr.content)==null?void 0:af.trim())||"",tl="tool",xu=e=>{if(typeof e!="string"||!e.trim())return null;const t=Date.parse(e);return Number.isFinite(t)?t:null},Ev=()=>{try{const e=globalThis.crypto;if(e!=null&&e.randomUUID)return e.randomUUID()}catch{}return`id_${Date.now()}_${Math.random().toString(16).slice(2)}`},Rv=()=>{let e=kr().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`},Af=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}},Av=e=>{const t=Af(e);return t?`${Rv()}/sessions/${encodeURIComponent(t.sessionId)}/attachments/${encodeURIComponent(t.attachmentId)}`:e},jn=e=>{if(typeof e!="string")return;const t=e.trim();if(t&&t.toLowerCase()!=="unknown")return t},Iv=e=>{const t=(e||"").trim();if(!t)return;const s=t.match(/tool policy blocked ['"`]([^'"`]+)['"`]/i);if(s!=null&&s[1])return jn(s[1]);try{const n=JSON.parse(t);if(typeof(n==null?void 0:n.tool_name)=="string")return jn(n.tool_name)}catch{}},sl=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||es.t("chat.session.defaultTitle"),createdAt:t,pinned:e.pinned,messages:[],config:{systemPromptId:Pv,baseSystemPrompt:Rf,lastUsedEnhancedPrompt:null,model:e.model,model_ref:e.model_ref??null,reasoningEffort:e.reasoning_effort??null,tokenUsage:s,truncationOccurred:(n=e.token_usage)==null?void 0:n.truncation_occurred,segmentsRemoved:(o=e.token_usage)==null?void 0:o.segments_removed,compressionEvents:[]},currentInteraction:null}},$v=(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 v=(a=f.image_url)==null?void 0:a.trim();if(!v)continue;const x=(f.lines||[]).map(_=>((_==null?void 0:_.text)||"").trim()).filter(Boolean);p.set(v,{ocrText:x.length?x.join(`
|
|
12
|
+
`):void 0,ocrError:f.error?String(f.error):void 0})}const g=[];for(const f of u.content_parts||[]){if(f.type!=="image_url")continue;const v=((i=f.image_url)==null?void 0:i.url)||"";if(!v)continue;const b=Av(v),x=Af(v),_=p.get(v.trim());g.push({id:Ev(),url:b,ocrText:_==null?void 0:_.ocrText,ocrError:_==null?void 0:_.ocrError,name:x?`attachment-${x.attachmentId}`:"image",size:0,type:"image/*"})}const y={role:"user",id:u.id,createdAt:h,content:u.content||"",images:g.length?g:void 0,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(y);continue}if(u.role==="assistant"){const p=u.tool_calls||[];if(p.length>0){const f=(u.content||"").trim(),v=typeof u.reasoning=="string"&&u.reasoning.trim().length>0;if(f||v){const w=v?{reasoning:u.reasoning,backendMessageId:u.id}:{backendMessageId:u.id},k={role:"assistant",type:"text",id:`${u.id}_text`,createdAt:h,content:u.content||"",metadata:w,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(k)}for(const w of p)w.id&&s.set(w.id,jn((l=w.function)==null?void 0:l.name)||tl);const b=(c=p[0])==null?void 0:c.id,x=b?n.get(b):void 0,_={role:"assistant",type:"tool_call",id:u.id,createdAt:h,toolCalls:p.map(w=>{var k;return{toolCallId:w.id,toolName:jn((k=w.function)==null?void 0:k.name)||tl,parameters:(()=>{var C,E;try{return JSON.parse(((C=w.function)==null?void 0:C.arguments)||"{}")}catch{return{raw:((E=w.function)==null?void 0:E.arguments)||""}}})(),streamingOutput:""}}),...x?{metadata:x}:{},isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(_);continue}const g=typeof u.reasoning=="string"&&u.reasoning.trim().length>0?{reasoning:u.reasoning}:{},y={role:"assistant",type:"text",id:u.id,createdAt:h,content:u.content||"",metadata:g,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(y);continue}if(u.role==="tool"){const p=((d=u.tool_call_id)==null?void 0:d.trim())||`orphan-tool-call:${u.id}`,g=jn(s.get(p))||jn(u.tool_name)||jn(u.name)||Iv(u.content)||tl,y=u.tool_success===!1||u.tool_success==null&&typeof u.content=="string"&&u.content.trimStart().startsWith("Error:"),f={role:"assistant",type:"tool_result",id:u.id,createdAt:h,toolName:g,toolCallId:p,result:{tool_name:g,result:u.content||"",display_preference:"Default"},isError:y,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(f);continue}}return o},Dv=(e,t)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,processingChats:new Set,autoGenerateTitles:!0,isUpdatingAutoTitlePreference:!1,subSessionsByParent:{},addChat:async s=>{var p,g,y,f,v,b;const n=(s.title||es.t("chat.sidebar.newSession")).trim(),o=((g=(p=s.config)==null?void 0:p.baseSystemPrompt)==null?void 0:g.trim())||"",a=(y=Ee.getState().getActiveModel())==null?void 0:y.trim(),i=((v=(f=s.config)==null?void 0:f.model)==null?void 0:v.trim())||a||void 0,l=((b=s.config)==null?void 0:b.reasoningEffort)??void 0;let c,d;if(Ee.getState().isProviderModelRefEnabled()){const x=Ee.getState().selectedModelRef;if(x)c=x,d=x.provider;else{const _=Ee.getState().getActiveModel();_&&(c={provider:Ee.getState().currentProvider,model:_},d=Ee.getState().currentProvider)}}const u=await Gs.createSession({title:n,system_prompt:o||void 0,model:i,model_ref:c,provider:d,reasoning_effort:l||void 0}),h={...sl(u.session),title:n,config:{...s.config,model:u.session.model,model_ref:u.session.model_ref??null,reasoningEffort:u.session.reasoning_effort??null,baseSystemPrompt:o||Rf},messages:[],currentInteraction:null};return e(x=>{const _=[h,...x.chats.filter(w=>w.id!==h.id)];return{...x,chats:_,currentSessionId:h.id,latestActiveSessionId:h.id}}),h.id},selectSession:s=>{const n=t();n.currentSessionId===s&&n.latestActiveSessionId===s||e({currentSessionId:s,latestActiveSessionId:s})},deleteSession:async s=>{try{await Gs.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)=>{const o=!!n.config&&(Object.prototype.hasOwnProperty.call(n.config,"model")||Object.prototype.hasOwnProperty.call(n.config,"reasoningEffort")),a=typeof n.title=="string"||typeof n.pinned=="boolean",l=o||a?new Date().toISOString():void 0;e(d=>{const u=d.chats.map(h=>h.id===s?{...h,...n,...l?{updatedAt:l}:{}}:h);return{...d,chats:u}});const c={};if(typeof n.title=="string"&&(c.title=n.title),typeof n.pinned=="boolean"&&(c.pinned=n.pinned),n.config&&Object.prototype.hasOwnProperty.call(n.config,"model")&&(c.model=n.config.model??null),n.config&&Object.prototype.hasOwnProperty.call(n.config,"model_ref")&&Ee.getState().isProviderModelRefEnabled()&&(c.model_ref=n.config.model_ref??null,n.config.model_ref&&(c.provider=n.config.model_ref.provider)),n.config&&Object.prototype.hasOwnProperty.call(n.config,"reasoningEffort")){const d=n.config.reasoningEffort;d?c.reasoning_effort=d:c.clear_reasoning_effort=!0}Object.keys(c).length>0&&Gs.patchSession(s,c).catch(d=>{console.warn(`[ChatSlice] Failed to patch session ${s}:`,d)})},pinSession:s=>{t().updateSession(s,{pinned:!0})},unpinSession:s=>{t().updateSession(s,{pinned:!1})},setMessages:(s,n)=>{t().chats.find(a=>a.id===s)&&t().updateSession(s,{messages:n})},addMessage:async(s,n)=>{const 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 Gs.deleteSessionMessage(s,n)}catch(a){return console.warn(`[ChatSlice] Failed to delete message ${n} from session ${s}:`,a),a instanceof Bn?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 Gs.listSessions()).sessions.map(sl);e(o=>{const a=new Set(o.processingChats);n.forEach(c=>{c.isRunning&&a.add(c.id)});const i=new Map(o.chats.map(c=>[c.id,c])),l=n.map(c=>{var _,w,k,C;const d=i.get(c.id);if(!d)return c;const u=xu(d.updatedAt),h=xu(c.updatedAt),p=u!==null&&h!==null&&u>h,g=d.config||{},y=c.config||{},f=Object.prototype.hasOwnProperty.call(g,"model"),v=Object.prototype.hasOwnProperty.call(g,"model_ref"),b=Object.prototype.hasOwnProperty.call(g,"reasoningEffort"),x=Math.max(d.messageCount??0,c.messageCount??0);return{...c,title:p?d.title:c.title,pinned:p?d.pinned:c.pinned,updatedAt:p?d.updatedAt:c.updatedAt,messages:d.messages,messageCount:x,config:{...g,...y,model:p&&f?g.model:y.model,model_ref:p&&v?g.model_ref:y.model_ref,reasoningEffort:p&&b?g.reasoningEffort:y.reasoningEffort,compressionEvents:((_=d.config)==null?void 0:_.compressionEvents)??((w=c.config)==null?void 0:w.compressionEvents),syncCursor:((k=d.config)==null?void 0:k.syncCursor)??((C=c.config)==null?void 0:C.syncCursor)}}});return{...o,chats:l,processingChats:a}})},loadChats:async()=>{var c;const s=localStorage.getItem(bu),n=s===null?t().autoGenerateTitles:s==="true";let o=await Gs.listSessions();(!o.sessions||o.sessions.length===0)&&(o={sessions:[(await Gs.createSession({title:es.t("chat.sidebar.newSession")})).session]});const a=o.sessions.map(sl),i=((c=a[0])==null?void 0:c.id)??null,l=a.filter(d=>d.isRunning).map(d=>d.id);e({chats:a,latestActiveSessionId:i,currentSessionId:i,processingChats:new Set(l),autoGenerateTitles:n}),i&&await t().loadChatHistory(i)},loadChatHistory:async(s,n)=>{var l,c,d,u,h,p,g;const o=(n==null?void 0:n.mode)??"replace",a=Math.max(0,(n==null?void 0:n.retries)??0),i=Math.max(0,(n==null?void 0:n.retryDelayMs)??0);for(let y=0;y<=a;y+=1)try{const f=t().chats.find(_=>_.id===s);if(!f)return;const v=await Gs.getHistory(s),b=(l=v.messages[v.messages.length-1])==null?void 0:l.role;if(n!=null&&n.waitForAssistant&&b==="user"&&y<a){const _=i>0?i*(y+1):200*(y+1);await new Promise(w=>setTimeout(w,_));continue}const x=$v(s,v.messages);if(o==="monotonic"){const _=f.messages||[],w=_.length,k=x.length,C=(c=x[x.length-1])==null?void 0:c.role,E=(d=_[_.length-1])==null?void 0:d.role,j=_[_.length-1],R=x[x.length-1],M=j==null?void 0:j.id,T=R==null?void 0:R.id;let P=!1;if(k>w?P=!0:k===w&&(P=E==="user"&&C!=="user"||typeof M=="string"&&typeof T=="string"&&M!==T),!P){t().updateSession(s,{messageCount:Math.max(f.messageCount??0,v.messages.length)});return}}t().updateSession(s,{messages:x,messageCount:v.messages.length,config:{...f.config||{},compressionEvents:(v.compression_events||[]).map(_=>({id:_.id,createdAt:_.created_at,messagesCompressed:_.messages_compressed,segmentsRemoved:_.segments_removed})),syncCursor:{messageCount:v.messages.length,lastMessageId:((u=v.messages[v.messages.length-1])==null?void 0:u.id)??null,hasPendingQuestion:((h=t().pendingQuestionRespond)==null?void 0:h.sessionId)===s,pendingQuestionToolCallId:((p=t().pendingQuestionRespond)==null?void 0:p.sessionId)===s?((g=t().pendingQuestionRespond)==null?void 0:g.toolCallId)??null:null}}});return}catch(f){if(y>=a){console.warn(`[ChatSlice] Failed to load history for ${s}:`,f);return}const v=i>0?i*(y+1):200*(y+1);await new Promise(b=>setTimeout(b,v))}},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(bu,String(s))}catch(o){throw console.warn("[ChatSlice] Failed to update auto-title preference:",o),e({autoGenerateTitles:n}),o}finally{e({isUpdatingAutoTitlePreference:!1})}}});class ac extends Error{constructor(s="Proxy authentication required"){super(s);He(this,"code","proxy_auth_required");this.name="ProxyAuthRequiredError"}}const En=class En{constructor(){}static getInstance(){return En.instance||(En.instance=new En),En.instance}resolveOpenAICompatBaseUrl(){const t=kr().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 pd({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 Bn){if(n.status===428)throw new ac(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 ac(((s=o.error)==null?void 0:s.message)||n.message)}throw n}}};He(En,"instance");let ic=En;const If=ic.getInstance(),Lv=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)},Ov=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")},os=async e=>{try{await Lv(e);return}catch(t){try{Ov(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 Fv{async copyToClipboard(t){await os(t)}async getBambooConfig(){try{return await xe.get("bamboo/config")}catch(t){return console.error("Failed to fetch Bamboo config:",t),{}}}async getBambooTools(){try{return await xe.get("bamboo/tools")}catch(t){return console.error("Failed to fetch Bamboo tools:",t),{tools:[]}}}async getModelLimitDefaults(){try{return await xe.get("bamboo/model-limits/defaults")}catch(t){return console.error("Failed to fetch model limit defaults:",t),{model_limits:[]}}}async setBambooConfig(t){return xe.post("bamboo/config",t)}async validateBambooConfigPatch(t){return xe.post("bamboo/config/validate",t)}async setProxyAuth(t){return xe.post("bamboo/proxy-auth",t)}async getProxyAuthStatus(){try{return await xe.get("bamboo/proxy-auth/status")}catch(t){return console.error("Failed to fetch proxy auth status:",t),{configured:!1,username:null}}}async clearProxyAuth(){return xe.post("bamboo/proxy-auth",{username:"",password:""})}async resetBambooConfig(){return xe.post("bamboo/config/reset",{})}async saveWorkflow(t,s){return xe.post("bamboo/workflows",{name:t,content:s})}async deleteWorkflow(t){return xe.delete(`bamboo/workflows/${encodeURIComponent(t)}`)}async getKeywordMaskingConfig(){try{return await xe.get("bamboo/keyword-masking")}catch(t){return console.error("Failed to fetch keyword masking config:",t),{entries:[]}}}async updateKeywordMaskingConfig(t){return xe.post("bamboo/keyword-masking",t)}async validateKeywordEntries(t){return xe.post("bamboo/keyword-masking/validate",t)}async getSetupStatus(){return await xe.get("bamboo/setup/status")}async markSetupComplete(){return xe.post("bamboo/setup/complete",{})}async resetSetupStatus(){await xe.post("bamboo/setup/incomplete",{})}async getAccessStatus(){return xe.get("bamboo/access/status")}async verifyAccessPassword(t){return xe.post("bamboo/access/verify",{password:t})}async updateAccessPassword(t){return xe.post("bamboo/access/password",t)}}const Rn=class Rn{constructor(){He(this,"httpUtilityService",new Fv)}static getInstance(){return Rn.instance||(Rn.instance=new Rn),Rn.instance}getUtilityService(){return{copyToClipboard:t=>this.httpUtilityService.copyToClipboard(t),getBambooConfig:()=>this.httpUtilityService.getBambooConfig(),getBambooTools:()=>this.httpUtilityService.getBambooTools(),getModelLimitDefaults:()=>this.httpUtilityService.getModelLimitDefaults(),setBambooConfig:t=>this.httpUtilityService.setBambooConfig(t),validateBambooConfigPatch:t=>this.httpUtilityService.validateBambooConfigPatch(t),setProxyAuth:t=>this.httpUtilityService.setProxyAuth(t),getProxyAuthStatus:()=>this.httpUtilityService.getProxyAuthStatus(),clearProxyAuth:()=>this.httpUtilityService.clearProxyAuth(),resetBambooConfig:()=>this.httpUtilityService.resetBambooConfig(),resetSetupStatus:()=>this.httpUtilityService.resetSetupStatus(),saveWorkflow:(t,s)=>this.httpUtilityService.saveWorkflow(t,s),deleteWorkflow:t=>this.httpUtilityService.deleteWorkflow(t),getKeywordMaskingConfig:()=>this.httpUtilityService.getKeywordMaskingConfig(),updateKeywordMaskingConfig:t=>this.httpUtilityService.updateKeywordMaskingConfig(t),validateKeywordEntries:t=>this.httpUtilityService.validateKeywordEntries(t),getSetupStatus:()=>this.httpUtilityService.getSetupStatus(),markSetupComplete:()=>this.httpUtilityService.markSetupComplete(),getAccessStatus:()=>this.httpUtilityService.getAccessStatus(),verifyAccessPassword:t=>this.httpUtilityService.verifyAccessPassword(t),updateAccessPassword:t=>this.httpUtilityService.updateAccessPassword(t)}}async copyToClipboard(t){return this.getUtilityService().copyToClipboard(t)}async getBambooConfig(){return this.getUtilityService().getBambooConfig()}async getBambooTools(){return this.getUtilityService().getBambooTools()}async getModelLimitDefaults(){return this.getUtilityService().getModelLimitDefaults()}async setBambooConfig(t){return this.getUtilityService().setBambooConfig(t)}async validateBambooConfigPatch(t){return this.getUtilityService().validateBambooConfigPatch(t)}async setProxyAuth(t){return this.getUtilityService().setProxyAuth(t)}async getProxyAuthStatus(){return this.getUtilityService().getProxyAuthStatus()}async clearProxyAuth(){return this.getUtilityService().clearProxyAuth()}async resetBambooConfig(){return this.getUtilityService().resetBambooConfig()}async resetSetupStatus(){return this.getUtilityService().resetSetupStatus()}async saveWorkflow(t,s){return this.getUtilityService().saveWorkflow(t,s)}async deleteWorkflow(t){return this.getUtilityService().deleteWorkflow(t)}async getKeywordMaskingConfig(){return this.getUtilityService().getKeywordMaskingConfig()}async updateKeywordMaskingConfig(t){return this.getUtilityService().updateKeywordMaskingConfig(t)}async validateKeywordEntries(t){return this.getUtilityService().validateKeywordEntries(t)}async getSetupStatus(){return this.getUtilityService().getSetupStatus()}async markSetupComplete(){return this.getUtilityService().markSetupComplete()}async getAccessStatus(){return this.getUtilityService().getAccessStatus()}async verifyAccessPassword(t){return this.getUtilityService().verifyAccessPassword(t)}async updateAccessPassword(t){return this.getUtilityService().updateAccessPassword(t)}};He(Rn,"instance");let fs=Rn;const et=fs.getInstance();let Ar=null,Ir=null;const nl=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,ms=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(Ar)return Ar;Ar=(async()=>{e({isLoadingConfig:!0,error:null});try{const o=await et.getBambooConfig()??{};return e({config:o,lastLoadedAt:Date.now(),error:null}),o}catch(o){const a=nl(o,"Failed to load Bamboo config");throw e({error:a}),o}finally{e({isLoadingConfig:!1})}})();try{return await Ar}finally{Ar=null}},saveConfig:async s=>{e({isLoadingConfig:!0,error:null,config:s});try{const n=await et.setBambooConfig(s);return e({config:n,lastLoadedAt:Date.now(),error:null}),n}catch(n){const o=nl(n,"Failed to save Bamboo config");throw e({error:o}),n}finally{e({isLoadingConfig:!1})}},patchConfig:async s=>{const o={...await t().loadConfig()??{},...s??{}};return t().saveConfig(o)},loadProxyAuthStatus:async({force:s=!1}={})=>{const n=t().proxyAuthStatus;if(!s&&n)return n;if(Ir)return Ir;Ir=(async()=>{e({isLoadingProxyAuthStatus:!0,error:null});try{const o=await et.getProxyAuthStatus();return e({proxyAuthStatus:o,error:null}),o}catch(o){const a=nl(o,"Failed to load proxy auth status");throw e({error:a}),o}finally{e({isLoadingProxyAuthStatus:!1})}})();try{return await Ir}finally{Ir=null}},applyProxyAuth:async s=>{await et.setProxyAuth(s),await t().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await et.clearProxyAuth(),await t().loadProxyAuthStatus({force:!0})}}));let $r=null;const zv=(e,t)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:s=>{e({selectedModel:s})},loadConfigModel:async()=>{try{const s=await ms.getState().loadConfig(),n=typeof(s==null?void 0:s.model)=="string"?s.model:void 0;n&&e({configModel:n})}catch(s){console.error("Failed to load model from config:",s)}},fetchModels:async()=>{if($r)return $r;$r=(async()=>{e({isLoadingModels:!0,modelsError:null});try{try{if(!(await et.getSetupStatus()).is_complete){st("[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 If.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 ac){e(o=>({...o,models:o.models,selectedModel:o.selectedModel,modelsError:n||"Proxy authentication required. Please configure proxy auth."}));return}e(o=>({...o,models:[],selectedModel:o.selectedModel,modelsError:n}))}finally{e({isLoadingModels:!1})}})();try{await $r}finally{$r=null}}}),Nv=["system_prompt","system_prompt_selected_id"],rl=e=>({id:e.id,name:e.name||e.id,content:e.content||"",description:e.description,isDefault:!!e.is_default}),nn=class nn{constructor(){He(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return nn.instance||(nn.instance=new nn),nn.instance.cleanupDeprecatedPromptStorageKeys(),nn.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const t of Nv)localStorage.removeItem(t)}catch(t){console.warn("[SystemPromptService] Failed to cleanup deprecated prompt storage keys:",t)}}}async getSystemPromptPresets(){try{const t=await pe.get("prompt-presets"),n=(Array.isArray(t==null?void 0:t.prompts)?t.prompts:[]).filter(o=>o.id&&o.id.trim().length>0).map(rl);if(n.length>0)return n}catch(t){console.error("Failed to load prompt presets from backend:",t)}return gi()}async createSystemPromptPreset(t){var o;const s={name:t.name,content:t.content};(o=t.id)!=null&&o.trim()&&(s.id=t.id.trim()),t.description!==void 0&&(s.description=t.description);const n=await pe.post("prompt-presets",s);if(!(n!=null&&n.prompt))throw new Error("Backend did not return created prompt preset");return rl(n.prompt)}async updateSystemPromptPreset(t){const s=encodeURIComponent(t.id),n={name:t.name,content:t.content,description:t.description},o=await pe.patch(`prompt-presets/${s}`,n);if(!(o!=null&&o.prompt))throw new Error("Backend did not return updated prompt preset");return rl(o.prompt)}async deleteSystemPromptPreset(t){const s=encodeURIComponent(t);await pe.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)||""}};He(nn,"instance");let yi=nn;const vu="copilot_last_selected_prompt_id",$f="copilot_custom_system_prompts_v2",Df="copilot_custom_system_prompts_v2_migrated_to_backend",Lf="general_assistant",fd=80,dr=yi.getInstance();let Ma=null;function gd(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,fd)}function Of(e){if(typeof e!="string")return null;const t=e.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return t?t.slice(0,fd):null}function Ff(e,t){if(!t.has(e))return e;let s=2;for(;;){const n=`_${s}`,a=`${e.slice(0,Math.max(0,fd-n.length))}${n}`;if(!t.has(a))return a;s+=1}}function zf(){try{const e=localStorage.getItem($f);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=Of(o==null?void 0:o.id)||gd(a),d=Ff(c,s);d!==Lf&&(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 Nf(){try{return localStorage.getItem(Df)==="1"}catch(e){return console.error("[promptSlice] Failed to read migration marker:",e),!1}}function Su(){try{localStorage.setItem(Df,"1")}catch(e){console.error("[promptSlice] Failed to write migration marker:",e)}}function wu(){try{localStorage.removeItem($f)}catch(e){console.error("[promptSlice] Failed to clear legacy custom prompts:",e)}}async function Bv(){var o,a;if(Nf())return;const e=zf();if(e.length===0){wu(),Su();return}const t=await dr.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===Lf||i.isDefault)continue;const d=Of(i.id)||gd(l),u=Ff(d,s);try{const h=await dr.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||(wu(),Su())}async function Wv(){Ma||(Ma=Bv().finally(()=>{Ma=null})),await Ma}const Uv=(e,t)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(vu)||null,loadSystemPrompts:async()=>{try{await Wv()}catch(o){console.warn("[promptSlice] Legacy prompt migration skipped:",o)}let s=[];try{s=await dr.getSystemPromptPresets()}catch(o){console.error("Failed to load system prompts from backend:",o)}let n=s.length?s:gi();if(!Nf()){const o=zf();n=qv(n,o)}n.length===0&&(n=gi()),e({systemPrompts:n})},addSystemPrompt:async s=>{try{await dr.createSystemPromptPreset({id:gd(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 dr.updateSystemPromptPreset(s),await t().loadSystemPrompts()}catch(n){throw console.error("Failed to update system prompt:",n),n}},deleteSystemPrompt:async s=>{try{await dr.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(vu,s)}catch(n){console.error("Failed to save last selected prompt ID to localStorage:",n)}}}),qv=(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())},Hv=(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 Yv{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 xe.get(a)}async getSkill(t){return xe.get(`skills/${t}`)}async getFilteredTools(t){const s=t?`?session_id=${encodeURIComponent(t)}`:"";return(await xe.get(`skills/filtered-tools${s}`)).tools??[]}}const lc=new Yv,Xv=(e,t)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(s,n)=>{e({isLoadingSkills:!0,skillsError:null});try{const o=await lc.listSkills(s,n);e({skills:o.skills,isLoadingSkills:!1})}catch(o){e({skillsError:o instanceof Error?o.message:es.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async s=>{e({isLoadingSkills:!0,skillsError:null});try{const n=await lc.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:es.t("components.skillManager.getFailed"),isLoadingSkills:!1})}},clearSkillsError:()=>{e({skillsError:null})}}),Vv=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}})}),Kv=(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}})}),cc=e=>Array.isArray(e)?e.map(t=>String(t??"")):[],Ka=({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o})=>JSON.stringify({sessionId:e??null,question:t??"",options:cc(s),allowCustom:n??!0,toolCallId:o??null}),Gv=(e,t)=>{if(!e||!t)return e===t;if((e.sessionId??null)!==(t.sessionId??null)||(e.question??"")!==(t.question??"")||(e.allowCustom??!0)!==(t.allowCustom??!0)||(e.toolCallId??null)!==(t.toolCallId??null))return!1;const s=cc(e.options),n=cc(t.options);return s.length!==n.length?!1:s.every((o,a)=>o===n[a])},Bf="chat_input_reasoning_by_session_v1",Wf="chat_input_reasoning_last_used_v1",_u={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},yd=e=>e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",Uf=()=>{if(typeof window>"u")return{};try{const e=localStorage.getItem(Bf);if(!e)return{};const t=JSON.parse(e),s={};for(const[n,o]of Object.entries(t||{}))yd(o)&&(s[n]=o);return s}catch{return{}}},Jv=e=>{if(!(typeof window>"u"))try{localStorage.setItem(Bf,JSON.stringify(e))}catch{}},Qv=()=>{if(!(typeof window>"u"))try{const e=localStorage.getItem(Wf);return yd(e)?e:void 0}catch{return}},Zv=e=>{if(!(typeof window>"u"))try{localStorage.setItem(Wf,e)}catch{}},bd=e=>{const t=Uf();return yd(t[e])?t[e]:Qv()},Dr=e=>({..._u,reasoningEffort:bd(e)??_u.reasoningEffort}),eS=(e,t)=>({inputStates:{},pendingQuestionRespond:null,setInputContent:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Dr(s),content:n}}})),setReferenceText:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Dr(s),referenceText:n}}})),setAttachments:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Dr(s),attachments:n}}})),setInputReasoningEffort:(s,n)=>{e(a=>({inputStates:{...a.inputStates,[s]:{...a.inputStates[s]||Dr(s),reasoningEffort:n}}}));const o=Uf();o[s]=n,Jv(o),Zv(n)},clearInputState:s=>e(n=>{const{[s]:o,...a}=n.inputStates;return{inputStates:a}}),getInputState:s=>t().inputStates[s]||Dr(s),setPendingQuestionRespond:s=>e(n=>Gv(n.pendingQuestionRespond,s)?{}:{pendingQuestionRespond:s}),clearPendingQuestionRespondForSession:s=>e(n=>{var o;return((o=n.pendingQuestionRespond)==null?void 0:o.sessionId)!==s?{}:n.pendingQuestionRespond===null?{}:{pendingQuestionRespond:null}})}),tS="bamboo_proxy_auth",sS=()=>{try{const e=localStorage.getItem(tS);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}},nS="auto",rS="required",oS=1e4,aS=2e3,iS=rs.getInstance();let Tu=null,Lr=null,ku=null,Or=null;const ju=new WeakMap,N=un()(lv(dv((e,t,s)=>({...Dv(e,t),...zv(e,t),...Uv(e,t),...Hv(e,t),...Xv(e,t),...Vv(e),...Kv(e,t),...eS(e,t),agentAvailability:null,setAgentAvailability:n=>{e({agentAvailability:n})},checkAgentAvailability:async()=>{if(Lr)return Lr;Lr=(async()=>{const n=await iS.healthCheck();return t().agentAvailability!==n&&e({agentAvailability:n}),n})();try{return await Lr}finally{Lr=null}},startAgentHealthCheck:()=>{Tu||(t().checkAgentAvailability(),Tu=setInterval(()=>{t().checkAgentAvailability()},oS))},refreshSessionsIndex:async()=>{if(Or)return Or;Or=(async()=>{try{await t().refreshChats()}catch(n){console.warn("[AppStore] refreshChats failed:",n)}})();try{return await Or}finally{Or=null}},startSessionsIndexSync:()=>{ku||(t().refreshSessionsIndex(),ku=setInterval(()=>{t().refreshSessionsIndex()},aS))}})),{name:"AppStore"})),qf=e=>{const t=ju.get(e);if(t)return t;const s=new Map(e.map(n=>[n.id,n]));return ju.set(e,s),s},Xn=e=>t=>e?qf(t.chats).get(e)??null:null,lS=e=>e.currentSessionId?qf(e.chats).get(e.currentSessionId)??null:null,Cu=async()=>{const e=sS();if(!e)return!1;try{return await et.setProxyAuth(e),!0}catch(t){return console.error("Failed to apply stored proxy auth during startup:",t),!1}},cS=async()=>{try{const e=await ms.getState().loadConfig();if((typeof(e==null?void 0:e.proxy_auth_mode)=="string"?e.proxy_auth_mode:nS)!==rS)return await Cu(),!1;const s=await ms.getState().loadProxyAuthStatus({force:!0});return s!=null&&s.configured||await Cu()?!1:(N.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 Mu=!1;const dS=async(e=!1)=>{if(Mu&&!e)return;Mu=!0,N.getState().startAgentHealthCheck(),N.getState().startSessionsIndexSync(),await N.getState().loadChats(),await cS()||await N.getState().fetchModels(),await N.getState().loadSystemPrompts()},Un={'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:Pu,Paragraph:uS}=le,mS=({content:e,token:t,showGradient:s,onClick:n})=>r.jsx(ee,{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(hs,{remarkPlugins:[Ii],components:{p:({children:o})=>r.jsx(uS,{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(Pu,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block"},children:o}),h2:({children:o})=>r.jsx(Pu,{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(fr,{style:Un,language:(c==null?void 0:c[1])||"text",PreTag:"div",wrapLongLines:!0,children:String(i).replace(/\n$/,"")})}},children:e||"No content available."}),s?r.jsx("div",{style:{position:"sticky",bottom:0,height:48,background:`linear-gradient(180deg, transparent, ${t.colorBgLayout})`,pointerEvents:"none",marginTop:-48}}):null]})}),{Text:ol,Paragraph:hS}=le,pS=({prompt:e,token:t,isSelected:s,isExpanded:n,onSelect:o,onToggleExpand:a,onCopy:i})=>{const{t:l}=ne(),c=e.content||"",{nonEmptyLineCount:d,wordCount:u,characterCount:h,showGradient:p}=m.useMemo(()=>{const y=(c?c.split(/\r?\n/):[]).filter(b=>b.trim().length>0).length,f=c.trim()?c.trim().split(/\s+/).filter(Boolean).length:0,v=c.length;return{nonEmptyLineCount:y,wordCount:f,characterCount:v,showGradient:!n&&v>600}},[c,n]);return r.jsx(nt.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(X,{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(X,{align:"start",children:[r.jsx(ts,{checked:s,onChange:()=>o(e.id),onClick:g=>g.stopPropagation()}),r.jsxs("div",{children:[r.jsx(ol,{strong:!0,children:e.name||e.id}),r.jsx("div",{children:r.jsx(ol,{code:!0,style:{fontSize:t.fontSizeSM,color:t.colorTextSecondary},children:e.id})})]}),e.isDefault?r.jsx(oe,{color:"warning",children:l("chat.systemPromptSelector.defaultTag")}):null]}),r.jsxs(X,{size:"small",children:[r.jsx(Y,{type:"text",size:"small",icon:n?r.jsx(nx,{}):r.jsx(td,{}),onClick:g=>{g.stopPropagation(),a(e.id)},children:l(n?"chat.systemPromptSelector.hide":"chat.systemPromptSelector.preview")}),r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ss,{}),onClick:g=>i(g,e),children:l("chat.systemPromptSelector.copy")})]})]}),e.description?r.jsx(ol,{type:"secondary",style:{marginLeft:t.marginLG,fontSize:t.fontSizeSM},children:e.description}):null,r.jsxs(X,{size:"small",wrap:!0,style:{marginLeft:t.marginLG},children:[r.jsx(oe,{color:"processing",children:l("chat.systemPromptSelector.lines",{count:d})}),r.jsx(oe,{color:"purple",children:l("chat.systemPromptSelector.words",{count:u})}),r.jsx(oe,{color:"success",children:l("chat.systemPromptSelector.chars",{count:h})})]}),n?r.jsx(mS,{content:c,token:t,showGradient:p,onClick:g=>g.stopPropagation()}):r.jsx(hS,{type:"secondary",ellipsis:{rows:3},style:{marginLeft:t.marginLG,marginBottom:0,color:t.colorTextSecondary},children:c||l("chat.systemPromptSelector.noContent")})]})},e.id)},{Text:fS}=le,{useToken:gS}=he,yS=({open:e,onClose:t,onSelect:s,prompts:n,title:o,showCancelButton:a=!0})=>{const{t:i}=ne(),{token:l}=gS(),[c,d]=fe.useMessage(),u=N(k=>k.lastSelectedPromptId),h=N(k=>k.setLastSelectedPromptId),[p,g]=m.useState(null),[y,f]=m.useState(null),v=m.useMemo(()=>n.filter(k=>k.id&&k.id.trim()!==""),[n]),b=async(k,C)=>{k.stopPropagation();const E=C.content??"";try{await os(E),c.success(i("success.promptCopied",{name:C.name}))}catch(j){console.error("[SystemPromptSelector] Failed to copy prompt:",j),c.error(i("error.copyPromptFailed"))}},x=o??i("chat.prompt.selectorTitle");m.useEffect(()=>{if(e){const k=v.find(E=>E.isDefault),C=u||(k==null?void 0:k.id)||(v.length>0?v[0].id:null);g(C)}},[e,u,v.length]);const _=k=>{g(k.id),h(k.id),s(k),t()},w=()=>{t()};return r.jsxs(r.Fragment,{children:[d,r.jsxs(Lt,{title:r.jsxs(X,{children:[r.jsx(Sr,{}),x]}),open:e,onCancel:w,width:700,footer:r.jsx(Qx,{buttons:[...a?[Zx(w)]:[],ev(()=>{const k=v.find(C=>C.id===p);k&&_(k)},{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(fS,{type:"secondary",style:{fontSize:l.fontSizeSM},children:i("chat.prompt.helperText")})}),v.length===0?r.jsx(kt,{description:i("chat.prompt.emptyDescription"),style:{margin:l.marginLG}}):r.jsx("div",{children:v.map(k=>r.jsx(pS,{prompt:k,token:l,isSelected:p===k.id,isExpanded:y===k.id,onSelect:C=>g(C),onToggleExpand:C=>f(y===C?null:C),onCopy:b},k.id))})]})]})},bS=({chat:e,isSelected:t,onSelect:s,onDelete:n,onPin:o,onUnpin:a,onEdit:i,onGenerateTitle:l,onRunProjectDream:c,isGeneratingTitle:d,isRunningProjectDream:u,titleGenerationError:h})=>{const{t:p}=ne(),[g,y]=m.useState(!1),[f,v]=m.useState(e.title),[b,x]=m.useState(!1),[_,w]=m.useState(!1),{token:k}=he.useToken(),C=m.useCallback(S=>{S.stopPropagation(),i&&f.trim()&&i(e.id,f.trim()),y(!1)},[e.id,f,i]),E=m.useCallback(S=>{S.stopPropagation(),v(e.title),y(!1)},[e.title]),j=[{key:"pin",icon:e.pinned?r.jsx(sc,{style:{color:k.colorWarning}}):r.jsx(sd,{}),label:e.pinned?p("chat.actions.unpin"):p("chat.actions.pin"),onClick:({domEvent:S})=>{S.stopPropagation(),e.pinned?a(e.id):o(e.id)}},{key:"edit",icon:r.jsx(ca,{}),label:p("chat.chatItem.edit"),onClick:({domEvent:S})=>{S.stopPropagation(),y(!0)}},...l?[{key:"generate-title",icon:d?r.jsx(gr,{}):r.jsx(ff,{style:h?{color:k.colorError}:void 0}),label:h||p("chat.actions.generateTitle"),disabled:d,onClick:({domEvent:S})=>{S.stopPropagation(),l(e.id)}}]:[],...c?[{key:"run-project-dream",icon:u?r.jsx(gr,{}):r.jsx(rx,{}),label:p("chat.actions.runProjectDream"),disabled:u,onClick:({domEvent:S})=>{S.stopPropagation(),c(e.id)}}]:[],{type:"divider"},{key:"delete",icon:r.jsx(dn,{}),label:p("common.delete"),danger:!0,onClick:({domEvent:S})=>{S.stopPropagation(),n(e.id)}}],R={padding:"8px 12px",borderRadius:k.borderRadiusSM,marginBottom:k.marginXXS,cursor:"pointer",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)",backgroundColor:t?"var(--lotus-primary-soft)":b||_?"var(--lotus-item-hover-bg)":"transparent",border:"1px solid transparent",borderColor:t?"var(--lotus-tool-card-border)":b||_?k.colorBorderSecondary:"transparent",position:"relative",overflow:"visible",boxShadow:t?"var(--lotus-tool-card-shadow)":"none",transform:b&&!t?"translateX(2px)":"none"},M={flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontSize:13,fontWeight:t?600:500,color:t?"var(--lotus-primary)":k.colorText},T={flex:1,fontSize:k.fontSizeSM,marginRight:k.marginSM},P=g?[r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ox,{style:{color:k.colorSuccess}}),onClick:C,"aria-label":p("common.save")},"save"),r.jsx(Y,{type:"text",size:"small",icon:r.jsx(wr,{style:{color:k.colorError}}),onClick:E,"aria-label":p("common.cancel")},"cancel")]:b||_?[r.jsx(zn,{menu:{items:j,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:_,onOpenChange:S=>w(S),children:r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ax,{}),"aria-label":p("common.moreActions","More actions"),onClick:S=>S.stopPropagation(),style:{color:k.colorTextSecondary,borderRadius:k.borderRadiusSM,background:k.colorFillTertiary,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return r.jsx(nt.Item,{style:R,tabIndex:0,onClick:()=>!g&&s(e.id),onKeyDown:S=>{S.key==="Enter"&&!g?(S.preventDefault(),s(e.id)):(S.key==="Delete"||S.key==="Backspace")&&!g&&S.metaKey&&(S.preventDefault(),n(e.id))},onMouseEnter:()=>x(!0),onMouseLeave:()=>{_||x(!1)},onFocus:()=>x(!0),onBlur:()=>{_||x(!1)},actions:P,"data-testid":"chat-item",role:"option","aria-selected":t,"aria-label":e.title||p("chat.sidebar.untitledChat"),children:r.jsx(nt.Item.Meta,{title:g?r.jsx(me,{value:f,onChange:S=>v(S.target.value),onClick:S=>S.stopPropagation(),onPressEnter:S=>{S.preventDefault(),C(S)},autoFocus:!0,style:T,variant:"borderless",size:"small"}):r.jsxs("div",{style:{...M,display:"flex",alignItems:"center",gap:k.marginXS,minWidth:0},children:[e.pinned&&r.jsx(sc,{style:{color:k.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(oe,{color:"processing",style:{marginInlineEnd:0,flex:"0 0 auto"},children:p("chat.chatItem.childTag")}):null]})})})},xS=(e,t)=>e.chat.id===t.chat.id&&e.chat.title===t.chat.title&&e.chat.pinned===t.chat.pinned&&e.isSelected===t.isSelected&&e.isGeneratingTitle===t.isGeneratingTitle&&e.isRunningProjectDream===t.isRunningProjectDream&&e.titleGenerationError===t.titleGenerationError,dc=m.memo(bS,xS);dc.displayName="ChatItem";const Eu=e=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[e]??4,vS=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},SS=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:Eu(s)-Eu(n)})},wS=(e,t)=>e[t]?e[t].map(s=>s.id):[],Hf=(e,t)=>e[t]?e[t].length:0,Ru=e=>e.pinned?"Pinned":e.createdByScheduleId?"Scheduled":new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),Au=(e,t)=>{const n={Today:"chat.sidebar.dateGroups.today",Yesterday:"chat.sidebar.dateGroups.yesterday","This Week":"chat.sidebar.dateGroups.thisWeek","This Month":"chat.sidebar.dateGroups.thisMonth",Pinned:"chat.sidebar.dateGroups.pinned",Scheduled:"chat.sidebar.dateGroups.scheduled"}[e];return n?t(n):e},_S=({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:g,onGenerateTitle:y,onRunProjectDream:f,titleGenerationState:v,projectDreamState:b,token:x,hasActiveFilters:_})=>{const{t:w}=ne(),k=m.useMemo(()=>o.length?o.map(E=>{const j=e[E],R=Hf(e,E);return{dateKey:E,dateGroup:j,totalChatsInDate:R}}):[],[e,o]);if(!o.length)return r.jsx(kt,{image:kt.PRESENTED_IMAGE_SIMPLE,description:r.jsxs(X,{direction:"vertical",size:4,align:"center",children:[r.jsx("span",{style:{color:x.colorTextSecondary},children:_?w("chat.sidebar.empty.noMatches","No matching sessions"):w("chat.sidebar.empty.noSessions")}),r.jsx("span",{style:{color:x.colorTextSecondary,fontSize:12},children:_?w("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):w("chat.sidebar.empty.hint")}),_&&r.jsx(Y,{size:"small",type:"link",onClick:()=>{var j;const E=document.querySelector('[data-testid="sidebar-search-input"] input, .lotus-sidebar-search input');if(E){const R=(j=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value"))==null?void 0:j.set;R==null||R.call(E,""),E.dispatchEvent(new Event("input",{bubbles:!0}))}},children:w("chat.sidebar.empty.clearFilters","Clear filters")})]})});const C=new Set(a);return r.jsx(X,{direction:"vertical",size:"small",style:{width:"100%"},children:k.map(({dateKey:E,dateGroup:j,totalChatsInDate:R})=>{const M=C.has(E);return r.jsxs("div",{style:{borderRadius:x.borderRadiusSM,background:M?x.colorFillTertiary:"transparent",padding:4},children:[r.jsxs(G,{align:"center",justify:"space-between",style:{cursor:"pointer",padding:"8px 12px",borderRadius:x.borderRadiusSM,transition:"all 0.2s ease",border:"1px solid transparent"},role:"button",tabIndex:0,"aria-expanded":M,"aria-label":`${Au(E,w)} (${R})`,onKeyDown:T=>{if(T.key==="Enter"||T.key===" "){T.preventDefault();const P=new Set(C);P.has(E)?P.delete(E):P.add(E),i(Array.from(P))}},onMouseEnter:T=>{T.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.92))",T.currentTarget.style.borderColor="var(--lotus-sidebar-item-hover-border, rgba(13, 148, 136, 0.28))";const P=T.currentTarget.querySelector(".chat-sidebar-date-group-delete");P&&(P.style.opacity="1")},onMouseLeave:T=>{T.currentTarget.style.background="transparent",T.currentTarget.style.borderColor="transparent";const P=T.currentTarget.querySelector(".chat-sidebar-date-group-delete");P&&(P.style.opacity="0")},onClick:()=>{const T=new Set(C);T.has(E)?T.delete(E):T.add(E),i(Array.from(T))},className:"chat-sidebar-date-group-header",children:[r.jsxs(G,{align:"center",gap:"small",style:{minWidth:0},children:[M?r.jsx(Wt,{style:{fontSize:12,opacity:.6}}):r.jsx(Ws,{style:{fontSize:12,opacity:.6}}),r.jsxs("span",{style:{fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:E==="Today"?"var(--lotus-primary)":x.colorTextSecondary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[Au(E,w)," (",R,")"]})]}),r.jsx(Y,{type:"text",size:"small",icon:r.jsx(dn,{}),className:"chat-sidebar-date-group-delete",style:{color:x.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:T=>{T.stopPropagation(),u(E)}})]}),M?r.jsx("div",{style:{marginTop:4},children:r.jsx(nt,{itemLayout:"horizontal",dataSource:j,split:!1,renderItem:T=>{var P,S,L,$,I,W;return r.jsxs("div",{children:[r.jsxs(G,{align:"center",gap:6,children:[(P=t[T.id])!=null&&P.length?r.jsx(Y,{size:"small",type:"text",style:{padding:0,width:22},"aria-label":s.has(T.id)?w("chat.sidebar.actions.collapseChildren"):w("chat.sidebar.actions.expandChildren"),onClick:A=>{A.preventDefault(),A.stopPropagation(),n(T.id)},children:s.has(T.id)?r.jsx(Wt,{}):r.jsx(Ws,{})}):r.jsx("div",{style:{width:22}}),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsx(dc,{chat:T,isSelected:T.id===l,onSelect:c,onDelete:d,onPin:h,onUnpin:p,onEdit:g,onGenerateTitle:y,onRunProjectDream:f,isGeneratingTitle:((S=v[T.id])==null?void 0:S.status)==="loading",isRunningProjectDream:((L=b[T.id])==null?void 0:L.status)==="loading",titleGenerationError:(($=v[T.id])==null?void 0:$.status)==="error"?(I=v[T.id])==null?void 0:I.error:void 0})})]}),s.has(T.id)&&(((W=t[T.id])==null?void 0:W.length)??0)>0?r.jsx("div",{style:{marginLeft:22,marginTop:2},children:r.jsx(nt,{itemLayout:"horizontal",dataSource:t[T.id],split:!1,renderItem:A=>{var O,D,H,B;return r.jsx("div",{style:{paddingLeft:12},children:r.jsx(dc,{chat:A,isSelected:A.id===l,onSelect:c,onDelete:d,onPin:h,onUnpin:p,onEdit:g,onGenerateTitle:y,onRunProjectDream:f,isGeneratingTitle:((O=v[A.id])==null?void 0:O.status)==="loading",isRunningProjectDream:((D=b[A.id])==null?void 0:D.status)==="loading",titleGenerationError:((H=v[A.id])==null?void 0:H.status)==="error"?(B=v[A.id])==null?void 0:B.error:void 0})},A.id)}})}):null]},T.id)}})}):null]},E)})})},TS="copilot_ui_theme_v1";function kS(){var e;try{const t=localStorage.getItem(TS);if(t==="light"||t==="dark")return t}catch{}return(e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const qn=un(e=>({themeMode:kS(),setThemeMode:t=>e({themeMode:t}),toggleTheme:()=>e(t=>({themeMode:t.themeMode==="dark"?"light":"dark"}))})),jS="2026.4.24",CS={version:jS},xd=CS.version,{Text:MS}=le,PS=({collapsed:e,onNewChat:t,onOpenSettings:s,screens:n,token:o})=>{const{t:a}=ne(),i=qn(h=>h.themeMode),l=qn(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(G,{vertical:!0,gap:e?"small":"middle",style:{padding:e?10:16,background:"transparent",borderTop:`1px solid ${o.colorBorderSecondary}`},children:[r.jsx(Y,{"data-testid":"new-chat","data-tour-id":"new-session",type:"primary",icon:r.jsx(Us,{}),onClick:t,block:!e,shape:"default",size:e?"large":n.xs?"small":"middle",title:c,"aria-label":c,className:"lotus-primary-cta",style:{...e?{width:"44px",height:"44px",margin:"0 auto"}:{},borderRadius:o.borderRadiusLG,minHeight:e?44:46,fontWeight:600},children:!e&&c}),r.jsxs(G,{gap:8,align:"center",children:[r.jsx(Y,{"data-testid":"open-settings","data-tour-id":"open-settings",icon:r.jsx(da,{}),onClick:s,block:!e,shape:"default",size:e?"large":n.xs?"small":"middle",title: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(ke,{title:u,placement:"top",children:r.jsx(Y,{"data-testid":"toggle-theme",type:"text",icon:i==="dark"?r.jsx(ix,{}):r.jsx(lx,{}),onClick:l,"aria-label":u,className:"lotus-toolbar-icon",style:{width:44,height:44,borderRadius:o.borderRadiusLG,flexShrink:0}})})]}),!e&&r.jsxs(MS,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:o.fontSizeSM,textAlign:"center",userSelect:"text"},children:[a("settings.appTab.runningVersion","Running version"),": v",xd]})]})},Iu="provider",Bs=un(e=>({isOpen:!1,origin:"chat",activeTabKey:Iu,open:(t,s=Iu)=>e({isOpen:!0,origin:t,activeTabKey:s}),close:()=>e({isOpen:!1}),setActiveTabKey:t=>e({activeTabKey:t})}));function ve(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 q(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 Yf=function(){const{crypto:e}=globalThis;if(e!=null&&e.randomUUID)return Yf=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 uc(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const mc=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 Se extends Error{}class St extends Se{constructor(t,s,n,o){super(`${St.makeMessage(t,s,n)}`),this.status=t,this.headers=o,this.requestID=o==null?void 0:o.get("x-request-id"),this.error=s;const a=s;this.code=a==null?void 0:a.code,this.param=a==null?void 0:a.param,this.type=a==null?void 0:a.type}static makeMessage(t,s,n){const o=s!=null&&s.message?typeof s.message=="string"?s.message:JSON.stringify(s.message):s?JSON.stringify(s):n;return t&&o?`${t} ${o}`:t?`${t} status code (no body)`:o||"(no status code or body)"}static generate(t,s,n,o){if(!t||!o)return new Fi({message:n,cause:mc(s)});const a=s==null?void 0:s.error;return t===400?new Xf(t,a,n,o):t===401?new Vf(t,a,n,o):t===403?new Kf(t,a,n,o):t===404?new Gf(t,a,n,o):t===409?new Jf(t,a,n,o):t===422?new Qf(t,a,n,o):t===429?new Zf(t,a,n,o):t>=500?new eg(t,a,n,o):new St(t,a,n,o)}}class Qt extends St{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class Fi extends St{constructor({message:t,cause:s}){super(void 0,void 0,t||"Connection error.",void 0),s&&(this.cause=s)}}class vd extends Fi{constructor({message:t}={}){super({message:t??"Request timed out."})}}class Xf extends St{}class Vf extends St{}class Kf extends St{}class Gf extends St{}class Jf extends St{}class Qf extends St{}class Zf extends St{}class eg extends St{}class tg extends Se{constructor(){super("Could not parse response content as the length limit was reached")}}class sg extends Se{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Lo extends Error{constructor(t){super(t)}}const ES=/^[a-z][a-z0-9+.-]*:/i,RS=e=>ES.test(e);let $t=e=>($t=Array.isArray,$t(e)),$u=$t;function AS(e){return typeof e!="object"?{}:e??{}}function IS(e){if(!e)return!0;for(const t in e)return!1;return!0}function $S(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function al(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}const DS=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new Se(`${e} must be an integer`);if(t<0)throw new Se(`${e} must be a positive integer`);return t},LS=e=>{try{return JSON.parse(e)}catch{return}},ga=e=>new Promise(t=>setTimeout(t,e)),ir="5.10.2",OS=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function FS(){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 zS=()=>{var s;const e=FS();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ir,"X-Stainless-OS":Lu(Deno.build.os),"X-Stainless-Arch":Du(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":ir,"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":ir,"X-Stainless-OS":Lu(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Du(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=NS();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ir,"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":ir,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function NS(){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 Du=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",Lu=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 Ou;const BS=()=>Ou??(Ou=zS());function WS(){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 ng(...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 rg(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ng({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 og(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 US(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 qS=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),ag="RFC3986",ig=e=>String(e),Fu={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:ig},HS="RFC1738";let hc=(e,t)=>(hc=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),hc(e,t));const xs=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),il=1024,YS=(e,t,s,n,o)=>{if(e.length===0)return e;let a=e;if(typeof e=="symbol"?a=Symbol.prototype.toString.call(e):typeof e!="string"&&(a=String(e)),s==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<a.length;l+=il){const c=a.length>=il?a.slice(l,l+il):a,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===HS&&(h===40||h===41)){d[d.length]=c.charAt(u);continue}if(h<128){d[d.length]=xs[h];continue}if(h<2048){d[d.length]=xs[192|h>>6]+xs[128|h&63];continue}if(h<55296||h>=57344){d[d.length]=xs[224|h>>12]+xs[128|h>>6&63]+xs[128|h&63];continue}u+=1,h=65536+((h&1023)<<10|c.charCodeAt(u)&1023),d[d.length]=xs[240|h>>18]+xs[128|h>>12&63]+xs[128|h>>6&63]+xs[128|h&63]}i+=d.join("")}return i};function XS(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function zu(e,t){if($t(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}const lg={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},cg=function(e,t){Array.prototype.push.apply(e,$t(t)?t:[t])};let Nu;const dt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:YS,encodeValuesOnly:!1,format:ag,formatter:ig,indices:!1,serializeDate(e){return(Nu??(Nu=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function VS(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}const ll={};function dg(e,t,s,n,o,a,i,l,c,d,u,h,p,g,y,f,v,b){let x=e,_=b,w=0,k=!1;for(;(_=_.get(ll))!==void 0&&!k;){const M=_.get(e);if(w+=1,typeof M<"u"){if(M===w)throw new RangeError("Cyclic object value");k=!0}typeof _.get(ll)>"u"&&(w=0)}if(typeof d=="function"?x=d(t,x):x instanceof Date?x=p==null?void 0:p(x):s==="comma"&&$t(x)&&(x=zu(x,function(M){return M instanceof Date?p==null?void 0:p(M):M})),x===null){if(a)return c&&!f?c(t,dt.encoder,v,"key",g):t;x=""}if(VS(x)||XS(x)){if(c){const M=f?t:c(t,dt.encoder,v,"key",g);return[(y==null?void 0:y(M))+"="+(y==null?void 0:y(c(x,dt.encoder,v,"value",g)))]}return[(y==null?void 0:y(t))+"="+(y==null?void 0:y(String(x)))]}const C=[];if(typeof x>"u")return C;let E;if(s==="comma"&&$t(x))f&&c&&(x=zu(x,c)),E=[{value:x.length>0?x.join(",")||null:void 0}];else if($t(d))E=d;else{const M=Object.keys(x);E=u?M.sort(u):M}const j=l?String(t).replace(/\./g,"%2E"):String(t),R=n&&$t(x)&&x.length===1?j+"[]":j;if(o&&$t(x)&&x.length===0)return R+"[]";for(let M=0;M<E.length;++M){const T=E[M],P=typeof T=="object"&&typeof T.value<"u"?T.value:x[T];if(i&&P===null)continue;const S=h&&l?T.replace(/\./g,"%2E"):T,L=$t(x)?typeof s=="function"?s(R,S):R:R+(h?"."+S:"["+S+"]");b.set(e,w);const $=new WeakMap;$.set(ll,b),cg(C,dg(P,L,s,n,o,a,i,l,s==="comma"&&f&&$t(x)?null:c,d,u,h,p,g,y,f,v,$))}return C}function KS(e=dt){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||dt.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=ag;if(typeof e.format<"u"){if(!hc(Fu,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const n=Fu[s];let o=dt.filter;(typeof e.filter=="function"||$t(e.filter))&&(o=e.filter);let a;if(e.arrayFormat&&e.arrayFormat in lg?a=e.arrayFormat:"indices"in e?a=e.indices?"indices":"repeat":a=dt.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:dt.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:dt.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:dt.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:dt.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?dt.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:dt.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:dt.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:dt.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:dt.encodeValuesOnly,filter:o,format:s,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:dt.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:dt.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:dt.strictNullHandling}}function GS(e,t={}){let s=e;const n=KS(t);let o,a;typeof n.filter=="function"?(a=n.filter,s=a("",s)):$t(n.filter)&&(a=n.filter,o=a);const i=[];if(typeof s!="object"||s===null)return"";const l=lg[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 g=o[p];n.skipNulls&&s[g]===null||cg(i,dg(s[g],g,l,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,d))}const u=i.join(n.delimiter);let h=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),u.length>0?h+u:""}function JS(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 Bu;function Sd(e){let t;return(Bu??(t=new globalThis.TextEncoder,Bu=t.encode.bind(t)))(e)}let Wu;function Uu(e){let t;return(Wu??(t=new globalThis.TextDecoder,Wu=t.decode.bind(t)))(e)}var Ft,zt;class zi{constructor(){Ft.set(this,void 0),zt.set(this,void 0),ve(this,Ft,new Uint8Array),ve(this,zt,null)}decode(t){if(t==null)return[];const s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Sd(t):t;ve(this,Ft,JS([q(this,Ft,"f"),s]));const n=[];let o;for(;(o=QS(q(this,Ft,"f"),q(this,zt,"f")))!=null;){if(o.carriage&&q(this,zt,"f")==null){ve(this,zt,o.index);continue}if(q(this,zt,"f")!=null&&(o.index!==q(this,zt,"f")+1||o.carriage)){n.push(Uu(q(this,Ft,"f").subarray(0,q(this,zt,"f")-1))),ve(this,Ft,q(this,Ft,"f").subarray(q(this,zt,"f"))),ve(this,zt,null);continue}const a=q(this,zt,"f")!==null?o.preceding-1:o.preceding,i=Uu(q(this,Ft,"f").subarray(0,a));n.push(i),ve(this,Ft,q(this,Ft,"f").subarray(o.index)),ve(this,zt,null)}return n}flush(){return q(this,Ft,"f").length?this.decode(`
|
|
13
|
+
`):[]}}Ft=new WeakMap,zt=new WeakMap;zi.NEWLINE_CHARS=new Set([`
|
|
14
|
+
`,"\r"]);zi.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function QS(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 ZS(e){for(let n=0;n<e.length-1;n++){if(e[n]===10&&e[n+1]===10||e[n]===13&&e[n+1]===13)return n+2;if(e[n]===13&&e[n+1]===10&&n+3<e.length&&e[n+2]===13&&e[n+3]===10)return n+4}return-1}const bi={off:0,error:200,warn:300,info:400,debug:500},qu=(e,t,s)=>{if(e){if($S(bi,e))return e;xt(s).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(bi))}`)}};function Oo(){}function Pa(e,t,s){return!t||bi[e]>bi[s]?Oo:t[e].bind(t)}const ew={error:Oo,warn:Oo,info:Oo,debug:Oo};let Hu=new WeakMap;function xt(e){const t=e.logger,s=e.logLevel??"off";if(!t)return ew;const n=Hu.get(t);if(n&&n[0]===s)return n[1];const o={error:Pa("error",t,s),warn:Pa("warn",t,s),info:Pa("info",t,s),debug:Pa("debug",t,s)};return Hu.set(t,[s,o]),o}const _n=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 Fr;class Cs{constructor(t,s,n){this.iterator=t,Fr.set(this,void 0),this.controller=s,ve(this,Fr,n)}static fromSSEResponse(t,s,n){let o=!1;const a=n?xt(n):console;async function*i(){if(o)throw new Se("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let l=!1;try{for await(const c of tw(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 St(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 St(void 0,d.error,d.message,void 0);yield{event:c.event,data:d}}}l=!0}catch(c){if(uc(c))return;throw c}finally{l||s.abort()}}return new Cs(i,s,n)}static fromReadableStream(t,s,n){let o=!1;async function*a(){const l=new zi,c=og(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 Se("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(uc(c))return;throw c}finally{l||s.abort()}}return new Cs(i,s,n)}[(Fr=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 Cs(()=>o(t),this.controller,q(this,Fr,"f")),new Cs(()=>o(s),this.controller,q(this,Fr,"f"))]}toReadableStream(){const t=this;let s;return ng({async start(){s=t[Symbol.asyncIterator]()},async pull(n){try{const{value:o,done:a}=await s.next();if(a)return n.close();const i=Sd(JSON.stringify(o)+`
|
|
15
|
+
`);n.enqueue(i)}catch(o){n.error(o)}},async cancel(){var n;await((n=s.return)==null?void 0:n.call(s))}})}}async function*tw(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Se("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 Se("Attempted to iterate over a response with no body");const s=new nw,n=new zi,o=og(e.body);for await(const a of sw(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*sw(e){let t=new Uint8Array;for await(const s of e){if(s==null)continue;const n=s instanceof ArrayBuffer?new Uint8Array(s):typeof s=="string"?Sd(s):s;let o=new Uint8Array(t.length+n.length);o.set(t),o.set(n,t.length),t=o;let a;for(;(a=ZS(t))!==-1;)yield t.slice(0,a),t=t.slice(a)}t.length>0&&(yield t)}class nw{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]=rw(t,":");return o.startsWith(" ")&&(o=o.substring(1)),s==="event"?this.event=o:s==="data"&&this.data.push(o),null}}function rw(e,t){const s=e.indexOf(t);return s!==-1?[e.substring(0,s),t,e.substring(s+t.length)]:[e,"",""]}async function ug(e,t){const{response:s,requestLogID:n,retryOfRequestLogID:o,startTime:a}=t,i=await(async()=>{var h;if(t.options.stream)return xt(e).debug("response",s.status,s.url,s.headers,s.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(s,t.controller,e):Cs.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 mg(p,s)}return await s.text()})();return xt(e).debug(`[${n}] response parsed`,_n({retryOfRequestLogID:o,url:s.url,status:s.status,body:i,durationMs:Date.now()-a})),i}function mg(e,t){return!e||typeof e!="object"||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}var Fo;class Ni extends Promise{constructor(t,s,n=ug){super(o=>{o(null)}),this.responsePromise=s,this.parseResponse=n,Fo.set(this,void 0),ve(this,Fo,t)}_thenUnwrap(t){return new Ni(q(this,Fo,"f"),this.responsePromise,async(s,n)=>mg(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(q(this,Fo,"f"),t))),this.parsedPromise}then(t,s){return this.parse().then(t,s)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}}Fo=new WeakMap;var Ea;class hg{constructor(t,s,n,o){Ea.set(this,void 0),ve(this,Ea,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 Se("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await q(this,Ea,"f").requestAPIList(this.constructor,t)}async*iterPages(){let t=this;for(yield t;t.hasNextPage();)t=await t.getNextPage(),yield t}async*[(Ea=new WeakMap,Symbol.asyncIterator)](){for await(const t of this.iterPages())for(const s of t.getPaginatedItems())yield s}}class ow extends Ni{constructor(t,s,n){super(t,s,async(o,a)=>new n(o,a.response,await ug(o,a),a.options))}async*[Symbol.asyncIterator](){const t=await this;for await(const s of t)yield s}}class Bi extends hg{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 lt extends hg{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:{...AS(this.options.query),after:s}}:null}}const pg=()=>{var e;if(typeof File>"u"){const{process:t}=globalThis,s=typeof((e=t==null?void 0:t.versions)==null?void 0:e.node)=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(s?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Ko(e,t,s){return pg(),new File(e,t??"unknown_file",s)}function Ga(e){return(typeof e=="object"&&e!==null&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}const fg=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",Hn=async(e,t)=>({...e,body:await iw(e.body,t)}),Yu=new WeakMap;function aw(e){const t=typeof e=="function"?e:e.fetch,s=Yu.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 Yu.set(t,n),n}const iw=async(e,t)=>{if(!await aw(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])=>pc(s,n,o))),s},lw=e=>e instanceof Blob&&"name"in e,pc=async(e,t,s)=>{if(s!==void 0){if(s==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")e.append(t,String(s));else if(s instanceof Response)e.append(t,Ko([await s.blob()],Ga(s)));else if(fg(s))e.append(t,Ko([await new Response(rg(s)).blob()],Ga(s)));else if(lw(s))e.append(t,s,Ga(s));else if(Array.isArray(s))await Promise.all(s.map(n=>pc(e,t+"[]",n)));else if(typeof s=="object")await Promise.all(Object.entries(s).map(([n,o])=>pc(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`)}},gg=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",cw=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&gg(e),dw=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function uw(e,t,s){if(pg(),e=await e,cw(e))return e instanceof File?e:Ko([await e.arrayBuffer()],e.name);if(dw(e)){const o=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Ko(await fc(o),t,s)}const n=await fc(e);if(t||(t=Ga(e)),!(s!=null&&s.type)){const o=n.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof o=="string"&&(s={...s,type:o})}return Ko(n,t,s)}async function fc(e){var s;let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(gg(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(fg(e))for await(const n of e)t.push(...await fc(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}`:""}${mw(e)}`)}return t}function mw(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(s=>`"${s}"`).join(", ")}]`}class we{constructor(t){this._client=t}}function yg(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Xu=Object.freeze(Object.create(null)),hw=(e=yg)=>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 g=n[p];let y=(o?encodeURIComponent:e)(""+g);return p!==n.length&&(g==null||typeof g=="object"&&g.toString===((f=Object.getPrototypeOf(Object.getPrototypeOf(g.hasOwnProperty??Xu)??Xu))==null?void 0:f.toString))&&(y=g+"",a.push({start:u.length+h.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(g).slice(8,-1)} is not a valid path parameter`})),u+h+(p===n.length?"":y)},""),l=i.split(/[?#]/,1)[0],c=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let d;for(;(d=c.exec(l))!==null;)a.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(a.sort((u,h)=>u.start-h.start),a.length>0){let u=0;const h=a.reduce((p,g)=>{const y=" ".repeat(g.start-u),f="^".repeat(g.length);return u=g.start+g.length,p+y+f},"");throw new Se(`Path parameters result in path with invalid segments:
|
|
17
|
+
${a.map(p=>p.error).join(`
|
|
18
|
+
`)}
|
|
19
|
+
${i}
|
|
20
|
+
${h}`)}return i},ie=hw(yg);let bg=class extends we{list(t,s={},n){return this._client.getAPIList(ie`/chat/completions/${t}/messages`,lt,{query:s,...n})}};function pw(e){return typeof e.parse=="function"}const xi=e=>(e==null?void 0:e.role)==="assistant",xg=e=>(e==null?void 0:e.role)==="tool";var gc,Ja,Qa,zo,No,Za,Bo,zs,Wo,vi,Si,lr,vg;class wd{constructor(){gc.add(this),this.controller=new AbortController,Ja.set(this,void 0),Qa.set(this,()=>{}),zo.set(this,()=>{}),No.set(this,void 0),Za.set(this,()=>{}),Bo.set(this,()=>{}),zs.set(this,{}),Wo.set(this,!1),vi.set(this,!1),Si.set(this,!1),lr.set(this,!1),ve(this,Ja,new Promise((t,s)=>{ve(this,Qa,t,"f"),ve(this,zo,s,"f")})),ve(this,No,new Promise((t,s)=>{ve(this,Za,t,"f"),ve(this,Bo,s,"f")})),q(this,Ja,"f").catch(()=>{}),q(this,No,"f").catch(()=>{})}_run(t){setTimeout(()=>{t().then(()=>{this._emitFinal(),this._emit("end")},q(this,gc,"m",vg).bind(this))},0)}_connected(){this.ended||(q(this,Qa,"f").call(this),this._emit("connect"))}get ended(){return q(this,Wo,"f")}get errored(){return q(this,vi,"f")}get aborted(){return q(this,Si,"f")}abort(){this.controller.abort()}on(t,s){return(q(this,zs,"f")[t]||(q(this,zs,"f")[t]=[])).push({listener:s}),this}off(t,s){const n=q(this,zs,"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(q(this,zs,"f")[t]||(q(this,zs,"f")[t]=[])).push({listener:s,once:!0}),this}emitted(t){return new Promise((s,n)=>{ve(this,lr,!0),t!=="error"&&this.once("error",n),this.once(t,s)})}async done(){ve(this,lr,!0),await q(this,No,"f")}_emit(t,...s){if(q(this,Wo,"f"))return;t==="end"&&(ve(this,Wo,!0),q(this,Za,"f").call(this));const n=q(this,zs,"f")[t];if(n&&(q(this,zs,"f")[t]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...s))),t==="abort"){const o=s[0];!q(this,lr,"f")&&!(n!=null&&n.length)&&Promise.reject(o),q(this,zo,"f").call(this,o),q(this,Bo,"f").call(this,o),this._emit("end");return}if(t==="error"){const o=s[0];!q(this,lr,"f")&&!(n!=null&&n.length)&&Promise.reject(o),q(this,zo,"f").call(this,o),q(this,Bo,"f").call(this,o),this._emit("end")}}_emitFinal(){}}Ja=new WeakMap,Qa=new WeakMap,zo=new WeakMap,No=new WeakMap,Za=new WeakMap,Bo=new WeakMap,zs=new WeakMap,Wo=new WeakMap,vi=new WeakMap,Si=new WeakMap,lr=new WeakMap,gc=new WeakSet,vg=function(t){if(ve(this,vi,!0),t instanceof Error&&t.name==="AbortError"&&(t=new Qt),t instanceof Qt)return ve(this,Si,!0),this._emit("abort",t);if(t instanceof Se)return this._emit("error",t);if(t instanceof Error){const s=new Se(t.message);return s.cause=t,this._emit("error",s)}return this._emit("error",new Se(String(t)))};function _d(e){return(e==null?void 0:e.$brand)==="auto-parseable-response-format"}function ya(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function fw(e,t){return!t||!Sg(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}}))}:Td(e,t)}function Td(e,t){const s=e.choices.map(n=>{var o;if(n.finish_reason==="length")throw new tg;if(n.finish_reason==="content_filter")throw new sg;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((o=n.message.tool_calls)==null?void 0:o.map(a=>yw(t,a)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?gw(t,n.message.content):null}}});return{...e,choices:s}}function gw(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 yw(e,t){var n;const s=(n=e.tools)==null?void 0:n.find(o=>{var a;return((a=o.function)==null?void 0:a.name)===t.function.name});return{...t,function:{...t.function,parsed_arguments:ya(s)?s.$parseRaw(t.function.arguments):s!=null&&s.function.strict?JSON.parse(t.function.arguments):null}}}function bw(e,t){var n;if(!e)return!1;const s=(n=e.tools)==null?void 0:n.find(o=>{var a;return((a=o.function)==null?void 0:a.name)===t.function.name});return ya(s)||(s==null?void 0:s.function.strict)||!1}function Sg(e){var t;return _d(e.response_format)?!0:((t=e.tools)==null?void 0:t.some(s=>ya(s)||s.type==="function"&&s.function.strict===!0))??!1}function xw(e){for(const t of e??[]){if(t.type!=="function")throw new Se(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new Se(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Et,yc,wi,bc,xc,vc,wg,_g;const vw=10;class Tg extends wd{constructor(){super(...arguments),Et.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),xg(t)&&t.content)this._emit("functionToolCallResult",t.content);else if(xi(t)&&t.tool_calls)for(const n of t.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();const t=this._chatCompletions[this._chatCompletions.length-1];if(!t)throw new Se("stream ended without producing a ChatCompletion");return t}async finalContent(){return await this.done(),q(this,Et,"m",yc).call(this)}async finalMessage(){return await this.done(),q(this,Et,"m",wi).call(this)}async finalFunctionToolCall(){return await this.done(),q(this,Et,"m",bc).call(this)}async finalFunctionToolCallResult(){return await this.done(),q(this,Et,"m",xc).call(this)}async totalUsage(){return await this.done(),q(this,Et,"m",vc).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const t=this._chatCompletions[this._chatCompletions.length-1];t&&this._emit("finalChatCompletion",t);const s=q(this,Et,"m",wi).call(this);s&&this._emit("finalMessage",s);const n=q(this,Et,"m",yc).call(this);n&&this._emit("finalContent",n);const o=q(this,Et,"m",bc).call(this);o&&this._emit("finalFunctionToolCall",o);const a=q(this,Et,"m",xc).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",q(this,Et,"m",vc).call(this))}async _createChatCompletion(t,s,n){const o=n==null?void 0:n.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),q(this,Et,"m",wg).call(this,s);const a=await t.chat.completions.create({...s,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Td(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 g,y,f;const o="tool",{tool_choice:a="auto",stream:i,...l}=s,c=typeof a!="string"&&((g=a==null?void 0:a.function)==null?void 0:g.name),{maxChatCompletions:d=vw}=n||{},u=s.tools.map(v=>{if(ya(v)){if(!v.$callback)throw new Se("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:v.$callback,name:v.function.name,description:v.function.description||"",parameters:v.function.parameters,parse:v.$parseRaw,strict:!0}}}return v}),h={};for(const v of u)v.type==="function"&&(h[v.function.name||v.function.function.name]=v.function);const p="tools"in s?u.map(v=>v.type==="function"?{type:"function",function:{name:v.function.name||v.function.function.name,parameters:v.function.parameters,description:v.function.description,strict:v.function.strict}}:v):void 0;for(const v of s.messages)this._addMessage(v,!1);for(let v=0;v<d;++v){const x=(y=(await this._createChatCompletion(t,{...l,tool_choice:a,tools:p,messages:[...this.messages]},n)).choices[0])==null?void 0:y.message;if(!x)throw new Se("missing message in ChatCompletion response");if(!((f=x.tool_calls)!=null&&f.length))return;for(const _ of x.tool_calls){if(_.type!=="function")continue;const w=_.id,{name:k,arguments:C}=_.function,E=h[k];if(E){if(c&&c!==k){const T=`Invalid tool_call: ${JSON.stringify(k)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:o,tool_call_id:w,content:T});continue}}else{const T=`Invalid tool_call: ${JSON.stringify(k)}. Available options are: ${Object.keys(h).map(P=>JSON.stringify(P)).join(", ")}. Please try again`;this._addMessage({role:o,tool_call_id:w,content:T});continue}let j;try{j=pw(E)?await E.parse(C):C}catch(T){const P=T instanceof Error?T.message:String(T);this._addMessage({role:o,tool_call_id:w,content:P});continue}const R=await E.function(j,this),M=q(this,Et,"m",_g).call(this,R);if(this._addMessage({role:o,tool_call_id:w,content:M}),c)return}}}}Et=new WeakSet,yc=function(){return q(this,Et,"m",wi).call(this).content??null},wi=function(){let t=this.messages.length;for(;t-- >0;){const s=this.messages[t];if(xi(s))return{...s,content:s.content??null,refusal:s.refusal??null}}throw new Se("stream ended without producing a ChatCompletionMessage with role=assistant")},bc=function(){var t,s;for(let n=this.messages.length-1;n>=0;n--){const o=this.messages[n];if(xi(o)&&((t=o==null?void 0:o.tool_calls)!=null&&t.length))return(s=o.tool_calls.at(-1))==null?void 0:s.function}},xc=function(){for(let t=this.messages.length-1;t>=0;t--){const s=this.messages[t];if(xg(s)&&s.content!=null&&typeof s.content=="string"&&this.messages.some(n=>{var o;return n.role==="assistant"&&((o=n.tool_calls)==null?void 0:o.some(a=>a.type==="function"&&a.id===s.tool_call_id))}))return s.content}},vc=function(){const t={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:s}of this._chatCompletions)s&&(t.completion_tokens+=s.completion_tokens,t.prompt_tokens+=s.prompt_tokens,t.total_tokens+=s.total_tokens);return t},wg=function(t){if(t.n!=null&&t.n>1)throw new Se("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},_g=function(t){return typeof t=="string"?t:t===void 0?"undefined":JSON.stringify(t)};class kd extends Tg{static runTools(t,s,n){const o=new kd,a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(t,s,a)),o}_addMessage(t,s=!0){super._addMessage(t,s),xi(t)&&t.content&&this._emit("content",t.content)}}const kg=1,jg=2,Cg=4,Mg=8,Pg=16,Eg=32,Rg=64,Ag=128,Ig=256,$g=Ag|Ig,Dg=Pg|Eg|$g|Rg,Lg=kg|jg|Dg,Og=Cg|Mg,Sw=Lg|Og,ft={STR:kg,NUM:jg,ARR:Cg,OBJ:Mg,NULL:Pg,BOOL:Eg,NAN:Rg,INFINITY:Ag,MINUS_INFINITY:Ig,INF:$g,SPECIAL:Dg,ATOM:Lg,COLLECTION:Og,ALL:Sw};class ww extends Error{}class _w extends Error{}function Tw(e,t=ft.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return kw(e.trim(),t)}const kw=(e,t)=>{const s=e.length;let n=0;const o=p=>{throw new ww(`${p} at position ${n}`)},a=p=>{throw new _w(`${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"||ft.NULL&t&&s-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):e.substring(n,n+4)==="true"||ft.BOOL&t&&s-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):e.substring(n,n+5)==="false"||ft.BOOL&t&&s-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):e.substring(n,n+8)==="Infinity"||ft.INFINITY&t&&s-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):e.substring(n,n+9)==="-Infinity"||ft.MINUS_INFINITY&t&&1<s-n&&s-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):e.substring(n,n+3)==="NaN"||ft.NAN&t&&s-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):u()),l=()=>{const p=n;let g=!1;for(n++;n<s&&(e[n]!=='"'||g&&e[n-1]==="\\");)g=e[n]==="\\"?!g:!1,n++;if(e.charAt(n)=='"')try{return JSON.parse(e.substring(p,++n-Number(g)))}catch(y){a(String(y))}else if(ft.STR&t)try{return JSON.parse(e.substring(p,n-Number(g))+'"')}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&&ft.OBJ&t)return p;const g=l();h(),n++;try{const y=i();Object.defineProperty(p,g,{value:y,writable:!0,enumerable:!0,configurable:!0})}catch(y){if(ft.OBJ&t)return p;throw y}h(),e[n]===","&&n++}}catch{if(ft.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(ft.ARR&t)return p;o("Expected ']' at end of array")}return n++,p},u=()=>{if(n===0){e==="-"&&ft.NUM&t&&o("Not sure what '-' is");try{return JSON.parse(e)}catch(g){if(ft.NUM&t)try{return e[e.length-1]==="."?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(g))}}const p=n;for(e[n]==="-"&&n++;e[n]&&!",]}".includes(e[n]);)n++;n==s&&!(ft.NUM&t)&&o("Unterminated number literal");try{return JSON.parse(e.substring(p,n))}catch{e.substring(p,n)==="-"&&ft.NUM&t&&o("Not sure what '-' is");try{return JSON.parse(e.substring(p,e.lastIndexOf("e")))}catch(y){a(String(y))}}},h=()=>{for(;n<s&&`
|
|
21
|
+
\r `.includes(e[n]);)n++};return i()},Vu=e=>Tw(e,ft.ALL^ft.NUM);var ct,$s,Jn,Js,cl,Ra,dl,ul,ml,Aa,hl,Ku;class ra extends Tg{constructor(t){super(),ct.add(this),$s.set(this,void 0),Jn.set(this,void 0),Js.set(this,void 0),ve(this,$s,t),ve(this,Jn,[])}get currentChatCompletionSnapshot(){return q(this,Js,"f")}static fromReadableStream(t){const s=new ra(null);return s._run(()=>s._fromReadableStream(t)),s}static createChatCompletion(t,s,n){const o=new ra(s);return o._run(()=>o._runChatCompletion(t,{...s,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(t,s,n){var i;super._createChatCompletion;const o=n==null?void 0:n.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),q(this,ct,"m",cl).call(this);const a=await t.chat.completions.create({...s,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const l of a)q(this,ct,"m",dl).call(this,l);if((i=a.controller.signal)!=null&&i.aborted)throw new Qt;return this._addChatCompletion(q(this,ct,"m",Aa).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())),q(this,ct,"m",cl).call(this),this._connected();const o=Cs.fromReadableStream(t,this.controller);let a;for await(const l of o)a&&a!==l.id&&this._addChatCompletion(q(this,ct,"m",Aa).call(this)),q(this,ct,"m",dl).call(this,l),a=l.id;if((i=o.controller.signal)!=null&&i.aborted)throw new Qt;return this._addChatCompletion(q(this,ct,"m",Aa).call(this))}[($s=new WeakMap,Jn=new WeakMap,Js=new WeakMap,ct=new WeakSet,cl=function(){this.ended||ve(this,Js,void 0)},Ra=function(s){let n=q(this,Jn,"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},q(this,Jn,"f")[s.index]=n,n)},dl=function(s){var o,a,i,l,c,d,u,h,p,g,y,f,v,b,x;if(this.ended)return;const n=q(this,ct,"m",Ku).call(this,s);this._emit("chunk",s,n);for(const _ of s.choices){const w=n.choices[_.index];_.delta.content!=null&&((o=w.message)==null?void 0:o.role)==="assistant"&&((a=w.message)!=null&&a.content)&&(this._emit("content",_.delta.content,w.message.content),this._emit("content.delta",{delta:_.delta.content,snapshot:w.message.content,parsed:w.message.parsed})),_.delta.refusal!=null&&((i=w.message)==null?void 0:i.role)==="assistant"&&((l=w.message)!=null&&l.refusal)&&this._emit("refusal.delta",{delta:_.delta.refusal,snapshot:w.message.refusal}),((c=_.logprobs)==null?void 0:c.content)!=null&&((d=w.message)==null?void 0:d.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(u=_.logprobs)==null?void 0:u.content,snapshot:((h=w.logprobs)==null?void 0:h.content)??[]}),((p=_.logprobs)==null?void 0:p.refusal)!=null&&((g=w.message)==null?void 0:g.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(y=_.logprobs)==null?void 0:y.refusal,snapshot:((f=w.logprobs)==null?void 0:f.refusal)??[]});const k=q(this,ct,"m",Ra).call(this,w);w.finish_reason&&(q(this,ct,"m",ml).call(this,w),k.current_tool_call_index!=null&&q(this,ct,"m",ul).call(this,w,k.current_tool_call_index));for(const C of _.delta.tool_calls??[])k.current_tool_call_index!==C.index&&(q(this,ct,"m",ml).call(this,w),k.current_tool_call_index!=null&&q(this,ct,"m",ul).call(this,w,k.current_tool_call_index)),k.current_tool_call_index=C.index;for(const C of _.delta.tool_calls??[]){const E=(v=w.message.tool_calls)==null?void 0:v[C.index];E!=null&&E.type&&((E==null?void 0:E.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(b=E.function)==null?void 0:b.name,index:C.index,arguments:E.function.arguments,parsed_arguments:E.function.parsed_arguments,arguments_delta:((x=C.function)==null?void 0:x.arguments)??""}):(E==null||E.type,void 0))}}},ul=function(s,n){var i,l,c;if(q(this,ct,"m",Ra).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=q(this,$s,"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:ya(d)?d.$parseRaw(a.function.arguments):d!=null&&d.function.strict?JSON.parse(a.function.arguments):null})}else a.type},ml=function(s){var o,a;const n=q(this,ct,"m",Ra).call(this,s);if(s.message.content&&!n.content_done){n.content_done=!0;const i=q(this,ct,"m",hl).call(this);this._emit("content.done",{content:s.message.content,parsed:i?i.$parseRaw(s.message.content):null})}s.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:s.message.refusal})),(o=s.logprobs)!=null&&o.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:s.logprobs.content})),(a=s.logprobs)!=null&&a.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:s.logprobs.refusal}))},Aa=function(){if(this.ended)throw new Se("stream has ended, this shouldn't happen");const s=q(this,Js,"f");if(!s)throw new Se("request ended without sending any chunks");return ve(this,Js,void 0),ve(this,Jn,[]),jw(s,q(this,$s,"f"))},hl=function(){var n;const s=(n=q(this,$s,"f"))==null?void 0:n.response_format;return _d(s)?s:null},Ku=function(s){var n,o,a,i;let l=q(this,Js,"f");const{choices:c,...d}=s;l?Object.assign(l,d):l=ve(this,Js,{...d,choices:[]});for(const{delta:u,finish_reason:h,index:p,logprobs:g=null,...y}of s.choices){let f=l.choices[p];if(f||(f=l.choices[p]={finish_reason:h,index:p,message:{},logprobs:g,...y}),g)if(!f.logprobs)f.logprobs=Object.assign({},g);else{const{content:C,refusal:E,...j}=g;Object.assign(f.logprobs,j),C&&((n=f.logprobs).content??(n.content=[]),f.logprobs.content.push(...C)),E&&((o=f.logprobs).refusal??(o.refusal=[]),f.logprobs.refusal.push(...E))}if(h&&(f.finish_reason=h,q(this,$s,"f")&&Sg(q(this,$s,"f")))){if(h==="length")throw new tg;if(h==="content_filter")throw new sg}if(Object.assign(f,y),!u)continue;const{content:v,refusal:b,function_call:x,role:_,tool_calls:w,...k}=u;if(Object.assign(f.message,k),b&&(f.message.refusal=(f.message.refusal||"")+b),_&&(f.message.role=_),x&&(f.message.function_call?(x.name&&(f.message.function_call.name=x.name),x.arguments&&((a=f.message.function_call).arguments??(a.arguments=""),f.message.function_call.arguments+=x.arguments)):f.message.function_call=x),v&&(f.message.content=(f.message.content||"")+v,!f.message.refusal&&q(this,ct,"m",hl).call(this)&&(f.message.parsed=Vu(f.message.content))),w){f.message.tool_calls||(f.message.tool_calls=[]);for(const{index:C,id:E,type:j,function:R,...M}of w){const T=(i=f.message.tool_calls)[C]??(i[C]={});Object.assign(T,M),E&&(T.id=E),j&&(T.type=j),R&&(T.function??(T.function={name:R.name??"",arguments:""})),R!=null&&R.name&&(T.function.name=R.name),R!=null&&R.arguments&&(T.function.arguments+=R.arguments,bw(q(this,$s,"f"),T)&&(T.function.parsed_arguments=Vu(T.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 Cs(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function jw(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,...g})=>{if(!u)throw new Se(`missing finish_reason for choice ${h}`);const{content:y=null,function_call:f,tool_calls:v,...b}=d,x=d.role;if(!x)throw new Se(`missing role for choice ${h}`);if(f){const{arguments:_,name:w}=f;if(_==null)throw new Se(`missing function_call.arguments for choice ${h}`);if(!w)throw new Se(`missing function_call.name for choice ${h}`);return{...g,message:{content:y,function_call:{arguments:_,name:w},role:x,refusal:d.refusal??null},finish_reason:u,index:h,logprobs:p}}return v?{...g,index:h,finish_reason:u,logprobs:p,message:{...b,role:x,content:y,refusal:d.refusal??null,tool_calls:v.map((_,w)=>{const{function:k,type:C,id:E,...j}=_,{arguments:R,name:M,...T}=k||{};if(E==null)throw new Se(`missing choices[${h}].tool_calls[${w}].id
|
|
22
|
+
${Ia(e)}`);if(C==null)throw new Se(`missing choices[${h}].tool_calls[${w}].type
|
|
23
|
+
${Ia(e)}`);if(M==null)throw new Se(`missing choices[${h}].tool_calls[${w}].function.name
|
|
24
|
+
${Ia(e)}`);if(R==null)throw new Se(`missing choices[${h}].tool_calls[${w}].function.arguments
|
|
25
|
+
${Ia(e)}`);return{...j,id:E,type:C,function:{...T,name:M,arguments:R}}})}}:{...g,message:{...b,content:y,role:x,refusal:d.refusal??null},finish_reason:u,index:h,logprobs:p}}),created:o,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return fw(c,t)}function Ia(e){return JSON.stringify(e)}class _i extends ra{static fromReadableStream(t){const s=new _i(null);return s._run(()=>s._fromReadableStream(t)),s}static runTools(t,s,n){const o=new _i(s),a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(t,s,a)),o}}let jd=class extends we{constructor(){super(...arguments),this.messages=new bg(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(ie`/chat/completions/${t}`,s)}update(t,s,n){return this._client.post(ie`/chat/completions/${t}`,{body:s,...n})}list(t={},s){return this._client.getAPIList("/chat/completions",lt,{query:t,...s})}delete(t,s){return this._client.delete(ie`/chat/completions/${t}`,s)}parse(t,s){return xw(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=>Td(n,t))}runTools(t,s){return t.stream?_i.runTools(this._client,t,s):kd.runTools(this._client,t,s)}stream(t,s){return ra.createChatCompletion(this._client,t,s)}};jd.Messages=bg;class Cd extends we{constructor(){super(...arguments),this.completions=new jd(this._client)}}Cd.Completions=jd;const Fg=Symbol("brand.privateNullableHeaders");function*Cw(e){if(!e)return;if(Fg 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():$u(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=$u(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 ge=e=>{const t=new Headers,s=new Set;for(const n of e){const o=new Set;for(const[a,i]of Cw(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{[Fg]:!0,values:t,nulls:s}};class zg extends we{create(t,s){return this._client.post("/audio/speech",{body:t,...s,headers:ge([{Accept:"application/octet-stream"},s==null?void 0:s.headers]),__binaryResponse:!0})}}class Ng extends we{create(t,s){return this._client.post("/audio/transcriptions",Hn({body:t,...s,stream:t.stream??!1,__metadata:{model:t.model}},this._client))}}class Bg extends we{create(t,s){return this._client.post("/audio/translations",Hn({body:t,...s,__metadata:{model:t.model}},this._client))}}class ba extends we{constructor(){super(...arguments),this.transcriptions=new Ng(this._client),this.translations=new Bg(this._client),this.speech=new zg(this._client)}}ba.Transcriptions=Ng;ba.Translations=Bg;ba.Speech=zg;class Wg extends we{create(t,s){return this._client.post("/batches",{body:t,...s})}retrieve(t,s){return this._client.get(ie`/batches/${t}`,s)}list(t={},s){return this._client.getAPIList("/batches",lt,{query:t,...s})}cancel(t,s){return this._client.post(ie`/batches/${t}/cancel`,s)}}class Ug extends we{create(t,s){return this._client.post("/assistants",{body:t,...s,headers:ge([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,s){return this._client.get(ie`/assistants/${t}`,{...s,headers:ge([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,s,n){return this._client.post(ie`/assistants/${t}`,{body:s,...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t={},s){return this._client.getAPIList("/assistants",lt,{query:t,...s,headers:ge([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}delete(t,s){return this._client.delete(ie`/assistants/${t}`,{...s,headers:ge([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class qg extends we{create(t,s){return this._client.post("/realtime/sessions",{body:t,...s,headers:ge([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class Hg extends we{create(t,s){return this._client.post("/realtime/transcription_sessions",{body:t,...s,headers:ge([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class Wi extends we{constructor(){super(...arguments),this.sessions=new qg(this._client),this.transcriptionSessions=new Hg(this._client)}}Wi.Sessions=qg;Wi.TranscriptionSessions=Hg;class Yg extends we{create(t,s,n){return this._client.post(ie`/threads/${t}/messages`,{body:s,...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,s,n){const{thread_id:o}=s;return this._client.get(ie`/threads/${o}/messages/${t}`,{...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,s,n){const{thread_id:o,...a}=s;return this._client.post(ie`/threads/${o}/messages/${t}`,{body:a,...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s={},n){return this._client.getAPIList(ie`/threads/${t}/messages`,lt,{query:s,...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,s,n){const{thread_id:o}=s;return this._client.delete(ie`/threads/${o}/messages/${t}`,{...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class Xg extends we{retrieve(t,s,n){const{thread_id:o,run_id:a,...i}=s;return this._client.get(ie`/threads/${o}/runs/${a}/steps/${t}`,{query:i,...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s,n){const{thread_id:o,...a}=s;return this._client.getAPIList(ie`/threads/${o}/runs/${t}/steps`,lt,{query:a,...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}const Mw=e=>{if(typeof Buffer<"u"){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{const t=atob(e),s=t.length,n=new Uint8Array(s);for(let o=0;o<s;o++)n[o]=t.charCodeAt(o);return Array.from(new Float32Array(n.buffer))}};var pl={};const Qn=e=>{var t,s,n,o;if(typeof globalThis.process<"u")return((t=pl==null?void 0:pl[e])==null?void 0:t.trim())??void 0;if(typeof globalThis.Deno<"u")return(o=(n=(s=globalThis.Deno.env)==null?void 0:s.get)==null?void 0:n.call(s,e))==null?void 0:o.trim()};var vt,Ln,Sc,_s,ei,ds,On,ur,Cn,Ti,Nt,ti,si,Go,Uo,qo,Gu,Ju,Qu,Zu,em,tm,sm;class Jo extends wd{constructor(){super(...arguments),vt.add(this),Sc.set(this,[]),_s.set(this,{}),ei.set(this,{}),ds.set(this,void 0),On.set(this,void 0),ur.set(this,void 0),Cn.set(this,void 0),Ti.set(this,void 0),Nt.set(this,void 0),ti.set(this,void 0),si.set(this,void 0),Go.set(this,void 0)}[(Sc=new WeakMap,_s=new WeakMap,ei=new WeakMap,ds=new WeakMap,On=new WeakMap,ur=new WeakMap,Cn=new WeakMap,Ti=new WeakMap,Nt=new WeakMap,ti=new WeakMap,si=new WeakMap,Go=new WeakMap,vt=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 Ln;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=Cs.fromReadableStream(t,this.controller);for await(const i of o)q(this,vt,"m",Uo).call(this,i);if((a=o.controller.signal)!=null&&a.aborted)throw new Qt;return this._addRun(q(this,vt,"m",qo).call(this))}toReadableStream(){return new Cs(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,s,n,o){const a=new Ln;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)q(this,vt,"m",Uo).call(this,d);if((c=l.controller.signal)!=null&&c.aborted)throw new Qt;return this._addRun(q(this,vt,"m",qo).call(this))}static createThreadAssistantStream(t,s,n){const o=new Ln;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 Ln;return a._run(()=>a._runAssistantStream(t,s,n,{...o,headers:{...o==null?void 0:o.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return q(this,ti,"f")}currentRun(){return q(this,si,"f")}currentMessageSnapshot(){return q(this,ds,"f")}currentRunStepSnapshot(){return q(this,Go,"f")}async finalRunSteps(){return await this.done(),Object.values(q(this,_s,"f"))}async finalMessages(){return await this.done(),Object.values(q(this,ei,"f"))}async finalRun(){if(await this.done(),!q(this,On,"f"))throw Error("Final run was not received.");return q(this,On,"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)q(this,vt,"m",Uo).call(this,c);if((l=i.controller.signal)!=null&&l.aborted)throw new Qt;return this._addRun(q(this,vt,"m",qo).call(this))}async _createAssistantStream(t,s,n,o){var c;const a=o==null?void 0:o.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},l=await t.create(s,i,{...o,signal:this.controller.signal});this._connected();for await(const d of l)q(this,vt,"m",Uo).call(this,d);if((c=l.controller.signal)!=null&&c.aborted)throw new Qt;return this._addRun(q(this,vt,"m",qo).call(this))}static accumulateDelta(t,s){for(const[n,o]of Object.entries(s)){if(!t.hasOwnProperty(n)){t[n]=o;continue}let a=t[n];if(a==null){t[n]=o;continue}if(n==="index"||n==="type"){t[n]=o;continue}if(typeof a=="string"&&typeof o=="string")a+=o;else if(typeof a=="number"&&typeof o=="number")a+=o;else if(al(a)&&al(o))a=this.accumulateDelta(a,o);else if(Array.isArray(a)&&Array.isArray(o)){if(a.every(i=>typeof i=="string"||typeof i=="number")){a.push(...o);continue}for(const i of o){if(!al(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const l=i.index;if(l==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);const c=a[l];c==null?a.push(i):a[l]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${o}, accValue: ${a}`);t[n]=a}return t}_addRun(t){return t}async _threadAssistantStream(t,s,n){return await this._createThreadAssistantStream(s,t,n)}async _runAssistantStream(t,s,n,o){return await this._createAssistantStream(s,t,n,o)}async _runToolAssistantStream(t,s,n,o){return await this._createToolAssistantStream(s,t,n,o)}}Ln=Jo,Uo=function(t){if(!this.ended)switch(ve(this,ti,t),q(this,vt,"m",Qu).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":q(this,vt,"m",sm).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":q(this,vt,"m",Ju).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":q(this,vt,"m",Gu).call(this,t);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},qo=function(){if(this.ended)throw new Se("stream has ended, this shouldn't happen");if(!q(this,On,"f"))throw Error("Final run has not been received");return q(this,On,"f")},Gu=function(t){const[s,n]=q(this,vt,"m",em).call(this,t,q(this,ds,"f"));ve(this,ds,s),q(this,ei,"f")[s.id]=s;for(const o of n){const a=s.content[o.index];(a==null?void 0:a.type)=="text"&&this._emit("textCreated",a.text)}switch(t.event){case"thread.message.created":this._emit("messageCreated",t.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",t.data.delta,s),t.data.delta.content)for(const o of t.data.delta.content){if(o.type=="text"&&o.text){let a=o.text,i=s.content[o.index];if(i&&i.type=="text")this._emit("textDelta",a,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(o.index!=q(this,ur,"f")){if(q(this,Cn,"f"))switch(q(this,Cn,"f").type){case"text":this._emit("textDone",q(this,Cn,"f").text,q(this,ds,"f"));break;case"image_file":this._emit("imageFileDone",q(this,Cn,"f").image_file,q(this,ds,"f"));break}ve(this,ur,o.index)}ve(this,Cn,s.content[o.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(q(this,ur,"f")!==void 0){const o=t.data.content[q(this,ur,"f")];if(o)switch(o.type){case"image_file":this._emit("imageFileDone",o.image_file,q(this,ds,"f"));break;case"text":this._emit("textDone",o.text,q(this,ds,"f"));break}}q(this,ds,"f")&&this._emit("messageDone",t.data),ve(this,ds,void 0)}},Ju=function(t){const s=q(this,vt,"m",Zu).call(this,t);switch(ve(this,Go,s),t.event){case"thread.run.step.created":this._emit("runStepCreated",t.data);break;case"thread.run.step.delta":const n=t.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&s.step_details.type=="tool_calls")for(const a of n.step_details.tool_calls)a.index==q(this,Ti,"f")?this._emit("toolCallDelta",a,s.step_details.tool_calls[a.index]):(q(this,Nt,"f")&&this._emit("toolCallDone",q(this,Nt,"f")),ve(this,Ti,a.index),ve(this,Nt,s.step_details.tool_calls[a.index]),q(this,Nt,"f")&&this._emit("toolCallCreated",q(this,Nt,"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":ve(this,Go,void 0),t.data.step_details.type=="tool_calls"&&q(this,Nt,"f")&&(this._emit("toolCallDone",q(this,Nt,"f")),ve(this,Nt,void 0)),this._emit("runStepDone",t.data,s);break}},Qu=function(t){q(this,Sc,"f").push(t),this._emit("event",t)},Zu=function(t){switch(t.event){case"thread.run.step.created":return q(this,_s,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let s=q(this,_s,"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=Ln.accumulateDelta(s,n.delta);q(this,_s,"f")[t.data.id]=o}return q(this,_s,"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":q(this,_s,"f")[t.data.id]=t.data;break}if(q(this,_s,"f")[t.data.id])return q(this,_s,"f")[t.data.id];throw new Error("No snapshot available")},em=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]=q(this,vt,"m",tm).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")},tm=function(t,s){return Ln.accumulateDelta(s,t)},sm=function(t){switch(ve(this,si,t.data),t.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":ve(this,On,t.data),q(this,Nt,"f")&&(this._emit("toolCallDone",q(this,Nt,"f")),ve(this,Nt,void 0));break}};let Md=class extends we{constructor(){super(...arguments),this.steps=new Xg(this._client)}create(t,s,n){const{include:o,...a}=s;return this._client.post(ie`/threads/${t}/runs`,{query:{include:o},body:a,...n,headers:ge([{"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(ie`/threads/${o}/runs/${t}`,{...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,s,n){const{thread_id:o,...a}=s;return this._client.post(ie`/threads/${o}/runs/${t}`,{body:a,...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s={},n){return this._client.getAPIList(ie`/threads/${t}/runs`,lt,{query:s,...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(t,s,n){const{thread_id:o}=s;return this._client.post(ie`/threads/${o}/runs/${t}/cancel`,{...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(t,s,n){const o=await this.create(t,s,n);return await this.poll(o.id,{thread_id:t},n)}createAndStream(t,s,n){return Jo.createAssistantStream(t,this._client.beta.threads.runs,s,n)}async poll(t,s,n){var a;const o=ge([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 ga(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(t,s,n){return Jo.createAssistantStream(t,this._client.beta.threads.runs,s,n)}submitToolOutputs(t,s,n){const{thread_id:o,...a}=s;return this._client.post(ie`/threads/${o}/runs/${t}/submit_tool_outputs`,{body:a,...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:s.stream??!1})}async submitToolOutputsAndPoll(t,s,n){const o=await this.submitToolOutputs(t,s,n);return await this.poll(o.id,s,n)}submitToolOutputsStream(t,s,n){return Jo.createToolAssistantStream(t,this._client.beta.threads.runs,s,n)}};Md.Steps=Xg;class Ui extends we{constructor(){super(...arguments),this.runs=new Md(this._client),this.messages=new Yg(this._client)}create(t={},s){return this._client.post("/threads",{body:t,...s,headers:ge([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,s){return this._client.get(ie`/threads/${t}`,{...s,headers:ge([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,s,n){return this._client.post(ie`/threads/${t}`,{body:s,...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,s){return this._client.delete(ie`/threads/${t}`,{...s,headers:ge([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}createAndRun(t,s){return this._client.post("/threads/runs",{body:t,...s,headers:ge([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers]),stream:t.stream??!1})}async createAndRunPoll(t,s){const n=await this.createAndRun(t,s);return await this.runs.poll(n.id,{thread_id:n.thread_id},s)}createAndRunStream(t,s){return Jo.createThreadAssistantStream(t,this._client.beta.threads,s)}}Ui.Runs=Md;Ui.Messages=Yg;class xa extends we{constructor(){super(...arguments),this.realtime=new Wi(this._client),this.assistants=new Ug(this._client),this.threads=new Ui(this._client)}}xa.Realtime=Wi;xa.Assistants=Ug;xa.Threads=Ui;class Vg extends we{create(t,s){return this._client.post("/completions",{body:t,...s,stream:t.stream??!1})}}let Kg=class extends we{retrieve(t,s,n){const{container_id:o}=s;return this._client.get(ie`/containers/${o}/files/${t}/content`,{...n,headers:ge([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}},Pd=class extends we{constructor(){super(...arguments),this.content=new Kg(this._client)}create(t,s,n){return this._client.post(ie`/containers/${t}/files`,Hn({body:s,...n},this._client))}retrieve(t,s,n){const{container_id:o}=s;return this._client.get(ie`/containers/${o}/files/${t}`,n)}list(t,s={},n){return this._client.getAPIList(ie`/containers/${t}/files`,lt,{query:s,...n})}delete(t,s,n){const{container_id:o}=s;return this._client.delete(ie`/containers/${o}/files/${t}`,{...n,headers:ge([{Accept:"*/*"},n==null?void 0:n.headers])})}};Pd.Content=Kg;class Ed extends we{constructor(){super(...arguments),this.files=new Pd(this._client)}create(t,s){return this._client.post("/containers",{body:t,...s})}retrieve(t,s){return this._client.get(ie`/containers/${t}`,s)}list(t={},s){return this._client.getAPIList("/containers",lt,{query:t,...s})}delete(t,s){return this._client.delete(ie`/containers/${t}`,{...s,headers:ge([{Accept:"*/*"},s==null?void 0:s.headers])})}}Ed.Files=Pd;class Gg extends we{create(t,s){const n=!!t.encoding_format;let o=n?t.encoding_format:"base64";n&&xt(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:(xt(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=Mw(c)}),i)))}}class Jg extends we{retrieve(t,s,n){const{eval_id:o,run_id:a}=s;return this._client.get(ie`/evals/${o}/runs/${a}/output_items/${t}`,n)}list(t,s,n){const{eval_id:o,...a}=s;return this._client.getAPIList(ie`/evals/${o}/runs/${t}/output_items`,lt,{query:a,...n})}}class Rd extends we{constructor(){super(...arguments),this.outputItems=new Jg(this._client)}create(t,s,n){return this._client.post(ie`/evals/${t}/runs`,{body:s,...n})}retrieve(t,s,n){const{eval_id:o}=s;return this._client.get(ie`/evals/${o}/runs/${t}`,n)}list(t,s={},n){return this._client.getAPIList(ie`/evals/${t}/runs`,lt,{query:s,...n})}delete(t,s,n){const{eval_id:o}=s;return this._client.delete(ie`/evals/${o}/runs/${t}`,n)}cancel(t,s,n){const{eval_id:o}=s;return this._client.post(ie`/evals/${o}/runs/${t}`,n)}}Rd.OutputItems=Jg;class Ad extends we{constructor(){super(...arguments),this.runs=new Rd(this._client)}create(t,s){return this._client.post("/evals",{body:t,...s})}retrieve(t,s){return this._client.get(ie`/evals/${t}`,s)}update(t,s,n){return this._client.post(ie`/evals/${t}`,{body:s,...n})}list(t={},s){return this._client.getAPIList("/evals",lt,{query:t,...s})}delete(t,s){return this._client.delete(ie`/evals/${t}`,s)}}Ad.Runs=Rd;let Qg=class extends we{create(t,s){return this._client.post("/files",Hn({body:t,...s},this._client))}retrieve(t,s){return this._client.get(ie`/files/${t}`,s)}list(t={},s){return this._client.getAPIList("/files",lt,{query:t,...s})}delete(t,s){return this._client.delete(ie`/files/${t}`,s)}content(t,s){return this._client.get(ie`/files/${t}/content`,{...s,headers:ge([{Accept:"application/binary"},s==null?void 0:s.headers]),__binaryResponse:!0})}async waitForProcessing(t,{pollInterval:s=5e3,maxWait:n=30*60*1e3}={}){const o=new Set(["processed","error","deleted"]),a=Date.now();let i=await this.retrieve(t);for(;!i.status||!o.has(i.status);)if(await ga(s),i=await this.retrieve(t),Date.now()-a>n)throw new vd({message:`Giving up on waiting for file ${t} to finish processing after ${n} milliseconds.`});return i}};class Zg extends we{}let ey=class extends we{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 Id extends we{constructor(){super(...arguments),this.graders=new ey(this._client)}}Id.Graders=ey;class ty extends we{create(t,s,n){return this._client.getAPIList(ie`/fine_tuning/checkpoints/${t}/permissions`,Bi,{body:s,method:"post",...n})}retrieve(t,s={},n){return this._client.get(ie`/fine_tuning/checkpoints/${t}/permissions`,{query:s,...n})}delete(t,s,n){const{fine_tuned_model_checkpoint:o}=s;return this._client.delete(ie`/fine_tuning/checkpoints/${o}/permissions/${t}`,n)}}let $d=class extends we{constructor(){super(...arguments),this.permissions=new ty(this._client)}};$d.Permissions=ty;class sy extends we{list(t,s={},n){return this._client.getAPIList(ie`/fine_tuning/jobs/${t}/checkpoints`,lt,{query:s,...n})}}class Dd extends we{constructor(){super(...arguments),this.checkpoints=new sy(this._client)}create(t,s){return this._client.post("/fine_tuning/jobs",{body:t,...s})}retrieve(t,s){return this._client.get(ie`/fine_tuning/jobs/${t}`,s)}list(t={},s){return this._client.getAPIList("/fine_tuning/jobs",lt,{query:t,...s})}cancel(t,s){return this._client.post(ie`/fine_tuning/jobs/${t}/cancel`,s)}listEvents(t,s={},n){return this._client.getAPIList(ie`/fine_tuning/jobs/${t}/events`,lt,{query:s,...n})}pause(t,s){return this._client.post(ie`/fine_tuning/jobs/${t}/pause`,s)}resume(t,s){return this._client.post(ie`/fine_tuning/jobs/${t}/resume`,s)}}Dd.Checkpoints=sy;class jr extends we{constructor(){super(...arguments),this.methods=new Zg(this._client),this.jobs=new Dd(this._client),this.checkpoints=new $d(this._client),this.alpha=new Id(this._client)}}jr.Methods=Zg;jr.Jobs=Dd;jr.Checkpoints=$d;jr.Alpha=Id;class ny extends we{}class Ld extends we{constructor(){super(...arguments),this.graderModels=new ny(this._client)}}Ld.GraderModels=ny;class ry extends we{createVariation(t,s){return this._client.post("/images/variations",Hn({body:t,...s},this._client))}edit(t,s){return this._client.post("/images/edits",Hn({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 oy extends we{retrieve(t,s){return this._client.get(ie`/models/${t}`,s)}list(t){return this._client.getAPIList("/models",Bi,t)}delete(t,s){return this._client.delete(ie`/models/${t}`,s)}}class ay extends we{create(t,s){return this._client.post("/moderations",{body:t,...s})}}function Pw(e,t){return!t||!Rw(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)}:iy(e,t)}function iy(e,t){const s=e.output.map(o=>{if(o.type==="function_call")return{...o,parsed_arguments:$w(t,o)};if(o.type==="message"){const a=o.content.map(i=>i.type==="output_text"?{...i,parsed:Ew(t,i.text)}:i);return{...o,content:a}}return o}),n=Object.assign({},e,{output:s});return Object.getOwnPropertyDescriptor(e,"output_text")||wc(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 Ew(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 Rw(e){var t;return!!_d((t=e.text)==null?void 0:t.format)}function Aw(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function Iw(e,t){return e.find(s=>s.type==="function"&&s.name===t)}function $w(e,t){const s=Iw(e.tools??[],t.name);return{...t,...t,parsed_arguments:Aw(s)?s.$parseRaw(t.arguments):s!=null&&s.strict?JSON.parse(t.arguments):null}}function wc(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 Zn,$a,Qs,Da,nm,rm,om,am;class Od extends wd{constructor(t){super(),Zn.add(this),$a.set(this,void 0),Qs.set(this,void 0),Da.set(this,void 0),ve(this,$a,t)}static createResponse(t,s,n){const o=new Od(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())),q(this,Zn,"m",nm).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)q(this,Zn,"m",rm).call(this,c,i);if((l=a.controller.signal)!=null&&l.aborted)throw new Qt;return q(this,Zn,"m",om).call(this)}[($a=new WeakMap,Qs=new WeakMap,Da=new WeakMap,Zn=new WeakSet,nm=function(){this.ended||ve(this,Qs,void 0)},rm=function(s,n){if(this.ended)return;const o=(i,l)=>{(n==null||l.sequence_number>n)&&this._emit(i,l)},a=q(this,Zn,"m",am).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 Se(`missing output at index ${s.output_index}`);if(i.type==="message"){const l=i.content[s.content_index];if(!l)throw new Se(`missing content at index ${s.content_index}`);if(l.type!=="output_text")throw new Se(`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 Se(`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}},om=function(){if(this.ended)throw new Se("stream has ended, this shouldn't happen");const s=q(this,Qs,"f");if(!s)throw new Se("request ended without sending any events");ve(this,Qs,void 0);const n=Dw(s,q(this,$a,"f"));return ve(this,Da,n),n},am=function(s){let n=q(this,Qs,"f");if(!n){if(s.type!=="response.created")throw new Se(`When snapshot hasn't been set yet, expected 'response.created' event, got ${s.type}`);return n=ve(this,Qs,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 Se(`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 Se(`missing output at index ${s.output_index}`);if(o.type==="message"){const a=o.content[s.content_index];if(!a)throw new Se(`missing content at index ${s.content_index}`);if(a.type!=="output_text")throw new Se(`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 Se(`missing output at index ${s.output_index}`);o.type==="function_call"&&(o.arguments+=s.delta);break}case"response.completed":{ve(this,Qs,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=q(this,Da,"f");if(!t)throw new Se("stream ended without producing a ChatCompletion");return t}}function Dw(e,t){return Pw(e,t)}class ly extends we{list(t,s={},n){return this._client.getAPIList(ie`/responses/${t}/input_items`,lt,{query:s,...n})}}class Fd extends we{constructor(){super(...arguments),this.inputItems=new ly(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"&&wc(n),n))}retrieve(t,s={},n){return this._client.get(ie`/responses/${t}`,{query:s,...n,stream:(s==null?void 0:s.stream)??!1})._thenUnwrap(o=>("object"in o&&o.object==="response"&&wc(o),o))}delete(t,s){return this._client.delete(ie`/responses/${t}`,{...s,headers:ge([{Accept:"*/*"},s==null?void 0:s.headers])})}parse(t,s){return this._client.responses.create(t,s)._thenUnwrap(n=>iy(n,t))}stream(t,s){return Od.createResponse(this._client,t,s)}cancel(t,s){return this._client.post(ie`/responses/${t}/cancel`,s)}}Fd.InputItems=ly;class cy extends we{create(t,s,n){return this._client.post(ie`/uploads/${t}/parts`,Hn({body:s,...n},this._client))}}class zd extends we{constructor(){super(...arguments),this.parts=new cy(this._client)}create(t,s){return this._client.post("/uploads",{body:t,...s})}cancel(t,s){return this._client.post(ie`/uploads/${t}/cancel`,s)}complete(t,s,n){return this._client.post(ie`/uploads/${t}/complete`,{body:s,...n})}}zd.Parts=cy;const Lw=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 dy extends we{create(t,s,n){return this._client.post(ie`/vector_stores/${t}/file_batches`,{body:s,...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,s,n){const{vector_store_id:o}=s;return this._client.get(ie`/vector_stores/${o}/file_batches/${t}`,{...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(t,s,n){const{vector_store_id:o}=s;return this._client.post(ie`/vector_stores/${o}/file_batches/${t}/cancel`,{...n,headers:ge([{"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(ie`/vector_stores/${o}/file_batches/${t}/files`,lt,{query:a,...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async poll(t,s,n){var a;const o=ge([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 ga(c);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(t,{files:s,fileIds:n=[]},o){if(s==null||s.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const a=(o==null?void 0:o.maxConcurrency)??5,i=Math.min(a,s.length),l=this._client,c=s.values(),d=[...n];async function u(p){for(let g of p){const y=await l.files.create({file:g,purpose:"assistants"},o);d.push(y.id)}}const h=Array(i).fill(c).map(u);return await Lw(h),await this.createAndPoll(t,{file_ids:d})}}class uy extends we{create(t,s,n){return this._client.post(ie`/vector_stores/${t}/files`,{body:s,...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,s,n){const{vector_store_id:o}=s;return this._client.get(ie`/vector_stores/${o}/files/${t}`,{...n,headers:ge([{"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(ie`/vector_stores/${o}/files/${t}`,{body:a,...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s={},n){return this._client.getAPIList(ie`/vector_stores/${t}/files`,lt,{query:s,...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,s,n){const{vector_store_id:o}=s;return this._client.delete(ie`/vector_stores/${o}/files/${t}`,{...n,headers:ge([{"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=ge([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 ga(c);break;case"failed":case"completed":return l}}}async upload(t,s,n){const o=await this._client.files.create({file:s,purpose:"assistants"},n);return this.create(t,{file_id:o.id},n)}async uploadAndPoll(t,s,n){const o=await this.upload(t,s,n);return await this.poll(t,o.id,n)}content(t,s,n){const{vector_store_id:o}=s;return this._client.getAPIList(ie`/vector_stores/${o}/files/${t}/content`,Bi,{...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class qi extends we{constructor(){super(...arguments),this.files=new uy(this._client),this.fileBatches=new dy(this._client)}create(t,s){return this._client.post("/vector_stores",{body:t,...s,headers:ge([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,s){return this._client.get(ie`/vector_stores/${t}`,{...s,headers:ge([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,s,n){return this._client.post(ie`/vector_stores/${t}`,{body:s,...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t={},s){return this._client.getAPIList("/vector_stores",lt,{query:t,...s,headers:ge([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}delete(t,s){return this._client.delete(ie`/vector_stores/${t}`,{...s,headers:ge([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}search(t,s,n){return this._client.getAPIList(ie`/vector_stores/${t}/search`,Bi,{body:s,method:"post",...n,headers:ge([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}qi.Files=uy;qi.FileBatches=dy;var cr,my,ni;class hy extends we{constructor(){super(...arguments),cr.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");q(this,cr,"m",my).call(this,n);const a=ge([s]).values,i=q(this,cr,"m",ni).call(this,a,"webhook-signature"),l=q(this,cr,"m",ni).call(this,a,"webhook-timestamp"),c=q(this,cr,"m",ni).call(this,a,"webhook-id"),d=parseInt(l,10);if(isNaN(d))throw new Lo("Invalid webhook timestamp format");const u=Math.floor(Date.now()/1e3);if(u-d>o)throw new Lo("Webhook timestamp is too old");if(d>u+o)throw new Lo("Webhook timestamp is too new");const h=i.split(" ").map(f=>f.startsWith("v1,")?f.substring(3):f),p=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),g=c?`${c}.${l}.${t}`:`${l}.${t}`,y=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const f of h)try{const v=Buffer.from(f,"base64");if(await crypto.subtle.verify("HMAC",y,v,new TextEncoder().encode(g)))return}catch{continue}throw new Lo("The given webhook signature does not match the expected signature")}}cr=new WeakSet,my=function(t){if(typeof t!="string"||t.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},ni=function(t,s){if(!t)throw new Error("Headers are required");const n=t.get(s);if(n==null)throw new Error(`Missing required header: ${s}`);return n};var _c,Nd,ri,py;class Re{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(_c.add(this),ri.set(this,void 0),this.completions=new Vg(this),this.chat=new Cd(this),this.embeddings=new Gg(this),this.files=new Qg(this),this.images=new ry(this),this.audio=new ba(this),this.moderations=new ay(this),this.models=new oy(this),this.fineTuning=new jr(this),this.graders=new Ld(this),this.vectorStores=new qi(this),this.webhooks=new hy(this),this.beta=new xa(this),this.batches=new Wg(this),this.uploads=new zd(this),this.responses=new Fd(this),this.evals=new Ad(this),this.containers=new Ed(this),s===void 0)throw new Se("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&&OS())throw new Se(`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??Nd.DEFAULT_TIMEOUT,this.logger=l.logger??console;const c="warn";this.logLevel=c,this.logLevel=qu(l.logLevel,"ClientOptions.logLevel",this)??qu(Qn("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??WS(),ve(this,ri,qS),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 ge([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return GS(t,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${ir}`}defaultIdempotencyKey(){return`stainless-node-retry-${Yf()}`}makeStatusError(t,s,n,o){return St.generate(t,s,n,o)}buildURL(t,s,n){const o=!q(this,_c,"m",py).call(this)&&n||this.baseURL,a=RS(t)?new URL(t):new URL(o+(o.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),i=this.defaultQuery();return IS(i)||(s={...i,...s}),typeof s=="object"&&s&&!Array.isArray(s)&&(a.search=this.stringifyQuery(s)),a.toString()}async prepareOptions(t){}async prepareRequest(t,{url:s,options:n}){}get(t,s){return this.methodRequest("get",t,s)}post(t,s){return this.methodRequest("post",t,s)}patch(t,s){return this.methodRequest("patch",t,s)}put(t,s){return this.methodRequest("put",t,s)}delete(t,s){return this.methodRequest("delete",t,s)}methodRequest(t,s,n){return this.request(Promise.resolve(n).then(o=>({method:t,path:s,...o})))}request(t,s=null){return new Ni(this,this.makeRequest(t,s,void 0))}async makeRequest(t,s,n){var b,x;const o=await t,a=o.maxRetries??this.maxRetries;s==null&&(s=a),await this.prepareOptions(o);const{req:i,url:l,timeout:c}=await this.buildRequest(o,{retryCount:a-s});await this.prepareRequest(i,{url:l,options:o});const d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,h=Date.now();if(xt(this).debug(`[${d}] sending request`,_n({retryOfRequestLogID:n,method:o.method,url:l,options:o,headers:i.headers})),(b=o.signal)!=null&&b.aborted)throw new Qt;const p=new AbortController,g=await this.fetchWithTimeout(l,i,c,p).catch(mc),y=Date.now();if(g instanceof Error){const _=`retrying, ${s} attempts remaining`;if((x=o.signal)!=null&&x.aborted)throw new Qt;const w=uc(g)||/timed? ?out/i.test(String(g)+("cause"in g?String(g.cause):""));if(s)return xt(this).info(`[${d}] connection ${w?"timed out":"failed"} - ${_}`),xt(this).debug(`[${d}] connection ${w?"timed out":"failed"} (${_})`,_n({retryOfRequestLogID:n,url:l,durationMs:y-h,message:g.message})),this.retryRequest(o,s,n??d);throw xt(this).info(`[${d}] connection ${w?"timed out":"failed"} - error; no more retries left`),xt(this).debug(`[${d}] connection ${w?"timed out":"failed"} (error; no more retries left)`,_n({retryOfRequestLogID:n,url:l,durationMs:y-h,message:g.message})),w?new vd:new Fi({cause:g})}const f=[...g.headers.entries()].filter(([_])=>_==="x-request-id").map(([_,w])=>", "+_+": "+JSON.stringify(w)).join(""),v=`[${d}${u}${f}] ${i.method} ${l} ${g.ok?"succeeded":"failed"} with status ${g.status} in ${y-h}ms`;if(!g.ok){const _=await this.shouldRetry(g);if(s&&_){const R=`retrying, ${s} attempts remaining`;return await US(g.body),xt(this).info(`${v} - ${R}`),xt(this).debug(`[${d}] response error (${R})`,_n({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:y-h})),this.retryRequest(o,s,n??d,g.headers)}const w=_?"error; no more retries left":"error; not retryable";xt(this).info(`${v} - ${w}`);const k=await g.text().catch(R=>mc(R).message),C=LS(k),E=C?void 0:k;throw xt(this).debug(`[${d}] response error (${w})`,_n({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,message:E,durationMs:Date.now()-h})),this.makeStatusError(g.status,C,E,g.headers)}return xt(this).info(v),xt(this).debug(`[${d}] response start`,_n({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:y-h})),{response:g,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 ow(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 ga(a),this.makeRequest(t,s-1,n)}calculateDefaultRetryTimeoutMillis(t,s){const a=s-t,i=Math.min(.5*Math.pow(2,a),8),l=1-Math.random()*.25;return i*l*1e3}async buildRequest(t,{retryCount:s=0}={}){const n={...t},{method:o,path:a,query:i,defaultBaseURL:l}=n,c=this.buildURL(a,i,l);"timeout"in n&&DS("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=ge([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))}:{},...BS(),"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=ge([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:rg(t)}:q(this,ri,"f").call(this,{body:t,headers:n})}}Nd=Re,ri=new WeakMap,_c=new WeakSet,py=function(){return this.baseURL!=="https://api.openai.com/v1"};Re.OpenAI=Nd;Re.DEFAULT_TIMEOUT=6e5;Re.OpenAIError=Se;Re.APIError=St;Re.APIConnectionError=Fi;Re.APIConnectionTimeoutError=vd;Re.APIUserAbortError=Qt;Re.NotFoundError=Gf;Re.ConflictError=Jf;Re.RateLimitError=Zf;Re.BadRequestError=Xf;Re.AuthenticationError=Vf;Re.InternalServerError=eg;Re.PermissionDeniedError=Kf;Re.UnprocessableEntityError=Qf;Re.InvalidWebhookSignatureError=Lo;Re.toFile=uw;Re.Completions=Vg;Re.Chat=Cd;Re.Embeddings=Gg;Re.Files=Qg;Re.Images=ry;Re.Audio=ba;Re.Moderations=ay;Re.Models=oy;Re.FineTuning=jr;Re.Graders=Ld;Re.VectorStores=qi;Re.Webhooks=hy;Re.Beta=xa;Re.Batches=Wg;Re.Uploads=zd;Re.Responses=Fd;Re.Evals=Ad;Re.Containers=Ed;let La=null,fl=null;const Ow=()=>{const e=kr().trim().replace(/\/+$/,"");if(e.endsWith("/openai/v1"))return e;const t="/v1";return`${e.endsWith(t)?e.slice(0,-t.length):e}/openai/v1`},fy=()=>{const e=Ow();return La?fl!==e&&(La=new Re({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),fl=e):(La=new Re({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),fl=e),La};function Hi(e){const t=Ee(a=>a.currentProvider),s=Ee(a=>a.providerConfig),n=N(Xn(e??null));return m.useMemo(()=>{var l,c;const a=e?(c=(l=n==null?void 0:n.config)==null?void 0:l.model)==null?void 0:c.trim():void 0;if(a)return a;const i=s.providers[t];if(i&&"model"in i&&i.model)return i.model},[n,t,s,e])}function gy(e){const t=Hi(e),s=Ee(o=>o.currentProvider),n=Ee(o=>o.providerConfig);return m.useMemo(()=>{const o=n.providers[s];return o&&"fast_model"in o&&o.fast_model?o.fast_model:t},[s,n,t])}function Bd(e){const t=Ee(a=>a.isProviderModelRefEnabled),s=Ee(a=>a.selectedModelRef),n=Ee(a=>a.currentProvider),o=Ee(a=>a.getActiveModel);return m.useMemo(()=>{if(!t())return null;if(e)return e;if(s)return s;const a=o();return a?{provider:n,model:a}:null},[e,s,n,t,o])}function yy(){const e=Ee(t=>t.getFastModelRef);return m.useMemo(()=>e(),[e])}const gl="__BODHI_PROMPT_TITLE__",oi=e=>e.trim().toLowerCase(),Fw=(e,t)=>{let s=e;for(const n of t){if(!s||typeof s!="object"||!(n in s))return;s=s[n]}return typeof s=="string"?s:void 0},yl=e=>{const t=new Set,s=es.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=Fw(o,e);if(!a)return;const i=oi(a);i&&t.add(i)}),Array.from(t))},zw=e=>{const t=new Set(["new session","new chat","main"]),s=new Set(["new session","new chat"]),n=[],o=i=>{const l=oi(i);l&&(t.add(l),s.add(l))},a=i=>{const l=oi(i);if(l){if(l.includes("{{prompt}}")){const[c,d]=l.split("{{prompt}}",2);n.push({prefix:c,suffix:d});return}if(l.includes(gl.toLowerCase())){const[c,d]=l.split(gl.toLowerCase(),2);n.push({prefix:c,suffix:d});return}s.add(l)}};return yl(["chat","sidebar","newSession"]).forEach(o),yl(["chat","session","defaultTitle"]).forEach(o),yl(["chat","sidebar","newSessionWithPrompt"]).forEach(a),o(e("chat.sidebar.newSession")),o(e("chat.session.defaultTitle")),a(e("chat.sidebar.newSessionWithPrompt",{prompt:gl})),i=>{if(!i)return!0;const l=oi(i);if(!l||t.has(l))return!0;for(const c of s)if(c&&(l.startsWith(`${c} -`)||l.startsWith(`${c}-`)||l.startsWith(`${c}:`)||l.startsWith(`${c}:`)))return!0;for(const{prefix:c,suffix: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}},Wd=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""},im=e=>e.filter(t=>t.role!=="user"&&t.role!=="assistant"?!1:Wd(t).length>0);function Ud(e){const{message:t}=Ot.useApp(),{t:s}=ne(),n=N(v=>v.autoGenerateTitles),o=gy(),a=yy(),i=Hi(),l=N(v=>v.setAutoGenerateTitlesPreference),c=N(v=>v.isUpdatingAutoTitlePreference),d=m.useRef(new Set),u=m.useRef(new Set),[h,p]=m.useState({}),g=m.useMemo(()=>zw((v,b)=>s(v,b)),[s]),y=m.useCallback(v=>g(v),[g]),f=m.useCallback(async(v,b)=>{var C,E;let x=e.chats.find(j=>j.id===v);if(!x)return!1;let _=im(x.messages);if(b!=null&&b.force&&_.length===0){await N.getState().loadChatHistory(v,{mode:"replace"});const j=N.getState().chats.find(R=>R.id===v);j&&(x=j,_=im(j.messages))}const w=!(b!=null&&b.force);if(w&&!n||w&&(u.current.has(v)||d.current.has(v)||!y(x.title)||_.length===0||_.length>6))return!1;u.current.add(v),p(j=>({...j,[v]:{status:"loading"}}));try{const j=(a==null?void 0:a.model)??o,R=(j==null?void 0:j.trim())||"",M=(i==null?void 0:i.trim())||"";let T,P="";if(R)try{P=await cm(_,R)}catch(S){T=S}if(!P&&M&&M!==R)try{P=await cm(_,M)}catch(S){T||(T=S)}if(P||(P=Uw(_)),!P){if(w)return p(S=>({...S,[v]:{status:"idle"}})),!1;throw T instanceof Error?T:new Error(s("chat.title.generateFailed"))}return e.updateSession(v,{title:P}),(!w||P.toLowerCase()!=="new chat")&&d.current.add(v),p(S=>({...S,[v]:{status:"idle"}})),b!=null&&b.force&&((C=t==null?void 0:t.success)==null||C.call(t,s("chat.title.updated"))),!0}catch(j){const R=j instanceof Error?j.message:s("chat.title.generateFailed");throw p(M=>({...M,[v]:{status:"error",error:R}})),b!=null&&b.force?(E=t==null?void 0:t.error)==null||E.call(t,R):console.warn("[ChatTitleGeneration] Auto title generation failed:",R),j instanceof Error?j:new Error(R)}finally{u.current.delete(v)}},[t,n,y,o,a,i,e,s]);return{titleGenerationState:h,autoGenerateTitles:n,isUpdatingAutoTitlePreference:c,generateChatTitle:f,setAutoGenerateTitlesPreference:l,isDefaultTitle:y}}const Tc=60,Nw=20,Bw=8,lm=220,Ww=e=>e.slice(0,Bw).map(n=>{const o=n.role==="user"?"User":"Assistant",a=Wd(n);if(!a)return"";const i=a.length>lm?`${a.slice(0,lm-3)}...`:a;return`${o}: ${i}`}).filter(n=>n.length>0).join(`
|
|
35
|
+
`),Uw=e=>{const t=[...e.filter(s=>s.role==="user"),...e.filter(s=>s.role!=="user")];for(const s of t){const n=Wd(s).replace(/\s+/g," ").trim();if(!n)continue;const o=by(n);if(o)return o}return""},by=e=>{var n;const s=(((n=e.split(/\r?\n/)[0])==null?void 0:n.trim())??"").replace(/^["']+|["']+$/g,"");return s.length<=Tc?s:`${s.slice(0,Tc-3)}...`},qw=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:""},cm=async(e,t)=>{var l,c;const s=Ww(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 fy().chat.completions.create({model:n,temperature:.2,max_tokens:Nw,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 ${Tc} characters) for this chat:
|
|
37
|
+
|
|
38
|
+
${s}`}]}),i=qw((c=(l=a.choices)==null?void 0:l[0])==null?void 0:c.message).trim();return by(i)},Oa={THEME:"copilot_ui_theme_v1",LAYOUT:"copilot_ui_layout_v1"};class Hw{getTheme(){try{return localStorage.getItem(Oa.THEME)}catch(t){return console.error("Failed to get theme:",t),null}}setTheme(t){try{localStorage.setItem(Oa.THEME,t)}catch(s){console.error("Failed to set theme:",s)}}getLayout(){try{return localStorage.getItem(Oa.LAYOUT)}catch(t){return console.error("Failed to get layout:",t),null}}setLayout(t){try{localStorage.setItem(Oa.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 xy=new Hw,qd={collapsed:!1,widthPx:260,collapsedWidthPx:72,minWidthPx:180,maxWidthPx:520},vy={v:2,sidebar:qd,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:null},splitSizesPx:{}},dm=e=>{const t=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return`${e}-${t}`},Bt=e=>e.type==="leaf"?[e.id]:[...Bt(e.children[0]),...Bt(e.children[1])],oa=e=>e.type==="leaf"?[]:[e.id,...oa(e.children[0]),...oa(e.children[1])],Yw=(e,t)=>{for(const[s,n]of Object.entries(e))if(n===t)return s;return null},Xw=(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},kc=(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:[kc(e.children[0],t,s,n,o),kc(e.children[1],t,s,n,o)]},jc=(e,t)=>{if(e.type==="leaf")return e.id===t?{node:null,removed:!0}:{node:e,removed:!1};const s=jc(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=jc(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}},Vw=e=>({v:2,sidebar:e.sidebar,tree:e.tree,activeLeafId:e.activeLeafId,leafSessionIds:e.leafSessionIds,splitSizesPx:e.splitSizesPx}),Kw=e=>{try{xy.setLayout(JSON.stringify(e))}catch(t){console.warn("[uiLayoutStore] Failed to persist layout:",t)}},Ds=e=>{const t=Vw(e);return Kw(t),t},Gw=e=>{var p,g,y,f,v,b,x,_,w,k,C;const t={...qd,...e.sidebar||{}},s=((p=e.view)==null?void 0:p.mode)??"single",n=((g=e.view)==null?void 0:g.twoDirection)??"horizontal",o={...((y=e.panes)==null?void 0:y.sessionIds)||{}},a=((f=e.panes)==null?void 0:f.activePaneId)??"lt",i={};if(s==="single")return{v:2,sidebar:t,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:o.lt??null},splitSizesPx:{}};if(s==="two"){const E="split-root",j=n,R=j==="horizontal"?{type:"split",id:E,layout:j,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"rt"}]}:{type:"split",id:E,layout:j,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},M=j==="horizontal"?((v=e.split)==null?void 0:v.twoHorizontalPx)||((b=e.split)==null?void 0:b.columnsPx)||null:((x=e.split)==null?void 0:x.twoVerticalPx)||((_=e.split)==null?void 0:_.leftRowsPx)||null;M&&(i[E]=M);const T=Bt(R);return{v:2,sidebar:t,tree:R,activeLeafId:T.includes(a)?a:T[0],leafSessionIds:Object.fromEntries(T.map(P=>[P,o[P]??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"}]}]};(w=e.split)!=null&&w.columnsPx&&(i[l]=e.split.columnsPx),(k=e.split)!=null&&k.leftRowsPx&&(i[c]=e.split.leftRowsPx),(C=e.split)!=null&&C.rightRowsPx&&(i[d]=e.split.rightRowsPx);const h=Bt(u);return{v:2,sidebar:t,tree:u,activeLeafId:h.includes(a)?a:h[0],leafSessionIds:Object.fromEntries(h.map(E=>[E,o[E]??null])),splitSizesPx:i}},Jw=e=>{if(!e)return null;try{const t=JSON.parse(e);if(!t||typeof t!="object")return null;if(t.v===2){const s={...qd,...t.sidebar||{}},n=t.tree||vy.tree,o=Bt(n),a=oa(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=Xw(o,i);return{v:2,sidebar:s,tree:n,activeLeafId:c,leafSessionIds:d,splitSizesPx:l}}return t.v===1?Gw(t):null}catch{return null}},Qw=()=>Jw(xy.getLayout())??vy,Ae=un(e=>({...Qw(),setSidebarCollapsed:t=>{e(s=>s.sidebar.collapsed===t?s:Ds({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:Ds({sidebar:{...s.sidebar,widthPx:n},tree:s.tree,activeLeafId:s.activeLeafId,leafSessionIds:s.leafSessionIds,splitSizesPx:s.splitSizesPx})})},setActiveLeafId:t=>{e(s=>s.activeLeafId===t||!Bt(s.tree).includes(t)?s:(Jt("setActiveLeafId",{from:s.activeLeafId,to:t}),Ds({sidebar:s.sidebar,tree:s.tree,activeLeafId:t,leafSessionIds:s.leafSessionIds,splitSizesPx:s.splitSizesPx})))},setLeafSessionId:(t,s)=>{e(n=>{const o=Bt(n.tree);if(!o.includes(t)||(n.leafSessionIds[t]??null)===s)return n;const a=[];Jt("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&&Jt("setLeafSessionId dedupe",{sessionId:s,clearedLeafIds:a,assignedLeafId:t}),o.forEach(l=>{l in i||(i[l]=null)}),Ds({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?Ds({sidebar:s.sidebar,tree:s.tree,activeLeafId:s.activeLeafId,leafSessionIds:n,splitSizesPx:s.splitSizesPx}):s})},splitLeaf:(t,s)=>{e(n=>{const o=Bt(n.tree);if(!o.includes(t)||o.length>=4)return n;const a=dm("split"),i=dm("pane"),l=kc(n.tree,t,s,a,i),c={...n.leafSessionIds,[i]:null};return Ds({sidebar:n.sidebar,tree:l,activeLeafId:i,leafSessionIds:c,splitSizesPx:n.splitSizesPx})})},closeLeaf:t=>{e(s=>{const n=Bt(s.tree);if(!n.includes(t)||n.length<=1)return s;const o=jc(s.tree,t);if(!o.removed||!o.node)return s;const a=o.node,i=Bt(a),l=oa(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 Ds({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:Ds({sidebar:n.sidebar,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:{...n.splitSizesPx,[t]:s}})})},pruneSplitSizes:()=>{e(t=>{const s=new Set(oa(t.tree)),n={};for(const[i,l]of Object.entries(t.splitSizesPx))s.has(i)&&(n[i]=l);const o=Object.keys(t.splitSizesPx),a=Object.keys(n);return o.length===a.length&&o.every(i=>i in n)?t:Ds({sidebar:t.sidebar,tree:t.tree,activeLeafId:t.activeLeafId,leafSessionIds:t.leafSessionIds,splitSizesPx:n})})}})),Zw=async(e,t)=>{var i;const s=N.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=N.getState().chats.find(l=>l.id===e);if(!o)return;if(t!=null&&t.forceLoadHistory||n||(((i=o.messages)==null?void 0:i.length)||0)===0&&(o.messageCount||0)>0)try{await s.loadChatHistory(e)}catch(l){console.warn("[openSession] loadChatHistory failed:",l)}if(t!=null&&t.forceSubscribe){s.setSessionProcessing(e,!0);return}((t==null?void 0:t.subscribeIfRunning)??!0)&&o.isRunning&&s.setSessionProcessing(e,!0)},Yi=(e,t)=>{const{activeLeafId:s,leafSessionIds:n,setLeafSessionId:o,setActiveLeafId:a}=Ae.getState(),i=Yw(n,e),l=n[s]??null;Jt("openSession (input)",{activeLeafId:s,activeLeafSessionId:l,sessionId:e,existingLeafId:i}),i?i===s?Jt("openSession (decision)",{action:"noop_already_active",leafId:s,sessionId:e}):(a(i),Jt("openSession (decision)",{action:"focus_existing_leaf",leafId:i,sessionId:e})):(o(s,e),Jt("openSession (decision)",{action:"assign_to_active_leaf",leafId:s,sessionId:e})),N.getState().selectSession(e),Zw(e,t)},bl=(e,t)=>{if(!t)return!0;const s=[e.title,e.id,e.kind||"root",e.config.workspacePath||"",e.config.systemPromptId||"",e.updatedAt||"",e.createdByScheduleId||"",e.lastRunStatus||"",e.lastRunError||"",...e.messages.filter(o=>o.role==="user"&&"content"in o).slice(0,3).map(o=>"content"in o?o.content:"")].join(" ").toLowerCase();return t.split(/\s+/).filter(Boolean).every(o=>s.includes(o))},xl=(e,t)=>{switch(t){case"pinned":return!!e.pinned;case"running":return!!e.isRunning;case"child":return e.kind==="child";case"all":default:return!0}},e_=()=>{const{t:e}=ne(),{message:t}=Ot.useApp(),s=N(V=>V.chats),n=N(V=>V.currentSessionId),o=N(V=>V.deleteSession),a=N(V=>V.deleteSessions),i=N(V=>V.pinSession),l=N(V=>V.unpinSession),c=N(V=>V.updateSession),d=N(V=>V.addChat),u=N(V=>V.refreshChats),h=N(V=>V.lastSelectedPromptId),p=N(V=>V.systemPrompts),g=Ae(V=>V.sidebar.collapsed),y=Ae(V=>V.setSidebarCollapsed),f=Ae(V=>V.clearSessionFromAllLeaves),{generateChatTitle:v,titleGenerationState:b}=Ud({chats:s,updateSession:c}),x=m.useCallback(async(V,Q)=>{var jt,Ct;const se=p.find(Tt=>Tt.id===h),ce=(se==null?void 0:se.id)||(p.length>0?((jt=p.find(Tt=>Tt.id==="general_assistant"))==null?void 0:jt.id)||p[0].id:""),Ie={title:V||e("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:ce,baseSystemPrompt:(se==null?void 0:se.content)||(p.length>0?((Ct=p.find(Tt=>Tt.id==="general_assistant"))==null?void 0:Ct.content)||p[0].content:""),lastUsedEnhancedPrompt:null,...Ee.getState().isProviderModelRefEnabled()?{model_ref:Ee.getState().selectedModelRef}:{}},currentInteraction:null,...Q},Je=await d(Ie),{activeLeafId:_t}=Ae.getState();Ae.getState().setLeafSessionId(_t,Je),Ae.getState().setActiveLeafId(_t)},[d,h,p,e]),[_,w]=m.useState(!1),[k,C]=m.useState(new Set(["Today"])),[E,j]=m.useState(""),[R,M]=m.useState("all"),[T,P]=m.useState({}),S=N(Xn(n)),L=m.useMemo(()=>S?Ru(S):null,[S]),$=m.useMemo(()=>{const V=new Set(k);return L&&V.add(L),Array.from(V)},[L,k]),I=V=>{const Q=new Set(Array.isArray(V)?V:[V]);C(se=>{if(se.size!==Q.size)return Q;for(const ce of Q)if(!se.has(ce))return Q;return se})},W=E.trim().toLowerCase(),A=W.length>0||R!=="all",O=m.useMemo(()=>s.filter(V=>V.kind!=="child"),[s]),D=m.useMemo(()=>{const V={};for(const Q of s){if(Q.kind!=="child")continue;const se=Q.parentSessionId||Q.rootSessionId;se&&(V[se]||(V[se]=[]),V[se].push(Q))}return Object.keys(V).forEach(Q=>{V[Q].sort((se,ce)=>{if(se.pinned!==ce.pinned)return se.pinned?-1:1;const Ie=Date.parse(se.updatedAt||"")||se.createdAt||0;return(Date.parse(ce.updatedAt||"")||ce.createdAt||0)-Ie})}),V},[s]),H=m.useMemo(()=>A?O.filter(V=>bl(V,W)&&xl(V,R)?!0:(D[V.id]||[]).some(ce=>bl(ce,W)&&xl(ce,R))):O,[D,A,W,O,R]),B=m.useMemo(()=>{if(!A)return D;const V={};for(const Q of H){const se=D[Q.id]||[];V[Q.id]=se.filter(ce=>bl(ce,W)&&xl(ce,R))}return V},[D,H,A,W,R]),K=vS(H),F=SS(K),z=m.useCallback(V=>{i(V),C(Q=>{if(Q.has("Pinned"))return Q;const se=new Set(Q);return se.add("Pinned"),se})},[i]),de=m.useCallback(V=>{const Q=s.find(ce=>ce.id===V),se=Q?Ru({...Q,pinned:!1}):null;l(V),se&&C(ce=>{if(ce.has(se))return ce;const Ie=new Set(ce);return Ie.add(se),Ie})},[s,l]),Te=V=>{Lt.confirm({title:e("chat.sidebar.delete.title"),content:e("chat.sidebar.delete.confirm"),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{f(V),o(V)}})},$e=Bs(V=>V.open),De=()=>{$e("chat")},be=m.useCallback(V=>{j(V)},[]),ye=m.useCallback(V=>{M(V)},[]),je=(V,Q)=>{c(V,{title:Q})},Ue=async V=>{try{await v(V,{force:!0})}catch(Q){console.error("Failed to generate title:",Q)}},ht=m.useCallback(async V=>{var se;if(((se=T[V])==null?void 0:se.status)==="loading")return;P(ce=>({...ce,[V]:{status:"loading"}}));const Q=t.loading(e("chat.actions.runProjectDreamRunning"),0);try{const ce=await rs.getInstance().runProjectDream(V);Q(),ce.dream_generated?t.success(e("chat.actions.runProjectDreamSuccess")):t.info(ce.message||e("chat.actions.runProjectDreamNoChange"));try{await u()}catch(Ie){console.warn("Failed to refresh chats after project dream run:",Ie)}}catch(ce){Q();const Ie=ce instanceof Error&&ce.message?ce.message:e("chat.actions.runProjectDreamFailed");t.error(Ie),console.error("Failed to run project dream:",ce)}finally{P(ce=>({...ce,[V]:{status:"idle"}}))}},[t,T,u,e]),Ge=V=>{const Q=wS(K,V),se=Hf(K,V);Lt.confirm({title:e("chat.sidebar.deleteByDate.title",{date:V}),content:e("chat.sidebar.deleteByDate.confirm",{count:se,date:V}),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{Q.forEach(ce=>f(ce)),a(Q)}})},wt=()=>{w(!0)},U=()=>{w(!1)},_e=async V=>{try{await x(e("chat.sidebar.newSessionWithPrompt",{prompt:V.name}),{config:{systemPromptId:V.id,baseSystemPrompt:V.content,lastUsedEnhancedPrompt:null}}),w(!1)}catch(Q){console.error("Failed to create chat:",Q),Lt.error({title:e("chat.sidebar.createFailedTitle"),content:Q instanceof Error?Q.message:e("chat.sidebar.createFailedUnknown")})}},Ce=m.useCallback(V=>Yi(V),[]),[Ve,qe]=m.useState(new Set),J=m.useMemo(()=>{var se;const V=new Set(Ve),Q=s.find(ce=>ce.id===n);if(Q){const ce=Q.kind==="child"?Q.parentSessionId||Q.rootSessionId:Q.id;ce&&V.add(ce)}for(const ce of s)if(ce.kind==="child"&&ce.pinned){const Ie=ce.parentSessionId||ce.rootSessionId;Ie&&V.add(Ie)}if(A)for(const ce of H)(((se=B[ce.id])==null?void 0:se.length)??0)>0&&V.add(ce.id);return V},[s,B,n,Ve,H,A]),re=m.useCallback(V=>{qe(Q=>{const se=new Set(Q);return se.has(V)?se.delete(V):se.add(V),se})},[]);return{chats:H,childrenByRoot:B,expandedRootIds:J,toggleRootExpanded:re,collapsed:g,currentSessionId:n,expandedKeys:$,groupedChatsByDate:K,hasActiveFilters:A,handleCollapseChange:I,handleDelete:Te,handleDeleteByDate:Ge,handleEditTitle:je,handleGenerateTitle:Ue,handleNewChat:wt,handleNewChatSelectorClose:U,handleOpenSettings:De,handleRunProjectDream:ht,handleSearchQueryChange:be,handleStatusFilterChange:ye,handleSystemPromptSelect:_e,isNewChatSelectorOpen:_,pinSession:z,projectDreamState:T,searchQuery:E,selectSession:Ce,setCollapsed:y,sortedDateKeys:F,statusFilter:R,systemPrompts:p,titleGenerationState:b,unpinSession:de}},{useBreakpoint:t_}=$i,{useToken:s_}=he,um=()=>{const{token:e}=s_(),{t}=ne(),s=t_(),{childrenByRoot:n,expandedRootIds:o,toggleRootExpanded:a,collapsed:i,currentSessionId:l,expandedKeys:c,groupedChatsByDate:d,handleCollapseChange:u,handleDelete:h,handleDeleteByDate:p,handleEditTitle:g,handleGenerateTitle:y,handleNewChat:f,handleNewChatSelectorClose:v,handleOpenSettings:b,handleRunProjectDream:x,handleSearchQueryChange:_,handleStatusFilterChange:w,handleSystemPromptSelect:k,hasActiveFilters:C,isNewChatSelectorOpen:E,pinSession:j,projectDreamState:R,searchQuery:M,selectSession:T,setCollapsed:P,sortedDateKeys:S,statusFilter:L,systemPrompts:$,titleGenerationState:I,unpinSession:W}=e_(),{xs:A,sm:O}=s;return m.useEffect(()=>{typeof A!="boolean"||typeof O!="boolean"||A===!1&&O===!1&&P(!0)},[O,A,P]),i?null:r.jsxs("nav",{"data-tour-id":"sidebar","aria-label":t("chat.sidebar.title","Chat sidebar"),style:{width:"100%",height:"100%",background:"transparent",borderRight:`1px solid ${e.colorBorderSecondary}`,position:"relative",overflow:"hidden",display:"flex",flexDirection:"column",minHeight:0},children:[r.jsx(G,{justify:"flex-end",style:{flexShrink:0,padding:"10px 12px 2px 12px",minHeight:40},children:r.jsx(Y,{type:"text",icon:r.jsx(gf,{}),onClick:()=>P(!0),size:s.xs?"small":"middle",className:"lotus-toolbar-icon","aria-label":t("chat.sidebar.collapse","Collapse sidebar")})}),r.jsxs(G,{vertical:!0,gap:"small",style:{flexShrink:0,padding:"10px 12px 8px 12px"},children:[r.jsx(me,{allowClear:!0,value:M,onChange:D=>_(D.target.value),prefix:r.jsx(sa,{style:{color:e.colorTextTertiary}}),placeholder:t("chat.sidebar.searchPlaceholder","Search sessions"),"aria-label":t("chat.sidebar.searchPlaceholder","Search sessions"),size:s.xs?"middle":"large",style:{borderRadius:e.borderRadiusLG}}),r.jsx(cx,{block:!0,size:s.xs?"middle":"small",value:L,onChange:D=>w(D),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(G,{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(_S,{groupedChatsByDate:d,childrenByRoot:n,expandedRootIds:o,onToggleRootExpanded:a,sortedDateKeys:S,expandedKeys:c,onCollapseChange:u,currentSessionId:l,onSelectChat:T,onDeleteChat:h,onDeleteByDate:p,onPinChat:j,onUnpinChat:W,onEditTitle:g,onGenerateTitle:y,onRunProjectDream:x,titleGenerationState:I,projectDreamState:R,token:e,hasActiveFilters:C})}),r.jsx(PS,{collapsed:!1,onNewChat:f,onOpenSettings:b,screens:s,token:e}),r.jsx(yS,{open:E,onClose:v,onSelect:k,prompts:$,title:t("chat.prompt.newSessionSelectorTitle"),showCancelButton:!0})]})},mm=e=>Symbol.iterator in e,hm=e=>"entries"in e,pm=(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},n_=(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 r_(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:mm(e)&&mm(t)?hm(e)&&hm(t)?pm(e,t):n_(e,t):pm({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function o_(e){const t=ut.useRef(void 0);return s=>{const n=e(s);return r_(t.current,n)?t.current:t.current=n}}function a_(){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:g}=N(o_(_=>({chats:_.chats,currentSessionId:_.currentSessionId,currentChat:lS(_),addMessage:_.addMessage,selectSession:_.selectSession,deleteSession:_.deleteSession,deleteSessions:_.deleteSessions,deleteMessage:_.deleteMessage,updateSession:_.updateSession,pinSession:_.pinSession,unpinSession:_.unpinSession,loadChats:_.loadChats,processingChats:_.processingChats,setSessionProcessing:_.setSessionProcessing}))),y=t?p.has(t):!1,f=m.useMemo(()=>(s==null?void 0:s.messages)||[],[s]),v=m.useMemo(()=>e.filter(_=>_.pinned),[e]),b=m.useMemo(()=>e.filter(_=>!_.pinned),[e]),x=e.length;return{chats:e,currentSessionId:t,currentChat:s,isProcessing:y,baseMessages:f,pinnedChats:v,unpinnedChats:b,chatCount:x,addMessage:n,deleteMessage:l,selectSession:o,deleteSession:a,deleteSessions:i,pinSession:d,unpinSession:u,updateSession:c,loadChats:h,setSessionProcessing:g}}function i_(e){const t=N(p=>p.addChat),s=N(p=>p.lastSelectedPromptId),n=N(p=>p.systemPrompts),o=rs.getInstance(),a=m.useCallback(async(p,g)=>{var b,x;const y=n.find(_=>_.id===s),f=(y==null?void 0:y.id)||(n.length>0?((b=n.find(_=>_.id==="general_assistant"))==null?void 0:b.id)||n[0].id:""),v={title:p||"New Session",createdAt:Date.now(),messages:[],config:{systemPromptId:f,baseSystemPrompt:(y==null?void 0:y.content)||(n.length>0?((x=n.find(_=>_.id==="general_assistant"))==null?void 0:x.content)||n[0].content:""),lastUsedEnhancedPrompt:null,...Ee.getState().isProviderModelRefEnabled()?{model_ref:Ee.getState().selectedModelRef}:{}},currentInteraction:null,...g};await t(v)},[t,s,n]),i=m.useCallback(async p=>{st("[ChatOps]","[useChatOperations] createChatWithSystemPrompt started with prompt:",p);const g={title:`New Session - ${p.name}`,createdAt:Date.now(),messages:[],config:{systemPromptId:p.id,baseSystemPrompt:p.content,lastUsedEnhancedPrompt:null},currentInteraction:null};st("[ChatOps]","[useChatOperations] Calling addChat with newChatData.config:",g.config),await t(g)},[t]),l=m.useCallback(p=>{const g=e.chats.find(y=>y.id===p);g&&(g.pinned?e.unpinSession(p):e.pinSession(p))},[e]),c=m.useCallback((p,g)=>{e.updateSession(p,{title:g})},[e]),d=m.useCallback(async()=>{await o.cleanupSessions("empty",!0),await N.getState().loadChats()},[o]),u=m.useCallback(async()=>{await o.cleanupSessions("all",!0),await N.getState().loadChats()},[o]),h=m.useCallback(async()=>{await o.cleanupSessions("all",!1),await N.getState().loadChats()},[o]);return{createNewChat:a,createChatWithSystemPrompt:i,toggleChatPin:l,updateChatTitle:c,deleteEmptyChats:d,deleteAllUnpinnedChats:u,deleteAllChats:h}}const Ho=new Map,ai=new Set,er=new Map,Qo=new Map;let Yo=null;const Sy=(e,t)=>{const s=Ho.get(e);s&&s.forEach(n=>n(t))},fm=()=>{if(Yo=null,Qo.size===0)return;const e=Array.from(Qo.values());Qo.clear(),e.forEach(t=>{Sy(t.messageId,t.content),ai.forEach(s=>s(t))})},ze={getLatest(e){return er.get(e)??null},subscribeMessage(e,t){let s=Ho.get(e);return s||(s=new Set,Ho.set(e,s)),s.add(t),er.has(e)&&t(er.get(e)??null),()=>{const n=Ho.get(e);n&&(n.delete(t),n.size===0&&Ho.delete(e))}},subscribe(e){return ai.add(e),()=>{ai.delete(e)}},publish(e){e.content===null?er.delete(e.messageId):er.set(e.messageId,e.content),Qo.set(e.messageId,e),Yo===null&&(Yo=requestAnimationFrame(fm))},clear(e,t){er.delete(t),Qo.delete(t),Sy(t,null),ai.forEach(s=>s({sessionId:e,messageId:t,content:null}))},forceFlush(){Yo!==null&&(cancelAnimationFrame(Yo),fm())}},wy="mermaid_enhancement_enabled",Cc=()=>localStorage.getItem(wy)!=="false",l_=e=>{localStorage.setItem(wy,e.toString())},c_=()=>`
|
|
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.`,Mc="task_enhancement_enabled",gm="todo_enhancement_enabled",d_=e=>e==="false",Pc=()=>{let e=localStorage.getItem(Mc);if(e===null){const t=localStorage.getItem(gm);t!==null&&(e=t,localStorage.setItem(Mc,t),localStorage.removeItem(gm))}return!d_(e)},u_=e=>{localStorage.setItem(Mc,e.toString())},m_=()=>`
|
|
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
|
+
`,_y=()=>{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"},h_=e=>{switch(e){case"windows":return"Windows";case"macos":return"macOS";case"linux":return"Linux";default:return"Unknown OS"}},p_=()=>{const e=_y(),s=`## 🖥️ Operating System Information
|
|
75
|
+
|
|
76
|
+
You are running on **${h_(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},Ty="copilot_conclusion_with_options_enhancement_enabled",ki=()=>localStorage.getItem(Ty)==="true",f_=e=>{try{localStorage.setItem(Ty,e.toString())}catch(t){console.error("[copilotConclusionWithOptionsEnhancement] Failed to persist setting:",t)}},g_=()=>"\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",y_=()=>["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(" "),ky="bamboo_system_prompt_enhancement",b_=()=>["## 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
|
+
`),x_=e=>e.map(s=>s.trim()).filter(s=>s.length>0).join(`
|
|
109
|
+
|
|
110
|
+
`),jy=()=>{try{return localStorage.getItem(ky)??""}catch(e){return console.error("Failed to load system prompt enhancement:",e),""}},v_=e=>{try{const t=e.trim()?e:"";localStorage.setItem(ky,t)}catch(t){console.error("Failed to save system prompt enhancement:",t)}},S_=e=>{const t=[];t.push(p_().trim()),t.push(b_().trim());const s=jy().trim();return s&&t.push(s),Cc()&&t.push(c_().trim()),Pc()&&t.push(m_().trim()),(e??"").trim().toLowerCase()==="copilot"&&ki()&&t.push(g_().trim()),t},w_=e=>x_(S_(e)),Ec=e=>{const t=(e??"").trim().toLowerCase();return t.includes("completion policy violation")&&t.includes("conclusion_with_options")},Rc=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 Cy(e){var R;const{modal:t,message:s}=Ot.useApp(),{t:n}=ne(),o=m.useRef(null),a=m.useRef(null),i=m.useRef(""),l=m.useRef(new rs),c=N(M=>M.agentAvailability),d=N(M=>M.setAgentAvailability),u=N(M=>M.checkAgentAvailability),h=N(M=>M.startAgentHealthCheck),p=Hi(e.sessionId),g=Ee(M=>M.currentProvider),y=N(M=>e.sessionId&&M.chats.find(T=>T.id===e.sessionId)||null),f=Bd((R=y==null?void 0:y.config)==null?void 0:R.model_ref);m.useEffect(()=>{h()},[h]);const v=m.useCallback(()=>{var T;(T=o.current)==null||T.abort();const M=y==null?void 0:y.id;M&&l.current.stopGeneration(M).catch(P=>{console.error("[useMessageStreaming] Failed to stop generation:",P)})},[y==null?void 0:y.id]),b=m.useCallback(M=>{var O;const T=N.getState(),S=(Array.isArray(T.chats)?T.chats:[]).find(D=>D.id===M),L=T.pendingQuestionRespond,$=(L==null?void 0:L.sessionId)===M?L:null,I=(O=S==null?void 0:S.config)==null?void 0:O.syncCursor,W=!!$||!!(I!=null&&I.hasPendingQuestion),A=($==null?void 0:$.toolCallId)??(I==null?void 0:I.pendingQuestionToolCallId)??null;return{client_message_count:(I==null?void 0:I.messageCount)??(S==null?void 0:S.messageCount)??0,client_last_message_id:(I==null?void 0:I.lastMessageId)??null,client_has_pending_question:W,client_pending_question_tool_call_id:A}},[]),x=m.useCallback((M,T)=>{const P=T.sync;if(!P)return;const S=N.getState(),$=(Array.isArray(S.chats)?S.chats:[]).find(I=>I.id===M);$&&e.updateSession(M,{messageCount:P.server_message_count,config:{...$.config||{},syncCursor:{messageCount:P.server_message_count,lastMessageId:P.server_last_message_id??null,hasPendingQuestion:P.has_pending_question,pendingQuestionToolCallId:P.pending_question_tool_call_id??null}}})},[e]),_=m.useCallback(async M=>{try{return await pe.get(`respond/${M}/pending`)}catch(T){return console.warn(`[useMessageStreaming] Failed to fetch pending question for ${M}:`,T),{has_pending_question:!1}}},[]),w=m.useCallback(async(M,T,P)=>{var A,O;e.setSessionProcessing(M,!1),await N.getState().loadChatHistory(M,{mode:"replace"});const S=await _(M),L=N.getState().setPendingQuestionRespond,$=N.getState().clearPendingQuestionRespondForSession;if(S.has_pending_question){L({sessionId:M,question:S.question||"",options:S.options||[],allowCustom:S.allow_custom??!0,toolCallId:S.tool_call_id??null});const D=N.getState().chats.find(H=>H.id===M);return D&&e.updateSession(M,{config:{...D.config||{},syncCursor:{messageCount:D.messageCount??D.messages.length,lastMessageId:((O=(A=D.config)==null?void 0:A.syncCursor)==null?void 0:O.lastMessageId)??null,hasPendingQuestion:!0,pendingQuestionToolCallId:S.tool_call_id??null}}}),null}if($(M),!((T==null?void 0:T.has_pending_user_message)??!1))return null;e.setSessionProcessing(M,!0),await new Promise(D=>setTimeout(D,0));const W=P?await l.current.execute(M,void 0,P,b(M),f??void 0):await l.current.execute(M,void 0,void 0,b(M),f??void 0);return x(M,W),W},[f,x,b,e,_]),k=m.useCallback(async(M,T,P)=>{var I,W;let S=T;x(M,S);const L=2;let $=0;for(;(I=S.sync)!=null&&I.need_sync&&$<L;){const A=await w(M,S.sync,P);if($+=1,!A){e.setSessionProcessing(M,!1);return}S=A,x(M,S)}if((W=S.sync)!=null&&W.need_sync){console.warn(`[useMessageStreaming] Execute remains out-of-sync after ${L} recovery attempt(s) for session ${M}.`,S.sync),e.setSessionProcessing(M,!1);return}if(!["started","already_running"].includes(S.status)){if(S.status==="completed"){st("[Streaming]","[Agent] Session already completed"),e.setSessionProcessing(M,!1);return}throw console.error("[Agent] Execute failed:",S.status),e.setSessionProcessing(M,!1),new Error(`Execute failed: ${S.status}`)}},[x,e,w]),C=m.useCallback(async(M,T,P,S,L)=>{var I,W;if(!p)throw new Error(n("chat.model.noModelSelected"));const $=new AbortController;o.current=$;try{const A=w_(g).trim(),O=(g??"").trim().toLowerCase()==="copilot"&&ki(),H=(((I=y==null?void 0:y.config)==null?void 0:I.workspacePath)||"").trim().replace(/\/+$/,"").replace(/\\+$/,""),B=await l.current.sendMessage({message:M,session_id:T,enhance_prompt:A||void 0,copilot_conclusion_with_options_enhancement_enabled:O,workspace_path:H||void 0,selected_skill_ids:L&&L.length>0?L:void 0,images:(W=P.images)==null?void 0:W.filter(z=>!!z.base64).map(z=>({base64:z.base64,name:z.name,size:z.size,type:z.type})),model:p,...f?{model_ref:f,provider:f.provider}:{}}),{session_id:K}=B;K!==T&&console.warn(`[useMessageStreaming] Backend returned unexpected session_id=${K} for sessionId=${T}`),await N.getState().loadChatHistory(T,{mode:"replace"}),e.setSessionProcessing(T,!0),await new Promise(z=>setTimeout(z,0));const F=S?await l.current.execute(T,void 0,S,b(T),f??void 0):await l.current.execute(T,void 0,void 0,b(T),f??void 0);st("[Streaming]","[Agent] Execute status:",F.status),await k(T,F,S)}catch(A){throw A}},[p,f,b,y,g,e,k,n]),E=m.useCallback(async(M,T,P,S)=>{if(!y){t.info({title:n("chat.streaming.noActiveChatTitle"),content:n("chat.streaming.noActiveChatSendContent")});return}if(!e.sessionId){t.info({title:n("chat.streaming.noChatIdTitle"),content:n("chat.streaming.noChatIdSendContent")});return}if(!p){t.error({title:n("chat.model.noModelSelected"),content:n("chat.model.selectModelBeforeSend")});return}let L=c;if(L===null&&(L=await u()),!L){s.error(n("chat.streaming.agentUnavailable"));return}if(!p){s.error(n("chat.streaming.modelConfigNotLoaded"));return}const $=e.sessionId,I=(T==null?void 0:T.map(A=>({id:A.id,base64:A.base64,name:A.name,size:A.size,type:A.type})))||[],W={role:"user",content:M,id:crypto.randomUUID(),createdAt:new Date().toISOString(),images:I};await e.addMessage($,W);try{st("[Streaming]","[useChatStreaming] Using Agent Server"),await C(M,$,W,P,S)}catch(A){if(a.current&&ze.clear($,a.current),a.current=null,i.current="",A instanceof Error&&A.name==="AbortError")s.info(n("chat.streaming.requestCancelled"));else{console.error("[useChatStreaming] Failed to send message:",A);const O=A instanceof Error?A.message:String(A??"");Ec(O)?s.error(Rc(O)):(s.error(n("chat.streaming.sendFailed")),d(!1))}e.setSessionProcessing($,!1)}finally{o.current=null,a.current&&ze.clear($,a.current),a.current=null,i.current=""}},[c,s,u,y,e,t,C,d,p,n]),j=m.useCallback(async(M,T="regenerate")=>{if(!y){t.info({title:n("chat.streaming.noActiveChatTitle"),content:n("chat.streaming.noActiveChatRetryContent")});return}if(!e.sessionId){t.info({title:n("chat.streaming.noChatIdTitle"),content:n("chat.streaming.noChatIdRetryContent")});return}if(!p){t.error({title:n("chat.model.noModelSelected"),content:n("chat.model.selectModelBeforeRetry")});return}let P=c;if(P===null&&(P=await u()),!P){s.error(n("chat.streaming.agentUnavailable"));return}const S=e.sessionId;a.current&&ze.clear(S,a.current),a.current=null,i.current="";try{const L=T==="error_retry"?"error_retry":"after_last_user",$=await l.current.truncateSessionMessages(S,{mode:L});(T==="regenerate"||($.messages_removed??0)>0)&&await N.getState().loadChatHistory(S,{mode:"replace"}),e.setSessionProcessing(S,!0);const I=M?await l.current.execute(S,void 0,M,b(S),f??void 0):await l.current.execute(S,void 0,void 0,b(S),f??void 0);await k(S,I,M)}catch(L){console.error("[useMessageStreaming] Retry failed:",L);const $=L instanceof Error?L.message:String(L??"");Ec($)?s.error(Rc($)):s.error(n("chat.streaming.retryFailed")),e.setSessionProcessing(S,!1)}finally{o.current=null}},[p,f,c,s,b,u,y,e,k,t,n]);return{sendMessage:E,retryLastTurn:j,cancel:v,agentAvailable:c}}function __(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 T_=()=>{const e=a_(),t=Ud(e),s=i_(e),n=Cy({sessionId:e.currentSessionId,addMessage:e.addMessage,setSessionProcessing:e.setSessionProcessing,updateSession:e.updateSession}),o=__(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}},My="lotus_vdi_safe_mode",ji=()=>{try{return localStorage.getItem(My)==="true"}catch{return!1}},k_=e=>{try{localStorage.setItem(My,e.toString())}catch(t){console.error("[vdiSafeMode] Failed to persist setting:",t)}},{Text:Fa}=le,{useToken:j_}=he,C_=({httpProxy:e,httpsProxy:t,onHttpProxyChange:s,onHttpsProxyChange:n,onReload:o,onSave:a,isLoading:i})=>{const{t:l}=ne(),{token:c}=j_(),d=ms(w=>w.proxyAuthStatus),u=ms(w=>w.isLoadingProxyAuthStatus),h=ms(w=>w.loadProxyAuthStatus),p=ms(w=>w.applyProxyAuth),g=ms(w=>w.clearProxyAuth),[y,f]=m.useState({username:"",password:""}),[v,b]=m.useState(!1);m.useEffect(()=>{h()},[h]);const x=async()=>{const w=y.username.trim();if(w){b(!0);try{await p({username:w,password:y.password}),f({username:"",password:""})}catch(k){console.error("Failed to apply proxy auth:",k)}finally{b(!1)}}},_=async()=>{b(!0);try{await g()}catch(w){console.error("Failed to clear proxy auth:",w)}finally{b(!1)}};return r.jsx(ee,{size:"small",title:r.jsx(Fa,{strong:!0,children:l("settings.networkCard.title")}),className:"lotus-settings-card",children:r.jsxs(X,{direction:"vertical",size:c.marginSM,style:{width:"100%"},children:[r.jsx(Xe,{message:l("settings.networkCard.guideTip"),type:"info",showIcon:!0}),r.jsxs(X,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[r.jsx(Fa,{type:"secondary",children:l("settings.networkCard.httpProxy")}),r.jsx(me,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:w=>s(w.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),r.jsxs(X,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[r.jsx(Fa,{type:"secondary",children:l("settings.networkCard.httpsProxy")}),r.jsx(me,{style:{width:"100%"},value:t,onChange:w=>n(w.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),r.jsx(ee,{size:"small",title:l("settings.networkCard.proxyAuthTitle"),className:"lotus-settings-card",style:{marginTop:c.marginSM},children:d!=null&&d.configured?r.jsxs(X,{direction:"vertical",style:{width:"100%"},children:[r.jsx(Xe,{type:"success",message:l("settings.networkCard.proxyConfiguredForUser",{username:d.username??""}),showIcon:!0}),r.jsx(Y,{onClick:_,loading:v||u,danger:!0,children:l("settings.networkCard.clearCredentials")})]}):r.jsxs(X,{direction:"vertical",size:c.marginXS,style:{width:"100%"},children:[r.jsx(me,{placeholder:l("settings.networkCard.username"),value:y.username,onChange:w=>f(k=>({...k,username:w.target.value}))}),r.jsx(me.Password,{placeholder:l("settings.networkCard.password"),value:y.password,onChange:w=>f(k=>({...k,password:w.target.value}))}),r.jsx(Y,{type:"primary",onClick:x,loading:v||u,disabled:!y.username.trim(),children:l("settings.networkCard.apply")})]})}),r.jsx(Fa,{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(Y,{onClick:()=>Promise.resolve(o()).finally(()=>h({force:!0})),disabled:i,children:l("settings.networkCard.reload")}),r.jsx(Y,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(a()).finally(()=>h({force:!0})),disabled:i,children:l("settings.networkCard.save")})]})]})})},{Text:M_}=le,{useToken:P_}=he,E_=({msgApi:e})=>{const{t}=ne(),{token:s}=P_(),[n]=Z.useForm(),[o,a]=m.useState(!1),[i,l]=m.useState(!1),[c,d]=m.useState(!1),[u,h]=m.useState(!1),[p,g]=m.useState(null),y=c&&!u,f=m.useMemo(()=>c?u?t("settings.configTab.accessPassword.helperLocalBypass","当前是本地访问,可直接修改访问密码,无需输入当前密码。"):t("settings.configTab.accessPassword.helperRemote","当前是远程访问。修改访问密码前,必须先输入当前密码。"):t("settings.configTab.accessPassword.helperNotEnabled","未设置访问密码。设置后,远程访问需要先输入密码,本地 loopback 访问可直接绕过。"),[u,c,t]),v=m.useCallback(async()=>{a(!0),g(null);try{const x=await et.getAccessStatus();d(x.password_enabled),h(x.local_bypass)}catch(x){const _=x instanceof Error?x.message:t("settings.configTab.accessPassword.loadStatusFailed","Failed to load access status");g(_)}finally{a(!1)}},[t]);m.useEffect(()=>{v()},[v]);const b=async()=>{var x;try{const _=await n.validateFields();l(!0),await et.updateAccessPassword({current_password:((x=_.currentPassword)==null?void 0:x.trim())||void 0,new_password:_.newPassword.trim()}),e.success(c?t("settings.configTab.accessPassword.updated","访问密码已更新"):t("settings.configTab.accessPassword.enabled","访问密码已设置")),n.resetFields(),await v()}catch(_){if(_.errorFields)return;const w=_ instanceof Error?_.message:t("settings.configTab.accessPassword.updateFailed","Failed to update access password");e.error(w)}finally{l(!1)}};return r.jsx(ee,{size:"small",className:"lotus-settings-card",title:r.jsx(M_,{strong:!0,children:t("settings.configTab.accessPasswordTitle","访问密码")}),children:r.jsxs(X,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[r.jsx(Xe,{type:c?"info":"warning",showIcon:!0,message:c?t("settings.configTab.accessPassword.statusEnabled","访问密码已启用"):t("settings.configTab.accessPassword.statusDisabled","访问密码未启用"),description:f}),p?r.jsx(Xe,{type:"error",showIcon:!0,message:p}):null,r.jsxs(Z,{form:n,layout:"vertical",disabled:o||i,children:[y?r.jsx(Z.Item,{label:t("settings.configTab.accessPassword.currentPasswordLabel","当前密码"),name:"currentPassword",rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.currentPasswordRequired","请输入当前密码")}],children:r.jsx(me.Password,{autoComplete:"current-password"})}):null,r.jsx(Z.Item,{label:c?t("settings.configTab.accessPassword.newPasswordLabel","新密码"):t("settings.configTab.accessPassword.setPasswordLabel","设置密码"),name:"newPassword",rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.newPasswordRequired","请输入新密码")},{min:4,message:t("settings.configTab.accessPassword.validation.minLength","密码长度至少 4 位")}],children:r.jsx(me.Password,{autoComplete:"new-password"})}),r.jsx(Z.Item,{label:t("settings.configTab.accessPassword.confirmPasswordLabel","确认密码"),name:"confirmPassword",dependencies:["newPassword"],rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.confirmPasswordRequired","请再次输入新密码")},({getFieldValue:x})=>({validator(_,w){return!w||x("newPassword")===w?Promise.resolve():Promise.reject(new Error(t("settings.configTab.accessPassword.validation.passwordMismatch","两次输入的密码不一致")))}})],children:r.jsx(me.Password,{autoComplete:"new-password"})}),r.jsx(Y,{type:"primary",loading:i,onClick:()=>void b(),children:c?t("settings.configTab.accessPassword.updateAction","更新访问密码"):t("settings.configTab.accessPassword.enableAction","启用访问密码")})]})]})})},{Text:qt}=le,{useToken:R_}=he,ym="http://127.0.0.1:9562/v1",Xo=e=>[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort(),A_=e=>{var s;const t=(s=e.tools)==null?void 0:s.disabled;return Array.isArray(t)?Xo(t.filter(n=>typeof n=="string")):[]},I_=({msgApi:e,locale:t,onLocaleChange:s})=>{const{t:n}=ne(),{token:o}=R_(),[a,i]=m.useState({http_proxy:"",https_proxy:"",memory:{auto_dream_enabled:!1,background_model:""}}),[l,c]=m.useState(ym),[d,u]=m.useState([]),[h,p]=m.useState([]),[g,y]=m.useState([]),[f,v]=m.useState(!1),[b,x]=m.useState(!1),_=m.useCallback(async()=>{var I,W;v(!0);try{const[A,O]=await Promise.all([et.getBambooConfig(),et.getBambooTools()]);i({http_proxy:A.http_proxy||"",https_proxy:A.https_proxy||"",memory:{auto_dream_enabled:((I=A.memory)==null?void 0:I.auto_dream_enabled)??!1,background_model:((W=A.memory)==null?void 0:W.background_model)||""}});const D=A_(A);p(D),y(D),u(Xo(O.tools||[]))}catch(A){console.error("Failed to load config:",A),e.error(n("settings.configTab.loadConfigFailed"))}finally{v(!1)}},[e,n]);m.useEffect(()=>{_()},[_]);const w=I=>{i(W=>({...W,http_proxy:I}))},k=I=>{i(W=>({...W,https_proxy:I}))},C=I=>{i(W=>({...W,memory:{...W.memory,auto_dream_enabled:I}}))},E=I=>{i(W=>({...W,memory:{...W.memory,background_model:I}}))},j=async()=>{var I,W;v(!0);try{const A=await et.validateBambooConfigPatch(a);if(!A.valid){const D=((W=(I=A.errors)==null?void 0:I.proxy)==null?void 0:W[0])??Object.values(A.errors||{}).flat().filter(Boolean)[0];e.error((D==null?void 0:D.message)||n("settings.configTab.invalidConfig"));return}await et.setBambooConfig(a),e.success(n("settings.configTab.saveConfigSuccess"))}catch(A){console.error("Failed to save config:",A);const O=A instanceof Error&&A.message.trim()?A.message:n("settings.configTab.saveConfigFailed");e.error(O)}finally{v(!1)}},R=async()=>{e.success(n("settings.configTab.backendSaved"))},M=()=>{c(ym),e.success(n("settings.configTab.backendResetDefault"))},T=(I,W)=>{p(A=>{const O=new Set(A);return W?O.delete(I):O.add(I),Xo([...O])})},P=async()=>{x(!0);try{const I=await et.getBambooTools();u(Xo(I.tools||[])),e.success(n("settings.configTab.toolsReloadSuccess"))}catch(I){console.error("Failed to reload tools:",I),e.error(n("settings.configTab.toolsLoadFailed"))}finally{x(!1)}},S=async()=>{x(!0);try{const I=Xo(h);await et.setBambooConfig({tools:{disabled:I}}),p(I),y(I),e.success(n("settings.configTab.toolsSaveSuccess"))}catch(I){console.error("Failed to save tool settings:",I),e.error(n("settings.configTab.toolsSaveFailed"))}finally{x(!1)}},L=JSON.stringify(h)!==JSON.stringify(g),$=new Set(h);return r.jsx(ps,{spinning:f,tip:n("settings.common.loading"),children:r.jsx(ui,{items:[{key:"general",label:n("settings.configTab.tabs.general"),children:r.jsxs(X,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(Xe,{message:n("settings.configTab.providerMovedTitle"),description:n("settings.configTab.providerMovedDescription"),type:"info",showIcon:!0,closable:!0}),r.jsx(C_,{httpProxy:a.http_proxy,httpsProxy:a.https_proxy,onHttpProxyChange:w,onHttpsProxyChange:k,onReload:_,onSave:j,isLoading:f}),r.jsx(ee,{size:"small",className:"lotus-settings-card",title:r.jsx(qt,{strong:!0,children:n("settings.configTab.language")}),children:r.jsx(Pe,{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:I=>s(I)})}),r.jsx(ee,{size:"small",className:"lotus-settings-card",title:r.jsx(qt,{strong:!0,children:n("settings.configTab.memoryTitle")}),children:r.jsxs(X,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(qt,{type:"secondary",children:n("settings.configTab.memoryDescription")}),r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:o.marginMD,flexWrap:"wrap"},children:[r.jsxs("div",{children:[r.jsx(qt,{strong:!0,children:n("settings.configTab.autoDreamEnabled")}),r.jsx("div",{children:r.jsx(qt,{type:"secondary",style:{fontSize:o.fontSizeSM},children:n("settings.configTab.autoDreamEnabledHint")})})]}),r.jsx(it,{"data-testid":"auto-dream-toggle",checked:a.memory.auto_dream_enabled,onChange:C})]}),r.jsxs(X,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:[r.jsx(qt,{strong:!0,children:n("settings.configTab.backgroundModel")}),r.jsx(me,{"data-testid":"auto-dream-background-model-input",value:a.memory.background_model,onChange:I=>E(I.target.value),placeholder:n("settings.configTab.backgroundModelPlaceholder")}),r.jsx(qt,{type:"secondary",style:{fontSize:o.fontSizeSM},children:n("settings.configTab.backgroundModelHint")})]}),r.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:r.jsx(Y,{"data-testid":"save-memory-settings",type:"primary",onClick:j,loading:f,children:n("settings.configTab.save")})})]})}),r.jsx(ee,{size:"small",title:r.jsx(qt,{strong:!0,children:n("settings.configTab.backendApiBaseUrlTitle")}),children:r.jsxs(X,{direction:"vertical",size:o.marginSM,style:{width:"100%"},children:[r.jsx(X,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:r.jsx(me,{style:{width:"100%"},value:l,onChange:I=>c(I.target.value),placeholder:n("settings.configTab.backendApiPlaceholder")})}),r.jsx(qt,{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(Y,{"data-testid":"reset-to-defaults",onClick:M,children:n("settings.configTab.resetToDefault")}),r.jsx(Y,{"data-testid":"save-api-settings",type:"primary",onClick:R,children:n("settings.configTab.save")})]})]})}),r.jsx(E_,{msgApi:e})]})},{key:"tools",label:n("settings.configTab.tabs.tools"),children:r.jsx(ee,{size:"small",title:r.jsx(qt,{strong:!0,children:n("settings.configTab.toolsTitle")}),children:r.jsxs(X,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(qt,{type:"secondary",children:n("settings.configTab.toolsDescription")}),d.length===0?r.jsx(Xe,{type:"info",showIcon:!0,message:n("settings.configTab.toolsEmpty")}):r.jsx(nt,{bordered:!0,dataSource:d,renderItem:I=>r.jsx(nt.Item,{actions:[r.jsx(it,{checked:!$.has(I),onChange:W=>T(I,W)},`${I}-switch`)],children:r.jsx(qt,{code:!0,children:I})})}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:o.marginSM},children:[r.jsx(Y,{onClick:P,loading:b,children:n("settings.configTab.reloadTools")}),r.jsx(Y,{type:"primary",onClick:S,loading:b,disabled:!L,children:n("settings.configTab.save")})]})]})})}]})})},bm={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},Hd=un()(hv(e=>({settings:bm,updateSettings:t=>e(s=>({settings:{...s.settings,...t}})),resetSettings:()=>e({settings:bm})}),{name:"mermaid-settings"})),Xi=()=>Hd(t=>t.settings),$_=()=>Hd(e=>e.updateSettings),D_=()=>Hd(e=>e.resetSettings),{Title:L_,Text:vl}=le,{useToken:O_}=he,F_=()=>{const{t:e}=ne(),{token:t}=O_(),s=Xi(),n=$_(),o=D_(),[a]=Z.useForm();ut.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(L_,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),r.jsx(vl,{type:"secondary",style:{display:"block",marginBottom:"24px"},children:e("settings.mermaidTab.description")}),r.jsxs(Z,{form:a,layout:"vertical",initialValues:s,onValuesChange:i,children:[r.jsxs(ee,{title:e("settings.mermaidTab.themeCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[r.jsx(Gt,{gutter:16,children:r.jsx(Oe,{span:24,children:r.jsx(Z.Item,{name:"theme",label:r.jsxs(X,{children:[e("settings.mermaidTab.themeLabel"),r.jsx(ke,{title:e("settings.mermaidTab.themeTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsxs(Pe,{children:[r.jsx(Pe.Option,{value:"default",children:e("settings.mermaidTab.themeOptions.default")}),r.jsx(Pe.Option,{value:"neutral",children:e("settings.mermaidTab.themeOptions.neutral")}),r.jsx(Pe.Option,{value:"dark",children:e("settings.mermaidTab.themeOptions.dark")}),r.jsx(Pe.Option,{value:"forest",children:e("settings.mermaidTab.themeOptions.forest")}),r.jsx(Pe.Option,{value:"base",children:e("settings.mermaidTab.themeOptions.base")})]})})})}),r.jsxs(vl,{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(ee,{title:e("settings.mermaidTab.globalCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[r.jsxs(Gt,{gutter:16,children:[r.jsx(Oe,{span:12,children:r.jsx(Z.Item,{name:"fontSize",label:r.jsxs(X,{children:[e("settings.mermaidTab.fontSizeLabel"),r.jsx(ke,{title:e("settings.mermaidTab.fontSizeTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:10,max:32,step:1,style:{width:"100%"},addonAfter:"px"})})}),r.jsx(Oe,{span:12,children:r.jsx(Z.Item,{name:"defaultScale",label:r.jsxs(X,{children:[e("settings.mermaidTab.defaultZoomLabel"),r.jsx(ke,{title:e("settings.mermaidTab.defaultZoomTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:.1,max:3,step:.1,style:{width:"100%"}})})})]}),r.jsx(Z.Item,{name:"useMaxWidth",label:r.jsxs(X,{children:[e("settings.mermaidTab.responsiveWidthLabel"),r.jsx(ke,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),valuePropName:"checked",children:r.jsx(it,{})})]}),r.jsx(ee,{title:e("settings.mermaidTab.flowchartCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(Gt,{gutter:16,children:[r.jsx(Oe,{span:8,children:r.jsx(Z.Item,{name:"flowchartNodeSpacing",label:r.jsxs(X,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),r.jsx(ke,{title:e("settings.mermaidTab.flowchartNodeSpacingTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Oe,{span:8,children:r.jsx(Z.Item,{name:"flowchartRankSpacing",label:r.jsxs(X,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),r.jsx(ke,{title:e("settings.mermaidTab.flowchartRankSpacingTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Oe,{span:8,children:r.jsx(Z.Item,{name:"flowchartCurve",label:r.jsxs(X,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),r.jsx(ke,{title:e("settings.mermaidTab.flowchartCurveTypeTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsxs(Pe,{children:[r.jsx(Pe.Option,{value:"basis",children:e("settings.mermaidTab.flowchartCurveOptions.basis")}),r.jsx(Pe.Option,{value:"linear",children:e("settings.mermaidTab.flowchartCurveOptions.linear")}),r.jsx(Pe.Option,{value:"cardinal",children:e("settings.mermaidTab.flowchartCurveOptions.cardinal")})]})})})]})}),r.jsx(ee,{title:e("settings.mermaidTab.sequenceCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(Gt,{gutter:16,children:[r.jsx(Oe,{span:6,children:r.jsx(Z.Item,{name:"sequenceActorMargin",label:r.jsxs(X,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),r.jsx(ke,{title:e("settings.mermaidTab.sequenceActorMarginTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Oe,{span:6,children:r.jsx(Z.Item,{name:"sequenceMessageMargin",label:r.jsxs(X,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),r.jsx(ke,{title:e("settings.mermaidTab.sequenceMessageMarginTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:10,max:100,step:5,style:{width:"100%"}})})}),r.jsx(Oe,{span:6,children:r.jsx(Z.Item,{name:"sequenceWidth",label:r.jsxs(X,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),r.jsx(ke,{title:e("settings.mermaidTab.sequenceActorWidthTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:100,max:300,step:10,style:{width:"100%"}})})}),r.jsx(Oe,{span:6,children:r.jsx(Z.Item,{name:"sequenceHeight",label:r.jsxs(X,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),r.jsx(ke,{title:e("settings.mermaidTab.sequenceActorHeightTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:40,max:150,step:5,style:{width:"100%"}})})})]})}),r.jsx(ee,{title:e("settings.mermaidTab.ganttCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(Gt,{gutter:16,children:[r.jsx(Oe,{span:12,children:r.jsx(Z.Item,{name:"ganttBarHeight",label:r.jsxs(X,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),r.jsx(ke,{title:e("settings.mermaidTab.ganttBarHeightTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:10,max:50,step:5,style:{width:"100%"},addonAfter:"px"})})}),r.jsx(Oe,{span:12,children:r.jsx(Z.Item,{name:"ganttTopPadding",label:r.jsxs(X,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),r.jsx(ke,{title:e("settings.mermaidTab.ganttTopPaddingTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:20,max:100,step:10,style:{width:"100%"}})})})]})}),r.jsx(X,{children:r.jsx(Y,{icon:r.jsx(dx,{}),onClick:l,children:e("settings.mermaidTab.resetToDefaults")})}),r.jsx(Rt,{}),r.jsx(ee,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsx(vl,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},z_=m.lazy(()=>Dt(()=>import("./index-BAxa3Q-a.js"),__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url)),{Text:bn}=le,{useToken:N_}=he,B_=({promptEnhancement:e,onPromptEnhancementChange:t,mermaidEnhancementEnabled:s,taskEnhancementEnabled:n,showCopilotConclusionWithOptionsEnhancement:o,copilotConclusionWithOptionsEnhancementEnabled:a,onMermaidToggle:i,onTaskToggle:l,onCopilotConclusionWithOptionsToggle:c,onSaveEnhancement:d})=>{const{t:u}=ne(),{token:h}=N_(),p=h.marginLG;return r.jsxs(G,{vertical:!0,gap:p,children:[r.jsx(ee,{size:"small",className:"lotus-settings-card",children:r.jsx(m.Suspense,{fallback:r.jsx(ps,{size:"small"}),children:r.jsx(z_,{})})}),r.jsx(ee,{size:"small",className:"lotus-settings-card",children:r.jsxs(X,{direction:"vertical",size:h.marginXS,style:{width:"100%"},children:[r.jsx(bn,{strong:!0,children:u("settings.promptsTab.title")}),r.jsxs(G,{align:"center",gap:h.marginSM,children:[r.jsx(bn,{strong:!0,children:u("settings.promptsTab.mermaidEnhancement")}),r.jsx(it,{checked:s,onChange:i})]}),r.jsxs(G,{align:"center",gap:h.marginSM,children:[r.jsx(bn,{strong:!0,children:u("settings.promptsTab.taskListRules")}),r.jsx(it,{checked:n,onChange:l})]}),o&&r.jsxs(X,{direction:"vertical",size:h.marginXXS,style:{width:"100%"},children:[r.jsxs(G,{align:"center",gap:h.marginSM,children:[r.jsx(bn,{strong:!0,children:u("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),r.jsx(it,{checked:a,onChange:c})]}),r.jsx(bn,{type:"secondary",style:{fontSize:h.fontSizeSM},children:u("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:y_()})})]}),r.jsx(me.TextArea,{rows:6,placeholder:u("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:g=>t(g.target.value)}),r.jsx(G,{justify:"flex-end",children:r.jsx(Y,{type:"primary",onClick:d,children:u("settings.promptsTab.saveEnhancement")})}),r.jsx(bn,{type:"secondary",style:{fontSize:h.fontSizeSM},children:u("settings.promptsTab.description")})]})}),s&&r.jsx(ns,{size:"small",items:[{key:"mermaid",label:r.jsx(bn,{strong:!0,children:u("settings.mermaidTab.title")}),children:r.jsx(F_,{})}]})]})},Yd="bodhi_onboarding_complete",W_=()=>localStorage.getItem(Yd)==="true",U_=()=>localStorage.setItem(Yd,"true"),q_=()=>localStorage.removeItem(Yd),H_=["new-session","task-templates","model-picker","sidebar","open-settings"],Y_=()=>{const e={};for(const t of H_)e[t]=document.querySelector(`[data-tour-id="${t}"]`);return e},X_=({disabled:e=!1})=>{const{t}=ne(),[s,n]=m.useState(!1),[o,a]=m.useState(null);m.useEffect(()=>{if(e||W_())return;const c=setTimeout(()=>{const d=Y_();a(d),n(!0)},800);return()=>clearTimeout(c)},[e]);const i=m.useMemo(()=>[{title:t("onboarding.welcome.title"),description:t("onboarding.welcome.description"),target:null},{title:t("onboarding.newSession.title"),description:t("onboarding.newSession.description"),target:(o==null?void 0:o["new-session"])??void 0},{title:t("onboarding.taskTemplates.title"),description:t("onboarding.taskTemplates.description"),target:(o==null?void 0:o["task-templates"])??void 0},{title:t("onboarding.modelPicker.title"),description:t("onboarding.modelPicker.description"),target:(o==null?void 0:o["model-picker"])??void 0},{title:t("onboarding.sidebar.title"),description:t("onboarding.sidebar.description"),target:(o==null?void 0:o.sidebar)??void 0},{title:t("onboarding.settings.title"),description:t("onboarding.settings.description"),target:(o==null?void 0:o["open-settings"])??void 0}],[t,o]),l=()=>{U_(),n(!1)};return r.jsx(ux,{open:s,onClose:l,steps:i})},{Text:vs}=le,{useToken:V_}=he,K_=({autoGenerateTitles:e,isUpdatingAutoTitlePreference:t,onAutoTitleToggle:s,themeMode:n,onThemeModeChange:o,vdiSafeMode:a,onVdiSafeModeToggle:i,onClearLocalStorage:l,onResetApp:c,isResetting:d,darkModeKey:u})=>{const{t:h}=ne(),{token:p}=V_();return r.jsx(ee,{size:"small",className:"lotus-settings-card",children:r.jsxs(X,{direction:"vertical",size:p.marginSM,style:{width:"100%"},children:[r.jsxs(G,{align:"center",gap:p.marginSM,children:[r.jsx(vs,{strong:!0,children:h("settings.appTab.autoGenerateTitle")}),r.jsx(it,{checked:e,loading:t,onChange:s})]}),r.jsx(vs,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.autoGenerateTitleDesc")}),r.jsxs(G,{align:"center",justify:"space-between",gap:p.marginSM,children:[r.jsx(vs,{strong:!0,children:h("settings.appTab.runningVersion","Running version")}),r.jsxs(vs,{code:!0,"data-testid":"settings-app-version",children:["v",xd]})]}),r.jsx(vs,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),r.jsxs(G,{align:"center",gap:p.marginSM,children:[r.jsx(vs,{strong:!0,children:h("settings.appTab.darkMode")}),r.jsx(it,{"data-testid":"dark-mode-toggle",checked:n==="dark",onChange:g=>{const y=g?"dark":"light";o(y),localStorage.setItem(u,y)}})]}),r.jsxs(G,{align:"center",gap:p.marginSM,children:[r.jsx(vs,{strong:!0,children:h("settings.appTab.vdiSafeMode","Graphics compatibility mode")}),r.jsx(it,{"data-testid":"vdi-safe-mode-toggle",checked:a,onChange:i})]}),r.jsx(vs,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.vdiSafeModeDesc","Disables blur and glass effects that can break dropdowns and hover overlays in some virtual desktop, remote, or graphics-constrained environments.")}),r.jsx(Y,{block:!0,icon:r.jsx(nd,{}),onClick:()=>{q_(),window.location.reload()},children:h("settings.appTab.resetStepReplayGuide")}),r.jsx(mi,{title:h("settings.appTab.clearLocalStorageTitle"),description:h("settings.appTab.clearLocalStorageDescription"),onConfirm:l,okText:h("settings.appTab.confirmClear"),cancelText:h("settings.appTab.cancel"),placement:"top",children:r.jsx(Y,{danger:!0,block:!0,icon:r.jsx(dn,{}),children:h("settings.appTab.clearLocalStorageButton")})}),r.jsx(Rt,{style:{margin:`${p.marginSM}px 0`}}),r.jsxs(G,{align:"center",gap:p.marginSM,children:[r.jsx(ua,{style:{color:p.colorError}}),r.jsx(vs,{strong:!0,style:{color:p.colorError},children:h("settings.appTab.dangerZone")})]}),r.jsx(vs,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.dangerDescription")}),r.jsx(mi,{title:h("settings.appTab.resetApplicationTitle"),description:r.jsxs("div",{children:[r.jsx("p",{children:h("settings.appTab.resetApplicationIntro")}),r.jsxs("ul",{style:{margin:0,paddingLeft:16},children:[r.jsx("li",{children:h("settings.appTab.resetStepDeleteAllSessions")}),r.jsx("li",{children:h("settings.appTab.resetStepClearStorage")}),r.jsx("li",{children:h("settings.appTab.resetStepResetConfig")}),r.jsx("li",{children:h("settings.appTab.resetStepSetupFlow")}),r.jsx("li",{children:h("settings.appTab.resetStepReload")})]})]}),onConfirm:c,okText:h("settings.appTab.resetConfirm"),cancelText:h("settings.appTab.cancel"),placement:"top",okButtonProps:{danger:!0},children:r.jsx(Y,{"data-testid":"reset-to-defaults",danger:!0,block:!0,type:"primary",icon:r.jsx(yf,{}),loading:d,children:h("settings.appTab.resetButton")})})]})})},{Text:xn}=le,{useToken:G_}=he,xm=[{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,}"}],J_=(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:es.t("settings.keywordMaskingTab.invalidRegexPattern")}}},Q_=()=>{const{t:e}=ne(),{token:t}=G_(),[s,n]=m.useState([]),[o,a]=m.useState(!1),[i,l]=m.useState(null),[c,d]=m.useState(""),[u,h]=m.useState("exact"),[p,g]=m.useState(!0),[y,f]=m.useState(),[v,b]=m.useState("My token is sk-123"),x=m.useCallback(async()=>{try{a(!0);const P=await fs.getInstance().getKeywordMaskingConfig();n(P.entries)}catch(T){fe.error(e("settings.keywordMaskingTab.loadFailed")),console.error(T)}finally{a(!1)}},[e]);m.useEffect(()=>{x()},[x]);const _=async T=>{try{const P=fs.getInstance(),S=await P.validateKeywordEntries(T);if(!S.valid&&S.errors){const $=S.errors.map(I=>`Entry ${I.index+1}: ${I.message}`).join("; ");return fe.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${$}`),!1}const L=await P.updateKeywordMaskingConfig(T);return n(L.entries),fe.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch(P){return fe.error(P instanceof Error?P.message:e("settings.keywordMaskingTab.saveFailed")),!1}},w=async()=>{const T={pattern:"",match_type:"exact",enabled:!0},P=[...s,T];n(P),l(P.length-1),d(""),h("exact"),g(!0),f(void 0)},k=T=>{const P=s[T];l(T),d(P.pattern),h(P.match_type),g(P.enabled),f(void 0)},C=async()=>{if(i===null)return;if(!c.trim()){fe.error(e("settings.keywordMaskingTab.patternRequired"));return}const T=[...s];T[i]={pattern:c.trim(),match_type:u,enabled:p},await _(T)&&l(null)},E=()=>{var T;i!==null&&!((T=s[i])!=null&&T.pattern)&&n(s.filter((P,S)=>S!==i)),l(null)},j=async T=>{const P=s.filter((S,L)=>L!==T);await _(P)},R=async(T,P)=>{const S=[...s];S[T]={...S[T],enabled:P},await _(S)},M=J_(v,c,u);return r.jsx(ee,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:r.jsx(Y,{"data-testid":"add-keyword",type:"primary",icon:r.jsx(Us,{}),onClick:w,loading:o,children:e("settings.keywordMaskingTab.addKeyword")}),children:r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:"large",children:[r.jsx(xn,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),r.jsx(nt,{loading:o,dataSource:s,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(T,P)=>r.jsx(nt.Item,{style:{backgroundColor:t.colorFillAlter,marginBottom:8,borderRadius:t.borderRadius,padding:12},actions:i===P?[r.jsx(Y,{"data-testid":"save-keyword",type:"primary",icon:r.jsx(Di,{}),onClick:C,"aria-label":e("settings.keywordMaskingTab.save")},"save"),r.jsx(Y,{onClick:E,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[r.jsx(Y,{icon:r.jsx(ca,{}),onClick:()=>k(P),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),r.jsx(Y,{"data-testid":`delete-keyword-${P}`,danger:!0,icon:r.jsx(dn,{}),onClick:()=>j(P),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:r.jsx(G,{vertical:!0,style:{width:"100%"},gap:8,children:i===P?r.jsxs(r.Fragment,{children:[r.jsx(me,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:c,onChange:S=>d(S.target.value),autoFocus:!0}),r.jsxs(G,{gap:8,align:"center",wrap:"wrap",children:[r.jsx(Pe,{"data-testid":"keyword-examples-select","aria-label":e("settings.keywordMaskingTab.examples"),placeholder:e("settings.keywordMaskingTab.examples"),value:y,onChange:S=>{f(S);const L=xm.find($=>$.value===S);L&&(d(L.pattern),h(L.match_type))},options:xm.map(S=>({value:S.value,label:e(S.labelKey)})),style:{minWidth:220}}),r.jsx(Pe,{value:u,onChange:h,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),r.jsx(it,{checked:p,onChange:g})]}),r.jsxs(G,{vertical:!0,gap:6,children:[r.jsx(xn,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),r.jsx(me,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:v,onChange:S=>b(S.target.value)}),r.jsx(xn,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),r.jsx(me,{readOnly:!0,value:M.masked,status:M.error?"error":void 0}),M.error&&r.jsx(xn,{type:"danger",children:M.error})]})]}):r.jsxs(G,{justify:"space-between",align:"center",children:[r.jsxs(G,{vertical:!0,gap:4,children:[r.jsx(xn,{strong:!0,children:T.pattern||e("settings.keywordMaskingTab.emptyPattern")}),r.jsxs(G,{gap:8,children:[r.jsx(xn,{type:"secondary",style:{fontSize:12},children:T.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!T.enabled&&r.jsx(xn,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),r.jsx(it,{checked:T.enabled,onChange:S=>R(P,S),size:"small"})]})})})})]})})},{Text:tr,Paragraph:Z_}=le,e0=/^[A-Za-z_][A-Za-z0-9_]*$/,t0=()=>{const{t:e}=ne(),[t,s]=m.useState([]),[n,o]=m.useState(!1),[a,i]=m.useState(!1),[l,c]=m.useState(null),[d]=Z.useForm(),u=m.useCallback(async()=>{o(!0);try{const b=await It.getEnvVars();s(b.entries)}catch{fe.error(e("settings.envVars.fetchError","Failed to load environment variables"))}finally{o(!1)}},[e]);m.useEffect(()=>{u()},[u]);const h=async b=>{var _;const x={name:b.name.trim(),value:b.value,secret:b.secret??!1,description:((_=b.description)==null?void 0:_.trim())||void 0};try{const w=await It.upsertEnvVar(x);s(w.entries),fe.success(l?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),f()}catch(w){fe.error((w instanceof Error?w.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},p=async b=>{try{const x=await It.deleteEnvVar(b);s(x.entries),fe.success(e("settings.envVars.deleted","Variable deleted"))}catch(x){fe.error((x instanceof Error?x.message:void 0)||e("settings.envVars.deleteError","Failed to delete variable"))}},g=()=>{c(null),d.resetFields(),d.setFieldsValue({secret:!1}),i(!0)},y=b=>{c(b.name),d.setFieldsValue({name:b.name,value:"",secret:b.secret,description:b.description??""}),i(!0)},f=()=>{i(!1),c(null),d.resetFields()},v=[{title:e("settings.envVars.name","Name"),dataIndex:"name",key:"name",render:b=>r.jsx(tr,{code:!0,children:b})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(b,x)=>x.secret?r.jsxs(tr,{type:"secondary",children:[r.jsx(lu,{style:{marginRight:4}}),x.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):r.jsx(tr,{children:b||r.jsx(tr,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(b,x)=>x.secret?r.jsx(oe,{color:"warning",icon:r.jsx(lu,{}),children:e("settings.envVars.secret","Secret")}):r.jsx(oe,{color:"processing",children:e("settings.envVars.plain","Plain")})},{title:e("settings.envVars.descriptionCol","Description"),dataIndex:"description",key:"description",ellipsis:!0,render:b=>b?r.jsx(tr,{type:"secondary",children:b}):r.jsx(tr,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(b,x)=>r.jsxs(X,{size:"small",children:[r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ca,{}),onClick:()=>y(x),"aria-label":e("settings.envVars.edit","Edit")}),r.jsx(mi,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>p(x.name),okText:e("settings.envVars.yes","Yes"),cancelText:e("settings.envVars.no","No"),children:r.jsx(Y,{type:"text",size:"small",danger:!0,icon:r.jsx(dn,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return r.jsxs("div",{style:{maxWidth:900},children:[r.jsxs(ee,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:r.jsx(Y,{type:"primary",icon:r.jsx(Us,{}),onClick:g,children:e("settings.envVars.addButton","Add Variable")}),children:[r.jsx(Z_,{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(qs,{dataSource:t,columns:v,rowKey:"name",size:"small",pagination:!1,loading:n,locale:{emptyText:e("settings.envVars.noVars","No environment variables configured")}})]}),r.jsx(Lt,{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(Z,{form:d,layout:"vertical",onFinish:h,initialValues:{secret:!1},children:[r.jsx(Z.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:e0,message:e("settings.envVars.nameInvalid","Must start with a letter or underscore, followed by letters, digits, or underscores")}],children:r.jsx(me,{placeholder:"GITHUB_TOKEN",disabled:l!==null,autoFocus:l===null})}),r.jsx(Z.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(me.Password,{placeholder:l?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),r.jsx(Z.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(it,{})}),r.jsx(Z.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:r.jsx(me,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},An=class An{constructor(){}static getInstance(){return An.instance||(An.instance=new An),An.instance}async listWorkflows(){try{st("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const t=await xe.get("bamboo/workflows"),s=Array.isArray(t)?t:[];return st("[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{st("[WorkflowManager]","[WorkflowManagerService] Getting workflow: "+t);const s=await xe.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 st("[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),kv(s)&&s.status===404?new Error("Workflow '"+t+"' not found"):s instanceof Error&&s.message.includes("404")?new Error("Workflow '"+t+"' not found"):s}}};He(An,"instance");let Ac=An;const{Text:Sl}=le,{TextArea:s0}=me,{useToken:n0}=he,r0=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),o0=()=>{const{t:e}=ne(),{token:t}=n0(),[s,n]=fe.useMessage(),[o,a]=m.useState([]),[i,l]=m.useState(!1),[c,d]=m.useState(!1),[u,h]=m.useState(!1),[p,g]=m.useState(null),[y,f]=m.useState(""),[v,b]=m.useState(""),[x,_]=m.useState(!1),w=m.useMemo(()=>Ac.getInstance(),[]),k=m.useCallback(async()=>{l(!0);try{const M=await w.listWorkflows();return a(M),M}catch{return s.error(e("settings.workflowsTab.loadFailed")),[]}finally{l(!1)}},[s,e,w]);m.useEffect(()=>{k()},[k]);const C=m.useCallback(async M=>{g(M),f(M.name),_(!1),d(!0);try{const T=await w.getWorkflow(M.name);b(T.content??"")}catch{s.error(e("settings.workflowsTab.loadContentFailed")),b("")}finally{d(!1)}},[s,e,w]),E=()=>{g(null),f(""),b(""),_(!1)},j=m.useCallback(async()=>{if(!r0(y)){s.error(e("settings.workflowsTab.invalidName"));return}const M=o.some(T=>T.name===y);if(!p&&M){s.error(e("settings.workflowsTab.nameAlreadyExists"));return}h(!0);try{await fs.getInstance().saveWorkflow(y,v),s.success(e("settings.workflowsTab.saved")),_(!1);const S=(await k()).find(L=>L.name===y);S&&g(S)}catch(T){s.error(T instanceof Error?T.message:e("settings.workflowsTab.saveFailed"))}finally{h(!1)}},[v,y,k,s,p,e,o]),R=m.useCallback(async M=>{try{await fs.getInstance().deleteWorkflow(M.name),s.success(e("settings.workflowsTab.deleted")),(p==null?void 0:p.name)===M.name&&E(),await k()}catch(T){s.error(T instanceof Error?T.message:e("settings.workflowsTab.deleteFailed"))}},[k,s,p,e]);return r.jsxs("div",{style:{padding:"24px"},children:[n,r.jsxs(ee,{title:e("settings.workflowsTab.title"),extra:r.jsxs(X,{children:[r.jsx(Y,{icon:r.jsx(Ms,{}),onClick:k,loading:i,children:e("settings.workflowsTab.refresh")}),r.jsx(Y,{"data-testid":"create-workflow",icon:r.jsx(Us,{}),onClick:E,children:e("settings.workflowsTab.newWorkflow")}),r.jsx(Y,{"data-testid":"save-workflow",type:"primary",icon:r.jsx(Di,{}),onClick:j,loading:u,disabled:!x,children:e("settings.workflowsTab.save")})]}),children:[r.jsx(Sl,{type:"secondary",children:e("settings.workflowsTab.description")}),r.jsxs(G,{gap:t.marginLG,style:{marginTop:t.marginLG},children:[r.jsx("div",{style:{width:320,flexShrink:0},children:r.jsx(nt,{loading:i,dataSource:o,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:M=>r.jsx(nt.Item,{style:{cursor:"pointer",backgroundColor:(p==null?void 0:p.name)===M.name?t.colorFillSecondary:"transparent",borderRadius:t.borderRadius,padding:t.paddingSM},onClick:()=>C(M),actions:[r.jsx(Y,{"data-testid":`delete-workflow-${M.name}`,type:"text",danger:!0,size:"small",icon:r.jsx(dn,{}),onClick:T=>{T.stopPropagation(),R(M)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:r.jsxs(X,{direction:"vertical",size:0,children:[r.jsxs(Sl,{strong:!0,children:["/",M.name]}),r.jsx(Sl,{type:"secondary",style:{fontSize:12},children:M.filename})]})})})}),r.jsx("div",{style:{flex:1},children:r.jsxs(X,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(me,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:y,onChange:M=>{f(M.target.value),_(!0)},disabled:!!p,prefix:r.jsx(ca,{})}),r.jsx(s0,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:v,onChange:M=>{b(M.target.value),_(!0)},autoSize:{minRows:12},disabled:c})]})})]})]})]})};var ue=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))(ue||{});const va=6e4,Sa=3e4,aa=2e4,Ci=1e4,Vi=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:aa},request_timeout_ms:va,healthcheck_interval_ms:Sa,allowed_tools:[],denied_tools:[]}),a0=()=>({status:"stopped",tool_count:0,restart_count:0}),i0=e=>{switch(typeof e=="string"?e.trim().toLowerCase():""){case ue.Connecting:return ue.Connecting;case ue.Ready:return ue.Ready;case ue.Degraded:return ue.Degraded;case ue.Error:return ue.Error;case ue.Stopped:default:return ue.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},l0=(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,Ci)}}const n=Array.isArray(s.args)?s.args.filter(a=>typeof a=="string"):[],o=s.env&&typeof s.env=="object"?Object.entries(s.env):[];return{type:"stdio",command:typeof s.command=="string"?s.command:"",args:n,cwd:typeof s.cwd=="string"?s.cwd:void 0,env:o.reduce((a,[i,l])=>(typeof l=="string"&&(a[i]=l),a),{}),startup_timeout_ms:Ns(s.startup_timeout_ms,aa)}},c0=(e,t)=>{const s=Vi(e.id),n=t??{};return{...s,...n,id:e.id,name:typeof n.name=="string"?n.name:typeof e.name=="string"?e.name:void 0,enabled:typeof e.enabled=="boolean"?e.enabled:typeof n.enabled=="boolean"?n.enabled:!0,request_timeout_ms:Ns(n.request_timeout_ms,va),healthcheck_interval_ms:Ns(n.healthcheck_interval_ms,Sa),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:l0(n.transport,s.transport)}},d0=e=>{const t=a0(),n=e.runtime??{},o=n.status??e.status;return{status:i0(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}},u0=e=>{const t=c0(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:d0(e)}},m0=(e,t)=>`mcp__${e}__${t}`,h0=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}},p0=(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"?h0(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?m0(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 f0{async getServers(){const t=await pe.get("mcp/servers");return Array.isArray(t.servers)?t.servers.map(u0):[]}async addServer(t){return pe.post("mcp/servers",t)}async updateServer(t,s){const n={...s,id:t};return pe.put(`mcp/servers/${t}`,n)}async deleteServer(t){return pe.delete(`mcp/servers/${t}`)}async connectServer(t){return pe.post(`mcp/servers/${t}/connect`)}async disconnectServer(t){return pe.post(`mcp/servers/${t}/disconnect`)}async refreshTools(t){return pe.post(`mcp/servers/${t}/refresh`)}async getTools(t){const s=t?`mcp/servers/${t}/tools`:"mcp/tools",n=await pe.get(s);return(Array.isArray(n.tools)?n.tools:[]).map((a,i)=>p0(a,t,i)).filter(a=>!!a)}async importServers(t){return pe.post("mcp/servers/import",t)}}const Py=new f0,g0=5e3,Ls=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,vm=(e,t)=>`${e}:${t}`,y0=(e={})=>{const{service:t=Py,autoRefreshMs:s=g0,autoRefreshEnabled:n=!0}=e,[o,a]=m.useState([]),[i,l]=m.useState(null),[c,d]=m.useState({}),[u,h]=m.useState({}),[p,g]=m.useState({}),[y,f]=m.useState(!1),[v,b]=m.useState(!1),[x,_]=m.useState(!1),[w,k]=m.useState(null),C=m.useRef({}),E=m.useCallback(B=>{const K=new Set(B.map(z=>z.id)),F=B.map(z=>{const Te=C.current[z.id]??z.config,$e={...Te,id:z.id,name:Te.name??z.name};return C.current[z.id]=$e,{...z,name:z.name||$e.name||z.id,enabled:z.enabled??$e.enabled,config:$e}});return Object.keys(C.current).forEach(z=>{K.has(z)||delete C.current[z]}),F},[]),j=m.useCallback(async({silent:B=!1}={})=>{B||f(!0);try{const K=await t.getServers(),F=E(K);a(F),l(z=>{var de;return z&&F.some(Te=>Te.id===z)?z:((de=F[0])==null?void 0:de.id)??null}),k(null)}catch(K){throw k(Ls(K,"Failed to load MCP servers")),K}finally{B||f(!1)}},[E,t]),R=m.useCallback(async(B,K=!1)=>{if(!B)return[];if(!K&&c[B])return c[B];h(F=>({...F,[B]:!0}));try{const F=await t.getTools(B);return d(z=>({...z,[B]:F})),k(null),F}catch(F){throw k(Ls(F,"Failed to load MCP tools")),F}finally{h(F=>({...F,[B]:!1}))}},[t,c]),M=m.useCallback((B,K,F)=>{const z=vm(B,K);g(de=>({...de,[z]:F}))},[]),T=m.useCallback(async B=>{b(!0);try{await t.addServer(B),C.current[B.id]=B,await j()}catch(K){throw k(Ls(K,"Failed to add MCP server")),K}finally{b(!1)}},[j,t]),P=m.useCallback(async(B,K)=>{b(!0);try{const F={...K,id:B};await t.updateServer(B,F),C.current[B]=F,await j()}catch(F){throw k(Ls(F,"Failed to update MCP server")),F}finally{b(!1)}},[j,t]),S=m.useCallback(async B=>{M(B,"delete",!0);try{await t.deleteServer(B),d(K=>{const F={...K};return delete F[B],F}),delete C.current[B],await j()}catch(K){throw k(Ls(K,"Failed to delete MCP server")),K}finally{M(B,"delete",!1)}},[j,t,M]),L=m.useCallback(async B=>{M(B,"connect",!0);try{await t.connectServer(B),await j({silent:!0})}catch(K){throw k(Ls(K,"Failed to connect MCP server")),K}finally{M(B,"connect",!1)}},[j,t,M]),$=m.useCallback(async B=>{M(B,"disconnect",!0);try{await t.disconnectServer(B),await j({silent:!0})}catch(K){throw k(Ls(K,"Failed to disconnect MCP server")),K}finally{M(B,"disconnect",!1)}},[j,t,M]),I=m.useCallback(async B=>{M(B,"refresh",!0);try{await t.refreshTools(B),await R(B,!0),await j({silent:!0})}catch(K){throw k(Ls(K,"Failed to refresh MCP tools")),K}finally{M(B,"refresh",!1)}},[R,j,t,M]),W=m.useCallback(async()=>{_(!0);try{const B=o.map(K=>K.id);await Promise.all(B.map(async K=>{try{await t.refreshTools(K)}catch{}})),await j(),i&&await R(i,!0)}catch(B){throw k(Ls(B,"Failed to refresh MCP status")),B}finally{_(!1)}},[R,j,i,o,t]),A=m.useCallback(B=>{l(B)},[]),O=m.useCallback((B,K)=>!!p[vm(B,K)],[p]),D=m.useMemo(()=>i?c[i]??[]:[],[i,c]),H=m.useMemo(()=>i?!!u[i]:!1,[i,u]);return m.useEffect(()=>{j().catch(()=>{})},[j]),m.useEffect(()=>{if(!n||s<=0)return;const B=window.setInterval(()=>{j({silent:!0}).catch(()=>{})},s);return()=>{window.clearInterval(B)}},[n,s,j]),m.useEffect(()=>{i&&R(i).catch(()=>{})},[R,i]),{servers:o,selectedServerId:i,selectedServerTools:D,isLoadingServers:y,isMutatingConfig:v,isRefreshingAll:x,isSelectedServerToolsLoading:H,error:w,setSelectedServerId:A,refreshServers:j,addServer:T,updateServer:P,deleteServer:S,connectServer:L,disconnectServer:$,refreshServerTools:I,refreshAll:W,isServerActionLoading:O}},b0={[ue.Connecting]:"blue",[ue.Ready]:"green",[ue.Degraded]:"orange",[ue.Stopped]:"default",[ue.Error]:"red"},x0=e=>e===ue.Connecting||e===ue.Ready||e===ue.Degraded,v0=e=>{if(!e)return;const t=e.replace(/\s+/g," ").trim();if(t)return t.length>180?`${t.slice(0,180)}...`:t},S0=({servers:e,loading:t=!1,selectedServerId:s,onSelectServer:n,onEditServer:o,onDeleteServer:a,onConnectServer:i,onDisconnectServer:l,onRefreshTools:c,isServerActionLoading:d})=>{const{t:u}=ne(),{token:h}=he.useToken(),p=m.useMemo(()=>({[ue.Connecting]:u("settings.mcpTab.statusHelp.connecting"),[ue.Ready]:u("settings.mcpTab.statusHelp.ready"),[ue.Degraded]:u("settings.mcpTab.statusHelp.degraded"),[ue.Stopped]:u("settings.mcpTab.statusHelp.stopped"),[ue.Error]:u("settings.mcpTab.statusHelp.error")}),[u]),g=m.useMemo(()=>[{key:"name",title:u("settings.mcpServerTable.columns.name"),render:(y,f)=>f.name||f.id},{key:"transport",title:u("settings.mcpServerTable.columns.transportType"),render:(y,f)=>f.config.transport.type==="sse"?u("settings.mcpServerTable.transportOptions.sse"):u("settings.mcpServerTable.transportOptions.stdio"),width:140},{key:"status",title:u("settings.mcpServerTable.columns.status"),render:(y,f)=>{var w,k;const v=((w=f.runtime)==null?void 0:w.status)??ue.Stopped,b=v0((k=f.runtime)==null?void 0:k.last_error),x=p[v],_={[ue.Connecting]:u("settings.mcpTab.status.connecting"),[ue.Ready]:u("settings.mcpTab.status.ready"),[ue.Degraded]:u("settings.mcpTab.status.degraded"),[ue.Stopped]:u("settings.mcpTab.status.stopped"),[ue.Error]:u("settings.mcpTab.status.error")};return r.jsx(ke,{title:b?`${x} ${u("settings.mcpTab.statusLastError",{error:b})}`:x,children:r.jsx(oe,{color:v===ue.Stopped?void 0:b0[v],style:{marginInlineEnd:0,cursor:"help",...v===ue.Stopped?{background:h.colorFillSecondary,borderColor:h.colorBorderSecondary,color:h.colorTextSecondary}:void 0},children:_[v]})})},width:120},{key:"toolCount",title:u("settings.mcpServerTable.columns.toolCount"),render:(y,f)=>{var v;return((v=f.runtime)==null?void 0:v.tool_count)??0},width:100},{key:"actions",title:u("settings.mcpServerTable.columns.actions"),width:360,render:(y,f)=>{var x;const v=((x=f.runtime)==null?void 0:x.status)??ue.Stopped,b=x0(v);return r.jsxs(X,{size:h.marginXS,children:[r.jsx(Y,{size:"small",onClick:_=>{_.stopPropagation(),o==null||o(f)},children:u("settings.mcpServerTable.actions.edit")}),r.jsx(mi,{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(Y,{size:"small",danger:!0,loading:d==null?void 0:d(f.id,"delete"),onClick:_=>_.stopPropagation(),children:u("settings.mcpServerTable.actions.delete")})}),b?r.jsx(Y,{size:"small",onClick:_=>{_.stopPropagation(),l==null||l(f)},loading:d==null?void 0:d(f.id,"disconnect"),children:u("settings.mcpServerTable.actions.disconnect")}):r.jsx(Y,{size:"small",type:"primary",ghost:!0,onClick:_=>{_.stopPropagation(),i==null||i(f)},loading:d==null?void 0:d(f.id,"connect"),children:u("settings.mcpServerTable.actions.connect")}),r.jsx(Y,{size:"small",onClick:_=>{_.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(qs,{rowKey:"id",columns:g,dataSource:e,loading:t,pagination:!1,locale:{emptyText:u("settings.mcpServerTable.empty")},onRow:y=>({onClick:()=>n==null?void 0:n(y.id),style:{cursor:n?"pointer":"default",backgroundColor:s===y.id?h.colorFillSecondary:void 0}})})},{Text:Sm}=le,{TextArea:w0}=me,wm=e=>{const t=e??Vi(""),s=t.transport,n=s.type==="stdio"?Object.entries(s.env??{}).map(([a,i])=>({key:a,value:i})):[],o=s.type==="sse"?s.headers.map(a=>({name:a.name,value:a.value})):[];return{id:t.id,name:t.name,enabled:t.enabled,transportType:s.type,command:s.type==="stdio"?s.command:void 0,args:s.type==="stdio"?s.args:[],envEntries:n,url:s.type==="sse"?s.url:void 0,headerEntries:o,requestTimeoutMs:t.request_timeout_ms||va,healthcheckIntervalMs:t.healthcheck_interval_ms||Sa,allowedTools:t.allowed_tools||[],deniedTools:t.denied_tools||[]}},_0=e=>e.reduce((t,s)=>{var o;const n=(o=s.key)==null?void 0:o.trim();return n&&(t[n]=s.value??""),t},{}),T0=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??""}}),_m=(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)??va,i=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(s==null?void 0:s.healthcheck_interval_ms)??Sa,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:T0(e.headerEntries||[]),connect_timeout_ms:(s==null?void 0:s.transport.type)==="sse"?s.transport.connect_timeout_ms??Ci:Ci}:{type:"stdio",command:((p=e.command)==null?void 0:p.trim())||"",args:e.args||[],env:_0(e.envEntries||[]),cwd:(s==null?void 0:s.transport.type)==="stdio"?s.transport.cwd:void 0,startup_timeout_ms:(s==null?void 0:s.transport.type)==="stdio"?s.transport.startup_timeout_ms??aa:aa};return{id:n,name:o||void 0,enabled:e.enabled,transport:d,request_timeout_ms:a,healthcheck_interval_ms:i,allowed_tools:l,denied_tools:c,reconnect:s==null?void 0:s.reconnect}},Tm=e=>JSON.stringify(e||Vi(""),null,2),wl=(e,t)=>{try{const s=JSON.parse(e);if(!s||typeof s!="object")return{valid:!1,error:t("settings.mcpServerForm.jsonMustBeObject")};const n=s;if(n.mcpServers&&typeof n.mcpServers=="object")return{valid:!1,error:t("settings.mcpServerForm.detectedBulkConfig")};const o=typeof n.id=="string"?n.id:"";if(!o.trim())return{valid:!1,error:t("settings.mcpServerForm.missingIdField")};if(n.transport&&typeof n.transport=="object"){const h=n;return!h.transport||typeof h.transport!="object"?{valid:!1,error:t("settings.mcpServerForm.missingTransportField")}:{valid:!0,config:h}}const a=typeof n.enabled=="boolean"?n.enabled:typeof n.disabled=="boolean"?!n.disabled:!0,i=typeof n.request_timeout_ms=="number"?n.request_timeout_ms:va,l=typeof n.healthcheck_interval_ms=="number"?n.healthcheck_interval_ms:Sa,c=Array.isArray(n.allowed_tools)?n.allowed_tools.filter(h=>typeof h=="string"):[],d=Array.isArray(n.denied_tools)?n.denied_tools.filter(h=>typeof h=="string"):[],u=typeof n.name=="string"?n.name:void 0;if(typeof n.url=="string"){const h=n.headers,p=Array.isArray(h)?h.map(y=>{if(!y||typeof y!="object")return null;const f=y,v=typeof f.name=="string"?f.name:"",b=typeof f.value=="string"?f.value:"";return v.trim()?{name:v,value:b}:null}).filter(y=>!!y):h&&typeof h=="object"?Object.entries(h).filter(([y])=>y.trim()).map(([y,f])=>({name:y,value:typeof f=="string"?f:""})):[],g=typeof n.connect_timeout_ms=="number"?n.connect_timeout_ms:Ci;return{valid:!0,config:{id:o,name:u,enabled:a,transport:{type:"sse",url:n.url,headers:p,connect_timeout_ms:g},request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:d,reconnect:void 0}}}if(typeof n.command=="string"){const h=Array.isArray(n.args)?n.args.filter(f=>typeof f=="string"):[],p=n.env,g=p&&typeof p=="object"?Object.entries(p).reduce((f,[v,b])=>(typeof b=="string"&&(f[v]=b),f),{}):{},y=typeof n.startup_timeout_ms=="number"?n.startup_timeout_ms:aa;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:g,startup_timeout_ms:y},request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:d,reconnect:void 0}}}return{valid:!1,error:t("settings.mcpServerForm.missingTransportInfo")}}catch(s){return{valid:!1,error:t("settings.mcpServerForm.invalidJson",{message:s instanceof Error?s.message:t("settings.mcpServerForm.unknownError")})}}},k0=({open:e,mode:t,initialConfig:s,confirmLoading:n=!1,onCancel:o,onSubmit:a})=>{const{t:i}=ne(),[l]=Z.useForm(),[c,d]=m.useState("form"),[u,h]=m.useState(""),[p,g]=m.useState(null),y=m.useMemo(()=>wm(s),[s]),f=Z.useWatch("transportType",l)??"stdio";m.useEffect(()=>{e&&(l.setFieldsValue(y),h(Tm(s)),g(null),d("form"))},[l,y,s,e]);const v=()=>{l.resetFields(),h(""),g(null),o()},b=async()=>{if(c==="json"){const w=wl(u,i);if(!w.valid){g(w.error);return}g(null);try{await a(w.config),h("")}catch(k){console.error("MCP server JSON submission error:",k)}return}try{const w=await l.validateFields(),k=_m(w,t,s);await a(k),l.resetFields()}catch(w){console.error("MCP server form submission error:",w)}},x=w=>{h(w),p&&wl(w,i).valid&&g(null)},_=w=>{if(w==="json")try{const k=l.getFieldsValue(),C=_m(k,t,s);h(JSON.stringify(C,null,2))}catch{h(Tm(s))}else{const k=wl(u,i);k.valid&&l.setFieldsValue(wm(k.config))}d(w),g(null)};return r.jsxs(Lt,{title:i(t==="edit"?"settings.mcpServerForm.editTitle":"settings.mcpServerForm.addTitle"),open:e,onCancel:v,onOk:()=>{b()},okText:i("settings.mcpServerForm.save"),destroyOnClose:!0,confirmLoading:n,width:720,children:[r.jsx("div",{style:{marginBottom:16},children:r.jsxs(ts.Group,{value:c,onChange:w=>_(w.target.value),optionType:"button",buttonStyle:"solid",children:[r.jsxs(ts.Button,{value:"form",children:[r.jsx(mx,{})," ",i("settings.mcpServerForm.modeForm")]}),r.jsxs(ts.Button,{value:"json",children:[r.jsx(Li,{})," ",i("settings.mcpServerForm.modeJson")]})]})}),c==="json"&&p&&r.jsx(Xe,{type:"error",message:i("settings.mcpServerForm.jsonError"),description:p,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>g(null)}),c==="json"?r.jsx(w0,{value:u,onChange:w=>x(w.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(Vi("example-server"),null,2)}):r.jsxs(Z,{layout:"vertical",form:l,preserve:!0,initialValues:y,children:[r.jsx(Z.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(me,{placeholder:"filesystem",disabled:t==="edit",autoComplete:"off"})}),r.jsx(Z.Item,{name:"name",label:i("settings.mcpServerForm.displayName"),children:r.jsx(me,{placeholder:"Filesystem MCP",autoComplete:"off"})}),r.jsx(Z.Item,{name:"enabled",label:i("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:i("settings.mcpServerForm.enabledHelp"),children:r.jsx(it,{})}),r.jsx(Z.Item,{name:"transportType",label:i("settings.mcpServerForm.transportType"),rules:[{required:!0,message:i("settings.mcpServerForm.transportTypeRequired")}],children:r.jsx(Pe,{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(Z.Item,{name:"command",label:i("settings.mcpServerForm.command"),rules:[{required:!0,message:i("settings.mcpServerForm.commandRequired")}],children:r.jsx(me,{placeholder:"npx",autoComplete:"off"})}),r.jsx(Z.Item,{name:"args",label:i("settings.mcpServerForm.arguments"),children:r.jsx(Pe,{mode:"tags",tokenSeparators:[","],placeholder:i("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),r.jsx(Z.List,{name:"envEntries",children:(w,{add:k,remove:C})=>r.jsxs(X,{direction:"vertical",style:{width:"100%"},children:[r.jsxs(X,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[r.jsx(Sm,{strong:!0,children:i("settings.mcpServerForm.envVars")}),r.jsx(Y,{icon:r.jsx(Us,{}),onClick:()=>k({key:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addEnv")})]}),w.map(E=>r.jsxs(X,{align:"baseline",style:{display:"flex"},children:[r.jsx(Z.Item,{...E,name:[E.name,"key"],rules:[{required:!0,message:i("settings.mcpServerForm.keyRequired")}],children:r.jsx(me,{placeholder:"MCP_ROOT",autoComplete:"off"})}),r.jsx(Z.Item,{...E,name:[E.name,"value"],children:r.jsx(me,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),r.jsx(Y,{danger:!0,type:"text",icon:r.jsx(nc,{}),onClick:()=>C(E.name),"aria-label":i("settings.mcpServerForm.removeEnv","Remove environment variable")})]},E.key))]})})]}):r.jsxs(r.Fragment,{children:[r.jsx(Z.Item,{name:"url",label:i("settings.mcpServerForm.sseUrl"),rules:[{required:!0,message:i("settings.mcpServerForm.sseUrlRequired")},{validator:async(w,k)=>{if(k)try{new URL(k)}catch{throw new Error(i("settings.mcpServerForm.validUrlRequired"))}}}],children:r.jsx(me,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),r.jsx(Z.List,{name:"headerEntries",children:(w,{add:k,remove:C})=>r.jsxs(X,{direction:"vertical",style:{width:"100%"},children:[r.jsxs(X,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[r.jsx(Sm,{strong:!0,children:i("settings.mcpServerForm.headers")}),r.jsx(Y,{icon:r.jsx(Us,{}),onClick:()=>k({name:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addHeader")})]}),w.map(E=>r.jsxs(X,{align:"baseline",style:{display:"flex"},children:[r.jsx(Z.Item,{...E,name:[E.name,"name"],rules:[{required:!0,message:i("settings.mcpServerForm.headerNameRequired")}],children:r.jsx(me,{placeholder:"Authorization",autoComplete:"off"})}),r.jsx(Z.Item,{...E,name:[E.name,"value"],children:r.jsx(me,{placeholder:"Bearer token",autoComplete:"off"})}),r.jsx(Y,{danger:!0,type:"text",icon:r.jsx(nc,{}),onClick:()=>C(E.name),"aria-label":i("settings.mcpServerForm.removeHeader","Remove header")})]},E.key))]})})]})]})]})},j0={maxLines:8,maxCharacters:500},on=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Zs=e=>typeof e=="string"?e:void 0,Mn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,km=e=>typeof e=="boolean"?e:void 0,Xd=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const s=JSON.parse(t);return on(s)?s:null}catch{return null}},Ey=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,js=e=>Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>Ey(t).trim()).filter(Boolean):[],gt=e=>{if(typeof e!="string")return;const t=Ey(e).trim();return t.length>0?t:void 0},C0=e=>{if(!on(e))return;const t=gt(e.graph);if(t)return{title:gt(e.title),graph:t}},M0=e=>{if(!on(e))return;const t=gt(e.summary)??gt(e.conclusion);if(t)return{title:gt(e.title)||"Conclusion",summary:t,key_points:js(e.key_points),next_steps:js(e.next_steps),confidence:gt(e.confidence),mermaid:C0(e.mermaid)}},P0=e=>{const t=Xd(e);if(!t)return null;const s=gt(t.conclusion);return!s||t.type!=null&&t.type!=="conclusion"?null:{type:"conclusion",title:gt(t.title)||"Conclusion",conclusion:s,key_points:js(t.key_points),next_steps:js(t.next_steps),confidence:gt(t.confidence)}},E0=e=>{const t=Xd(e);if(!t)return null;const s=gt(t.question);if(!s)return null;const n=gt(t.status);return n&&n!=="awaiting_user_input"&&n!=="awaiting_permission_approval"?null:{question:s,options:js(t.options),allow_custom:typeof t.allow_custom=="boolean"?t.allow_custom:!0,conclusion:M0(t.conclusion)}},R0=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
|
+
`)},Ry=e=>{const t=P0(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
|
+
`)},wa=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const s=JSON.parse(t);if(!on(s))return null;const n=Zs(s.file_path),o=Zs(s.operation),a=s.diff;if(!n||!o||!on(a))return null;const i=Zs(a.unified);if(!i)return null;const l=s.checkpoint,c=on(l)?{created:km(l.created)??!1,id:Zs(l.id),path:Zs(l.path),size_bytes:Mn(l.size_bytes),reason:Zs(l.reason)}:void 0;return{operation:o,message:Zs(s.message),file_path:n,workspace:Zs(s.workspace),checkpoint:c,diff:{unified:i,old_line_count:Mn(a.old_line_count),new_line_count:Mn(a.new_line_count),added_lines:Mn(a.added_lines),removed_lines:Mn(a.removed_lines),truncated:km(a.truncated)}}}catch{return null}},Ay=e=>{const t=Xd(e);if(!t)return null;const s=gt(t.action);if(s!=="inspect"&&s!=="rebuild")return null;const n=t.data;if(!on(n))return null;const o=gt(n.scope),a=Mn(n.total_memories);if(!o||typeof a!="number")return null;const i=l=>on(l)?Object.fromEntries(Object.entries(l).filter(c=>typeof c[0]=="string"&&typeof c[1]=="number")):{};return{action:s,scope:gt(t.scope),project_key:gt(t.project_key),data:{scope:o,project_key:gt(n.project_key),total_memories:a,by_type:i(n.by_type),by_status:i(n.by_status),recent_ids:js(n.recent_ids),view_files:js(n.view_files),index_files:js(n.index_files),state_files:js(n.state_files),stale_candidate_count:Mn(n.stale_candidate_count)??0,last_reindex_at:gt(n.last_reindex_at),last_dream_at:gt(n.last_dream_at),topic_paths:js(n.topic_paths)}}},Ic=e=>e.startsWith("-")&&!e.startsWith("---"),$c=e=>e.startsWith("+")&&!e.startsWith("+++"),Iy=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(Ic(o)){const a=[];for(;n<t.length&&Ic(t[n]??"");)a.push(t[n]??""),n+=1;const i=[];for(;n<t.length&&$c(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($c(o)){s.push({kind:"add",text:o}),n+=1;continue}s.push({kind:"context",text:o}),n+=1}return s},A0=e=>{let t=0,s=0;for(const n of e.split(`
|
|
129
|
+
`)){if($c(n)){t+=1;continue}Ic(n)&&(s+=1)}return{added:t,removed:s}},Dc=e=>{const t=wa(e);if(!t)return null;const s=A0(t.diff.unified);return{added:t.diff.added_lines??s.added,removed:t.diff.removed_lines??s.removed}},Lc=e=>{if(typeof e=="string")return e.replace(/\\n/g,`
|
|
130
|
+
`).replace(/\\t/g," ");if(Array.isArray(e))return e.map(Lc);if(e!==null&&typeof e=="object"){const t={};for(const[s,n]of Object.entries(e))t[s]=Lc(n);return t}return e},Oc=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=Lc(s);return{isJson:!0,formattedText:JSON.stringify(n,null,2),parsedJson:n}}catch{return{isJson:!1,formattedText:e}}},I0=(e,t={})=>{const s={...j0,...t};return e?e.split(/\r?\n/).length>s.maxLines?!0:e.length>s.maxCharacters:!1},$0=(e,t=320)=>e?e.length<=t?{preview:e,isTruncated:!1}:{preview:e.substring(0,t).trimEnd()+"…",isTruncated:!0}:{preview:"",isTruncated:!1},D0=e=>{if(!e)return"No content";const t=60,s=e.trim(),n=wa(s);if(n){const a=n.file_path.split(/[\\/]/).pop()||n.file_path,i=`${n.operation}: ${a}`;return i.length<=t?i:i.substring(0,t).trimEnd()+"…"}const o=Ay(s);if(o){const a=o.data.project_key||o.data.scope,i=`Memory ${o.action}: ${a} (${o.data.total_memories})`;return i.length<=t?i:i.substring(0,t).trimEnd()+"…"}if(s.length<=t)return s;if(s.startsWith("{")||s.startsWith("["))try{const a=JSON.parse(s);if(typeof a=="object"&&a!==null){if(a.type==="mermaid"&&typeof a.chart=="string"&&a.chart.trim().length>0){const d=`Diagram: ${typeof a.title=="string"&&a.title.trim().length>0?a.title.trim():"Mermaid diagram"}`;return d.length<=t?d:d.substring(0,t).trimEnd()+"…"}if(a.type==="conclusion"&&typeof a.conclusion=="string"&&a.conclusion.trim().length>0){const c=a.conclusion.trim();return c.length<=t?c:c.substring(0,t).trimEnd()+"…"}const i=["content","result","output","message","data"].find(c=>c in a&&typeof a[c]=="string");if(i){const c=a[i];return c.length<=t?c:c.substring(0,t).trimEnd()+"…"}if(Array.isArray(a))return`Array with ${a.length} items`;const l=Object.keys(a);return`Object with ${l.length} propert${l.length===1?"y":"ies"}`}}catch{}return s.substring(0,t).trimEnd()+"…"},$y=e=>{switch(e){case"success":return"green";case"error":return"red";case"warning":return"orange";default:return"blue"}},xr=(e,t=2)=>{if(typeof e=="string")return e;try{return JSON.stringify(e,null,t)}catch(s){return console.error("[resultFormatters] Failed to stringify value:",s),String(e)}},ii=e=>!!e&&typeof e=="object"&&!Array.isArray(e),vn=(e,t)=>{const s=e[t];return typeof s=="string"?s:void 0},jm=(e,t)=>{const s=e[t];return typeof s=="boolean"?s:void 0},L0=(e,t)=>{const s=e[t];return Array.isArray(s)?s:void 0},Vo=e=>{if(!ii(e))return"any";const t=e.type;if(typeof t=="string"){if(t==="array"){const a=e.items;return`array<${Vo(a)}>`}return t==="object"?"object":t}if(Array.isArray(t)){const a=t.filter(i=>typeof i=="string").map(i=>i==="array"?"array<any>":i);return a.length>0?a.join(" | "):"any"}const s=Array.isArray(e.oneOf)?e.oneOf:null;if(s)return s.map(Vo).join(" | ")||"any";const n=Array.isArray(e.anyOf)?e.anyOf:null;if(n)return n.map(Vo).join(" | ")||"any";const o=Array.isArray(e.allOf)?e.allOf:null;return o&&o.map(Vo).join(" & ")||"any"},O0=e=>{if(!ii(e))return null;const t=e.properties;if(!ii(t))return{schemaUri:vn(e,"$schema"),title:vn(e,"title"),description:vn(e,"description"),additionalProperties:jm(e,"additionalProperties"),fields:[]};const s=new Set((L0(e,"required")??[]).filter(o=>typeof o=="string").map(o=>o)),n=Object.entries(t).map(([o,a])=>{const i=ii(a)?a:void 0;return{name:o,type:Vo(a),required:s.has(o),description:i?vn(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:vn(e,"$schema"),title:vn(e,"title"),description:vn(e,"description"),additionalProperties:jm(e,"additionalProperties"),fields:n}},{Text:Ss}=le,F0=e=>e===void 0?"":e===null?"null":typeof e=="string"?e:xr(e,0),z0=({schema:e})=>{const{token:t}=he.useToken(),{t:s}=ne(),n=m.useMemo(()=>O0(e),[e]);if(!n)return r.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:xr(e,2)});const o=[{title:s("components.jsonSchema.field"),dataIndex:"name",key:"name",width:180,render:i=>r.jsx(Ss,{code:!0,children:i})},{title:s("components.jsonSchema.type"),dataIndex:"type",key:"type",width:140,render:i=>r.jsx(Ss,{children:i})},{title:s("components.jsonSchema.required"),dataIndex:"required",key:"required",width:110,render:i=>i?r.jsx(Ss,{strong:!0,style:{color:t.colorError},children:s("components.jsonSchema.yes")}):r.jsx(Ss,{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(Ss,{type:"secondary",children:"-"}):r.jsx(Ss,{children:F0(i)})},{title:s("components.jsonSchema.description"),dataIndex:"description",key:"description",render:i=>i?r.jsx(Ss,{style:{whiteSpace:"pre-wrap"},children:i}):r.jsx(Ss,{type:"secondary",children:"-"})}],a=(n.fields??[]).map(i=>({...i,key:i.name}));return r.jsxs("div",{style:{width:"100%"},children:[r.jsx(Pt,{size:"small",column:1,items:[n.schemaUri?{key:"schema",label:"$schema",children:r.jsx(Ss,{code:!0,children:n.schemaUri})}:null,typeof n.additionalProperties=="boolean"?{key:"additionalProperties",label:"additionalProperties",children:r.jsx(Ss,{children:n.additionalProperties?"true":"false"})}:null].filter(Boolean)}),r.jsx(qs,{size:"small",pagination:!1,columns:o,dataSource:a,locale:{emptyText:s("components.jsonSchema.noProperties")},style:{marginTop:t.marginSM}})]})},{Text:zr}=le,N0=(e,t)=>`mcp__${e}__${t}`,B0=({server:e,tools:t,loading:s=!1})=>{const{t:n}=ne();return r.jsx(ee,{title:n("settings.mcpToolList.title"),size:"small",children:e?r.jsx(nt,{loading:s,dataSource:t,locale:{emptyText:n("settings.mcpToolList.empty")},renderItem:o=>{const a=N0(o.server_id,o.original_name);return r.jsx(nt.Item,{children:r.jsxs(X,{direction:"vertical",size:2,style:{width:"100%"},children:[r.jsx(zr,{strong:!0,children:o.original_name}),r.jsx(zr,{type:"secondary",children:o.description||n("settings.mcpToolList.noDescription")}),r.jsx(zr,{code:!0,children:o.alias}),r.jsxs(zr,{type:"secondary",children:[n("settings.mcpToolList.aliasMapping"),": ",r.jsx(zr,{code:!0,children:a})]}),o.parameters!==void 0&&r.jsx(ns,{size:"small",items:[{key:"schema",label:n("settings.mcpToolList.parametersSchema"),children:r.jsx(z0,{schema:o.parameters})}]})]})})}}):r.jsx(kt,{image:kt.PRESENTED_IMAGE_SIMPLE,description:n("settings.mcpToolList.selectServerHint")})})},{Text:Nr}=le,{useToken:W0}=he,{TextArea:U0}=me,Cm={[ue.Connecting]:"processing",[ue.Ready]:"success",[ue.Degraded]:"warning",[ue.Stopped]:"default",[ue.Error]:"error"},q0=()=>({[ue.Connecting]:0,[ue.Ready]:0,[ue.Degraded]:0,[ue.Stopped]:0,[ue.Error]:0}),Sn=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,H0=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 g of d.headers??[]){const y=(n=g.name)==null?void 0:n.trim();y&&(h[y]=g.value??"")}const p={url:d.url};c&&(p.disabled=!0),Object.keys(h).length&&(p.headers=h),t[i]=p;continue}const u={command:d.command};c&&(u.disabled=!0),(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}},Y0=()=>{const{t:e}=ne(),{token:t}=W0(),[s,n]=fe.useMessage(),{servers:o,selectedServerId:a,selectedServerTools:i,isLoadingServers:l,isMutatingConfig:c,isRefreshingAll:d,isSelectedServerToolsLoading:u,error:h,setSelectedServerId:p,addServer:g,updateServer:y,deleteServer:f,connectServer:v,disconnectServer:b,refreshServerTools:x,refreshAll:_,isServerActionLoading:w}=y0(),k=m.useMemo(()=>({[ue.Connecting]:e("settings.mcpTab.status.connecting"),[ue.Ready]:e("settings.mcpTab.status.ready"),[ue.Degraded]:e("settings.mcpTab.status.degraded"),[ue.Stopped]:e("settings.mcpTab.status.stopped"),[ue.Error]:e("settings.mcpTab.status.error")}),[e]),C=m.useMemo(()=>({[ue.Connecting]:e("settings.mcpTab.statusHelp.connecting"),[ue.Ready]:e("settings.mcpTab.statusHelp.ready"),[ue.Degraded]:e("settings.mcpTab.statusHelp.degraded"),[ue.Stopped]:e("settings.mcpTab.statusHelp.stopped"),[ue.Error]:e("settings.mcpTab.statusHelp.error")}),[e]),[E,j]=m.useState(!1),[R,M]=m.useState("create"),[T,P]=m.useState(null),[S,L]=m.useState(!1),[$,I]=m.useState("merge"),[W,A]=m.useState(""),[O,D]=m.useState(null),[H,B]=m.useState(!1),K=m.useMemo(()=>a?o.find(U=>U.id===a)??null:null,[a,o]),F=m.useMemo(()=>{const U=q0();let _e=0;return o.forEach(Ce=>{var qe,J;const Ve=((qe=Ce.runtime)==null?void 0:qe.status)??ue.Stopped;U[Ve]+=1,_e+=((J=Ce.runtime)==null?void 0:J.tool_count)??0}),{byStatus:U,totalServers:o.length,totalTools:_e}},[o]),z={background:t.colorFillSecondary,borderColor:t.colorBorderSecondary,color:t.colorTextSecondary},de=async U=>{try{await f(U.id),s.success(e("settings.mcpTab.serverDeleted"))}catch(_e){s.error(Sn(_e,e("settings.mcpTab.deleteServerFailed")))}},Te=async U=>{try{await v(U.id),s.success(e("settings.mcpTab.connectedTo",{name:U.name||U.id}))}catch(_e){s.error(Sn(_e,e("settings.mcpTab.connectServerFailed")))}},$e=async U=>{try{await b(U.id),s.success(e("settings.mcpTab.disconnected",{name:U.name||U.id}))}catch(_e){s.error(Sn(_e,e("settings.mcpTab.disconnectServerFailed")))}},De=async U=>{try{await x(U.id),s.success(e("settings.mcpTab.toolsRefreshedFor",{name:U.name||U.id}))}catch(_e){s.error(Sn(_e,e("settings.mcpTab.refreshToolsFailed")))}},be=async()=>{try{await _(),s.success(e("settings.mcpTab.statusRefreshed"))}catch(U){s.error(Sn(U,e("settings.mcpTab.refreshStatusFailed")))}},ye=()=>{P(null),M("create"),j(!0)},je=U=>{P(U),M("edit"),j(!0)},Ue=async U=>{try{if(R==="edit"){if(!T){s.error(e("settings.mcpTab.noServerForEditing"));return}await y(T.id,U),s.success(e("settings.mcpTab.savedServer",{name:T.name||T.id}))}else await g(U),s.success(e("settings.mcpTab.addedServer",{name:U.name||U.id}));j(!1),P(null)}catch(_e){s.error(Sn(_e,e("settings.mcpTab.saveServerFailed")))}},ht=()=>{L(!0),D(null),I("merge"),A("")},Ge=async()=>{const U=H0(o),_e=JSON.stringify(U,null,2);try{await os(_e),s.success(e("settings.mcpTab.copiedConfig"))}catch{L(!0),D(null),I("merge"),A(_e),s.warning(e("settings.mcpTab.clipboardUnavailable"))}},wt=async()=>{var Ve;D(null);let U;try{U=JSON.parse(W)}catch(qe){D(`${e("settings.mcpTab.invalidJsonPrefix")}: ${qe instanceof Error?qe.message:e("settings.mcpTab.unknownError")}`);return}if(!U||typeof U!="object"){D(e("settings.mcpTab.jsonMustBeObject"));return}const Ce=U.mcpServers;if(!Ce||typeof Ce!="object"){D(e("settings.mcpTab.missingMcpServers"));return}B(!0);try{const qe=await Py.importServers({mcpServers:Ce,mode:$}),J=((Ve=qe.start_errors)==null?void 0:Ve.length)??0;s.success(e("settings.mcpTab.importSummary",{count:qe.server_ids.length,added:qe.added,updated:qe.updated,removed:qe.removed,failed:J})),J&&s.warning(e("settings.mcpTab.importStartFailures")),L(!1),A(""),await be()}catch(qe){D(Sn(qe,e("settings.mcpTab.importFailed")))}finally{B(!1)}};return r.jsxs(X,{direction:"vertical",size:t.marginMD,style:{width:"100%"},children:[n,h?r.jsx(Xe,{type:"error",showIcon:!0,message:h}):null,r.jsx(ee,{size:"small",title:e("settings.mcpTab.overviewTitle"),children:r.jsxs(X,{direction:"vertical",size:t.marginXS,style:{width:"100%"},children:[r.jsx(Nr,{type:"secondary",children:e("settings.mcpTab.overviewDescription")}),r.jsxs(X,{wrap:!0,children:[r.jsx(oe,{style:z,children:e("settings.mcpTab.totalServers",{count:F.totalServers})}),r.jsx(oe,{style:z,children:e("settings.mcpTab.totalTools",{count:F.totalTools})}),Object.values(ue).map(U=>r.jsx(ke,{title:C[U],children:r.jsxs(oe,{color:U===ue.Stopped?void 0:Cm[U],style:{cursor:"help",...U===ue.Stopped?z:void 0},children:[k[U],": ",F.byStatus[U]]})},U))]}),r.jsx(Nr,{type:"secondary",children:e("settings.mcpTab.statusGuideTitle")}),r.jsx(X,{direction:"vertical",size:2,style:{width:"100%"},children:Object.values(ue).map(U=>r.jsxs(Nr,{type:"secondary",children:[r.jsx(oe,{color:U===ue.Stopped?void 0:Cm[U],style:{marginInlineEnd:8,...U===ue.Stopped?z:void 0},children:k[U]}),C[U]]},`guide-${U}`))})]})}),r.jsx(ee,{size:"small",title:e("settings.mcpTab.serversTitle"),extra:r.jsxs(X,{children:[r.jsx(Y,{type:"primary",onClick:ye,children:e("settings.mcpTab.addServer")}),r.jsx(Y,{icon:r.jsx(Ms,{}),loading:d,onClick:()=>{be()},children:e("settings.mcpTab.refreshAll")}),r.jsx(Y,{icon:r.jsx(ss,{}),onClick:()=>void Ge(),children:e("settings.mcpTab.export")}),r.jsx(Y,{icon:r.jsx(hx,{}),onClick:ht,children:e("settings.mcpTab.import")})]}),children:r.jsx(S0,{servers:o,loading:l,selectedServerId:a,onSelectServer:p,onEditServer:je,onDeleteServer:de,onConnectServer:Te,onDisconnectServer:$e,onRefreshTools:De,isServerActionLoading:w})}),r.jsx(B0,{server:K,tools:i,loading:u}),r.jsx(k0,{open:E,mode:R,initialConfig:(T==null?void 0:T.config)??null,confirmLoading:c,onCancel:()=>{c||(j(!1),P(null))},onSubmit:U=>void Ue(U)}),r.jsx(Lt,{open:S,title:e("settings.mcpTab.importModalTitle"),okText:e("settings.mcpTab.import"),onOk:()=>void wt(),okButtonProps:{loading:H},onCancel:()=>{H||(L(!1),D(null))},width:800,destroyOnClose:!1,children:r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:"middle",children:[r.jsxs(Nr,{type:"secondary",children:[e("settings.mcpTab.importHint"),r.jsx("br",{}),r.jsx(Nr,{code:!0,children:'{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "..."] } } }'})]}),r.jsxs(ts.Group,{value:$,onChange:U=>I(U.target.value),optionType:"button",buttonStyle:"solid",children:[r.jsx(ts.Button,{value:"merge",children:e("settings.mcpTab.importModeMerge")}),r.jsx(ts.Button,{value:"replace",children:e("settings.mcpTab.importModeReplace")})]}),$==="replace"?r.jsx(Xe,{type:"warning",showIcon:!0,message:e("settings.mcpTab.replaceWarning")}):null,O?r.jsx(Xe,{type:"error",showIcon:!0,message:O}):null,r.jsx(U0,{value:W,onChange:U=>A(U.target.value),rows:14,placeholder:'{"mcpServers": { "filesystem": { "command": "...", "args": [], "env": {} } }}',spellCheck:!1})]})})]})},Ht=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 X0{async getSummary(t={}){const s=Ht({start_date:t.startDate,end_date:t.endDate});return pe.get(`metrics/summary${s}`)}async getByModel(t={}){const s=Ht({start_date:t.startDate,end_date:t.endDate});return pe.get(`metrics/by-model${s}`)}async getSessions(t={}){const s=Ht({start_date:t.startDate,end_date:t.endDate,model:t.model,limit:t.limit});return pe.get(`metrics/sessions${s}`)}async getSessionDetail(t){try{return await pe.get(`metrics/sessions/${encodeURIComponent(t)}`)}catch(s){if(s instanceof Error&&s.message.includes("not found"))return null;throw s}}async getUsageBreakdown(t={}){const s=Ht({start_date:t.startDate,end_date:t.endDate,model:t.model});return pe.get(`metrics/usage-breakdown${s}`)}async getDaily(t={}){const s=Ht({days:t.days,end_date:t.endDate,granularity:t.granularity});return pe.get(`metrics/daily${s}`)}async getForwardSummary(t={}){const s=Ht({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return pe.get(`metrics/forward/summary${s}`)}async getForwardByEndpoint(t={}){const s=Ht({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return pe.get(`metrics/forward/by-endpoint${s}`)}async getForwardRequests(t={}){const s=Ht({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return pe.get(`metrics/forward/requests${s}`)}async getMemorySummary(t={}){const s=Ht({scope:t.scope,project_key:t.projectKey});return pe.get(`metrics/memory/summary${s}`)}async getMemoryTimeline(t={}){const s=Ht({scope:t.scope,project_key:t.projectKey,days:t.days,end_date:t.endDate,granularity:t.granularity});return pe.get(`metrics/memory/timeline${s}`)}async getUnifiedSummary(t={}){const s=Ht({start_date:t.startDate,end_date:t.endDate});return pe.get(`metrics/v2/summary${s}`)}async getUnifiedTimeline(t={}){const s=Ht({days:t.days,end_date:t.endDate,granularity:t.granularity});return pe.get(`metrics/v2/timeline${s}`)}}const Zo=new X0,Dy=1,V0=365,Ly=e=>Number.isFinite(e)?Math.min(V0,Math.max(Dy,Math.floor(e??30))):30,_l=e=>{if(!e)return null;const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const s=Number(t[1]),n=Number(t[2]),o=Number(t[3]),a=new Date(Date.UTC(s,n-1,o));return a.getUTCFullYear()!==s||a.getUTCMonth()!==n-1||a.getUTCDate()!==o?null:a},Br=e=>e.toISOString().slice(0,10),K0=(e,t)=>{const s=new Date(e.getTime());return s.setUTCDate(s.getUTCDate()+t),s},G0=(e,t)=>{const s=t.getTime()-e.getTime(),n=Math.floor(s/864e5)+1;return Ly(n)},Vd=(e,t=new Date)=>{const s=Ly(e.days),n=Br(t),o=_l(e.endDate)??_l(n);if(!o)return{startDate:n,endDate:n,days:Dy};const a=_l(e.startDate);if(a){const l=o<a?a:o;return{startDate:Br(a),endDate:Br(l),days:G0(a,l)}}const i=K0(o,-(s-1));return{startDate:Br(i),endDate:Br(o),days:s}},J0=15e3,Q0=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,Z0=(e={})=>{const{filters:t,autoRefreshMs:s=J0}=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(()=>Vd({startDate:n.startDate,endDate:n.endDate,days:n.days}),[n.days,n.endDate,n.startDate]),[a,i]=m.useState(null),[l,c]=m.useState([]),[d,u]=m.useState([]),[h,p]=m.useState(!1),[g,y]=m.useState(!1),[f,v]=m.useState(null),b=m.useCallback(async _=>{_?p(!0):y(!0);try{const w={startDate:o.startDate,endDate:o.endDate,endpoint:n.endpoint,model:n.model,limit:n.limit},[k,C,E]=await Promise.all([Zo.getForwardSummary(w),Zo.getForwardByEndpoint(w),Zo.getForwardRequests(w)]);i(k),c(C),u(E),v(null)}catch(w){v(Q0(w,"Failed to load forward metrics"))}finally{_?p(!1):y(!1)}},[n.endpoint,n.model,n.limit,o.endDate,o.startDate]),x=m.useCallback(async()=>{await b(!1)},[b]);return m.useEffect(()=>{b(!0)},[b]),m.useEffect(()=>{if(s<=0)return;const _=window.setInterval(()=>{b(!1)},s);return()=>{window.clearInterval(_)}},[s,b]),{summary:a,endpointMetrics:l,requests:d,isLoading:h,isRefreshing:g,error:f,refresh:x}},eT=15e3,Mm=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,tT=(e={})=>{const{filters:t,autoRefreshMs:s=eT,service:n=Zo}=e,o=m.useMemo(()=>({startDate:t==null?void 0:t.startDate,endDate:t==null?void 0:t.endDate,model:t==null?void 0:t.model,days:(t==null?void 0:t.days)??30,granularity:(t==null?void 0:t.granularity)??"daily",sessionLimit:(t==null?void 0:t.sessionLimit)??200}),[t==null?void 0:t.startDate,t==null?void 0:t.endDate,t==null?void 0:t.model,t==null?void 0:t.days,t==null?void 0:t.granularity,t==null?void 0:t.sessionLimit]),a=m.useMemo(()=>Vd({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,g]=m.useState([]),[y,f]=m.useState(null),[v,b]=m.useState([]),[x,_]=m.useState(null),[w,k]=m.useState(!1),[C,E]=m.useState(!1),[j,R]=m.useState(!1),[M,T]=m.useState(null),P=m.useCallback(async I=>{I?E(!0):R(!0);try{const W=n.getMemorySummary?n.getMemorySummary().catch(()=>null):Promise.resolve(null),A=n.getMemoryTimeline?n.getMemoryTimeline({days:a.days,endDate:a.endDate,granularity:o.granularity}).catch(()=>[]):Promise.resolve([]),[O,D,H,B,K,F]=await Promise.all([n.getSummary({startDate:a.startDate,endDate:a.endDate}),n.getByModel({startDate:a.startDate,endDate:a.endDate}),n.getSessions({startDate:a.startDate,endDate:a.endDate,model:o.model,limit:o.sessionLimit}),n.getDaily({days:a.days,endDate:a.endDate,granularity:o.granularity}),W,A]);l(O),d(D),h(H),g(B),f(K),b(F),T(null)}catch(W){T(Mm(W,"Failed to load metrics"))}finally{I?E(!1):R(!1)}},[o.granularity,o.model,o.sessionLimit,a.days,a.endDate,a.startDate,n]),S=m.useCallback(async()=>{await P(!1)},[P]),L=m.useCallback(async I=>{k(!0);try{const W=await n.getSessionDetail(I);_(W)}catch(W){T(Mm(W,"Failed to load session detail"))}finally{k(!1)}},[n]),$=m.useCallback(()=>{_(null)},[]);return m.useEffect(()=>{P(!0)},[P]),m.useEffect(()=>{if(s<=0)return;const I=window.setInterval(()=>{P(!1)},s);return()=>{window.clearInterval(I)}},[s,P]),{summary:i,modelMetrics:c,sessions:u,timeline:p,memorySummary:y,memoryTimeline:v,sessionDetail:x,isLoading:C,isRefreshing:j,isSessionDetailLoading:w,error:M,refresh:S,loadSessionDetail:L,clearSessionDetail:$}},sT=15e3,nT=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,rT=(e={})=>{const{filters:t,autoRefreshMs:s=sT}=e,n=m.useMemo(()=>({startDate:t==null?void 0:t.startDate,endDate:t==null?void 0:t.endDate,days:(t==null?void 0:t.days)??30,model:t==null?void 0:t.model}),[t==null?void 0:t.days,t==null?void 0:t.endDate,t==null?void 0:t.model,t==null?void 0:t.startDate]),o=m.useMemo(()=>Vd({startDate:n.startDate,endDate:n.endDate,days:n.days}),[n.days,n.endDate,n.startDate]),[a,i]=m.useState(null),[l,c]=m.useState(!1),[d,u]=m.useState(!1),[h,p]=m.useState(null),g=m.useCallback(async f=>{f?c(!0):u(!0);try{const v=await Zo.getUsageBreakdown({startDate:o.startDate,endDate:o.endDate,model:n.model});i(v),p(null)}catch(v){p(nT(v,"Failed to load usage breakdown"))}finally{f?c(!1):u(!1)}},[n.model,o.endDate,o.startDate]),y=m.useCallback(async()=>{await g(!1)},[g]);return m.useEffect(()=>{g(!0)},[g]),m.useEffect(()=>{if(s<=0)return;const f=window.setInterval(()=>{g(!1)},s);return()=>{window.clearInterval(f)}},[s,g]),{data:a,isLoading:l,isRefreshing:d,error:h,refresh:y}},{useToken:oT}=he,aT=({data:e,loading:t})=>{const{t:s}=ne(),{token:n}=oT();if(t)return r.jsx(ee,{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(ee,{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(ee,{size:"small",className:"lotus-metric-card",title:s("settings.charts.endpointDistribution"),children:r.jsx("div",{style:{width:"100%",height:240},children:r.jsx(_r,{children:r.jsxs(cd,{data:o,children:[r.jsx(ma,{strokeDasharray:"3 3"}),r.jsx(ha,{dataKey:"endpoint"}),r.jsx(pa,{}),r.jsx(Tr,{formatter:(a,i)=>[`${a}`,i.charAt(0).toUpperCase()+i.slice(1)]}),r.jsx(dd,{}),r.jsx(fi,{dataKey:"successful",fill:"var(--lotus-chart-secondary)",name:s("settings.common.successful"),fillOpacity:.9,radius:[4,4,0,0]}),r.jsx(fi,{dataKey:"failed",fill:"var(--lotus-chart-danger)",name:s("settings.common.failed"),fillOpacity:.9,radius:[4,4,0,0]})]})})})})},{useToken:iT}=he,lT=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`},Pm=({summary:e,loading:t})=>{const{t:s}=ne(),{token:n}=iT();if(t)return r.jsx(Xs,{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(Gt,{gutter:[n.marginSM,n.marginSM],children:[r.jsx(Oe,{xs:24,sm:12,xl:6,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(ot,{title:s("settings.forwardMetricsCards.totalForwardRequests"),value:(e==null?void 0:e.total_requests)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),r.jsx(Oe,{xs:24,sm:12,xl:6,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(ot,{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(Oe,{xs:24,sm:12,xl:6,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(ot,{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(Oe,{xs:24,sm:12,xl:6,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(ot,{title:s("settings.forwardMetricsCards.avgResponseTime"),value:lT(e==null?void 0:e.avg_duration_ms),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:wn}=le,cT=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`},dT=e=>new Date(e).toLocaleString(),uT=({requests:e,loading:t})=>{const{t:s}=ne(),n=[{title:s("settings.metricsTable.forward.columns.id"),dataIndex:"forward_id",key:"forward_id",width:120,render:o=>r.jsxs(wn,{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(oe,{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(oe,{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(rd,{status:i,text:a.status_code?r.jsxs("span",{children:[a.status,r.jsxs(wn,{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(wn,{children:a.token_usage.total_tokens.toLocaleString()}):r.jsx(wn,{type:"secondary",children:"-"})},{title:s("settings.metricsTable.forward.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",width:100,render:o=>cT(o)},{title:s("settings.metricsTable.forward.columns.started"),dataIndex:"started_at",key:"started_at",width:160,render:o=>r.jsx(wn,{type:"secondary",style:{fontSize:12},children:dT(o)})},{title:s("settings.metricsTable.forward.columns.error"),dataIndex:"error",key:"error",width:200,render:o=>o?r.jsx(wn,{type:"danger",ellipsis:!0,style:{maxWidth:180},children:o}):r.jsx(wn,{type:"secondary",children:"-"})}];return r.jsx(qs,{rowKey:"forward_id",className:"lotus-metric-table",columns:n,dataSource:e,loading:t,size:"small",pagination:{pageSize:10,showSizeChanger:!0,showTotal:o=>s("settings.metricsTable.forward.totalRequests",{total:o}),pageSizeOptions:["10","20","50","100"]},scroll:{x:1200},locale:{emptyText:s("settings.metricsTable.forward.empty")}})},{useToken:mT}=he,hT=e=>{if(!e)return"-";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},Em=({summary:e,loading:t})=>{const{t:s}=ne(),{token:n}=mT();return t?r.jsx(Xs,{active:!0,paragraph:{rows:1}}):r.jsxs(Gt,{gutter:[n.marginSM,n.marginSM],children:[r.jsx(Oe,{xs:24,sm:12,lg:8,xl:6,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(ot,{title:s("settings.unifiedMetricsCards.totalMemories"),value:(e==null?void 0:e.total_memories)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),r.jsx(Oe,{xs:24,sm:12,lg:8,xl:6,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(ot,{title:s("settings.unifiedMetricsCards.staleCandidates"),value:(e==null?void 0:e.stale_candidate_count)??0,precision:0,valueStyle:{color:((e==null?void 0:e.stale_candidate_count)??0)>0?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)"}})})}),r.jsx(Oe,{xs:24,sm:12,lg:8,xl:6,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(ot,{title:s("settings.unifiedMetricsCards.memoryProjects"),value:(e==null?void 0:e.project_count)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),r.jsx(Oe,{xs:24,sm:12,lg:8,xl:6,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(ot,{title:s("settings.unifiedMetricsCards.lastReindex"),value:hT(e==null?void 0:e.last_reindex_at),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:pT}=le,fT=({data:e,loading:t})=>{const{t:s}=ne();return t?r.jsx(ee,{size:"small",className:"lotus-metric-card",title:s("settings.charts.memoryTrendTitle"),children:r.jsx(Xs,{active:!0,paragraph:{rows:5}})}):r.jsx(ee,{size:"small",className:"lotus-metric-card",title:s("settings.charts.memoryTrendTitle"),children:e.length===0?r.jsx(kt,{image:kt.PRESENTED_IMAGE_SIMPLE,description:s("settings.charts.noMemoryTrend")}):r.jsxs(r.Fragment,{children:[r.jsx(pT,{type:"secondary",children:s("settings.charts.memoryTrendDescription")}),r.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:r.jsx(_r,{children:r.jsxs(jf,{data:e,children:[r.jsx(ma,{strokeDasharray:"3 3"}),r.jsx(ha,{dataKey:"label",minTickGap:24}),r.jsx(pa,{allowDecimals:!1}),r.jsx(Tr,{}),r.jsx(dd,{}),r.jsx(mr,{type:"monotone",dataKey:"total_memories",name:s("settings.charts.totalMemories"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),r.jsx(mr,{type:"monotone",dataKey:"created_memories",name:s("settings.charts.createdMemories"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),r.jsx(mr,{type:"monotone",dataKey:"updated_memories",name:s("settings.charts.updatedMemories"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{useToken:gT}=he,yT=e=>{const t=Math.floor(e/1e3),s=Math.floor(t/60),n=t%60;return s>0?`${s}m ${n}s`:`${n}s`},bT=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)},Rm=({summary:e,sessions:t,loading:s})=>{const{t:n}=ne(),{token:o}=gT();if(s)return r.jsx(Xs,{active:!0,paragraph:{rows:1}});const a=bT(t);return r.jsxs(Gt,{gutter:[o.marginSM,o.marginSM],children:[r.jsx(Oe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(ot,{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(Oe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(ot,{title:n("settings.metricsCards.totalSessions"),value:(e==null?void 0:e.total_sessions)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),r.jsx(Oe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(ot,{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(Oe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(ot,{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(Oe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(ot,{title:n("settings.metricsCards.avgSessionDuration"),value:a>0?yT(a):"-",valueStyle:{color:"var(--lotus-chart-accent)"}})})})]})},{Text:xT}=le,Am=["var(--lotus-chart-primary)","var(--lotus-chart-secondary)","var(--lotus-chart-accent)","var(--lotus-chart-purple)","var(--lotus-chart-cyan)"],vT=({data:e,loading:t})=>{const{t:s}=ne();if(t)return r.jsx(ee,{size:"small",className:"lotus-metric-card",title:s("settings.charts.modelDistribution"),children:r.jsx(Xs,{active:!0,paragraph:{rows:5}})});const n=e.map(o=>({name:o.model,value:o.tokens.total_tokens}));return r.jsx(ee,{size:"small",className:"lotus-metric-card",title:s("settings.charts.modelDistribution"),children:n.length===0?r.jsx(kt,{image:kt.PRESENTED_IMAGE_SIMPLE,description:s("settings.charts.noModelMetrics")}):r.jsxs(r.Fragment,{children:[r.jsx(xT,{type:"secondary",children:s("settings.charts.modelDistributionDescription")}),r.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:r.jsx(_r,{children:r.jsxs(Kx,{children:[r.jsx(Gx,{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(Jx,{fill:Am[a%Am.length]},`${o.name}-${a}`))}),r.jsx(Tr,{})]})})})]})})},ST=e=>{if(!e)return"-";const t=new Date(e);return Number.isNaN(t.getTime())?"-":t.toLocaleString()},wT=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`},_T=e=>{switch(e){case"completed":return"success";case"running":return"processing";case"error":return"error";case"cancelled":return"warning";default:return"default"}},TT=({sessions:e,loading:t,onSelectSession:s})=>{const{t:n}=ne(),o=[{title:n("settings.metricsTable.session.columns.session"),dataIndex:"session_id",key:"session_id",render:a=>r.jsx(ke,{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(oe,{color:_T(a),children:a})},{title:n("settings.metricsTable.session.columns.started"),dataIndex:"started_at",key:"started_at",render:a=>ST(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=>wT(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(Y,{type:"link",onClick:()=>{s(i.session_id)},children:n("settings.metricsTable.session.view")})}];return r.jsx(qs,{rowKey:"session_id",size:"small",className:"lotus-metric-table",columns:o,loading:t,dataSource:e,pagination:{pageSize:10,showSizeChanger:!1},scroll:{x:1100}})},{Text:kT}=le,Im={message_count:"Message Count",last_message_id:"Last Message",pending_question:"Pending Question"},jT=e=>Im[e]?Im[e]:e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" "),CT=({breakdown:e,loading:t})=>{const{t:s}=ne();if(t)return r.jsx(ee,{size:"small",className:"lotus-metric-card",title:s("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),children:r.jsx(Xs,{active:!0,paragraph:{rows:5}})});const n=Object.entries(e??{}).map(([o,a])=>({reason:o,label:s(`settings.syncMismatchReasons.${o}`,{defaultValue:jT(o)}),count:a})).sort((o,a)=>a.count-o.count);return r.jsx(ee,{size:"small",className:"lotus-metric-card",title:s("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),extra:r.jsx(kT,{type:"secondary",children:s("settings.metricsDashboard.syncMismatchBreakdownSubtitle",{defaultValue:"Grouped by execute sync mismatch reason"})}),children:n.length===0?r.jsx(kt,{image:kt.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(_r,{children:r.jsxs(cd,{data:n,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[r.jsx(ma,{strokeDasharray:"3 3"}),r.jsx(ha,{type:"number",allowDecimals:!1}),r.jsx(pa,{dataKey:"label",type:"category",width:110}),r.jsx(Tr,{formatter:o=>[o.toLocaleString(),s("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})],labelFormatter:o=>s("settings.metricsDashboard.syncMismatchReasonLabel",{defaultValue:"Reason: {{label}}",label:o})}),r.jsx(fi,{dataKey:"count",fill:"var(--lotus-chart-danger)",radius:[0,6,6,0],name:s("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})})]})})})})},{Text:MT}=le,PT=({data:e,loading:t})=>{const{t:s}=ne();return t?r.jsx(ee,{size:"small",className:"lotus-metric-card",title:s("settings.charts.tokenUsageOverTime"),children:r.jsx(Xs,{active:!0,paragraph:{rows:5}})}):r.jsx(ee,{size:"small",className:"lotus-metric-card",title:s("settings.charts.tokenUsageOverTime"),children:e.length===0?r.jsx(kt,{image:kt.PRESENTED_IMAGE_SIMPLE,description:s("settings.charts.noTokenUsage")}):r.jsxs(r.Fragment,{children:[r.jsx(MT,{type:"secondary",children:s("settings.charts.tokenUsageDescription")}),r.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:r.jsx(_r,{children:r.jsxs(jf,{data:e,children:[r.jsx(ma,{strokeDasharray:"3 3"}),r.jsx(ha,{dataKey:"label",minTickGap:24}),r.jsx(pa,{allowDecimals:!1}),r.jsx(Tr,{}),r.jsx(dd,{}),r.jsx(mr,{type:"monotone",dataKey:"totalTokens",name:s("settings.charts.total"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),r.jsx(mr,{type:"monotone",dataKey:"promptTokens",name:s("settings.charts.prompt"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),r.jsx(mr,{type:"monotone",dataKey:"completionTokens",name:s("settings.charts.completion"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{Text:ET}=le,Wr=({title:e,subtitle:t,emptyText:s,color:n="var(--lotus-chart-primary)",data:o,loading:a,countLabel:i})=>{const{t:l}=ne();return a?r.jsx(ee,{size:"small",className:"lotus-metric-card",title:e,children:r.jsx(Xs,{active:!0,paragraph:{rows:5}})}):r.jsx(ee,{size:"small",className:"lotus-metric-card",title:e,children:o.length===0?r.jsx(kt,{image:kt.PRESENTED_IMAGE_SIMPLE,description:s}):r.jsxs(r.Fragment,{children:[t?r.jsx(ET,{type:"secondary",children:t}):null,r.jsx("div",{style:{width:"100%",minWidth:0,height:280,marginTop:t?12:0},children:r.jsx(_r,{children:r.jsxs(cd,{data:o,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[r.jsx(ma,{strokeDasharray:"3 3"}),r.jsx(ha,{type:"number",allowDecimals:!1}),r.jsx(pa,{dataKey:"label",type:"category",width:110}),r.jsx(Tr,{formatter:c=>[c.toLocaleString(),i??l("settings.metricsDashboard.calls",{defaultValue:"Calls"})],labelFormatter:(c,d)=>{var h,p;const u=(p=(h=d==null?void 0:d[0])==null?void 0:h.payload)==null?void 0:p.meta;return u?`${c} · ${u}`:String(c)}}),r.jsx(fi,{dataKey:"count",fill:n,radius:[0,6,6,0],name:i??l("settings.metricsDashboard.calls",{defaultValue:"Calls"})})]})})})]})})},{useToken:RT}=he,$m=({summary:e,loading:t})=>{const{t:s}=ne(),{token:n}=RT();return t?r.jsx(Xs,{active:!0,paragraph:{rows:1}}):r.jsxs(Gt,{gutter:[n.marginSM,n.marginSM],children:[r.jsx(Oe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(ot,{title:s("settings.metricsDashboard.skillsAndMcp.cards.skillLoadCalls",{defaultValue:"Skill Loads"}),value:(e==null?void 0:e.skill_load_calls)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),r.jsx(Oe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(ot,{title:s("settings.metricsDashboard.skillsAndMcp.cards.uniqueSkills",{defaultValue:"Unique Skills"}),value:(e==null?void 0:e.unique_skills)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),r.jsx(Oe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(ot,{title:s("settings.metricsDashboard.skillsAndMcp.cards.mcpCalls",{defaultValue:"MCP Calls"}),value:(e==null?void 0:e.mcp_calls)??0,precision:0,valueStyle:{color:"var(--lotus-chart-accent)"}})})}),r.jsx(Oe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(ot,{title:s("settings.metricsDashboard.skillsAndMcp.cards.uniqueMcpServers",{defaultValue:"MCP Servers"}),value:(e==null?void 0:e.unique_mcp_servers)??0,precision:0,valueStyle:{color:"var(--lotus-chart-cyan)"}})})}),r.jsx(Oe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(ot,{title:s("settings.metricsDashboard.skillsAndMcp.cards.uniqueMcpTools",{defaultValue:"MCP Tools"}),value:(e==null?void 0:e.unique_mcp_tools)??0,precision:0,valueStyle:{color:"var(--lotus-chart-secondary)"}})})}),r.jsx(Oe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(ot,{title:s("settings.metricsDashboard.skillsAndMcp.cards.coreToolCalls",{defaultValue:"Core Tool Calls"}),value:(e==null?void 0:e.core_tool_calls)??0,precision:0,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})})]})},{Text:sr}=le,{useToken:AT}=he,Dm=70,Lm=130,Om=2,Fm=1.2,zm=.65,Nm=45,Bm=1.8,Wm=e=>"date"in e?e.date:e.label,IT=(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)"},Ur=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`},Um=e=>{if(!e)return"-";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},Tl=e=>{const t=Object.entries(e??{}).sort((s,n)=>n[1]-s[1]);return t.length===0?"-":t.slice(0,6).map(([s,n])=>`${s}: ${n.toLocaleString()}`).join(" • ")},kl=(e,t=320)=>({width:"100%",display:"grid",gridTemplateColumns:`repeat(auto-fit, minmax(${t}px, 1fr))`,gap:e}),$T=()=>{const{t:e}=ne(),{token:t}=AT(),s=qn(U=>U.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:g,modelMetrics:y,sessions:f,timeline:v,memorySummary:b,memoryTimeline:x,sessionDetail:_,isLoading:w,isRefreshing:k,isSessionDetailLoading:C,error:E,refresh:j,loadSessionDetail:R,clearSessionDetail:M}=tT({filters:{startDate:n,endDate:a,model:l,days:d,granularity:h}}),{summary:T,endpointMetrics:P,requests:S,isLoading:L,isRefreshing:$,error:I,refresh:W}=Z0({filters:{startDate:n,endDate:a,days:d,model:l}}),{data:A,isLoading:O,isRefreshing:D,error:H,refresh:B}=rT({filters:{startDate:n,endDate:a,days:d,model:l}}),K=m.useMemo(()=>v.map(U=>({label:Wm(U),promptTokens:U.total_token_usage.prompt_tokens,completionTokens:U.total_token_usage.completion_tokens,totalTokens:U.total_token_usage.total_tokens})),[v]),F=m.useMemo(()=>y.map(U=>({label:U.model,value:U.model})),[y]),z=m.useMemo(()=>{const U=v.map(Ce=>({label:Wm(Ce),sessions:Ce.total_sessions,tokens:Ce.total_token_usage.total_tokens})),_e=U.reduce((Ce,Ve)=>Math.max(Ce,Ve.sessions),0);return{points:U,maxSessions:_e}},[v]),de=m.useMemo(()=>{const U=S.map(Ce=>Ce.duration_ms).filter(Ce=>typeof Ce=="number"&&Ce>0).sort((Ce,Ve)=>Ce-Ve);if(U.length===0)return null;const _e=Math.ceil(U.length*.95)-1;return U[Math.max(0,Math.min(_e,U.length-1))]},[S]),Te=m.useMemo(()=>[{title:e("settings.metricsDashboard.roundColumns.round"),dataIndex:"round_id",key:"round_id",render:U=>`${U.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:U=>Ur(U)},{title:e("settings.metricsDashboard.roundColumns.tokens"),key:"tokens",render:(U,_e)=>_e.token_usage.total_tokens.toLocaleString()},{title:e("settings.metricsDashboard.roundColumns.toolCalls"),key:"tool_calls",render:(U,_e)=>_e.tool_calls.length}],[e]),$e=m.useMemo(()=>{const U=(g==null?void 0:g.total_sessions)??0,_e=(g==null?void 0:g.total_tokens.total_tokens)??0,Ce=(g==null?void 0:g.total_tool_calls)??0,Ve=(g==null?void 0:g.active_sessions)??0,qe=f.reduce((Ks,Er)=>Ks+Er.total_rounds,0),J=(T==null?void 0:T.total_requests)??0,re=(T==null?void 0:T.total_tokens.total_tokens)??0,V=(T==null?void 0:T.failed_requests)??0,Q=S.filter(Ks=>Ks.is_stream).length,se=U>0?Ve/U*100:0,ce=J>0?V/J*100:0,Ie=S.length>0?Q/S.length*100:0,Je=_e/Dm+Ce*Om,_t=_e/Lm+Ce*Fm,Ct=Math.max(0,Je-_t)*zm,Tt=Math.max(_t,Je-Ct),hn=Ur(Ct*6e4),Vs=Number((Ct/(8*60)).toFixed(2)),Pr=Je>0?Math.min(Nm,Number((Ct/Je*100).toFixed(1))):0,Vn=Tt>0?Math.min(Bm,Number((Je/Tt).toFixed(2))):1;return[{title:e("settings.metricsDashboard.compactStats.avgTokensPerSession"),value:U>0?Math.round(_e/U):0},{title:e("settings.metricsDashboard.compactStats.estimatedTimeSaved"),value:hn},{title:e("settings.metricsDashboard.compactStats.estimatedEfficiencyLift"),value:Pr,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.estimatedSpeedMultiplier"),value:Vn,suffix:e("settings.metricsDashboard.multiplierSuffix")},{title:e("settings.metricsDashboard.compactStats.estimatedSavedWorkdays"),value:Vs},{title:e("settings.metricsDashboard.compactStats.avgRoundsPerSession"),value:U>0?Number((qe/U).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.toolCallsPerSession"),value:U>0?Number((Ce/U).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.activeSessionRate"),value:Number(se.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.avgTokensPerForward"),value:J>0?Math.round(re/J):0},{title:e("settings.metricsDashboard.compactStats.forwardErrorRate"),value:Number(ce.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.streamingRatio"),value:Number(Ie.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.p95ForwardLatency"),value:Ur(de)},{title:e("settings.metricsDashboard.compactStats.modelCoverage"),value:y.length},{title:e("settings.metricsDashboard.compactStats.endpointCoverage"),value:P.length}]},[P.length,S,T,y.length,de,f,g,e]),De=m.useMemo(()=>{const U=(T==null?void 0:T.total_requests)??0,_e=(T==null?void 0:T.failed_requests)??0,Ce=S.filter(J=>J.is_stream).length,Ve=S.length>0?Ce/S.length*100:0,qe=U>0?_e/U*100:0;return[{title:e("settings.metricsDashboard.forward.performance.p95Latency",{defaultValue:"P95 Latency"}),value:Ur(de)},{title:e("settings.metricsDashboard.forward.performance.errorRate",{defaultValue:"Error Rate"}),value:Number(qe.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.streamingRatio",{defaultValue:"Streaming Ratio"}),value:Number(Ve.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.endpointCoverage",{defaultValue:"Endpoint Coverage"}),value:P.length}]},[P.length,S,T,de,e]),be=m.useMemo(()=>A?[{label:e("settings.metricsDashboard.skillsAndMcp.mix.coreTools",{defaultValue:"Core Tools"}),count:A.core_tool_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.skillLoads",{defaultValue:"Skill Loads"}),count:A.skill_load_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.mcpCalls",{defaultValue:"MCP Calls"}),count:A.mcp_calls}].filter(U=>U.count>0):[],[e,A]),ye=m.useMemo(()=>((A==null?void 0:A.top_skills)??[]).map(U=>({label:U.skill_id,count:U.count})),[A]),je=m.useMemo(()=>((A==null?void 0:A.top_mcp_servers)??[]).map(U=>({label:U.server_id,count:U.count,meta:e("settings.metricsDashboard.skillsAndMcp.meta.uniqueTools",{defaultValue:"{{count}} tools",count:U.unique_tools})})),[e,A]),Ue=m.useMemo(()=>((A==null?void 0:A.top_mcp_tools)??[]).map(U=>({label:U.tool_name,count:U.count,meta:U.server_id})),[A]),ht=m.useMemo(()=>((A==null?void 0:A.top_core_tools)??[]).map(U=>({label:U.name,count:U.count})),[A]),Ge=_==null?void 0:_.session,wt=k||$||D;return r.jsxs(X,{direction:"vertical",size:t.marginMD,style:{width:"100%"},children:[E?r.jsx(Xe,{type:"error",showIcon:!0,message:E}):null,I?r.jsx(Xe,{type:"error",showIcon:!0,message:I}):null,H?r.jsx(Xe,{type:"error",showIcon:!0,message:H}):null,r.jsx(ee,{size:"small",title:e("settings.metricsDashboard.filtersTitle"),extra:r.jsx(Y,{icon:r.jsx(Ms,{}),loading:wt,onClick:()=>{j(),W(),B()},children:e("settings.metricsDashboard.refresh")}),children:r.jsxs(X,{wrap:!0,children:[r.jsx(cu,{placeholder:e("settings.metricsDashboard.startDate"),onChange:U=>{o(U?U.format("YYYY-MM-DD"):void 0)}}),r.jsx(cu,{placeholder:e("settings.metricsDashboard.endDate"),onChange:U=>{i(U?U.format("YYYY-MM-DD"):void 0)}}),r.jsx(Pe,{allowClear:!0,style:{minWidth:180},placeholder:e("settings.metricsDashboard.model"),value:l,options:F,onChange:U=>{c(U)}}),r.jsx(Pe,{style:{width:120},value:d,options:[7,14,30,90].map(U=>({label:e("settings.metricsDashboard.daysOption",{value:U}),value:U})),onChange:U=>{u(U)}}),r.jsx(Pe,{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:U=>{p(U)}})]})}),r.jsx(ee,{size:"small",title:e("settings.metricsDashboard.dashboardTitle"),children:r.jsx(ui,{size:"small",destroyInactiveTabPane:!0,items:[{key:"overview",label:e("settings.metricsDashboard.tabs.overview"),children:r.jsxs(X,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(Rm,{summary:g,sessions:f,loading:w}),r.jsx(Pm,{summary:T,loading:L}),r.jsx($m,{summary:A,loading:O}),r.jsx(Em,{summary:b,loading:w}),r.jsxs(ee,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.derivedMetricsTitle"),extra:r.jsx(sr,{type:"secondary",children:e("settings.metricsDashboard.derivedMetricsSubtitle")}),children:[r.jsx(Gt,{gutter:[t.marginSM,t.marginSM],children:$e.map(U=>r.jsx(Oe,{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(ot,{title:U.title,value:U.value,suffix:U.suffix,valueStyle:{fontSize:t.fontSizeHeading4}})})},U.title))}),r.jsx(sr,{type:"secondary",style:{display:"block",marginTop:t.marginXS},children:e("settings.metricsDashboard.efficiencyHint",{manualTpm:Dm,manualToolMinutes:Om,assistedTpm:Lm,assistedToolMinutes:Fm,realization:Math.round(zm*100),maxLift:Nm,maxMultiplier:Bm})})]})]})},{key:"chat",label:e("settings.metricsDashboard.tabs.chat",{defaultValue:"Chat"}),children:r.jsxs(X,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(Rm,{summary:g,sessions:f,loading:w}),r.jsxs("div",{style:kl(t.marginSM,360),children:[r.jsx(PT,{data:K,loading:w}),r.jsx(vT,{data:y,loading:w})]}),r.jsxs("div",{style:kl(t.marginSM,360),children:[r.jsx(CT,{breakdown:g==null?void 0:g.sync_mismatch_breakdown,loading:w}),r.jsx(ee,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.activityHeatmapTitle"),children:z.points.length===0?r.jsx(sr,{type:"secondary",children:e("settings.metricsDashboard.noActivity")}):r.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))",gap:t.marginXS},children:z.points.map(U=>r.jsxs("div",{style:{borderRadius:t.borderRadiusSM,padding:t.paddingXS,background:IT(U.sessions,z.maxSessions),minHeight:64,color:U.sessions>0?"var(--lotus-metric-text-strong)":t.colorTextSecondary},children:[r.jsx("div",{style:{fontSize:12,lineHeight:1.2},children:U.label}),r.jsx("div",{style:{fontWeight:600,marginTop:4},children:e("settings.metricsDashboard.sessionsCount",{count:U.sessions})}),r.jsx("div",{style:{fontSize:12},children:e("settings.metricsDashboard.tokensAmount",{value:U.tokens.toLocaleString()})})]},U.label))})})]})]})},{key:"skills-and-mcp",label:e("settings.metricsDashboard.tabs.skillsAndMcp",{defaultValue:"Skills & MCP"}),children:r.jsxs(X,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx($m,{summary:A,loading:O}),r.jsxs("div",{style:kl(t.marginSM,360),children:[r.jsx(Wr,{title:e("settings.metricsDashboard.skillsAndMcp.usageMixTitle",{defaultValue:"Usage Mix"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.usageMixSubtitle",{defaultValue:"Compare core tools, skill loads, and MCP calls in one view."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noUsageMix",{defaultValue:"No usage data available for this range."}),data:be,loading:O,color:"var(--lotus-chart-primary)"}),r.jsx(Wr,{title:e("settings.metricsDashboard.skillsAndMcp.topSkillsTitle",{defaultValue:"Top Skills"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.topSkillsSubtitle",{defaultValue:"Counted from load_skill calls during matching sessions."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noSkills",{defaultValue:"No skills were loaded in this range."}),data:ye,loading:O,color:"var(--lotus-chart-purple)"}),r.jsx(Wr,{title:e("settings.metricsDashboard.skillsAndMcp.topMcpServersTitle",{defaultValue:"Top MCP Servers"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.topMcpServersSubtitle",{defaultValue:"Server-level MCP call distribution."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noMcpServers",{defaultValue:"No MCP activity recorded for this range."}),data:je,loading:O,color:"var(--lotus-chart-cyan)"}),r.jsx(Wr,{title:e("settings.metricsDashboard.skillsAndMcp.topMcpToolsTitle",{defaultValue:"Top MCP Tools"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.topMcpToolsSubtitle",{defaultValue:"Most frequently called MCP tool aliases."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noMcpTools",{defaultValue:"No MCP tools were called in this range."}),data:Ue,loading:O,color:"var(--lotus-chart-accent)"}),r.jsx(Wr,{title:e("settings.metricsDashboard.skillsAndMcp.topCoreToolsTitle",{defaultValue:"Top Core Tools"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.topCoreToolsSubtitle",{defaultValue:"Canonicalized built-in and server tool usage ranking."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noCoreTools",{defaultValue:"No core tools were called in this range."}),data:ht,loading:O,color:"var(--lotus-chart-secondary)"})]})]})},{key:"forward",label:e("settings.metricsDashboard.tabs.forward",{defaultValue:"Forward"}),children:r.jsxs(X,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(Pm,{summary:T,loading:L}),r.jsx(ee,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.forward.performanceTitle",{defaultValue:"Forward Performance"}),children:r.jsx(Gt,{gutter:[t.marginSM,t.marginSM],children:De.map(U=>r.jsx(Oe,{xs:24,sm:12,xl:6,children:r.jsx("div",{style:{borderRadius:t.borderRadiusSM,padding:t.paddingXS,background:s?"rgba(255, 255, 255, 0.05)":"rgba(255, 255, 255, 0.82)",border:s?"1px solid rgba(255,255,255,0.08)":"1px solid rgba(148,163,184,0.18)"},children:r.jsx(ot,{title:U.title,value:U.value,suffix:U.suffix,valueStyle:{fontSize:t.fontSizeHeading4}})})},U.title))})}),r.jsx(aT,{data:P,loading:L})]})},{key:"memory",label:e("settings.metricsDashboard.tabs.memory",{defaultValue:"Memory"}),children:r.jsxs(X,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(Em,{summary:b,loading:w}),r.jsx(fT,{data:x,loading:w}),r.jsx(ee,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.memory.breakdownTitle",{defaultValue:"Memory Breakdown"}),children:r.jsxs(Pt,{size:"small",bordered:!0,column:1,children:[r.jsx(Pt.Item,{label:e("settings.metricsDashboard.memory.byType",{defaultValue:"By Type"}),children:Tl(b==null?void 0:b.by_type)}),r.jsx(Pt.Item,{label:e("settings.metricsDashboard.memory.byStatus",{defaultValue:"By Status"}),children:Tl(b==null?void 0:b.by_status)}),r.jsx(Pt.Item,{label:e("settings.metricsDashboard.memory.byScope",{defaultValue:"By Scope"}),children:Tl(b==null?void 0:b.by_scope)}),r.jsx(Pt.Item,{label:e("settings.metricsDashboard.memory.lastDream",{defaultValue:"Last Dream"}),children:Um(b==null?void 0:b.last_dream_at)}),r.jsx(Pt.Item,{label:e("settings.metricsDashboard.memory.lastReindex",{defaultValue:"Last Reindex"}),children:Um(b==null?void 0:b.last_reindex_at)})]})})]})},{key:"records",label:e("settings.metricsDashboard.tabs.records"),children:r.jsx(ui,{size:"small",destroyInactiveTabPane:!0,items:[{key:"sessions",label:e("settings.metricsDashboard.sessionsTabLabel",{count:f.length}),children:r.jsx(ee,{size:"small",extra:r.jsx(sr,{type:"secondary",children:e("settings.metricsDashboard.sessionsHint")}),children:r.jsx(TT,{sessions:f,loading:w,onSelectSession:U=>{R(U)}})})},{key:"forward-requests",label:e("settings.metricsDashboard.forwardTabLabel",{count:S.length}),children:r.jsx(ee,{size:"small",children:r.jsx(uT,{requests:S,loading:L})})}]})}]})}),r.jsx(Lt,{title:e("settings.metricsDashboard.sessionMetricsTitle"),open:!!_,onCancel:M,onOk:M,width:960,destroyOnClose:!0,children:C?r.jsx(sr,{children:e("settings.metricsDashboard.loadingSessionDetails")}):Ge?r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:t.marginMD,children:[r.jsxs(Pt,{size:"small",bordered:!0,column:2,children:[r.jsx(Pt.Item,{label:e("settings.metricsDashboard.sessionDetail.sessionId"),span:2,children:Ge.session_id}),r.jsx(Pt.Item,{label:e("settings.metricsDashboard.sessionDetail.model"),children:Ge.model}),r.jsx(Pt.Item,{label:e("settings.metricsDashboard.sessionDetail.status"),children:Ge.status}),r.jsx(Pt.Item,{label:e("settings.metricsDashboard.sessionDetail.duration"),children:Ur(Ge.duration_ms)}),r.jsx(Pt.Item,{label:e("settings.metricsDashboard.sessionDetail.messages"),children:Ge.message_count}),r.jsx(Pt.Item,{label:e("settings.metricsDashboard.sessionDetail.totalTokens"),children:Ge.total_token_usage.total_tokens.toLocaleString()}),r.jsx(Pt.Item,{label:e("settings.metricsDashboard.sessionDetail.toolCalls"),children:Ge.tool_call_count})]}),r.jsx(qs,{rowKey:"round_id",size:"small",columns:Te,dataSource:_.rounds,pagination:{pageSize:6,showSizeChanger:!1}})]}):r.jsx(sr,{type:"secondary",children:e("settings.metricsDashboard.noDetail")})})]})},{Text:za}=le,{useToken:DT}=he,LT=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"},OT=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},FT=()=>{const{t:e}=ne(),{token:t}=DT(),[s,n]=fe.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 et.getBambooConfig();l(OT(f)),d(LT(f))}catch(f){s.error(f instanceof Error?f.message:e("settings.hooksTab.loadFailed"))}finally{a(!1)}},[s,e]),p=m.useCallback(async(f,v)=>{await et.setBambooConfig({hooks:{image_fallback:{enabled:f,mode:v}}})},[]),g=m.useCallback(async f=>{a(!0);try{await p(f,c),s.success(e(f?"settings.hooksTab.enabled":"settings.hooksTab.disabled")),await h()}catch(v){s.error(v instanceof Error?v.message:e("settings.hooksTab.updateFailed"))}finally{a(!1)}},[h,c,s,p,e]),y=m.useCallback(async f=>{var v;a(!0);try{await p(i,f),s.success(e("settings.hooksTab.modeUpdated",{mode:((v=u.find(b=>b.value===f))==null?void 0:v.label)??f})),await h()}catch(b){s.error(b instanceof Error?b.message:e("settings.hooksTab.modeUpdateFailed"))}finally{a(!1)}},[i,h,u,s,p,e]);return m.useEffect(()=>{h()},[h]),r.jsxs(G,{vertical:!0,gap:t.marginLG,children:[n,r.jsx(ee,{size:"small",loading:o,children:r.jsxs(G,{vertical:!0,gap:t.marginXS,children:[r.jsx(za,{strong:!0,children:e("settings.hooksTab.title")}),r.jsxs(G,{align:"center",justify:"space-between",children:[r.jsx(za,{children:e("settings.hooksTab.enableImagePreflight")}),r.jsx(it,{checked:i,onChange:g})]}),r.jsxs(G,{align:"center",justify:"space-between",children:[r.jsx(za,{children:e("settings.hooksTab.modeLabel")}),r.jsx(Pe,{style:{width:180},value:c,options:u,onChange:y,disabled:!i})]}),r.jsx(za,{type:"secondary",style:{fontSize:t.fontSizeSM},children:e("settings.hooksTab.description")})]})})]})},{Text:yt}=le,Os=rs.getInstance();function zT(e){switch(e){case"success":return"success";case"failed":case"cancelled":return"error";case"running":return"processing";case"queued":return"gold";case"missed":case"skipped":default:return"default"}}const NT=[{label:"Mon",value:"mon"},{label:"Tue",value:"tue"},{label:"Wed",value:"wed"},{label:"Thu",value:"thu"},{label:"Fri",value:"fri"},{label:"Sat",value:"sat"},{label:"Sun",value:"sun"}];function pt(e){return String(e??"").trim()||void 0}function BT(e){return(e==null?void 0:e.type)==="interval"?e.every_seconds:null}function Oy(e){return{type:"interval",every_seconds:e}}function WT(e){switch(e.type){case"interval":return`interval · ${e.every_seconds}s`;case"daily":return`daily · ${String(e.hour).padStart(2,"0")}:${String(e.minute).padStart(2,"0")}`;case"weekly":return`weekly · ${e.weekdays.join(", ")}`;case"monthly":return`monthly · ${e.days.join(", ")}`;case"cron":return`cron · ${e.expr}`}}function UT(e){switch(e==null?void 0:e.type){case"skip":return"skip";case"catch_up_all":return"catch up all";case"catch_up_window":return"catch up window";case"run_once":default:return"run once"}}function qT(e){switch(e){case"allow":return"allow overlap";case"skip":return"skip overlap";case"queue_one":default:return"queue one"}}function HT(e){var t;return(t=e.state)!=null&&t.next_fire_at?String(e.state.next_fire_at):"-"}function YT(e){var t,s;return(t=e.state)!=null&&t.last_success_at?String(e.state.last_success_at):(s=e.state)!=null&&s.last_finished_at?String(e.state.last_finished_at):"-"}function XT(e){var t,s,n,o;return((t=e.state)==null?void 0:t.running_run_count)>0?{color:"processing",label:"running",detail:`${e.state.running_run_count} active`}:(((s=e.state)==null?void 0:s.queued_run_count)||0)>0?{color:"gold",label:"queued",detail:`${e.state.queued_run_count} pending`}:(((n=e.state)==null?void 0:n.consecutive_failures)||0)>0?{color:"error",label:"failing",detail:`${e.state.consecutive_failures} consecutive failures`}:e.enabled?(o=e.state)!=null&&o.last_success_at?{color:"success",label:"healthy",detail:"last run succeeded"}:{color:"default",label:"idle"}:{color:"default",label:"disabled"}}function VT(e){const t=pt(e);if(!t)return{days:[],invalid:!1};const n=t.split(/[\s,]+/).filter(Boolean).map(i=>Number(i)),o=n.some(i=>!Number.isInteger(i)||i<1||i>31);return{days:Array.from(new Set(n.filter(i=>Number.isInteger(i)&&i>=1&&i<=31))),invalid:o}}function qm(e){switch(e.trigger_type){case"interval":{const t=Number(e.interval_seconds||0);return t<=0?{errorKey:"settings.schedulesTab.validation.intervalRequired"}:{trigger:Oy(t)}}case"daily":{const t=e.daily_hour,s=e.daily_minute;return t==null||s==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"daily",hour:t,minute:s,second:0}}}case"weekly":{const t=e.weekly_weekdays||[],s=e.weekly_hour,n=e.weekly_minute;return t.length===0?{errorKey:"settings.schedulesTab.validation.weekdaysRequired"}:s==null||n==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"weekly",weekdays:t,hour:s,minute:n,second:0}}}case"monthly":{const{days:t,invalid:s}=VT(e.monthly_days);if(s)return{errorKey:"settings.schedulesTab.validation.invalidMonthDays"};if(t.length===0)return{errorKey:"settings.schedulesTab.validation.monthDaysRequired"};const n=e.monthly_hour,o=e.monthly_minute;return n==null||o==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"monthly",days:t,hour:n,minute:o,second:0}}}case"cron":{const t=pt(e.cron_expr);return t?{trigger:{type:"cron",expr:t}}:{errorKey:"settings.schedulesTab.validation.cronRequired"}}default:return{errorKey:"settings.schedulesTab.validation.triggerRequired"}}}function Hm(e){switch(e.misfire_policy){case"skip":return{type:"skip"};case"catch_up_all":return{type:"catch_up_all"};case"catch_up_window":return{type:"catch_up_window",max_catch_up_runs:Number(e.catch_up_window_max_runs||1),max_lateness_seconds:Number(e.catch_up_window_max_lateness_seconds||60)};case"run_once":default:return{type:"run_once"}}}function KT(e){var s,n,o,a,i,l,c,d;const t={name:e.name,enabled:e.enabled,trigger_type:e.trigger.type,timezone:e.timezone||"",start_at:e.start_at||"",end_at:e.end_at||"",misfire_policy:((s=e.misfire_policy)==null?void 0:s.type)||"run_once",overlap_policy:e.overlap_policy||"queue_one",system_prompt:((n=e.run_config)==null?void 0:n.system_prompt)||"",task_message:((o=e.run_config)==null?void 0:o.task_message)||"",model:((a=e.run_config)==null?void 0:a.model)||"",workspace_path:((i=e.run_config)==null?void 0:i.workspace_path)||"",enhance_prompt:((l=e.run_config)==null?void 0:l.enhance_prompt)||"",auto_execute:!!((c=e.run_config)!=null&&c.auto_execute)};switch(((d=e.misfire_policy)==null?void 0:d.type)==="catch_up_window"&&(t.catch_up_window_max_runs=e.misfire_policy.max_catch_up_runs,t.catch_up_window_max_lateness_seconds=e.misfire_policy.max_lateness_seconds),e.trigger.type){case"interval":t.interval_seconds=e.trigger.every_seconds;break;case"daily":t.daily_hour=e.trigger.hour,t.daily_minute=e.trigger.minute;break;case"weekly":t.weekly_weekdays=e.trigger.weekdays,t.weekly_hour=e.trigger.hour,t.weekly_minute=e.trigger.minute;break;case"monthly":t.monthly_days=e.trigger.days.join(", "),t.monthly_hour=e.trigger.hour,t.monthly_minute=e.trigger.minute;break;case"cron":t.cron_expr=e.trigger.expr;break}return t}function GT(){const{t:e}=ne(),[t,s]=fe.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,scheduleId:null,runs:[],loading:!1}),[h,p]=m.useState({open:!1,schedule:null,saving:!1}),g=Bs(M=>M.close),[y]=Z.useForm(),[f]=Z.useForm(),v=Z.useWatch("trigger_type",y),b=Z.useWatch("misfire_policy",y),x=Z.useWatch("trigger_type",f),_=Z.useWatch("misfire_policy",f),w=m.useCallback(async()=>{o(!0);try{const M=await Os.listSchedules();i(M.schedules||[])}catch(M){console.error("[Schedules] Failed to load schedules:",M),t.error(e("settings.schedulesTab.loadFailed"))}finally{o(!1)}},[t,e]);m.useEffect(()=>{w()},[w]);const k=[{value:"interval",label:e("settings.schedulesTab.triggerTypes.interval")},{value:"daily",label:e("settings.schedulesTab.triggerTypes.daily")},{value:"weekly",label:e("settings.schedulesTab.triggerTypes.weekly")},{value:"monthly",label:e("settings.schedulesTab.triggerTypes.monthly")},{value:"cron",label:e("settings.schedulesTab.triggerTypes.cron")}],C=[{value:"run_once",label:e("settings.schedulesTab.misfirePolicyOptions.runOnce")},{value:"skip",label:e("settings.schedulesTab.misfirePolicyOptions.skip")},{value:"catch_up_all",label:e("settings.schedulesTab.misfirePolicyOptions.catchUpAll")},{value:"catch_up_window",label:e("settings.schedulesTab.misfirePolicyOptions.catchUpWindow")}],E=[{value:"queue_one",label:e("settings.schedulesTab.overlapPolicyOptions.queueOne")},{value:"skip",label:e("settings.schedulesTab.overlapPolicyOptions.skip")},{value:"allow",label:e("settings.schedulesTab.overlapPolicyOptions.allow")}],j=(M,T)=>r.jsxs(r.Fragment,{children:[r.jsxs(G,{gap:12,wrap:"wrap",children:[r.jsx(Z.Item,{label:e("settings.schedulesTab.form.name"),name:"name",rules:[{required:!0,message:e("settings.schedulesTab.validation.nameRequired")}],style:{flex:"1 1 260px"},children:r.jsx(me,{})}),r.jsx(Z.Item,{label:e("settings.schedulesTab.form.triggerType"),name:"trigger_type",rules:[{required:!0,message:e("settings.schedulesTab.validation.triggerRequired")}],style:{width:220},children:r.jsx(Pe,{options:k})}),r.jsx(Z.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",style:{width:120},children:r.jsx(it,{})})]}),M==="interval"?r.jsx(Z.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(rt,{min:1,style:{width:"100%"}})}):null,M==="daily"?r.jsxs(G,{gap:12,wrap:"wrap",children:[r.jsx(Z.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"daily_hour",style:{width:180},children:r.jsx(rt,{min:0,max:23,style:{width:"100%"}})}),r.jsx(Z.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"daily_minute",style:{width:180},children:r.jsx(rt,{min:0,max:59,style:{width:"100%"}})})]}):null,M==="weekly"?r.jsxs(r.Fragment,{children:[r.jsx(Z.Item,{label:e("settings.schedulesTab.form.weeklyWeekdays"),name:"weekly_weekdays",style:{minWidth:320},children:r.jsx(Pe,{mode:"multiple",options:NT})}),r.jsxs(G,{gap:12,wrap:"wrap",children:[r.jsx(Z.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"weekly_hour",style:{width:180},children:r.jsx(rt,{min:0,max:23,style:{width:"100%"}})}),r.jsx(Z.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"weekly_minute",style:{width:180},children:r.jsx(rt,{min:0,max:59,style:{width:"100%"}})})]})]}):null,M==="monthly"?r.jsxs(r.Fragment,{children:[r.jsx(Z.Item,{label:e("settings.schedulesTab.form.monthlyDays"),name:"monthly_days",style:{minWidth:320},children:r.jsx(me,{placeholder:e("settings.schedulesTab.form.monthlyDaysPlaceholder")})}),r.jsxs(G,{gap:12,wrap:"wrap",children:[r.jsx(Z.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"monthly_hour",style:{width:180},children:r.jsx(rt,{min:0,max:23,style:{width:"100%"}})}),r.jsx(Z.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"monthly_minute",style:{width:180},children:r.jsx(rt,{min:0,max:59,style:{width:"100%"}})})]})]}):null,M==="cron"?r.jsx(Z.Item,{label:e("settings.schedulesTab.form.cronExpr"),name:"cron_expr",children:r.jsx(me,{placeholder:e("settings.schedulesTab.form.cronExprPlaceholder")})}):null,r.jsxs(G,{gap:12,wrap:"wrap",children:[r.jsx(Z.Item,{label:e("settings.schedulesTab.form.timezone"),name:"timezone",style:{flex:"1 1 240px"},children:r.jsx(me,{placeholder:e("settings.schedulesTab.form.timezonePlaceholder")})}),r.jsx(Z.Item,{label:e("settings.schedulesTab.form.startAt"),name:"start_at",style:{flex:"1 1 240px"},children:r.jsx(me,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})}),r.jsx(Z.Item,{label:e("settings.schedulesTab.form.endAt"),name:"end_at",style:{flex:"1 1 240px"},children:r.jsx(me,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})})]}),r.jsxs(G,{gap:12,wrap:"wrap",children:[r.jsx(Z.Item,{label:e("settings.schedulesTab.form.misfirePolicy"),name:"misfire_policy",style:{flex:"1 1 240px"},children:r.jsx(Pe,{options:C})}),r.jsx(Z.Item,{label:e("settings.schedulesTab.form.overlapPolicy"),name:"overlap_policy",style:{flex:"1 1 240px"},children:r.jsx(Pe,{options:E})})]}),T==="catch_up_window"?r.jsxs(G,{gap:12,wrap:"wrap",children:[r.jsx(Z.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxRuns"),name:"catch_up_window_max_runs",style:{width:220},children:r.jsx(rt,{min:1,style:{width:"100%"}})}),r.jsx(Z.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxLatenessSeconds"),name:"catch_up_window_max_lateness_seconds",style:{width:260},children:r.jsx(rt,{min:1,style:{width:"100%"}})})]}):null,r.jsx(Z.Item,{label:e("settings.schedulesTab.form.taskMessage"),name:"task_message",children:r.jsx(me.TextArea,{rows:3,placeholder:e("settings.schedulesTab.form.taskMessagePlaceholder")})}),r.jsx(Z.Item,{label:e("settings.schedulesTab.form.systemPrompt"),name:"system_prompt",children:r.jsx(me.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})}),r.jsxs(G,{gap:12,wrap:"wrap",children:[r.jsx(Z.Item,{label:e("settings.schedulesTab.form.model"),name:"model",style:{flex:"1 1 240px"},children:r.jsx(me,{placeholder:e("settings.schedulesTab.form.modelPlaceholder")})}),r.jsx(Z.Item,{label:e("settings.schedulesTab.form.workspacePath"),name:"workspace_path",style:{flex:"1 1 320px"},children:r.jsx(me,{placeholder:e("settings.schedulesTab.optional")})}),r.jsx(Z.Item,{label:e("settings.schedulesTab.form.autoExecute"),name:"auto_execute",valuePropName:"checked",style:{width:160},children:r.jsx(it,{})})]}),r.jsx(Z.Item,{label:e("settings.schedulesTab.form.enhancePrompt"),name:"enhance_prompt",children:r.jsx(me.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})})]}),R=m.useMemo(()=>[{title:e("settings.schedulesTab.columns.name"),key:"name",render:(M,T)=>r.jsxs(G,{vertical:!0,gap:6,children:[r.jsx(yt,{strong:!0,children:T.name}),r.jsxs(G,{gap:6,wrap:"wrap",children:[r.jsx(oe,{children:WT(T.trigger)}),T.timezone?r.jsx(oe,{color:"blue",children:T.timezone}):null,r.jsx(oe,{children:UT(T.misfire_policy)}),r.jsx(oe,{children:qT(T.overlap_policy)})]})]})},{title:e("settings.schedulesTab.columns.status"),key:"status",render:(M,T)=>{const P=XT(T);return r.jsxs(G,{vertical:!0,gap:4,children:[r.jsx(oe,{color:P.color,children:P.label}),P.detail?r.jsx(yt,{type:"secondary",children:P.detail}):null]})}},{title:e("settings.schedulesTab.columns.activity"),key:"activity",render:(M,T)=>{var P,S,L,$;return r.jsxs(G,{vertical:!0,gap:2,children:[r.jsxs(yt,{type:"secondary",children:["queued: ",((P=T.state)==null?void 0:P.queued_run_count)??0]}),r.jsxs(yt,{type:"secondary",children:["running: ",((S=T.state)==null?void 0:S.running_run_count)??0]}),r.jsxs(yt,{type:"secondary",children:["ok: ",((L=T.state)==null?void 0:L.total_success_count)??0]}),r.jsxs(yt,{type:"secondary",children:["fail: ",(($=T.state)==null?void 0:$.total_failure_count)??0]})]})}},{title:e("settings.schedulesTab.columns.nextRun"),key:"next_run_at",render:(M,T)=>r.jsx(yt,{type:"secondary",children:HT(T)})},{title:e("settings.schedulesTab.columns.lastRun"),key:"last_run_at",render:(M,T)=>r.jsx(yt,{type:"secondary",children:YT(T)})},{title:e("settings.schedulesTab.columns.autoExecute"),key:"auto_execute",render:(M,T)=>{var P,S;return r.jsx(yt,{type:(P=T.run_config)!=null&&P.auto_execute?void 0:"secondary",children:(S=T.run_config)!=null&&S.auto_execute?e("settings.schedulesTab.yes"):e("settings.schedulesTab.no")})}},{title:e("settings.schedulesTab.columns.model"),key:"model",render:(M,T)=>{var P;return r.jsx(yt,{type:"secondary",children:(P=T.run_config)!=null&&P.model?String(T.run_config.model):"-"})}},{title:e("settings.schedulesTab.columns.enabled"),key:"enabled",render:(M,T)=>r.jsx(it,{checked:T.enabled,onChange:async P=>{try{await Os.patchSchedule(T.id,{enabled:P}),await w()}catch(S){console.error("[Schedules] Failed to toggle:",S),t.error(e("settings.schedulesTab.updateFailed"))}}})},{title:e("settings.schedulesTab.columns.actions"),key:"actions",render:(M,T)=>{const P=r.jsx(rt,{min:1,value:BT(T.trigger)??void 0,disabled:T.trigger.type!=="interval",onChange:async S=>{const L=typeof S=="number"?S:null;if(!(!L||L<=0))try{await Os.patchSchedule(T.id,{trigger:Oy(L)}),await w()}catch($){console.error("[Schedules] Failed to patch interval:",$),t.error(e("settings.schedulesTab.updateFailed"))}}});return r.jsxs(G,{vertical:!0,gap:8,children:[r.jsxs(G,{gap:8,wrap:"wrap",children:[r.jsx(Y,{size:"small",onClick:()=>{p({open:!0,schedule:T,saving:!1}),f.setFieldsValue(KT(T))},children:e("settings.schedulesTab.actions.edit")}),r.jsx(Y,{size:"small",onClick:async()=>{try{await Os.runScheduleNow(T.id),t.success(e("settings.schedulesTab.enqueuedRun")),await w()}catch(S){console.error("[Schedules] Failed to run now:",S),t.error(e("settings.schedulesTab.runNowFailed"))}},children:e("settings.schedulesTab.actions.runNow")}),r.jsx(Y,{size:"small",onClick:async()=>{c(S=>({...S,open:!0,scheduleId:T.id,loading:!0,sessions:[]}));try{const S=await Os.listScheduleSessions(T.id);c(L=>({...L,open:!0,scheduleId:T.id,loading:!1,sessions:(S.sessions||[]).map($=>({id:$.id,title:$.title,updated_at:$.updated_at}))}))}catch(S){console.error("[Schedules] Failed to list sessions:",S),t.error(e("settings.schedulesTab.loadSessionsFailed")),c(L=>({...L,loading:!1}))}},children:e("settings.schedulesTab.actions.sessions")}),r.jsx(Y,{size:"small",onClick:async()=>{u(S=>({...S,open:!0,scheduleId:T.id,loading:!0,runs:[]}));try{const S=await Os.listScheduleRuns(T.id);u(L=>({...L,open:!0,scheduleId:T.id,loading:!1,runs:S.runs||[]}))}catch(S){console.error("[Schedules] Failed to list runs:",S),t.error(e("settings.schedulesTab.loadRunsFailed")),u(L=>({...L,loading:!1}))}},children:e("settings.schedulesTab.actions.runs")}),r.jsx(Y,{danger:!0,size:"small",onClick:async()=>{try{await Os.deleteSchedule(T.id),t.success(e("settings.schedulesTab.deleted")),await w()}catch(S){console.error("[Schedules] Failed to delete:",S),t.error(e("settings.schedulesTab.deleteFailed"))}},children:e("settings.schedulesTab.actions.delete")})]}),r.jsxs(G,{gap:8,align:"center",wrap:"wrap",children:[r.jsx(yt,{type:"secondary",children:e("settings.schedulesTab.columns.intervalSeconds")}),T.trigger.type==="interval"?P:r.jsx(ke,{title:e("settings.schedulesTab.nonIntervalReadOnly"),children:r.jsx("span",{children:P})})]})]})}}],[f,t,w,e]);return r.jsxs(G,{vertical:!0,gap:16,children:[s,r.jsx(ee,{title:e("settings.schedulesTab.createTitle"),className:"lotus-settings-card",children:r.jsxs(Z,{form:y,layout:"vertical",initialValues:{name:e("settings.schedulesTab.defaultName"),trigger_type:"interval",interval_seconds:3600,daily_hour:9,daily_minute:0,weekly_weekdays:["mon"],weekly_hour:9,weekly_minute:0,monthly_days:"1",monthly_hour:9,monthly_minute:0,cron_expr:"",timezone:"",start_at:"",end_at:"",enabled:!1,task_message:"",model:"",auto_execute:!0,misfire_policy:"run_once",overlap_policy:"queue_one",catch_up_window_max_runs:1,catch_up_window_max_lateness_seconds:60},onFinish:async M=>{try{const T=!!M.auto_execute,P=pt(M.task_message),S=pt(M.model);if(T&&!P){t.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:L,errorKey:$}=qm(M);if(!L){t.error(e($||"settings.schedulesTab.validation.triggerRequired"));return}await Os.createSchedule({name:String(M.name||"").trim(),trigger:L,timezone:pt(M.timezone),start_at:pt(M.start_at),end_at:pt(M.end_at),misfire_policy:Hm(M),overlap_policy:M.overlap_policy,enabled:!!M.enabled,run_config:{system_prompt:pt(M.system_prompt),task_message:P,model:S,workspace_path:pt(M.workspace_path),enhance_prompt:pt(M.enhance_prompt),auto_execute:T}}),t.success(e("settings.schedulesTab.created")),y.resetFields(),await w()}catch(T){console.error("[Schedules] Failed to create schedule:",T),t.error(e("settings.schedulesTab.createFailed"))}},children:[j(v,b),r.jsx(Y,{type:"primary",htmlType:"submit",children:e("settings.schedulesTab.actions.create")})]})}),r.jsx(ee,{title:e("settings.schedulesTab.listTitle"),className:"lotus-settings-card",extra:r.jsx(Y,{onClick:()=>void w(),loading:n,children:e("settings.schedulesTab.actions.refresh")}),children:r.jsx(qs,{rowKey:"id",columns:R,dataSource:a,loading:n,pagination:{pageSize:10},scroll:{x:1500}})}),r.jsx(Lt,{title:e("settings.schedulesTab.scheduleSessionsTitle"),open:l.open,onCancel:()=>c(M=>({...M,open:!1,scheduleId:null})),footer:null,children:l.loading?r.jsx(yt,{type:"secondary",children:e("settings.schedulesTab.loading")}):r.jsx(G,{vertical:!0,gap:8,children:l.sessions.length===0?r.jsx(yt,{type:"secondary",children:e("settings.schedulesTab.noSessionsYet")}):l.sessions.map(M=>r.jsxs(G,{justify:"space-between",align:"center",children:[r.jsxs(G,{vertical:!0,style:{minWidth:0},children:[r.jsx(yt,{strong:!0,ellipsis:!0,children:M.title}),r.jsxs(yt,{type:"secondary",ellipsis:!0,children:[M.id," • ",M.updated_at]})]}),r.jsx(Y,{size:"small",onClick:()=>{Yi(M.id,{forceRefreshIndex:!0,forceLoadHistory:!0,subscribeIfRunning:!0,forceSubscribe:!0}),g()},children:e("settings.schedulesTab.actions.open")})]},M.id))})}),r.jsx(Lt,{title:e("settings.schedulesTab.scheduleRunsTitle"),open:d.open,onCancel:()=>u(M=>({...M,open:!1,scheduleId:null})),footer:null,width:960,children:d.loading?r.jsx(yt,{type:"secondary",children:e("settings.schedulesTab.loading")}):d.runs.length===0?r.jsx(yt,{type:"secondary",children:e("settings.schedulesTab.noRunsYet")}):r.jsx(qs,{rowKey:"run_id",pagination:{pageSize:8},dataSource:d.runs,columns:[{title:e("settings.schedulesTab.runHistory.columns.status"),key:"status",render:(M,T)=>r.jsx(oe,{color:zT(T.status),children:T.status})},{title:e("settings.schedulesTab.runHistory.columns.scheduledFor"),dataIndex:"scheduled_for",key:"scheduled_for"},{title:e("settings.schedulesTab.runHistory.columns.startedAt"),key:"started_at",render:(M,T)=>T.started_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.completedAt"),key:"completed_at",render:(M,T)=>T.completed_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.session"),key:"session_id",render:(M,T)=>T.session_id||"-"},{title:e("settings.schedulesTab.runHistory.columns.duration"),key:"execution_duration_ms",render:(M,T)=>T.execution_duration_ms!=null?`${T.execution_duration_ms}ms`:"-"},{title:e("settings.schedulesTab.runHistory.columns.outcome"),key:"outcome_reason",render:(M,T)=>T.outcome_reason||(T.was_catch_up?"catch-up":"-")}]})}),r.jsx(Lt,{title:e("settings.schedulesTab.editTitle"),open:h.open,onCancel:()=>p({open:!1,schedule:null,saving:!1}),okText:e("settings.schedulesTab.actions.save"),confirmLoading:h.saving,onOk:()=>f.submit(),children:r.jsx(Z,{form:f,layout:"vertical",onFinish:async M=>{const T=h.schedule;if(!T)return;const P=!!M.auto_execute,S=pt(M.task_message),L=pt(M.model);if(P&&!S){t.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:$,errorKey:I}=qm(M);if(!$){t.error(e(I||"settings.schedulesTab.validation.triggerRequired"));return}p(W=>({...W,saving:!0}));try{await Os.patchSchedule(T.id,{name:String(M.name||"").trim()||void 0,enabled:!!M.enabled,trigger:$,timezone:pt(M.timezone),start_at:pt(M.start_at),end_at:pt(M.end_at),misfire_policy:Hm(M),overlap_policy:M.overlap_policy,run_config:{system_prompt:pt(M.system_prompt),task_message:S,model:L,workspace_path:pt(M.workspace_path),enhance_prompt:pt(M.enhance_prompt),auto_execute:P}}),t.success(e("settings.schedulesTab.updated")),p({open:!1,schedule:null,saving:!1}),await w()}catch(W){console.error("[Schedules] Failed to patch schedule:",W),t.error(e("settings.schedulesTab.updateFailed")),p(A=>({...A,saving:!1}))}},children:j(x,_)})})]})}const{Text:qr}=le,Hr=rs.getInstance();function JT(){const{t:e}=ne(),{modal:t,message:s}=Ot.useApp(),n=N(y=>y.chats),o=N(y=>y.currentSessionId),a=N(y=>y.refreshChats),i=N(y=>y.loadChats),l=N(y=>y.loadChatHistory),[c,d]=m.useState(!0),[u,h]=m.useState(!1),p=m.useMemo(()=>o?n.find(y=>y.id===o)??null:null,[n,o]),g=async y=>{if(!u){h(!0);try{await y()}finally{h(!1)}}};return r.jsxs(G,{vertical:!0,gap:16,children:[r.jsx(ee,{size:"small",title:e("settings.sessionsTab.currentSessionTitle"),children:p?r.jsxs(G,{vertical:!0,gap:4,children:[r.jsx(qr,{strong:!0,ellipsis:!0,children:p.title}),r.jsxs(qr,{type:"secondary",ellipsis:!0,children:[e("settings.sessionsTab.id"),": ",p.id," ","•"," ",e("settings.sessionsTab.kind"),": ",p.kind]}),r.jsx(G,{gap:8,wrap:"wrap",style:{marginTop:8},children:r.jsx(Y,{danger:!0,loading:u,onClick:()=>{t.confirm({title:e("settings.sessionsTab.clearMessagesTitle"),content:e("settings.sessionsTab.clearMessagesContent"),okText:e("settings.sessionsTab.clear"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await g(async()=>{await Hr.clearSession(p.id),await l(p.id),await a(),s.success(e("settings.sessionsTab.sessionCleared"))})}})},children:e("settings.sessionsTab.clearMessages")})})]}):r.jsx(qr,{type:"secondary",children:e("settings.sessionsTab.noActiveSession")})}),r.jsxs(ee,{size:"small",title:e("settings.sessionsTab.bulkCleanupTitle"),children:[r.jsxs(G,{align:"center",gap:8,style:{marginBottom:12},children:[r.jsx(qr,{children:e("settings.sessionsTab.keepPinned")}),r.jsx(it,{checked:c,onChange:d})]}),r.jsxs(G,{gap:8,wrap:"wrap",children:[r.jsx(Y,{danger:!0,loading:u,onClick:()=>{t.confirm({title:e("settings.sessionsTab.deleteAllTitle"),content:e(c?"settings.sessionsTab.deleteAllKeepPinned":"settings.sessionsTab.deleteAllIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await g(async()=>{await Hr.cleanupSessions("all",c),await i(),s.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteAll")}),r.jsx(Y,{danger:!0,loading:u,onClick:()=>{t.confirm({title:e("settings.sessionsTab.deleteEmptyTitle"),content:e(c?"settings.sessionsTab.deleteEmptyKeepPinned":"settings.sessionsTab.deleteEmptyIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await g(async()=>{await Hr.cleanupSessions("empty",c),await i(),s.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteEmpty")}),r.jsx(Y,{danger:!0,loading:u,onClick:()=>{t.confirm({title:e("settings.sessionsTab.deleteChildrenTitle"),content:e(c?"settings.sessionsTab.deleteChildrenKeepPinned":"settings.sessionsTab.deleteChildrenIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await g(async()=>{await Hr.cleanupSessions("children",c),await i(),s.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteChildren")})]})]}),r.jsxs(ee,{size:"small",title:e("settings.sessionsTab.devResetTitle"),children:[r.jsx(qr,{type:"secondary",children:e("settings.sessionsTab.devResetDescription")}),r.jsx(G,{style:{marginTop:12},children:r.jsx(Y,{danger:!0,type:"primary",loading:u,onClick:()=>{t.confirm({title:e("settings.sessionsTab.devResetConfirmTitle"),content:e("settings.sessionsTab.devResetConfirmContent"),okText:e("settings.sessionsTab.reset"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await g(async()=>{await Hr.devResetSessions(),await i(),s.success(e("settings.sessionsTab.devResetDone"))})}})},children:e("settings.sessionsTab.devResetAction")})})]})]})}const{Text:Na,Paragraph:QT}=le,ZT=({open:e,onCancel:t,onComplete:s,onCopyCode:n,completingAuth:o,copiedUserCode:a,deviceCodeInfo:i,timeRemaining:l,token:c})=>{const{t:d}=ne();return r.jsx(Lt,{title:d("settings.providerTab.copilotAuthModalTitle"),open:e,onCancel:t,footer:[r.jsx(Y,{onClick:t,children:d("settings.providerTab.cancel")},"cancel"),r.jsx(Y,{type:"primary",onClick:s,loading:o,children:d("settings.providerTab.completedAuthorization")},"complete")],children:i&&r.jsxs(X,{direction:"vertical",size:"large",style:{width:"100%"},children:[r.jsx(Xe,{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(ee,{size:"small",className:"lotus-settings-card",children:r.jsxs(X,{direction:"vertical",style:{width:"100%"},children:[r.jsx(Na,{type:"secondary",children:d("settings.providerTab.visitUrl")}),r.jsx(X,{children:r.jsx(Na,{copyable:{text:i.verification_uri},children:i.verification_uri})})]})}),r.jsx(ee,{style:{textAlign:"center",background:c.colorFillTertiary,borderColor:c.colorBorderSecondary},children:r.jsxs(X,{direction:"vertical",style:{width:"100%"},children:[r.jsx(Na,{type:"secondary",children:d("settings.providerTab.enterCode")}),r.jsxs(X,{children:[r.jsx(Na,{style:{color:c.colorText,fontSize:"32px",fontFamily:"monospace",fontWeight:"bold",letterSpacing:"4px"},children:i.user_code}),r.jsx(Y,{icon:a?r.jsx(Hs,{}):r.jsx(ss,{}),onClick:n,type:a?"default":"primary",children:d(a?"settings.providerTab.copied":"settings.providerTab.copyCode")})]}),r.jsx("div",{style:{marginTop:8},children:r.jsxs(oe,{color:l<60?"error":l<180?"warning":"success",children:[r.jsx(Ys,{style:{marginRight:4}}),"Expires in ",Math.floor(l/60),":",(l%60).toString().padStart(2,"0")]})})]})}),r.jsx(QT,{type:"secondary",children:d("settings.providerTab.afterContinueHint")})]})})},jl={copilot:"GitHub Copilot",openai:"OpenAI",anthropic:"Anthropic",gemini:"Google Gemini",bodhi:"Bodhi"},ek=[{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"}],tk=[{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"}],sk=[{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"}],nk=[{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4o-mini",label:"GPT-4o Mini"}],{Option:rk}=Pe,nr=({provider:e,value:t,onChange:s,disabled:n,placeholder:o})=>{const{t:a}=ne(),i=Ee(c=>c.catalog);m.useEffect(()=>{i||Ee.getState().loadCatalog()},[i]);const l=m.useMemo(()=>i!=null&&i.models?i.models.filter(c=>c.reference.provider===e):[],[i,e]);return r.jsx(Pe,{value:t,onChange:s,disabled:n,placeholder:o,allowClear:!0,showSearch:!0,notFoundContent:l.length===0?r.jsx("span",{children:a("settings.providerTab.noCatalogModels")}):null,children:l.map(c=>r.jsx(rk,{value:c.reference.model,children:r.jsxs(X,{size:4,children:[r.jsx("span",{children:c.display_name}),c.capabilities.supports_vision&&r.jsx(oe,{color:"blue",style:{fontSize:11,lineHeight:"18px",padding:"0 4px"},children:a("settings.providerTab.capabilityVision")}),c.capabilities.supports_tools&&r.jsx(oe,{color:"green",style:{fontSize:11,lineHeight:"18px",padding:"0 4px"},children:a("settings.providerTab.capabilityTools")}),c.capabilities.supports_reasoning&&r.jsx(oe,{color:"orange",style:{fontSize:11,lineHeight:"18px",padding:"0 4px"},children:a("settings.providerTab.capabilityReasoning")})]})},c.reference.model))})},{Password:Ym}=me,{Text:rn,Paragraph:Cl}=le,Ba=["openai","anthropic","gemini","copilot","bodhi"],Xm=e=>r.jsxs(X,{direction:"vertical",size:4,children:[r.jsxs(rn,{type:"secondary",children:[e("settings.providerTab.responsesOnlyHelp1")," ",r.jsx(rn,{code:!0,children:"/responses"}),"."]}),r.jsx(rn,{type:"secondary",children:e("settings.providerTab.responsesOnlyHelp2")})]}),ok=()=>{const{t:e}=ne(),{token:t}=he.useToken(),[s]=Z.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),[g,y]=m.useState(!1),[f,v]=m.useState(!1),[b,x]=m.useState(null),[_,w]=m.useState(!1),[k,C]=m.useState(!1),[E,j]=m.useState(0),[R,M]=m.useState(!1),[T,P]=m.useState([]),[S,L]=m.useState(!1),[$,I]=m.useState("idle"),[W,A]=m.useState(null);m.useEffect(()=>{if($!=="success")return;const J=setTimeout(()=>{I("idle"),A(null)},2e3);return()=>clearTimeout(J)},[$]),m.useEffect(()=>{if(!_||!b){j(0);return}j(b.expires_in);const J=setInterval(()=>{j(re=>re<=1?(clearInterval(J),0):re-1)},1e3);return()=>clearInterval(J)},[_,b]);const O=m.useCallback(async()=>{try{o(!0);const J=await It.getProviderConfig(),re={provider:J.provider,providers:J.providers||{},features:J.features};if(re.provider==="copilot"){const Q=re.providers.copilot??{};Q.model||(re.providers.copilot={...Q,model:"gpt-4o"})}st("[Provider]","Loaded provider config:",re);const V={...re.providers||{}};Ba.forEach(Q=>{const se=V[Q];se&&se.request_overrides&&typeof se.request_overrides=="object"&&(se.request_overrides_json=JSON.stringify(se.request_overrides,null,2))}),c(re.provider),s.setFieldsValue({...re,providers:V}),u(!0)}catch(J){fe.error(e("settings.providerTab.loadConfigFailed")),console.error("Failed to load provider config:",J)}finally{o(!1)}},[s,e]),D=m.useCallback(async()=>{try{const J=await It.getEnvVars();P(J.entries||[])}catch(J){console.warn("Failed to load env vars for provider overrides:",J)}},[]),H=m.useCallback(async()=>{try{y(!0);const J=await It.getCopilotAuthStatus();p(J)}catch(J){console.error("Failed to check Copilot auth status:",J),p({authenticated:!1,message:e("settings.providerTab.checkStatusFailed")})}finally{y(!1)}},[e]);m.useEffect(()=>{O(),D(),Ee.getState().loadCatalog(),H()},[O,D,H]);const B=async()=>{try{v(!0);const J=await It.startCopilotAuth();x(J),w(!0)}catch(J){fe.error(e("settings.providerTab.startCopilotAuthFailed")),console.error("Failed to start Copilot authentication:",J)}finally{v(!1)}},K=async()=>{if(b)try{C(!0),await It.completeCopilotAuth({device_code:b.device_code,interval:b.interval||5,expires_in:b.expires_in}),fe.success(e("settings.providerTab.copilotAuthSuccess")),w(!1),x(null),await H()}catch(J){fe.error(e("settings.providerTab.completeAuthFailed")),console.error("Authentication completion failed:",J)}finally{C(!1)}},F=async()=>{if(b)try{await os(b.user_code),M(!0),fe.success(e("settings.providerTab.userCodeCopied")),setTimeout(()=>M(!1),2e3)}catch{fe.error(`${e("settings.providerTab.copyCodeFailedPrefix")} ${b.user_code}`)}},z=async()=>{try{v(!0),await It.logoutCopilot(),fe.success(e("settings.providerTab.logoutSuccess")),await H()}catch(J){fe.error(e("settings.providerTab.logoutFailed")),console.error("Failed to logout:",J)}finally{v(!1)}},de=m.useCallback(async()=>{L(!0);try{const J=await It.fetchCatalogModels();await Ee.getState().loadCatalog();const re=J.fetched.filter(Q=>Q.models&&Q.models.length>0).length;J.fetched.filter(Q=>Q.error).length>0?fe.warning(e("settings.providerTab.fetchModelsPartialSuccess",{success:re,total:J.fetched.length})):fe.success(e("settings.providerTab.fetchModelsSuccess",{count:re}))}catch{fe.error(e("settings.providerTab.fetchModelsFailed"))}finally{L(!1)}},[e]),Te=J=>Tv(J)||J instanceof Error?J.message:e("settings.providerTab.unknownError"),$e=J=>{s.setFields([{name:["provider"],errors:[]},{name:["providers",J,"api_key"],errors:[]},{name:["providers",J,"model"],errors:[]}])},De=J=>{const re=J.trim();return re?re.includes(".")?re.split(".").filter(Boolean):re==="provider"?["provider"]:re==="provider/providers"?["provider"]:null:null},be=(J,re)=>{if(!J.length)return;const V=J.map(Q=>{const se=De(Q.path);return se?{name:se,errors:[Q.message]}:Q.message.toLowerCase().includes("api key")?{name:["providers",re,"api_key"],errors:[Q.message]}:{name:["provider"],errors:[Q.message]}}).filter((Q,se,ce)=>ce.findIndex(Ie=>JSON.stringify(Ie.name)===JSON.stringify(Q.name))===se);V.length&&s.setFields(V)},ye=async J=>{var V;const re=J.provider||l;$e(re);try{const se=await fs.getInstance().validateBambooConfigPatch({provider:J.provider,providers:J.providers||{}});if(se.valid)return{valid:!0};const ce=((V=se.errors)==null?void 0:V.provider)||[];be(ce,re);const Ie=ce[0];return{valid:!1,message:(Ie==null?void 0:Ie.message)||e("settings.providerTab.invalidConfig")}}catch(Q){return console.warn("Config validation failed, falling back to save:",Q),{valid:!0}}},je=async(J,re)=>{try{o(!0);const V={provider:J.provider,providers:{...J.providers||{}},features:J.features},Q=V.providers;for(const Ie of Ba){const Je=Q[Ie];if(!Je)continue;const _t=Je.request_overrides_json;if(typeof _t!="string")continue;const jt=_t.trim();if(!jt)delete Je.request_overrides;else try{Je.request_overrides=JSON.parse(jt)}catch(Ct){const Tt=`Invalid request_overrides JSON for ${Ie}: ${Ct.message}`;if(s.setFields([{name:["providers",Ie,"request_overrides_json"],errors:[Tt]}]),(re==null?void 0:re.showMessage)!==!1&&fe.error(Tt),re!=null&&re.throwOnError)throw Ct;return}delete Je.request_overrides_json}const se={provider:V.provider,providers:V.providers||{},features:V.features},ce=await ye(V);if(!ce.valid){const Ie=ce.message||e("settings.providerTab.invalidConfig");if((re==null?void 0:re.showMessage)!==!1&&fe.error(`${e("settings.providerTab.invalidConfigPrefix")}: ${Ie}`),re!=null&&re.throwOnError)throw new Error(Ie);return}st("[Provider]","Saving provider config:",se),await It.saveProviderConfig(se),(re==null?void 0:re.showMessage)!==!1&&fe.success(e("settings.providerTab.saveConfigSuccess"))}catch(V){const Q=Te(V);if((re==null?void 0:re.showMessage)!==!1&&fe.error(Q?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${Q}`:e("settings.providerTab.saveConfigFailed")),console.error("Failed to save configuration:",V),re!=null&&re.throwOnError)throw V}finally{o(!1)}},Ue=async J=>{try{i(!0);const{useProviderStore:re}=await Dt(async()=>{const{useProviderStore:V}=await Promise.resolve().then(()=>Mv);return{useProviderStore:V}},void 0,import.meta.url);await re.getState().loadProviderConfig(),(J==null?void 0:J.showMessage)!==!1&&fe.success(e("settings.providerTab.applyConfigSuccess"))}catch(re){const V=Te(re);if((J==null?void 0:J.showMessage)!==!1&&fe.error(V?`${e("settings.providerTab.applyConfigErrorPrefix")}: ${V}`:e("settings.providerTab.applyConfigFailed")),console.error("Failed to apply configuration:",re),J!=null&&J.throwOnError)throw re}finally{i(!1)}},ht=async J=>{try{await je(J,{throwOnError:!0}),await Ue({throwOnError:!0})}catch{}},Ge=async(J,re)=>{if(re&&$!=="saving"){I("saving"),A(null);try{const V=s.getFieldsValue(!0),Q=V.providers||{},se=Q;se[J]={...se[J]??{},model:re},V.providers=Q,await je(V,{showMessage:!1,throwOnError:!0}),await Ue({showMessage:!1,throwOnError:!0}),I("success"),fe.success(e("settings.providerTab.modelUpdated"))}catch(V){const Q=Te(V);I("error"),A(Q),fe.error(Q?`${e("settings.providerTab.updateModelErrorPrefix")}: ${Q}`:e("settings.providerTab.updateModelFailed"))}}},wt=async(J,re,V)=>{if($!=="saving"){I("saving"),A(null);try{const Q=s.getFieldsValue(!0),se=Q.providers||{},ce=se;ce[J]={...ce[J]??{},[re]:V||void 0},Q.providers=se,await je(Q,{showMessage:!1,throwOnError:!0}),await Ue({showMessage:!1,throwOnError:!0}),I("success"),fe.success(e("settings.providerTab.modelUpdated"))}catch(Q){const se=Te(Q);I("error"),A(se),fe.error(se?`${e("settings.providerTab.updateModelErrorPrefix")}: ${se}`:e("settings.providerTab.updateModelFailed"))}}},U=m.useCallback(J=>{const re=s.getFieldValue(["providers",J]);return re?J==="copilot"?(h==null?void 0:h.authenticated)??!1:!!re.api_key:!1},[s,h]),_e=J=>r.jsxs(r.Fragment,{children:[r.jsx(Z.Item,{name:["providers",J,"fast_model"],label:e("settings.providerTab.fastModel"),extra:r.jsx(rn,{type:"secondary",children:e("settings.providerTab.fastModelHelp")}),children:r.jsx(nr,{provider:J,disabled:$==="saving",placeholder:e("settings.providerTab.sameAsDefault"),onChange:re=>wt(J,"fast_model",re)})}),r.jsx(Z.Item,{name:["providers",J,"vision_model"],label:e("settings.providerTab.visionModel"),extra:r.jsx(rn,{type:"secondary",children:e("settings.providerTab.visionModelHelp")}),children:r.jsx(nr,{provider:J,disabled:$==="saving",placeholder:e("settings.providerTab.sameAsDefault"),onChange:re=>wt(J,"vision_model",re)})})]}),Ce=J=>{const re=T.map(Q=>Q.name);return r.jsx(Z.Item,{name:["providers",J,"request_overrides_json"],label:"Advanced Request Overrides (JSON)",extra:r.jsxs(X,{direction:"vertical",size:4,children:[r.jsx(rn,{type:"secondary",children:"Customize provider request headers/body patch rules."}),r.jsxs(rn,{type:"secondary",children:["Env var injection:"," ",r.jsx(rn,{code:!0,children:'{ "type": "env_ref", "name": "YOUR_ENV_NAME" }'})]}),re.length>0&&r.jsx(X,{wrap:!0,size:[6,6],children:re.map(Q=>r.jsx(oe,{children:Q},Q))})]}),children:r.jsx(me.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"}})})},Ve=J=>{switch(J){case"openai":return r.jsxs(r.Fragment,{children:[r.jsx(Z.Item,{name:["providers","openai","api_key"],label:e("settings.providerTab.openaiApiKey"),rules:[{required:!0,message:e("settings.providerTab.openaiApiKeyRequired")}],children:r.jsx(me.Password,{"data-testid":"api-key-input",placeholder:"sk-...",prefix:r.jsx(ja,{})})}),r.jsx(Z.Item,{name:["providers","openai","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.openaiBaseUrlHelp"),children:r.jsx(me,{placeholder:"https://api.openai.com/v1"})}),r.jsx(Z.Item,{name:["providers","openai","model"],label:e("settings.providerTab.defaultModel"),rules:[{required:!0,message:e("settings.providerTab.selectModelRequired")}],children:r.jsx(nr,{provider:"openai",disabled:$==="saving",placeholder:e("settings.providerTab.selectModel"),onChange:re=>Ge("openai",re)})}),r.jsx(Z.Item,{name:["providers","openai","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:Xm(e),children:r.jsx(Pe,{mode:"tags",placeholder:'e.g. "gpt-5.3-codex", "gpt-5*"',tokenSeparators:[","," ",`
|
|
149
|
+
`," "]})}),r.jsx(Rt,{dashed:!0}),_e("openai"),Ce("openai")]});case"anthropic":return r.jsxs(r.Fragment,{children:[r.jsx(Z.Item,{name:["providers","anthropic","api_key"],label:e("settings.providerTab.anthropicApiKey"),rules:[{required:!0,message:e("settings.providerTab.anthropicApiKeyRequired")}],children:r.jsx(Ym,{placeholder:"sk-ant-...",prefix:r.jsx(ja,{})})}),r.jsx(Z.Item,{name:["providers","anthropic","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.anthropicBaseUrlHelp"),children:r.jsx(me,{placeholder:"https://api.anthropic.com/v1"})}),r.jsx(Z.Item,{name:["providers","anthropic","model"],label:e("settings.providerTab.defaultModel"),rules:[{required:!0,message:e("settings.providerTab.selectModelRequired")}],children:r.jsx(nr,{provider:"anthropic",disabled:$==="saving",placeholder:e("settings.providerTab.selectModel"),onChange:re=>Ge("anthropic",re)})}),r.jsx(Z.Item,{name:["providers","anthropic","max_tokens"],label:e("settings.providerTab.maxTokensOptional"),extra:e("settings.providerTab.maxTokensHelp"),children:r.jsx(me,{type:"number",placeholder:"4096",min:1,max:1e5})}),r.jsx(Rt,{dashed:!0}),_e("anthropic"),Ce("anthropic")]});case"gemini":return r.jsxs(r.Fragment,{children:[r.jsx(Z.Item,{name:["providers","gemini","api_key"],label:e("settings.providerTab.geminiApiKey"),rules:[{required:!0,message:e("settings.providerTab.geminiApiKeyRequired")}],children:r.jsx(Ym,{placeholder:"AIza...",prefix:r.jsx(ja,{})})}),r.jsx(Z.Item,{name:["providers","gemini","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.geminiBaseUrlHelp"),children:r.jsx(me,{placeholder:"https://generativelanguage.googleapis.com/v1beta"})}),r.jsx(Z.Item,{name:["providers","gemini","model"],label:e("settings.providerTab.defaultModel"),rules:[{required:!0,message:e("settings.providerTab.selectModelRequired")}],children:r.jsx(nr,{provider:"gemini",disabled:$==="saving",placeholder:e("settings.providerTab.selectModel"),onChange:re=>Ge("gemini",re)})}),r.jsx(Rt,{dashed:!0}),_e("gemini"),Ce("gemini")]});case"copilot":return r.jsxs(r.Fragment,{children:[r.jsxs(ee,{size:"small",style:{marginBottom:16},title:e("settings.providerTab.authStatusTitle"),extra:g?r.jsx(ps,{size:"small"}):h!=null&&h.authenticated?r.jsx(oe,{icon:r.jsx(Hs,{}),color:"success",children:e("settings.providerTab.authenticated")}):r.jsx(oe,{icon:r.jsx(rc,{}),color:"error",children:e("settings.providerTab.notAuthenticated")}),children:[(h==null?void 0:h.message)&&r.jsx(Cl,{type:"secondary",style:{marginBottom:16},children:h.message}),r.jsxs(X,{children:[h!=null&&h.authenticated?r.jsx(Y,{danger:!0,icon:r.jsx(px,{}),onClick:z,loading:f,children:e("settings.providerTab.logoutCopilot")}):r.jsx(Y,{type:"primary",icon:r.jsx(fx,{}),onClick:B,loading:f,children:e("settings.providerTab.authenticateCopilot")}),r.jsx(Y,{onClick:H,loading:g,children:e("settings.providerTab.refreshStatus")})]})]}),r.jsx(Z.Item,{name:["providers","copilot","headless_auth"],label:e("settings.providerTab.headlessAuth"),valuePropName:"checked",extra:e("settings.providerTab.headlessAuthHelp"),children:r.jsx(it,{})}),r.jsx(Z.Item,{name:["providers","copilot","model"],label:e("settings.providerTab.defaultModel"),rules:[{required:!0,message:e("settings.providerTab.selectModelRequired")}],children:r.jsx(nr,{provider:"copilot",disabled:$==="saving",placeholder:e("settings.providerTab.selectModel"),onChange:re=>Ge("copilot",re)})}),r.jsx(Z.Item,{name:["providers","copilot","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:Xm(e),children:r.jsx(Pe,{mode:"tags",placeholder:'e.g. "gpt-5.3-codex", "gpt-5*"',tokenSeparators:[","," ",`
|
|
150
|
+
`," "]})}),r.jsx(Rt,{dashed:!0}),_e("copilot"),Ce("copilot"),r.jsxs(Cl,{type:"secondary",children:[e("settings.providerTab.copilotUsageTitle"),r.jsxs("ul",{style:{marginTop:8,marginBottom:0},children:[r.jsx("li",{children:e("settings.providerTab.copilotUsageStep1")}),r.jsx("li",{children:e("settings.providerTab.copilotUsageStep2")}),r.jsx("li",{children:e("settings.providerTab.copilotUsageStep3")})]})]})]});case"bodhi":return r.jsxs(r.Fragment,{children:[r.jsx(Z.Item,{name:["providers","bodhi","api_key"],label:"Bodhi API Key",rules:[{required:!0,message:"API key is required"}],children:r.jsx(me.Password,{"data-testid":"bodhi-api-key-input",placeholder:"bhi_sk_...",prefix:r.jsx(ja,{})})}),r.jsx(Z.Item,{name:["providers","bodhi","base_url"],label:"Base URL",extra:"Your Bodhi Server endpoint address",children:r.jsx(me,{placeholder:"http://localhost:8080"})}),r.jsx(Z.Item,{name:["providers","bodhi","target_provider"],label:"Target Provider",extra:"Which upstream provider to route through Bodhi",children:r.jsxs(Pe,{placeholder:"openai",allowClear:!0,children:[r.jsx(Pe.Option,{value:"openai",children:"OpenAI"}),r.jsx(Pe.Option,{value:"anthropic",children:"Anthropic"}),r.jsx(Pe.Option,{value:"gemini",children:"Gemini"})]})}),r.jsx(Z.Item,{name:["providers","bodhi","reasoning_effort"],label:"Reasoning Effort (optional)",children:r.jsxs(Pe,{placeholder:"Default",allowClear:!0,children:[r.jsx(Pe.Option,{value:"low",children:"Low"}),r.jsx(Pe.Option,{value:"medium",children:"Medium"}),r.jsx(Pe.Option,{value:"high",children:"High"}),r.jsx(Pe.Option,{value:"xhigh",children:"Extra High"}),r.jsx(Pe.Option,{value:"max",children:"Max"})]})}),r.jsx(Rt,{dashed:!0}),Ce("bodhi")]});default:return null}},qe=J=>{const re=U(J),V=jl[J];return r.jsxs(X,{size:"small",children:[r.jsx("span",{style:{fontWeight:500},children:V}),re?r.jsx(oe,{color:"success",style:{fontSize:11},children:e("settings.providerTab.authenticated")}):r.jsx(oe,{color:"default",style:{fontSize:11},children:e("settings.providerTab.providerNotConfigured")})]})};return r.jsxs(ee,{title:e("settings.providerTab.title"),loading:n&&!d,className:"lotus-settings-card",children:[r.jsx(Cl,{type:"secondary",children:e("settings.providerTab.description")}),r.jsx(Rt,{}),r.jsxs(Z,{form:s,layout:"vertical",onFinish:ht,disabled:n&&!d,children:[r.jsx(Z.Item,{name:"provider",label:e("settings.providerTab.activeProvider"),rules:[{required:!0,message:e("settings.providerTab.selectProviderRequired")}],children:r.jsx(Pe,{"data-testid":"provider-select",size:"large",children:Object.keys(jl).map(J=>r.jsx(Pe.Option,{value:J,children:jl[J]},J))})}),r.jsx(Rt,{}),r.jsxs("div",{style:{marginBottom:16},children:[r.jsx(Y,{icon:r.jsx(Ms,{}),onClick:de,loading:S,children:e(S?"settings.providerTab.fetchingAllModels":"settings.providerTab.fetchAllModels")}),$==="saving"&&r.jsx(ps,{size:"small",style:{marginLeft:8}}),$==="success"&&r.jsx(Hs,{style:{color:"var(--lotus-chart-secondary)",marginLeft:8}}),$==="error"&&r.jsx(ke,{title:W,children:r.jsx(rc,{style:{color:"var(--lotus-chart-danger)",marginLeft:8}})})]}),r.jsx(ns,{defaultActiveKey:Ba.filter(J=>U(J)),ghost:!0,style:{marginBottom:16},children:Ba.map(J=>r.jsx(ns.Panel,{header:qe(J),children:Ve(J)},J))}),r.jsx(Rt,{}),r.jsx(X,{size:"middle",children:r.jsx(Y,{"data-testid":"save-api-settings",type:"primary",htmlType:"submit",icon:r.jsx(Di,{}),loading:n||a,size:"large",children:e("settings.providerTab.saveAndApply")})})]}),r.jsx(ZT,{open:_,onCancel:()=>w(!1),onComplete:K,onCopyCode:F,completingAuth:k,copiedUserCode:R,deviceCodeInfo:b,timeRemaining:E,token:t})]})},{Text:Vm}=le,ak=({skill:e,disabled:t=!1,busy:s=!1,onToggleDisabled:n})=>{const{t:o}=ne(),{token:a}=he.useToken();return r.jsx(ee,{title:r.jsxs(X,{size:a.marginXS,wrap:!0,style:{width:"100%",justifyContent:"space-between"},children:[r.jsxs(X,{size:a.marginXS,wrap:!0,children:[r.jsx("span",{children:e.name}),t&&r.jsx(oe,{color:"default",children:o("components.skillManager.disabledTag")}),e.license&&r.jsxs(oe,{color:"processing",children:["License: ",e.license]})]}),n&&r.jsx(it,{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(X,{direction:"vertical",size:a.marginXS,style:{width:"100%"},children:[r.jsx(Vm,{type:"secondary",children:e.description}),e.compatibility&&r.jsxs(Vm,{type:"secondary",children:["Compatibility: ",e.compatibility]}),e.tool_refs.length>0&&r.jsx(X,{size:a.marginXXS,wrap:!0,children:e.tool_refs.map(i=>r.jsx(oe,{style:{background:a.colorFillSecondary,borderColor:a.colorBorderSecondary,color:a.colorText},children:i},i))})]})})},ik=3e4,lk=()=>{const{t:e}=ne(),t=ms(C=>C.config),s=ms(C=>C.loadConfig),n=ms(C=>C.saveConfig),[o,a]=m.useState([]),[i,l]=m.useState(!1),[c,d]=m.useState(null),[u,h]=m.useState(null),[p,g]=m.useState(""),[y,f]=m.useState(new Date),v=m.useMemo(()=>{var C;return new Set((((C=t==null?void 0:t.skills)==null?void 0:C.disabled)??[]).map(E=>E.trim()).filter(Boolean))},[t]),b=m.useCallback(async(C=!0)=>{l(!0),d(null);try{const[E]=await Promise.all([lc.listSkills({includeDisabled:!0},C),s({force:C})]);a(E.skills),f(new Date)}catch(E){const j=E instanceof Error?E.message:e("components.skillManager.loadFailed");d(j)}finally{l(!1)}},[s,e]);m.useEffect(()=>{b(!0);const C=setInterval(()=>{b(!0)},ik);return()=>clearInterval(C)},[b]),m.useEffect(()=>{const C=()=>{b(!0)};return window.addEventListener("focus",C),()=>window.removeEventListener("focus",C)},[b]);const x=m.useCallback(async()=>{await b(!0),fe.success(e("components.skillManager.skillsRefreshed"))},[b,e]);m.useEffect(()=>{c&&(fe.error(c),d(null))},[c]);const _=m.useCallback(async(C,E)=>{var j;h(C);try{const R=await s({force:!0}),M=((j=R==null?void 0:R.skills)==null?void 0:j.disabled)??[],T=Array.from(new Set((E?[...M,C]:M.filter(P=>P!==C)).map(P=>P.trim()).filter(Boolean))).sort();await n({...R??{},skills:{...(R==null?void 0:R.skills)??{},disabled:T}}),fe.success(e("components.skillManager.skillStateSaved"))}catch(R){fe.error(R instanceof Error?R.message:e("components.skillManager.saveFailed"))}finally{h(null)}},[s,n,e]),w=o.filter(C=>{const E=p.trim().toLowerCase();return!(E&&![C.name,C.description,C.license??"",C.compatibility??"",...C.tool_refs].join(" ").toLowerCase().includes(E))}),k=()=>{const E=new Date().getTime()-y.getTime(),j=Math.floor(E/1e3);if(j<5)return e("components.skillManager.justNow");if(j<60)return e("components.skillManager.secondsAgo",{count:j});const R=Math.floor(j/60);return R<60?e("components.skillManager.minutesAgo",{count:R}):y.toLocaleTimeString()};return r.jsx("div",{style:{padding:"24px"},children:r.jsxs(ee,{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(Y,{icon:r.jsx(Ms,{spin:i}),onClick:x,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:k()})})]}),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(Gt,{style:{marginBottom:"24px"},children:r.jsx(me,{placeholder:e("components.skillManager.searchPlaceholder"),prefix:r.jsx(sa,{}),value:p,onChange:C=>g(C.target.value),allowClear:!0})}),r.jsx(ps,{spinning:i,children:w.length===0?r.jsx(kt,{description:e(p?"components.skillManager.noMatch":"components.skillManager.noSkillsFound")}):r.jsx(nt,{grid:{gutter:16,xs:1,sm:2,md:3,lg:3,xl:4},dataSource:w,renderItem:C=>r.jsx(nt.Item,{children:r.jsx(ak,{skill:C,disabled:v.has(C.id),busy:u===C.id,onToggleDisabled:_})})})})]})})},{Title:ck,Text:Ml,Paragraph:dk}=le,Km="model_limits",Fc="modelLimitsConfigs",Gm="defaultBudgetStrategy",Kt=1e3;function Jm(e){return[{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5.4-thinking",max_context_tokens:1e6,max_output_tokens:128e3,safety_margin:Kt,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:Kt,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:Kt,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:Kt,note:e("settings.modelLimits.defaults.gpt5Mini")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4.1",max_context_tokens:128e3,max_output_tokens:16384,safety_margin:Kt,note:e("settings.modelLimits.defaults.gpt41")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4o",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:Kt,note:e("settings.modelLimits.defaults.gpt4o")},{vendor:"Google",model_pattern:"gemini-2.5-pro",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:Kt,note:e("settings.modelLimits.defaults.gemini25Pro")},{vendor:"Moonshot",model_pattern:"kimi-k2.5",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:Kt,note:e("settings.modelLimits.defaults.kimiK25")},{vendor:"Moonshot",model_pattern:"kimi-for-coding",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:Kt,note:e("settings.modelLimits.defaults.kimiCoding")},{vendor:"Zhipu",model_pattern:"glm-5",max_context_tokens:2e5,max_output_tokens:128e3,safety_margin:Kt,note:e("settings.modelLimits.defaults.glm5")}]}function uk(e){return Array.isArray(e)?Kd(e):[]}function Qm(e,t){if(typeof e!="number"||!Number.isFinite(e))return t;const s=Math.floor(e);return s>0?s:t}function mk(e,t){if(typeof e!="number"||!Number.isFinite(e))return t;const s=Math.floor(e);return s>=0?s:t}function hk(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=Qm(t.max_context_tokens??t.maxContextTokens,128e3),o=Qm(t.max_output_tokens??t.maxOutputTokens,Math.min(4096,Math.floor(n/4))),a=mk(t.safety_margin??t.safetyMargin,Kt);return{vendor:typeof t.vendor=="string"&&t.vendor.trim()?t.vendor.trim():"",model_pattern:s.trim(),max_context_tokens:n,max_output_tokens:o,safety_margin:a,note:typeof t.note=="string"?t.note:""}}function Kd(e){return Array.isArray(e)?e.map(t=>hk(t)).filter(t=>!!t):[]}function pk(){const e=localStorage.getItem(Fc);if(!e)return[];try{const t=JSON.parse(e);return Kd(t)}catch{return[]}}function fk(e){const t=Object.prototype.hasOwnProperty.call(e,Km);return t?{hasModelLimitsKey:t,modelLimits:Kd(e[Km])}:{hasModelLimitsKey:!1,modelLimits:[]}}function gk(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 yk=()=>{const{t:e}=ne(),[t,s]=m.useState(()=>Jm(e)),[n,o]=m.useState(!1),[a,i]=fe.useMessage(),l=m.useCallback((f,v)=>{s(b=>b.map((x,_)=>_===f?{...x,...v}:x))},[]),c=m.useCallback(()=>{s(f=>[...f,{vendor:"",model_pattern:"",max_context_tokens:128e3,max_output_tokens:4096,safety_margin:Kt,note:""}])},[]),d=m.useCallback(f=>{s(v=>v.filter((b,x)=>x!==f))},[]),u=m.useCallback(async()=>{const f=Jm(e),v=await et.getModelLimitDefaults(),b=uk(v.model_limits);return b.length>0?b:f},[e]),h=m.useCallback(async()=>{o(!0);try{const f=await et.getBambooConfig(),{hasModelLimitsKey:v,modelLimits:b}=fk(f);if(b.length>0){s(b);return}if(v){s(await u());return}const x=pk();if(x.length>0){await et.setBambooConfig({model_limits:x}),localStorage.removeItem(Fc),localStorage.removeItem(Gm),s(x),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=gk(t,e);if(f){a.error(f);return}o(!0);try{await et.setBambooConfig({model_limits:t}),a.success(e("settings.modelLimits.saveSuccess"))}catch(v){console.error("Failed to save model limits settings:",v),a.error(e("settings.modelLimits.saveFailed"))}finally{o(!1)}},g=async()=>{o(!0);try{const f=await u();await et.setBambooConfig({model_limits:f}),s(f),localStorage.removeItem(Fc),localStorage.removeItem(Gm),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)}},y=m.useMemo(()=>[{title:e("settings.modelLimits.columns.vendor"),dataIndex:"vendor",key:"vendor",width:170,render:(f,v,b)=>r.jsx(me,{value:f,placeholder:e("settings.modelLimits.placeholders.vendor"),onChange:x=>l(b,{vendor:x.target.value})})},{title:e("settings.modelLimits.columns.model"),dataIndex:"model_pattern",key:"model_pattern",width:220,render:(f,v,b)=>r.jsx(me,{value:f,placeholder:e("settings.modelLimits.placeholders.model"),onChange:x=>l(b,{model_pattern:x.target.value})})},{title:e("settings.modelLimits.columns.contextWindow"),dataIndex:"max_context_tokens",key:"max_context_tokens",width:180,render:(f,v,b)=>r.jsx(rt,{value:f,onChange:x=>l(b,{max_context_tokens:Math.max(1e3,Number(x)||128e3)}),min:1e3,max:2e6,step:1e3,style:{width:"100%"}})},{title:e("settings.modelLimits.columns.maxOutput"),dataIndex:"max_output_tokens",key:"max_output_tokens",width:160,render:(f,v,b)=>r.jsx(rt,{value:f,onChange:x=>l(b,{max_output_tokens:Math.max(1,Number(x)||4096)}),min:1,max:2e6,step:256,style:{width:"100%"}})},{title:e("settings.modelLimits.columns.notes"),dataIndex:"note",key:"note",width:240,render:(f,v,b)=>r.jsx(me,{value:f,placeholder:e("settings.modelLimits.placeholders.optional"),onChange:x=>l(b,{note:x.target.value})})},{title:e("settings.modelLimits.columns.actions"),key:"actions",width:100,render:(f,v,b)=>r.jsx(Y,{danger:!0,size:"small",onClick:()=>d(b),children:e("settings.modelLimits.actions.remove")})}],[d,e,l]);return r.jsxs("div",{className:"model-limits-settings",children:[i,r.jsxs(ee,{children:[r.jsx(ck,{level:4,children:e("settings.modelLimits.title")}),r.jsxs(dk,{type:"secondary",children:[e("settings.modelLimits.descriptionPrefix")," ",r.jsx(Ml,{code:!0,children:"config.json"})," ",e("settings.modelLimits.descriptionSuffix")]}),r.jsx(Rt,{}),r.jsxs(X,{direction:"vertical",size:"small",style:{width:"100%"},children:[r.jsx(Ml,{strong:!0,children:e("settings.modelLimits.defaultsTitle")}),r.jsx(Ml,{type:"secondary",children:e("settings.modelLimits.defaultsDescription")})]}),r.jsx(qs,{dataSource:t,columns:y,rowKey:(f,v)=>`${f.model_pattern}-${v}`,pagination:!1,size:"small",style:{margin:"16px 0"},scroll:{x:1150}}),r.jsxs(X,{children:[r.jsx(Y,{onClick:c,children:e("settings.modelLimits.actions.addRow")}),r.jsx(Y,{type:"primary",icon:r.jsx(Di,{}),onClick:()=>void p(),loading:n,children:e("settings.modelLimits.actions.save")}),r.jsx(Y,{icon:r.jsx(Ms,{}),onClick:()=>void g(),loading:n,children:e("settings.modelLimits.actions.resetToDefaults")}),r.jsx(Y,{onClick:()=>void h(),loading:n,children:e("settings.modelLimits.actions.reload")})]})]})]})},zc="lotus_experience_mode_v1",Fy=new Set(["skills","hooks","masking","env-vars","metrics","sessions","config"]);function Zm(){try{const e=localStorage.getItem(zc);if(e==="simple"||e==="advanced")return e}catch{}return"advanced"}const Mi=un(e=>({mode:Zm(),isAdvanced:Zm()==="advanced",setMode:t=>{try{localStorage.setItem(zc,t)}catch{}e({mode:t,isAdvanced:t==="advanced"})},toggleMode:()=>e(t=>{const s=t.mode==="simple"?"advanced":"simple";try{localStorage.setItem(zc,s)}catch{}return{mode:s,isAdvanced:s==="advanced"}})})),{Text:Pl}=le,{useToken:bk}=he,xk="bamboo_dark_mode",vk=({themeMode:e,onThemeModeChange:t,locale:s,onLocaleChange:n,onBack:o})=>{const{t:a}=ne(),{token:i}=bk(),{deleteAllChats:l,autoGenerateTitles:c,setAutoGenerateTitlesPreference:d,isUpdatingAutoTitlePreference:u}=T_(),[h,p]=m.useState(!1),[g,y]=fe.useMessage(),[f,v]=m.useState(""),[b,x]=m.useState(Cc()),[_,w]=m.useState(Pc()),[k,C]=m.useState(ki()),[E,j]=m.useState(ji()),M=Ee(z=>z.currentProvider)==="copilot",T=Bs(z=>z.activeTabKey),P=Bs(z=>z.setActiveTabKey),S=Mi(z=>z.isAdvanced),L=i.paddingSM,$=(z,de)=>({key:z,label:r.jsx(Pl,{type:"secondary",style:{fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em",cursor:"default",userSelect:"none"},children:de}),disabled:!0,children:null}),I=(z,de)=>r.jsx("span",{"data-testid":`settings-tab-${z}`,children:de}),W=()=>{localStorage.clear(),g.success(a("settings.notifications.localStorageCleared"))},A=async()=>{p(!0);try{await l(),await et.resetSetupStatus(),await et.resetBambooConfig(),localStorage.clear(),g.success(a("settings.notifications.resetSuccessReloading")),setTimeout(()=>{window.location.reload()},1500)}catch(z){console.error("Failed to reset application:",z),g.error(z instanceof Error?z.message:a("settings.notifications.resetFailed")),p(!1)}},O=async z=>{try{await d(z),g.success(a(z?"settings.notifications.autoTitleEnabled":"settings.notifications.autoTitleDisabled"))}catch{g.error(a("settings.notifications.autoTitleUpdateFailed"))}},D=()=>{v_(f),g.success(a("settings.notifications.promptEnhancementSaved"))},H=z=>{x(z),l_(z)},B=z=>{w(z),u_(z)},K=z=>{C(z),f_(z)},F=z=>{j(z),k_(z),window.dispatchEvent(new Event("lotus-vdi-safe-mode-change")),g.success(z?a("settings.appTab.vdiSafeModeEnabled","Graphics compatibility mode enabled"):a("settings.appTab.vdiSafeModeDisabled","Graphics compatibility mode disabled"))};return m.useEffect(()=>{v(jy()),x(Cc()),w(Pc()),C(ki()),j(ji())},[]),r.jsxs(G,{vertical:!0,role:"region","aria-label":a("settings.page.title"),style:{height:"100vh",overflow:"hidden",background:i.colorBgContainer},children:[y,r.jsxs(G,{align:"center",justify:"space-between",style:{padding:i.padding,paddingTop:i.padding+L,borderBottom:`1px solid ${i.colorBorderSecondary}`},children:[r.jsxs(G,{align:"center",gap:i.marginSM,children:[r.jsx(Y,{icon:r.jsx(gx,{}),onClick:o,"aria-label":a("settings.page.back"),children:a("settings.page.back")}),r.jsx(Pl,{strong:!0,"data-testid":"settings-page-title",children:a("settings.page.title")})]}),r.jsxs(Pl,{type:"secondary","data-testid":"settings-page-version",children:[a("settings.appTab.runningVersion","Running version"),": v",xd]})]}),r.jsx(Dn.Content,{style:{flex:1,minHeight:0,overflow:"auto",padding:i.padding},children:r.jsx(ui,{tabPosition:"left",activeKey:T,onChange:z=>P(z),items:[$("group-ai",a("settings.page.groups.ai")),{key:"provider",label:I("provider",a("settings.page.tabs.provider")),children:r.jsx(ok,{})},{key:"model-limits",label:I("model-limits",a("settings.page.tabs.modelLimits")),children:r.jsx(yk,{})},{key:"prompts",label:I("prompts",a("settings.page.tabs.prompts")),children:r.jsx(B_,{promptEnhancement:f,onPromptEnhancementChange:v,mermaidEnhancementEnabled:b,taskEnhancementEnabled:_,showCopilotConclusionWithOptionsEnhancement:M,copilotConclusionWithOptionsEnhancementEnabled:k,onMermaidToggle:H,onTaskToggle:B,onCopilotConclusionWithOptionsToggle:K,onSaveEnhancement:D})},$("group-tools",a("settings.page.groups.toolsAndExtensions")),{key:"skills",label:I("skills",a("settings.page.tabs.skills")),children:r.jsx(lk,{})},{key:"mcp",label:I("mcp",a("settings.page.tabs.mcp")),children:r.jsx(Y0,{})},{key:"workflows",label:I("workflows",a("settings.page.tabs.workflows")),children:r.jsx(o0,{})},{key:"hooks",label:I("hooks",a("settings.page.tabs.hooks")),children:r.jsx(FT,{})},$("group-security",a("settings.page.groups.securityAndPrivacy")),{key:"masking",label:I("masking",a("settings.page.tabs.masking")),children:r.jsx(Q_,{})},{key:"env-vars",label:I("env-vars",a("settings.page.tabs.envVars")),children:r.jsx(t0,{})},$("group-monitoring",a("settings.page.groups.monitoring")),{key:"metrics",label:I("metrics",a("settings.page.tabs.metrics")),children:r.jsx($T,{})},{key:"sessions",label:I("sessions",a("settings.page.tabs.sessions")),children:r.jsx(JT,{})},$("group-system",a("settings.page.groups.system")),{key:"config",label:I("config",a("settings.page.tabs.config")),children:r.jsx(I_,{msgApi:g,locale:s,onLocaleChange:n})},{key:"schedules",label:I("schedules",a("settings.page.tabs.schedules")),children:r.jsx(GT,{})},{key:"app",label:I("app",a("settings.page.tabs.app")),children:r.jsx(K_,{autoGenerateTitles:c,isUpdatingAutoTitlePreference:u,onAutoTitleToggle:O,themeMode:e,onThemeModeChange:t,vdiSafeMode:E,onVdiSafeModeToggle:F,onClearLocalStorage:W,onResetApp:A,isResetting:h,darkModeKey:xk})}].filter(z=>!(!S&&z.key&&Fy.has(z.key)||!S&&(z.key==="group-security"||z.key==="group-monitoring")))})})]})},{Text:eh,Paragraph:Sk}=le;class ia extends m.Component{constructor(s){super(s);He(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(wk,{error:n,onReset:this.handleReset})}}const wk=({error:e,onReset:t})=>{const{token:s}=he.useToken(),[n,o]=ut.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(bf,{style:{fontSize:36,color:s.colorWarning}}),r.jsx(eh,{strong:!0,style:{fontSize:16},children:"Something went wrong"}),r.jsx(eh,{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(Y,{type:"primary",icon:r.jsx(Ms,{}),onClick:t,"aria-label":"Retry rendering this section",children:"Try Again"}),r.jsx(Y,{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(Sk,{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}`:""]})]})},_k=15e3,Tk=()=>{const e=N(a=>a.chats),t=N(a=>a.updateSession),{generateChatTitle:s}=Ud({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<_k||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},kk=()=>{const{token:e}=he.useToken(),t=Xi(),s=m.useRef("");m.useEffect(()=>{const n=jk(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),ud.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 jk(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}ud.initialize({startOnLoad:!1,theme:"dark",securityLevel:"loose",suppressErrorRendering:!0});ud.parseError=function(e){console.warn("Mermaid parse error (handled gracefully):",e)};const th=new Map,Ck=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,Mk=e=>e.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),Pk=e=>(Ck.test(e)?Mk(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}]`}),Ek=200,Ts=new Map,li=new Map;let El=null;const Rk=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 Ak(){El||(El=Dt(()=>import("./vendor-mermaid-DDHJCH-e.js").then(t=>t.bd),__vite__mapDeps([7,1,2,3,6]),import.meta.url));const e=await El;return e.default??e}function Ik(e,t){if(Ts.has(e)&&Ts.delete(e),Ts.set(e,t),Ts.size>Ek){const s=Ts.keys().next().value;s&&Ts.delete(s)}}function ci(e){const t=Ts.get(e);return t?(Ts.delete(e),Ts.set(e,t),t):null}function sh(){Ts.clear(),li.clear()}function $k(e,t){const s=ci(e);if(s)return Promise.resolve(s);const n=li.get(e);if(n)return n;const o=(async()=>{var x,_;const a=await Ak();await a.parse(t);const i=`mermaid-${e}`,l=document.createElement("div"),c=Math.max(1600,window.innerWidth||0,((x=document.documentElement)==null?void 0:x.clientWidth)||0);l.style.cssText=["position:absolute","left:-9999px","top:-9999px",`width:${c}px`,`min-width:${c}px`,"visibility:hidden","pointer-events:none","overflow:visible"].join(";"),document.body.appendChild(l);let 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=Rk(u);if(h>0)throw new Error(`Mermaid rendered invalid SVG (${h} rect widths < 0)`);const y=new DOMParser().parseFromString(u,"image/svg+xml").querySelector("svg");let f=800,v=300;if(y){const w=y.getAttribute("viewBox");if(w){const k=w.split(/\s+/).map(Number);k.length===4&&(f=k[2]||800,v=k[3]||300)}if(f===800&&v===300){const k=document.createElement("div");k.style.cssText="position:absolute;visibility:hidden;width:800px;",k.innerHTML=u,document.body.appendChild(k);const C=(_=k.querySelector("svg"))==null?void 0:_.getBoundingClientRect();C&&(f=C.width,v=C.height),document.body.removeChild(k)}}const b={svg:u,width:f,height:v};return Ik(e,b),b})().finally(()=>{li.delete(e)});return li.set(e,o),o}const Dk=e=>{const t=e;return(t==null?void 0:t.name)==="AbortError"||(t==null?void 0:t.code)===20},nh=220,rh=e=>{const t=e.replace(/\s+/g," ").trim();return t.length<=nh?t:`${t.slice(0,nh)}...`},Lk=e=>e==="pending"||e==="in_progress"||e==="completed"||e==="blocked",Wa=e=>{const t=e.trim().toLowerCase();return t==="memory_note"||t==="session_note"};function Ok(){const e=N(j=>j.processingChats),t=N(j=>j.addMessage),s=N(j=>j.setSessionProcessing),n=N(j=>j.updateTokenUsage),o=N(j=>j.setTruncationInfo),a=N(j=>j.updateSession),i=N(j=>j.updateMessage),l=N(j=>j.setTaskList),c=N(j=>j.updateTaskListDelta),d=N(j=>j.setEvaluationState),u=N(j=>j.upsertSubSessionProgress),h=N(j=>j.refreshChats),p=m.useRef(new rs),g=m.useRef(new Map),y=m.useRef(new Map),f=m.useRef(new Map),v=m.useRef(new Map),b=m.useRef(new Map),x=m.useRef(new Set),_=m.useRef(new Map),w=m.useCallback(j=>{const R=_.current.get(j);R!=null&&R.timer&&clearTimeout(R.timer),_.current.delete(j)},[]),k=m.useCallback((j,R)=>{w(j),x.current.delete(j);const M=g.current.get(j);if(!M)return;g.current.delete(j),M.controller.abort(),ze.forceFlush();const T=y.current.get(M.sessionId);T?(R!=null&&R.clearDraft&&(ze.clear(T.sessionId,T.messageId),ze.clear(T.sessionId,T.reasoningMessageId),ze.clear(T.sessionId,T.statusMessageId)),y.current.delete(M.sessionId)):R!=null&&R.clearDraft&&(ze.clear(j,`streaming-${j}`),ze.clear(j,`streaming-reasoning-${j}`),ze.clear(j,`streaming-status-${j}`))},[w]),C=m.useCallback(j=>{w(j);const R=new AbortController;g.current.set(j,{sessionId:j,controller:R});const M=`streaming-${j}`,T=`streaming-reasoning-${j}`,P=`streaming-status-${j}`,S=ze.getLatest(M),L=ze.getLatest(T),$=ze.getLatest(P);y.current.set(j,{sessionId:j,messageId:M,content:S??"",reasoningMessageId:T,reasoningContent:L??"",statusMessageId:P,status:$??""});const I=A=>{const O=y.current.get(j);if(!O)return;const D=(A??"").trim();if(!D){if(!O.status)return;O.status="",ze.clear(O.sessionId,O.statusMessageId);return}O.status!==D&&(O.status=D,ze.publish({sessionId:O.sessionId,messageId:O.statusMessageId,content:O.status}))};S===null&&ze.publish({sessionId:j,messageId:M,content:""});const W=()=>{const A=_.current.get(j),O=(A==null?void 0:A.attempt)??0,D=Math.min(5e3,250*Math.pow(2,O));k(j,{clearDraft:!1});const H=setTimeout(()=>{var F;if(_.current.delete(j),!N.getState().processingChats.has(j))return;const B=N.getState().chats.find(z=>z.id===j),K=(F=B==null?void 0:B.id)==null?void 0:F.trim();K&&C(K)},D);_.current.set(j,{attempt:O+1,timer:H})};p.current.subscribeToEvents(j,{onToken:A=>{const O=y.current.get(j);O&&(I(null),O.content+=A,ze.publish({sessionId:O.sessionId,messageId:O.messageId,content:O.content}))},onReasoningToken:A=>{const O=y.current.get(j);O&&(O.reasoningContent+=A,ze.publish({sessionId:O.sessionId,messageId:O.reasoningMessageId,content:O.reasoningContent}))},onToolStart:(A,O,D)=>{var $e,De;const H=y.current.get(j),B=(H==null?void 0:H.content)||"",K=(H==null?void 0:H.reasoningContent)||"",F=B.trim().length>0,z=K.trim().length>0;if(F||z){const be=N.getState().chats.find(ht=>ht.id===j),ye=($e=be==null?void 0:be.messages)==null?void 0:$e[be.messages.length-1],je=typeof((De=ye==null?void 0:ye.metadata)==null?void 0:De.reasoning)=="string"?ye.metadata.reasoning:"";(ye==null?void 0:ye.role)==="assistant"&&(ye==null?void 0:ye.type)==="text"&&typeof(ye==null?void 0:ye.content)=="string"&&ye.content===B&&je===K||t(j,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:B,createdAt:new Date().toISOString(),metadata:{sessionId:j,model:"agent",...z?{reasoning:K}:{}}}),H&&(H.content="",H.reasoningContent="",H.status&&(H.status="",ze.clear(H.sessionId,H.statusMessageId)),ze.publish({sessionId:H.sessionId,messageId:H.messageId,content:""}),ze.publish({sessionId:H.sessionId,messageId:H.reasoningMessageId,content:""}))}v.current.set(A,O);const de=O.trim().toLowerCase();Wa(O)?I("memory_updating"):I(`tool_running:${de||"tool"}`);const Te=crypto.randomUUID();b.current.set(A,Te),t(j,{id:Te,role:"assistant",type:"tool_call",toolCalls:[{toolCallId:A,toolName:O,parameters:D||{},streamingOutput:""}],metadata:{},createdAt:new Date().toISOString()})},onToolToken:(A,O)=>{const D=b.current.get(A),H=N.getState().chats.find(z=>z.id===j);if(!H)return;const B=(D?H==null?void 0:H.messages.find(z=>z.id===D):null)||(H==null?void 0:H.messages[H.messages.length-1]);if(!B||!("type"in B)||B.type!=="tool_call"||!("toolCalls"in B)||!Array.isArray(B.toolCalls))return;const K=B.toolCalls.find(z=>z.toolCallId===A);K&&!v.current.has(A)&&(v.current.set(A,K.toolName),b.current.set(A,B.id));const F=B.toolCalls.map(z=>{if(z.toolCallId!==A)return z;const de=(z.streamingOutput||"")+(O||"");return{...z,streamingOutput:de}});i(j,B.id,{toolCalls:F})},onToolComplete:(A,O)=>{const D=v.current.get(A)||"unknown";v.current.delete(A),b.current.delete(A);const H=D.trim().toLowerCase(),B=y.current.get(j);(Wa(D)?(B==null?void 0:B.status)==="memory_updating":!!(B!=null&&B.status&&B.status.includes(H)))&&I(null);const F=(O==null?void 0:O.display_preference)||"Default";t(j,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:D,toolCallId:A,result:{tool_name:D,result:(O==null?void 0:O.result)??"",display_preference:F},isError:!(O!=null&&O.success),createdAt:new Date().toISOString()})},onToolError:(A,O)=>{v.current.delete(A),b.current.delete(A),I(null),t(j,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:"unknown",toolCallId:A,result:{tool_name:"unknown",result:O,display_preference:"Default"},isError:!0,createdAt:new Date().toISOString()})},onToolLifecycle:(A,O,D,H,B)=>{if(D==="begin"){const K=(O||"").trim().toLowerCase();Wa(O||"")?I("memory_updating"):I(`tool_running:${K||"tool"}`)}if(D==="finished"||D==="error"||D==="cancelled"){const K=b.current.get(A);K&&i(j,K,{metadata:{elapsed_ms:H,is_mutating:B}});const F=(O||"").trim().toLowerCase(),z=y.current.get(j);(Wa(O||"")?(z==null?void 0:z.status)==="memory_updating":!!(z!=null&&z.status&&z.status.includes(F)))&&I(null)}},onContextCompressionStatus:(A,O)=>{if(O==="started"){I("context_compacting");return}if(O==="degraded_sections"){I("context_compaction_degraded");return}if(O==="failed"){I("context_compaction_failed");return}I(null)},onTokenBudgetUpdated:A=>{const O=typeof A.max_context_tokens=="number"&&A.max_context_tokens>0?A.max_context_tokens:void 0,D={systemTokens:A.system_tokens,summaryTokens:A.summary_tokens,windowTokens:A.window_tokens,totalTokens:A.total_tokens,budgetLimit:A.budget_limit,...O?{maxContextTokens:O}:{},...typeof A.prompt_cached_tool_outputs=="number"&&A.prompt_cached_tool_outputs>0?{promptCachedToolOutputs:A.prompt_cached_tool_outputs}:{}};n(j,D),o(j,A.truncation_occurred,A.segments_removed);const H=N.getState().chats.find(B=>B.id===j);H&&a(j,{config:{...H.config,tokenUsage:D,truncationOccurred:A.truncation_occurred,segmentsRemoved:A.segments_removed}})},onContextSummarized:A=>{I(null),fe.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,O,D)=>{fe.success(`All tasks completed! Total rounds: ${O}, Tool calls: ${D}`,3)},onTaskEvaluationStarted:(A,O)=>{d(A,{isEvaluating:!0,reasoning:null,timestamp:Date.now()}),fe.info(`Evaluating ${O} task(s)...`,2)},onTaskEvaluationCompleted:(A,O,D)=>{const H=rh(D);d(A,{isEvaluating:!1,reasoning:O>0?H:null,timestamp:Date.now()}),O>0?fe.success(`Evaluation complete: ${O} task(s) updated.`,3):fe.info("Evaluation complete: No updates needed",2)},onComplete:()=>{const A=R;(async()=>{var de,Te,$e;I(null),ze.forceFlush();const O=()=>{const De=g.current.get(j);return De!=null&&De.controller!==A};if(O())return;const D=y.current.get(j),H=(D==null?void 0:D.content)||"",B=(D==null?void 0:D.reasoningContent)||"",K=H.trim().length>0,F=B.trim().length>0;if(K||F){const De=N.getState().chats.find(Ue=>Ue.id===j),be=(de=De==null?void 0:De.messages)==null?void 0:de[De.messages.length-1],ye=typeof((Te=be==null?void 0:be.metadata)==null?void 0:Te.reasoning)=="string"?be.metadata.reasoning:"";(be==null?void 0:be.role)==="assistant"&&(be==null?void 0:be.type)==="text"&&typeof(be==null?void 0:be.content)=="string"&&be.content===H&&ye===B||await t(j,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:H,createdAt:new Date().toISOString(),metadata:{sessionId:j,model:"agent",...F?{reasoning:B}:{}}})}if(O()||(await N.getState().loadChatHistory(j,{mode:"monotonic",retries:4,retryDelayMs:200,waitForAssistant:!0}),O()))return;if(F){const De=N.getState().chats.find(je=>je.id===j),be=[...(De==null?void 0:De.messages)||[]].reverse().find(je=>(je==null?void 0:je.role)==="assistant"&&(je==null?void 0:je.type)==="text"),ye=typeof(($e=be==null?void 0:be.metadata)==null?void 0:$e.reasoning)=="string"&&be.metadata.reasoning.trim().length>0;be!=null&&be.id&&!ye&&i(j,be.id,{metadata:{...be.metadata||{},reasoning:B}})}if(O())return;const z=f.current.get(j)??{children:new Set};if(f.current.set(j,{children:new Set(z.children),parentDone:!0}),z.children.size===0)k(j,{clearDraft:!0}),s(j,!1);else{const De=g.current.get(j);De&&(ze.clear(j,`streaming-${j}`),ze.clear(j,`streaming-reasoning-${j}`),ze.clear(j,`streaming-status-${j}`),y.current.delete(De.sessionId))}})()},onError:async A=>{I(null);const O=Ec(A)?Rc(A):A;await t(j,{id:`error-${Date.now()}`,role:"assistant",type:"text",content:`❌ **Error**: ${O}`,createdAt:new Date().toISOString(),finishReason:"error"});const D=f.current.get(j)??{children:new Set};f.current.set(j,{children:new Set(D.children),parentDone:!0}),D.children.size===0&&(k(j,{clearDraft:!0}),s(j,!1))},onSubSessionStarted:(A,O,D)=>{const H=f.current.get(A)??{children:new Set,parentDone:!1},B=new Set(H.children);B.add(O),f.current.set(A,{children:B,parentDone:H.parentDone}),s(j,!0),u(A,O,{title:D,status:"pending",lastEventAt:new Date().toISOString()}),h()},onSubSessionEvent:(A,O,D)=>{var H,B,K;if(D.type==="task_list_updated"&&D.task_list){const F=D.task_list.session_id||A;l(F,D.task_list);return}if(D.type==="task_list_item_progress"){const F=D.session_id||A;typeof D.item_id=="string"&&Lk(D.status)&&typeof D.tool_calls_count=="number"&&typeof D.version=="number"&&c(F,{session_id:F,item_id:D.item_id,status:D.status,tool_calls_count:D.tool_calls_count,version:D.version});return}if(D.type==="task_evaluation_started"){const F=D.session_id||A;d(F,{isEvaluating:!0,reasoning:null,timestamp:Date.now()});return}if(D.type==="task_evaluation_completed"){const F=D.session_id||A,z=D.updates_count??0;d(F,{isEvaluating:!1,reasoning:z>0?rh(D.reasoning??""):null,timestamp:Date.now()});return}if(D.type==="token"&&typeof D.content=="string"){const z=((((K=(B=(H=N.getState().subSessionsByParent)==null?void 0:H[A])==null?void 0:B[O])==null?void 0:K.outputPreview)||"")+D.content).slice(-2e3);u(A,O,{status:"running",outputPreview:z,lastEventAt:new Date().toISOString()})}else u(A,O,{status:"running",lastEventAt:new Date().toISOString()})},onSubSessionHeartbeat:(A,O,D)=>{u(A,O,{status:"running",lastHeartbeatAt:D})},onSubSessionCompleted:(A,O,D,H)=>{const B=f.current.get(A)??{children:new Set,parentDone:!1},K=new Set(B.children);K.delete(O),f.current.set(A,{children:K,parentDone:B.parentDone}),u(A,O,{status:D,error:H,lastEventAt:new Date().toISOString()}),B.parentDone&&K.size===0&&(k(j,{clearDraft:!0}),s(j,!1)),h()}},R).then(()=>{if(R.signal.aborted)return;const A=g.current.get(j);if(A&&A.controller!==R)return;if(!N.getState().processingChats.has(j)){k(j,{clearDraft:!0});return}W()}).catch(A=>{if(!R.signal.aborted){if(Dk(A)){if(!N.getState().processingChats.has(j)){k(j,{clearDraft:!0});return}W();return}console.error("[useAgentEventSubscription] Subscription error:",A),k(j,{clearDraft:!0}),s(j,!1)}})},[t,k,w,h,d,s,l,o,i,a,c,n,u]),E=m.useCallback(j=>{const R=j.trim();if(!R)return;x.current.delete(R);const M=g.current.get(R);(M==null?void 0:M.sessionId)===R&&!M.controller.signal.aborted||(M&&k(R,{clearDraft:!1}),C(R))},[k,C]);m.useEffect(()=>{e.forEach(j=>E(j));for(const j of Array.from(g.current.keys()))e.has(j)||k(j,{clearDraft:!0});for(const j of Array.from(x.current))e.has(j)||x.current.delete(j)},[e,E,k]),m.useEffect(()=>N.subscribe(j=>j.chats,()=>{if(x.current.size!==0)for(const j of Array.from(x.current)){if(!N.getState().processingChats.has(j)){x.current.delete(j);continue}E(j)}}),[E]),m.useEffect(()=>{const j=g.current;return()=>{const R=Array.from(j.keys());for(const M of R)k(M,{clearDraft:!0})}},[k])}const zy=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_result",Fk=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_call",zk=e=>e.role==="assistant"&&"type"in e&&e.type==="workflow_result",Nk=e=>e.role==="user"&&"type"in e&&e.type==="file_reference",Bk=e=>e.role==="assistant"&&"type"in e&&e.type==="task_list",Pi=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/bmp"],oh=10*1024*1024,Wk=2048,Uk=2048,qk=.82,Hk=512*1024,Yk=e=>Pi.includes(e.type)?e.size>oh?{isValid:!1,error:`Image size too large: ${(e.size/1024/1024).toFixed(2)}MB. Maximum size: ${oh/1024/1024}MB`}:{isValid:!0}:{isValid:!1,error:`Unsupported image type: ${e.type}. Supported types: ${Pi.join(", ")}`},Xk=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}),ah=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)}),Vk=e=>URL.createObjectURL(e),Kk=(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))},Gk=async(e,t)=>{const s=await Xk(e),n=document.createElement("canvas");return Kk(n,s,Wk,Uk),Zk(n,t)},Jk=async e=>{const t=Yk(e);if(!t.isValid)throw new Error(t.error);const s=Vk(e);try{let n;if(e.type==="image/gif"||e.size<Hk)n=await ah(e);else try{n=await Gk(s,qk)}catch(a){console.warn("[imageUtils] Failed to re-encode image, using original:",a),n=await ah(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 Ny(s),n}},Qk=async e=>{const t=Array.from(e),s=[];for(const n of t)try{const o=await Jk(n);s.push(o)}catch(o){console.error(`Failed to process image ${n.name}:`,o)}return s},Zk=(e,t=.8)=>e.toDataURL("image/jpeg",t),Ny=e=>{e.startsWith("blob:")&&URL.revokeObjectURL(e)},ih=e=>{e.forEach(t=>Ny(t.preview))},ej=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]},tj=e=>!e.files||e.files.length===0?!1:Array.from(e.files).some(t=>Pi.includes(t.type)),sj=e=>e.files?Array.from(e.files).filter(t=>Pi.includes(t.type)):[],{Text:nj,Title:rj}=le,oj=({visible:e,images:t,currentIndex:s=0,onClose:n,onDownload:o})=>{const{token:a}=he.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(Lt,{open:e,onCancel:n,footer:null,width:"90vw",style:{top:20},styles:{body:{padding:0,height:"80vh",display:"flex",flexDirection:"column"}},closeIcon:r.jsx(wr,{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(rj,{level:5,style:{margin:0},children:c.name}),r.jsxs(nj,{type:"secondary",style:{fontSize:a.fontSizeSM},children:[ej(c.size)," • ",c.type,t.length>1&&` • ${i+1} of ${t.length}`]})]}),r.jsxs(X,{children:[t.length>1&&r.jsxs(r.Fragment,{children:[r.jsx(Y,{icon:r.jsx(du,{}),onClick:u,disabled:t.length<=1}),r.jsx(Y,{icon:r.jsx(Ws,{}),onClick:h,disabled:t.length<=1})]}),r.jsx(Y,{icon:r.jsx(yr,{}),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(yx,{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(Y,{type:"primary",shape:"circle",icon:r.jsx(du,{}),onClick:u,style:{position:"absolute",left:20,top:"50%",transform:"translateY(-50%)",zIndex:10}}),r.jsx(Y,{type:"primary",shape:"circle",icon:r.jsx(Ws,{}),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,g)=>r.jsx("div",{style:{minWidth:60,height:60,border:g===i?`2px solid ${a.colorPrimary}`:`1px solid ${a.colorBorder}`,borderRadius:a.borderRadius,overflow:"hidden",cursor:"pointer",opacity:g===i?1:.7},onClick:()=>l(g),children:r.jsx("img",{src:p.preview,alt:p.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},p.id))})]})},Yr=e=>/\s/.test(e),aj=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||Yr(a)),l=o==="@"&&(n===0||Yr(a));if(!i&&!l){let u=n;for(;n<s&&!((e[n]==="/"||e[n]==="@")&&(n===0||Yr(e[n-1])));)n+=1;t.push({text:e.slice(u,n),type:"text"});continue}let c=n+1;for(;c<s&&!Yr(e[c]);)c+=1;const d=e.slice(n,c);i?c===s||Yr(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"}]},ij=/(\/)([a-zA-Z0-9_-]*)$/,lj=e=>{if(!e)return{command:null,isTriggerActive:!1,searchText:""};const t=e.match(ij);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}},cj=/@([a-zA-Z0-9._\-\/\\]*)$/,dj=e=>{if(!e)return{isTriggerActive:!1,searchText:"",tokenStart:null};const t=e.match(cj);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}},uj=(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:mj}=le,hj=({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(X,{direction:"vertical",align:"center",children:[r.jsx(bx,{style:{fontSize:32,color:t.colorPrimary}}),r.jsx(mj,{style:{color:t.colorPrimary,fontWeight:500},children:"Drop images here"})]})}):null,{Text:lh}=le,pj=({images:e,token:t,allowImages:s,onPreview:n,onClear:o})=>{const{t:a}=ne();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(G,{align:"center",wrap:"wrap",gap:t.marginXS,children:[r.jsx(lh,{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(lh,{type:"secondary",style:{fontSize:t.fontSizeSM},children:a("chat.input.moreImages",{count:e.length-3})}),r.jsx(Y,{type:"text",size:"small",icon:r.jsx(wr,{}),onClick:o,style:{marginLeft:"auto",minWidth:"auto",padding:"0 4px",height:24},title:a("chat.input.clearAllImages")})]})})},{TextArea:fj}=me,gj=({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",g=1.65,y=s?n.colorTextDisabled:n.colorText;return r.jsxs("div",{style:{position:"relative",flex:1},children:[h?r.jsxs("div",{ref:i,"aria-hidden":!0,style:{position:"absolute",top:0,left:0,right:0,bottom:0,padding:p,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflow:"hidden",pointerEvents:"none",color:"transparent",fontSize:n.fontSize,lineHeight:g,fontFamily:"inherit",fontWeight:400,letterSpacing:"normal",transform:"translate(0, 0)",zIndex:0},children:[o.map((f,v)=>{let b;return f.type==="workflow"?b={backgroundColor:n.colorPrimaryBg,color:"transparent",WebkitTextFillColor:"transparent",fontWeight:400,textDecoration:"underline",textDecorationStyle:"dotted",textDecorationColor:n.colorPrimary}:f.type==="file"&&(b={backgroundColor:n.colorSuccessBg,color:"transparent",WebkitTextFillColor:"transparent"}),r.jsx("span",{style:b,children:f.text},`segment-${v}`)}),e.endsWith(`
|
|
153
|
+
`)?`
|
|
154
|
+
`:null]}):null,r.jsx(fj,{"data-testid":"chat-input",ref:a,value:e,onChange:f=>l(f.target.value),onKeyDown:c,onPaste:d,placeholder:t,disabled:s,autoSize:{minRows:3,maxRows:8},variant:"borderless",onScroll:u,className:"lotus-message-input-field",style:{resize:"none",flex:1,fontSize:n.fontSize,padding:p,lineHeight:g,border:"none",outline:"none",background:"transparent",color:y,WebkitTextFillColor:y,caretColor:y,position:"relative",zIndex:1,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflowY:"auto"}})]})},yj=({allowImages:e,disabled:t,isStreaming:s,token:n,fileInputRef:o,onFileInputChange:a,onFileReferenceButtonClick:i,extraControl:l})=>{const{t:c}=ne();return r.jsxs(G,{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(Y,{type:"text",icon:r.jsx(Us,{}),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(Y,{type:"text",icon:r.jsx(br,{}),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]})},bj=({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:g}=ne(),y=!l.trim()&&c.length===0,f=s||n||!o,v=p??g("chat.actions.sendMessage");return r.jsxs(G,{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(zn,{trigger:["click"],menu:{items:[{key:"regenerate",label:g("chat.actions.regenerate"),icon:r.jsx(Ms,{})},{key:"error_retry",label:g("chat.actions.retryFailed"),icon:r.jsx(Oi,{})}],onClick:({key:b})=>o==null?void 0:o(b)},disabled:f,children:r.jsx(Y,{"data-testid":"regenerate-button",type:"text",icon:r.jsx(od,{spin:s}),disabled:f,title:g("chat.actions.retryOptions"),"aria-label":g("chat.actions.retryOptions"),size:"small",className:"lotus-secondary-button",style:{minWidth:38,padding:"0 8px",height:38,width:38,borderRadius:19,color:u.colorTextSecondary}})}),r.jsx(Y,{"data-testid":s?"cancel-button":"send-button",type:"primary",icon:s?r.jsx(xx,{}):r.jsx(vx,{}),onClick:s?a:i,loading:s&&!a,disabled:s?!a||n:y||n||d,size:"small",danger:s,className:s?"message-input-send-button":"message-input-send-button lotus-primary-cta",style:{minWidth:50,padding:0,height:50,width:50,borderRadius:25,display:"inline-flex",alignItems:"center",justifyContent:"center",background:s?void 0:"linear-gradient(135deg, var(--lotus-primary) 0%, var(--lotus-accent-secondary) 100%)",border:s?void 0:"none",boxShadow:s?void 0:"var(--lotus-send-btn-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",transform:"scale(1)"},title:s?g("chat.actions.cancelRequest"):v,"aria-label":s?g("chat.actions.cancelRequest"):v})]})},{Text:ch}=le,xj=({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(G,{justify:"flex-end",style:{marginTop:a.marginXXS},children:r.jsxs(ch,{type:s?"danger":n?"warning":"secondary",style:{fontSize:a.fontSizeSM},children:[e.toLocaleString()," / ",t.toLocaleString()]})}),o&&r.jsxs(X,{size:"small",style:{marginTop:a.marginXS},children:[r.jsx(ps,{size:"small"}),r.jsx(ch,{type:"secondary",children:"Processing files…"})]})]})},vj=({onFiles:e,mode:t="images"})=>{const[s,n]=m.useState(!1),o=m.useCallback(l=>{var d,u;l.preventDefault(),l.stopPropagation(),(t==="images"?tj(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=sj(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}},Sj=e=>{const{message:t}=Ot.useApp(),[s,n]=m.useState([]),[o,a]=m.useState(!1),[i,l]=m.useState(0),c=m.useCallback(async p=>{if(e)try{const g=await Qk(p);g.length>0&&(n(y=>[...y,...g]),t.success(`Added ${g.length} image(s)`))}catch(g){t.error(`Failed to process images: ${g}`)}},[e,t]),d=m.useCallback(p=>{const g=s.find(y=>y.id===p);g&&ih([g]),n(y=>y.filter(f=>f.id!==p))},[s]),u=m.useCallback(p=>{const g=s.findIndex(y=>y.id===p.id);l(g>=0?g:0),a(!0)},[s]),h=m.useCallback(()=>{ih(s),n([])},[s]);return{images:s,setImages:n,previewModalVisible:o,setPreviewModalVisible:a,previewImageIndex:i,handleImageFiles:c,handleRemoveImage:d,handleImagePreview:u,clearImages:h}},wj=({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])}),bt=[];for(let e=0;e<256;++e)bt.push((e+256).toString(16).slice(1));function _j(e,t=0){return(bt[e[t+0]]+bt[e[t+1]]+bt[e[t+2]]+bt[e[t+3]]+"-"+bt[e[t+4]]+bt[e[t+5]]+"-"+bt[e[t+6]]+bt[e[t+7]]+"-"+bt[e[t+8]]+bt[e[t+9]]+"-"+bt[e[t+10]]+bt[e[t+11]]+bt[e[t+12]]+bt[e[t+13]]+bt[e[t+14]]+bt[e[t+15]]).toLowerCase()}let Rl;const Tj=new Uint8Array(16);function kj(){if(!Rl){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Rl=crypto.getRandomValues.bind(crypto)}return Rl(Tj)}const jj=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),dh={randomUUID:jj};function uh(e,t,s){var o;if(dh.randomUUID&&!e)return dh.randomUUID();e=e||{};const n=e.random??((o=e.rng)==null?void 0:o.call(e))??kj();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,_j(n)}const Cj=["text/","application/json","application/xml"],Mj=[".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"],Pj=200*1024,By=e=>e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`,mh=e=>{const t=e.toLowerCase();return Mj.some(s=>t.endsWith(s))},Ej=e=>!e.type&&mh(e.name)?!0:Cj.some(t=>e.type.startsWith(t))||mh(e.name),Rj=e=>new Promise((t,s)=>{const n=new FileReader;n.onerror=()=>s(n.error),n.onload=()=>t(n.result),n.readAsText(e)}),hh=async(e,t)=>{const s=Pj,n=[],o=[];for(const a of e)try{if(Ej(a)&&a.size<=s){const i=await Rj(a);n.push({id:uh(),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:uh(),file:a,name:a.name,size:a.size,type:a.type||"application/octet-stream",kind:"binary",preview:`(${By(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}},Aj=e=>{const t=[],s=[];return e.forEach(n=>{n.type.startsWith("image/")?t.push(n):s.push(n)}),{images:t,others:s}},Ij=e=>e.length===0?"":e.map(t=>{const s=`### File: ${t.name}`,n=`(_${By(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
|
+
`),$j=({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}=Sj(e),g=m.useCallback(async w=>{if(!w||w.length===0)return;const{images:k,others:C}=Aj(w);if(k.length>0&&await u(k),C.length>0&&t){o(!0);const{processed:E,errors:j}=await hh(C);E.length>0&&(t(E),s.success(`Added ${E.length} file(s)`)),j.forEach(R=>s.error(R)),o(!1)}},[u,s,t]),{isDragOver:y,handleDragOver:f,handleDragLeave:v,handleDrop:b}=vj({onFiles:g,mode:"any"}),{handlePaste:x}=wj({onImages:u,onAttachments:t?async w=>{o(!0);const{processed:k,errors:C}=await hh(w);k.length>0&&(t(k),s.success(`Attached ${k.length} file(s)`)),C.forEach(E=>s.error(E)),o(!1)}:void 0,allowImages:e}),_=m.useCallback(w=>{const k=w.target.files;k&&k.length>0&&u(k),w.target.value=""},[u]);return{images:a,setImages:i,previewModalVisible:l,setPreviewModalVisible:c,previewImageIndex:d,handleImageFiles:u,handleImagePreview:h,clearImages:p,isProcessingAttachments:n,isDragOver:y,handleDragOver:f,handleDragLeave:v,handleDrop:b,handlePaste:x,handleFileInputChange:_}},Dj=({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(lj(t))},[t,s]),m.useEffect(()=>{n&&n(dj(t))},[t,n]),m.useEffect(()=>{o&&o(a)},[a,o]),m.useEffect(()=>{i&&l(i)},[i,l])},Lj=({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:g,textAreaRef:y})=>{const f=m.useCallback(()=>{const x=e.trim();if(!(!x&&t.length===0||s||n)){if(u){const _=typeof h=="number"?h.toLocaleString():"configured";p.error(`Message exceeds the maximum length of ${_} characters.`);return}if(d){const _=d(x);if(!_.isValid){p.error(_.errorMessage||"Message format is incorrect");return}}i(x,t.length>0?t:void 0),g()}},[g,n,t,u,s,h,p,i,d,e]),v=m.useCallback(x=>{if(c&&!n&&!s&&!x.shiftKey&&(x.key==="ArrowUp"||x.key==="ArrowDown")){const _=x.key==="ArrowUp"?"previous":"next",w=c(_,e);if(w!=null){x.preventDefault(),a(w),requestAnimationFrame(()=>{var C,E;const k=((E=(C=y.current)==null?void 0:C.resizableTextArea)==null?void 0:E.textArea)||null;if(k){const j=w.length;k.setSelectionRange(j,j)}});return}}x.key==="Enter"&&!x.shiftKey&&!s&&!n&&!o&&(x.preventDefault(),f())},[n,f,s,o,a,c,y,e]),b=m.useCallback((x="regenerate")=>{s||n||!l||l(x)},[n,s,l]);return{handleKeyDown:v,handleSubmit:f,handleRetry:b}},Oj=({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:g,onWorkflowCommandChange:y,onFileReferenceChange:f,onFileReferenceButtonClick:v,maxCharCount:b,leftControlsExtra:x,submitButtonLabel:_})=>{const{t:w}=ne(),{isStreaming:k,hasMessages:C,allowRetry:E=!0,onRetry:j,onCancel:R,onHistoryNavigate:M}=n,T=m.useRef(null),P=m.useRef(null),S=u||P,L=m.useRef(null),{token:$}=he.useToken(),I=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",[W,A]=fe.useMessage(),O=e.length,D=typeof b=="number"&&Number.isFinite(b)&&b>0,H=D?O>b:!1,B=D?!H&&O>=b*.9:!1,{images:K,setImages:F,previewModalVisible:z,setPreviewModalVisible:de,previewImageIndex:Te,handleImagePreview:$e,clearImages:De,isProcessingAttachments:be,isDragOver:ye,handleDragOver:je,handleDragLeave:Ue,handleDrop:ht,handlePaste:Ge,handleFileInputChange:wt}=$j({allowImages:c,onAttachmentsAdded:g,messageApi:W}),U=uj(e,80),_e=m.useMemo(()=>aj(e),[e]),Ce=()=>{var ce,Ie;const V=(Ie=(ce=S.current)==null?void 0:ce.resizableTextArea)==null?void 0:Ie.textArea;if(!V||!L.current)return;const Q=V.scrollTop,se=V.scrollLeft;L.current.style.transform=`translate(${-se}px, ${-Q}px)`};Dj({value:e,debouncedValue:U,onWorkflowCommandChange:y,onFileReferenceChange:f,onImagesChange:l,images:K,propImages:i,setImages:F,syncOverlayScroll:Ce});const{handleKeyDown:Ve,handleSubmit:qe,handleRetry:J}=Lj({value:e,images:K,isStreaming:k,disabled:a,isWorkflowSelectorVisible:d,onChange:t,onSubmit:s,onRetry:j,onHistoryNavigate:M,validateMessage:p,isOverCharLimit:H,maxCharCount:b,messageApi:W,clearImages:De,textAreaRef:S}),re=o??w("chat.input.placeholder");return r.jsxs(r.Fragment,{children:[A,r.jsxs("div",{className:`message-input-container lotus-message-input-shell ${ye?"is-drag-over":""}`,role:"group","aria-label":w("chat.input.messageComposer","Message composer"),style:{position:"relative",border:`1px solid ${ye?"var(--lotus-input-border-active)":"var(--lotus-input-border)"}`,borderRadius:26,background:ye?"var(--lotus-input-bg-active)":"var(--lotus-input-bg)",backdropFilter:I?"none":"blur(18px)",WebkitBackdropFilter:I?"none":"blur(18px)",boxShadow:"var(--lotus-input-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",width:"100%",padding:`${$.paddingSM}px`,overflow:"hidden"},onDragOver:je,onDragLeave:Ue,onDrop:ht,children:[r.jsx(pj,{images:K,token:$,allowImages:c,onPreview:$e,onClear:De}),r.jsx(hj,{visible:ye,token:$}),r.jsxs(G,{vertical:!0,style:{gap:$.marginXS,minHeight:132,width:"100%"},children:[r.jsx(gj,{value:e,placeholder:re,disabled:a,token:$,highlightSegments:_e,textAreaRef:S,highlightOverlayRef:L,onChange:t,onKeyDown:Ve,onPaste:Ge,onScrollSync:Ce}),r.jsxs(G,{align:"center",justify:"space-between",gap:$.marginSM,wrap:"wrap",style:{rowGap:$.marginXS},children:[r.jsx(G,{align:"center",gap:$.marginXS,wrap:"wrap",style:{minWidth:0,flex:"1 1 260px"},children:r.jsx(yj,{allowImages:c,disabled:a,isStreaming:k,token:$,fileInputRef:T,onFileInputChange:wt,onFileReferenceButtonClick:v,extraControl:x})}),r.jsx(bj,{allowRetry:E,hasMessages:C,isStreaming:k,disabled:a,onRetry:J,onCancel:R,onSubmit:qe,value:e,images:K,isOverCharLimit:H,token:$,statusIndicator:h,submitButtonLabel:_})]})]})]}),r.jsx(xj,{charCount:O,maxCharCount:b,isOverCharLimit:H,isNearCharLimit:B,isProcessingAttachments:be,token:$}),c&&r.jsx(oj,{visible:z,images:K,currentIndex:Te,onClose:()=>de(!1)})]})},{Text:ph}=le,{useToken:Fj}=he,zj=({text:e,onClose:t})=>{const{token:s}=Fj(),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(X,{style:{width:"100%",justifyContent:"space-between",alignItems:"flex-start"},children:[r.jsxs("div",{style:{flex:1},children:[r.jsx(ph,{style:{fontSize:s.fontSizeSM,color:s.colorPrimary},children:"Referencing"}),r.jsx(ph,{style:{fontSize:s.fontSizeSM,color:s.colorTextSecondary,marginLeft:s.marginSM},ellipsis:!0,children:o})]}),r.jsx(Y,{type:"text",size:"small",icon:r.jsx(wr,{}),onClick:t,style:{marginLeft:s.marginXS,color:s.colorTextSecondary,borderRadius:999}})]})})},Nj=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 y=n??h.length,f=Math.max(0,y-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 g=n+1;return g>=h.length?(o(null),s.current=!0,{value:"",applied:!0}):(o(g),s.current=!0,{value:h[g]??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}},In=class In{constructor(){He(this,"cache",null);He(this,"cacheTime",0);He(this,"CACHE_TTL",3e4)}static getInstance(){return In.instance||(In.instance=new In),In.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 xe.get("commands");if(!Array.isArray(n.commands))throw new Error("Invalid command list response");return this.cache=n.commands,this.cacheTime=s,st("[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 xe.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}};He(In,"instance");let ea=In;const Yn=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}},Bj=({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((k,C)=>{const E=k.trimStart(),j=`/${C}`;if(!E.startsWith(j))return!1;const R=E.charAt(j.length);return!R||/\s/.test(R)},[]),g=m.useCallback(()=>{h(null),t==null||t(null)},[t]),y=m.useCallback((k,C)=>{if(!p(k,C.name))return;const E=`/${C.name}`,R=k.trim().slice(E.length).trim(),M=[C.content,R].filter(Boolean).join(`
|
|
165
|
+
|
|
166
|
+
`);t==null||t({...C,content:M})},[p,t]),f=m.useCallback(k=>{s(),u&&!p(k,u.name)&&g(),u&&p(k,u.name)&&y(k,u),e(k)},[s,g,p,u,y,e]),v=m.useCallback(k=>{l(k.isTriggerActive),d(k.isTriggerActive?k.searchText:"")},[]),b=m.useCallback(async k=>{var $,I,W,A,O,D;l(!1);const E=(H=>{var F;if(H.type!=="mcp")return H.name;const B=(F=H.metadata)==null?void 0:F.originalName;if(typeof B=="string"&&B.trim())return B.trim();const K=Yn(H.name);return K!=null&&K.toolName?K.toolName:H.displayName||H.name})(k),j=(I=($=o.current)==null?void 0:$.resizableTextArea)==null?void 0:I.textArea,R=(j==null?void 0:j.selectionStart)??a.length;let M,T;const S=a.substring(0,R).match(/\/([a-zA-Z0-9_-]*)$/);if(S){const H=R-S[0].length,B=a.substring(0,H),K=a.substring(R);M=`${B}/${E} ${K}`,T=`${B}/${E} `.length}else if(a.trim()==="")M=`/${E} `,T=M.length;else{const H=a.substring(0,R),B=a.substring(R);M=`${H}/${E} ${B}`,T=`${H}/${E} `.length}if(e(M),setTimeout(()=>{j&&(j.selectionStart=T,j.selectionEnd=T,j.focus())},0),k.type!=="workflow"){const H={id:`command-draft-${k.id}`,name:E,content:"",createdAt:new Date().toISOString(),type:k.type,displayName:k.displayName,mcpAlias:k.type==="mcp"?k.name:void 0,mcpServerId:k.type==="mcp"?(W=k.metadata)==null?void 0:W.serverId:void 0,mcpServerName:k.type==="mcp"?(A=k.metadata)==null?void 0:A.serverName:void 0,mcpOriginalName:k.type==="mcp"?(O=k.metadata)==null?void 0:O.originalName:void 0};h(H),t==null||t(H);return}const L=ea.getInstance();try{const H=k.id.startsWith("workflow-")?k.id.slice(9):k.id,K=((D=(await L.getCommand(k.type,H)).content)==null?void 0:D.trim())||"";if(K){const F={id:`command-draft-${k.id}`,name:k.name,content:K,createdAt:new Date().toISOString(),type:k.type,displayName:k.displayName};h(F),t==null||t(F)}else g()}catch(H){console.error(`[InputContainer] Failed to apply command '${k.name}':`,H),g()}},[g,t,e,a,o]),x=m.useCallback(async k=>{try{const j=(await ea.getInstance().listCommands()).find(R=>R.id===k.id&&R.type===k.type);if(!j){console.error(`[InputContainer] Command '${k.id}' of type '${k.type}' not found`),e(`/${k.name} `),g();return}await b(j)}catch(C){console.error(`[InputContainer] Failed to select command '${k.name}':`,C),e(`/${k.name} `),g()}},[b,g,e]),_=m.useCallback(()=>{l(!1)},[]),w=m.useCallback(async k=>{l(!1);try{const j=(await ea.getInstance().listCommands()).find(R=>R.name===k);j?await b(j):(console.error(`[InputContainer] Command '${k}' not found in auto-complete`),e(`/${k} `),g())}catch(C){console.error(`[InputContainer] Failed to load command '${k}' in auto-complete:`,C),e(`/${k} `),g()}},[b,g,e]);return{selectedCommand:u,showCommandSelector:i,commandSearchText:c,clearCommandDraft:g,matchesCommandToken:p,handleInputChange:f,handleCommandChange:v,handleCommandSelect:x,handleCommandSelectorCancel:_,handleAutoComplete:w,setShowCommandSelector:l}};class Wj{constructor(t={}){He(this,"cache",null);He(this,"options");He(this,"validateWorkspacePath",this.validatePath.bind(this));He(this,"getRecentWorkspaces",this.getRecent.bind(this));He(this,"addRecentWorkspace",this.addRecent.bind(this));He(this,"removeRecentWorkspace",this.removeRecent.bind(this));He(this,"clearRecentWorkspaces",this.clearRecent.bind(this));He(this,"getWorkspaceSuggestions",this.getCombinedSuggestions.bind(this));He(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 xe.post("workspace/validate",{path:t})}async getRecent(){var t;if(this.isCacheValid())return this.cache.recentWorkspaces;try{const s=await xe.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 xe.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 xe.get("workspace/suggestions")}async browseFolder(t){return xe.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 xe.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 xe.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 Uj=new Wj,qj=({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,g]=m.useState(""),[y,f]=m.useState(!1),[v,b]=m.useState(""),[x,_]=m.useState(!1),[w,k]=m.useState(null),[C,E]=m.useState(!1),j=m.useRef(null);m.useEffect(()=>{y&&b((n==null?void 0:n.config.workspacePath)??"")},[y,n==null?void 0:n.config.workspacePath]),m.useEffect(()=>{h(!1),g(""),d([]),l(new Map),j.current=(n==null?void 0:n.config.workspacePath)??null},[s,n==null?void 0:n.config.workspacePath]);const R=m.useCallback(async(I,W)=>{_(!0),d([]),k(null);try{const A=await Uj.listWorkspaceFiles(W);d(A),j.current=W}catch(A){console.error("Failed to load workspace files:",A),k(A instanceof Error?A.message:"Workspace file browsing is unavailable.")}finally{_(!1)}},[]),M=m.useCallback(I=>{if(g(I.searchText),!I.isTriggerActive){h(!1);return}if(!s||!n){h(!1);return}const W=n.config.workspacePath;if(!W){b(""),f(!0),h(!1);return}h(!0),(j.current!==W||c.length===0)&&R(s,W)},[n,s,R,c.length]),T=m.useCallback(I=>{const W=e.lastIndexOf("@");let A;W>=0&&e.substring(W).match(/^@[a-zA-Z0-9._\\-\\/\\\\]*$/)?A=`${e.slice(0,W)}@${I.name} `:A=e.trim()?`${e.trim()} @${I.name} `:`@${I.name} `,t(A),l(O=>{const D=new Map(O);return D.set(I.name,I),D}),h(!1),g("")},[e,t]),P=m.useCallback(()=>{h(!1)},[]),S=m.useCallback(()=>{if(!s||!n)return;const I=n.config.workspacePath;if(!I){b(""),f(!0),h(!1);return}g(""),h(!0),(j.current!==I||c.length===0)&&R(s,I)},[n,s,R,c.length]),L=m.useCallback(()=>{f(!1),b("")},[]),$=m.useCallback(async I=>{if(!n||!s)return;const W=I.trim();if(!W){a.error("Workspace path cannot be empty");return}E(!0);try{o(s,{config:{...n.config,workspacePath:W}}),f(!1),b(""),h(!1),k(null)}catch(A){const O=A instanceof Error?A.message:"Unable to save workspace path";a.error(O)}finally{E(!1)}},[n,s,a,o]);return{fileReferences:i,setFileReferences:l,workspaceFiles:c,showFileSelector:u,setShowFileSelector:h,fileSearchText:p,isWorkspaceLoading:x,workspaceError:w,isWorkspaceModalVisible:y,workspacePathInput:v,isSavingWorkspace:C,setWorkspacePathInput:b,setIsWorkspaceModalVisible:f,handleFileReferenceChange:M,handleFileReferenceSelect:T,handleFileSelectorCancel:P,handleFileReferenceButtonClick:S,handleWorkspaceModalCancel:L,handleWorkspaceModalSubmit:$,fetchWorkspaceFiles:R}},Hj=()=>{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}},Yj=({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(y,f)=>{const v=y.trim(),b=Ij(e),x=(t==null?void 0:t.trim())??"";let _=v,w;if(s!=null&&s.content&&s.type==="workflow"){const C=`/${s.name}`;if(n(v,s.name)){const j=v.slice(C.length).trim();_=[s.content,j].filter(Boolean).join(`
|
|
167
|
+
|
|
168
|
+
`)}}else if((s==null?void 0:s.type)==="skill"){const C=`/${s.name}`;if(n(v,s.name)){const j=v.slice(C.length).trim();_=[`[User explicitly selected skill: ${s.displayName||s.name} (ID: ${s.name})]`,j].filter(Boolean).join(`
|
|
169
|
+
|
|
170
|
+
`),w=[s.name]}}else if((s==null?void 0:s.type)==="mcp"){const C=`/${s.name}`;if(n(v,s.name)){const j=v.slice(C.length).trim();_=[`[User explicitly selected MCP tool: ${s.mcpAlias||s.displayName||s.name}]`,j].filter(Boolean).join(`
|
|
171
|
+
|
|
172
|
+
`)}}if(!_&&!b&&(!f||f.length===0))return;const k=[x,_,b].filter(Boolean).join(`
|
|
173
|
+
|
|
174
|
+
`);if(l(k),d(""),c(),o.size>0){const C=Array.from(k.matchAll(/@([^\\s]+)/g));if(C.length>0){const E=[];for(const j of C){const R=j[1],M=o.get(R);M&&E.push(M)}if(E.length>0){const j=JSON.stringify({type:"file_reference",paths:E.map(R=>R.path),display_text:k});await i(j,f,a,w)}else await i(k,f,a,w)}else await i(k,f,a,w)}else await i(k,f,a,w);u(null),h([]),p(new Map)},[e,c,o,n,l,a,s,i,h,d,p,u,t])}),Xj=({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}},Vj=({referenceText:e,isToolSpecificMode:t,isRestrictConversation:s,allowedTools:n,autoToolPrefix:o,t:a})=>a(e?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows");function Kj({value:e,onChange:t,disabled:s}){const n=Ee(d=>d.catalog),o=Ee(d=>d.isCatalogFetching),a=m.useMemo(()=>{if(!(n!=null&&n.models))return[];const d={};for(const p of n.models){const g=p.reference.provider;d[g]||(d[g]={display:p.provider_display_name,models:[]}),d[g].models.push(p)}const u=[];return Object.keys(d).forEach((p,g)=>{const y=d[p];g>0&&u.push({type:"divider"}),u.push({type:"group",label:y.display,children:y.models.map(f=>({key:`${f.reference.provider}/${f.reference.model}`,label:r.jsxs(X,{size:4,children:[r.jsx("span",{children:f.display_name}),f.capabilities.supports_vision&&r.jsx(oe,{color:"blue",style:{fontSize:10,lineHeight:"16px",padding:"0 3px"},children:"Vision"})]})}))})}),u},[n]),i=e?`${e.provider}/${e.model}`:void 0,l=m.useCallback(d=>{const[u,...h]=d.key.split("/"),p=h.join("/");u&&p&&t({provider:u,model:p})},[t]),c=m.useCallback(async()=>{await Ee.getState().fetchCatalogModels()},[]);return r.jsxs(X,{size:4,"data-tour-id":"model-picker",children:[r.jsx(zn,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:i?[i]:[],items:a,style:{maxHeight:"50vh",overflowY:"auto"},onClick:l},disabled:s,children:r.jsx(Y,{type:"text",size:"small",disabled:s,style:{minWidth:146,padding:"0 12px",height:36,borderRadius:18},title:e?`${e.provider}/${e.model}`:"Select model",children:r.jsxs(X,{size:4,children:[r.jsx("span",{style:{maxWidth:150,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13},children:e?`${e.provider}/${e.model}`:"Select model"}),r.jsx(Wt,{style:{fontSize:10}})]})})}),r.jsx(Y,{type:"text",size:"small",icon:r.jsx(Ms,{spin:o}),onClick:c,disabled:o,style:{height:36,borderRadius:18},title:"Fetch all provider models"})]})}const Nc="chat-toggle-batch-export-selection",Bc="chat-focus-input",pr="chat-pending-question-resolved",Gj=m.lazy(()=>Dt(()=>import("./index-CYeT_vWc.js"),__vite__mapDeps([8,1,2,3]),import.meta.url)),Jj=m.lazy(()=>Dt(()=>import("./index-Dx8glliP.js"),__vite__mapDeps([9,1,2,3,4,5,6,7,10]),import.meta.url)),Qj=m.lazy(()=>Dt(()=>import("./index-BoZANqat.js"),__vite__mapDeps([11,1,2,3,4,5,6,7]),import.meta.url)),Zj=m.lazy(()=>Dt(()=>import("./index-B9rhKJTy.js"),__vite__mapDeps([12,1,2,3]),import.meta.url)),{useToken:eC}=he,fh="chat-send-message",gh="reference-text",tC="chat-model-options-cache-v1",sC=24*60*60*1e3,nC=["low","medium","high","xhigh","max"],rC=[],Wy=e=>`${tC}:${e}`,oC=e=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(Wy(e));if(!t)return null;const s=JSON.parse(t);return!s||!Array.isArray(s.options)||Date.now()-s.timestamp>sC?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}},aC=(e,t)=>{if(!(typeof window>"u"))try{const s={timestamp:Date.now(),options:t};localStorage.setItem(Wy(e),JSON.stringify(s))}catch{}},iC=({sessionId:e,onWorkflowDraftChange:t,statusIndicator:s})=>{var ru,ou;const{t:n}=ne(),o=m.useRef(null),{token:a}=eC(),i=md(),l=Bs(te=>te.open),c=N(te=>e??te.currentSessionId),d=N(te=>te.currentSessionId),u=N(Xn(c)),h=(u==null?void 0:u.messages)||[],p=N(te=>te.addMessage),g=N(te=>te.updateSession),y=N(te=>te.processingChats),f=N(te=>te.setSessionProcessing),v=N(te=>te.pendingQuestionRespond),b=N(te=>te.clearPendingQuestionRespondForSession),x=Hi(c),_=Bd((ru=u==null?void 0:u.config)==null?void 0:ru.model_ref),w=Ee(te=>te.isProviderModelRefEnabled),k=N(te=>c?te.inputStates[c]:void 0),C=N(te=>te.setInputContent),E=N(te=>te.setReferenceText),j=N(te=>te.setInputReasoningEffort),R=Ee(te=>te.currentProvider),M=Ee(te=>te.providerConfig),[T,P]=m.useState([]),[S,L]=m.useState(!1),[$,I]=m.useState(null),[W,A]=m.useState(!1),O=(k==null?void 0:k.content)||"",D=(k==null?void 0:k.referenceText)||null,H=m.useMemo(()=>{var te;return(te=M.providers[R])==null?void 0:te.reasoning_effort},[M,R]),B=m.useMemo(()=>c?bd(c):void 0,[c]),K=((ou=u==null?void 0:u.config)==null?void 0:ou.reasoningEffort)??(k==null?void 0:k.reasoningEffort)??B??H??"medium",F=m.useCallback(te=>{c&&C(c,te)},[c,C]),z=m.useCallback(te=>{c&&E(c,te)},[c,E]),de=m.useCallback(async te=>{if(c&&(j(c,te),!!u))try{await Wn.patchSession(c,{reasoning_effort:te}),g(c,{config:{...u.config,reasoningEffort:te}})}catch(Ne){console.warn("[InputContainer] Failed to persist reasoning effort:",Ne)}},[u,c,j,g]),Te=c?y.has(c):!1,{sendMessage:$e,retryLastTurn:De,cancel:be}=Cy({sessionId:c,addMessage:p,setSessionProcessing:f,updateSession:g});m.useEffect(()=>{if(typeof window>"u")return;const te=at=>at?c===at:c!==null&&c===d,Ne=at=>{const Be=at;if(!Be.detail||typeof Be.detail.text!="string")return;const is=typeof Be.detail.sessionId=="string"?Be.detail.sessionId:null;if(!te(is))return;const ls=Be.detail.text.trim();ls&&(Be.detail.handled=!0,z(ls),requestAnimationFrame(()=>{var bs;(bs=o.current)==null||bs.focus()}))},Ke=at=>{var ls;const Be=at,is=typeof((ls=Be.detail)==null?void 0:ls.sessionId)=="string"?Be.detail.sessionId:null;te(is)&&(Be.detail&&(Be.detail.handled=!0),requestAnimationFrame(()=>{var bs;(bs=o.current)==null||bs.focus()}))};return window.addEventListener(gh,Ne),window.addEventListener(Bc,Ke),()=>{window.removeEventListener(gh,Ne),window.removeEventListener(Bc,Ke)}},[d,c,z]);const ye=Te,{message:je}=Ot.useApp(),Ue=!1,ht=!1,Ge=rC,wt=void 0,{recordEntry:U,navigate:_e,acknowledgeManualInput:Ce}=Nj(c),{attachments:Ve,setAttachments:qe,handleAttachmentsAdded:J,handleAttachmentRemove:re,handleClearAttachments:V}=Hj(),Q=Bj({setContent:F,onWorkflowDraftChange:t,acknowledgeManualInput:Ce,currentSessionId:c,textAreaRef:o,content:O}),se=qj({content:O,setContent:F,currentSessionId:c,currentChat:u,updateSession:g,messageApi:je}),{setShowFileSelector:ce}=se;m.useEffect(()=>{Q.showCommandSelector&&ce(!1)},[Q.showCommandSelector,ce]);const{handleSubmit:Ie}=Yj({attachments:Ve,referenceText:D,selectedWorkflow:Q.selectedCommand,matchesWorkflowToken:Q.matchesCommandToken,fileReferences:se.fileReferences,reasoningEffort:K,sendMessage:$e,recordEntry:U,clearWorkflowDraft:Q.clearCommandDraft,setContent:F,setReferenceText:z,setAttachments:qe,setFileReferences:se.setFileReferences}),Je=v&&v.sessionId===c?v:null,_t=!!Je,jt=(Je==null?void 0:Je.options)||[],Ct=(Je==null?void 0:Je.allowCustom)??!0,Tt=m.useCallback(te=>{if(!te)return!1;const Ne=N.getState().pendingQuestionRespond;return(Ne==null?void 0:Ne.sessionId)===te},[]),hn=m.useCallback(async te=>{const Ne=te.trim();if(!Ne||!c)return;const Ke=N.getState().pendingQuestionRespond,at=(Ke==null?void 0:Ke.sessionId)===c?Ke:null;if(at&&!at.allowCustom&&at.options.length>0&&!at.options.includes(Ne)){je.warning(n("components.questionDialog.selectOptionWarning"));return}try{const Be={response:Ne,reasoning_effort:K};w()&&_&&(Be.model_ref=_,Be.provider=_.provider);const is=await pe.post(`respond/${c}`,Be);je.success(n("components.questionDialog.responseSubmittedContinue")),F(""),b(c),typeof window<"u"&&window.dispatchEvent(new CustomEvent(pr,{detail:{sessionId:c}}));const ls=is==null?void 0:is.auto_resume_status;ls&&["started","already_running"].includes(ls)&&f(c,!0)}catch(Be){console.error("[InputContainer] Failed to submit respond:",Be),je.error(Be instanceof Error?Be.message:n("components.questionDialog.submitFailed"))}},[c,K,_,w,je,F,b,f,n]),Vs=m.useCallback(async(te,Ne)=>{if(Tt(c)){await hn(te);return}await Ie(te,Ne)},[c,Tt,hn,Ie]),Pr=m.useCallback(async(te,Ne)=>{await Vs(te,Ne)},[Vs]);m.useEffect(()=>{if(typeof window>"u")return;const te=Ne=>{var ls,bs,au;const Ke=Ne;if(!Ke.detail)return;const at=typeof Ke.detail.sessionId=="string"?Ke.detail.sessionId:null;if(!(at?c===at:c!==null&&c===d))return;Ke.detail.handled=!0;const is=(ls=Ke.detail)==null?void 0:ls.content;if(typeof is!="string"||is.trim().length===0){(au=(bs=Ke.detail)==null?void 0:bs.reject)==null||au.call(bs,new Error("External send message content is empty"));return}Vs(is,void 0).then(()=>{var Gn,yn;(yn=(Gn=Ke.detail)==null?void 0:Gn.resolve)==null||yn.call(Gn)}).catch(Gn=>{var yn,iu;(iu=(yn=Ke.detail)==null?void 0:yn.reject)==null||iu.call(yn,Gn)})};return window.addEventListener(fh,te),()=>{window.removeEventListener(fh,te)}},[d,c,Vs]);const{retryLastMessage:Vn,handleHistoryNavigate:Ks}=Xj({currentSessionId:c,currentChat:u,currentMessages:h,reasoningEffort:K,retryLastTurn:De,navigate:_e}),Er=()=>z(null),Ps=m.useMemo(()=>M.providers[R],[M,R]),Ut=m.useMemo(()=>!Ps||typeof Ps!="object"?!1:R==="copilot"?Object.keys(Ps).length>0:"api_key"in Ps?typeof Ps.api_key=="string"&&Ps.api_key.trim().length>0:!1,[R,Ps]),pn=m.useCallback(()=>Ut?!1:(l("chat"),je.warning("Please configure provider first"),!0),[Ut,je,l]);m.useEffect(()=>{const te=oC(R);P(te??[]),I(null)},[R]);const fn=m.useCallback(te=>te instanceof Error&&te.message.trim()?te.message:"Unknown error",[]),gn=m.useMemo(()=>({openai:[...ek],anthropic:[...tk],gemini:[...sk],copilot:[...nk],bodhi:[]})[R]||[],[R]),Kn=m.useMemo(()=>{const Ne=[...T.length>0?T:gn];return x&&!Ne.some(Ke=>Ke.value===x)&&Ne.unshift({value:x,label:x}),Ne},[T,gn,x]),Rr=m.useCallback(async(te,Ne)=>{if(!(!(Ne!=null&&Ne.force)&&T.length>0))try{L(!0),I(null);const at=(te==="copilot"?await If.getModels():gn).map(Be=>({value:typeof Be=="string"?Be:Be.value,label:typeof Be=="string"?Be:Be.label}));P(at),aC(te,at)}catch(Ke){I(fn(Ke))}finally{L(!1)}},[gn,fn,T.length]),ka=m.useCallback(te=>{te&&(pn()||S||T.length>0||Rr(R))},[R,Rr,S,T.length,pn]),ae=m.useCallback(async te=>{var Ne,Ke,at;if(!(!te||te===x)&&!W)try{if(pn())return;if(A(!0),!c||!u){c&&g(c,{config:{systemPromptId:((Ne=u==null?void 0:u.config)==null?void 0:Ne.systemPromptId)||"default",baseSystemPrompt:((Ke=u==null?void 0:u.config)==null?void 0:Ke.baseSystemPrompt)||"",lastUsedEnhancedPrompt:((at=u==null?void 0:u.config)==null?void 0:at.lastUsedEnhancedPrompt)??null,...(u==null?void 0:u.config)||{},model:te}});return}await Wn.patchSession(c,{model:te}),g(c,{config:{...u.config,model:te}}),je.success(n("settings.providerTab.modelUpdated"))}catch(Be){je.error(`${n("settings.providerTab.updateModelErrorPrefix")}: ${fn(Be)}`)}finally{A(!1)}},[x,u,fn,W,je,pn,c,n,g]),Me=m.useCallback(te=>{Ee.getState().setSelectedModelRef(te),c&&(u!=null&&u.config)&&g(c,{config:{systemPromptId:u.config.systemPromptId,baseSystemPrompt:u.config.baseSystemPrompt,lastUsedEnhancedPrompt:u.config.lastUsedEnhancedPrompt,model_ref:te}})},[u==null?void 0:u.config,c,g]),Le=m.useMemo(()=>Vj({referenceText:D,isToolSpecificMode:Ue,isRestrictConversation:ht,allowedTools:Ge,autoToolPrefix:wt,t:n}),[D,Ue,ht,Ge,wt,n]),Qe=_t&&Ct?n("chat.respond.customAnswerPlaceholder"):_t?n("components.questionDialog.selectOptionWarning"):Le,Mt=_t?n("chat.respond.submitToolResult","Submit tool result"):void 0,Es=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]),Rs=m.useMemo(()=>Es[K]??K,[K,Es]),as=r.jsx(zn,{trigger:["click"],placement:"topLeft",disabled:!x||ye,menu:{selectable:!0,selectedKeys:[K],items:nC.map(te=>({key:te,label:Es[te]})),onClick:({key:te})=>{de(te)}},children:r.jsx(Y,{type:"text",size:"small",disabled:!x||ye,style:{minWidth:i?74:88,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:K==="medium"?a.colorTextSecondary:a.colorPrimary},title:n("chat.input.reasoningTitle",{label:Rs}),children:r.jsxs(X,{size:6,children:[r.jsx(xf,{}),r.jsx("span",{children:Rs}),r.jsx(Wt,{style:{fontSize:10}})]})})}),ys=x||n(Ut?"chat.model.selectModel":"chat.model.configureProvider"),As=m.useMemo(()=>Kn.length>0?Kn.map(te=>({key:te.value,label:te.label})):[{key:"__no_models__",label:$||n("chat.model.noModelsAvailable"),disabled:!0}],[Kn,$,n]),Is=r.jsx(Y,{type:"text",size:"small",disabled:ye||W,onClick:()=>{Ut||pn()},style:{minWidth:i?112:146,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:$?a.colorError:a.colorTextSecondary},title:ys,children:r.jsxs(X,{size:6,children:[S?r.jsx(gr,{}):r.jsx(ad,{}),r.jsx("span",{style:{maxWidth:i?84:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ys}),r.jsx(Wt,{style:{fontSize:10}})]})}),Kb=w()?r.jsx(Kj,{value:_,onChange:Me,disabled:ye||W}):Ut?r.jsx(zn,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:x?[x]:[],items:As,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:te})=>{te!=="__no_models__"&&ae(String(te))}},onOpenChange:ka,disabled:ye||W,children:Is}):Is;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(Xe,{type:"warning",showIcon:!0,icon:r.jsx(da,{}),message:n(Ut?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:n(Ut?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:Ut?void 0:r.jsx(X,{children:r.jsx("a",{onClick:()=>l("chat"),children:n("chat.model.openSettings")})}),style:{marginBottom:a.marginSM}}),Ue,D&&r.jsx(zj,{text:D,onClose:Er}),Ve.length>0&&r.jsx(m.Suspense,{fallback:r.jsx(ps,{size:"small"}),children:r.jsx(Gj,{files:Ve,onRemove:re,onClear:V})}),_t&&jt.length>0&&r.jsx("div",{style:{marginBottom:a.marginSM},children:r.jsx(X,{wrap:!0,size:[8,8],children:jt.map(te=>r.jsx(Y,{size:"small",onClick:()=>{hn(te)},disabled:ye,children:te},te))})}),r.jsx(Oj,{value:O,onChange:Q.handleInputChange,onSubmit:Pr,placeholder:Qe,allowImages:!0,disabled:!x||_t&&!Ct&&jt.length>0,statusIndicator:s,submitButtonLabel:Mt,isWorkflowSelectorVisible:Q.showCommandSelector,textAreaRef:o,validateMessage:te=>({isValid:!0}),onAttachmentsAdded:J,onWorkflowCommandChange:Q.handleCommandChange,onFileReferenceChange:se.handleFileReferenceChange,onFileReferenceButtonClick:se.handleFileReferenceButtonClick,leftControlsExtra:r.jsxs(X,{size:0,wrap:!0,children:[Kb,as]}),interaction:{isStreaming:ye,hasMessages:h.some(te=>te.role==="user"),allowRetry:!0,onRetry:Vn,onCancel:be,onHistoryNavigate:Ks}}),r.jsx(m.Suspense,{fallback:null,children:r.jsx(Jj,{visible:Q.showCommandSelector,onSelect:Q.handleCommandSelect,onCancel:Q.handleCommandSelectorCancel,onAutoComplete:Q.handleAutoComplete,searchText:Q.commandSearchText})}),se.showFileSelector&&r.jsx(m.Suspense,{fallback:r.jsx(ps,{size:"small"}),children:r.jsx(Zj,{visible:se.showFileSelector,files:se.workspaceFiles,searchText:se.fileSearchText,loading:se.isWorkspaceLoading,error:se.workspaceError,onSelect:se.handleFileReferenceSelect,onCancel:se.handleFileSelectorCancel,onChangeWorkspace:()=>{se.setWorkspacePathInput((u==null?void 0:u.config.workspacePath)??""),se.setIsWorkspaceModalVisible(!0)}})}),r.jsx(m.Suspense,{fallback:null,children:r.jsx(Qj,{open:se.isWorkspaceModalVisible,initialPath:se.workspacePathInput,loading:se.isSavingWorkspace,onSubmit:se.handleWorkspaceModalSubmit,onCancel:se.handleWorkspaceModalCancel})})]})},{Text:Fs}=le,lC=220,cC="chat-session-diff-collapse:",dC=e=>e.split(/[\\/]/).pop()||e,Uy=e=>`${cC}${e??"default"}`,Al=e=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Uy(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}},uC=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Uy(e),JSON.stringify(t))}catch{}},mC=({sessionDiffSummary:e,sessionId:t})=>{const{token:s}=he.useToken(),n=!!(e&&e.files.length>0),[o,a]=m.useState(n),[i,l]=m.useState(n),[c,d]=m.useState(()=>{var y;return((y=Al(t))==null?void 0:y.isExpanded)??!0}),[u,h]=m.useState(()=>{var y;return new Set(((y=Al(t))==null?void 0:y.expandedFiles)??[])});m.useEffect(()=>{if(n){a(!0);const f=window.setTimeout(()=>l(!0),0);return()=>window.clearTimeout(f)}l(!1);const y=window.setTimeout(()=>a(!1),lC);return()=>window.clearTimeout(y)},[n]);const p=m.useMemo(()=>e?e.files:[],[e]),g=m.useMemo(()=>{const y=new Map;return e&&e.files.forEach(f=>{y.set(f.filePath,Iy(f.unifiedDiff))}),y},[e]);return m.useEffect(()=>{const y=Al(t);d((y==null?void 0:y.isExpanded)??!0),h(new Set((y==null?void 0:y.expandedFiles)??[]))},[t]),m.useEffect(()=>{uC(t,{isExpanded:c,expandedFiles:Array.from(u)})},[t,c,u]),m.useEffect(()=>{if(!e||e.files.length===0)return;const y=new Set(e.files.map(f=>f.filePath));h(f=>{const v=new Set;let b=!1;return f.forEach(x=>{y.has(x)?v.add(x):b=!0}),!b&&v.size===f.size?f:v})},[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(ee,{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(X,{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(y=>!y),"data-testid":"session-diff-toggle",children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.marginSM,minWidth:0},children:[r.jsx(vf,{style:{color:s.colorPrimary}}),r.jsx(Fs,{strong:!0,style:{whiteSpace:"nowrap"},children:"Session diffs"}),r.jsxs(Fs,{type:"secondary",style:{fontSize:s.fontSizeSM,whiteSpace:"nowrap"},children:["(",e.files.length," files / ",e.changedTools," tools)"]}),r.jsxs(X,{size:4,style:{marginInlineStart:s.marginXS},children:[r.jsxs(Fs,{style:{color:s.colorSuccess,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",e.totalAdded]}),r.jsxs(Fs,{style:{color:s.colorError,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",e.totalRemoved]})]})]}),r.jsx("div",{style:{color:s.colorTextSecondary},children:c?r.jsx(Wt,{}):r.jsx(Ws,{})})]}),c&&r.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr",gap:6,maxHeight:280,overflowY:"auto"},"data-testid":"session-diff-file-list",children:p.map(y=>{const f=u.has(y.filePath),v=g.get(y.filePath)??[];return r.jsxs("div",{style:{border:`1px solid ${s.colorBorderSecondary}`,borderRadius:s.borderRadiusSM,overflow:"hidden",background:s.colorBgContainer},"data-testid":"session-diff-file-item","data-file-path":y.filePath,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.marginSM,padding:"4px 8px",borderRadius:s.borderRadiusSM,background:s.colorFillTertiary,cursor:"pointer"},onClick:()=>{h(b=>{const x=new Set(b);return x.has(y.filePath)?x.delete(y.filePath):x.add(y.filePath),x})},"data-testid":"session-diff-file-header","data-file-path":y.filePath,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.marginXS,minWidth:0,flex:1},children:[r.jsx("span",{style:{color:s.colorTextSecondary},children:f?r.jsx(Wt,{}):r.jsx(Ws,{})}),r.jsx(Fs,{ellipsis:{tooltip:y.filePath},style:{flex:1,minWidth:0,fontSize:s.fontSizeSM},children:dC(y.filePath)})]}),r.jsxs(X,{size:4,children:[r.jsxs(Fs,{style:{color:s.colorSuccess,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",y.added]}),r.jsxs(Fs,{style:{color:s.colorError,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",y.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":y.filePath,children:[v.length>0?v.map((b,x)=>{const _={margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:s.fontSizeSM,lineHeight:1.5,padding:"0 8px",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"};return b.kind==="add"?_.background=s.colorSuccessBg:b.kind==="remove"?_.background=s.colorErrorBg:b.kind==="modified_add"?(_.background=s.colorWarningBg,_.borderLeft=`3px solid ${s.colorSuccess}`):b.kind==="modified_remove"?(_.background=s.colorWarningBg,_.borderLeft=`3px solid ${s.colorError}`):b.kind==="hunk"?(_.background=s.colorFillSecondary,_.color=s.colorTextSecondary):b.kind==="meta"&&(_.background=s.colorFillTertiary,_.color=s.colorTextSecondary),r.jsx("pre",{style:_,"data-testid":"session-diff-line","data-kind":b.kind,children:b.text||" "},`${y.filePath}-${x}`)}):r.jsx(Fs,{type:"secondary",style:{display:"block",padding:"8px",fontSize:s.fontSizeSM},children:"No diff preview available."}),y.truncated&&r.jsx(Fs,{type:"secondary",style:{display:"block",padding:"6px 8px 8px",fontSize:s.fontSizeSM},children:"Diff truncated for display."})]})]},y.filePath)})})]})})})},hC=e=>{if(!e)return;const{activeLeafId:t,setLeafSessionId:s,setActiveLeafId:n}=Ae.getState();s(t,e),n(t),N.getState().selectSession(e)},pC=["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(" "),fC=["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(" "),gC=["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(" "),yC=["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(" "),bC=["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(" "),xC=["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(" "),vC=["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(" "),SC=["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(" "),wC=["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(" "),_C=["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(" "),TC=["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(" "),kC=["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(" "),jC=["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(" "),CC=["development","debugging","analysis","documentation","operations"],MC={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"}},PC=(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)||""}},qy=({sessionId:e=null,embedded:t=!1,hideHeader:s=!1,layoutMode:n="default"})=>{var T;const{t:o}=ne(),{token:a}=he.useToken(),{message:i}=Ot.useApp(),l=N(P=>e??P.currentSessionId),c=N(Xn(l)),d=N(P=>P.addChat),u=N(P=>P.lastSelectedPromptId),h=N(P=>P.setInputContent),p=N(P=>P.systemPrompts),g=N(P=>P.chats),[y,f]=m.useState(null),[v,b]=m.useState(""),x=(c==null?void 0:c.config.workspacePath)??((T=g.find(P=>P.config.workspacePath))==null?void 0:T.config.workspacePath),_=m.useMemo(()=>[{id:"blank",icon:r.jsx(Us,{}),title:o("chat.emptyLauncher.actions.blank.title","Blank session"),description:o("chat.emptyLauncher.actions.blank.description","Start from scratch with the default assistant and an empty composer."),sessionTitle:o("chat.emptyLauncher.actions.blank.sessionTitle","New Session"),prefill:o("chat.emptyLauncher.actions.blank.prefill",""),category:"development"},{id:"codeReview",icon:r.jsx(Li,{}),title:o("chat.emptyLauncher.actions.codeReview.title","Code review"),description:o("chat.emptyLauncher.actions.codeReview.description","Open a review-focused session with an editable review brief."),sessionTitle:o("chat.emptyLauncher.actions.codeReview.sessionTitle","Code Review"),prefill:o("chat.emptyLauncher.actions.codeReview.prefill","Review the relevant code changes in this workspace or repository. Start with the overall scope, then list risks, notable diffs, and the most important fixes."),baseSystemPrompt:pC,category:"development",recommendWorkspace:!0},{id:"implementFeature",icon:r.jsx(Sr,{}),title:o("chat.emptyLauncher.actions.implementFeature.title","Implement feature"),description:o("chat.emptyLauncher.actions.implementFeature.description","Plan and build a feature step by step following existing code conventions."),sessionTitle:o("chat.emptyLauncher.actions.implementFeature.sessionTitle","Implement Feature"),prefill:o("chat.emptyLauncher.actions.implementFeature.prefill","Help me implement a new feature in this workspace. Start by understanding the codebase structure, then propose an implementation plan before writing code."),baseSystemPrompt:gC,category:"development",recommendWorkspace:!0},{id:"refactor",icon:r.jsx(vf,{}),title:o("chat.emptyLauncher.actions.refactor.title","Refactor code"),description:o("chat.emptyLauncher.actions.refactor.description","Get targeted suggestions for improving code quality and maintainability."),sessionTitle:o("chat.emptyLauncher.actions.refactor.sessionTitle","Refactor Suggestion"),prefill:o("chat.emptyLauncher.actions.refactor.prefill","Suggest refactoring improvements for the code in this workspace. Focus on readability, maintainability, and performance. Propose incremental changes with clear rationale."),baseSystemPrompt:vC,category:"development",recommendWorkspace:!0},{id:"bugInvestigation",icon:r.jsx(bf,{}),title:o("chat.emptyLauncher.actions.bugInvestigation.title","Bug investigation"),description:o("chat.emptyLauncher.actions.bugInvestigation.description","Diagnose issues by analyzing code, logs, and runtime behavior."),sessionTitle:o("chat.emptyLauncher.actions.bugInvestigation.sessionTitle","Bug Investigation"),prefill:o("chat.emptyLauncher.actions.bugInvestigation.prefill","Help me investigate a bug. I'll describe the symptoms and share relevant code or logs. Trace the root cause and suggest targeted fixes."),baseSystemPrompt:fC,category:"debugging",recommendWorkspace:!0},{id:"explainError",icon:r.jsx(nd,{}),title:o("chat.emptyLauncher.actions.explainError.title","Explain error"),description:o("chat.emptyLauncher.actions.explainError.description","Understand what went wrong from an error message or stack trace."),sessionTitle:o("chat.emptyLauncher.actions.explainError.sessionTitle","Explain Error"),prefill:o("chat.emptyLauncher.actions.explainError.prefill","Help me understand the following error. Explain the root cause, suggest fixes, and share prevention tips."),baseSystemPrompt:bC,category:"debugging"},{id:"tokenUsage",icon:r.jsx(Sx,{}),title:o("chat.emptyLauncher.actions.tokenUsage.title","Token usage investigation"),description:o("chat.emptyLauncher.actions.tokenUsage.description","Diagnose context growth, truncation risk, and token budget pressure."),sessionTitle:o("chat.emptyLauncher.actions.tokenUsage.sessionTitle","Token Usage Investigation"),prefill:o("chat.emptyLauncher.actions.tokenUsage.prefill","Help me investigate token usage, context growth, and truncation risk for this session or workflow. Summarize the likely drivers and recommend concrete next fixes."),baseSystemPrompt:jC,category:"debugging"},{id:"architectureReview",icon:r.jsx(wx,{}),title:o("chat.emptyLauncher.actions.architectureReview.title","Read repo architecture"),description:o("chat.emptyLauncher.actions.architectureReview.description","Analyze repository structure, modules, and architectural patterns."),sessionTitle:o("chat.emptyLauncher.actions.architectureReview.sessionTitle","Architecture Review"),prefill:o("chat.emptyLauncher.actions.architectureReview.prefill","Analyze the architecture of this repository. Map the key modules, data flow, abstractions, and dependency patterns. Identify strengths and potential improvements."),baseSystemPrompt:yC,category:"analysis",recommendWorkspace:!0},{id:"compareFiles",icon:r.jsx(_x,{}),title:o("chat.emptyLauncher.actions.compareFiles.title","Compare files"),description:o("chat.emptyLauncher.actions.compareFiles.description","Diff and understand differences between files or code sections."),sessionTitle:o("chat.emptyLauncher.actions.compareFiles.sessionTitle","Compare Files"),prefill:o("chat.emptyLauncher.actions.compareFiles.prefill","Compare the following files or code sections. Highlight key differences, their implications, and any potential risks."),baseSystemPrompt:xC,category:"analysis",recommendWorkspace:!0},{id:"releaseNotes",icon:r.jsx(br,{}),title:o("chat.emptyLauncher.actions.releaseNotes.title","Generate release notes"),description:o("chat.emptyLauncher.actions.releaseNotes.description","Create structured release notes from git history and code changes."),sessionTitle:o("chat.emptyLauncher.actions.releaseNotes.sessionTitle","Release Notes"),prefill:o("chat.emptyLauncher.actions.releaseNotes.prefill","Generate release notes for the latest changes in this workspace. Categorize into features, fixes, improvements, and breaking changes."),baseSystemPrompt:SC,category:"documentation",recommendWorkspace:!0},{id:"summarizeWork",icon:r.jsx(Tx,{}),title:o("chat.emptyLauncher.actions.summarizeWork.title","Summarize work"),description:o("chat.emptyLauncher.actions.summarizeWork.description","Create a work summary for standups or weekly status reports."),sessionTitle:o("chat.emptyLauncher.actions.summarizeWork.sessionTitle","Work Summary"),prefill:o("chat.emptyLauncher.actions.summarizeWork.prefill","Help me summarize my recent work for a status update. Pull key accomplishments, blockers, and next steps."),baseSystemPrompt:wC,category:"documentation"},{id:"writeDocs",icon:r.jsx(br,{}),title:o("chat.emptyLauncher.actions.writeDocs.title","Write documentation"),description:o("chat.emptyLauncher.actions.writeDocs.description","Create or improve technical documentation from code and context."),sessionTitle:o("chat.emptyLauncher.actions.writeDocs.sessionTitle","Write Documentation"),prefill:o("chat.emptyLauncher.actions.writeDocs.prefill","Help me write technical documentation for this project. Analyze the code and produce clear, well-structured Markdown documentation."),baseSystemPrompt:_C,category:"documentation",recommendWorkspace:!0},{id:"createSchedule",icon:r.jsx(Ys,{}),title:o("chat.emptyLauncher.actions.createSchedule.title","Create scheduled task"),description:o("chat.emptyLauncher.actions.createSchedule.description","Set up a recurring task that runs automatically on a schedule."),sessionTitle:o("chat.emptyLauncher.actions.createSchedule.sessionTitle","Create Schedule"),prefill:o("chat.emptyLauncher.actions.createSchedule.prefill","Help me set up a recurring scheduled task. I'll describe what I want it to do, and you guide me through the configuration."),baseSystemPrompt:TC,category:"operations"},{id:"sessionReview",icon:r.jsx(sa,{}),title:o("chat.emptyLauncher.actions.sessionReview.title","Review session history"),description:o("chat.emptyLauncher.actions.sessionReview.description","Inspect and analyze past sessions for patterns and insights."),sessionTitle:o("chat.emptyLauncher.actions.sessionReview.sessionTitle","Session Review"),prefill:o("chat.emptyLauncher.actions.sessionReview.prefill","Help me review my recent session history. Summarize key decisions, outcomes, and areas that need follow-up."),baseSystemPrompt:kC,category:"operations"}],[o]),w=v.trim().toLowerCase(),k=m.useMemo(()=>w?_.filter(P=>P.title.toLowerCase().includes(w)||P.description.toLowerCase().includes(w)):_,[w,_]),C=m.useMemo(()=>{const P={};for(const S of k)P[S.category]||(P[S.category]=[]),P[S.category].push(S);return P},[k]),E=m.useCallback(P=>{typeof window>"u"||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent(Bc,{detail:{sessionId:P}}))},0)},[]),j=m.useCallback(async P=>{if(!y){f(P.id);try{const S=PC(p,u),L=await d({title:P.sessionTitle,createdAt:Date.now(),messages:[],config:{systemPromptId:S.systemPromptId,baseSystemPrompt:P.baseSystemPrompt??S.baseSystemPrompt,lastUsedEnhancedPrompt:null,...x?{workspacePath:x}:{}},currentInteraction:null});hC(L),P.prefill.trim().length>0&&h(L,P.prefill),E(L)}catch(S){console.error("[EmptyTaskLauncher] Failed to create session",S),i.error(S instanceof Error?S.message:o("chat.emptyLauncher.errors.createFailed","Failed to create session"))}finally{f(null)}}},[d,u,i,y,E,h,p,o,x]),R=m.useMemo(()=>({"--lotus-empty-launcher-border":a.colorBorderSecondary,"--lotus-empty-launcher-border-hover":a.colorPrimaryBorder,"--lotus-empty-launcher-bg":a.colorBgElevated,"--lotus-empty-launcher-icon-bg":a.colorPrimaryBg,"--lotus-empty-launcher-icon-color":a.colorPrimary,"--lotus-empty-launcher-text":a.colorText,"--lotus-empty-launcher-text-secondary":a.colorTextSecondary,"--lotus-empty-launcher-shadow":a.boxShadowSecondary,"--lotus-empty-launcher-shadow-hover":a.boxShadow,"--lotus-empty-launcher-category-border":a.colorBorderSecondary,"--lotus-empty-launcher-search-bg":a.colorBgContainer,"--lotus-empty-launcher-badge-bg":a.colorPrimaryBg,"--lotus-empty-launcher-badge-text":a.colorPrimary}),[a]),M=!!x;return r.jsxs("div",{className:`lotus-empty-task-launcher ${t?"is-embedded":""} ${s?"is-headerless":""} ${n==="staggered"?"is-staggered":""}`,style:R,children:[!s&&r.jsxs("div",{className:"lotus-empty-task-launcher__header",children:[r.jsx(le.Title,{level:t?4:3,style:{margin:0},children:o("chat.emptyLauncher.title","Start with a task")}),r.jsx(le.Paragraph,{type:"secondary",className:"lotus-empty-task-launcher__subtitle",children:o("chat.emptyLauncher.subtitle","Create a focused session in this pane and prefill the first message before you send it.")}),r.jsx(le.Text,{type:"secondary",className:"lotus-empty-task-launcher__hint",children:o("chat.emptyLauncher.hint","Nothing is sent automatically — you can edit the prompt first.")})]}),r.jsx("div",{className:"lotus-empty-task-launcher__search",children:r.jsx(me,{placeholder:o("chat.emptyLauncher.searchPlaceholder","Search templates..."),prefix:r.jsx(sa,{style:{color:a.colorTextQuaternary}}),value:v,onChange:P=>b(P.target.value),allowClear:!0,size:"middle",variant:"filled"})}),r.jsxs("div",{className:"lotus-empty-task-launcher__categories",children:[CC.map(P=>{const S=C[P];if(!S||S.length===0)return null;const L=MC[P];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:o(L.titleKey,L.fallback)}),r.jsx("div",{className:"lotus-empty-task-launcher__grid",children:S.map($=>{const I=y===$.id,W=$.recommendWorkspace&&M;return r.jsxs("button",{type:"button",className:"lotus-empty-task-card",onClick:()=>{j($)},disabled:y!==null,"aria-busy":I,"aria-label":$.title,children:[r.jsx("div",{className:"lotus-empty-task-card__icon","aria-hidden":!0,children:I?r.jsx(gr,{}):$.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:$.title}),r.jsx(kx,{className:"lotus-empty-task-card__arrow","aria-hidden":!0})]}),r.jsx("p",{className:"lotus-empty-task-card__description",children:$.description}),W&&r.jsx("div",{className:"lotus-empty-task-card__badges",children:r.jsxs("span",{className:"lotus-empty-task-card__badge",title:x,children:["📂 ",o("chat.emptyLauncher.badges.workspace","workspace")]})})]})]},$.id)})})]},P)}),k.length===0&&r.jsx("div",{className:"lotus-empty-task-launcher__no-results",children:r.jsx(le.Text,{type:"secondary",children:o("chat.emptyLauncher.noResults","No templates match your search. Try a different keyword or start a blank session.")})})]})]})},EC=({sessionId:e,isCenteredLayout:t,maxWidth:s,onWorkflowDraftChange:n,showMessagesView:o,sessionDiffSummary:a,contextUsageIndicator:i})=>r.jsx(G,{justify:"center",className:`chat-view-input-container-wrapper ${o?"messages-view":"centered-view"}`,children:r.jsxs("div",{style:{width:"100%",maxWidth:o?s:"min(100%, 920px)",margin:o?"0 auto":void 0,position:"relative",paddingBottom:o?12:0,display:"flex",flexDirection:"column",gap:o?0:24},children:[o&&r.jsx(mC,{sessionDiffSummary:a,sessionId:e}),!o&&e&&r.jsx(qy,{sessionId:e}),r.jsx(iC,{sessionId:e,isCenteredLayout:t,onWorkflowDraftChange:n,statusIndicator:i})]})});function rr(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((y,f)=>n[f]!==y)))return o;n=h;let g;if(s.key&&((l=s.debug)!=null&&l.call(s))&&(g=Date.now()),o=t(...h),s.key&&((c=s.debug)!=null&&c.call(s))){const y=Math.round((Date.now()-u)*100)/100,f=Math.round((Date.now()-g)*100)/100,v=f/16,b=(x,_)=>{for(x=String(x);x.length<_;)x=" "+x;return x};console.info(`%c⏱ ${b(f,5)} /${b(y,5)} ms`,`
|
|
175
|
+
font-size: .6rem;
|
|
176
|
+
font-weight: bold;
|
|
177
|
+
color: hsl(${Math.max(0,Math.min(120-120*v,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 yh(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const RC=(e,t)=>Math.abs(e-t)<1.01,AC=(e,t,s)=>{let n;return function(...o){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,o),s)}},bh=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},IC=e=>e,$C=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},DC=(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(bh(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(bh(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(s,{box:"border-box"}),()=>{a.unobserve(s)}},xh={passive:!0},vh=typeof window>"u"?!0:"onscrollend"in window,LC=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;let o=0;const a=e.options.useScrollendEvent&&vh?()=>{}:AC(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,xh);const d=e.options.useScrollendEvent&&vh;return d&&s.addEventListener("scrollend",c,xh),()=>{s.removeEventListener("scroll",l),d&&s.removeEventListener("scrollend",c)}},OC=(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"]},FC=(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 zC{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:IC,rangeExtractor:$C,onChange:()=>{},measureElement:OC,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=rr(()=>(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=rr(()=>[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=rr(()=>[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),g=p?p.end+this.options.gap:n+o,y=l.get(h),f=typeof y=="number"?y:this.options.estimateSize(u),v=g+f,b=p?p.lane:u%this.options.lanes;d[u]={index:u,start:g,size:f,end:v,key:h,lane:b}}return this.measurementsCache=d,d},{key:!1,debug:()=>this.options.debug}),this.calculateRange=rr(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,n,o,a)=>this.range=s.length>0&&n>0?NC({measurements:s,outerSize:n,scrollOffset:o,lanes:a}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=rr(()=>{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=rr(()=>[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 yh(n[Hy(0,n.length-1,o=>yh(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 g=this.getScrollOffset(),y=this.getOffsetForIndex(s,p);if(!y){console.warn("Failed to get offset for index:",s);return}RC(y[0],g)||c(p)})},c=d=>{this.targetWindow&&(a++,a<i?this.targetWindow.requestAnimationFrame(()=>l(d)):console.warn(`Failed to scroll to index ${s} after ${i} attempts.`))};l(n)},this.scrollBy=(s,{behavior:n}={})=>{n==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getScrollOffset()+s,{adjustments:void 0,behavior:n})},this.getTotalSize=()=>{var s;const n=this.getMeasurements();let 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 Hy=(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 NC({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=Hy(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 Sh=typeof document<"u"?m.useLayoutEffect:m.useEffect;function BC(e){const t=m.useReducer(()=>({}),{})[1],s={...e,onChange:(o,a)=>{var i;a?jx.flushSync(t):t(),(i=e.onChange)==null||i.call(e,o,a)}},[n]=m.useState(()=>new zC(s));return n.setOptions(s),Sh(()=>n._didMount(),[]),Sh(()=>n._willUpdate()),n}function WC(e){return BC({observeElementRect:DC,observeElementOffset:LC,scrollToFn:FC,...e})}const{Text:wh,Paragraph:UC}=le,qC=({content:e,token:t,headingColor:s})=>r.jsx(hs,{components:{p:({children:n})=>r.jsx(UC,{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(wh,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block",color:s},children:n}),h2:({children:n})=>r.jsx(wh,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block",color:s},children:n})},children:e}),_h=m.memo(qC),HC=e=>{if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null},YC=e=>e?[["base",e.base_system_prompt],["enhancement",e.enhancement_prompt],["workspace",e.workspace_context],["instruction",e.instruction_context],["env",e.env_context],["skills",e.skill_context],["toolGuide",e.tool_guide_context],["dream",e.dream_notebook],["sessionMemory",e.session_memory_note],["externalMemory",e.external_memory],["taskList",e.task_list],["effective",e.effective_system_prompt]].flatMap(([s,n])=>{const o=HC(n);return o?[{key:s,content:o}]:[]}):[],XC=({currentChat:e,message:t,systemPrompts:s})=>{var M;const[n,o]=m.useState(null),[a,i]=m.useState(null),[l,c]=m.useState(null),[d,u]=m.useState(!1),[h,p]=m.useState(!1),g=m.useMemo(()=>yi.getInstance(),[]),y=m.useMemo(()=>rs.getInstance(),[]),f=t.role==="system"&&typeof t.content=="string"?t.content:"",v=t.role==="system"&&!t.id.startsWith("system-prompt-")&&f.trim().length>0;m.useEffect(()=>{t.role==="system"&&(i(null),c(null),p(!1))},[t.id,t.role,f]);const b=(e==null?void 0:e.id)??null,x=((M=e==null?void 0:e.config)==null?void 0:M.systemPromptId)??null,_=m.useMemo(()=>x?s.find(T=>T.id===x)??null:null,[x,s]),w=(_==null?void 0:_.content)??(n==null?void 0:n.content)??"",k=(_==null?void 0:_.description)??(n==null?void 0:n.description)??"",C=m.useRef(null);m.useEffect(()=>{o(null),C.current=null},[b,x]),m.useEffect(()=>{if(!x)return;const T=x;if(_!=null&&_.content)return;const P=`${b??"no-chat"}:${T}`;if(C.current===P)return;C.current=P;let S=!1;return(async()=>{try{const $=await g.findPresetById(T);if(S)return;const I=$?{content:$.content,description:$.description}:null;o(W=>!W&&!I||W&&I&&W.content===I.content&&W.description===I.description?W:I)}catch($){console.error("Failed to load preset prompt:",$)}})(),()=>{S=!0}},[b,x,g,_==null?void 0:_.content]);const E=m.useCallback(async()=>{var T;if(!d){u(!0);try{if(b)try{const P=await y.getSessionSystemPrompt(b);c(P);const S=(T=P.effective_system_prompt)==null?void 0:T.trim();if(S){i(S),p(!0);return}}catch(P){console.warn("Failed to load backend prompt snapshot:",P)}if(v){c(null),i(f),p(!0);return}console.warn("Enhanced prompt snapshot unavailable; keeping base prompt view.")}catch(P){console.error("Failed to load enhanced prompt:",P)}finally{u(!1)}}},[y,b,v,d,f]),j=m.useMemo(()=>h&&a?a:w||k||(t.role==="system"?f:"System prompt is being prepared..."),[h,a,w,k,t.role,f]),R=m.useMemo(()=>YC(l),[l]);return{basePrompt:w,categoryDescription:k,enhancedPrompt:a,loadingEnhanced:d,loadEnhancedPrompt:E,promptSnapshot:l,promptToDisplay:j,showEnhanced:h,setShowEnhanced:p,snapshotSections:R,systemMessageContent:f}},{Text:Th}=le,{useToken:VC}=he,KC=(e,t)=>({base:e("chat.prompt.systemCard.sections.base"),enhancement:e("chat.prompt.systemCard.sections.enhancement"),workspace:e("chat.prompt.systemCard.sections.workspace"),instruction:e("chat.prompt.systemCard.sections.instruction"),env:e("chat.prompt.systemCard.sections.env"),skills:e("chat.prompt.systemCard.sections.skills"),toolGuide:e("chat.prompt.systemCard.sections.toolGuide"),dream:e("chat.prompt.systemCard.sections.dream"),sessionMemory:e("chat.prompt.systemCard.sections.sessionMemory"),externalMemory:e("chat.prompt.systemCard.sections.externalMemory"),taskList:e("chat.prompt.systemCard.sections.taskList"),effective:e("chat.prompt.systemCard.sections.effective")})[t],GC=({currentChat:e,message:t})=>{const{token:s}=VC(),{t:n}=ne(),o=N(y=>y.systemPrompts),{basePrompt:a,loadingEnhanced:i,loadEnhancedPrompt:l,promptSnapshot:c,promptToDisplay:d,showEnhanced:u,setShowEnhanced:h,snapshotSections:p}=XC({currentChat:e,message:t,systemPrompts:o}),g=m.useCallback(async y=>{try{await os(y)}catch(f){console.error("Failed to copy text:",f)}},[]);return r.jsx(ee,{style:{width:"100%",maxWidth:"100%",background:s.colorBgContainer,borderRadius:s.borderRadiusLG,boxShadow:"none"},children:r.jsxs(X,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[r.jsxs(G,{justify:"space-between",align:"center",children:[r.jsx(G,{align:"center",gap:s.marginXS,children:r.jsx(Th,{type:"secondary",strong:!0,style:{fontSize:s.fontSizeSM},children:n("chat.prompt.systemCard.title")})}),r.jsxs(X,{children:[a&&!u?r.jsx(Y,{type:"text",size:"small",icon:r.jsx(td,{}),onClick:l,loading:i,children:n("chat.prompt.systemCard.viewEnhanced")}):null,a&&u?r.jsx(Y,{type:"text",size:"small",onClick:()=>h(!1),children:n("chat.prompt.systemCard.viewBase")}):null,r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ss,{}),onClick:()=>g(d),children:n("chat.prompt.systemCard.copy")})]})]}),r.jsx(G,{vertical:!0,style:{maxHeight:u?400:300,overflowY:"auto",paddingRight:s.paddingXS},children:r.jsx(_h,{content:d,token:s,headingColor:s.colorPrimary})}),c&&p.length>0?r.jsxs(r.Fragment,{children:[r.jsx(Rt,{style:{margin:`${s.marginXS}px 0`}}),r.jsxs(X,{direction:"vertical",size:s.marginXS,style:{width:"100%"},children:[r.jsx(Th,{type:"secondary",strong:!0,style:{fontSize:s.fontSizeSM},children:n("chat.prompt.systemCard.snapshotTitle")}),r.jsx(ns,{defaultActiveKey:p.map(y=>y.key),items:p.map(y=>({key:y.key,label:KC(n,y.key),children:r.jsx(_h,{content:y.content,token:s,headingColor:s.colorPrimary})}))})]})]}):null]})})},Yy=m.memo(GC);Yy.displayName="SystemMessageCard";const Xy=6048e5,JC=864e5,kh=Symbol.for("constructDateFrom");function ln(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&kh in e?e[kh](t):e instanceof Date?new e.constructor(t):new Date(t)}function gs(e,t){return ln(t||e,e)}let QC={};function Ki(){return QC}function la(e,t){var l,c,d,u;const s=Ki(),n=(t==null?void 0:t.weekStartsOn)??((c=(l=t==null?void 0:t.locale)==null?void 0:l.options)==null?void 0:c.weekStartsOn)??s.weekStartsOn??((u=(d=s.locale)==null?void 0:d.options)==null?void 0:u.weekStartsOn)??0,o=gs(e,t==null?void 0:t.in),a=o.getDay(),i=(a<n?7:0)+a-n;return o.setDate(o.getDate()-i),o.setHours(0,0,0,0),o}function Ei(e,t){return la(e,{...t,weekStartsOn:1})}function Vy(e,t){const s=gs(e,t==null?void 0:t.in),n=s.getFullYear(),o=ln(s,0);o.setFullYear(n+1,0,4),o.setHours(0,0,0,0);const a=Ei(o),i=ln(s,0);i.setFullYear(n,0,4),i.setHours(0,0,0,0);const l=Ei(i);return s.getTime()>=a.getTime()?n+1:s.getTime()>=l.getTime()?n:n-1}function jh(e){const t=gs(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 ZC(e,...t){const s=ln.bind(null,t.find(n=>typeof n=="object"));return t.map(s)}function Ch(e,t){const s=gs(e,t==null?void 0:t.in);return s.setHours(0,0,0,0),s}function eM(e,t,s){const[n,o]=ZC(s==null?void 0:s.in,e,t),a=Ch(n),i=Ch(o),l=+a-jh(a),c=+i-jh(i);return Math.round((l-c)/JC)}function tM(e,t){const s=Vy(e,t),n=ln(e,0);return n.setFullYear(s,0,4),n.setHours(0,0,0,0),Ei(n)}function sM(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function nM(e){return!(!sM(e)&&typeof e!="number"||isNaN(+gs(e)))}function rM(e,t){const s=gs(e,t==null?void 0:t.in);return s.setFullYear(s.getFullYear(),0,1),s.setHours(0,0,0,0),s}const oM={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"}},aM=(e,t,s)=>{let n;const o=oM[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 Il(e){return(t={})=>{const s=t.width?String(t.width):e.defaultWidth;return e.formats[s]||e.formats[e.defaultWidth]}}const iM={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},lM={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},cM={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},dM={date:Il({formats:iM,defaultWidth:"full"}),time:Il({formats:lM,defaultWidth:"full"}),dateTime:Il({formats:cM,defaultWidth:"full"})},uM={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},mM=(e,t,s,n)=>uM[e];function Xr(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 hM={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},pM={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},fM={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"]},gM={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"]},yM={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"}},bM={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"}},xM=(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"},vM={ordinalNumber:xM,era:Xr({values:hM,defaultWidth:"wide"}),quarter:Xr({values:pM,defaultWidth:"wide",argumentCallback:e=>e-1}),month:Xr({values:fM,defaultWidth:"wide"}),day:Xr({values:gM,defaultWidth:"wide"}),dayPeriod:Xr({values:yM,defaultWidth:"wide",formattingValues:bM,defaultFormattingWidth:"wide"})};function Vr(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)?wM(l,h=>h.test(i)):SM(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 SM(e,t){for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)&&t(e[s]))return s}function wM(e,t){for(let s=0;s<e.length;s++)if(t(e[s]))return s}function _M(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 TM=/^(\d+)(th|st|nd|rd)?/i,kM=/\d+/i,jM={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},CM={any:[/^b/i,/^(a|c)/i]},MM={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},PM={any:[/1/i,/2/i,/3/i,/4/i]},EM={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},RM={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]},AM={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},IM={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]},$M={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},DM={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}},LM={ordinalNumber:_M({matchPattern:TM,parsePattern:kM,valueCallback:e=>parseInt(e,10)}),era:Vr({matchPatterns:jM,defaultMatchWidth:"wide",parsePatterns:CM,defaultParseWidth:"any"}),quarter:Vr({matchPatterns:MM,defaultMatchWidth:"wide",parsePatterns:PM,defaultParseWidth:"any",valueCallback:e=>e+1}),month:Vr({matchPatterns:EM,defaultMatchWidth:"wide",parsePatterns:RM,defaultParseWidth:"any"}),day:Vr({matchPatterns:AM,defaultMatchWidth:"wide",parsePatterns:IM,defaultParseWidth:"any"}),dayPeriod:Vr({matchPatterns:$M,defaultMatchWidth:"any",parsePatterns:DM,defaultParseWidth:"any"})},OM={code:"en-US",formatDistance:aM,formatLong:dM,formatRelative:mM,localize:vM,match:LM,options:{weekStartsOn:0,firstWeekContainsDate:1}};function FM(e,t){const s=gs(e,t==null?void 0:t.in);return eM(s,rM(s))+1}function zM(e,t){const s=gs(e,t==null?void 0:t.in),n=+Ei(s)-+tM(s);return Math.round(n/Xy)+1}function Ky(e,t){var u,h,p,g;const s=gs(e,t==null?void 0:t.in),n=s.getFullYear(),o=Ki(),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??((g=(p=o.locale)==null?void 0:p.options)==null?void 0:g.firstWeekContainsDate)??1,i=ln((t==null?void 0:t.in)||e,0);i.setFullYear(n+1,0,a),i.setHours(0,0,0,0);const l=la(i,t),c=ln((t==null?void 0:t.in)||e,0);c.setFullYear(n,0,a),c.setHours(0,0,0,0);const d=la(c,t);return+s>=+l?n+1:+s>=+d?n:n-1}function NM(e,t){var l,c,d,u;const s=Ki(),n=(t==null?void 0:t.firstWeekContainsDate)??((c=(l=t==null?void 0:t.locale)==null?void 0:l.options)==null?void 0:c.firstWeekContainsDate)??s.firstWeekContainsDate??((u=(d=s.locale)==null?void 0:d.options)==null?void 0:u.firstWeekContainsDate)??1,o=Ky(e,t),a=ln((t==null?void 0:t.in)||e,0);return a.setFullYear(o,0,n),a.setHours(0,0,0,0),la(a,t)}function BM(e,t){const s=gs(e,t==null?void 0:t.in),n=+la(s,t)-+NM(s,t);return Math.round(n/Xy)+1}function We(e,t){const s=e<0?"-":"",n=Math.abs(e).toString().padStart(t,"0");return s+n}const en={y(e,t){const s=e.getFullYear(),n=s>0?s:1-s;return We(t==="yy"?n%100:n,t.length)},M(e,t){const s=e.getMonth();return t==="M"?String(s+1):We(s+1,2)},d(e,t){return We(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 We(e.getHours()%12||12,t.length)},H(e,t){return We(e.getHours(),t.length)},m(e,t){return We(e.getMinutes(),t.length)},s(e,t){return We(e.getSeconds(),t.length)},S(e,t){const s=t.length,n=e.getMilliseconds(),o=Math.trunc(n*Math.pow(10,s-3));return We(o,t.length)}},or={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Mh={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 en.y(e,t)},Y:function(e,t,s,n){const o=Ky(e,n),a=o>0?o:1-o;if(t==="YY"){const i=a%100;return We(i,2)}return t==="Yo"?s.ordinalNumber(a,{unit:"year"}):We(a,t.length)},R:function(e,t){const s=Vy(e);return We(s,t.length)},u:function(e,t){const s=e.getFullYear();return We(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 We(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 We(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 en.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 We(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=BM(e,n);return t==="wo"?s.ordinalNumber(o,{unit:"week"}):We(o,t.length)},I:function(e,t,s){const n=zM(e);return t==="Io"?s.ordinalNumber(n,{unit:"week"}):We(n,t.length)},d:function(e,t,s){return t==="do"?s.ordinalNumber(e.getDate(),{unit:"date"}):en.d(e,t)},D:function(e,t,s){const n=FM(e);return t==="Do"?s.ordinalNumber(n,{unit:"dayOfYear"}):We(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 We(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 We(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 We(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=or.noon:n===0?o=or.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=or.evening:n>=12?o=or.afternoon:n>=4?o=or.morning:o=or.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 en.h(e,t)},H:function(e,t,s){return t==="Ho"?s.ordinalNumber(e.getHours(),{unit:"hour"}):en.H(e,t)},K:function(e,t,s){const n=e.getHours()%12;return t==="Ko"?s.ordinalNumber(n,{unit:"hour"}):We(n,t.length)},k:function(e,t,s){let n=e.getHours();return n===0&&(n=24),t==="ko"?s.ordinalNumber(n,{unit:"hour"}):We(n,t.length)},m:function(e,t,s){return t==="mo"?s.ordinalNumber(e.getMinutes(),{unit:"minute"}):en.m(e,t)},s:function(e,t,s){return t==="so"?s.ordinalNumber(e.getSeconds(),{unit:"second"}):en.s(e,t)},S:function(e,t){return en.S(e,t)},X:function(e,t,s){const n=e.getTimezoneOffset();if(n===0)return"Z";switch(t){case"X":return Eh(n);case"XXXX":case"XX":return Tn(n);case"XXXXX":case"XXX":default:return Tn(n,":")}},x:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"x":return Eh(n);case"xxxx":case"xx":return Tn(n);case"xxxxx":case"xxx":default:return Tn(n,":")}},O:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+Ph(n,":");case"OOOO":default:return"GMT"+Tn(n,":")}},z:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+Ph(n,":");case"zzzz":default:return"GMT"+Tn(n,":")}},t:function(e,t,s){const n=Math.trunc(+e/1e3);return We(n,t.length)},T:function(e,t,s){return We(+e,t.length)}};function Ph(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+We(a,2)}function Eh(e,t){return e%60===0?(e>0?"-":"+")+We(Math.abs(e)/60,2):Tn(e,t)}function Tn(e,t=""){const s=e>0?"-":"+",n=Math.abs(e),o=We(Math.trunc(n/60),2),a=We(n%60,2);return s+o+t+a}const Rh=(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"})}},Gy=(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"})}},WM=(e,t)=>{const s=e.match(/(P+)(p+)?/)||[],n=s[1],o=s[2];if(!o)return Rh(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}}",Rh(n,t)).replace("{{time}}",Gy(o,t))},UM={p:Gy,P:WM},qM=/^D+$/,HM=/^Y+$/,YM=["D","DD","YY","YYYY"];function XM(e){return qM.test(e)}function VM(e){return HM.test(e)}function KM(e,t,s){const n=GM(e,t,s);if(console.warn(n),YM.includes(e))throw new RangeError(n)}function GM(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 JM=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,QM=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,ZM=/^'([^]*?)'?$/,eP=/''/g,tP=/[a-zA-Z]/;function sP(e,t,s){var u,h,p,g;const n=Ki(),o=n.locale??OM,a=n.firstWeekContainsDate??((h=(u=n.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??1,i=n.weekStartsOn??((g=(p=n.locale)==null?void 0:p.options)==null?void 0:g.weekStartsOn)??0,l=gs(e,s==null?void 0:s.in);if(!nM(l))throw new RangeError("Invalid time value");let c=t.match(QM).map(y=>{const f=y[0];if(f==="p"||f==="P"){const v=UM[f];return v(y,o.formatLong)}return y}).join("").match(JM).map(y=>{if(y==="''")return{isToken:!1,value:"'"};const f=y[0];if(f==="'")return{isToken:!1,value:nP(y)};if(Mh[f])return{isToken:!0,value:y};if(f.match(tP))throw new RangeError("Format string contains an unescaped latin alphabet character `"+f+"`");return{isToken:!1,value:y}});o.localize.preprocessor&&(c=o.localize.preprocessor(l,c));const d={firstWeekContainsDate:a,weekStartsOn:i,locale:o};return c.map(y=>{if(!y.isToken)return y.value;const f=y.value;(VM(f)||XM(f))&&KM(f,t,String(e));const v=Mh[f[0]];return v(l,f,o.localize,d)}).join("")}function nP(e){const t=e.match(ZM);return t?t[1].replace(eP,"'"):e}const{useToken:rP}=he,{Text:Ua}=le,oP=({images:e,className:t,style:s,maxHeight:n={single:400,multiple:200}})=>{const{token:o}=rP(),{t:a}=ne();return!e||e.length===0?null:r.jsx(ee,{className:t,style:{marginBottom:o.marginMD,...s},styles:{body:{padding:0}},variant:"borderless",children:r.jsx(G,{wrap:"wrap",gap:o.marginSM,style:{width:"100%"},children:e.map(i=>r.jsxs(ee,{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(Cx,{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(G,{align:"center",justify:"center",gap:o.marginXS,style:{color:o.colorTextLightSolid},children:[r.jsx(td,{}),r.jsx(Ua,{style:{color:o.colorTextLightSolid},children:a("components.imageGrid.preview")})]})}}),r.jsxs(G,{vertical:!0,style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(transparent, rgba(0,0,0,0.7))",color:o.colorTextLightSolid,padding:`${o.paddingXS}px ${o.paddingSM}px`,fontSize:o.fontSizeSM},children:[r.jsx(Ua,{style:{color:o.colorTextLightSolid},strong:!0,children:i.name}),i.size&&r.jsxs(Ua,{style:{fontSize:o.fontSizeSM*.85,opacity:.8,color:o.colorTextLightSolid},children:[(i.size/1024).toFixed(1)," KB",i.width&&i.height&&` • ${i.width}×${i.height}`]})]})]}),(i.ocrText||i.ocrError)&&r.jsx("div",{style:{padding:o.paddingSM},children:r.jsx(ns,{ghost:!0,size:"small",items:[{key:"ocr",label:a("components.imageGrid.ocr"),children:r.jsxs(r.Fragment,{children:[i.ocrError&&r.jsx(Ua,{type:"danger",children:i.ocrError}),i.ocrText&&r.jsx(le.Paragraph,{style:{marginTop:i.ocrError?o.marginXS:0,marginBottom:0,whiteSpace:"pre-wrap"},children:i.ocrText})]})}]})})]},i.id))})})},{useToken:aP}=he,{useBreakpoint:iP}=$i,lP=({buttons:e,isVisible:t,className:s,style:n,position:o={bottom:"8px",right:"8px"}})=>{const{token:a}=aP(),i=iP(),l=()=>(i.xs,"small");return r.jsx(G,{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(ke,{title:c.title,children:r.jsx(Y,{"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))})},cP=(e,t)=>({key:"copy","data-testid":"copy-message",icon:r.jsx(ss,{}),title:t||"Copy message",onClick:e}),dP=(e,t)=>({key:"reference",icon:r.jsx(Sf,{}),title:t||"Reference message",onClick:e}),{Title:Ah,Text:Yt,Paragraph:Ih}=le,{useToken:uP}=he,mP=({plan:e,contextId:t,onExecute:s,onRefine:n,timestamp:o})=>{const{t:a}=ne(),{token:i}=uP(),[l,c]=m.useState(!1),[d,u]=m.useState(""),h=()=>{d.trim()&&(n(d),u(""),c(!1))};return r.jsxs(ee,{style:{marginBottom:i.marginMD,borderColor:i.colorPrimary,borderWidth:2,backgroundColor:i.colorPrimaryBg},title:r.jsxs(X,{children:[r.jsx(Hs,{style:{color:i.colorPrimary}}),r.jsx(Yt,{strong:!0,style:{color:i.colorPrimary},children:a("components.plan.executionPlan")})]}),extra:o?r.jsx(Yt,{type:"secondary",style:{fontSize:i.fontSizeSM},children:o}):void 0,children:[r.jsxs(G,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(Ah,{level:5,style:{marginBottom:i.marginXS},children:a("components.plan.goal")}),r.jsx(Ih,{style:{fontSize:15,marginBottom:0},children:e.goal})]}),r.jsxs(G,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(Ah,{level:5,style:{marginBottom:i.marginMD},children:a("components.plan.steps")}),r.jsx(Mx,{direction:"vertical",current:-1,items:e.steps.map(p=>({title:r.jsxs(Yt,{strong:!0,children:[a("components.plan.stepTitle",{number:p.step_number}),": ",p.action]}),description:r.jsxs(G,{vertical:!0,children:[r.jsxs(Ih,{style:{marginBottom:i.marginXS},children:[r.jsxs(Yt,{type:"secondary",children:[a("components.plan.reason"),":"]})," ",p.reason]}),r.jsxs(X,{wrap:!0,children:[r.jsxs(Yt,{type:"secondary",children:[r.jsx(Sr,{})," ",a("components.plan.tools"),":"]}),p.tools_needed.map((g,y)=>r.jsx(oe,{color:"processing",children:g},y))]}),r.jsx(G,{style:{marginTop:i.marginXS},children:r.jsxs(Yt,{type:"secondary",children:[r.jsx(Ys,{})," ",a("components.plan.estimated"),": ",p.estimated_time]})})]}),icon:r.jsx(Yt,{children:p.step_number})}))})]}),r.jsxs(X,{direction:"vertical",style:{width:"100%",marginBottom:i.marginLG},children:[r.jsxs(G,{align:"center",gap:i.marginXS,wrap:"wrap",children:[r.jsxs(Yt,{type:"secondary",children:[r.jsx(Ys,{})," ",a("components.plan.totalEstimatedTime")," "]}),r.jsx(oe,{color:"processing",children:e.estimated_total_time})]}),e.prerequisites&&e.prerequisites.length>0&&r.jsxs(G,{vertical:!0,children:[r.jsxs(Yt,{type:"secondary",children:[a("components.plan.prerequisites"),":"]}),r.jsx(nt,{size:"small",dataSource:e.prerequisites,renderItem:(p,g)=>r.jsx(nt.Item,{style:{padding:0},children:r.jsx(Yt,{children:p})},`${p}-${g}`)})]})]}),e.risks&&e.risks.length>0&&r.jsx(ns,{ghost:!0,style:{marginBottom:i.marginLG},items:[{key:"risks",label:r.jsxs(X,{children:[r.jsx(ua,{style:{color:i.colorWarning}}),r.jsx(Yt,{strong:!0,children:a("components.plan.potentialRisks",{count:e.risks.length})})]}),children:r.jsx(nt,{size:"small",dataSource:e.risks,renderItem:(p,g)=>r.jsx(nt.Item,{style:{padding:0},children:r.jsx(Yt,{children:p})},`${p}-${g}`)})}]}),r.jsx(X,{style:{width:"100%",justifyContent:"flex-end"},children:l?r.jsxs(r.Fragment,{children:[r.jsx(Y,{onClick:()=>c(!1),children:a("common.cancel")}),r.jsx(Y,{type:"primary",onClick:h,disabled:!d.trim(),children:a("components.plan.sendFeedback")})]}):r.jsxs(r.Fragment,{children:[r.jsx(Y,{onClick:()=>c(!0),children:a("components.plan.refinePlan")}),r.jsx(Y,{type:"primary",icon:r.jsx(wf,{}),onClick:s,children:a("components.plan.executePlan")})]})}),l&&r.jsx(G,{vertical:!0,style:{marginTop:i.marginMD},children:r.jsx(me.TextArea,{value:d,onChange:p=>u(p.target.value),placeholder:a("components.plan.feedbackPlaceholder"),autoSize:{minRows:4,maxRows:10}})})]})},Jy=m.memo(mP);Jy.displayName="PlanMessageCard";const{Title:hP,Text:ar,Paragraph:pP}=le,{useToken:fP}=he,gP=({question:e,contextId:t,onAnswer:s,disabled:n=!1,timestamp:o})=>{const{t:a}=ne(),{token:i}=fP(),[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(Oi,{style:{color:i.colorError}});case"major":return r.jsx(ua,{style:{color:i.colorWarning}});case"minor":return r.jsx(At,{style:{color:i.colorInfo}});default:return r.jsx(nd,{style:{color:i.colorPrimary}})}},g=()=>{switch(e.severity){case"critical":return i.colorErrorBg;case"major":return i.colorWarningBg;case"minor":return i.colorInfoBg;default:return i.colorPrimaryBg}},y=()=>{switch(e.severity){case"critical":return i.colorError;case"major":return i.colorWarning;case"minor":return i.colorInfo;default:return i.colorPrimary}};return r.jsxs(ee,{style:{marginBottom:i.marginMD,borderColor:y(),borderWidth:2,backgroundColor:g()},title:r.jsxs(X,{children:[p(),r.jsx(ar,{strong:!0,style:{color:y()},children:a("components.question.agentQuestion")}),r.jsxs(ar,{type:"secondary",style:{fontSize:12},children:["(",e.severity,")"]})]}),extra:o?r.jsx(ar,{type:"secondary",style:{fontSize:i.fontSizeSM},children:o}):void 0,children:[r.jsx(G,{vertical:!0,style:{marginBottom:i.marginLG},children:r.jsx(hP,{level:5,style:{marginBottom:i.marginXS},children:e.question})}),e.context&&r.jsx(Xe,{message:a("components.question.context"),description:e.context,type:"info",showIcon:!0,style:{marginBottom:i.marginLG}}),r.jsxs(G,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(ar,{strong:!0,style:{display:"block",marginBottom:i.marginSM},children:a("components.question.chooseOption")}),r.jsx(ts.Group,{value:l,onChange:f=>c(f.target.value),disabled:n||d,style:{width:"100%"},children:r.jsx(X,{direction:"vertical",style:{width:"100%"},children:e.options.map(f=>r.jsx(ee,{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(ts,{value:f.value,style:{width:"100%"},children:r.jsxs(G,{vertical:!0,children:[r.jsxs(G,{align:"center",gap:i.marginXS,wrap:"wrap",children:[r.jsx(ar,{strong:!0,children:f.label}),f.value===e.default&&r.jsx(oe,{color:"processing",style:{marginLeft:i.marginXS},children:a("components.question.recommended")})]}),r.jsx(pP,{type:"secondary",style:{marginTop:i.marginXXS,marginBottom:0},children:f.description})]})})},f.value))})})]}),e.allow_custom&&r.jsxs(G,{vertical:!0,style:{marginBottom:i.marginMD},children:[r.jsx(ar,{type:"secondary",style:{fontSize:12},children:a("components.question.customAnswerHint")}),r.jsx(me.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(G,{justify:"flex-end",children:r.jsx(Y,{type:"primary",icon:r.jsx(Hs,{}),onClick:h,loading:d,disabled:n||!l,children:a("components.question.submitAnswer")})})]})},Qy=m.memo(gP);Qy.displayName="QuestionMessageCard";const{Text:$h}=le,yP=({paths:e,displayText:t})=>{const{token:s}=he.useToken(),n=t.replace(/@[^\s]+/g,"").trim();return r.jsxs(ee,{size:"small",styles:{body:{padding:`${s.paddingSM}px ${s.paddingMD}px`}},style:{maxWidth:"100%"},children:[r.jsx(X,{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(G,{vertical:!0,children:[r.jsxs(X,{size:s.marginXS,align:"center",wrap:!0,children:[c?r.jsx(hi,{style:{color:s.colorWarning,fontSize:s.fontSizeLG}}):r.jsx(br,{style:{color:s.colorPrimary,fontSize:s.fontSizeLG}}),r.jsx(oe,{color:c?"warning":"processing",style:{margin:0,fontFamily:s.fontFamilyCode,fontSize:s.fontSize},children:i})]}),l&&r.jsx(ke,{title:o,children:r.jsxs(X,{size:4,align:"center",style:{marginTop:4},children:[r.jsx(hi,{style:{color:s.colorTextTertiary,fontSize:s.fontSizeSM}}),r.jsx($h,{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($h,{style:{fontSize:s.fontSize,color:s.colorText,marginTop:s.marginXS,paddingTop:s.marginXS,borderTop:`1px solid ${s.colorBorderSecondary}`},children:n})]})},Zy=m.memo(yP);Zy.displayName="FileReferenceCard";const bP=({taskList:e})=>{const{token:t}=he.useToken(),{Text:s}=le,n=l=>{switch(l){case"pending":return r.jsx(oe,{icon:r.jsx(Ys,{}),color:"default",children:"Pending"});case"in_progress":return r.jsx(oe,{icon:r.jsx(gr,{spin:!0}),color:"processing",children:"In Progress"});case"completed":return r.jsx(oe,{icon:r.jsx(Hs,{}),color:"success",children:"Completed"});case"skipped":return r.jsx(oe,{icon:r.jsx(nc,{}),color:"default",children:"Skipped"});case"failed":return r.jsx(oe,{icon:r.jsx(rc,{}),color:"error",children:"Failed"});default:return null}},o=()=>{switch(e.status){case"active":return r.jsx(oe,{color:"processing",children:"Active"});case"completed":return r.jsx(oe,{color:"success",children:"Completed"});case"abandoned":return r.jsx(oe,{color:"error",children:"Abandoned"});default:return null}},a=ut.useMemo(()=>{if(e.items.length===0)return 0;const l=e.items.filter(c=>c.status==="completed").length;return Math.round(l/e.items.length*100)},[e.items]),i=ut.useMemo(()=>e.items.find(l=>l.status==="in_progress"),[e.items]);return r.jsx(ee,{size:"small",styles:{body:{padding:t.paddingSM}},style:{borderRadius:t.borderRadiusLG},children:r.jsxs(G,{vertical:!0,gap:t.marginSM,children:[r.jsxs(G,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[r.jsxs(X,{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(X,{direction:"vertical",size:4,children:[r.jsx(id,{percent:a,status:e.status==="completed"?"success":e.status==="abandoned"?"exception":"active",showInfo:!0}),r.jsxs(s,{type:"secondary",children:[a,"% Complete"]})]}),r.jsx(nt,{size:"small",dataSource:e.items,renderItem:l=>{var d;const c=(i==null?void 0:i.id)===l.id;return r.jsx(nt.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(G,{vertical:!0,style:{width:"100%"},gap:4,children:[r.jsxs(G,{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(G,{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]})]})})},xP=100,kn=new Set;function vP(e){if(kn.has(e)&&kn.delete(e),kn.add(e),kn.size>xP){const t=kn.values().next().value;t&&kn.delete(t)}}function SP(e){let t=2166136261;for(let s=0;s<e.length;s++)t=(t^e.charCodeAt(s))*16777619;return(t>>>0).toString(36)}const wP=e=>{const{t}=ne(),s=SP(e.chart),[n,o]=m.useState(()=>kn.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)&&(vP(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(ut.Suspense,{fallback:r.jsx(ps,{size:"small",tip:t("components.mermaid.loadingDiagram")}),children:r.jsx(_P,{...e})}):r.jsx("div",{style:{minHeight:"200px"}})})},_P=e=>{const{t}=ne(),[s,n]=m.useState(null);return m.useEffect(()=>{let o=!1;return Dt(()=>Promise.resolve().then(()=>GE),void 0,import.meta.url).then(a=>{o||n(()=>a.MermaidChart)}),()=>{o=!0}},[]),s?r.jsx(s,{...e}):r.jsx(ps,{size:"small",tip:t("components.mermaid.loadingDiagram")})},TP=ut.memo(wP),kP=({error:e,className:t,style:s,token:n,onFix:o,isFixing:a,fixError:i})=>{const{t:l}=ne(),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(ua,{})}),r.jsx("span",{style:{fontWeight:600,color:n.colorError},children:l("components.mermaid.diagramError")})]}),r.jsx("div",{style:{fontSize:n.fontSizeSM,lineHeight:1.4,wordBreak:"break-word",flex:1,width:"100%"},children:c.map((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(Y,{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(ff,{style:{marginRight:4}})," ",l("components.mermaid.checkConsoleHint")]})]})};var Zt=function(e,t){return Number(e.toFixed(t))},jP=function(e,t){return typeof e=="number"?e:t},Ze=function(e,t,s){s&&typeof s=="function"&&s(e,t)},CP=function(e){return-Math.cos(e*Math.PI)/2+.5},MP=function(e){return e},PP=function(e){return e*e},EP=function(e){return e*(2-e)},RP=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},AP=function(e){return e*e*e},IP=function(e){return--e*e*e+1},$P=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},DP=function(e){return e*e*e*e},LP=function(e){return 1- --e*e*e*e},OP=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},FP=function(e){return e*e*e*e*e},zP=function(e){return 1+--e*e*e*e*e},NP=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},eb={easeOut:CP,linear:MP,easeInQuad:PP,easeOutQuad:EP,easeInOutQuad:RP,easeInCubic:AP,easeOutCubic:IP,easeInOutCubic:$P,easeInQuart:DP,easeOutQuart:LP,easeInOutQuart:OP,easeInQuint:FP,easeOutQuint:zP,easeInOutQuint:NP},tb=function(e){typeof e=="number"&&cancelAnimationFrame(e)},us=function(e){e.mounted&&(tb(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function sb(e,t,s,n){if(e.mounted){var o=new Date().getTime(),a=1;us(e),e.animation=function(){if(!e.mounted)return tb(e.animation);var i=new Date().getTime()-o,l=i/s,c=eb[t],d=c(l);i>=s?(n(a),e.animation=null):e.animation&&(n(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function BP(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=BP(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):sb(e,n,s,function(g){var y=l+u*g,f=c+h*g,v=d+p*g;a(y,f,v)})}}function WP(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 UP=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}},Gd=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=WP(s,n,t),i=a.wrapperWidth,l=a.wrapperHeight,c=a.newContentWidth,d=a.newDiffWidth,u=a.newContentHeight,h=a.newDiffHeight,p=UP(i,c,d,l,u,h,!!o);return p},Wc=function(e,t,s,n){return n?e<t?Zt(t,2):e>s?Zt(s,2):Zt(e,2):Zt(e,2)},Fn=function(e,t){var s=Gd(e,t);return e.bounds=s,s};function _a(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 g=Wc(e,l-h,d+h,n),y=Wc(t,c-p,u+p,n);return{x:g,y}}function Gi(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,g=_a(h,p,o,a,0,0,null);return g}function Ta(e,t,s,n,o){var a=o?n:0,i=t-a;return!Number.isNaN(s)&&e>=s?s:!Number.isNaN(t)&&e<=i?i:e}var Dh=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=Ji(a,s);return!d},Lh=function(e){var t=e.isInitialized,s=e.isPanning,n=e.setup,o=n.panning.disabled,a=t&&s&&!o;return!!a},qP=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}},HP=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 YP(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,g=u.maxPositionY,y=u.minPositionY,f=s>h||s<p,v=n>g||n<y,b=s>h?d.offsetWidth:e.setup.minPositionX||0,x=n>g?d.offsetHeight:e.setup.minPositionY||0,_=Gi(e,b,x,o,e.bounds,l||c),w=_.x,k=_.y;return{scale:o,positionX:f?w:s,positionY:v?k:n}}}function nb(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=_a(t,s,l,a,n,o,i),g=p.x,y=p.y;e.setTransformState(d,g,y)}}var XP=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,g=l?d:h;return{x:p,y:g}},cn=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},VP=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},KP=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 GP(e,t){var s=e.setup.velocityAnimation,n=s.equalToMove,o=s.animationTime,a=s.sensitivity;return n?o*t*a:o}function Oh(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:Wc(e,a,i,o)}function JP(e,t){var s=1;return t?Math.min(s,e.offsetWidth/window.innerWidth):s}function QP(e,t){var s=VP(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=JP(i,l),u=t.x-n.x,h=t.y-n.y,p=u/d,g=h/d,y=c-o,f=u*u+h*h,v=Math.sqrt(f)/y;e.velocity={velocityX:p,velocityY:g,total:v}}e.lastMousePosition=t,e.velocityTime=c}}function ZP(e){var t=e.velocity,s=e.bounds,n=e.setup,o=e.wrapperComponent,a=KP(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,g=n.limitToBounds,y=n.alignmentAnimation,f=n.zoomAnimation,v=n.panning,b=v.lockAxisY,x=v.lockAxisX,_=f.animationType,w=y.sizeX,k=y.sizeY,C=y.velocityAlignmentTime,E=C,j=GP(e,c),R=Math.max(j,E),M=cn(e,w),T=cn(e,k),P=M*o.offsetWidth/100,S=T*o.offsetHeight/100,L=d+P,$=u-P,I=h+S,W=p-S,A=e.transformState,O=new Date().getTime();sb(e,_,R,function(D){var H=e.transformState,B=H.scale,K=H.positionX,F=H.positionY,z=new Date().getTime()-O,de=z/E,Te=eb[y.animationType],$e=1-Te(Math.min(1,de)),De=1-D,be=K+i*De,ye=F+l*De,je=Oh(be,A.positionX,K,x,g,u,d,$,L,$e),Ue=Oh(ye,A.positionY,F,b,g,p,h,W,I,$e);(K!==be||F!==ye)&&e.setTransformState(B,je,Ue)})}}function Fh(e,t){var s=e.transformState.scale;us(e),Fn(e,s),window.TouchEvent!==void 0&&t instanceof TouchEvent?HP(e,t):qP(e,t)}function Jd(e,t){var s=e.transformState.scale,n=e.setup,o=n.minScale,a=n.alignmentAnimation,i=a.disabled,l=a.sizeX,c=a.sizeY,d=a.animationTime,u=a.animationType,h=i||s<o||!l&&!c;if(!h){var p=YP(e);p&&mn(e,p,t??d,u)}}function zh(e,t,s){var n=e.startCoords,o=e.setup,a=o.alignmentAnimation,i=a.sizeX,l=a.sizeY;if(n){var c=XP(e,t,s),d=c.x,u=c.y,h=cn(e,i),p=cn(e,l);QP(e,{x:d,y:u}),nb(e,d,u,h,p)}}function eE(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?ZP(e):Jd(e)}}function Qd(e,t,s,n){var o=e.setup,a=o.minScale,i=o.maxScale,l=o.limitToBounds,c=Ta(Zt(t,2),a,i,0,!1),d=Fn(e,c),u=Gi(e,s,n,c,d,l),h=u.x,p=u.y;return{scale:c,positionX:h,positionY:p}}function rb(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)&&Jd(e),!(p||!o||!e.mounted)){var g=t||o.offsetWidth/2,y=s||o.offsetHeight/2,f=Qd(e,i,g,y);f&&mn(e,f,u,h)}}var an=function(){return an=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},an.apply(this,arguments)};function Nh(e,t,s){for(var n=0,o=t.length,a;n<o;n++)(a||!(n in t))&&(a||(a=Array.prototype.slice.call(t,0,n)),a[n]=t[n]);return e.concat(a||Array.prototype.slice.call(t))}var qa={scale:1,positionX:0,positionY:0},Kr={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}},Uc={wrapperClass:"react-transform-wrapper",contentClass:"react-transform-component"},ob=function(e){var t,s,n,o;return{previousScale:(t=e.initialScale)!==null&&t!==void 0?t:qa.scale,scale:(s=e.initialScale)!==null&&s!==void 0?s:qa.scale,positionX:(n=e.initialPositionX)!==null&&n!==void 0?n:qa.positionX,positionY:(o=e.initialPositionY)!==null&&o!==void 0?o:qa.positionY}},Bh=function(e){var t=an({},Kr);return Object.keys(e).forEach(function(s){var n=typeof e[s]<"u",o=typeof Kr[s]<"u";if(o&&n){var a=Object.prototype.toString.call(Kr[s]),i=a==="[object Object]",l=a==="[object Array]";i?t[s]=an(an({},Kr[s]),e[s]):l?t[s]=Nh(Nh([],Kr[s],!0),e[s]):t[s]=e[s]}}),t},ab=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=Ta(Zt(h,3),l,i,u,!1);return p};function ib(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,g=(h/2-d)/l,y=ab(e,t,s),f=Qd(e,y,p,g);if(!f)return console.error("Error during zoom event. New transformation state was not calculated.");mn(e,f,n,o)}function lb(e,t,s,n){var o=e.setup,a=e.wrapperComponent,i=o.limitToBounds,l=ob(e.props),c=e.transformState,d=c.scale,u=c.positionX,h=c.positionY;if(a){var p=Gd(e,l.scale),g=_a(l.positionX,l.positionY,p,i,0,0,a),y={scale:l.scale,positionX:g.x,positionY:g.y};d===l.scale&&u===l.positionX&&h===l.positionY||(n==null||n(),mn(e,y,t,s))}}function tE(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 sE(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=tE(t,n,o,a),g=p.x,y=p.y,f=h.width/a.scale,v=h.height/a.scale,b=n.offsetWidth/f,x=n.offsetHeight/v,_=Ta(s||Math.min(b,x),c,d,0,!1),w=(u.width-f*_)/2,k=(u.height-v*_)/2,C=(u.left-g)*_+w,E=(u.top-y)*_+k,j=Gd(e,_),R=_a(C,E,j,l,0,0,n),M=R.x,T=R.y;return{positionX:M,positionY:T,scale:_}}var nE=function(e){return function(t,s,n){t===void 0&&(t=.5),s===void 0&&(s=300),n===void 0&&(n="easeOut"),ib(e,1,t,s,n)}},rE=function(e){return function(t,s,n){t===void 0&&(t=.5),s===void 0&&(s=300),n===void 0&&(n="easeOut"),ib(e,-1,t,s,n)}},oE=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 g={positionX:Number.isNaN(t)?l:t,positionY:Number.isNaN(s)?c:s,scale:Number.isNaN(n)?d:n};mn(e,g,o,a)}}},aE=function(e){return function(t,s){t===void 0&&(t=200),s===void 0&&(s="easeOut"),lb(e,t,s)}},iE=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=cb(t||o.scale,a,i);mn(e,l,s,n)}}},lE=function(e){return function(t,s,n,o){n===void 0&&(n=600),o===void 0&&(o="easeOut"),us(e);var a=e.wrapperComponent,i=typeof t=="string"?document.getElementById(t):t;if(a&&i&&a.contains(i)){var l=sE(e,i,s);mn(e,l,n,o)}}},qc=function(e){return{instance:e,zoomIn:nE(e),zoomOut:rE(e),setTransform:oE(e),resetTransform:aE(e),centerView:iE(e),zoomToElement:lE(e)}},cE=function(e){return{instance:e,state:e.transformState}},Ye=function(e){var t={};return Object.assign(t,cE(e)),Object.assign(t,qc(e)),t},$l=!1;function Dl(){try{var e={get passive(){return $l=!0,!1}};return e}catch{return $l=!1,$l}}var Ha=".".concat(Uc.wrapperClass),Ji=function(e,t){return t.some(function(s){return e.matches("".concat(Ha," ").concat(s,", ").concat(Ha," .").concat(s,", ").concat(Ha," ").concat(s," *, ").concat(Ha," .").concat(s," *"))})},Hc=function(e){e&&clearTimeout(e)},dE=function(e,t,s){return"translate(".concat(e,"px, ").concat(t,"px) scale(").concat(s,")")},cb=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 uE(e){return function(t){e.forEach(function(s){typeof s=="function"?s(t):s!=null&&(s.current=t)})}}var mE=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=Ji(d,i);return!h},hE=function(e){return e?e.deltaY<0?1:-1:0};function pE(e,t){var s=hE(e),n=jP(t,s);return n}function db(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 fE=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,g=u.disabled;if(!i)throw new Error("Wrapper is not mounted");var y=a+t*s,f=n?!1:!g,v=Ta(Zt(y,3),d,c,p,f&&!h);return v},gE=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},yE=function(e,t){var s=e.setup.pinch,n=s.disabled,o=s.excluded,a=e.isInitialized,i=t.target,l=a&&!n&&i;if(!l)return!1;var c=Ji(i,o);return!c},bE=function(e){var t=e.setup.pinch.disabled,s=e.isInitialized,n=e.pinchStartDistance,o=s&&!t&&n;return!!o},xE=function(e,t,s){var n=s.getBoundingClientRect(),o=e.touches,a=Zt(o[0].clientX-n.left,5),i=Zt(o[0].clientY-n.top,5),l=Zt(o[1].clientX-n.left,5),c=Zt(o[1].clientY-n.top,5);return{x:(a+l)/2/t,y:(i+c)/2/t}},ub=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))},vE=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 Ta(Zt(p,2),i,a,d,!u&&!c)},SE=160,wE=100,_E=function(e,t){var s=e.props,n=s.onWheelStart,o=s.onZoomStart;e.wheelStopEventTimer||(us(e),Ze(Ye(e),t,n),Ze(Ye(e),t,o))},TE=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,g=i.disablePadding,y=i.smooth,f=h.size,v=h.disabled,b=p.step,x=p.smoothStep;if(!a)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var _=pE(t,null),w=y?x*Math.abs(t.deltaY):b,k=fE(e,_,w,!t.ctrlKey);if(c!==k){var C=Fn(e,k),E=db(t,a,c),j=v||f===0||u||g,R=d&&j,M=Gi(e,E.x,E.y,k,C,R),T=M.x,P=M.y;e.previousWheelEvent=t,e.setTransformState(k,T,P),Ze(Ye(e),t,n),Ze(Ye(e),t,o)}},kE=function(e,t){var s=e.props,n=s.onWheelStop,o=s.onZoomStop;Hc(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(rb(e,t.x,t.y),e.wheelAnimationTimer=null)},wE);var a=gE(e,t);a&&(Hc(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Ze(Ye(e),t,n),Ze(Ye(e),t,o))},SE))},mb=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}},jE=function(e,t){var s=ub(t);e.pinchStartDistance=s,e.lastDistance=s,e.pinchStartScale=e.transformState.scale,e.isPanning=!1;var n=mb(t);e.pinchLastCenterX=n.x,e.pinchLastCenterY=n.y,us(e)},CE=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 g=xE(t,a,s);if(!(!Number.isFinite(g.x)||!Number.isFinite(g.y))){var y=ub(t),f=vE(e,y),v=mb(t),b=v.x-(e.pinchLastCenterX||0),x=v.y-(e.pinchLastCenterY||0);if(!(f===a&&b===0&&x===0)){e.pinchLastCenterX=v.x,e.pinchLastCenterY=v.y;var _=Fn(e,f),w=h||p===0||c,k=l&&w,C=Gi(e,g.x,g.y,f,_,k),E=C.x,j=C.y;e.pinchMidpoint=g,e.lastDistance=y;var R=u.sizeX,M=u.sizeY,T=cn(e,R),P=cn(e,M),S=E+b,L=j+x,$=_a(S,L,_,l,T,P,o),I=$.x,W=$.y;e.setTransformState(f,I,W)}}}},ME=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,rb(e,t==null?void 0:t.x,t==null?void 0:t.y)},hb=function(e,t){var s=e.props.onZoomStop,n=e.setup.doubleClick.animationTime;Hc(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Ze(Ye(e),t,s)},n)},PE=function(e,t){var s=e.props,n=s.onZoomStart,o=s.onZoom,a=e.setup.doubleClick,i=a.animationTime,l=a.animationType;Ze(Ye(e),t,n),lb(e,i,l,function(){return Ze(Ye(e),t,o)}),hb(e,t)};function EE(e,t){return e==="toggle"?t===1?1:-1:e==="zoomOut"?-1:1}function RE(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,g=u.step,y=u.animationTime,f=u.animationType;if(!h&&!n){if(p==="reset")return PE(e,t);if(!a)return console.error("No ContentComponent found");var v=EE(p,e.transformState.scale),b=ab(e,v,g);if(i!==b){Ze(Ye(e),t,c);var x=db(t,a,i),_=Qd(e,b,x.x,x.y);if(!_)return console.error("Error during zoom event. New transformation state was not calculated.");Ze(Ye(e),t,d),mn(e,_,y,f),hb(e,t)}}}var AE=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=Ji(c,l);return!h},IE=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=Bh(n)},this.initializeWindowEvents=function(){var n,o,a=Dl(),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=Dl(),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),us(s),(o=s.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(n){var o=Dl();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(Ye(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 us(s),Fn(s,s.transformState.scale),Jd(s,0)}),s.observer.observe(n),s.observer.observe(o)},this.onWheelZoom=function(n){var o=s.setup.disabled;if(!o){var a=mE(s,n);if(a){var i=s.isPressingKeys(s.setup.wheel.activationKeys);i&&(_E(s,n),TE(s,n),kE(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,g=l.lockAxisX?d:h,y=l.lockAxisY?u:p,f=s.setup.alignmentAnimation,v=f.sizeX,b=f.sizeY,x=cn(s,v),_=cn(s,b);g===d&&y===u||nb(s,g,y,x,_)}},this.onPanningStart=function(n){var o=s.setup.disabled,a=s.props.onPanningStart;if(!o){var i=Dh(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(),us(s),Fh(s,n),Ze(Ye(s),n,a)))}}},this.onPanning=function(n){var o=s.setup.disabled,a=s.props.onPanning;if(!o){var i=Lh(s);if(i){var l=s.isPressingKeys(s.setup.panning.activationKeys);l&&(n.preventDefault(),n.stopPropagation(),zh(s,n.clientX,n.clientY),Ze(Ye(s),n,a))}}},this.onPanningStop=function(n){var o=s.props.onPanningStop;s.isPanning&&(eE(s),Ze(Ye(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=yE(s,n);c&&(jE(s,n),us(s),Ze(Ye(s),n,i),Ze(Ye(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=bE(s);c&&(n.preventDefault(),n.stopPropagation(),CE(s,n),Ze(Ye(s),n,i),Ze(Ye(s),n,l))}},this.onPinchStop=function(n){var o=s.props,a=o.onPinchingStop,i=o.onZoomStop;s.pinchStartScale&&(ME(s),Ze(Ye(s),n,a),Ze(Ye(s),n,i))},this.onTouchPanningStart=function(n){var o=s.setup.disabled,a=s.props.onPanningStart;if(!o){var i=Dh(s,n);if(i){var l=s.lastTouch&&+new Date-s.lastTouch<200&&n.touches.length===1;if(!l){s.lastTouch=+new Date,us(s);var c=n.touches,d=c.length===1,u=c.length===2;d&&(us(s),Fh(s,n),Ze(Ye(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=Lh(s);if(!i)return;n.preventDefault(),n.stopPropagation();var l=n.touches[0];zh(s,l.clientX,l.clientY),Ze(Ye(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=AE(s,n);a&&RE(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=Ye(s);s.onChangeCallbacks.forEach(function(c){return c(l)}),Ze(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=cb(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):dE(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 Ye(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=Ye(s);Ze(a,void 0,s.props.onInit)},this.props=t,this.setup=Bh(this.props),this.transformState=ob(this.props)}return e}(),Zd=ut.createContext(null),$E=function(e,t){return typeof e=="function"?e(t):e},DE=ut.forwardRef(function(e,t){var s=m.useRef(new IE(e)).current,n=$E(e.children,qc(s));return m.useImperativeHandle(t,function(){return qc(s)},[s]),m.useEffect(function(){s.update(e)},[s,e]),ut.createElement(Zd.Provider,{value:s},n)});ut.forwardRef(function(e,t){var s=m.useRef(null),n=m.useContext(Zd);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]),ut.createElement("div",an({},e,{ref:uE([s,t])}))});function LE(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 OE=`.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
|
+
`,Wh={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};LE(OE);var FE=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(Zd),g=p.init,y=p.cleanupWindowEvents,f=m.useRef(null),v=m.useRef(null);return m.useEffect(function(){var b=f.current,x=v.current;return b!==null&&x!==null&&g&&(g==null||g(b,x)),function(){y==null||y()}},[]),ut.createElement("div",an({},d,{ref:f,className:"".concat(Uc.wrapperClass," ").concat(Wh.wrapper," ").concat(n),style:i}),ut.createElement("div",an({},h,{ref:v,className:"".concat(Uc.contentClass," ").concat(Wh.content," ").concat(a),style:l}),t))};const pb=()=>typeof window<"u"&&!!window.__TAURI_INTERNALS__;class zE{async saveFile(t){const{content:s,filters:n,defaultPath:o}=t,{save:a}=await Dt(async()=>{const{save:d}=await import("./index-BmjFP0ha.js");return{save:d}},__vite__mapDeps([13,14]),import.meta.url),{writeFile:i,writeTextFile:l}=await Dt(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:fb(c,o),success:!0}}}class NE{async saveFile(t){const{content:s,filters:n,defaultPath:o}=t,a=fb(o,o);if(typeof window>"u"||typeof document>"u")throw new Error("File save is unavailable in this environment");const i=UE(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 BE=new zE,WE=new NE,fb=(e,t)=>e.split(/[/\\]/).pop()||t,UE=(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"}},qE=()=>pb()?BE:WE;class ks{static async saveFile(t){try{return await qE().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}`}}He(ks,"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 HE=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},YE=({svg:e,height:t,isLoading:s,initialScale:n,chartKey:o,className:a,style:i,token:l,containerRef:c})=>{const{t:d}=ne(),{message:u}=Ot.useApp(),[h,p]=m.useState(!1),g=m.useCallback(async()=>{var f;if(!(!e||h)){p(!0);try{const v=HE(e),b=new TextEncoder().encode(v),x=o?`mermaid-${o.slice(0,8)}`:"mermaid-graph",_=ks.generateTimestampedFilename(x,"svg"),w=await ks.saveBinaryFile(b,ks.FILTERS.SVG,_);if(w.success){u.success(d("chat.messageActions.savedFile",{filename:w.filename}));return}if((f=w.error)!=null&&f.toLowerCase().includes("cancel"))return;u.error(w.error||d("chat.messageActions.exportFailed"))}catch(v){const b=v instanceof Error?v.message:d("components.mermaid.exportFailed");u.error(b)}finally{p(!1)}}},[u,o,h,e,d]),y=s||!e||h;return r.jsxs("div",{ref:c,"data-mermaid-loading":s?"true":"false",className:a,style:{textAlign:"center",margin:`${l.marginXS}px 0`,padding:l.padding,background:l.colorBgContainer,borderRadius:l.borderRadiusSM,border:`1px solid ${l.colorBorder}`,overflow:"hidden",height:`${Math.min(t,800)}px`,minHeight:"300px",maxHeight:"80vh",display:"flex",alignItems:"center",justifyContent:"center",position:"relative",willChange:"auto",contain:"layout style paint",...i},children:[s&&r.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:l.colorTextSecondary,fontSize:l.fontSizeSM,zIndex:2},children:d("components.mermaid.renderingDiagram")}),r.jsx("div",{style:{width:"100%",height:"100%",opacity:s?0:1,position:"relative"},children:r.jsx(DE,{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:v,resetTransform:b})=>r.jsxs(r.Fragment,{children:[r.jsxs("div",{"data-mermaid-controls":"true",style:{position:"absolute",top:8,right:8,zIndex:10,display:"flex",flexDirection:"column",gap:4,background:l.colorBgContainer,borderRadius:l.borderRadiusSM,border:`1px solid ${l.colorBorder}`,padding:4,boxShadow:l.boxShadowSecondary},children:[r.jsx(Y,{size:"small",type:"text",onClick:()=>f(),style:{fontSize:12,padding:"2px 6px"},children:"+"}),r.jsx(Y,{size:"small",type:"text",onClick:()=>v(),style:{fontSize:12,padding:"2px 6px"},children:"-"}),r.jsx(Y,{size:"small",type:"text",onClick:()=>b(),style:{fontSize:10,padding:"2px 6px"},children:"⌂"}),r.jsx(ke,{title:d("components.mermaid.exportSvg"),children:r.jsx(Y,{size:"small",type:"text",icon:r.jsx(yr,{}),"aria-label":"Download chart",disabled:y,loading:h,onClick:()=>{g()},style:{fontSize:11,padding:"2px 6px"}})})]}),r.jsx(FE,{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 XE(e){let t=2166136261;for(let s=0;s<e.length;s++)t=(t^e.charCodeAt(s))*16777619;return(t>>>0).toString(36)}const VE=(e,t)=>{const s=m.useMemo(()=>Pk(e),[e]),n=m.useMemo(()=>XE(s),[s]),[o,a]=m.useState(()=>{const i=ci(n);return i?{svg:i.svg,height:i.height+80,svgWidth:i.width,svgHeight:i.height,error:"",isLoading:!1}:{svg:"",height:200,svgWidth:800,svgHeight:200,error:"",isLoading:t}});return m.useEffect(()=>{const i=ci(n);a(i?{svg:i.svg,height:i.height+80,svgWidth:i.width,svgHeight:i.height,error:"",isLoading:!1}:{svg:"",height:200,svgWidth:800,svgHeight:200,error:"",isLoading:!1})},[n]),m.useEffect(()=>{if(ci(n))return;let l=!1;return a(c=>({...c,isLoading:!0})),$k(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:KE}=he,Ri=ut.memo(({chart:e,id:t,className:s,style:n,onFix:o})=>{const{token:a}=KE(),i=Xi(),[l,c]=m.useState(!1),[d,u]=m.useState(""),h=m.useRef(null),{renderState:p,chartKey:g}=VE(e,!0),{svg:y,height:f,svgWidth:v,error:b,isLoading:x}=p,w=(()=>{const C=i.defaultScale;return v>1200?C*.8:v>800?C*1:C*1.2})(),k=async()=>{if(!(!o||l)){c(!0),u("");try{await o(e,b)}catch(C){const E=C instanceof Error?C.message:String(C);u(E||"Failed to fix Mermaid diagram")}finally{c(!1)}}};return b?r.jsx(kP,{error:b,className:s,style:n,token:a,onFix:o?k:void 0,isFixing:l,fixError:d}):r.jsx(YE,{svg:y,height:f,isLoading:x,initialScale:w,chartKey:g,className:s,style:n,token:a,containerRef:h})});Ri.displayName="MermaidChart";const GE=Object.freeze(Object.defineProperty({__proto__:null,MermaidChart:Ri,default:Ri},Symbol.toStringTag,{value:"Module"}));mt.registerLanguage("javascript",lf);mt.registerLanguage("js",lf);mt.registerLanguage("typescript",cf);mt.registerLanguage("ts",cf);mt.registerLanguage("python",df);mt.registerLanguage("py",df);mt.registerLanguage("json",Qb);mt.registerLanguage("bash",Qc);mt.registerLanguage("shell",Qc);mt.registerLanguage("sh",Qc);mt.registerLanguage("css",Zb);mt.registerLanguage("html",uf);mt.registerLanguage("xml",uf);mt.registerLanguage("sql",ex);mt.registerLanguage("yaml",mf);mt.registerLanguage("yml",mf);mt.registerLanguage("markdown",hf);mt.registerLanguage("md",hf);const JE=()=>Un,QE=["javascript","js","typescript","ts","python","py","json","bash","shell","sh","css","html","xml","sql","yaml","yml","markdown","md"],ZE=({language:e,codeString:t,token:s})=>{const{t:n}=ne(),[o,a]=m.useState(!1),i=async()=>{try{await os(t),fe.success(n("components.markdown.codeCopiedSuccess"))}catch(d){console.error("Copy failed:",d),fe.error(n("components.markdown.copyFailed"))}},l=e.toLowerCase(),c=QE.includes(l);return r.jsxs(ee,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto"},onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[r.jsx(mt,{style:JE(),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(Y,{type:"text",size:"small",icon:r.jsx(ss,{}),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"}})]})},e1=({codeString:e,token:t})=>{const{t:s}=ne();return r.jsxs(ee,{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(Y,{type:"text",size:"small",icon:r.jsx(ss,{}),"aria-label":"Copy code",className:"fallback-copy-btn",onClick:async()=>{try{await os(e),fe.success(s("components.markdown.codeCopiedSuccess"))}catch(n){console.error("Copy failed:",n),fe.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}})]})},t1={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"},gb=/^(\s*%%\{[\s\S]*?\}%%\s*)+/,s1=/^(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,n1=e=>e.replace(gb,"").trimStart(),r1=(e,t)=>{const s=e.match(gb);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}`},o1=(e,t)=>{const s=t1[e];if(!s)return null;const n=t.trim();if(!n)return"";if(e==="mermaid")return n;const o=n1(n);return s1.test(o)?n:r1(n,s)},yb=(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=o1(a,t);if(i!==null){const l=i.trim();return l?o==="eager"?r.jsx(Ri,{chart:l,onFix:n}):r.jsx(TP,{chart:l,onFix:n}):(console.warn("Empty Mermaid chart content"),null)}return r.jsx(ZE,{language:a,codeString:t,token:s})}catch(a){return console.warn("Syntax highlighting failed:",a),r.jsx(e1,{codeString:t,token:s})}},Uh=(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)},bb=async e=>{const t=e.trim();if(!t)return;if(pb()){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)}Uh(t,{allowLocationFallback:!1});return}Uh(t)},{Text:qh}=le,xb=(e,t)=>({p:({children:s})=>r.jsx(qh,{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(qh,{code:!0,className:s,...a,children:n}):d.trim()?yb(l,d,e,t==null?void 0:t.onFixMermaid,t==null?void 0:t.mermaidRenderMode):null},blockquote:({children:s})=>r.jsx(ee,{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(),bb(o)},style:{color:e.colorLink,textDecoration:"underline",overflowWrap:"anywhere"},children:s}):r.jsx(r.Fragment,{children:s})},table:({children:s})=>r.jsx(ee,{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:Fe}=le,Hh=e=>{if(!e)return;const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},a1=({content:e,toolName:t,status:s="success",timestamp:n,defaultCollapsed:o=!0,isLoading:a,errorMessage:i})=>{var b;const{t:l}=ne(),{token:c}=he.useToken(),d=m.useMemo(()=>Oc(e),[e]),u=m.useMemo(()=>typeof a=="boolean"?a:d.formattedText.trim().length===0,[d.formattedText,a]),h=m.useMemo(()=>D0(d.formattedText),[d.formattedText]),p=m.useMemo(()=>wa(e),[e]),g=m.useMemo(()=>Ay(e),[e]),y=m.useMemo(()=>p?Iy(p.diff.unified):[],[p]),f=async()=>{try{const x=d.isJson?xr(d.parsedJson):d.formattedText;await os(x)}catch(x){console.error("[ToolResultCard] Failed to copy result:",x)}},v=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(ns,{defaultActiveKey:o?[]:[v],style:{backgroundColor:c.colorBgContainer,borderColor:c.colorBorderSecondary,borderWidth:1,borderStyle:"solid",borderRadius:c.borderRadiusLG},items:[{key:v,label:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:c.marginSM,width:"100%"},children:[r.jsx(ad,{style:{color:c.colorPrimary,flexShrink:0}}),r.jsx(Fe,{strong:!0,style:{color:c.colorText,flexShrink:0},children:t}),r.jsx(Fe,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:c.fontSizeSM},children:u?l("components.toolResult.waiting"):h}),r.jsx(oe,{color:$y(s),style:{flexShrink:0,margin:0},children:s})]}),children:r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:c.marginSM,children:[n&&r.jsx(Fe,{type:"secondary",style:{fontSize:c.fontSizeSM},children:new Date(n).toLocaleString()}),i&&r.jsx(Xe,{type:"error",message:l("components.toolResult.executionFailed"),description:i,showIcon:!0}),r.jsxs("div",{style:{position:"relative"},children:[r.jsx(ke,{title:l("components.toolResult.copyResult"),children:r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ss,{}),"aria-label":l("components.toolResult.copyResult"),onClick:x=>{x.stopPropagation(),f()},style:{position:"absolute",top:8,right:8,zIndex:1}})}),u?r.jsx(Fe,{type:"secondary",children:l("components.toolResult.waitingForResult")}):g?r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:10,children:[r.jsxs(X,{wrap:!0,children:[r.jsx(oe,{color:g.action==="rebuild"?"gold":"blue",children:l(`components.toolResult.memory.action.${g.action}`)}),r.jsx(oe,{children:g.data.scope}),g.data.project_key?r.jsx(oe,{children:g.data.project_key}):null,r.jsx(oe,{color:"green",children:l("components.toolResult.memory.totalMemories",{count:g.data.total_memories})}),r.jsx(oe,{color:g.data.stale_candidate_count>0?"orange":"default",children:l("components.toolResult.memory.staleCandidates",{count:g.data.stale_candidate_count})})]}),r.jsxs("div",{children:[r.jsx(Fe,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.coverage")}),r.jsxs("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:[Object.entries(g.data.by_type).map(([x,_])=>r.jsx(oe,{children:`${x}: ${_}`},`type-${x}`)),Object.entries(g.data.by_status).map(([x,_])=>r.jsx(oe,{color:"processing",children:`${x}: ${_}`},`status-${x}`))]})]}),r.jsx(Rt,{style:{margin:`${c.marginXS}px 0`}}),r.jsxs("div",{style:{display:"grid",gap:c.marginXS},children:[r.jsxs(Fe,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Fe,{strong:!0,children:l("components.toolResult.memory.viewsLabel")})," ",g.data.view_files.length]}),r.jsxs(Fe,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Fe,{strong:!0,children:l("components.toolResult.memory.indexesLabel")})," ",g.data.index_files.length]}),r.jsxs(Fe,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Fe,{strong:!0,children:l("components.toolResult.memory.stateFilesLabel")})," ",g.data.state_files.length]}),g.data.last_reindex_at?r.jsxs(Fe,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Fe,{strong:!0,children:l("components.toolResult.memory.lastReindexLabel")})," ",Hh(g.data.last_reindex_at)]}):null,g.data.last_dream_at?r.jsxs(Fe,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Fe,{strong:!0,children:l("components.toolResult.memory.lastDreamLabel")})," ",Hh(g.data.last_dream_at)]}):null]}),g.data.view_files.length>0?r.jsxs("div",{children:[r.jsx(Fe,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.viewFiles")}),r.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:g.data.view_files.map(x=>r.jsx(oe,{children:x},`view-${x}`))})]}):null,g.data.index_files.length>0?r.jsxs("div",{children:[r.jsx(Fe,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.indexFiles")}),r.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:g.data.index_files.map(x=>r.jsx(oe,{children:x},`index-${x}`))})]}):null,g.data.state_files.length>0?r.jsxs("div",{children:[r.jsx(Fe,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.stateFiles")}),r.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:g.data.state_files.map(x=>r.jsx(oe,{children:x},`state-${x}`))})]}):null,g.data.topic_paths.length>0?r.jsxs("div",{children:[r.jsx(Fe,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.topicPaths")}),r.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:g.data.topic_paths.map(x=>r.jsx(oe,{children:x},`topic-${x}`))})]}):null,g.data.recent_ids.length>0?r.jsxs("div",{children:[r.jsx(Fe,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.recentMemories")}),r.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:g.data.recent_ids.map(x=>r.jsx(oe,{color:"default",children:x},`recent-${x}`))})]}):null]}):p?r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:8,children:[p.message&&r.jsx(Fe,{style:{fontSize:c.fontSizeSM},children:p.message}),r.jsxs(Fe,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(Fe,{strong:!0,children:[l("common.file"),":"]})," ",r.jsx(Fe,{code:!0,children:p.file_path})]}),p.workspace&&r.jsxs(Fe,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(Fe,{strong:!0,children:[l("common.workspace"),":"]})," ",r.jsx(Fe,{code:!0,children:p.workspace})]}),(b=p.checkpoint)!=null&&b.created?r.jsxs(Fe,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(Fe,{strong:!0,children:[l("components.toolResult.checkpoint"),":"]})," ",r.jsx(Fe,{code:!0,children:p.checkpoint.path})]}):r.jsx(Fe,{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,_)=>{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||" "},`${_}-${x.kind}`)})}),p.diff.truncated&&r.jsx(Fe,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("components.toolResult.diffTruncated")})]}):d.isJson?r.jsx(fr,{language:"json",style:Un,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})]})]})}]})},eu=m.memo(a1);eu.displayName="ToolResultCard";const{Text:ws}=le;function i1(e,t){const s=Yn(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 l1=({toolName:e,parameters:t,toolCallId:s,streamingOutput:n,defaultExpanded:o=!1,metadata:a})=>{const{t:i}=ne(),{token:l}=he.useToken(),c=m.useMemo(()=>Yn(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(b=>b.includes(s)?b:[s]),h.current=!0)},[n,s]),m.useEffect(()=>{if(!n||n.trim().length===0||!d.includes(s))return;const b=p.current;b&&(b.scrollTop=b.scrollHeight)},[n,d,s]);const g=m.useMemo(()=>i1(e,t),[e,t]),y=m.useMemo(()=>xr(t,2),[t]),f=async()=>{try{await os(y)}catch(b){console.error("[ToolCallCard] Failed to copy parameters:",b)}},v=m.useMemo(()=>{const b=["path","file_path","command","pattern","query","limit"];return Object.entries(t).sort((w,k)=>{const C=b.indexOf(w[0]),E=b.indexOf(k[0]);return C!==-1&&E!==-1?C-E:C!==-1?-1:E!==-1?1:0}).slice(0,3)},[t]);return r.jsx(ns,{activeKey:d,onChange:b=>{const x=Array.isArray(b)?b.map(String):b==null?[]:[String(b)];u(x),x.includes(s)&&(h.current=!0)},style:{background:"var(--lotus-tool-card-bg)",borderColor:"var(--lotus-tool-card-border)",borderWidth:1,borderStyle:"solid",borderRadius:l.borderRadiusLG,boxShadow:"var(--lotus-tool-card-shadow)",transition:"all 0.3s ease",overflow:"hidden"},className:"tool-call-card-collapse",items:[{key:s,label:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:l.marginSM,width:"100%"},children:[r.jsx("div",{style:{width:34,height:34,borderRadius:12,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,background:"var(--lotus-tool-badge-bg)",border:"var(--lotus-tool-badge-border)",boxShadow:"var(--lotus-tool-badge-shadow)"},children:r.jsx(Sr,{style:{color:l.colorPrimary,flexShrink:0}})}),c?r.jsxs(X,{size:"small",wrap:!1,children:[r.jsx(oe,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:8,fontWeight:700,boxShadow:"var(--lotus-purple-shadow)"},children:"MCP"}),r.jsx(ws,{strong:!0,style:{color:l.colorText},children:c.toolName}),r.jsx(ws,{type:"secondary",style:{fontSize:l.fontSizeSM},children:r.jsx(ws,{code:!0,style:{fontSize:l.fontSizeSM},children:c.serverId})})]}):r.jsx(ws,{strong:!0,style:{color:l.colorText,flexShrink:0},children:e}),r.jsx(ws,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:l.fontSizeSM},children:g}),(a==null?void 0:a.elapsed_ms)!=null&&r.jsx(ke,{title:a.is_mutating?"Mutating tool":"Read-only tool",children:r.jsx(oe,{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(X,{direction:"vertical",style:{width:"100%"},size:l.marginSM,children:[n&&n.trim().length>0&&r.jsxs("div",{children:[r.jsx(ws,{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(fr,{language:"text",style:Un,wrapLongLines:!0,customStyle:{margin:0,backgroundColor:"transparent",fontSize:l.fontSizeSM},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:n})})]}),v.length>0&&r.jsxs("div",{children:[r.jsx(ws,{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:v.map(([b,x])=>r.jsxs("li",{children:[r.jsx(ws,{code:!0,style:{fontSize:l.fontSizeSM},children:b}),r.jsxs(ws,{style:{fontSize:l.fontSizeSM},children:[": ",typeof x=="string"?x:JSON.stringify(x)]})]},b))})]}),r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:l.marginXS},children:[r.jsx(ws,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolCall.fullParameters")}),r.jsx(ke,{title:i("components.toolCall.copyParameters"),children:r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ss,{}),"aria-label":i("components.toolCall.copyParameters"),onClick:b=>{b.stopPropagation(),f()}})})]}),r.jsx(fr,{language:"json",style:Un,wrapLongLines:!0,customStyle:{margin:0,borderRadius:l.borderRadiusSM,backgroundColor:l.colorBgContainer,fontSize:l.fontSizeSM,maxHeight:400,overflow:"auto"},className:"lotus-code-surface",codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:y})]})]})}]})},tu=m.memo(l1);tu.displayName="ToolCallCard";const{Text:Ll}=le,c1=({content:e,workflowName:t,parameters:s,status:n="success",timestamp:o,onRetry:a,isLoading:i,errorMessage:l})=>{const{t:c}=ne(),{token:d}=he.useToken(),[u,h]=m.useState(!1),p=m.useMemo(()=>Oc(e),[e]),g=m.useMemo(()=>typeof i=="boolean"?i:p.formattedText.trim().length===0,[p.formattedText,i]),y=m.useMemo(()=>I0(p.formattedText),[p.formattedText]),f=p.isJson||y,v=!f||u,b=m.useMemo(()=>$0(p.formattedText),[p.formattedText]),x=m.useMemo(()=>{if(s==null)return null;if(typeof s=="string")return Oc(s);try{return{isJson:!0,formattedText:JSON.stringify(s,null,2),parsedJson:s}}catch(k){return console.error("[WorkflowResultCard] Failed to stringify parameters:",k),{isJson:!1,formattedText:String(s)}}},[s]),_=async()=>{try{const k=p.isJson?xr(p.parsedJson):p.formattedText;await os(k)}catch(k){console.error("[WorkflowResultCard] Failed to copy content:",k)}},w=async()=>{if(x)try{const k=x.isJson?xr(x.parsedJson):x.formattedText;await os(k)}catch(k){console.error("[WorkflowResultCard] Failed to copy parameters:",k)}};return r.jsx(ee,{size:"small",variant:"outlined",style:{borderRadius:d.borderRadiusLG,borderColor:d.colorBorderSecondary,backgroundColor:d.colorBgContainer},bodyStyle:{padding:d.paddingMD},children:r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:d.marginSM,children:[r.jsxs(G,{align:"center",justify:"space-between",children:[r.jsxs(X,{size:d.marginXS,align:"center",children:[r.jsx(Px,{style:{color:d.colorWarning}}),r.jsx(Ll,{strong:!0,children:c("components.workflowResult.userWorkflow")}),r.jsx(oe,{color:d.colorWarning,children:t}),r.jsx(oe,{color:$y(n),children:n})]}),r.jsxs(X,{size:"small",children:[r.jsx(ke,{title:c(u?"components.workflowResult.collapseResult":"components.workflowResult.expandResult"),children:f&&r.jsx(Y,{type:"text",size:"small",icon:u?r.jsx(Ex,{}):r.jsx(Rx,{}),onClick:()=>h(k=>!k)})}),r.jsx(ke,{title:c("components.workflowResult.copyResult"),children:r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ss,{}),onClick:_,"aria-label":c("components.workflowResult.copyContent")})}),a&&r.jsx(ke,{title:c("components.workflowResult.retryWorkflow"),children:r.jsx(Y,{type:"text",size:"small",icon:r.jsx(Ms,{}),onClick:a,"aria-label":c("components.workflowResult.retryWorkflow")})})]})]}),o&&r.jsx(Ll,{type:"secondary",style:{fontSize:d.fontSizeSM},children:new Date(o).toLocaleString()}),r.jsx(Rt,{style:{margin:`${d.marginXS}px 0`}}),l&&r.jsx(Xe,{type:"error",message:c("components.workflowResult.executionFailed"),description:l,showIcon:!0,style:{marginBottom:d.marginXS}}),r.jsx(G,{vertical:!0,style:{width:"100%"},children:g?r.jsx(ps,{tip:c("components.workflowResult.waitingForResult")}):p.isJson?r.jsx(fr,{language:"json",style:Un,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:v?"none":280,overflow:v?"auto":"hidden"},children:p.formattedText}):r.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,maxHeight:v?"none":280,overflow:v?"visible":"hidden",marginBottom:0},children:[v?p.formattedText:b.preview,!v&&b.isTruncated&&`
|
|
219
|
+
…`]})}),x&&r.jsxs(G,{vertical:!0,style:{width:"100%"},children:[r.jsx(Rt,{style:{margin:`${d.marginXS}px 0`},children:r.jsxs(X,{size:"small",children:[r.jsx(Ll,{strong:!0,children:c("common.parameters")}),r.jsx(ke,{title:c("components.workflowResult.copyParameters"),children:r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ss,{}),onClick:w,"aria-label":c("components.workflowResult.copyParameters")})})]})}),x.isJson?r.jsx(fr,{language:"json",style:Un,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:220,overflow:"auto"},children:x.formattedText}):r.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,marginBottom:0},children:x.formattedText})]})]})})},vb=m.memo(c1);vb.displayName="WorkflowResultCard";const{Text:Ol}=le,d1=({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o,conclusionMarkdown:a,markdownComponents:i,markdownPlugins:l,rehypePlugins:c})=>{const{t:d}=ne(),[u,h]=m.useState(null),p=m.useMemo(()=>Ka({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o}),[e,t,s,n,o]),g=u===p,y=N(v=>v.setPendingQuestionRespond),f=N(v=>v.clearPendingQuestionRespondForSession);return m.useEffect(()=>{if(typeof window>"u")return;const v=b=>{var w;const _=((w=b.detail)==null?void 0:w.sessionId)??null;!e||_!==e||(h(p),f(e))};return window.addEventListener(pr,v),()=>{window.removeEventListener(pr,v)}},[e,p,f]),m.useEffect(()=>{!e||g||y({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o??null})},[e,g,p,t,s,n,o,y]),m.useEffect(()=>()=>{e&&f(e)},[e,f]),r.jsxs(X,{direction:"vertical",size:"middle",style:{width:"100%"},children:[a?r.jsx(hs,{remarkPlugins:l,rehypePlugins:c,components:i,children:a}):null,r.jsxs("div",{children:[r.jsx(Ol,{strong:!0,children:d("components.questionDialog.questionLabel","Question")}),r.jsx("div",{style:{marginTop:8},children:r.jsx(hs,{remarkPlugins:l,rehypePlugins:c,components:i,children:t})})]}),g?r.jsx(Ol,{type:"secondary",children:d("components.questionDialog.responseSubmittedContinue","Response submitted. Continuing...")}):r.jsx(Ol,{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:cs}=le,u1=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=Yn(u);s.push({type:"mcp",label:u,serverId:h==null?void 0:h.serverId,toolName:h==null?void 0:h.toolName});continue}const d=l.match(/^\[User explicitly selected skill:\s*(.+?)\s*\]$/);if(d){const u=d[1]??"",h=u.match(/\(ID:\s*([^)]+)\)\s*$/i),p=(a=h==null?void 0:h[1])==null?void 0:a.trim(),g=h?u.replace(/\(ID:\s*([^)]+)\)\s*$/i,"").trim():u;s.push({type:"skill",label:g||u,skillId:p});continue}n.push(i)}return{cleanText:n.join(`
|
|
221
|
+
`).trimStart(),hints:s}},m1=({sessionId:e,message:t,messageText:s,isUserToolCall:n,formatUserToolCall:o,markdownComponents:a,markdownPlugins:i,rehypePlugins:l})=>{var y;const{t:c}=ne(),d=f=>(f??"").trim().toLowerCase()==="conclusion";if(zy(t)){const f=t.result.result??"",v=t.isError?f||c("components.toolResult.executionFailed"):void 0,b=!v&&f.trim().length===0;if(t.result.display_preference==="Hidden")return null;const x=(t.toolName??"").trim().toLowerCase(),_=x==="conclusion",w=E0(f),k=(x==="conclusion_with_options"||x==="exitplanmode"||x==="request_permissions")&&!t.isError&&w,C=x==="conclusion"?Ry(f):null;return k&&w?r.jsx(d1,{sessionId:e,question:w.question,options:w.options,allowCustom:w.allow_custom,toolCallId:t.toolCallId,conclusionMarkdown:R0(w.conclusion),markdownComponents:a,markdownPlugins:i,rehypePlugins:l}):C?r.jsx(X,{direction:"vertical",style:{width:"100%"},size:"small",children:r.jsx(hs,{remarkPlugins:i,rehypePlugins:l,components:a,children:C})}):r.jsx(eu,{content:f,toolName:t.toolName,status:t.isError?"error":b?"warning":"success",timestamp:t.createdAt,defaultCollapsed:!_,isLoading:b,errorMessage:v})}if(zk(t)){const f=t.content??"",v=t.status==="error"?f||c("components.workflowResult.executionFailed"):void 0,b=!v&&f.trim().length===0;return r.jsx(vb,{content:f,workflowName:t.workflowName,parameters:t.parameters,status:b?"warning":t.status??"success",timestamp:t.createdAt,isLoading:b,errorMessage:v})}if(Fk(t)){const f=t.toolCalls.filter(v=>!d(v.toolName));return f.length===0?null:r.jsx(X,{direction:"vertical",style:{width:"100%"},children:f.map(v=>r.jsx(tu,{toolName:v.toolName,parameters:v.parameters,toolCallId:v.toolCallId,streamingOutput:v.streamingOutput,defaultExpanded:!1,metadata:t.metadata},v.toolCallId))})}if(t.isAuthError)return r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:"middle",children:[r.jsx(Xe,{message:c("chat.messageCard.authRequired"),description:r.jsx(hs,{remarkPlugins:i,rehypePlugins:l,components:a,children:s}),type:"error",showIcon:!0}),r.jsx(Y,{type:"primary",icon:r.jsx(da,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:u,hints:h}=t.role==="user"?u1(s):{cleanText:s,hints:[]},p=t.role==="assistant"&&"type"in t&&t.type==="text"&&"metadata"in t&&typeof((y=t.metadata)==null?void 0:y.reasoning)=="string"?t.metadata.reasoning:"",g=p.trim().length>0;return t.role==="assistant"&&!s&&!g?r.jsx(cs,{italic:!0,children:c("chat.messageCard.assistantThinking")}):r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:"small",children:[g?r.jsx(ns,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:r.jsx(cs,{strong:!0,children:c("chat.messageCard.reasoning")}),children:r.jsx(hs,{remarkPlugins:i,rehypePlugins:l,components:a,children:p})}]}):null,h.map((f,v)=>f.type==="mcp"?r.jsx(Xe,{type:"info",showIcon:!1,message:r.jsxs(X,{wrap:!0,size:"small",children:[r.jsx(oe,{color:"purple",children:"MCP"}),r.jsx(cs,{strong:!0,children:c("chat.messageCard.selectedTool")}),f.serverId&&r.jsx(cs,{type:"secondary",children:r.jsx(cs,{code:!0,children:f.serverId})}),f.toolName&&r.jsx(cs,{type:"secondary",children:r.jsx(cs,{code:!0,children:f.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${v}`):r.jsx(Xe,{type:"success",showIcon:!1,message:r.jsxs(X,{wrap:!0,size:"small",children:[r.jsx(oe,{color:"success",children:"Skill"}),r.jsx(cs,{strong:!0,children:c("chat.messageCard.selected")}),f.label&&r.jsx(cs,{children:f.label}),f.skillId&&r.jsx(cs,{type:"secondary",children:r.jsx(cs,{code:!0,children:f.skillId})})]}),style:{marginBottom:0}},`hint-skill-${v}`)),u?r.jsx(hs,{remarkPlugins:i,rehypePlugins:l,components:a,children:n?o(u):u}):null]})},h1=m.memo(m1),{Text:Fl}=le,p1=({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(G,{align:"center",justify:"space-between",gap:s.marginXS,style:{marginBottom:s.marginXS},children:[r.jsxs(G,{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(G,{vertical:!0,gap:0,children:[r.jsx(Fl,{strong:!0,style:{fontSize:13,color:n?"var(--lotus-primary)":s.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:a}),r.jsx(Fl,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:n?"Prompt":o?"Assistant":"System"})]})]}),t&&r.jsx(Fl,{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})]})},su=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},f1=e=>e==="text"||e==="plan"||e==="question"||e==="tool_call"||e==="tool_result",g1=(e,t)=>{if(t)return t;if("message_type"in e&&e.message_type){const s=e.message_type;if(f1(s))return s}if(e.role==="assistant"&&e.type==="text"){const s=typeof e.content=="string"?e.content:"";try{const n=su(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"},y1=(e,t)=>{if(t!=="plan"||e.role!=="assistant"||e.type!=="text")return null;const s=e.content??"";try{const n=su(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},b1=(e,t)=>{if(t!=="question"||e.role!=="assistant"||e.type!=="text")return null;const s=e.content??"";try{const n=su(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},Sb=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"?Ry(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""},x1=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}`},Yh=e=>e.map(t=>({name:t.name,extensions:[...t.extensions]})),Xh=e=>e.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",v1={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"},S1='[data-mermaid-loading="true"]';class wb{static async exportMessageText(t){const{format:s,content:n,sessionId:o=null,messageId:a=null,filenamePrefix:i}=t,l=i||["chat-message",o?Xh(o.slice(0,8)):null,a?Xh(a.slice(0,8)):null].filter(Boolean).join("-"),c=s==="markdown"?ks.generateTimestampedFilename(l,"md"):ks.generateTimestampedFilename(l,"pdf");if(s==="markdown"){const d=await ks.saveTextFile(n,Yh(ks.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 ks.saveBinaryFile(d,Yh(ks.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:es.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(t){if(typeof document>"u")throw new Error(es.t("chat.messageActions.pdfUnavailable"));const s=(await Dt(async()=>{const{default:g}=await import("./vendor-pdf-Bg81_snq.js").then(y=>y.h);return{default:g}},__vite__mapDeps([16,1,2,3]),import.meta.url)).default,{jsPDF:n}=await Dt(async()=>{const{jsPDF:g}=await import("./vendor-pdf-Bg81_snq.js").then(y=>y.j);return{jsPDF:g}},__vite__mapDeps([16,1,2,3]),import.meta.url),{createRoot:o}=await Dt(async()=>{const{createRoot:g}=await import("./main-CNnWZQZu.js").then(y=>y.c);return{createRoot:g}},__vite__mapDeps([4,1,2,3,5]),import.meta.url),{flushSync:a}=await Dt(async()=>{const{flushSync:g}=await import("./vendor-antd-DzhFcYgt.js").then(y=>y.R);return{flushSync:g}},__vite__mapDeps([3,2]),import.meta.url),i=xb(v1,{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=es.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(ut.createElement(hs,{remarkPlugins:[Ii,ed],rehypePlugins:[Zc],components:i},t||""))});try{await this.waitForExportRenderReady(d);const g=await this.renderCanvasWithFallback(s,d),y=new n({unit:"pt",format:"a4",orientation:"portrait"}),f=y.internal.pageSize.getWidth(),v=y.internal.pageSize.getHeight(),b=24,x=f-b*2,_=v-b*2,w=g.width/x,k=Math.max(1,Math.floor(_*w));let C=0,E=0;for(;C<g.height;){const R=this.computeSmartSliceHeight(g,C,k),M=Math.max(1,Math.min(R,g.height-C)),T=document.createElement("canvas");T.width=g.width,T.height=M;const P=T.getContext("2d");if(!P)throw new Error("PDF render failed (no canvas context)");P.fillStyle="#ffffff",P.fillRect(0,0,T.width,T.height),P.drawImage(g,0,C,g.width,M,0,0,g.width,M);const S=T.toDataURL("image/jpeg",.92),L=M/w;E>0&&y.addPage(),y.addImage(S,"JPEG",b,b,x,L),C+=M,E+=1}const j=y.output("arraybuffer");return new Uint8Array(j)}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(S1)){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 g=null,y=Number.POSITIVE_INFINITY,f=Number.POSITIVE_INFINITY;for(let v=0;v<i;v+=1){let b=0,x=0;const _=v*c;for(let j=0;j<t.width;j+=d){const R=_+j*4,M=l[R+3];if(x+=1,M<=h)continue;const T=l[R],P=l[R+1],S=l[R+2];(T<u||P<u||S<u)&&(b+=1)}if(x===0)continue;const w=b/x,k=n+v,C=Math.abs(k-s);(w<y||w===y&&C<f)&&(y=w,f=C,g=k)}return g===null||y>p?null:g}catch{return null}}}const w1=({messageText:e,messageId:t,currentSessionId:s,onDelete:n,onRestoreChat:o,onRestoreFilesAndChat:a,cardRef:i})=>{const{message:l}=Ot.useApp(),{t:c}=ne(),[d,u]=m.useState(""),h=m.useCallback(async b=>{try{await os(b)}catch(x){console.error("Failed to copy text:",x)}},[]),p=m.useCallback(b=>`> ${b.replace(/\n/g,`
|
|
228
|
+
> `)}`,[]),g=m.useCallback(()=>{if(!s)return;const b=p(d||e),x=new CustomEvent("reference-text",{detail:{text:b,sessionId:s}});window.dispatchEvent(x)},[p,s,e,d]),y=m.useCallback(async b=>{var w;const x=d||e;if(!x){l.warning(c("chat.messageActions.nothingToExport"));return}const _=await wb.exportMessageText({format:b,content:x,sessionId:s??null,messageId:t??null});if(_.success)l.success(c("chat.messageActions.savedFile",{filename:_.filename}));else{if((w=_.error)!=null&&w.toLowerCase().includes("cancel"))return;l.error(_.error||c("chat.messageActions.exportFailed"))}},[l,s,t,e,d,c]),f=m.useCallback(b=>{b.preventDefault(),b.stopPropagation();const x=window.getSelection(),_=x?x.toString():"";_&&i.current&&x&&i.current.contains(x.anchorNode)?u(_):u("")},[i]);return{contextMenuItems:m.useMemo(()=>{const b=[...o&&a&&s&&t?[{key:"restore-chat",label:c("chat.messageActions.restoreChat"),icon:r.jsx(Ax,{}),onClick:()=>{o()}},{key:"restore-chat-files",label:c("chat.messageActions.restoreFilesAndChat"),icon:r.jsx(yf,{}),onClick:()=>{a()}},{type:"divider"}]:[],{key:"copy",label:c("chat.messageActions.copy"),icon:r.jsx(ss,{}),onClick:()=>{h(d||e)}},{key:"reference",label:c("chat.actions.referenceMessage"),icon:r.jsx(Sf,{}),onClick:g},{type:"divider"},{key:"export-md",label:c("chat.messageActions.exportMarkdown"),icon:r.jsx(yr,{}),onClick:()=>y("markdown")},{key:"export-pdf",label:c("chat.messageActions.exportPdf"),icon:r.jsx(yr,{}),onClick:()=>y("pdf")}];return n&&t&&b.push({key:"delete",label:c("chat.messageActions.deleteMessage"),icon:r.jsx(dn,{}),onClick:()=>n(t),danger:!0}),b},[h,y,t,e,n,o,a,g,d,s,c]),handleMouseUp:f,copyToClipboard:h,referenceMessage:g}},_1=({currentSessionId:e,updateSession:t,sendMessage:s})=>{const n=m.useCallback(async()=>{if(!e)return;const l=N.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}},_b=e=>{const t=e.match(/```mermaid\s*([\s\S]*?)```/i);return t?t[1].trim():e.trim()},T1=(e,t,s)=>{const n=t.trim(),o=_b(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},Vh="_text",Ai=e=>!!(e&&e.role==="assistant"&&"type"in e&&e.type==="text"),Kh=(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(Vh)){const a=e.slice(0,-Vh.length);if(a&&s.some(i=>i.id===a))return a}return e},k1=(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},j1=e=>(e instanceof Error?e.message:String(e)).toLowerCase().includes("message not found"),C1=(e,t,s,n)=>{const o=e.find(a=>a.id===t);return Ai(o)?o:e.find(a=>Ai(a)&&(a.content===s||k1(a.content,n)))},M1=(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
|
+
`)},P1=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 fy().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:M1(e,s)}],temperature:0})).choices)==null?void 0:l[0])==null?void 0:c.message)==null?void 0:d.content)??"";return _b(i)},E1=(e,t)=>{const s=gy(),n=yy(),o=(n==null?void 0:n.model)??s;return m.useCallback(async(a,i)=>{const l=N.getState(),c=t??l.currentSessionId,d=l.chats.find(x=>x.id===c);if(!c||!d)throw new Error("No active chat available");const u=d.messages.find(x=>x.id===e);if(!Ai(u))throw new Error("Mermaid fix is only available for assistant text messages");const h=await P1(a,o,i);if(!h)throw new Error("AI did not return a Mermaid fix");const p=T1(u.content,a,h);if(!p)throw new Error("Unable to locate Mermaid block to update");let g=Kh(e,u,d.messages);try{await Wn.patchSessionMessage(c,g,{content:p})}catch(x){if(!j1(x))throw x;await l.loadChatHistory(c,{mode:"replace",retries:2,retryDelayMs:150,waitForAssistant:!0});const w=N.getState().chats.find(C=>C.id===c);if(!w)throw x;const k=C1(w.messages,e,u.content,a);if(!k)throw x;g=Kh(k.id,k,w.messages),await Wn.patchSessionMessage(c,g,{content:p})}const y=N.getState(),f=y.chats.find(x=>x.id===c);if(!f)throw new Error("No active chat available");const v=new Set([e,g]),b=f.messages.map(x=>!v.has(x.id)||!Ai(x)?x:{...x,content:p});y.updateSession(c,{messages:b})},[e,t,o])},R1=e=>e.xs?"100%":e.sm?"95%":"800px",A1=[{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:"}],I1=({messageId:e,isVisible:t,onRetryWithVariation:s})=>{const{t:n}=ne(),[o,a]=m.useState(null),[i,l]=m.useState(!1),c=m.useCallback(()=>{a(g=>g==="like"?null:"like"),l(!1)},[]),d=m.useCallback(()=>{a(g=>{const y=g==="dislike"?null:"dislike";return l(y==="dislike"),y})},[]),u=m.useCallback(g=>{s&&s(g.prefix)},[s]),p=["lotus-msg-feedback",t?"is-visible":"",o!==null?"has-rating":""].filter(Boolean).join(" ");return r.jsxs("div",{className:p,"data-message-id":e,children:[r.jsx(ke,{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(Ix,{}):r.jsx($x,{})})}),r.jsx(ke,{title:n("feedback.notHelpful","Not helpful"),children:r.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${o==="dislike"?"is-disliked":""}`,onClick:d,"aria-label":n("feedback.notHelpful","Not helpful"),children:o==="dislike"?r.jsx(Dx,{}):r.jsx(Lx,{})})}),i&&s&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"lotus-msg-feedback-sep"}),r.jsx("span",{className:"lotus-msg-feedback-retry",children:A1.map(g=>r.jsx(oe,{color:g.color,bordered:!1,className:"lotus-msg-feedback-retry-tag",onClick:()=>u(g),children:n(g.labelKey,g.fallbackLabel)},g.key))})]})]})},{useToken:$1}=he,{useBreakpoint:D1}=$i,L1="chat-send-message",O1=({sessionId:e,message:t,onDelete:s,messageType:n})=>{const{role:o,id:a}=t,{token:i}=$1(),l=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:c}=ne(),{message:d}=Ot.useApp(),u=D1(),h=N(F=>F.updateSession),p=N(F=>F.loadChatHistory),g=N(F=>F.refreshChats),y=m.useRef(null),[f,v]=m.useState(!1),b=N(F=>e?F.processingChats.has(e):!1),x=m.useCallback(F=>typeof window>"u"?Promise.reject(new Error("window is unavailable")):new Promise((z,de)=>{const Te={content:F,sessionId:e,handled:!1,resolve:z,reject:de};window.dispatchEvent(new CustomEvent(L1,{detail:Te})),Te.handled||de(new Error("No chat message dispatcher available"))}),[e]),_=m.useMemo(()=>{if(!t.createdAt)return null;const F=new Date(t.createdAt);if(Number.isNaN(F.getTime()))return null;try{return sP(F,"MMM d, yyyy HH:mm")}catch{return F.toLocaleString()}},[t.createdAt]),w=m.useMemo(()=>g1(t,n),[t,n]),k=m.useMemo(()=>y1(t,w),[t,w]),C=m.useMemo(()=>b1(t,w),[t,w]),E=m.useMemo(()=>Sb(t),[t]),j=E1(a,e),R=m.useCallback(async F=>{var z;if(!e||!a){d.warning(c("chat.messageActions.cannotRestore"));return}try{const de=await Wn.restoreSessionState(e,{target_message_id:a,restore_files:F});await p(e,{mode:"replace"}),await g();const Te=((z=de.file_errors)==null?void 0:z.length)??0;if(Te>0){d.warning(c("chat.messageActions.restorePartial",{count:Te}));return}F?d.success(c("chat.messageActions.restoreFilesSuccess",{count:de.messages_removed})):d.success(c("chat.messageActions.restoreSuccess",{count:de.messages_removed}))}catch(de){const Te=de instanceof Error?de.message:c("chat.messageActions.restoreFailed");d.error(Te)}},[d,e,p,a,g,c]),M=m.useCallback(()=>{R(!1)},[R]),T=m.useCallback(()=>{R(!0)},[R]),{contextMenuItems:P,handleMouseUp:S,copyToClipboard:L,referenceMessage:$}=w1({messageText:E,messageId:a,currentSessionId:e,onDelete:s,onRestoreChat:M,onRestoreFilesAndChat:T,cardRef:y}),I=m.useMemo(()=>o==="user"&&E.startsWith("/"),[o,E]),W=m.useMemo(()=>xb(i,{onFixMermaid:j}),[i,j]),A=m.useMemo(()=>[Ii,ed],[]),O=m.useMemo(()=>[Zc],[]),D=m.useMemo(()=>[cP(()=>L(E),c("chat.actions.copyMessage")),dP($,c("chat.actions.referenceMessage"))],[E,L,$,c]),{handleExecutePlan:H,handleRefinePlan:B,handleQuestionAnswer:K}=_1({currentSessionId:e,updateSession:h,sendMessage:x});return w==="plan"&&k&&o==="assistant"?r.jsx(Jy,{plan:k,contextId:e||"",onExecute:H,onRefine:B,timestamp:_??void 0}):w==="question"&&C&&o==="assistant"?r.jsx(Qy,{question:C,contextId:e||"",onAnswer:K,disabled:b||!1,timestamp:_??void 0}):Bk(t)?r.jsx(bP,{taskList:t.taskList}):Nk(t)?(st("[MessageCard]","[MessageCard] Rendering FileReferenceCard for message:",t.id,"paths:",t.paths),r.jsx(G,{justify:"flex-end",style:{width:"100%"},children:r.jsx(Zy,{paths:t.paths,displayText:t.displayText,timestamp:_??void 0})})):r.jsxs(G,{vertical:!0,onContextMenu:F=>S(F),style:{width:"100%"},children:[r.jsx(zn,{menu:{items:P},trigger:["contextMenu"],children:r.jsx(ee,{"data-testid":o==="assistant"?"assistant-message":"user-message",id:a?`message-${a}`:void 0,ref:y,style:{width:"100%",minWidth:"100%",maxWidth:R1(u),margin:"0 auto",background:o==="user"?"var(--lotus-message-user-bg)":o==="assistant"?"var(--lotus-message-assistant-bg)":i.colorBgContainer,backdropFilter:l?"none":"blur(14px)",WebkitBackdropFilter:l?"none":"blur(14px)",border:o==="user"?"1px solid var(--lotus-message-user-border)":"1px solid var(--lotus-glass-border-subtle)",borderRadius:i.borderRadiusLG,boxShadow:f?"var(--lotus-card-hover-shadow)":"var(--lotus-shadow-soft)",position:"relative",wordWrap:"break-word",overflowWrap:"break-word",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",transform:f?"translateY(-2px) scale(1.002)":"none",overflow:"hidden"},bodyStyle:{padding:i.paddingMD},onMouseEnter:()=>v(!0),onMouseLeave:()=>v(!1),children:r.jsxs(X,{direction:"vertical",size:i.marginXS,style:{width:"100%",maxWidth:"100%"},children:[r.jsx(p1,{role:o,formattedTimestamp:_,token:i}),t.role==="user"&&t.images&&r.jsx(oP,{images:t.images}),r.jsx(G,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:r.jsx(h1,{sessionId:e,message:t,messageText:E,isUserToolCall:I,formatUserToolCall:x1,markdownComponents:W,markdownPlugins:A,rehypePlugins:O})}),r.jsx(lP,{isVisible:f,position:{bottom:i.paddingXS,right:i.paddingXS},buttons:D})]})})}),o==="assistant"&&w==="text"&&a&&r.jsx(I1,{messageId:a,isVisible:f})]})},Tb=m.memo(O1,(e,t)=>e.message===t.message&&e.messageType===t.messageType&&e.onDelete===t.onDelete);Tb.displayName="MessageCard";const{Text:ta}=le,{useToken:F1}=he,z1=e=>({p:({children:t})=>r.jsx(ta,{style:{marginBottom:e.marginSM,display:"block"},children:t}),ol:({children:t})=>r.jsx("ol",{style:{marginBottom:e.marginSM,paddingLeft:20},children:t}),ul:({children:t})=>r.jsx("ul",{style:{marginBottom:e.marginSM,paddingLeft:20},children:t}),li:({children:t})=>r.jsx("li",{style:{marginBottom:e.marginXS},children:t}),code({className:t,children:s,inline:n,...o}){const a=/language-([^\s]+)/i.exec(t||""),i=a?a[1]:"",l=n??(!a&&!t),c=s?String(s).replace(/\n$/,""):"";return l?r.jsx(ta,{code:!0,className:t,...o,children:s}):c.trim()?i.toLowerCase()==="mermaid"?r.jsx(ee,{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})})}):yb(i,c,e,void 0):null},blockquote:({children:t})=>r.jsx(ee,{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(),bb(n)},style:{color:e.colorLink,textDecoration:"underline",overflowWrap:"anywhere"},children:t}):r.jsx(r.Fragment,{children:t})},table:({children:t})=>r.jsx(ee,{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})}),kb=m.memo(({sessionId:e})=>{const{token:t}=F1(),s=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:n}=ne(),o=`streaming-${e}`,a=`streaming-reasoning-${e}`,i=`streaming-status-${e}`,[l,c]=m.useState(()=>ze.getLatest(o)??""),[d,u]=m.useState(()=>ze.getLatest(a)??""),[h,p]=m.useState(()=>ze.getLatest(i)??"");m.useEffect(()=>ze.subscribeMessage(o,b=>{c(b??"")}),[o]),m.useEffect(()=>ze.subscribeMessage(a,b=>{u(b??"")}),[a]),m.useEffect(()=>ze.subscribeMessage(i,b=>{p(b??"")}),[i]);const g=m.useMemo(()=>{const b=h.trim().toLowerCase();if(!b)return n("chat.messageCard.assistantThinking");if(b==="context_compacting")return n("chat.messageCard.assistantCompactingContext");if(b==="context_compaction_degraded")return n("chat.messageCard.assistantCompactingContextDegraded");if(b==="context_compaction_failed")return n("chat.messageCard.assistantCompactingContextFailed");if(b==="memory_updating")return n("chat.messageCard.assistantUpdatingMemory");if(b.startsWith("tool_running:")){const _=(b.slice(13).trim()||"tool").replace(/[_-]+/g," ");return n("chat.messageCard.assistantRunningTool",{tool:_})}return n("chat.messageCard.assistantThinking")},[h,n]),y=m.useMemo(()=>[Ii,ed],[]),f=m.useMemo(()=>[Zc],[]),v=m.useMemo(()=>z1(t),[t]);return r.jsx(ee,{"data-testid":"streaming-indicator",role:"status","aria-live":"polite","aria-busy":!0,"aria-label":"AI is responding",style:{width:"100%",minWidth:"100%",maxWidth:"800px",margin:"0 auto",background:"var(--lotus-message-streaming-bg)",backdropFilter:s?"none":"blur(14px)",WebkitBackdropFilter:s?"none":"blur(14px)",borderRadius:t.borderRadiusLG,boxShadow:"none",position:"relative",wordWrap:"break-word",overflowWrap:"break-word"},children:r.jsxs(X,{direction:"vertical",size:t.marginXS,style:{width:"100%",maxWidth:"100%"},children:[r.jsx(G,{align:"baseline",justify:"space-between",gap:t.marginXS,children:r.jsx(ta,{type:"secondary",strong:!0,style:{fontSize:t.fontSizeSM},children:n("chat.streaming.assistant")})}),r.jsxs(G,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:[d?r.jsx(ns,{size:"small",defaultActiveKey:["reasoning"],style:{marginBottom:t.marginSM,background:t.colorBgContainer,borderColor:t.colorBorderSecondary},items:[{key:"reasoning",label:r.jsx(ta,{strong:!0,children:n("chat.messageCard.reasoning")}),children:r.jsx(hs,{remarkPlugins:y,rehypePlugins:f,components:v,children:d})}]}):null,!l||h?r.jsx(ta,{italic:!0,className:"thinking-shimmer",children:g}):null,l?r.jsx(hs,{remarkPlugins:y,rehypePlugins:f,components:v,children:l}):null,r.jsx("span",{className:"blinking-cursor",style:{display:"inline-block",marginLeft:"0.2em",color:t.colorText}})]})]})})});kb.displayName="StreamingMessageCard";const{Text:Xt}=le,N1="chat-session-tool-collapse:",jb=(e,t)=>`${N1}${e}:${t}`,zl=(e,t)=>{if(typeof window>"u")return null;try{const s=window.localStorage.getItem(jb(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}},B1=(e,t,s)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(jb(e,t),JSON.stringify(s))}catch{}},Nl=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}`},W1=e=>{var t,s;return((s=(t=e.call.toolCalls)==null?void 0:t[0])==null?void 0:s.toolCallId)||e.call.id},U1="synthetic-tool-call:",q1=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(U1)&&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 H1(e,t,s){return e.result?e.result.isError?{icon:r.jsx(Oi,{style:{color:t.colorError}}),color:t.colorError,text:s("components.toolSession.error")}:{icon:r.jsx(Hs,{style:{color:t.colorSuccess}}),color:t.colorSuccess,text:s("components.toolSession.done")}:{icon:r.jsx(gr,{spin:!0,style:{color:t.colorPrimary}}),color:t.colorPrimary,text:s("components.toolSession.running")}}function Y1(e,t){const s=Yn(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 X1=({tools:e,sessionId:t,defaultExpanded:s=!1,onDeleteMessageIds:n})=>{const{t:o}=ne(),{token:a}=he.useToken(),i=e.length===1,l=m.useMemo(()=>{var R,M,T,P;const C=e[0],E=(M=(R=C==null?void 0:C.call)==null?void 0:R.toolCalls)==null?void 0:M[0];return`${(C==null?void 0:C.callMessageId)||((T=C==null?void 0:C.call)==null?void 0:T.id)||(C==null?void 0:C.resultMessageId)||((P=C==null?void 0:C.result)==null?void 0:P.id)||"tool-message-missing"}:${(E==null?void 0:E.toolCallId)||"tool-call-missing"}`},[e]),c=m.useMemo(()=>{const C=e[0];return C?Nl(C):null},[e]),[d,u]=m.useState(()=>{const C=zl(t,l);return C?C.isExpanded:s}),[h,p]=m.useState(()=>{const C=zl(t,l);return C?new Set(C.expandedTools):new Set(s&&c?[c]:[])});m.useEffect(()=>{const C=zl(t,l);if(C){u(C.isExpanded),p(new Set(C.expandedTools));return}u(s),p(new Set(s&&c?[c]:[]))},[s,c,t,l]),m.useEffect(()=>{const C=new Set(e.map(E=>Nl(E)));p(E=>{const j=new Set;let R=!1;return E.forEach(M=>{C.has(M)?j.add(M):R=!0}),!R&&j.size===E.size?E:j})},[e]),m.useEffect(()=>{B1(t,l,{isExpanded:d,expandedTools:Array.from(h)})},[t,l,d,h]);const{completedCount:g,pendingCount:y,hasErrors:f}=m.useMemo(()=>{let C=0,E=0,j=!1;return e.forEach(R=>{R.result?(C++,R.result.isError&&(j=!0)):E++}),{completedCount:C,pendingCount:E,hasErrors:j}},[e]),v=m.useMemo(()=>y>0?{color:"processing",text:o("components.toolSession.completedProgress",{completed:g,total:e.length})}:f?{color:"warning",text:o("components.toolSession.completedWithErrors",{completed:g})}:{color:"success",text:o("components.toolSession.completedOnly",{completed:g})},[g,y,f,e.length,o]),b=m.useMemo(()=>{let C=0,E=0,j=0;return e.forEach(R=>{var P,S;const M=(S=(P=R.result)==null?void 0:P.result)==null?void 0:S.result;if(!M)return;const T=Dc(M);T&&(C+=T.added,E+=T.removed,j+=1)}),{added:C,removed:E,changedTools:j}},[e]),x=m.useMemo(()=>{var j,R,M;if(e.length!==1)return o("components.toolSession.title");const C=(M=(R=(j=e[0])==null?void 0:j.call)==null?void 0:R.toolCalls)==null?void 0:M[0];if(!C)return o("components.toolSession.title");const E=Yn(C.toolName);return E?`MCP ${E.serverId}: ${E.toolName}`:C.toolName||o("components.toolSession.title")},[e,o]),_=m.useMemo(()=>e.map((C,E)=>{const j=C.call.toolCalls[0];if(!j)return null;const R=H1(C,a,o),M=Y1(j.toolName,j.parameters),T=Yn(j.toolName),P=C.result?Dc(C.result.result.result):null,S=C.result?wa(C.result.result.result):null,L=q1(C);return{key:Nl(C),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:[E+1,"."]}),r.jsx("span",{style:{flexShrink:0},children:R.icon}),T?r.jsxs(X,{size:"small",wrap:!1,children:[r.jsx(oe,{color:"purple",style:{marginInlineEnd:0},children:"MCP"}),r.jsx(Xt,{strong:!0,style:{fontSize:a.fontSizeSM},children:T.toolName}),r.jsx(Xt,{type:"secondary",style:{fontSize:a.fontSizeSM},children:r.jsx(Xt,{code:!0,style:{fontSize:a.fontSizeSM},children:T.serverId})})]}):r.jsx(Xt,{strong:!0,style:{fontSize:a.fontSizeSM,flexShrink:0},children:j.toolName}),r.jsx(Xt,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:a.fontSizeSM},children:M}),S&&r.jsx(Xt,{type:"secondary",ellipsis:!0,style:{maxWidth:180,fontSize:a.fontSizeSM},children:S.file_path.split(/[\\/]/).pop()||S.file_path}),P&&r.jsxs(X,{size:4,style:{marginLeft:a.marginXS},children:[r.jsxs(Xt,{style:{color:a.colorSuccess,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",P.added]}),r.jsxs(Xt,{style:{color:a.colorError,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",P.removed]})]}),n&&r.jsx(ke,{title:L.length>0?o("components.toolSession.deleteMessage"):o("components.toolSession.noPersistedMessage"),children:r.jsx(Y,{type:"text",size:"small",danger:!0,icon:r.jsx(dn,{}),"aria-label":o("components.toolSession.deleteMessage"),"data-testid":`delete-tool-message-${W1(C)}`,disabled:L.length===0,onClick:$=>{$.preventDefault(),$.stopPropagation(),L.length!==0&&n(L)}})})]}),children:r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:a.marginSM,children:[r.jsx(tu,{toolName:j.toolName,parameters:j.parameters,toolCallId:j.toolCallId,streamingOutput:j.streamingOutput,defaultExpanded:!1}),C.result&&C.result.result.display_preference!=="Hidden"&&r.jsx(eu,{content:C.result.result.result,toolName:j.toolName,status:C.result.isError?"error":"success",timestamp:C.result.createdAt,defaultCollapsed:!1})]}),style:{borderBottom:E<e.length-1?`1px solid ${a.colorBorderSecondary}`:void 0}}}).filter(C=>C!==null),[n,o,a,e]),w=r.jsx("div",{style:{padding:a.paddingSM},children:r.jsx(ns,{ghost:!0,activeKey:Array.from(h),onChange:C=>{const E=new Set(Array.isArray(C)?C:C?[C]:[]);p(E)},items:_})}),k={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:k,children:w})}):r.jsxs("div",{style:k,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(Sr,{style:{color:a.colorPrimary}}),r.jsx(Xt,{strong:!0,style:{flex:1},children:x}),r.jsx(rd,{count:e.length,style:{backgroundColor:a.colorPrimary}}),b.changedTools>0&&r.jsxs(X,{size:4,style:{marginInlineStart:a.marginXS},children:[r.jsxs(Xt,{style:{color:a.colorSuccess,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",b.added]}),r.jsxs(Xt,{style:{color:a.colorError,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",b.removed]})]}),r.jsx(Xt,{type:"secondary",style:{fontSize:a.fontSizeSM},children:v.text}),r.jsx("div",{style:{marginLeft:a.marginXS},children:d?r.jsx(Wt,{style:{color:a.colorTextSecondary}}):r.jsx(Ws,{style:{color:a.colorTextSecondary}})})]}),d&&w]})},Cb=m.memo(X1);Cb.displayName="ToolSessionCard";const{Content:V1}=Dn,{Text:Gh}=le,K1=24,G1=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};function Bl(e){return"type"in e&&(e.type==="tool_session"||e.type==="compression_divider")?e.id:e.message.id}const J1=({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:g,padding:y,selectionMode:f,selectedMessageIds:v,selectableMessageIds:b,onToggleMessageSelection:x})=>{const{t:_}=ne(),w=m.useRef(c);w.current=c;const k=m.useCallback(P=>{const S=w.current[P];return S?Bl(S):String(P)},[]),C=WC({count:c.length,getScrollElement:()=>l.current,estimateSize:()=>120,overscan:5,gap:d,getItemKey:k}),E=(P,S)=>{if(!f)return null;const L=b.has(P);return r.jsx(Ox,{checked:v.has(P),disabled:!L,onChange:()=>{L&&x(P)},style:{marginTop:8,marginLeft:S==="flex-end"?8:0,marginRight:S==="flex-start"?8:0}})},j=P=>{const S=s(P);if(S.type==="compression_divider"){const L=G1(S.createdAt);return r.jsx("div",{role:"note","aria-label":_("chat.compression.timelineAria",{detail:S.label,time:L,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(G,{align:"center",justify:"space-between",gap:8,wrap:!0,children:[r.jsxs(G,{align:"center",gap:8,wrap:!0,children:[r.jsx(oe,{color:"gold",icon:r.jsx(_f,{}),children:_("chat.compression.tag","Context compressed")}),r.jsx(Gh,{strong:!0,style:{fontSize:12},children:S.label})]}),r.jsx(Gh,{type:"secondary",style:{fontSize:11},children:L})]})})}return S.type==="tool_session"?r.jsx(G,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:r.jsx("div",{id:`message-${S.id}`,style:{width:"100%",maxWidth:h.xs?"100%":"90%"},children:r.jsx(Cb,{tools:S.tools,sessionId:S.sessionId,createdAt:S.createdAt,defaultExpanded:!1,onDeleteMessageIds:t?o:void 0})})}):S.message.role==="system"?r.jsxs(G,{align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[E(S.message.id,"flex-start"),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsx(Yy,{currentChat:e,message:S.message})})]}):r.jsxs(G,{justify:S.align,align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[S.align==="flex-start"&&E(S.message.id,S.align),r.jsx("div",{style:{width:S.message.role==="user"?"85%":"100%",maxWidth:h.xs?"100%":"90%"},children:r.jsx(Tb,{sessionId:t,message:S.message,messageType:S.messageType,onDelete:S.message.id===p?void 0:n})}),S.align==="flex-end"&&E(S.message.id,S.align)]})},R=(u||i)&&c.length>0,M=C.getVirtualItems(),T=c.length>K1;return r.jsxs(V1,{role:"log","aria-live":"polite","aria-label":"Chat messages",className:`chat-view-messages-list ${u?"visible":"hidden"}`,style:{flex:1,minHeight:0,padding:y,overflowY:"auto",opacity:u?1:0,scrollbarWidth:"none",msOverflowStyle:"none"},ref:l,onScroll:a,children:[R&&(T?r.jsx("div",{style:{position:"relative",width:"100%",height:C.getTotalSize()},children:M.map(P=>{const S=c[P.index];if(!S)return null;const L=Bl(S);return r.jsx("div",{"data-chat-entry-id":L,"data-index":P.index,ref:C.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${P.start}px)`},children:r.jsx("div",{className:"messageEnter",children:j(S)})},P.key)})}):r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:d,width:"100%"},children:c.map(P=>{const S=Bl(P);return r.jsx("div",{"data-chat-entry-id":S,className:"messageEnter",children:j(P)},S)})})),g.matches("THINKING")&&t&&r.jsx("div",{className:"streaming-card-enter",style:{paddingTop:d},children:r.jsx(G,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:r.jsx("div",{style:{width:"100%",maxWidth:h.xs?"100%":"90%"},children:r.jsx(kb,{sessionId:t})})})})]})},{Text:Gr}=le,Q1=e=>({pending:{icon:r.jsx(Ys,{}),color:e.colorTextTertiary,textKey:"components.todoList.status.pending",tagColor:"default"},in_progress:{icon:r.jsx(od,{spin:!0}),color:e.colorPrimary,textKey:"components.todoList.status.inProgress",tagColor:"processing"},completed:{icon:r.jsx(Hs,{}),color:e.colorSuccess,textKey:"components.todoList.status.completed",tagColor:"success"},blocked:{icon:r.jsx(Oi,{}),color:e.colorError,textKey:"components.todoList.status.blocked",tagColor:"error"}}),Z1=({sessionId:e,initialCollapsed:t=!0})=>{const{t:s}=ne(),{token:n}=he.useToken(),o=ut.useMemo(()=>Q1(n),[n]),a=N(E=>E.chats.find(j=>j.id===e)),i=(a==null?void 0:a.kind)==="child"&&(a.parentSessionId||a.rootSessionId)||e,l=N(E=>E.taskLists[i]),c=N(E=>E.activeItems[i]),d=N(E=>E.evaluationStates[i]),[u,h]=m.useState(t),[p,g]=m.useState(!1),y=(d==null?void 0:d.isEvaluating)||!1,f=(d==null?void 0:d.reasoning)||null,v=l?{session_id:l.session_id,title:l.title,items:l.items,progress:{completed:l.items.filter(E=>E.status==="completed").length,total:l.items.length,percentage:l.items.length>0?Math.round(l.items.filter(E=>E.status==="completed").length/l.items.length*100):0}}:null;if(!v)return null;const b=()=>{p||h(!u)},x=E=>{E.stopPropagation(),g(!p),p||h(!1)},{title:_,items:w,progress:k}=v,C=k.percentage===100;return r.jsx(ee,{size:"small",style:{marginBottom:16,borderRadius:8,boxShadow:y?`0 0 0 2px ${n.colorPrimaryBorder}`:"0 2px 8px rgba(0, 0, 0, 0.06)",opacity:u&&!p?.9:1},styles:{body:{padding:u?"12px 16px":16}},title:r.jsxs(X,{onClick:b,style:{cursor:"pointer",width:"100%"},children:[r.jsx(zx,{style:{color:n.colorPrimary}}),r.jsx(Gr,{strong:!0,style:{fontSize:15},children:_||s("components.todoList.title")}),y&&r.jsx(oe,{icon:r.jsx(od,{spin:!0}),color:"processing",children:s("components.todoList.evaluating")}),!u&&k.total>0&&r.jsx(rd,{count:`${k.completed}/${k.total}`,style:{backgroundColor:C?n.colorSuccess:n.colorPrimary}})]}),extra:r.jsxs(X,{children:[k.total>0&&u&&r.jsxs(Gr,{type:"secondary",style:{fontSize:13},children:[k.completed,"/",k.total,C&&r.jsx(Hs,{style:{color:n.colorSuccess,marginLeft:4}})]}),r.jsx(ke,{title:s(p?"components.todoList.unpin":"components.todoList.pin"),children:r.jsx("span",{onClick:x,style:{cursor:"pointer",color:p?n.colorPrimary:n.colorTextSecondary,fontSize:16},children:p?r.jsx(sc,{}):r.jsx(sd,{})})}),!p&&r.jsx("span",{onClick:b,style:{cursor:"pointer",color:n.colorTextSecondary,fontSize:12,transform:u?"rotate(-90deg)":void 0,transition:"transform 0.2s"},children:u?r.jsx(Ws,{}):r.jsx(Wt,{})})]}),children:!u&&r.jsxs(r.Fragment,{children:[f&&r.jsx(Xe,{icon:r.jsx(ad,{}),message:s("components.todoList.llmEvaluation"),description:f,type:"info",showIcon:!0,style:{marginBottom:16}}),k.total>0&&r.jsx("div",{style:{marginBottom:16},children:r.jsx(id,{percent:k.percentage,size:"small",status:C?"success":"active",format:E=>r.jsxs(Gr,{type:"secondary",children:[E,"%"]})})}),r.jsx(nt,{size:"small",dataSource:w,renderItem:E=>{const j=o[E.status],R=c===E.id,M=s(j.textKey);return r.jsx(nt.Item,{style:{padding:"12px 0",borderLeft:R?`3px solid ${n.colorPrimary}`:"3px solid transparent",paddingLeft:R?12:15,backgroundColor:R?n.colorPrimaryBg:"transparent",borderRadius:4,marginBottom:4},children:r.jsx("div",{style:{width:"100%"},children:r.jsxs(X,{align:"start",style:{width:"100%"},children:[r.jsx(ke,{title:M,children:r.jsx("span",{style:{color:j.color,fontSize:16},children:j.icon})}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsx(Gr,{style:{textDecoration:E.status==="completed"?"line-through":"none",color:E.status==="completed"?n.colorTextSecondary:n.colorText,fontWeight:R?500:400},children:E.description}),r.jsx("div",{style:{marginTop:4},children:r.jsxs(X,{size:8,wrap:!0,children:[r.jsx(oe,{color:j.tagColor,children:M}),E.tool_calls_count!==void 0&&E.tool_calls_count>0&&r.jsxs(oe,{icon:r.jsx(Sr,{}),color:"processing",children:[E.tool_calls_count," ",s("components.todoList.tools")]}),E.depends_on.length>0&&r.jsx(ke,{title:s("components.todoList.dependsOn",{deps:E.depends_on.join(", ")}),children:r.jsxs(oe,{icon:r.jsx(Fx,{}),children:[E.depends_on.length," ",s("components.todoList.dependencies")]})})]})}),E.notes&&r.jsx(Gr,{type:"secondary",style:{display:"block",marginTop:6,fontSize:12,padding:"4px 8px",backgroundColor:n.colorFillQuaternary,borderRadius:4},children:E.notes})]})]})})})}})]})})},eR="_questionCard_15meh_1",tR="_questionHeader_15meh_8",sR="_headerLeft_15meh_27",nR="_questionIcon_15meh_35",rR="_questionText_15meh_40",oR="_collapseBtn_15meh_52",aR="_questionBody_15meh_57",iR="_optionsGroup_15meh_61",lR="_optionItem_15meh_65",cR="_customHint_15meh_81",dR="_questionFooter_15meh_93",Vt={questionCard:eR,questionHeader:tR,headerLeft:sR,questionIcon:nR,questionText:rR,collapseBtn:oR,questionBody:aR,optionsGroup:iR,optionItem:lR,customHint:cR,questionFooter:dR},{Text:Ya}=le,{useToken:uR}=he,mR=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
|
+
`):""},hR=({sessionId:e,onResponseSubmitted:t,onQuestionAppeared:s})=>{var B,K;const{t:n}=ne(),{token:o}=uR(),[a,i]=m.useState(null),[l,c]=m.useState(null),[d,u]=m.useState(!1),[h,p]=m.useState(!0),[g,y]=m.useState(!1),f=m.useRef(0),v=m.useRef(null),b=m.useRef(s);b.current=s;const x=N(F=>F.setSessionProcessing),_=N(F=>F.setPendingQuestionRespond),w=N(F=>F.clearPendingQuestionRespondForSession),k=N(F=>F.chats.find(z=>z.id===e)||null),C=Bd((B=k==null?void 0:k.config)==null?void 0:B.model_ref),E=N(F=>{var z;return e?(z=F.inputStates)==null?void 0:z[e]:void 0}),j=Ee(F=>F.currentProvider),R=Ee(F=>F.providerConfig),M=m.useMemo(()=>{var F;return(F=R.providers[j])==null?void 0:F.reasoning_effort},[R,j]),T=m.useMemo(()=>e?bd(e):void 0,[e]),P=((K=k==null?void 0:k.config)==null?void 0:K.reasoningEffort)??(E==null?void 0:E.reasoningEffort)??T??M??"medium",S=N(F=>e?F.isSessionProcessing(e):!1),L=m.useCallback(async()=>{try{const F=await pe.get(`respond/${e}/pending`);F.has_pending_question?(i(z=>{const de=Ka({sessionId:e,question:F.question,options:F.options,allowCustom:F.allow_custom,toolCallId:F.tool_call_id});return(z!=null&&z.has_pending_question?Ka({sessionId:e,question:z.question,options:z.options,allowCustom:z.allow_custom,toolCallId:z.tool_call_id}):null)===de?z??F:F}),f.current=0):(i(null),v.current=null,f.current+=1)}catch(F){if(F instanceof Error&&F.message.includes("404")){i(null),v.current=null,f.current+=1;return}console.error("Failed to fetch pending question:",F)}finally{p(!1)}},[e]);m.useEffect(()=>{f.current=0,v.current=null,p(!0),c(null),y(!1)},[e]),m.useEffect(()=>{var F;if(a!=null&&a.has_pending_question){const z=Ka({sessionId:e,question:a==null?void 0:a.question,options:a==null?void 0:a.options,allowCustom:a==null?void 0:a.allow_custom,toolCallId:a==null?void 0:a.tool_call_id}),de=v.current===z;_({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}),de||(c(null),y(!1),(F=b.current)==null||F.call(b)),v.current=z}else v.current=null,w(e)},[a==null?void 0:a.allow_custom,a==null?void 0:a.has_pending_question,a==null?void 0:a.options,a==null?void 0:a.question,a==null?void 0:a.tool_call_id,e,_,w]);const $=a!=null&&a.has_pending_question||S?3e3:15e3;m.useEffect(()=>{L();const F=setInterval(()=>{d||L()},$);return()=>clearInterval(F)},[L,d,$]),m.useEffect(()=>{if(typeof window>"u")return;const F=z=>{var $e;const Te=(($e=z.detail)==null?void 0:$e.sessionId)??null;!Te||Te!==e||(i(null),c(null),f.current=0,w(e))};return window.addEventListener(pr,F),()=>{window.removeEventListener(pr,F)}},[e,w]);const I=m.useCallback(F=>{c(F)},[]);m.useEffect(()=>()=>{w(e)},[w,e]);const W=async()=>{if(!l||l==="custom"){fe.warning(n("components.questionDialog.selectOptionWarning"));return}u(!0);try{const F={};Ee.getState().isProviderModelRefEnabled()&&C&&(F.model_ref=C,F.provider=C.provider);const z=await pe.post(`respond/${e}`,{response:l,reasoning_effort:P,...F});fe.success(n("components.questionDialog.responseSubmitted")),i(null),c(null),f.current=0,typeof window<"u"&&window.dispatchEvent(new CustomEvent(pr,{detail:{sessionId:e}}));const de=z==null?void 0:z.auto_resume_status;["started","already_running"].includes(de||"")?e&&x(e,!0):de==="error"&&console.error("[QuestionDialog] Failed to auto-resume agent execution"),t==null||t()}catch(F){console.error("Failed to submit response:",F),fe.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:A,options:O,allow_custom:D}=a,H=mR(A);return r.jsxs("div",{className:Vt.questionCard,style:{background:o.colorBgContainer,borderColor:o.colorBorderSecondary,border:`1px solid ${o.colorBorderSecondary}`},children:[r.jsxs("div",{className:Vt.questionHeader,"data-collapsed":g?"true":"false",onClick:()=>y(F=>!F),role:"button",tabIndex:0,onKeyDown:F=>{(F.key==="Enter"||F.key===" ")&&y(z=>!z)},children:[r.jsxs("span",{className:Vt.headerLeft,children:[r.jsx("span",{className:Vt.questionIcon,children:"🤔"}),r.jsx(Ya,{strong:!0,className:Vt.questionText,style:{color:o.colorPrimary,whiteSpace:"pre-wrap"},title:g?H:void 0,children:H})]}),r.jsx(Y,{type:"text",size:"small",icon:g?r.jsx(Wt,{}):r.jsx(ld,{}),className:Vt.collapseBtn,tabIndex:-1})]}),!g&&r.jsxs("div",{className:Vt.questionBody,children:[r.jsx(ts.Group,{className:Vt.optionsGroup,value:l,onChange:F=>I(F.target.value),children:r.jsxs(X,{direction:"vertical",size:4,style:{width:"100%"},children:[O==null?void 0:O.map((F,z)=>r.jsx(ts,{value:F,className:Vt.optionItem,children:r.jsx(Ya,{style:{color:o.colorText},children:F})},z)),D&&r.jsx(ts,{value:"custom",className:Vt.optionItem,children:r.jsxs(X,{size:4,children:[r.jsx(ca,{}),r.jsx(Ya,{style:{color:o.colorText},children:n("components.questionDialog.otherTypeBelow")})]})})]})}),l==="custom"&&r.jsx("div",{className:Vt.customHint,children:r.jsx(Ya,{type:"secondary",style:{fontSize:12},children:n("components.questionDialog.customAnswerTip")})}),l&&l!=="custom"&&r.jsx("div",{className:Vt.questionFooter,children:r.jsx(Y,{type:"primary",size:"small",onClick:W,loading:d,children:n("components.questionDialog.confirm")})})]})]})};function Mb(e){return typeof e.maxContextTokens=="number"&&e.maxContextTokens>0?e.maxContextTokens:e.budgetLimit>0?e.budgetLimit:0}function Pb(e){const t=Mb(e);return t===0?0:e.totalTokens/t*100}function pR(e){const t=Pb(e);return t>=90?"error":t>=70?"warning":t>=50?"success":"default"}function Jr(e){return e.toLocaleString()}const fR=({usage:e,showDetails:t=!0,size:s="small",className:n=""})=>{const{t:o}=ne(),a=Mb(e),i=Pb(e),l=h=>{const p=Math.round(h*10)/10;return Number.isInteger(p)?p.toFixed(0):p.toFixed(1)},c=pR(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"),":"," ",Jr(e.totalTokens)," / ",Jr(a)," ",o("components.tokenUsage.tokens")]}),r.jsx("div",{style:{fontSize:12,color:"var(--lotus-metric-text-muted)"},children:o("components.tokenUsage.usedPercent",{value:i.toFixed(1)})}),t&&r.jsxs("div",{style:{marginTop:6,borderTop:"1px solid var(--lotus-metric-tooltip-border)",paddingTop:6,fontSize:11},children:[r.jsxs("div",{children:[o("components.tokenUsage.system"),": ",Jr(e.systemTokens)]}),e.summaryTokens>0&&r.jsxs("div",{children:[o("components.tokenUsage.summary"),": ",Jr(e.summaryTokens)]}),r.jsxs("div",{children:[o("components.tokenUsage.messages"),": ",Jr(e.windowTokens)]}),typeof e.promptCachedToolOutputs=="number"&&e.promptCachedToolOutputs>0&&r.jsx("div",{style:{color:"var(--lotus-metric-text-muted)"},children:o("components.tokenUsage.cachedToolOutputs",{count:e.promptCachedToolOutputs,defaultValue:"Prompt cache: {{count}} tool outputs summarized"})})]})]});return r.jsx(ke,{title:u,placement:"top",arrow:!0,children:r.jsxs(X,{className:`token-usage-display ${n}`,size:4,align:"center",style:{lineHeight:1},children:[r.jsx(id,{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),"%"]})]})})},$n=class $n{static getInstance(){return $n.instance||($n.instance=new $n),$n.instance}parseUserCommand(t){st("[ToolService]",`[ToolService] parseUserCommand: Parsing content: "${t}"`);const s=t.trim();if(!s.startsWith("/"))return st("[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 st("[ToolService]","[ToolService] parseUserCommand: Successfully parsed command:",i),i}return st("[ToolService]","[ToolService] parseUserCommand: Failed to parse tool name from content."),null}parseAIResponseToToolCall(t){return this.parseUserCommand(t)}async executeTool(t){st("[ToolService]","[ToolService] executeTool: Attempting to execute tool via HTTP with request:",t);try{const s=await xe.post("tools/execute",t),n=JSON.parse(s.result);return st("[ToolService]","[ToolService] executeTool: Parsed structured result:",n),n}catch(s){throw console.error("[ToolService] executeTool: HTTP tool execution failed:",s),s instanceof Bn?new Error(`Workflow execution failed: ${s.message}`):s}}};He($n,"instance");let Yc=$n;const gR=new Yc,{Text:sn}=le,{useToken:Eb}=he,yR="chat-session-sub-sessions-collapsed:",bR=3,xR=600,di=e=>{const t=(e||"").trim().toLowerCase();return t?t==="started"||t==="already_running"?"running":t==="success"||t==="done"?"completed":t==="canceled"?"cancelled":t==="queued"||t==="created"?"pending":t:"pending"},vR=(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")},Rb=e=>`${yR}${e}`,Wl=e=>{if(typeof window>"u")return!1;try{const t=window.localStorage.getItem(Rb(e));return t==="1"?!0:t==="0"?!1:null}catch{return null}},SR=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Rb(e),t?"1":"0")}catch{}},wR=({parentSessionId:e})=>{const{t}=ne(),{token:s}=Eb(),[n,o]=m.useState(()=>Wl(e)??!1),[a,i]=m.useState(null),[l,c]=m.useState(null),[d,u]=m.useState(null),h=N(S=>S.subSessionsByParent),p=N(S=>S.chats),g=N(S=>S.loadChatHistory),y=N(S=>S.refreshChats),f=N(S=>S.setSessionProcessing),v=N(S=>S.pinSession),b=N(S=>S.unpinSession),x=N(S=>S.deleteSession),_=N(S=>S.upsertSubSessionProgress),w=N(S=>S.clearSubSessionProgress),k=m.useMemo(()=>{const S=h[e]||{};return Object.entries(S).map(([L,$])=>({childSessionId:L,...$}))},[e,h]),C=m.useMemo(()=>p.filter(S=>S.kind==="child"&&S.parentSessionId===e).sort((S,L)=>{const $=Date.parse(S.updatedAt||"")||0;return(Date.parse(L.updatedAt||"")||0)-$}),[p,e]),E=m.useMemo(()=>{const S=new Map(k.map($=>[$.childSessionId,$])),L=[];for(const $ of C){const I=S.get($.id);L.push({childSessionId:$.id,title:(I==null?void 0:I.title)||$.title,status:di(vR($,I==null?void 0:I.status)),error:(I==null?void 0:I.error)||$.lastRunError,lastHeartbeatAt:I==null?void 0:I.lastHeartbeatAt,lastEventAt:I==null?void 0:I.lastEventAt,outputPreview:I==null?void 0:I.outputPreview,pinned:$.pinned,updatedAt:$.updatedAt,isRunning:$.isRunning,messageCount:$.messageCount,lastRunStatus:$.lastRunStatus,lastRunError:$.lastRunError}),S.delete($.id)}for(const $ of S.values())L.push({childSessionId:$.childSessionId,title:$.title,status:di($.status),error:$.error,lastHeartbeatAt:$.lastHeartbeatAt,lastEventAt:$.lastEventAt,outputPreview:$.outputPreview});return L},[C,k]);m.useEffect(()=>{o(Wl(e)??!1)},[e]),m.useEffect(()=>{Wl(e)===null&&o(E.length>bR)},[e,E.length]);const j=m.useCallback(()=>{o(S=>{const L=!S;return SR(e,L),L})},[e]),R=m.useCallback(S=>S instanceof Error&&S.message.trim()?S.message:"Failed to run child session",[]),M=m.useCallback(async(S,L="regenerate")=>{i(S),_(e,S,{status:"running",error:void 0,lastEventAt:new Date().toISOString()}),f(S,!0);try{const $=L==="error_retry"?"error_retry":"after_last_user",I=await Wn.truncateSessionMessages(S,{mode:$});(L==="regenerate"||(I.messages_removed??0)>0)&&await g(S,{mode:"replace"});const W=await Wn.execute(S);if(W.status==="started"||W.status==="already_running")return;if(W.status==="completed"){f(S,!1),_(e,S,{status:"completed",error:void 0,lastEventAt:new Date().toISOString()}),await y();return}throw new Error(`Execute failed: ${W.status}`)}catch($){f(S,!1),_(e,S,{status:"error",error:R($),lastEventAt:new Date().toISOString()})}finally{i($=>$===S?null:$)}},[g,e,y,f,R,_]),T=m.useCallback(async S=>{const L=typeof window<"u"?window.prompt.bind(window):null;if(!L)return;const $=L("Send a follow-up message to this child session:","Continue from where you left off.");if($===null)return;const I=$.trim();if(!I){_(e,S,{status:"error",error:"Follow-up message cannot be empty.",lastEventAt:new Date().toISOString()});return}c(S),_(e,S,{status:"running",error:void 0,lastEventAt:new Date().toISOString()}),f(S,!0);try{const W=await gR.executeTool({tool_name:"sub_session_manager",session_id:e,parameters:[{name:"action",value:"send_message"},{name:"child_session_id",value:S},{name:"message",value:I},{name:"auto_run",value:"true"}]});if(!W.success)throw new Error(W.result||"Follow-up failed");let A="running";try{JSON.parse(W.result).status==="pending"&&(A="pending")}catch{A="running"}_(e,S,{status:A,error:void 0,lastEventAt:new Date().toISOString()}),await y()}catch(W){f(S,!1),_(e,S,{status:"error",error:W instanceof Error&&W.message.trim()?W.message:"Failed to continue child session",lastEventAt:new Date().toISOString()})}finally{c(W=>W===S?null:W)}},[e,y,f,_]),P=m.useCallback(async S=>{u(S);try{await x(S),w(e,S)}finally{u(L=>L===S?null:L)}},[w,x,e]);return E.length===0?null:r.jsxs(ee,{size:"small",className:"lotus-settings-card",style:{marginBottom:s.marginMD},"data-testid":"sub-sessions-panel",title:r.jsxs(sn,{strong:!0,children:[t("chat.subSessions.title")," ",r.jsxs(sn,{type:"secondary",children:["(",E.length,")"]})]}),extra:r.jsx(Y,{type:"text",size:"small",icon:n?r.jsx(Wt,{}):r.jsx(ld,{}),onClick:j,"data-testid":"sub-sessions-toggle",children:t(n?"chat.subSessions.expand":"chat.subSessions.collapse")}),children:[n?r.jsx(sn,{type:"secondary","data-testid":"sub-sessions-collapsed-hint",children:t("chat.subSessions.hiddenHint",{count:E.length})}):r.jsx(G,{vertical:!0,gap:s.marginSM,"data-testid":"sub-sessions-list",style:{maxHeight:`${xR}px`,overflowY:"auto",paddingRight:s.paddingXS},children:E.map(S=>{const L=di(S.status),$=L==="running",I=a===S.childSessionId,W=l===S.childSessionId,A=d===S.childSessionId,O=I||W||A;return r.jsxs(G,{align:"flex-start",justify:"space-between",gap:s.marginSM,className:"lotus-settings-list-item",style:{padding:s.paddingSM,borderRadius:s.borderRadiusSM},children:[r.jsxs(G,{vertical:!0,style:{flex:1,minWidth:0},children:[r.jsxs(G,{align:"center",gap:s.marginXS,style:{minWidth:0},children:[r.jsx(sn,{strong:!0,ellipsis:!0,style:{minWidth:0},children:S.title||"Child Session"}),r.jsx(oe,{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}),S.pinned?r.jsx(oe,{color:"warning",style:{marginInlineEnd:0,flex:"0 0 auto"},children:"Pinned"}):null]}),r.jsxs(sn,{type:"secondary",style:{fontSize:12,marginTop:2},children:[S.childSessionId.slice(0,8),S.updatedAt?` • ${S.updatedAt}`:"",S.lastHeartbeatAt?` • heartbeat: ${S.lastHeartbeatAt}`:""]}),S.outputPreview?r.jsx(sn,{type:"secondary",style:{marginTop:s.marginXS,fontSize:13},ellipsis:!0,children:S.outputPreview}):null,S.error?r.jsx(sn,{type:"danger",style:{marginTop:s.marginXS},children:S.error}):null]}),r.jsxs(G,{gap:8,children:[r.jsx(Y,{size:"small",disabled:O,onClick:()=>{Yi(S.childSessionId),g(S.childSessionId)},children:t("chat.subSessions.open")}),r.jsx(Y,{size:"small",loading:W,disabled:A||I||$,"data-testid":`sub-session-continue-${S.childSessionId}`,onClick:()=>{T(S.childSessionId)},children:t("chat.subSessions.continue")}),r.jsx(zn,{trigger:["click"],menu:{items:[{key:"regenerate",label:t("chat.actions.regenerate")},{key:"error_retry",label:t("chat.actions.retryFailed")}],onClick:({key:D})=>{M(S.childSessionId,D)}},disabled:A||$||W,children:r.jsx(Y,{size:"small",loading:I,disabled:A||$||W,"data-testid":`sub-session-retry-${S.childSessionId}`,children:t("chat.subSessions.retry")})}),typeof S.pinned=="boolean"?r.jsx(Y,{size:"small",disabled:O,onClick:()=>{S.pinned?b(S.childSessionId):v(S.childSessionId)},children:S.pinned?t("chat.actions.unpin"):t("chat.actions.pin")}):null,r.jsx(Y,{danger:!0,size:"small",loading:A,disabled:I,"data-testid":`sub-session-delete-${S.childSessionId}`,onClick:()=>{P(S.childSessionId)},children:t("common.delete")})]})]},S.childSessionId)})}),!n&&E.length>1&&r.jsx(_R,{items:E})]})},_R=({items:e})=>{const{token:t}=Eb(),s=e.reduce((o,a)=>{const i=di(a.status);return i==="completed"?o.completed++:i==="running"?o.running++:i==="error"||i==="failed"?o.error++:o.pending++,o},{completed:0,running:0,error:0,pending:0}),n=[];return s.completed>0&&n.push(`${s.completed} completed`),s.running>0&&n.push(`${s.running} running`),s.pending>0&&n.push(`${s.pending} pending`),s.error>0&&n.push(`${s.error} failed`),n.length===0?null:r.jsx(sn,{type:"secondary",style:{fontSize:11,marginTop:t.marginXS,display:"block"},children:n.join(" · ")})},{useToken:TR}=he,kR=e=>{const t=e.replace(/\/$/,"").split("/").filter(Boolean);return t.length<=2?e:`~/${t.slice(-2).join("/")}`},jR=({sessionId:e})=>{const{t}=ne(),{token:s}=TR(),n=N(Xn(e)),o=N(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(G,{align:"center",gap:6,wrap:"wrap",className:"lotus-context-bar__content",children:[a&&r.jsx(ke,{title:a,children:r.jsx(oe,{className:"lotus-context-bar__tag",icon:r.jsx(hi,{}),bordered:!1,children:kR(a)})}),c>0&&r.jsx(ke,{title:t("chat.contextBar.fileRefsTooltip",{count:c,defaultValue:"{{count}} file reference(s) in this session"}),children:r.jsxs(oe,{className:"lotus-context-bar__tag",icon:r.jsx(Nx,{}),bordered:!1,children:[c," ",t("chat.contextBar.files","files")]})}),l&&r.jsx(ke,{title:t("chat.contextBar.promptTooltip",{name:l,defaultValue:"System prompt: {{name}}"}),children:r.jsx(oe,{className:"lotus-context-bar__tag",icon:r.jsx(Li,{}),bordered:!1,children:l})})]})})},CR=new Set(["Write","Edit","apply_patch","NotebookEdit"]),MR=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},PR=(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`},ER=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 g of e){const y=g.createdAt?new Date(g.createdAt).getTime():0;if(y>0&&(d===0||y<d)&&(d=y),y>u&&(u=y),g.isCompressed){a=!0,i++;continue}if(g.role==="user"&&!("type"in g&&g.type==="file_reference")&&t++,g.role==="assistant"){if("type"in g&&g.type==="tool_call"&&(n+=((h=g.toolCalls)==null?void 0:h.length)??0),"type"in g&&g.type==="tool_result"){const f=g;if(f.isError&&o++,CR.has(f.toolName)){const v=MR(((p=f.result)==null?void 0:p.result)??"");v&&c.add(v)}}if("type"in g&&g.type==="text"){s++;const f=g.content||"";f.length>0&&f.length>30&&(l=f.slice(0,300))}}}return{messageCount:e.length,userMessageCount:t,assistantMessageCount:s,toolCallCount:n,toolErrorCount:o,fileChanges:Array.from(c).slice(0,10),lastAssistantExcerpt:l,hasCompression:a,compressionCount:i,duration:d>0&&u>d?PR(d,u):""}},RR=({sessionId:e})=>{const{t}=ne(),{token:s}=he.useToken(),[n,o]=m.useState(!1),a=N(Xn(e)),i=a==null?void 0:a.messages,l=m.useMemo(()=>!i||i.length===0?null:ER(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(Bx,{})}),r.jsx("span",{className:"lotus-session-summary-header-title",style:{color:s.colorText},children:t("sessionSummary.title","Session Summary")}),!n&&r.jsxs("span",{className:"lotus-session-summary-stats",children:[r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(pi,{className:"lotus-session-summary-stat-icon"}),r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.messageCount})]}),l.toolCallCount>0&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(uu,{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(br,{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(Wt,{})})]}),n&&r.jsxs("div",{className:"lotus-session-summary-body",children:[r.jsxs("div",{className:"lotus-session-summary-stats",children:[r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(pi,{className:"lotus-session-summary-stat-icon"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.messageCount})," ",t("sessionSummary.messages","messages")]})]}),r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx("span",{className:"lotus-session-summary-stat-icon",children:"👤"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.userMessageCount})," ",t("sessionSummary.userTurns","user")]})]}),r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx("span",{className:"lotus-session-summary-stat-icon",children:"🤖"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.assistantMessageCount})," ",t("sessionSummary.assistantTurns","assistant")]})]}),l.toolCallCount>0&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(uu,{className:"lotus-session-summary-stat-icon"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolCallCount})," ",t("sessionSummary.toolCalls","tool calls")]})]}),l.toolErrorCount>0&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:"#ff4d4f"},children:[r.jsx(ua,{className:"lotus-session-summary-stat-icon"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolErrorCount})," ",t("sessionSummary.errors","errors")]})]}),l.duration&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(Ys,{className:"lotus-session-summary-stat-icon"}),r.jsx("span",{children:l.duration})]}),l.hasCompression&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(Li,{className:"lotus-session-summary-stat-icon"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.compressionCount})," ",t("sessionSummary.compressions","compressions")]})]})]}),c&&r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:11,fontWeight:600,color:s.colorTextSecondary,marginBottom:4,textTransform:"uppercase",letterSpacing:.3},children:t("sessionSummary.filesChanged","Files Changed")}),r.jsx("div",{className:"lotus-session-summary-files",children:l.fileChanges.map(u=>r.jsx(ke,{title:u,children:r.jsxs(oe,{bordered:!1,className:"lotus-session-summary-file-tag",children:[r.jsx(br,{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})]})]})]})},Ab="chat_scroll_anchors_v1";function AR(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 Ib(){try{const e=localStorage.getItem(Ab);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const s={};for(const[n,o]of Object.entries(t))AR(o)&&(s[n]=o);return s}catch{return{}}}function IR(e){try{localStorage.setItem(Ab,JSON.stringify(e))}catch(t){console.warn("[ScrollAnchor] Failed to write:",t)}}function $R(e){return Ib()[e]??null}function DR(e,t){const s=Ib();s[e]=t,IR(s)}const Ul=1,LR=3,OR=2e3;function FR(e,t){const s=Math.max(0,e.scrollHeight-e.clientHeight);return Math.min(Math.max(0,t),s)}function zR(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(),y=h.getBoundingClientRect().top-p.top,f=FR(t,t.scrollTop+(y-n));if(Math.abs(t.scrollTop-f)>Ul)t.scrollTop=f,l=0;else{const b=Number.isFinite(d)?Math.abs(f-d)<=Ul:!1,x=Math.abs(t.scrollTop-c)<=Ul;l=b&&x?l+1:0}d=f,c=t.scrollTop;const v=performance.now()-i>OR;if(l>=LR||v){a();return}requestAnimationFrame(u)};requestAnimationFrame(u)})}const NR=300,BR=.5;function WR(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 $b(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 Jh(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function UR(e,t){const s=Jh(e.createdAt);if(s!=null){let n=null,o=Number.POSITIVE_INFINITY;for(let a=0;a<t.length;a++){const i=Jh($b(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 nu(e){return Array.from(e.querySelectorAll("[data-chat-entry-id]"))}function qR(e,t){const s=nu(e);for(const n of s)if(n.dataset.chatEntryId===t)return n;return null}function HR(e,t){const s=nu(e);if(s.length===0)return null;const n=Math.max(0,Math.min(s.length-1,t));return s[n]??null}function YR(e){const t=nu(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 XR(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 y=s.current;if(!y)return;const f=()=>{d.current=!0};return y.addEventListener("wheel",f,{passive:!0}),y.addEventListener("touchmove",f,{passive:!0}),y.addEventListener("pointerdown",f),()=>{y.removeEventListener("wheel",f),y.removeEventListener("touchmove",f),y.removeEventListener("pointerdown",f)}},[s]);const u=m.useMemo(()=>{const y=new Map;for(let f=0;f<n.length;f++){const v=WR(n[f]);v&&y.set(v,f)}return y},[n]),h=m.useCallback(()=>{const y=s.current;if(!y||n.length===0)return null;const f=YR(y);if(!f)return null;const v=f.dataset.chatEntryId;if(!v)return null;const b=y.getBoundingClientRect(),x=f.getBoundingClientRect(),_=u.get(v),w=typeof _=="number"?n[_]:void 0;return{v:1,anchorId:v,offsetPx:x.top-b.top,ts:Date.now(),indexHint:_,createdAt:w?$b(w):void 0}},[u,s,n]),p=m.useCallback(y=>{if(a.current)return;const f=h();if(!f)return;const v=c.current;v&&v.anchorId===f.anchorId&&Math.abs(v.offsetPx-f.offsetPx)<=BR||(DR(y,f),c.current=f)},[h]),g=m.useCallback(y=>{if(!t||a.current)return;l.current&&clearTimeout(l.current);const f=t;l.current=setTimeout(()=>{p(f)},NR)},[t,p]);return m.useEffect(()=>{const y=t;return()=>{y&&(l.current&&(clearTimeout(l.current),l.current=null),p(y))}},[t,p]),m.useLayoutEffect(()=>{if(!t)return;const y=s.current;if(!y||n.length===0||o.current.has(t))return;const f=$R(t);if(!f){o.current.add(t);return}const v=u.get(f.anchorId),b=typeof v=="number"?v:UR(f,n);if(b==null){o.current.add(t);return}l.current&&(clearTimeout(l.current),l.current=null);const x=++i.current;a.current=!0,d.current=!1,y.style.overflowAnchor="none";const _=()=>i.current!==x||d.current;return zR({scrollEl:y,getAnchorElement:()=>qR(y,f.anchorId)??HR(y,b),offsetPx:f.offsetPx,isCancelled:_}).finally(()=>{i.current===x&&(a.current=!1,o.current.add(t),y.style.overflowAnchor="",p(t))}),()=>{i.current===x&&i.current++}},[t,u,n,n.length,s,p]),{handleScroll:g}}const Qh=2,Zh=6,VR=({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}=XR({currentSessionId:e,messagesListRef:s,renderableMessages:n}),h=m.useCallback(v=>{const b=s.current;if(!b)return;if(n.length===0){a(!1),l(!1);return}const x=b.scrollHeight-b.scrollTop-b.clientHeight,_=b.scrollTop,w=150,k=150,C=x<w,E=_<k;a(!C),l(!E&&n.length>3),x>w*2?c.current=!0:C&&(c.current=!1),u(v)},[s,n.length,u]),p=m.useCallback(()=>{if(!s.current||n.length===0)return;let b=0,x=-1;const _=()=>{const w=s.current;if(!w)return;const k=Math.max(0,w.scrollHeight-w.clientHeight),C=Math.max(0,w.scrollHeight-w.scrollTop-w.clientHeight),E=w.scrollHeight!==x,j=C>Qh||E||b===0;j&&w.scrollTo({top:k,behavior:b===0?"smooth":"auto"}),x=w.scrollHeight,b+=1,b<Zh&&j&&requestAnimationFrame(_)};requestAnimationFrame(_)},[s,n.length]),g=m.useCallback(()=>{if(!s.current)return;let b=0;const x=()=>{const _=s.current;if(!_)return;const w=_.scrollTop>Qh||b===0;w&&_.scrollTo({top:0,behavior:"auto"}),b+=1,b<Zh&&w&&requestAnimationFrame(x)};requestAnimationFrame(x)},[s]),y=m.useCallback(()=>{c.current=!1},[]);m.useEffect(()=>{const v=b=>{var M,T;const _=(M=b.detail)==null?void 0:M.messageId;if(!_){console.error("No messageId provided for navigation");return}const w=n.findIndex(P=>"message"in P&&P.message?P.message.id===_:"id"in P?P.id===_:!1);if(w===-1){console.warn("Message not found for navigation:",_);return}const k=n[w],C=k&&"message"in k?k.message.id:k&&"id"in k?k.id:_,E=document.getElementById(`message-${C}`),j=Array.from(((T=s.current)==null?void 0:T.querySelectorAll("[data-chat-entry-id]"))||[]),R=E||j.find(P=>P.dataset.chatEntryId===C);if(!R){console.warn("Message element not found for navigation:",_);return}R.scrollIntoView({behavior:"smooth",block:"center"}),R.classList.add("highlight-message"),setTimeout(()=>{R.classList.remove("highlight-message")},2e3)};return window.addEventListener("navigate-to-message",v),()=>{window.removeEventListener("navigate-to-message",v)}},[s,n]);const f=m.useRef(t.value);return m.useEffect(()=>{const v=t.value;f.current==="IDLE"&&v==="THINKING"&&(y(),p()),f.current=v},[t.value,y,p]),m.useEffect(()=>ze.subscribe(v=>{v.sessionId===e&&(c.current||v.content&&p())}),[e,p]),m.useEffect(()=>{!c.current&&n.length>0&&!d.current&&p(),d.current=!1},[n.length,p]),m.useEffect(()=>{if(!s.current){a(!1),l(!1);return}if(n.length===0){a(!1),l(!1);return}const b=()=>{const _=s.current;if(!_)return;const w=_.scrollHeight-_.scrollTop-_.clientHeight,k=_.scrollTop,C=150,E=150,j=w<C,R=k<E;a(!j),l(!R&&n.length>3)};b();let x=requestAnimationFrame(()=>{b(),x=requestAnimationFrame(b)});return()=>cancelAnimationFrame(x)},[s,n.length,e]),m.useEffect(()=>{d.current=!0,c.current=!1},[e]),{handleMessagesScroll:h,resetUserScroll:y,scrollToBottom:p,scrollToTop:g,showScrollToBottom:o,showScrollToTop:i}};function KR(e){return"type"in e&&e.type==="tool_session"}function GR(e){return"type"in e&&e.type==="compression_divider"}const ep=e=>{const t=Date.parse(e||"");return Number.isFinite(t)?t:Number.MAX_SAFE_INTEGER},JR=e=>"type"in e?e.createdAt:e.message.createdAt,QR=e=>!("type"in e)&&e.message.role==="system";function ZR(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_call"}function eA(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_result"}const tp=e=>(e??"").trim().toLowerCase()==="conclusion",tA=e=>{const t=(e??"").trim().toLowerCase();return t==="conclusion_with_options"||t==="exitplanmode"||t==="request_permissions"},sA=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"},nA=(e,t)=>{var s;return e.call.id||e.callMessageId||e.resultMessageId||((s=e.result)==null?void 0:s.id)||`tool-message-missing-${t}`},rA=(e,t)=>`tool-session-${nA(e,t)}:${sA(e)}`;function oA(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(ZR(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(tp(c.toolName)){n.add(u);return}if(tA(c.toolName)){n.add(u);const g={...i,id:`${i.id}:tool-call:${d}:${u}`,toolCalls:[{...c,toolCallId:u}]};t.push(g);return}const p={call:{...i,id:`${i.id}:tool-call:${d}:${u}`,toolCalls:[{...c,toolCallId:u}]},callMessageId:i.id};o(u,p),t.push([p])});continue}if(eA(i)){const l=i.toolCallId;if(l&&n.has(l)){n.delete(l),t.push(i);continue}if(tp(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 aA=(e,t)=>{var l;const{t:s}=ne(),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(GR(c))return{type:"compression_divider",id:c.id,createdAt:c.createdAt,label:c.label};if(KR(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(v=>{const b=v.role;return!(b!=="user"&&b!=="assistant"&&b!=="system"&&b!=="tool"||o(v))}),d=oA(c),u=[];d.forEach((v,b)=>{var w,k;if(Array.isArray(v)){const C=v[0];u.push({type:"tool_session",id:C?rA(C,b):`tool-session-unknown-${b}`,sessionId:(e==null?void 0:e.id)||"default",tools:v,createdAt:((w=C==null?void 0:C.call)==null?void 0:w.createdAt)||((k=C==null?void 0:C.result)==null?void 0:k.createdAt)||new Date().toISOString()});return}const x=v;let _;if(x.role==="assistant"&&"type"in x){const C="type"in x?x.type:void 0;(C==="text"||C==="plan"||C==="question"||C==="tool_call"||C==="tool_result")&&(_=C)}u.push({message:x,messageType:_})}),!c.some(v=>v.role==="system")&&n&&u.unshift({message:n});const p=((f=e==null?void 0:e.config)==null?void 0:f.compressionEvents)||[],g=u.findIndex(v=>!QR(v)),y=g===-1?u.length:g;for(const v of p){const b={type:"compression_divider",id:`compression-divider-${v.id}`,createdAt:v.createdAt,label:s("chat.compression.timelineDetail",{count:v.messagesCompressed,defaultValue:"{{count}} messages archived"})},x=ep(v.createdAt),_=u.findIndex((w,k)=>k>=y&&ep(JR(w))>x);_===-1?u.push(b):u.splice(_,0,b)}return u},[(l=e==null?void 0:e.config)==null?void 0:l.compressionEvents,e==null?void 0:e.id,t,o,n,s]);return{systemPromptMessage:n,renderableMessages:i,convertRenderableEntry:a}},{useToken:iA}=he,{useBreakpoint:lA}=$i,{Text:cA}=le,dA=e=>e.role==="user"?"You":e.role==="assistant"?"Assistant":e.role==="system"?"System":"Message",Db=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},uA=e=>e.map(({message:t,text:s},n)=>{const o=dA(t),a=Db(t.createdAt);return[`## ${n+1}. ${o} · ${a}`,"",s].join(`
|
|
241
|
+
`)}).join(`
|
|
242
|
+
|
|
243
|
+
---
|
|
244
|
+
|
|
245
|
+
`),mA=({sessionId:e,embedded:t=!1})=>{var fn,gn,Kn,Rr,ka;const{message:s}=Ot.useApp(),{t:n}=ne(),o=Mi(ae=>ae.isAdvanced),a=N(ae=>e??ae.currentSessionId),i=N(Xn(a)),l=N(ae=>ae.deleteMessage),c=N(ae=>ae.loadChatHistory),d=N(ae=>ae.processingChats),u=N(ae=>ae.tokenUsages),h=N(ae=>ae.truncationOccurred),p=N(ae=>ae.segmentsRemoved),g=m.useMemo(()=>(i==null?void 0:i.messages)||[],[i]),y=m.useMemo(()=>!a||!i?a:i.kind==="child"&&(i.parentSessionId||i.rootSessionId)||a,[i,a]),f=N(ae=>y?!!ae.taskLists[y]:!1),v=N(ae=>{if(!a)return!1;const Me=ae.subSessionsByParent[a];return Me&&Object.keys(Me).length>0?!0:ae.chats.some(Le=>Le.kind==="child"&&Le.parentSessionId===a)});m.useEffect(()=>{if(!a)return;const ae=N.getState().chats.find(Me=>Me.id===a);ae&&Array.isArray(ae.messages)&&ae.messages.length>0||c(a)},[a,c]);const b=(i==null?void 0:i.messageCount)??0,x=((fn=i==null?void 0:i.messages)==null?void 0:fn.length)??0;m.useEffect(()=>{if(!a)return;b-x>0&&c(a,{mode:"monotonic"})},[a,b,x,c]);const _=a?d.has(a):!1,w=m.useMemo(()=>{var Es;if(!g||g.length===0)return null;const ae=new Map;let Me=0,Le=0,Qe=0;for(const Rs of g){if(!zy(Rs))continue;const as=((Es=Rs.result)==null?void 0:Es.result)??"",ys=wa(as),As=Dc(as);if(!ys||!As)continue;Qe+=1,Me+=As.added,Le+=As.removed;const Is=ae.get(ys.file_path);Is?(Is.added+=As.added,Is.removed+=As.removed,Is.diffChunks.push(ys.diff.unified),Is.truncated=Is.truncated||!!ys.diff.truncated):ae.set(ys.file_path,{added:As.added,removed:As.removed,diffChunks:[ys.diff.unified],truncated:!!ys.diff.truncated})}if(ae.size===0)return null;const Mt=Array.from(ae.entries()).map(([Rs,as])=>({filePath:Rs,added:as.added,removed:as.removed,unifiedDiff:as.diffChunks.join(`
|
|
246
|
+
|
|
247
|
+
`),truncated:as.truncated})).sort((Rs,as)=>Rs.filePath.localeCompare(as.filePath));return{totalAdded:Me,totalRemoved:Le,files:Mt,changedTools:Qe}},[g]),k=m.useMemo(()=>{const ae=_?"THINKING":"IDLE";return{value:ae,context:{streamingContent:null,toolCallRequest:null,parsedParameters:null},matches:Me=>Me===ae}},[_]),C=m.useCallback(ae=>{if(ae.success)return null;switch(ae.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 ae.errorMessage||n("chat.messageActions.deleteFailed")}},[n]),E=m.useCallback(async(ae,Me)=>{if(!a){const Qe={success:!1,sessionId:"",messageId:ae,reason:"session_not_found"};return(Me==null?void 0:Me.notify)!==!1&&s.error(C(Qe)),Qe}const Le=await l(a,ae);return!Le.success&&(Me==null?void 0:Me.notify)!==!1&&s.error(C(Le)),Le},[a,l,s,C]),j=m.useCallback(async ae=>{const Me=Array.from(new Set(ae.map(Mt=>Mt.trim()).filter(Boolean)));if(Me.length===0)return;const Qe=(await Promise.all(Me.map(Mt=>E(Mt,{notify:!1})))).filter(Mt=>!Mt.success);if(Qe.length!==0){if(Qe.length===1){s.error(C(Qe[0]));return}s.error(n("chat.messageActions.deleteBatchFailed",{failed:Qe.length,total:Me.length}))}},[E,s,C,n]),R=m.useRef(null),{token:M}=iA(),T=lA(),P=md(),[S,L]=m.useState(null),[$,I]=m.useState(!1),[W,A]=m.useState(new Set),O=Ae(ae=>ae.sidebar.collapsed),D=()=>t||T.xs||T.sm?"100%":T.md?"90%":T.lg?"85%":"1024px",H=()=>{let ae;return t?ae=M.paddingSM:T.xs?ae=M.paddingXS:T.sm?ae=M.paddingSM:ae=M.padding,!t&&O&&!P?ae+18:ae};m.useEffect(()=>{L(null),I(!1),A(new Set)},[a]);const{systemPromptMessage:B,renderableMessages:K,convertRenderableEntry:F}=aA(i,g),z=g.length>0,de=!!(S!=null&&S.content),Te=!!B,$e=!!a&&(z||de),De=t&&!T.xs?190:0,be=m.useMemo(()=>{if(!(S!=null&&S.content))return K;const ae={message:{id:S.id,role:"user",content:S.content,createdAt:S.createdAt},messageType:"text"};return[...K,ae]},[K,S]),ye=m.useMemo(()=>{const ae=[];for(const Me of be){if(!("message"in Me))continue;const Le=Sb(Me.message).trim();Le&&ae.push({id:Me.message.id,message:Me.message,text:Le})}return ae},[be]),je=m.useMemo(()=>new Set(ye.map(ae=>ae.id)),[ye]);m.useEffect(()=>{A(ae=>{let Me=!1;const Le=new Set;for(const Qe of ae)je.has(Qe)?Le.add(Qe):Me=!0;return Me?Le:ae})},[je]);const Ue=m.useMemo(()=>ye.filter(ae=>W.has(ae.id)),[ye,W]),ht=ye.length>0,Ge=m.useCallback(ae=>{A(Me=>{const Le=new Set(Me);return Le.has(ae)?Le.delete(ae):Le.add(ae),Le})},[]),wt=m.useCallback(()=>{if(!ht){s.warning("No exportable messages");return}I(!0)},[s,ht]),U=m.useCallback(()=>{I(!1),A(new Set)},[]),_e=m.useCallback(()=>{if($){U();return}wt()},[wt,U,$]),Ce=m.useCallback(()=>{A(new Set(ye.map(ae=>ae.id)))},[ye]),Ve=m.useCallback(()=>{A(new Set)},[]),qe=m.useCallback(async ae=>{var Qe;if(!a){s.warning("No active chat");return}if(Ue.length===0){s.warning("Please select at least one message");return}const Me=uA(Ue),Le=await wb.exportMessageText({format:ae,content:Me,sessionId:a,filenamePrefix:`chat-messages-${Ue.length}`});if(Le.success){s.success(`Saved: ${Le.filename}`);return}(Qe=Le.error)!=null&&Qe.toLowerCase().includes("cancel")||s.error(Le.error||"Export failed")},[s,a,Ue]);m.useEffect(()=>{if(typeof window>"u")return;const ae=Me=>{var Mt;const Qe=((Mt=Me.detail)==null?void 0:Mt.sessionId)??null;!a||Qe!==a||_e()};return window.addEventListener(Nc,ae),()=>{window.removeEventListener(Nc,ae)}},[a,_e]);const J=a?u[a]:null,re=(gn=i==null?void 0:i.config)==null?void 0:gn.tokenUsage,V=J||re||null,Q=a?h[a]:!1,se=(Kn=i==null?void 0:i.config)==null?void 0:Kn.truncationOccurred,ce=Q||se||!1,Ie=a?p[a]:0,Je=(Rr=i==null?void 0:i.config)==null?void 0:Rr.segmentsRemoved,_t=Ie||Je||0,jt=m.useMemo(()=>{var Me;const ae=(Me=i==null?void 0:i.config)==null?void 0:Me.compressionEvents;return!ae||ae.length===0?null:ae.reduce((Le,Qe)=>{const Mt=Date.parse(Le.createdAt),Es=Date.parse(Qe.createdAt);return Number.isFinite(Mt)?Number.isFinite(Es)&&Es>Mt?Qe:Le:Qe})},[(ka=i==null?void 0:i.config)==null?void 0:ka.compressionEvents]),Ct=M.marginMD,{handleMessagesScroll:Tt,resetUserScroll:hn,scrollToBottom:Vs,scrollToTop:Pr,showScrollToBottom:Vn,showScrollToTop:Ks}=VR({currentSessionId:a,interactionState:k,messagesListRef:R,renderableMessages:be}),Er=()=>T.xs?16:32,Ps=!!$e&&ht&&(!t||$),Ut=jt?r.jsx(ke,{title:n("chat.compression.tooltip",{count:jt.messagesCompressed,time:Db(jt.createdAt),defaultValue:"Latest compression at {{time}}: {{count}} messages archived"}),children:r.jsx(oe,{color:"gold",icon:r.jsx(_f,{}),style:{marginInlineEnd:0,whiteSpace:"nowrap"},children:n("chat.compression.archivedShort",{count:jt.messagesCompressed,defaultValue:"{{count}} archived"})})}):null,pn=V&&V.budgetLimit>0?r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:M.marginXS},children:[r.jsx(fR,{usage:V,showDetails:!0,size:"small"}),ce&&r.jsxs("span",{style:{fontSize:11,color:M.colorTextSecondary,whiteSpace:"nowrap"},children:["(",_t," truncated)"]}),Ut]}):Ut?r.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:M.marginXS},children:Ut}):null;return r.jsx(Dn,{role:"region","aria-label":n("chat.view.chatRegion","Chat conversation"),style:{flex:1,minHeight:0,height:"100%",background:M.colorBgContainer,position:"relative",overflow:"hidden"},children:r.jsxs(G,{vertical:!0,style:{flex:1,minHeight:0,height:"100%"},children:[a&&r.jsx(jR,{sessionId:a}),o&&a&&$e&&r.jsx("div",{style:{paddingTop:M.paddingXS,paddingRight:H(),paddingBottom:0,paddingLeft:H(),maxWidth:D(),margin:"0 auto",width:"100%"},children:r.jsx(RR,{sessionId:a})}),a&&f&&r.jsx("div",{style:{paddingTop:H(),paddingRight:H(),paddingBottom:0,paddingLeft:H(),maxWidth:D(),margin:"0 auto",width:"100%"},children:r.jsx(Z1,{sessionId:a,initialCollapsed:!0})}),a&&v&&r.jsx("div",{style:{paddingTop:M.paddingXS,paddingRight:H(),paddingBottom:0,paddingLeft:H(),maxWidth:D(),margin:"0 auto",width:"100%"},children:r.jsx(wR,{parentSessionId:a})}),Ps&&r.jsx("div",{style:{paddingTop:M.paddingXS,paddingRight:H()+De,paddingBottom:0,paddingLeft:H(),maxWidth:D(),margin:"0 auto",width:"100%"},children:$?r.jsxs(G,{align:"center",justify:"space-between",wrap:"wrap",gap:M.marginXS,children:[r.jsx(cA,{type:"secondary",children:n("chat.selectionToolbar.selectedCount",{selected:Ue.length,total:ye.length})}),r.jsxs(X,{size:M.marginXS,wrap:!0,children:[r.jsx(Y,{size:"small",onClick:Ce,children:n("chat.selectionToolbar.selectAll")}),r.jsx(Y,{size:"small",onClick:Ve,children:n("chat.selectionToolbar.clear")}),r.jsx(Y,{size:"small",icon:r.jsx(yr,{}),onClick:()=>{qe("markdown")},disabled:Ue.length===0,children:n("chat.selectionToolbar.exportMarkdown")}),r.jsx(Y,{size:"small",type:"primary",icon:r.jsx(yr,{}),onClick:()=>{qe("pdf")},disabled:Ue.length===0,children:n("chat.selectionToolbar.exportPdf")}),r.jsx(Y,{size:"small",icon:r.jsx(wr,{}),onClick:_e,children:n("chat.selectionToolbar.done")})]})]}):r.jsx(G,{justify:"flex-end",children:r.jsx(ke,{title:n("chat.selectionToolbar.selectMessages"),children:r.jsx(Y,{"aria-label":n("chat.selectionToolbar.selectMessages"),icon:r.jsx(Tf,{}),size:"small",onClick:_e})})})}),r.jsx(J1,{currentChat:i,currentSessionId:a,convertRenderableEntry:F,handleDeleteMessage:E,handleDeleteToolMessages:j,handleMessagesScroll:Tt,hasSystemPrompt:Te,messagesListRef:R,renderableMessages:be,rowGap:Ct,showMessagesView:!!$e,screens:T,workflowDraftId:S==null?void 0:S.id,interactionState:k,padding:H(),selectionMode:$,selectedMessageIds:W,selectableMessageIds:je,onToggleMessageSelection:Ge}),(Ks||Vn)&&r.jsxs("div",{style:{position:"absolute",right:Er(),bottom:T.xs?160:180,display:"flex",flexDirection:"column",gap:M.marginXS,zIndex:1e3},children:[Ks&&r.jsx(mu,{type:"default",icon:r.jsx(ld,{}),style:{position:"relative",inset:"unset"},onClick:()=>{Pr()}}),Vn&&r.jsx(mu,{type:"primary",icon:r.jsx(Wt,{}),style:{position:"relative",inset:"unset"},onClick:()=>{hn(),Vs()}})]}),a&&r.jsx("div",{style:{paddingTop:M.paddingXS,paddingRight:H(),paddingBottom:0,paddingLeft:H(),maxWidth:D(),margin:"0 auto",width:"100%"},children:r.jsx(hR,{sessionId:a})}),r.jsx(EC,{sessionId:a,isCenteredLayout:!$e,maxWidth:$e?D():"100%",onWorkflowDraftChange:L,showMessagesView:!!$e,sessionDiffSummary:w,contextUsageIndicator:pn})]})})},hA=5,pA=5,fA=5,gA=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""}},yA=e=>e.isRunning?"is-running":e.lastRunStatus==="error"?"is-error":e.pinned?"is-pinned":"is-idle",ql=({chat:e,onOpen:t,textSecondary:s})=>{const n=e.config.workspacePath?e.config.workspacePath.split("/").pop()||e.config.workspacePath:null;return r.jsxs("button",{type:"button",className:"lotus-home-session-item",onClick:()=>t(e.id),children:[r.jsx("span",{className:`lotus-home-session-status ${yA(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:gA(e.updatedAt)}),n?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"lotus-home-session-meta-sep"}),r.jsxs("span",{children:[r.jsx(hi,{style:{marginRight:3}}),n]})]}):null,e.messageCount!=null?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"lotus-home-session-meta-sep"}),r.jsxs("span",{children:[r.jsx(pi,{style:{marginRight:3}}),e.messageCount]})]}):null]})]}),e.isRunning?r.jsx(oe,{color:"green",bordered:!1,style:{margin:0,fontSize:11},children:"Running"}):null,r.jsx(Ws,{className:"lotus-home-session-arrow"})]})},bA=({onOpenSession:e})=>{const{t}=ne(),{token:s}=he.useToken(),n=N(d=>d.chats),o=N(d=>d.processingChats),a=m.useMemo(()=>n.filter(d=>d.isRunning||o.has(d.id)).slice(0,pA),[n,o]),i=m.useMemo(()=>n.filter(d=>d.pinned&&!d.isRunning).slice(0,fA),[n]),l=m.useMemo(()=>{const d=new Set(a.map(h=>h.id)),u=new Set(i.map(h=>h.id));return n.filter(h=>h.kind!=="child"&&!d.has(h.id)&&!u.has(h.id)).sort((h,p)=>{const g=h.updatedAt?new Date(h.updatedAt).getTime():h.createdAt;return(p.updatedAt?new Date(p.updatedAt).getTime():p.createdAt)-g}).slice(0,hA)},[n,a,i]),c=m.useCallback(d=>{e(d)},[e]);return r.jsx("div",{className:"lotus-home-dashboard",children:r.jsxs("div",{className:"lotus-home-dashboard-inner",children:[r.jsxs("div",{className:"lotus-home-header",children:[r.jsx("span",{className:"lotus-home-header-icon",style:{background:`${s.colorPrimary}15`,color:s.colorPrimary},children:r.jsx(Wx,{})}),r.jsxs("div",{className:"lotus-home-header-text",children:[r.jsx("h2",{style:{color:s.colorText},children:t("home.title","Welcome to Bodhi")}),r.jsx("p",{style:{color:s.colorTextSecondary},children:t("home.subtitle","Here's an overview of your workspace.")})]})]}),r.jsx("div",{className:"lotus-home-launcher-shell","data-tour-id":"task-templates",children:r.jsx(qy,{embedded:!0,layoutMode:"staggered"})}),r.jsxs("div",{className:"lotus-home-secondary-sections",children:[a.length>0?r.jsxs("div",{className:"lotus-home-section",children:[r.jsxs("div",{className:"lotus-home-section-title",style:{color:s.colorTextSecondary},children:[r.jsx(wf,{className:"lotus-home-section-icon",style:{color:"#52c41a"}}),r.jsx("span",{children:t("home.sections.running","Running Now")})]}),r.jsx("div",{className:"lotus-home-session-list",children:a.map(d=>r.jsx(ql,{chat:d,onOpen:c,textSecondary:s.colorTextTertiary},d.id))})]}):null,i.length>0?r.jsxs("div",{className:"lotus-home-section",children:[r.jsxs("div",{className:"lotus-home-section-title",style:{color:s.colorTextSecondary},children:[r.jsx(sd,{className:"lotus-home-section-icon",style:{color:"#faad14"}}),r.jsx("span",{children:t("home.sections.pinned","Pinned")})]}),r.jsx("div",{className:"lotus-home-session-list",children:i.map(d=>r.jsx(ql,{chat:d,onOpen:c,textSecondary:s.colorTextTertiary},d.id))})]}):null,l.length>0?r.jsxs("div",{className:"lotus-home-section",children:[r.jsxs("div",{className:"lotus-home-section-title",style:{color:s.colorTextSecondary},children:[r.jsx(Ys,{className:"lotus-home-section-icon"}),r.jsx("span",{children:t("home.sections.recent","Recent Sessions")})]}),r.jsx("div",{className:"lotus-home-session-list",children:l.map(d=>r.jsx(ql,{chat:d,onOpen:c,textSecondary:s.colorTextTertiary},d.id))})]}):null,n.length===0?r.jsx("div",{className:"lotus-home-empty-hint",style:{color:s.colorTextTertiary},children:t("home.empty","No sessions yet. Create one to get started!")}):null]})]})})},tn=(e,t,s)=>Math.max(t,Math.min(s,e)),Xa=(e,t)=>t==="horizontal"?e.clientWidth:e.clientHeight,Va=(e,t,s)=>{const n=Math.max(0,Math.round(e)),o=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(s));return o+a>n?{minFirst:0,maxFirst:n,appliedMinFirst:0,appliedMinSecond:0}:{minFirst:o,maxFirst:n-a,appliedMinFirst:o,appliedMinSecond:a}},Lb=({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),g=m.useRef(null),[y,f]=m.useState(null),[v,b]=m.useState(0),[x,_]=m.useState(null),w=m.useMemo(()=>{if(!n)return null;const D=Number(n[0]);return Number.isFinite(D)?D:null},[n]),k=m.useMemo(()=>{if(!n)return null;const D=Number(n[0]),H=Number(n[1]);if(!Number.isFinite(D)||!Number.isFinite(H))return null;const B=D+H;return B<=0||H<=0?null:tn(D/B,0,1)},[n]);m.useLayoutEffect(()=>{const D=p.current;D&&b(Xa(D,e))},[e]),m.useEffect(()=>{const D=p.current;if(!D)return;const H=()=>{const B=Xa(D,e);b(K=>K===B?K:B)};if(H(),typeof ResizeObserver<"u"){const B=new ResizeObserver(H);return B.observe(D),()=>B.disconnect()}return window.addEventListener("resize",H),()=>window.removeEventListener("resize",H)},[e]),m.useEffect(()=>{if(k!==null){_(k);return}_(D=>D??tn(o,.1,.9))},[o,k]);const C=m.useMemo(()=>Va(v,a,i),[v,a,i]),E=tn(o,.1,.9),j=x??E,R=v>0?Math.round(v*j):null,M=y??(k!==null?R:null)??w??R??0,T=v>0?tn(M,C.minFirst,C.maxFirst):Math.max(0,Math.round(M)),P=m.useCallback(D=>{if(c)return;const H=p.current;if(!H)return;D.preventDefault(),D.stopPropagation();const B=e==="horizontal"?D.clientX:D.clientY,K=Xa(H,e),F=Va(K,a,i),z=tn(T||Math.round(K*E),F.minFirst,F.maxFirst);g.current={pointerId:D.pointerId,startPos:B,startFirstPx:z,containerSize:K};try{D.currentTarget.setPointerCapture(D.pointerId)}catch{}},[c,T,E,e,a,i]),S=m.useCallback(D=>{const H=g.current;if(!H||D.pointerId!==H.pointerId)return;D.preventDefault(),D.stopPropagation();const K=(e==="horizontal"?D.clientX:D.clientY)-H.startPos,F=H.containerSize,z=Va(F,a,i),de=tn(Math.round(H.startFirstPx+K),z.minFirst,z.maxFirst);f(de)},[e,a,i]),L=m.useCallback(D=>{const H=g.current;if(!H||H.pointerId!==D)return;const B=p.current,K=B?Xa(B,e):H.containerSize,F=y??H.startFirstPx,z=Va(K,a,i),de=tn(F,z.minFirst,z.maxFirst),Te=Math.max(0,K-de);f(null),K>0&&_(tn(de/K,0,1)),g.current=null,d==null||d([de,Te])},[e,y,a,i,d]),$=m.useCallback(D=>{D.preventDefault(),D.stopPropagation(),L(D.pointerId)},[L]),I=m.useCallback(D=>{D.preventDefault(),D.stopPropagation(),L(D.pointerId)},[L]),W=e==="horizontal",A=c?"default":W?"col-resize":"row-resize",O=Math.max(0,Math.round(l));return r.jsxs("div",{ref:p,className:h,style:{display:"flex",flexDirection:W?"row":"column",height:"100%",minHeight:0,minWidth:0,width:"100%",position:"relative",...u},children:[r.jsx("div",{style:{flex:`0 0 ${T}px`,minWidth:W?C.appliedMinFirst:0,minHeight:W?0:C.appliedMinFirst,overflow:"hidden",display:"flex"},children:r.jsx("div",{style:{flex:1,minHeight:0,minWidth:0},children:t})}),r.jsx("div",{style:{flex:"1 1 auto",minWidth:W?C.appliedMinSecond:0,minHeight:W?0:C.appliedMinSecond,overflow:"hidden",display:"flex"},children:r.jsx("div",{style:{flex:1,minHeight:0,minWidth:0},children:s})}),O>0?r.jsx("div",{role:"separator","aria-orientation":W?"vertical":"horizontal",onPointerDown:P,onPointerMove:S,onPointerUp:$,onPointerCancel:I,style:{position:"absolute",top:W?0:`${T-O/2}px`,left:W?`${T-O/2}px`:0,width:W?`${O}px`:"100%",height:W?"100%":`${O}px`,cursor:A,touchAction:"none",background:"transparent",zIndex:5}}):null]})},{useToken:xA}=he,vA=4,SA=({leafId:e})=>{const{token:t}=xA(),{t:s}=ne(),n=Ae(R=>R.tree),o=Ae(R=>R.leafSessionIds),a=Ae(R=>R.activeLeafId),i=Ae(R=>R.setActiveLeafId),l=Ae(R=>R.splitLeaf),c=Ae(R=>R.closeLeaf),d=Ae(R=>R.setLeafSessionId),u=N(R=>R.selectSession),h=N(R=>R.addChat),p=N(R=>R.systemPrompts),g=N(R=>R.lastSelectedPromptId),y=o[e]??null,f=m.useMemo(()=>Bt(n).length,[n]),v=f<vA,b=Cf("(max-width: 768px)"),x=f>1,w=x||!!y,k=f>1,C=a===e,E=m.useCallback(R=>{d(e,R),i(e),u(R)},[e,u,i,d]),j=m.useCallback(async()=>{var P,S;const R=p.find(L=>L.id===g),M=(R==null?void 0:R.id)||(p.length>0?((P=p.find(L=>L.id==="general_assistant"))==null?void 0:P.id)||p[0].id:""),T=await h({title:s("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:M,baseSystemPrompt:(R==null?void 0:R.content)||(p.length>0?((S=p.find(L=>L.id==="general_assistant"))==null?void 0:S.content)||p[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null});d(e,T),i(e)},[h,g,p,s,e,d,i]);return r.jsxs("div",{className:"chat-pane-shell",onMouseDownCapture:()=>{Jt("pane focus (mouse)",{leafId:e,sessionId:y,prevActiveLeafId:a}),i(e),y&&u(y)},onFocusCapture:()=>{Jt("pane focus (focus)",{leafId:e,sessionId:y,prevActiveLeafId:a}),i(e)},style:{height:"100%",minHeight:0,border:k?`1px solid ${C?t.colorPrimaryBorder:t.colorBorderSecondary}`:"none",borderRadius:k?t.borderRadiusLG:0,overflow:"hidden",background:t.colorBgContainer,position:"relative"},children:[!b&&r.jsx("div",{className:"chat-pane-actions",style:{background:t.colorBgElevated,border:`1px solid ${t.colorBorderSecondary}`,borderRadius:10,padding:"2px 4px"},children:r.jsxs(G,{gap:t.marginXS,children:[r.jsx(Y,{size:"small",type:"text",icon:r.jsx(Ux,{}),disabled:!v,title:s("chat.multiPane.splitHorizontal"),"aria-label":s("chat.multiPane.splitHorizontal"),onClick:R=>{R.preventDefault(),R.stopPropagation(),Jt("pane split request",{leafId:e,layout:"horizontal"}),l(e,"horizontal");const M=Ae.getState(),T=M.leafSessionIds[M.activeLeafId]??null;T&&u(T)}}),r.jsx(Y,{size:"small",type:"text",icon:r.jsx(qx,{}),disabled:!v,title:s("chat.multiPane.splitVertical"),"aria-label":s("chat.multiPane.splitVertical"),onClick:R=>{R.preventDefault(),R.stopPropagation(),Jt("pane split request",{leafId:e,layout:"vertical"}),l(e,"vertical");const M=Ae.getState(),T=M.leafSessionIds[M.activeLeafId]??null;T&&u(T)}}),r.jsx(Y,{size:"small",type:"text",icon:r.jsx(Tf,{}),disabled:!y,title:s("chat.multiPane.selectMessagesToExport"),"aria-label":s("chat.multiPane.selectMessagesToExport"),onClick:R=>{R.preventDefault(),R.stopPropagation(),y&&window.dispatchEvent(new CustomEvent(Nc,{detail:{sessionId:y}}))}}),r.jsx(Y,{size:"small",type:"text",danger:!0,icon:r.jsx(wr,{}),disabled:!w,title:s("chat.multiPane.closePane"),"aria-label":s("chat.multiPane.closePane"),onClick:R=>{R.preventDefault(),R.stopPropagation(),Jt("pane close request",{leafId:e}),x?c(e):d(e,null);const M=Ae.getState(),T=M.leafSessionIds[M.activeLeafId]??null;u(T)}})]})}),y?r.jsx(ia,{name:"ChatView",children:r.jsx(mA,{sessionId:y,embedded:!0})}):r.jsx(ia,{name:"HomeDashboard",children:r.jsx(bA,{onOpenSession:E,onCreateSession:j})})]})},wA=({node:e})=>{const t=Ae(n=>n.splitSizesPx[e.id]??null),s=Ae(n=>n.setSplitSizesPx);return r.jsx(Lb,{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(Xc,{node:e.children[0]}),second:r.jsx(Xc,{node:e.children[1]})})},Xc=({node:e})=>e.type==="leaf"?r.jsx(SA,{leafId:e.id}):r.jsx(wA,{node:e}),sp=()=>{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=N(h=>h.chats),l=N(h=>h.currentSessionId),c=m.useRef(!1),d=m.useMemo(()=>Bt(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(Xc,{node:e})})},_A=[{id:"settings-provider",tabKey:"provider",titleKey:"commandPalette.actions.openProviderSettings",fallbackTitle:"Open Provider Settings",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"AI",keywords:["api","key","openai","anthropic","gemini","model"]},{id:"settings-model-limits",tabKey:"model-limits",titleKey:"commandPalette.actions.openModelLimits",fallbackTitle:"Open Model Limits",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"AI",keywords:["token","context","window","budget","limit"]},{id:"settings-prompts",tabKey:"prompts",titleKey:"commandPalette.actions.openPrompts",fallbackTitle:"Open System Prompts",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"AI",keywords:["system","prompt","persona","instruction"]},{id:"settings-skills",tabKey:"skills",titleKey:"commandPalette.actions.openSkills",fallbackTitle:"Open Skills",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"Tools",keywords:["skill","capability","plugin"]},{id:"settings-mcp",tabKey:"mcp",titleKey:"commandPalette.actions.openMcpSettings",fallbackTitle:"Open MCP Settings",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"Tools",keywords:["mcp","server","tool","external"]},{id:"settings-workflows",tabKey:"workflows",titleKey:"commandPalette.actions.openWorkflowSettings",fallbackTitle:"Open Workflow Settings",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"Tools",keywords:["workflow","automation","template"]},{id:"settings-hooks",tabKey:"hooks",titleKey:"commandPalette.actions.openHooks",fallbackTitle:"Open Hooks",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"Tools",keywords:["hook","event","trigger","callback"]},{id:"settings-schedules",tabKey:"schedules",titleKey:"commandPalette.actions.openSchedulesSettings",fallbackTitle:"Open Schedules",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"Ops",keywords:["schedule","cron","recurring","timer","automated"]},{id:"settings-sessions",tabKey:"sessions",titleKey:"commandPalette.actions.openSessionsSettings",fallbackTitle:"Open Session Monitor",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"Monitor",keywords:["session","monitor","cleanup","history"]},{id:"settings-metrics",tabKey:"metrics",titleKey:"commandPalette.actions.openMetrics",fallbackTitle:"Open Metrics Dashboard",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"Monitor",keywords:["metrics","dashboard","analytics","usage","stats"]},{id:"settings-masking",tabKey:"masking",titleKey:"commandPalette.actions.openMasking",fallbackTitle:"Open Keyword Masking",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"Security & privacy",badge:"Security",keywords:["mask","redact","privacy","keyword","sensitive"]},{id:"settings-env",tabKey:"env-vars",titleKey:"commandPalette.actions.openEnvVars",fallbackTitle:"Open Environment Variables",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"System",keywords:["env","environment","variable","config"]},{id:"settings-config",tabKey:"config",titleKey:"commandPalette.actions.openConfig",fallbackTitle:"Open Configuration",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"System",keywords:["config","json","bamboo","data","path"]},{id:"settings-app",tabKey:"app",titleKey:"commandPalette.actions.openAppSettings",fallbackTitle:"Open App Settings",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"System",keywords:["app","application","reset","theme","language"]}],TA=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)},kA=(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(" • ")},jA=(e,t)=>{const s=t.trim().toLowerCase();return s?e.filter(n=>[n.title,n.subtitle||"",...n.keywords].join(" ").toLowerCase().includes(s)):e},CA=e=>{if(!(e instanceof HTMLElement))return!1;const t=e.tagName.toLowerCase();return e.isContentEditable?!0:t==="input"||t==="textarea"||t==="select"},MA=()=>{const{t:e}=ne(),{token:t}=he.useToken(),s=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{message:n}=Ot.useApp(),o=N(P=>P.chats),a=N(P=>P.addChat),i=N(P=>P.lastSelectedPromptId),l=N(P=>P.systemPrompts),[c,d]=m.useState(!1),[u,h]=m.useState(""),[p,g]=m.useState(0),y=m.useRef(null),f=m.useRef(null),v=Bs(P=>P.open),b=qn(P=>P.toggleTheme),x=qn(P=>P.themeMode),_=Ae(P=>P.sidebar.collapsed),w=Ae(P=>P.setSidebarCollapsed),k=Mi(P=>P.mode),C=Mi(P=>P.toggleMode),E=m.useCallback(async()=>{var A,O;const P=l.find(D=>D.id===i),S=(P==null?void 0:P.id)||(l.length>0?((A=l.find(D=>D.id==="general_assistant"))==null?void 0:A.id)||l[0].id:""),L=await a({title:e("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:S,baseSystemPrompt:(P==null?void 0:P.content)||(l.length>0?((O=l.find(D=>D.id==="general_assistant"))==null?void 0:O.content)||l[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null}),{activeLeafId:$,setLeafSessionId:I,setActiveLeafId:W}=Ae.getState();I($,L),W($)},[a,i,l,e]),j=m.useMemo(()=>{const P=_A.filter(S=>!(k==="simple"&&Fy.has(S.tabKey))).map(S=>({id:S.id,kind:"action",title:e(S.titleKey,S.fallbackTitle),subtitle:e(S.subtitleKey||"commandPalette.groups.settings",S.fallbackSubtitle||"System settings"),keywords:[S.tabKey,S.badge||"","settings","config",...S.keywords||[]],icon:r.jsx(da,{}),badge:S.badge,onSelect:()=>{v("chat",S.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(Us,{}),badge:e("commandPalette.badges.quickAction","Action"),onSelect:async()=>{await E()}},{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(Hx,{}),badge:x==="dark"?"☀️":"🌙",onSelect:()=>{b()}},{id:"toggle-sidebar",kind:"action",title:_?e("commandPalette.actions.showSidebar","Show Sidebar"):e("commandPalette.actions.hideSidebar","Hide Sidebar"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["sidebar","toggle","hide","show","panel","menu"],icon:_?r.jsx(kf,{}):r.jsx(gf,{}),badge:"Layout",onSelect:()=>{w(!_)}},{id:"split-pane",kind:"action",title:e("commandPalette.actions.splitPane","Split Pane"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["split","pane","multi","dual","side","layout"],icon:r.jsx(Yx,{}),badge:"Layout",onSelect:()=>{const{tree:S,activeLeafId:L,splitLeaf:$}=Ae.getState();Bt(S).length<4&&$(L,"vertical")}},...P,{id:"toggle-experience-mode",kind:"action",title:k==="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(xf,{}),badge:k==="simple"?"Simple":"Advanced",onSelect:()=>{C()}}]},[E,v,b,x,_,w,k,C,e]),R=m.useMemo(()=>o.map(P=>({id:`session-${P.id}`,kind:"session",title:P.title,subtitle:kA(P,e("commandPalette.badges.childSession","Child session"),e("commandPalette.badges.rootSession","Session")),keywords:TA(P),icon:r.jsx(pi,{}),badge:P.pinned?e("commandPalette.badges.pinned","Pinned"):P.isRunning?e("commandPalette.badges.running","Running"):P.kind==="child"?e("commandPalette.badges.child","Child"):void 0,onSelect:()=>{Yi(P.id)}})),[o,e]),M=m.useMemo(()=>[...j,...R],[j,R]),T=m.useMemo(()=>jA(M,u).slice(0,40),[M,u]);return m.useEffect(()=>{g(P=>T.length===0?0:Math.min(P,T.length-1))},[T.length]),m.useEffect(()=>{if(!c)return;const P=window.setTimeout(()=>{var S,L;(S=y.current)==null||S.focus(),(L=y.current)==null||L.select()},0);return()=>window.clearTimeout(P)},[c]),m.useEffect(()=>{if(typeof window>"u")return;const P=S=>{if((S.metaKey||S.ctrlKey)&&S.key.toLowerCase()==="k"){S.preventDefault(),d($=>!$);return}if(c){if(S.key==="Escape"){S.preventDefault(),d(!1);return}if(!(CA(S.target)&&S.key!=="ArrowUp"&&S.key!=="ArrowDown"&&S.key!=="Enter")){if(S.key==="ArrowDown"){S.preventDefault(),g($=>T.length===0?0:($+1)%T.length);return}if(S.key==="ArrowUp"){S.preventDefault(),g($=>T.length===0?0:$===0?T.length-1:$-1);return}if(S.key==="Enter"){const $=T[p];if(!$)return;S.preventDefault(),(async()=>{try{await $.onSelect(),d(!1),h("")}catch(I){console.error("[CommandPalette] action failed",I),n.error(I instanceof Error?I.message:e("commandPalette.errors.actionFailed","Command failed"))}})()}}}};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[T,n,c,p,e]),m.useEffect(()=>{c||(h(""),g(0))},[c]),m.useEffect(()=>{const P=f.current;if(!P)return;const S=P.querySelector(`[data-command-index="${p}"]`);S==null||S.scrollIntoView({block:"nearest"})},[p]),r.jsx(Lt,{open:c,onCancel:()=>d(!1),footer:null,centered:!0,width:680,destroyOnClose:!0,className:"lotus-command-palette-modal",title:null,closable:!1,styles:{content:{padding:12,borderRadius:t.borderRadiusLG,overflow:"hidden",background:t.colorBgElevated,backdropFilter:s?"none":"blur(18px)",WebkitBackdropFilter:s?"none":"blur(18px)"},body:{padding:0},mask:{backdropFilter:s?"none":"blur(6px)",WebkitBackdropFilter:s?"none":"blur(6px)"}},children:r.jsxs("div",{className:"lotus-command-palette-shell",children:[r.jsxs("div",{className:"lotus-command-palette-search",children:[r.jsx(sa,{style:{color:t.colorTextTertiary,fontSize:16}}),r.jsx(me,{ref:y,value:u,onChange:P=>h(P.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(Ys,{}),r.jsx("span",{children:e("commandPalette.navigationHint","Use ↑↓ to navigate, Enter to open, and Esc to close.")})]}),r.jsx("div",{ref:f,className:"lotus-command-palette-list",role:"listbox",children:T.length===0?r.jsxs("div",{className:"lotus-command-palette-empty",children:[r.jsx(Xx,{}),r.jsx("span",{children:e("commandPalette.empty","No matching commands")})]}):T.map((P,S)=>{const L=S===p;return r.jsxs("button",{type:"button",className:`lotus-command-palette-item ${L?"is-selected":""}`,"data-command-index":S,onMouseEnter:()=>g(S),onClick:()=>{(async()=>{try{await P.onSelect(),d(!1),h("")}catch($){console.error("[CommandPalette] action failed",$),n.error($ instanceof Error?$.message:e("commandPalette.errors.actionFailed","Command failed"))}})()},children:[r.jsx("span",{className:"lotus-command-palette-item-icon",children:P.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:P.title}),P.badge?r.jsx(oe,{bordered:!1,children:P.badge}):null]}),P.subtitle?r.jsx("span",{className:"lotus-command-palette-item-subtitle",children:P.subtitle}):null]})]},P.id)})})]})})},np="bodhi_open_provider_on_entry",PA=({themeMode:e,onThemeModeChange:t,locale:s,onLocaleChange:n})=>{const o=Bs(T=>T.isOpen),a=Bs(T=>T.close),{t:i}=ne(),{token:l}=he.useToken(),c=Xi(),d=m.useMemo(()=>_y()==="macos",[]),u=Ee(T=>T.loadProviderConfig);m.useEffect(()=>{u()},[u]),m.useEffect(()=>{localStorage.getItem(np)==="true"&&(localStorage.removeItem(np),Bs.getState().open("chat","provider"))},[]),Ok(),kk(),m.useEffect(()=>{th.clear(),sh()},[e]),m.useEffect(()=>{th.clear(),sh()},[c]);const h=Ae(T=>T.sidebar.collapsed),p=Ae(T=>T.sidebar.widthPx),g=Ae(T=>T.sidebar.minWidthPx),y=Ae(T=>T.sidebar.maxWidthPx),f=Ae(T=>T.setSidebarCollapsed),v=Ae(T=>T.setSidebarWidthPx),b=18,x=0,w=!o&&h&&d?44:x,k=0,C=88,E=10,j="none",R=md();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:T=>{T.currentTarget.style.top="8px",T.currentTarget.style.left="8px"},onBlur:T=>{T.currentTarget.style.top="-9999px",T.currentTarget.style.left="-9999px"},children:i("app.skipToContent","Skip to main content")}),r.jsx(MA,{}),r.jsx(X_,{disabled:o}),r.jsx(Dn,{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:w,paddingLeft:x,paddingRight:x,paddingBottom:x,background:"transparent"},children:[o?r.jsx(Dn,{className:"lotus-shell-panel lotus-settings-panel lotus-page-enter",style:{flex:1,display:"flex",flexDirection:"column",background:"var(--lotus-main-surface)",minHeight:0,borderRadius:`${b}px 0 0 ${b}px`,border:j,overflow:"hidden"},children:r.jsx(ia,{name:"SystemSettings",children:r.jsx(vk,{themeMode:e,onThemeModeChange:t,locale:s,onLocaleChange:n,onBack:a})})}):r.jsxs(r.Fragment,{children:[r.jsx(Tk,{}),R?r.jsxs(r.Fragment,{children:[r.jsx(Vx,{placement:"left",closable:!1,onClose:()=>f(!0),open:!h,width:"min(86vw, 360px)",styles:{body:{padding:0,background:"var(--lotus-sidebar-bg)"}},children:r.jsx(um,{})}),r.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{flex:1,height:"100%",minHeight:0,borderRadius:`${b}px`,border:j,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:r.jsx(Dn,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:r.jsx(sp,{})})})]}):r.jsx(Lb,{layout:"horizontal",style:{flex:1,minHeight:0,height:"100%",background:"transparent"},sizesPx:[h?k:p,0],minFirstPx:h?k:g,minSecondPx:320,disabled:h,handleSizePx:h?0:2,onResizeEnd:([T])=>{if(h)return;const P=Math.max(g,Math.min(y,T));v(P)},first:r.jsx("div",{className:"lotus-shell-panel lotus-shell-sidebar",style:{height:"100%",minHeight:0,borderRadius:`${b}px 0 0 ${b}px`,border:j,overflow:"hidden",background:"var(--lotus-sidebar-bg)"},children:r.jsx(um,{})}),second:r.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{height:"100%",minHeight:0,borderRadius:`0 ${b}px ${b}px 0`,border:j,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:r.jsx(Dn,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:r.jsx(sp,{})})})})]}),!o&&h?r.jsx(Y,{"data-testid":"show-sidebar",type:"text",size:"small",icon:r.jsx(kf,{}),onClick:()=>f(!1),title:i("layout.showSidebar"),"aria-label":i("layout.showSidebar"),className:"lotus-toolbar-icon lotus-floating-sidebar-toggle",style:{position:"absolute",top:R?8:E,left:R?8:C,zIndex:40,width:36,height:36,borderRadius:12,border:`1px solid ${l.colorBorderSecondary}`,background:l.colorBgElevated,boxShadow:l.boxShadowSecondary}}):null]})})]})},EA="bodhi_open_provider_on_entry",{Title:rp,Paragraph:op}=le,RA=()=>{const{t:e}=ne(),[t,s]=m.useState(!1),[n,o]=m.useState(null),[a,i]=m.useState(!1),l=async c=>{try{o(null),i(!0),await fs.getInstance().markSetupComplete(),c&&localStorage.setItem(EA,"true"),s(!0)}catch(d){console.error("Failed to complete setup:",d),o(e("setup.error.completeFailed"))}finally{i(!1)}};return t?r.jsxs("div",{"data-testid":"setup-complete",className:"setup-complete",children:[r.jsx(rp,{level:2,children:e("setup.complete.title")}),r.jsx(op,{children:e("setup.complete.restartMessage")}),r.jsx(Y,{"data-testid":"setup-restart",onClick:()=>window.location.reload(),children:e("setup.complete.restartMessage")})]}):r.jsx("div",{className:"setup-page",children:r.jsxs(ee,{className:"setup-page__card",children:[r.jsxs("div",{className:"setup-page__hero",children:[r.jsx("div",{className:"setup-page__hero-icon",children:r.jsx(hu,{})}),r.jsx(rp,{level:2,style:{marginTop:0},children:e("setup.welcome.heading")}),r.jsx(op,{type:"secondary",children:e("setup.welcome.description")})]}),r.jsx(Xe,{message:e("setup.welcome.providerHint"),type:"info",showIcon:!0,style:{marginBottom:16}}),r.jsx(Xe,{message:e("setup.welcome.proxyHint"),type:"info",showIcon:!0,style:{marginBottom:24}}),n?r.jsx(Xe,{message:n,type:"error",showIcon:!0,style:{marginBottom:16}}):null,r.jsxs("div",{className:"setup-page__actions",children:[r.jsx(Y,{"data-testid":"setup-configure-provider",icon:r.jsx(da,{}),onClick:()=>void l(!0),loading:a,children:e("setup.button.configureProvider")}),r.jsx(Y,{"data-testid":"setup-get-started",type:"primary",icon:r.jsx(hu,{}),onClick:()=>void l(!1),loading:a,children:e("setup.button.getStarted")})]})]})})},{Title:AA,Text:ap}=le,IA=({onVerified:e,verifyPassword:t})=>{const{t:s}=ne(),[n,o]=m.useState(""),[a,i]=m.useState(null),[l,c]=m.useState(!1),d=async()=>{const u=n.trim();if(!u){i(s("app.passwordGate.validation.required","请输入访问密码"));return}c(!0),i(null);try{await t(u),await e(),o("")}catch(h){const p=h instanceof Error?h.message:s("app.passwordGate.validation.verifyFailed","密码验证失败");i(p)}finally{c(!1)}};return r.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:r.jsx(ee,{style:{width:"100%",maxWidth:480},children:r.jsxs(X,{direction:"vertical",size:20,style:{width:"100%"},children:[r.jsxs("div",{children:[r.jsx(AA,{level:3,style:{marginBottom:8},children:s("app.passwordGate.title","请输入访问密码")}),r.jsx(ap,{type:"secondary",children:s("app.passwordGate.description","当前访问需要先通过密码验证,验证成功后才会进入应用。")})]}),a?r.jsx(Xe,{type:"error",showIcon:!0,message:a}):null,r.jsxs(X,{direction:"vertical",size:8,style:{width:"100%"},children:[r.jsx(ap,{strong:!0,children:s("app.passwordGate.passwordLabel","访问密码")}),r.jsx(me.Password,{value:n,autoFocus:!0,autoComplete:"current-password",onChange:u=>o(u.target.value),onPressEnter:()=>void d(),placeholder:s("app.passwordGate.passwordPlaceholder","请输入访问密码")})]}),r.jsx(Y,{type:"primary",block:!0,loading:l,onClick:()=>void d(),children:s("app.passwordGate.submit","验证并进入")})]})})})};var Qr={},Hl={exports:{}},ip;function tt(){return ip||(ip=1,function(e){function t(s){return s&&s.__esModule?s:{default:s}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}(Hl)),Hl.exports}var Zr={},lp;function $A(){if(lp)return Zr;lp=1,Object.defineProperty(Zr,"__esModule",{value:!0}),Zr.default=void 0;var e={items_per_page:"/ page",jump_to:"Go to",jump_to_confirm:"confirm",page:"Page",prev_page:"Previous Page",next_page:"Next Page",prev_5:"Previous 5 Pages",next_5:"Next 5 Pages",prev_3:"Previous 3 Pages",next_3:"Next 3 Pages",page_size:"Page Size"};return Zr.default=e,Zr}var eo={},to={},so={},Yl={exports:{}},Xl={exports:{}},Vl={exports:{}},Kl={exports:{}},cp;function DA(){return cp||(cp=1,function(e){var t=pf().default;function s(n,o){if(t(n)!="object"||!n)return n;var a=n[Symbol.toPrimitive];if(a!==void 0){var i=a.call(n,o||"default");if(t(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(o==="string"?String:Number)(n)}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}(Kl)),Kl.exports}var dp;function LA(){return dp||(dp=1,function(e){var t=pf().default,s=DA();function n(o){var a=s(o,"string");return t(a)=="symbol"?a:a+""}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports}(Vl)),Vl.exports}var up;function OA(){return up||(up=1,function(e){var t=LA();function s(n,o,a){return(o=t(o))in n?Object.defineProperty(n,o,{value:a,enumerable:!0,configurable:!0,writable:!0}):n[o]=a,n}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}(Xl)),Xl.exports}var mp;function Cr(){return mp||(mp=1,function(e){var t=OA();function s(o,a){var i=Object.keys(o);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(o);a&&(l=l.filter(function(c){return Object.getOwnPropertyDescriptor(o,c).enumerable})),i.push.apply(i,l)}return i}function n(o){for(var a=1;a<arguments.length;a++){var i=arguments[a]!=null?arguments[a]:{};a%2?s(Object(i),!0).forEach(function(l){t(o,l,i[l])}):Object.getOwnPropertyDescriptors?Object.defineProperties(o,Object.getOwnPropertyDescriptors(i)):s(Object(i)).forEach(function(l){Object.defineProperty(o,l,Object.getOwnPropertyDescriptor(i,l))})}return o}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports}(Yl)),Yl.exports}var no={},hp;function Mr(){return hp||(hp=1,Object.defineProperty(no,"__esModule",{value:!0}),no.commonLocale=void 0,no.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0}),no}var pp;function FA(){if(pp)return so;pp=1;var e=tt().default;Object.defineProperty(so,"__esModule",{value:!0}),so.default=void 0;var t=e(Cr()),s=Mr(),n=(0,t.default)((0,t.default)({},s.commonLocale),{},{locale:"en_US",today:"Today",now:"Now",backToToday:"Back to today",ok:"OK",clear:"Clear",week:"Week",month:"Month",year:"Year",timeSelect:"select time",dateSelect:"select date",weekSelect:"Choose a week",monthSelect:"Choose a month",yearSelect:"Choose a year",decadeSelect:"Choose a decade",dateFormat:"M/D/YYYY",dateTimeFormat:"M/D/YYYY HH:mm:ss",previousMonth:"Previous month (PageUp)",nextMonth:"Next month (PageDown)",previousYear:"Last year (Control + left)",nextYear:"Next year (Control + right)",previousDecade:"Last decade",nextDecade:"Next decade",previousCentury:"Last century",nextCentury:"Next century"});return so.default=n,so}var ro={},fp;function Ob(){if(fp)return ro;fp=1,Object.defineProperty(ro,"__esModule",{value:!0}),ro.default=void 0;const e={placeholder:"Select time",rangePlaceholder:["Start time","End time"]};return ro.default=e,ro}var gp;function Fb(){if(gp)return to;gp=1;var e=tt().default;Object.defineProperty(to,"__esModule",{value:!0}),to.default=void 0;var t=e(FA()),s=e(Ob());const n={lang:Object.assign({placeholder:"Select date",yearPlaceholder:"Select year",quarterPlaceholder:"Select quarter",monthPlaceholder:"Select month",weekPlaceholder:"Select week",rangePlaceholder:["Start date","End date"],rangeYearPlaceholder:["Start year","End year"],rangeQuarterPlaceholder:["Start quarter","End quarter"],rangeMonthPlaceholder:["Start month","End month"],rangeWeekPlaceholder:["Start week","End week"]},t.default),timePickerLocale:Object.assign({},s.default)};return to.default=n,to}var yp;function zA(){if(yp)return eo;yp=1;var e=tt().default;Object.defineProperty(eo,"__esModule",{value:!0}),eo.default=void 0;var t=e(Fb());return eo.default=t.default,eo}var bp;function NA(){if(bp)return Qr;bp=1;var e=tt().default;Object.defineProperty(Qr,"__esModule",{value:!0}),Qr.default=void 0;var t=e($A()),s=e(zA()),n=e(Fb()),o=e(Ob());const a="${label} is not a valid ${type}",i={locale:"en",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.default,global:{placeholder:"Please select"},Table:{filterTitle:"Filter menu",filterConfirm:"OK",filterReset:"Reset",filterEmptyText:"No filters",filterCheckAll:"Select all items",filterSearchPlaceholder:"Search in filters",emptyText:"No data",selectAll:"Select current page",selectInvert:"Invert current page",selectNone:"Clear all data",selectionAll:"Select all data",sortTitle:"Sort",expand:"Expand row",collapse:"Collapse row",triggerDesc:"Click to sort descending",triggerAsc:"Click to sort ascending",cancelSort:"Click to cancel sorting"},Tour:{Next:"Next",Previous:"Previous",Finish:"Finish"},Modal:{okText:"OK",cancelText:"Cancel",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Cancel"},Transfer:{titles:["",""],searchPlaceholder:"Search here",itemUnit:"item",itemsUnit:"items",remove:"Remove",selectCurrent:"Select current page",removeCurrent:"Remove current page",selectAll:"Select all data",deselectAll:"Deselect all data",removeAll:"Remove all data",selectInvert:"Invert current page"},Upload:{uploading:"Uploading...",removeFile:"Remove file",uploadError:"Upload error",previewFile:"Preview file",downloadFile:"Download file"},Empty:{description:"No data"},Icon:{icon:"icon"},Text:{edit:"Edit",copy:"Copy",copied:"Copied",expand:"Expand",collapse:"Collapse"},Form:{optional:"(optional)",defaultValidateMessages:{default:"Field validation error for ${label}",required:"Please enter ${label}",enum:"${label} must be one of [${enum}]",whitespace:"${label} cannot be a blank character",date:{format:"${label} date format is invalid",parse:"${label} cannot be converted to a date",invalid:"${label} is an invalid date"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"${label} must be ${len} characters",min:"${label} must be at least ${min} characters",max:"${label} must be up to ${max} characters",range:"${label} must be between ${min}-${max} characters"},number:{len:"${label} must be equal to ${len}",min:"${label} must be minimum ${min}",max:"${label} must be maximum ${max}",range:"${label} must be between ${min}-${max}"},array:{len:"Must be ${len} ${label}",min:"At least ${min} ${label}",max:"At most ${max} ${label}",range:"The amount of ${label} must be between ${min}-${max}"},pattern:{mismatch:"${label} does not match the pattern ${pattern}"}}},Image:{preview:"Preview"},QRCode:{expired:"QR code expired",refresh:"Refresh",scanned:"Scanned"},ColorPicker:{presetEmpty:"Empty",transparent:"Transparent",singleColor:"Single",gradientColor:"Gradient"}};return Qr.default=i,Qr}var Gl,xp;function BA(){return xp||(xp=1,Gl=NA()),Gl}var WA=BA();const UA=vr(WA);var oo={},ao={},vp;function qA(){if(vp)return ao;vp=1,Object.defineProperty(ao,"__esModule",{value:!0}),ao.default=void 0;var e={items_per_page:"/ page",jump_to:"Aller à",jump_to_confirm:"confirmer",page:"Page",prev_page:"Page précédente",next_page:"Page suivante",prev_5:"5 Pages précédentes",next_5:"5 Pages suivantes",prev_3:"3 Pages précédentes",next_3:"3 Pages suivantes",page_size:"taille de la page"};return ao.default=e,ao}var io={},lo={},co={},Sp;function HA(){if(Sp)return co;Sp=1;var e=tt().default;Object.defineProperty(co,"__esModule",{value:!0}),co.default=void 0;var t=e(Cr()),s=Mr(),n=(0,t.default)((0,t.default)({},s.commonLocale),{},{locale:"fr_FR",today:"Aujourd'hui",now:"Maintenant",backToToday:"Aujourd'hui",ok:"OK",clear:"Rétablir",week:"Semaine",month:"Mois",year:"Année",timeSelect:"Sélectionner l'heure",dateSelect:"Sélectionner la date",monthSelect:"Choisissez un mois",yearSelect:"Choisissez une année",decadeSelect:"Choisissez une décennie",dateFormat:"DD/MM/YYYY",dayFormat:"DD",dateTimeFormat:"DD/MM/YYYY HH:mm:ss",previousMonth:"Mois précédent (PageUp)",nextMonth:"Mois suivant (PageDown)",previousYear:"Année précédente (Ctrl + gauche)",nextYear:"Année prochaine (Ctrl + droite)",previousDecade:"Décennie précédente",nextDecade:"Décennie suivante",previousCentury:"Siècle précédent",nextCentury:"Siècle suivant"});return co.default=n,co}var uo={},wp;function zb(){if(wp)return uo;wp=1,Object.defineProperty(uo,"__esModule",{value:!0}),uo.default=void 0;const e={placeholder:"Sélectionner l'heure",rangePlaceholder:["Heure de début","Heure de fin"]};return uo.default=e,uo}var _p;function Nb(){if(_p)return lo;_p=1;var e=tt().default;Object.defineProperty(lo,"__esModule",{value:!0}),lo.default=void 0;var t=e(HA()),s=e(zb());const n={lang:Object.assign({placeholder:"Sélectionner une date",yearPlaceholder:"Sélectionner une année",quarterPlaceholder:"Sélectionner un trimestre",monthPlaceholder:"Sélectionner un mois",weekPlaceholder:"Sélectionner une semaine",rangePlaceholder:["Date de début","Date de fin"],rangeYearPlaceholder:["Année de début","Année de fin"],rangeMonthPlaceholder:["Mois de début","Mois de fin"],rangeWeekPlaceholder:["Semaine de début","Semaine de fin"]},t.default),timePickerLocale:Object.assign({},s.default)};return lo.default=n,lo}var Tp;function YA(){if(Tp)return io;Tp=1;var e=tt().default;Object.defineProperty(io,"__esModule",{value:!0}),io.default=void 0;var t=e(Nb());return io.default=t.default,io}var kp;function XA(){if(kp)return oo;kp=1;var e=tt().default;Object.defineProperty(oo,"__esModule",{value:!0}),oo.default=void 0;var t=e(qA()),s=e(YA()),n=e(Nb()),o=e(zb());const a="La valeur du champ ${label} n'est pas valide pour le type ${type}",i={locale:"fr",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.default,Table:{filterTitle:"Filtrer",filterConfirm:"OK",filterReset:"Réinitialiser",filterEmptyText:"Aucun filtre",filterCheckAll:"Tout sélectionner",filterSearchPlaceholder:"Chercher dans les filtres",emptyText:"Aucune donnée",selectAll:"Sélectionner la page actuelle",selectInvert:"Inverser la sélection de la page actuelle",selectNone:"Désélectionner toutes les données",selectionAll:"Sélectionner toutes les données",sortTitle:"Trier",expand:"Développer la ligne",collapse:"Réduire la ligne",triggerDesc:"Trier par ordre décroissant",triggerAsc:"Trier par ordre croissant",cancelSort:"Annuler le tri"},Tour:{Next:"Étape suivante",Previous:"Étape précédente",Finish:"Fin de la visite guidée"},Modal:{okText:"OK",cancelText:"Annuler",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Annuler"},Transfer:{titles:["",""],searchPlaceholder:"Rechercher",itemUnit:"élément",itemsUnit:"éléments",remove:"Désélectionner",selectCurrent:"Sélectionner la page actuelle",removeCurrent:"Désélectionner la page actuelle",selectAll:"Sélectionner toutes les données",removeAll:"Désélectionner toutes les données",selectInvert:"Inverser la sélection de la page actuelle"},Upload:{uploading:"Téléchargement...",removeFile:"Effacer le fichier",uploadError:"Erreur de téléchargement",previewFile:"Fichier de prévisualisation",downloadFile:"Télécharger un fichier"},Empty:{description:"Aucune donnée"},Icon:{icon:"icône"},Text:{edit:"Éditer",copy:"Copier",copied:"Copie effectuée",expand:"Développer"},Form:{optional:"(optionnel)",defaultValidateMessages:{default:"Erreur de validation pour le champ ${label}",required:"Le champ ${label} est obligatoire",enum:"La valeur du champ ${label} doit être parmi [${enum}]",whitespace:"La valeur du champ ${label} ne peut pas être vide",date:{format:"La valeur du champ ${label} n'est pas au format date",parse:"La valeur du champ ${label} ne peut pas être convertie vers une date",invalid:"La valeur du champ ${label} n'est pas une date valide"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"La taille du champ ${label} doit être de ${len} caractères",min:"La taille du champ ${label} doit être au minimum de ${min} caractères",max:"La taille du champ ${label} doit être au maximum de ${max} caractères",range:"La taille du champ ${label} doit être entre ${min} et ${max} caractères"},number:{len:"La valeur du champ ${label} doit être égale à ${len}",min:"La valeur du champ ${label} doit être plus grande que ${min}",max:"La valeur du champ ${label} doit être plus petit que ${max}",range:"La valeur du champ ${label} doit être entre ${min} et ${max}"},array:{len:"La taille du tableau ${label} doit être de ${len}",min:"La taille du tableau ${label} doit être au minimum de ${min}",max:"La taille du tableau ${label} doit être au maximum de ${max}",range:"La taille du tableau ${label} doit être entre ${min}-${max}"},pattern:{mismatch:"La valeur du champ ${label} ne correspond pas au modèle ${pattern}"}}},Image:{preview:"Aperçu"}};return oo.default=i,oo}var Jl,jp;function VA(){return jp||(jp=1,Jl=XA()),Jl}var KA=VA();const GA=vr(KA);var mo={},ho={},Cp;function JA(){if(Cp)return ho;Cp=1,Object.defineProperty(ho,"__esModule",{value:!0}),ho.default=void 0;var e={items_per_page:"/ पृष्ठ",jump_to:"इस पर चलें",jump_to_confirm:"पुष्टि करें",page:"",prev_page:"पिछला पृष्ठ",next_page:"अगला पृष्ठ",prev_5:"पिछले 5 पृष्ठ",next_5:"अगले 5 पृष्ठ",prev_3:"पिछले 3 पृष्ठ",next_3:"अगले 3 पेज",page_size:"Page Size"};return ho.default=e,ho}var po={},fo={},go={},Mp;function QA(){if(Mp)return go;Mp=1;var e=tt().default;Object.defineProperty(go,"__esModule",{value:!0}),go.default=void 0;var t=e(Cr()),s=Mr(),n=(0,t.default)((0,t.default)({},s.commonLocale),{},{locale:"hi_IN",today:"आज",now:"अभी",backToToday:"आज तक",ok:"ठीक",clear:"स्पष्ट",week:"सप्ताह",month:"महीना",year:"साल",timeSelect:"समय का चयन करें",dateSelect:"तारीख़ चुनें",weekSelect:"एक सप्ताह चुनें",monthSelect:"एक महीना चुनें",yearSelect:"एक वर्ष चुनें",decadeSelect:"एक दशक चुनें",dateFormat:"M/D/YYYY",dateTimeFormat:"M/D/YYYY HH:mm:ss",previousMonth:"पिछला महीना (पेजअप)",nextMonth:"अगले महीने (पेजडाउन)",previousYear:"पिछले साल (Ctrl + बाएं)",nextYear:"अगले साल (Ctrl + दाहिना)",previousDecade:"पिछला दशक",nextDecade:"अगले दशक",previousCentury:"पीछ्ली शताब्दी",nextCentury:"अगली सदी"});return go.default=n,go}var yo={},Pp;function Bb(){if(Pp)return yo;Pp=1,Object.defineProperty(yo,"__esModule",{value:!0}),yo.default=void 0;const e={placeholder:"समय का चयन करें",rangePlaceholder:["आरंभिक समय","अंत समय"]};return yo.default=e,yo}var Ep;function Wb(){if(Ep)return fo;Ep=1;var e=tt().default;Object.defineProperty(fo,"__esModule",{value:!0}),fo.default=void 0;var t=e(QA()),s=e(Bb());const n={lang:Object.assign({placeholder:"तारीख़ चुनें",yearPlaceholder:"वर्ष चुनें",quarterPlaceholder:"तिमाही चुनें",monthPlaceholder:"महीना चुनिए",weekPlaceholder:"सप्ताह चुनें",rangePlaceholder:["प्रारंभ तिथि","समाप्ति तिथि"],rangeYearPlaceholder:["आरंभिक वर्ष","अंत वर्ष"],rangeMonthPlaceholder:["आरंभिक महीना","अंत महीना"],rangeWeekPlaceholder:["आरंभिक सप्ताह","अंत सप्ताह"]},t.default),timePickerLocale:Object.assign({},s.default)};return fo.default=n,fo}var Rp;function ZA(){if(Rp)return po;Rp=1;var e=tt().default;Object.defineProperty(po,"__esModule",{value:!0}),po.default=void 0;var t=e(Wb());return po.default=t.default,po}var Ap;function eI(){if(Ap)return mo;Ap=1;var e=tt().default;Object.defineProperty(mo,"__esModule",{value:!0}),mo.default=void 0;var t=e(JA()),s=e(ZA()),n=e(Wb()),o=e(Bb());const a="${label} मान्य ${type} नहीं है",i={locale:"hi",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.default,global:{placeholder:"कृपया चुनें"},Table:{filterTitle:"सूची बंद करें",filterConfirm:"अच्छी तरह से",filterReset:"रीसेट",filterEmptyText:"कोई फ़िल्टर नहीं",emptyText:"कोई जानकारी नहीं",selectAll:"वर्तमान पृष्ठ का चयन करें",selectInvert:"वर्तमान पृष्ठ घुमाएं",selectNone:"सभी डेटा साफ़ करें",selectionAll:"सभी डेटा का चयन करें",sortTitle:"द्वारा क्रमबद्ध करें",expand:"पंक्ति का विस्तार करें",collapse:"पंक्ति संक्षिप्त करें",triggerDesc:"अवरोही क्रमित करने के लिए क्लिक करें",triggerAsc:"आरोही क्रमित करने के लिए क्लिक करें",cancelSort:"छँटाई रद्द करने के लिए क्लिक करें"},Modal:{okText:"अच्छी तरह से",cancelText:"रद्द करना",justOkText:"अच्छी तरह से"},Popconfirm:{okText:"अच्छी तरह से",cancelText:"रद्द करना"},Transfer:{titles:["",""],searchPlaceholder:"यहां खोजें",itemUnit:"तत्त्व",itemsUnit:"विषय-वस्तु",remove:"हटाए",selectCurrent:"वर्तमान पृष्ठ का चयन करें",removeCurrent:"वर्तमान पृष्ठ हटाएं",selectAll:"सभी डेटा का चयन करें",removeAll:"सभी डेटा हटाएं",selectInvert:"वर्तमान पृष्ठ को उल्टा करें"},Upload:{uploading:"अपलोड हो रहा...",removeFile:"फ़ाइल निकालें",uploadError:"अपलोड में त्रुटि",previewFile:"फ़ाइल पूर्वावलोकन",downloadFile:"फ़ाइल डाउनलोड करें"},Empty:{description:"कोई आकड़ा उपलब्ध नहीं है"},Icon:{icon:"आइकन"},Text:{edit:"संपादित करें",copy:"प्रतिलिपि",copied:"कॉपी किया गया",expand:"विस्तार"},Form:{optional:"(ऐच्छिक)",defaultValidateMessages:{default:"${label} के लिए फील्ड सत्यापन त्रुटि",required:"कृपया ${label} दर्ज करें",enum:"${label} [${enum}] में से एक होना चाहिए",whitespace:"${label} एक खाली अक्षर नहीं हो सकता",date:{format:"${label} तिथि प्रारूप अमान्य है",parse:"${label} को तारीख में नहीं बदला जा सकता",invalid:"${label} एक अमान्य तिथि है"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"${label} ${len} अक्षर का होना चाहिए",min:"${label} कम से कम ${min} वर्णों का होना चाहिए",max:"${label} अधिकतम ${max} वर्णों का होना चाहिए",range:"${label} ${min}-${max} वर्णों के बीच होना चाहिए"},number:{len:"${label} ${len} के बराबर होना चाहिए",min:"${label} कम से कम ${min} होना चाहिए",max:"${label} अधिकतम ${max} होना चाहिए",range:"${label} ${min}-${max} के बीच होना चाहिए"},array:{len:"${len} ${label} होना चाहिए",min:"कम से कम ${min} ${label}",max:"ज्यादा से ज्यादा ${max} ${label}",range:"${label} की राशि ${min}-${max} के बीच होनी चाहिए"},pattern:{mismatch:"${label} ${pattern} पैटर्न से मेल नहीं खाता"}}},Image:{preview:"पूर्वावलोकन"}};return mo.default=i,mo}var Ql,Ip;function tI(){return Ip||(Ip=1,Ql=eI()),Ql}var sI=tI();const nI=vr(sI);var bo={},xo={},$p;function rI(){if($p)return xo;$p=1,Object.defineProperty(xo,"__esModule",{value:!0}),xo.default=void 0;var e={items_per_page:"件 / ページ",jump_to:"移動",jump_to_confirm:"確認する",page:"ページ",prev_page:"前のページ",next_page:"次のページ",prev_5:"前 5ページ",next_5:"次 5ページ",prev_3:"前 3ページ",next_3:"次 3ページ",page_size:"ページサイズ"};return xo.default=e,xo}var vo={},So={},wo={},Dp;function oI(){if(Dp)return wo;Dp=1;var e=tt().default;Object.defineProperty(wo,"__esModule",{value:!0}),wo.default=void 0;var t=e(Cr()),s=Mr(),n=(0,t.default)((0,t.default)({},s.commonLocale),{},{locale:"ja_JP",today:"今日",now:"現在時刻",backToToday:"今日に戻る",ok:"確定",timeSelect:"時間を選択",dateSelect:"日時を選択",weekSelect:"週を選択",clear:"クリア",week:"週",month:"月",year:"年",previousMonth:"前月 (ページアップキー)",nextMonth:"翌月 (ページダウンキー)",monthSelect:"月を選択",yearSelect:"年を選択",decadeSelect:"年代を選択",yearFormat:"YYYY年",dateFormat:"YYYY年M月D日",dateTimeFormat:"YYYY年M月D日 HH時mm分ss秒",previousYear:"前年 (Controlを押しながら左キー)",nextYear:"翌年 (Controlを押しながら右キー)",previousDecade:"前の年代",nextDecade:"次の年代",previousCentury:"前の世紀",nextCentury:"次の世紀",monthBeforeYear:!1});return wo.default=n,wo}var _o={},Lp;function Ub(){if(Lp)return _o;Lp=1,Object.defineProperty(_o,"__esModule",{value:!0}),_o.default=void 0;const e={placeholder:"時間を選択",rangePlaceholder:["開始時間","終了時間"]};return _o.default=e,_o}var Op;function qb(){if(Op)return So;Op=1;var e=tt().default;Object.defineProperty(So,"__esModule",{value:!0}),So.default=void 0;var t=e(oI()),s=e(Ub());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 So.default=n,So}var Fp;function aI(){if(Fp)return vo;Fp=1;var e=tt().default;Object.defineProperty(vo,"__esModule",{value:!0}),vo.default=void 0;var t=e(qb());return vo.default=t.default,vo}var zp;function iI(){if(zp)return bo;zp=1;var e=tt().default;Object.defineProperty(bo,"__esModule",{value:!0}),bo.default=void 0;var t=e(rI()),s=e(aI()),n=e(qb()),o=e(Ub());const a="${label}は有効な${type}ではありません",i={locale:"ja",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.default,global:{placeholder:"選んでください"},Table:{filterTitle:"フィルター",filterConfirm:"OK",filterReset:"リセット",filterEmptyText:"フィルターなし",filterCheckAll:"すべてを選択",filterSearchPlaceholder:"フィルターで検索",emptyText:"データなし",selectAll:"ページ単位で選択",selectInvert:"ページ単位で反転",selectNone:"クリア",selectionAll:"すべてを選択",sortTitle:"ソート",expand:"展開する",collapse:"折り畳む",triggerDesc:"クリックで降順にソート",triggerAsc:"クリックで昇順にソート",cancelSort:"ソートをキャンセル"},Tour:{Next:"次",Previous:"前の",Finish:"仕上げる"},Modal:{okText:"OK",cancelText:"キャンセル",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"キャンセル"},Transfer:{titles:["",""],searchPlaceholder:"ここを検索",itemUnit:"アイテム",itemsUnit:"アイテム",remove:"削除",selectCurrent:"現在のページを選択",removeCurrent:"現在のページを削除",selectAll:"ページ単位で選択",deselectAll:"すべてのデータの選択を解除する",removeAll:"ページ単位で削除",selectInvert:"ページ単位で反転"},Upload:{uploading:"アップロード中...",removeFile:"ファイルを削除",uploadError:"アップロードエラー",previewFile:"ファイルをプレビュー",downloadFile:"ダウンロードファイル"},Empty:{description:"データがありません"},Icon:{icon:"アイコン"},Text:{edit:"編集",copy:"コピー",copied:"コピーされました",expand:"拡大する",collapse:"崩壊"},Form:{optional:"(オプション)",defaultValidateMessages:{default:"${label}のフィールド検証エラー",required:"${label}を入力してください",enum:"${label}は[${enum}]のいずれかである必要があります",whitespace:"${label}は空白文字にすることはできません",date:{format:"${label}の日付形式は不正です",parse:"${label}は日付に変換できません",invalid:"${label}は不正な日付です"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"${label}は${len}文字である必要があります",min:"${label}は${min}文字以上である必要があります",max:"${label}は${max}文字以下である必要があります",range:"${label}は${min}-${max}文字の範囲である必要があります"},number:{len:"${label}は${len}と等しい必要があります",min:"${label}の最小値は${min}です",max:"${label}の最大値は${max}です",range:"${label}は${min}-${max}の範囲である必要があります"},array:{len:"${label}は${len}である必要があります",min:"${label}の最小は${min}です",max:"${label}の最大は${max}です",range:"${label}の合計は${min}-${max}の範囲である必要があります"},pattern:{mismatch:"${label}はパターン${pattern}と一致しません"}}},Image:{preview:"プレビュー"},QRCode:{expired:"QRコードの有効期限が切れました",refresh:"リフレッシュ",scanned:"スキャン済み"},ColorPicker:{presetEmpty:"空の",transparent:"透明",singleColor:"単色",gradientColor:"グラデーション"}};return bo.default=i,bo}var Zl,Np;function lI(){return Np||(Np=1,Zl=iI()),Zl}var cI=lI();const dI=vr(cI);var To={},ko={},Bp;function uI(){if(Bp)return ko;Bp=1,Object.defineProperty(ko,"__esModule",{value:!0}),ko.default=void 0;var e={items_per_page:"条/页",jump_to:"跳至",jump_to_confirm:"确定",page:"页",prev_page:"上一页",next_page:"下一页",prev_5:"向前 5 页",next_5:"向后 5 页",prev_3:"向前 3 页",next_3:"向后 3 页",page_size:"页码"};return ko.default=e,ko}var jo={},Co={},Mo={},Wp;function mI(){if(Wp)return Mo;Wp=1;var e=tt().default;Object.defineProperty(Mo,"__esModule",{value:!0}),Mo.default=void 0;var t=e(Cr()),s=Mr(),n=(0,t.default)((0,t.default)({},s.commonLocale),{},{locale:"zh_CN",today:"今天",now:"此刻",backToToday:"返回今天",ok:"确定",timeSelect:"选择时间",dateSelect:"选择日期",weekSelect:"选择周",clear:"清除",week:"周",month:"月",year:"年",previousMonth:"上个月 (翻页上键)",nextMonth:"下个月 (翻页下键)",monthSelect:"选择月份",yearSelect:"选择年份",decadeSelect:"选择年代",previousYear:"上一年 (Control键加左方向键)",nextYear:"下一年 (Control键加右方向键)",previousDecade:"上一年代",nextDecade:"下一年代",previousCentury:"上一世纪",nextCentury:"下一世纪",yearFormat:"YYYY年",cellDateFormat:"D",monthBeforeYear:!1});return Mo.default=n,Mo}var Po={},Up;function Hb(){if(Up)return Po;Up=1,Object.defineProperty(Po,"__esModule",{value:!0}),Po.default=void 0;const e={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return Po.default=e,Po}var qp;function Yb(){if(qp)return Co;qp=1;var e=tt().default;Object.defineProperty(Co,"__esModule",{value:!0}),Co.default=void 0;var t=e(mI()),s=e(Hb());const n={lang:Object.assign({placeholder:"请选择日期",yearPlaceholder:"请选择年份",quarterPlaceholder:"请选择季度",monthPlaceholder:"请选择月份",weekPlaceholder:"请选择周",rangePlaceholder:["开始日期","结束日期"],rangeYearPlaceholder:["开始年份","结束年份"],rangeMonthPlaceholder:["开始月份","结束月份"],rangeQuarterPlaceholder:["开始季度","结束季度"],rangeWeekPlaceholder:["开始周","结束周"]},t.default),timePickerLocale:Object.assign({},s.default)};return n.lang.ok="确定",Co.default=n,Co}var Hp;function hI(){if(Hp)return jo;Hp=1;var e=tt().default;Object.defineProperty(jo,"__esModule",{value:!0}),jo.default=void 0;var t=e(Yb());return jo.default=t.default,jo}var Yp;function pI(){if(Yp)return To;Yp=1;var e=tt().default;Object.defineProperty(To,"__esModule",{value:!0}),To.default=void 0;var t=e(uI()),s=e(hI()),n=e(Yb()),o=e(Hb());const a="${label}不是一个有效的${type}",i={locale:"zh-cn",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.default,global:{placeholder:"请选择"},Table:{filterTitle:"筛选",filterConfirm:"确定",filterReset:"重置",filterEmptyText:"无筛选项",filterCheckAll:"全选",filterSearchPlaceholder:"在筛选项中搜索",emptyText:"暂无数据",selectAll:"全选当页",selectInvert:"反选当页",selectNone:"清空所有",selectionAll:"全选所有",sortTitle:"排序",expand:"展开行",collapse:"关闭行",triggerDesc:"点击降序",triggerAsc:"点击升序",cancelSort:"取消排序"},Modal:{okText:"确定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"结束导览"},Popconfirm:{cancelText:"取消",okText:"确定"},Transfer:{titles:["",""],searchPlaceholder:"请输入搜索内容",itemUnit:"项",itemsUnit:"项",remove:"删除",selectCurrent:"全选当页",removeCurrent:"删除当页",selectAll:"全选所有",deselectAll:"取消全选",removeAll:"删除全部",selectInvert:"反选当页"},Upload:{uploading:"文件上传中",removeFile:"删除文件",uploadError:"上传错误",previewFile:"预览文件",downloadFile:"下载文件"},Empty:{description:"暂无数据"},Icon:{icon:"图标"},Text:{edit:"编辑",copy:"复制",copied:"复制成功",expand:"展开",collapse:"收起"},Form:{optional:"(可选)",defaultValidateMessages:{default:"字段验证错误${label}",required:"请输入${label}",enum:"${label}必须是其中一个[${enum}]",whitespace:"${label}不能为空字符",date:{format:"${label}日期格式无效",parse:"${label}不能转换为日期",invalid:"${label}是一个无效日期"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"${label}须为${len}个字符",min:"${label}最少${min}个字符",max:"${label}最多${max}个字符",range:"${label}须在${min}-${max}字符之间"},number:{len:"${label}必须等于${len}",min:"${label}最小值为${min}",max:"${label}最大值为${max}",range:"${label}须在${min}-${max}之间"},array:{len:"须为${len}个${label}",min:"最少${min}个${label}",max:"最多${max}个${label}",range:"${label}数量须在${min}-${max}之间"},pattern:{mismatch:"${label}与模式不匹配${pattern}"}}},Image:{preview:"预览"},QRCode:{expired:"二维码过期",refresh:"点击刷新",scanned:"已扫描"},ColorPicker:{presetEmpty:"暂无",transparent:"无色",singleColor:"单色",gradientColor:"渐变色"}};return To.default=i,To}var ec,Xp;function fI(){return Xp||(Xp=1,ec=pI()),ec}var gI=fI();const yI=vr(gI);var Eo={},Ro={},Vp;function bI(){if(Vp)return Ro;Vp=1,Object.defineProperty(Ro,"__esModule",{value:!0}),Ro.default=void 0;var e={items_per_page:"條/頁",jump_to:"跳至",jump_to_confirm:"確定",page:"頁",prev_page:"上一頁",next_page:"下一頁",prev_5:"向前 5 頁",next_5:"向後 5 頁",prev_3:"向前 3 頁",next_3:"向後 3 頁",page_size:"頁碼"};return Ro.default=e,Ro}var Ao={},Io={},$o={},Kp;function xI(){if(Kp)return $o;Kp=1;var e=tt().default;Object.defineProperty($o,"__esModule",{value:!0}),$o.default=void 0;var t=e(Cr()),s=Mr(),n=(0,t.default)((0,t.default)({},s.commonLocale),{},{locale:"zh_TW",today:"今天",now:"此刻",backToToday:"返回今天",ok:"確定",timeSelect:"選擇時間",dateSelect:"選擇日期",weekSelect:"選擇周",clear:"清除",week:"週",month:"月",year:"年",previousMonth:"上個月 (翻頁上鍵)",nextMonth:"下個月 (翻頁下鍵)",monthSelect:"選擇月份",yearSelect:"選擇年份",decadeSelect:"選擇年代",yearFormat:"YYYY年",dateFormat:"YYYY年M月D日",dateTimeFormat:"YYYY年M月D日 HH時mm分ss秒",previousYear:"上一年 (Control鍵加左方向鍵)",nextYear:"下一年 (Control鍵加右方向鍵)",previousDecade:"上一年代",nextDecade:"下一年代",previousCentury:"上一世紀",nextCentury:"下一世紀",cellDateFormat:"D",monthBeforeYear:!1});return $o.default=n,$o}var Do={},Gp;function Xb(){if(Gp)return Do;Gp=1,Object.defineProperty(Do,"__esModule",{value:!0}),Do.default=void 0;const e={placeholder:"請選擇時間"};return Do.default=e,Do}var Jp;function Vb(){if(Jp)return Io;Jp=1;var e=tt().default;Object.defineProperty(Io,"__esModule",{value:!0}),Io.default=void 0;var t=e(xI()),s=e(Xb());const n={lang:Object.assign({placeholder:"請選擇日期",yearPlaceholder:"請選擇年份",quarterPlaceholder:"請選擇季度",monthPlaceholder:"請選擇月份",weekPlaceholder:"請選擇周",rangePlaceholder:["開始日期","結束日期"],rangeYearPlaceholder:["開始年份","結束年份"],rangeMonthPlaceholder:["開始月份","結束月份"],rangeQuarterPlaceholder:["開始季度","結束季度"],rangeWeekPlaceholder:["開始周","結束周"]},t.default),timePickerLocale:Object.assign({},s.default)};return n.lang.ok="確 定",Io.default=n,Io}var Qp;function vI(){if(Qp)return Ao;Qp=1;var e=tt().default;Object.defineProperty(Ao,"__esModule",{value:!0}),Ao.default=void 0;var t=e(Vb());return Ao.default=t.default,Ao}var Zp;function SI(){if(Zp)return Eo;Zp=1;var e=tt().default;Object.defineProperty(Eo,"__esModule",{value:!0}),Eo.default=void 0;var t=e(bI()),s=e(vI()),n=e(Vb()),o=e(Xb());const a="${label}不是一個有效的${type}",i={locale:"zh-tw",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.default,global:{placeholder:"請選擇"},Table:{filterTitle:"篩選器",filterConfirm:"確定",filterReset:"重置",filterEmptyText:"無篩選項",filterCheckAll:"全選",filterSearchPlaceholder:"在篩選項中搜尋",emptyText:"暫無數據",selectAll:"全部選取",selectInvert:"反向選取",selectNone:"清空所有",selectionAll:"全選所有",sortTitle:"排序",expand:"展開行",collapse:"關閉行",triggerDesc:"點擊降序",triggerAsc:"點擊升序",cancelSort:"取消排序"},Modal:{okText:"確定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"結束導覽"},Popconfirm:{okText:"確定",cancelText:"取消"},Transfer:{titles:["",""],searchPlaceholder:"搜尋資料",itemUnit:"項目",itemsUnit:"項目",remove:"删除",selectCurrent:"全選當頁",removeCurrent:"删除當頁",selectAll:"全選所有",removeAll:"删除全部",selectInvert:"反選當頁"},Upload:{uploading:"正在上傳...",removeFile:"刪除檔案",uploadError:"上傳失敗",previewFile:"檔案預覽",downloadFile:"下载文件"},Empty:{description:"無此資料"},Icon:{icon:"圖標"},Text:{edit:"編輯",copy:"複製",copied:"複製成功",expand:"展開",collapse:"收起"},Form:{optional:"(可選)",defaultValidateMessages:{default:"字段驗證錯誤${label}",required:"請輸入${label}",enum:"${label}必須是其中一個[${enum}]",whitespace:"${label}不能為空字符",date:{format:"${label}日期格式無效",parse:"${label}不能轉換為日期",invalid:"${label}是一個無效日期"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"${label}須為${len}個字符",min:"${label}最少${min}個字符",max:"${label}最多${max}個字符",range:"${label}須在${min}-${max}字符之間"},number:{len:"${label}必須等於${len}",min:"${label}最小值為${min}",max:"${label}最大值為${max}",range:"${label}須在${min}-${max}之間"},array:{len:"須為${len}個${label}",min:"最少${min}個${label}",max:"最多${max}個${label}",range:"${label}數量須在${min}-${max}之間"},pattern:{mismatch:"${label}與模式不匹配${pattern}"}}},Image:{preview:"預覽"},QRCode:{expired:"二維碼過期",refresh:"點擊刷新",scanned:"已掃描"},ColorPicker:{presetEmpty:"暫無",transparent:"透明",singleColor:"單色",gradientColor:"漸變色"}};return Eo.default=i,Eo}var tc,ef;function wI(){return ef||(ef=1,tc=SI()),tc}var _I=wI();const TI=vr(_I),tf=e=>{switch(e){case"zh-CN":return yI;case"zh-TW":return TI;case"fr-FR":return GA;case"ja-JP":return dI;case"hi-IN":return nI;default:return UA}},kI="copilot_ui_theme_v1",Vc={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)"},Kc={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)"},Gc={Tag:{defaultBg:"rgba(13, 148, 136, 0.1)",defaultColor:"#0f766e"},Table:{bodySortBg:"rgba(13, 148, 136, 0.08)"}},Jc={Tag:{defaultBg:"rgba(45, 212, 191, 0.18)",defaultColor:"#ccfbf1"},Table:{bodySortBg:"rgba(45, 212, 191, 0.14)"}},sf={...Vc,colorBgElevated:"#ffffff",colorBgSpotlight:"#0f172a",colorFillTertiary:"#f3f7f6"},nf={...Kc,colorBgElevated:"#0f1b18",colorBgSpotlight:"#22332f",colorFillTertiary:"#162622"},rf={...Gc,Menu:{popupBg:"#ffffff",itemBg:"transparent",itemHoverBg:"#f3f7f6",itemActiveBg:"#eef7f5",itemSelectedBg:"#e7f8f4",subMenuItemBg:"#ffffff",dangerItemActiveBg:"#fdecec",dangerItemSelectedBg:"#fdecec"},Select:{selectorBg:"#ffffff",clearBg:"#ffffff",optionActiveBg:"#f3f7f6",optionSelectedBg:"#e7f8f4"},Modal:{contentBg:"#ffffff",headerBg:"#ffffff",footerBg:"#ffffff"}},of={...Jc,Menu:{popupBg:"#0f1b18",darkPopupBg:"#0f1b18",itemBg:"transparent",itemHoverBg:"#162622",itemActiveBg:"#162622",itemSelectedBg:"#12332d",subMenuItemBg:"#0f1b18",dangerItemActiveBg:"#3a161c",dangerItemSelectedBg:"#3a161c"},Select:{selectorBg:"#0f1b18",clearBg:"#0f1b18",optionActiveBg:"#162622",optionSelectedBg:"#12332d"},Modal:{contentBg:"#0f1b18",headerBg:"#0f1b18",footerBg:"#0f1b18"}};function jI(){const{t:e}=ne(),t=qn(w=>w.themeMode),s=qn(w=>w.setThemeMode),[n,o]=m.useState(()=>tx()),[a,i]=m.useState(()=>ji()),[l,c]=m.useState(null),[d,u]=m.useState(null),[h,p]=m.useState(0),[g,y]=m.useState(null),[f,v]=m.useState(!1);if(m.useEffect(()=>{localStorage.setItem(kI,t)},[t]),m.useEffect(()=>{localStorage.setItem(sx,n),es.changeLanguage(n)},[n]),m.useEffect(()=>{let w=!1;const k=Date.now(),C=async()=>{try{const E=fs.getInstance(),j=await E.getAccessStatus();if(w)return;if(u(null),y(j),j.requires_password&&!f){c(!1);return}const R=await E.getSetupStatus();if(w)return;c(R.is_complete)}catch(E){if(w)return;const j=Date.now()-k;if(j>=2e4){const T=kr(),P=E instanceof Error&&E.message.trim()?E.message:"Unknown error";u(e("app.backendNotReachable",{baseUrl:T,message:P}));return}const M=Math.min(500+Math.floor(j/2),2e3);setTimeout(()=>{w||C()},M)}};return C(),()=>{w=!0}},[f,h,e]),m.useEffect(()=>{document.body.setAttribute("data-theme",t)},[t]),m.useEffect(()=>{const w=()=>{const k=ji();i(k),document.body.setAttribute("data-vdi-safe",k?"true":"false");const C=document.getElementById("root");C&&C.setAttribute("data-vdi-safe",k?"true":"false")};return w(),window.addEventListener("storage",w),window.addEventListener("lotus-vdi-safe-mode-change",w),()=>{window.removeEventListener("storage",w),window.removeEventListener("lotus-vdi-safe-mode-change",w)}},[]),m.useEffect(()=>{var k;const w=(k=window.__TAURI_INTERNALS__)==null?void 0:k.invoke;typeof w=="function"&&w("set_window_theme",{theme:t}).catch(C=>{console.warn("[App] Failed to sync native window theme:",C)})},[t]),m.useEffect(()=>{l&&dS()},[l]),g!=null&&g.requires_password&&!f)return r.jsx(pu,{locale:tf(n),theme:{token:t==="dark"?a?nf:Kc:a?sf:Vc,algorithm:t==="dark"?he.darkAlgorithm:he.defaultAlgorithm,components:t==="dark"?a?of:Jc:a?rf:Gc},children:r.jsx(Ot,{children:r.jsx(ia,{name:"PasswordGatePage",children:r.jsx(IA,{verifyPassword:async w=>{await fs.getInstance().verifyAccessPassword(w)},onVerified:async()=>{v(!0),u(null),p(w=>w+1)}})})})});if(l===null)return d?r.jsxs("div",{style:{padding:40,textAlign:"center"},children:[r.jsx("div",{style:{marginBottom:12},children:d}),r.jsx(Y,{type:"primary",onClick:()=>{u(null),y(null),c(null),p(w=>w+1)},children:e("app.retry")})]}):r.jsx("div",{style:{padding:40,textAlign:"center"},children:e("app.loading")});const b=l?r.jsx(PA,{themeMode:t,onThemeModeChange:s,locale:n,onLocaleChange:o}):r.jsx(RA,{}),x=t==="dark"?a?nf:Kc:a?sf:Vc,_=t==="dark"?a?of:Jc:a?rf:Gc;return r.jsx(pu,{locale:tf(n),theme:{token:x,algorithm:t==="dark"?he.darkAlgorithm:he.defaultAlgorithm,components:_},children:r.jsx(Ot,{children:r.jsx(ia,{name:"App",children:r.jsx("div",{style:{position:"relative"},children:b})})})})}const WI=Object.freeze(Object.defineProperty({__proto__:null,default:jI},Symbol.toStringTag,{value:"Module"}));export{WI as A,ea as C,xe as a,st as d,Yn as p,N as u,uh as v,Uj as w};
|