@bigduu/lotus 2026.4.2 → 2026.4.5
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-CdZyL2eF.js +247 -0
- package/dist/assets/App-D7QWpCG1.css +1 -0
- package/dist/assets/{_basePickBy-BspK35sI.js → _basePickBy-Dqp2ckVn.js} +1 -1
- package/dist/assets/{_baseUniq-yd3d-av8.js → _baseUniq-BUM12Ss4.js} +1 -1
- package/dist/assets/{architectureDiagram-VXUJARFQ-CQvKJy3I.js → architectureDiagram-VXUJARFQ-BpD9cUnY.js} +1 -1
- package/dist/assets/{blockDiagram-VD42YOAC-DyFWUqNO.js → blockDiagram-VD42YOAC-DEjFbRgv.js} +1 -1
- package/dist/assets/{c4Diagram-YG6GDRKO-CznZpCeX.js → c4Diagram-YG6GDRKO-0zi7mvhd.js} +1 -1
- package/dist/assets/{chunk-4BX2VUAB-CT4-fTmw.js → chunk-4BX2VUAB-Ddghj6OV.js} +1 -1
- package/dist/assets/{chunk-55IACEB6-DPoGFWVp.js → chunk-55IACEB6-DjZcM2Bg.js} +1 -1
- package/dist/assets/{chunk-B4BG7PRW-zd34bnG8.js → chunk-B4BG7PRW-Co42sS8K.js} +1 -1
- package/dist/assets/{chunk-DI55MBZ5-DjYfBoqF.js → chunk-DI55MBZ5-LsurJteE.js} +1 -1
- package/dist/assets/{chunk-FMBD7UC4-BDz1nBzO.js → chunk-FMBD7UC4-DiR6-e10.js} +1 -1
- package/dist/assets/{chunk-QN33PNHL-ByHoXcdI.js → chunk-QN33PNHL-CBDhq4-P.js} +1 -1
- package/dist/assets/{chunk-QZHKN3VN-B58DhLEz.js → chunk-QZHKN3VN-BcUNnjmn.js} +1 -1
- package/dist/assets/{chunk-TZMSLE5B-CE3fOJae.js → chunk-TZMSLE5B-CD1yZj6g.js} +1 -1
- package/dist/assets/classDiagram-2ON5EDUG-XasLIOdg.js +1 -0
- package/dist/assets/classDiagram-v2-WZHVMYZB-XasLIOdg.js +1 -0
- package/dist/assets/clone-CHqNgpti.js +1 -0
- package/dist/assets/{cose-bilkent-S5V4N54A-CQMexX_7.js → cose-bilkent-S5V4N54A-B7QH9b8b.js} +1 -1
- package/dist/assets/{dagre-6UL2VRFP-Nr0JTfw1.js → dagre-6UL2VRFP-bN17fB73.js} +1 -1
- package/dist/assets/{diagram-PSM6KHXK-2zflANlw.js → diagram-PSM6KHXK-DKulEHRw.js} +1 -1
- package/dist/assets/{diagram-QEK2KX5R-VyZmBtmD.js → diagram-QEK2KX5R-j4St2Wso.js} +1 -1
- package/dist/assets/{diagram-S2PKOQOG-B2faf1Ft.js → diagram-S2PKOQOG-DXlK8Mf9.js} +1 -1
- package/dist/assets/{erDiagram-Q2GNP2WA-DTAG75D2.js → erDiagram-Q2GNP2WA-BHcDHhwN.js} +1 -1
- package/dist/assets/{flowDiagram-NV44I4VS-Bl2QKbsY.js → flowDiagram-NV44I4VS-DNrm79Yr.js} +1 -1
- package/dist/assets/{ganttDiagram-JELNMOA3-aVmOIbJd.js → ganttDiagram-JELNMOA3-DcHidoKj.js} +1 -1
- package/dist/assets/{gitGraphDiagram-V2S2FVAM-B0eXnYux.js → gitGraphDiagram-V2S2FVAM-CPCXl6MV.js} +1 -1
- package/dist/assets/{graph-D0JBNw5a.js → graph-Cy2rLZk-.js} +1 -1
- package/dist/assets/{index-CYzkseBh.js → index-BAfth62E.js} +1 -1
- package/dist/assets/{index-CMK42DTl.js → index-BKrbsGr5.js} +1 -1
- package/dist/assets/{index-BOUR4S6d.js → index-Bd-pro36.js} +1 -1
- package/dist/assets/{infoDiagram-HS3SLOUP-Cii6S1my.js → infoDiagram-HS3SLOUP-BZqSW0xG.js} +1 -1
- package/dist/assets/{journeyDiagram-XKPGCS4Q-C_iPmuQZ.js → journeyDiagram-XKPGCS4Q--y_9wXpx.js} +1 -1
- package/dist/assets/{kanban-definition-3W4ZIXB7-Cczg6lpg.js → kanban-definition-3W4ZIXB7-p0s79n5j.js} +1 -1
- package/dist/assets/{layout-DNfKd0n6.js → layout-BVyH__KO.js} +1 -1
- package/dist/assets/{main-BTCes_R0.js → main-ik_6ertt.js} +5 -5
- package/dist/assets/{mindmap-definition-VGOIOE7T-qYnf--6q.js → mindmap-definition-VGOIOE7T-gPtTWSZ4.js} +1 -1
- package/dist/assets/{pieDiagram-ADFJNKIX-CKiWkeBJ.js → pieDiagram-ADFJNKIX-DiMr3lFK.js} +1 -1
- package/dist/assets/{quadrantDiagram-AYHSOK5B-CWwC8LhP.js → quadrantDiagram-AYHSOK5B-CcRJwEm3.js} +1 -1
- package/dist/assets/{requirementDiagram-UZGBJVZJ--E3kDOu5.js → requirementDiagram-UZGBJVZJ-BJF8xk4W.js} +1 -1
- package/dist/assets/{sankeyDiagram-TZEHDZUN-DjNk0_tw.js → sankeyDiagram-TZEHDZUN-WtpnGB-d.js} +1 -1
- package/dist/assets/{sequenceDiagram-WL72ISMW-CP99d7Wl.js → sequenceDiagram-WL72ISMW-BFIpMf3h.js} +1 -1
- package/dist/assets/{stateDiagram-FKZM4ZOC-BpDaflbT.js → stateDiagram-FKZM4ZOC-CPIa7zUD.js} +1 -1
- package/dist/assets/stateDiagram-v2-4FDKWEC3-C3L-LCup.js +1 -0
- package/dist/assets/{timeline-definition-IT6M3QCI-JLPdh86G.js → timeline-definition-IT6M3QCI-D36RXKRq.js} +1 -1
- package/dist/assets/{treemap-GDKQZRPO-D7fekm60.js → treemap-GDKQZRPO-C5etdcHn.js} +1 -1
- package/dist/assets/{vendor-charts-B5wo7wyK.js → vendor-charts-JINLUr-T.js} +1 -1
- package/dist/assets/{vendor-mermaid-CuzF-D1I.js → vendor-mermaid-7RLh-Mwz.js} +4 -4
- package/dist/assets/{vendor-pdf-DKSPuLa9.js → vendor-pdf-5uNnaI3-.js} +2 -2
- package/dist/assets/{xychartDiagram-PRI3JC2R-DFMu-kfv.js → xychartDiagram-PRI3JC2R-CHD9X5Zq.js} +1 -1
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/dist/assets/App-BHPFe35o.js +0 -247
- package/dist/assets/App-CWKFDTQi.css +0 -1
- package/dist/assets/classDiagram-2ON5EDUG-BrIAA29n.js +0 -1
- package/dist/assets/classDiagram-v2-WZHVMYZB-BrIAA29n.js +0 -1
- package/dist/assets/clone-UExS44xq.js +0 -1
- package/dist/assets/stateDiagram-v2-4FDKWEC3-C4ikui-V.js +0 -1
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-BKrbsGr5.js","./vendor-markdown-BtOz1kLl.js","./vendor-i18n-BNURlJ23.js","./vendor-antd-BlMATH2j.js","./main-ik_6ertt.js","./main-B6snAd4S.css","./vendor-charts-JINLUr-T.js","./vendor-mermaid-7RLh-Mwz.js","./index-Cd0gm8C7.js","./index-Bd-pro36.js","./index-Bi-vGirQ.css","./index-BAfth62E.js","./index-oVXhS3BO.js","./index-BmjFP0ha.js","./core-Cfh-QHsP.js","./index-_XI0Qq6F.js","./vendor-pdf-5uNnaI3-.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var Ax=Object.defineProperty;var Ix=(e,t,s)=>t in e?Ax(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var Ye=(e,t,s)=>Ix(e,typeof t!="symbol"?t+"":t,s);import{j as r,M as vs,r as ki,h as pr,_ as Ft,S as ft,a as Op,t as zp,p as Np,b as $x,c as Hc,d as Dx,m as Bp,s as Fx,y as Wp,e as Up,f as Yc,g as Xc,i as qp}from"./vendor-markdown-BtOz1kLl.js";import{R as pt,i as as,u as se,a as m,g as br}from"./vendor-i18n-BNURlJ23.js";import{r as Lx,A as Ox}from"./main-ik_6ertt.js";import{S as H,B as U,C as ee,n as ce,L as nt,Y as is,T as oe,Z as zx,$ as Vc,a0 as ls,l as fe,M as Lt,E as Pt,a1 as vr,t as pe,a2 as Jl,a3 as Kc,j as Sr,O as ra,a4 as Hp,k as yn,H as Nx,p as wr,a5 as fr,a6 as Bx,I as he,K as J,a7 as cs,a8 as Ks,i as Gs,a9 as ji,o as ke,aa as Wx,ab as Ux,ac as us,ad as Yp,ae as Qo,af as qx,ag as Ci,A as Ne,u as Fs,v as ht,ah as Fe,V as Dt,ai as ws,aj as ei,ak as ct,F as Z,al as ss,am as Le,an as Ot,ao as ot,ap as Hx,P as ti,aq as oa,ar as Xp,as as Mi,at as Kd,au as Js,av as Yx,aw as Pi,ax as Ql,ay as At,az as Xx,aA as en,aB as at,aC as Gc,aD as Gd,Q as Qs,aE as Zs,aF as Vx,aG as Kx,aH as Zl,aI as Yi,G as Gx,aJ as dr,aK as Vp,aL as Jd,aM as gr,aN as Jx,aO as Qx,m as yr,aP as Jc,U as Ei,aQ as Zx,aR as eb,aS as Kp,aT as Qc,aU as Gp,aV as Jp,aW as tb,aX as sb,aY as nb,aZ as rb,a_ as ob,a$ as ab,b0 as ib,b1 as Qp,b2 as Zp,x as ef,q as si,b3 as Zc,w as lb,b4 as cb,b5 as db,N as ub,b6 as mb,b7 as hb,b8 as pb,b9 as fb,ba as tf,bb as sf,bc as gb,bd as yb,be as ed,bf as xb,bg as bb,bh as ni,bi as Qd,bj as nf,bk as Zd,bl as vb,bm as Sb,bn as wb,bo as _b,bp as rf,bq as Tb,br as kb,bs as jb}from"./vendor-antd-BlMATH2j.js";import{Z as _r,_ as td,$ as aa,a0 as ia,a1 as la,a2 as Tr,a3 as sd,a4 as ri,a5 as of,a6 as ur,a7 as Cb,a8 as Mb,a9 as Pb}from"./vendor-charts-JINLUr-T.js";import{b9 as nd}from"./vendor-mermaid-7RLh-Mwz.js";const Eb=({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(H,{...a,children:e.map(i=>r.jsx(U,{type:i.type||"default",disabled:i.disabled,loading:i.loading,danger:i.danger,onClick:i.onClick,size:n,icon:i.icon,children:i.text},i.key))})},Rb=(e,t)=>({key:"cancel",text:t||"Cancel",type:"default",onClick:e}),Ab=(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}),eu=e=>{let t;const s=new Set,n=(d,u)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const f=t;t=u??(typeof h!="object"||h===null)?h:Object.assign({},t,h),s.forEach(g=>g(t,f))}},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},Ib=e=>e?eu(e):eu,$b=e=>e;function Db(e,t=$b){const s=pt.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return pt.useDebugValue(s),s}const tu=e=>{const t=Ib(e),s=n=>Db(t,n);return Object.assign(s,t),s},xn=e=>e?tu(e):tu,su={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},Zo=new Map,xa=e=>{const t=Zo.get(e);return t?Object.fromEntries(Object.entries(t.stores).map(([s,n])=>[s,n.getState()])):{}},Fb=(e,t,s)=>{if(e===void 0)return{type:"untracked",connection:t.connect(s)};const n=Zo.get(s.name);if(n)return{type:"tracked",store:e,...n};const o={connection:t.connect(s),stores:{}};return Zo.set(s.name,o),{type:"tracked",store:e,...o}},Lb=(e,t)=>{if(t===void 0)return;const s=Zo.get(e);s&&(delete s.stores[t],Object.keys(s.stores).length===0&&Zo.delete(e))},Ob=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]},zb=(e,t={})=>(s,n,o)=>{const{enabled:a,anonymousActionType:i,store:l,...c}=t;let d;try{d=(a??(su?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!d)return e(s,n,o);const{connection:u,...h}=Fb(l,d,c);let f=!0;o.setState=(p,x,b)=>{const S=s(p,x);if(!f)return S;const w=b===void 0?{type:i||Ob(new Error().stack)||"anonymous"}:typeof b=="string"?{type:b}:b;return l===void 0?(u==null||u.send(w,n()),S):(u==null||u.send({...w,type:`${l}/${w.type}`},{...xa(c.name),[l]:o.getState()}),S)},o.devtools={cleanup:()=>{u&&typeof u.unsubscribe=="function"&&u.unsubscribe(),Lb(c.name,l)}};const g=(...p)=>{const x=f;f=!1,s(...p),f=x},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(([p,x])=>[p,p===h.store?y:x.getState()])))),o.dispatchFromDevtools&&typeof o.dispatch=="function"){let p=!1;const x=o.dispatch;o.dispatch=(...b)=>{(su?"production":void 0)!=="production"&&b[0].type==="__setState"&&!p&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),p=!0),x(...b)}}return u.subscribe(p=>{var x;switch(p.type){case"ACTION":if(typeof p.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return Xi(p.payload,b=>{if(b.type==="__setState"){if(l===void 0){g(b.state);return}Object.keys(b.state).length!==1&&console.error(`
|
|
4
|
+
[zustand devtools middleware] Unsupported __setState action format.
|
|
5
|
+
When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
|
|
6
|
+
and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
|
|
7
|
+
`);const S=b.state[l];if(S==null)return;JSON.stringify(o.getState())!==JSON.stringify(S)&&g(S);return}o.dispatchFromDevtools&&typeof o.dispatch=="function"&&o.dispatch(b)});case"DISPATCH":switch(p.payload.type){case"RESET":return g(y),l===void 0?u==null?void 0:u.init(o.getState()):u==null?void 0:u.init(xa(c.name));case"COMMIT":if(l===void 0){u==null||u.init(o.getState());return}return u==null?void 0:u.init(xa(c.name));case"ROLLBACK":return Xi(p.state,b=>{if(l===void 0){g(b),u==null||u.init(o.getState());return}g(b[l]),u==null||u.init(xa(c.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return Xi(p.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}=p.payload,S=(x=b.computedStates.slice(-1)[0])==null?void 0:x.state;if(!S)return;g(l===void 0?S:S[l]),u==null||u.send(null,b);return}case"PAUSE_RECORDING":return f=!f}return}}),y},Nb=zb,Xi=(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)},Bb=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=f=>{const g=i(f);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)},Wb=Bb;function Ub(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 ec=e=>t=>{try{const s=e(t);return s instanceof Promise?s:{then(n){return ec(n)(s)},catch(n){return this}}}catch(s){return{then(n){return this},catch(n){return ec(n)(s)}}}},qb=(e,t)=>(s,n,o)=>{let a={storage:Ub(()=>localStorage),partialize:p=>p,version:0,merge:(p,x)=>({...x,...p}),...t},i=!1;const l=new Set,c=new Set;let d=a.storage;if(!d)return e((...p)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),s(...p)},n,o);const u=()=>{const p=a.partialize({...n()});return d.setItem(a.name,{state:p,version:a.version})},h=o.setState;o.setState=(p,x)=>{h(p,x),u()};const f=e((...p)=>{s(...p),u()},n,o);o.getInitialState=()=>f;let g;const y=()=>{var p,x;if(!d)return;i=!1,l.forEach(S=>{var w;return S((w=n())!=null?w:f)});const b=((x=a.onRehydrateStorage)==null?void 0:x.call(a,(p=n())!=null?p:f))||void 0;return ec(d.getItem.bind(d))(a.name).then(S=>{if(S)if(typeof S.version=="number"&&S.version!==a.version){if(a.migrate){const w=a.migrate(S.state,S.version);return w instanceof Promise?w.then(k=>[!0,k]):[!0,w]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,S.state];return[!1,void 0]}).then(S=>{var w;const[k,j]=S;if(g=a.merge(j,(w=n())!=null?w:f),s(g,!0),k)return u()}).then(()=>{b==null||b(g,void 0),g=n(),i=!0,c.forEach(S=>S(g))}).catch(S=>{b==null||b(void 0,S)})};return o.persist={setOptions:p=>{a={...a,...p},p.storage&&(d=p.storage)},clearStorage:()=>{d==null||d.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>y(),hasHydrated:()=>i,onHydrate:p=>(l.add(p),()=>{l.delete(p)}),onFinishHydration:p=>(c.add(p),()=>{c.delete(p)})},a.skipHydration||y(),g||f},Hb=qb,af=()=>!1,lf=e=>{if(!af())return!1;try{return localStorage.getItem(e)==="1"}catch{return!1}},Yb=()=>lf("bodhi_debug_ui_layout"),ns=(e,t)=>{Yb()&&console.log(`[ui-layout] ${e}`,t??"")},Ke=(e,t,...s)=>{af()&&lf("bodhi_debug_verbose")&&console.log(`${e} ${t}`,...s)};var Vi={};const nu="copilot_backend_base_url",Xb="http://127.0.0.1:9562/v1",cf=e=>e.trim().replace(/\/+$/,""),Vb=()=>{const t=Vi==null?void 0:Vi.VITE_BACKEND_BASE_URL;return t?cf(t):Xb},kr=()=>{const e=localStorage.getItem(nu);if(e){const t=cf(e);try{return new URL(t),t}catch{console.warn("Invalid stored backend URL, using default:",t),localStorage.removeItem(nu)}}return Vb()};class Wn extends Error{constructor(t,s,n,o){super(t),this.status=s,this.statusText=n,this.body=o,this.name="ApiError"}}function Kb(e){return e instanceof Wn}class rd{constructor(t={}){Ye(this,"baseUrl");Ye(this,"defaultHeaders");this.baseUrl=t.baseUrl??this.resolveBaseUrl(),this.defaultHeaders=t.defaultHeaders??{"Content-Type":"application/json"}}resolveBaseUrl(){let 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 Wn(l,t.status,t.statusText,i)}return t.status===204?void 0:(((a=(o=t.headers)==null?void 0:o.get)==null?void 0:a.call(o,"content-type"))||"").includes("application/json")?t.json():typeof t.text=="function"?await t.text():t.json()}delay(t){return new Promise(s=>setTimeout(s,t))}async fetchWithRetry(t,s,n=3){let o=null;for(let a=0;a<n;a++)try{const i=await fetch(t,s);if(i.status>=500&&a<n-1){const l=1e3*Math.pow(2,a);console.warn(`Request failed with ${i.status}, retrying in ${l}ms (attempt ${a+1}/${n})`),await this.delay(l);continue}return i}catch(i){if(o=i,a<n-1){const l=1e3*Math.pow(2,a);console.warn(`Network error: ${o.message}, retrying in ${l}ms (attempt ${a+1}/${n})`),await this.delay(l)}}throw o||new Error("Max retries exceeded")}async get(t,s){const n=this.buildUrl(t),o=new AbortController,a=setTimeout(()=>o.abort(),3e4);try{const i=await this.fetchWithRetry(n,{...s,method:"GET",headers:{...this.defaultHeaders,...s==null?void 0:s.headers},signal:o.signal},3);return this.handleResponse(i)}finally{clearTimeout(a)}}async post(t,s,n){const o=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(o,{...n,method:"POST",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},body:s?JSON.stringify(s):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async put(t,s,n){const o=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(o,{...n,method:"PUT",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},body:s?JSON.stringify(s):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async patch(t,s,n){const o=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(o,{...n,method:"PATCH",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},body:s?JSON.stringify(s):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async delete(t,s){const n=this.buildUrl(t),o=new AbortController,a=setTimeout(()=>o.abort(),3e4);try{const i=await this.fetchWithRetry(n,{...s,method:"DELETE",headers:{...this.defaultHeaders,...s==null?void 0:s.headers},signal:o.signal},3);return this.handleResponse(i)}finally{clearTimeout(a)}}async request(t,s,n){const o=this.buildUrl(s),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(o,{...n,method:t,headers:{...this.defaultHeaders,...n==null?void 0:n.headers},signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async fetchRaw(t,s){const n=this.buildUrl(t),o=await fetch(n,{...s,headers:{...this.defaultHeaders,...s==null?void 0:s.headers}});if(!o.ok)throw new Wn(`API request failed: ${o.statusText}`,o.status,o.statusText);return o}}const we=new rd,ye=new rd({baseUrl:(()=>{let e=kr().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`})()});function Gb(e){return e instanceof Wn}const In=class In{static getInstance(){return In.instance||(In.instance=new In),In.instance}async sendMessage(t){return ye.post("chat",t)}async execute(t,s,n,o){const a={};return s&&(a.model=s),n&&(a.reasoning_effort=n),o&&(a.client_sync=o),ye.post(`execute/${t}`,a)}async listSessions(){return ye.get("sessions")}async createSession(t){return ye.post("sessions",t)}async patchSession(t,s){const n=encodeURIComponent(t);await ye.patch(`sessions/${n}`,s)}async getSessionSystemPrompt(t){const s=encodeURIComponent(t);return ye.get(`sessions/${s}/system-prompt`)}async clearSession(t){const s=encodeURIComponent(t);await ye.post(`sessions/${s}/clear`)}async truncateSessionMessages(t,s){const n=encodeURIComponent(t);return ye.post(`sessions/${n}/messages/truncate`,s)}async restoreSessionState(t,s){const n=encodeURIComponent(t);return ye.post(`sessions/${n}/restore`,s)}async patchSessionMessage(t,s,n){const o=encodeURIComponent(t),a=encodeURIComponent(s);await ye.patch(`sessions/${o}/messages/${a}`,n)}async deleteSessionMessage(t,s){const n=encodeURIComponent(t),o=encodeURIComponent(s);await ye.delete(`sessions/${n}/messages/${o}`)}async cleanupSessions(t,s){await ye.post("sessions/cleanup",{mode:t,keep_pinned:s})}async devResetSessions(){await ye.post("dev/reset")}async listSchedules(){return ye.get("schedules")}async createSchedule(t){return ye.post("schedules",t)}async patchSchedule(t,s){const n=encodeURIComponent(t);return ye.patch(`schedules/${n}`,s)}async deleteSchedule(t){const s=encodeURIComponent(t);await ye.delete(`schedules/${s}`)}async runScheduleNow(t){const s=encodeURIComponent(t);await ye.post(`schedules/${s}/run`)}async listScheduleSessions(t){const s=encodeURIComponent(t);return ye.get(`schedules/${s}/sessions`)}async listScheduleRuns(t){const s=encodeURIComponent(t);return ye.get(`schedules/${s}/runs`)}async subscribeToEvents(t,s,n){var a;const o=n==null?void 0:n.signal;Ke("[AgentClient]","[AgentClient] Subscribing to events for session:",t);try{const i=await ye.fetchRaw(`events/${t}`,{signal:o});if(Ke("[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 f=JSON.parse(h);u=f.error||f.message||f.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 f=d.split(`
|
|
8
|
+
`);d=f.pop()||"";for(const g of f)if(g.startsWith("data: ")){const y=g.slice(6);if(y==="[DONE]")return;try{const p=JSON.parse(y);this.handleEvent(p,s)}catch(p){console.warn("Failed to parse event:",y,p)}}}}finally{l.releaseLock()}}catch(i){if(o!=null&&o.aborted){Ke("[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,f,g,y,p,x,b,S,w,k,j,C,P;switch(t.type){case"token":(n=s.onToken)==null||n.call(s,t.content||"");break;case"reasoning_token":(o=s.onReasoningToken)==null||o.call(s,t.content||"");break;case"tool_token":(a=s.onToolToken)==null||a.call(s,t.tool_call_id||"",t.content||"");break;case"tool_start":(i=s.onToolStart)==null||i.call(s,t.tool_call_id||"",t.tool_name||"",t.arguments||{});break;case"tool_complete":t.result&&((l=s.onToolComplete)==null||l.call(s,t.tool_call_id||"",t.result));break;case"tool_error":(c=s.onToolError)==null||c.call(s,t.tool_call_id||"",t.error||"");break;case"task_list_updated":t.task_list&&((d=s.onTaskListUpdated)==null||d.call(s,t.task_list));break;case"task_list_item_progress":if(t.session_id&&t.item_id&&t.status&&t.tool_calls_count!==void 0&&t.version!==void 0){const v=t.status;if(!(v==="pending"||v==="in_progress"||v==="completed"||v==="blocked"))break;(u=s.onTaskListItemProgress)==null||u.call(s,{session_id:t.session_id,item_id:t.item_id,status:v,tool_calls_count:t.tool_calls_count,version:t.version})}break;case"task_list_completed":t.session_id&&t.total_rounds!==void 0&&t.total_tool_calls!==void 0&&((h=s.onTaskListCompleted)==null||h.call(s,t.session_id,t.total_rounds,t.total_tool_calls));break;case"task_evaluation_started":t.session_id&&t.items_count!==void 0&&((f=s.onTaskEvaluationStarted)==null||f.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"&&((p=s.onContextCompressionStatus)==null||p.call(s,t.phase,t.status));break;case"tool_lifecycle":(x=s.onToolLifecycle)==null||x.call(s,t.tool_call_id||"",t.tool_name||"",t.phase||"",t.elapsed_ms,t.is_mutating,t.auto_approved,t.summary,t.error);break;case"context_summarized":t.summary_info&&((b=s.onContextSummarized)==null||b.call(s,t.summary_info));break;case"sub_session_started":t.parent_session_id&&t.child_session_id&&((S=s.onSubSessionStarted)==null||S.call(s,t.parent_session_id,t.child_session_id,t.title));break;case"sub_session_event":t.parent_session_id&&t.child_session_id&&t.event&&((w=s.onSubSessionEvent)==null||w.call(s,t.parent_session_id,t.child_session_id,t.event));break;case"sub_session_heartbeat":t.parent_session_id&&t.child_session_id&&t.timestamp&&((k=s.onSubSessionHeartbeat)==null||k.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&&((j=s.onSubSessionCompleted)==null||j.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":(P=s.onError)==null||P.call(s,t.message||t.error||"Unknown error");break;default:console.warn("Unknown event type:",t)}}async stopGeneration(t){await ye.post(`stop/${t}`)}async deleteSession(t){const s=encodeURIComponent(t);await ye.delete(`sessions/${s}`)}async getHistory(t){return ye.get(`history/${t}`)}async healthCheck(){try{return await ye.get("health"),!0}catch{return!1}}};Ye(In,"instance");let Ss=In;const Un=Ss.getInstance(),Jb=()=>({id:"general_assistant",name:"Bodhi",description:as.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}),oi=()=>[Jb()];class Qb{async getProviderConfig(){return we.get("/bamboo/settings/provider")}async saveProviderConfig(t){return we.post("/bamboo/settings/provider",t)}async reloadConfig(){return we.post("/bamboo/settings/reload")}async getCopilotAuthStatus(){return we.post("/bamboo/copilot/auth/status")}async startCopilotAuth(){return we.post("/bamboo/copilot/auth/start")}async completeCopilotAuth(t){return we.post("/bamboo/copilot/auth/complete",t)}async authenticateCopilot(){return we.post("/bamboo/copilot/authenticate")}async logoutCopilot(){return we.post("/bamboo/copilot/logout")}async fetchProviderModels(t){return(await we.post("/bamboo/settings/provider/models",{provider:t})).models}async getEnvVars(){return we.get("/bamboo/env-vars")}async upsertEnvVar(t){return we.post("/bamboo/env-vars",t)}async deleteEnvVar(t){return we.delete(`/bamboo/env-vars/${encodeURIComponent(t)}`)}async replaceEnvVars(t){return we.post("/bamboo/env-vars/replace",{entries:t})}}const $t=new Qb,Yt=xn((e,t)=>({currentProvider:"copilot",providerConfig:{provider:"copilot",providers:{}},isLoading:!1,error:null,loadProviderConfig:async()=>{e({isLoading:!0,error:null});try{const s=await $t.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()}})),Zb=Object.freeze(Object.defineProperty({__proto__:null,useProviderStore:Yt},Symbol.toStringTag,{value:"Module"})),ru="copilot_auto_generate_titles",nn=Ss.getInstance(),mr=oi()[0],ev=(mr==null?void 0:mr.id)||"general_assistant";var Lp;const df=((Lp=mr==null?void 0:mr.content)==null?void 0:Lp.trim())||"",Ki="tool",ou=e=>{if(typeof e!="string"||!e.trim())return null;const t=Date.parse(e);return Number.isFinite(t)?t:null},tv=()=>{try{const e=globalThis.crypto;if(e!=null&&e.randomUUID)return e.randomUUID()}catch{}return`id_${Date.now()}_${Math.random().toString(16).slice(2)}`},sv=()=>{let e=kr().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`},uf=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}},nv=e=>{const t=uf(e);return t?`${sv()}/sessions/${encodeURIComponent(t.sessionId)}/attachments/${encodeURIComponent(t.attachmentId)}`:e},En=e=>{if(typeof e!="string")return;const t=e.trim();if(t&&t.toLowerCase()!=="unknown")return t},rv=e=>{const t=(e||"").trim();if(!t)return;const s=t.match(/tool policy blocked ['"`]([^'"`]+)['"`]/i);if(s!=null&&s[1])return En(s[1]);try{const n=JSON.parse(t);if(typeof(n==null?void 0:n.tool_name)=="string")return En(n.tool_name)}catch{}},Gi=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||as.t("chat.session.defaultTitle"),createdAt:t,pinned:e.pinned,messages:[],config:{systemPromptId:ev,baseSystemPrompt:df,lastUsedEnhancedPrompt:null,model:e.model,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}},ov=(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 f={role:"system",id:u.id,createdAt:h,content:u.content||"",isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(f);continue}if(u.role==="user"){const f=new Map;for(const p of u.image_ocr||[]){const x=(a=p.image_url)==null?void 0:a.trim();if(!x)continue;const S=(p.lines||[]).map(w=>((w==null?void 0:w.text)||"").trim()).filter(Boolean);f.set(x,{ocrText:S.length?S.join(`
|
|
12
|
+
`):void 0,ocrError:p.error?String(p.error):void 0})}const g=[];for(const p of u.content_parts||[]){if(p.type!=="image_url")continue;const x=((i=p.image_url)==null?void 0:i.url)||"";if(!x)continue;const b=nv(x),S=uf(x),w=f.get(x.trim());g.push({id:tv(),url:b,ocrText:w==null?void 0:w.ocrText,ocrError:w==null?void 0:w.ocrError,name:S?`attachment-${S.attachmentId}`:"image",size:0,type:"image/*"})}const y={role:"user",id:u.id,createdAt:h,content:u.content||"",images:g.length?g:void 0,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(y);continue}if(u.role==="assistant"){const f=u.tool_calls||[];if(f.length>0){const p=(u.content||"").trim(),x=typeof u.reasoning=="string"&&u.reasoning.trim().length>0;if(p||x){const k=x?{reasoning:u.reasoning,backendMessageId:u.id}:{backendMessageId:u.id},j={role:"assistant",type:"text",id:`${u.id}_text`,createdAt:h,content:u.content||"",metadata:k,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(j)}for(const k of f)k.id&&s.set(k.id,En((l=k.function)==null?void 0:l.name)||Ki);const b=(c=f[0])==null?void 0:c.id,S=b?n.get(b):void 0,w={role:"assistant",type:"tool_call",id:u.id,createdAt:h,toolCalls:f.map(k=>{var j;return{toolCallId:k.id,toolName:En((j=k.function)==null?void 0:j.name)||Ki,parameters:(()=>{var C,P;try{return JSON.parse(((C=k.function)==null?void 0:C.arguments)||"{}")}catch{return{raw:((P=k.function)==null?void 0:P.arguments)||""}}})(),streamingOutput:""}}),...S?{metadata:S}:{},isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(w);continue}const g=typeof u.reasoning=="string"&&u.reasoning.trim().length>0?{reasoning:u.reasoning}:{},y={role:"assistant",type:"text",id:u.id,createdAt:h,content:u.content||"",metadata:g,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(y);continue}if(u.role==="tool"){const f=((d=u.tool_call_id)==null?void 0:d.trim())||`orphan-tool-call:${u.id}`,g=En(s.get(f))||En(u.tool_name)||En(u.name)||rv(u.content)||Ki,y=u.tool_success===!1||u.tool_success==null&&typeof u.content=="string"&&u.content.trimStart().startsWith("Error:"),p={role:"assistant",type:"tool_result",id:u.id,createdAt:h,toolName:g,toolCallId:f,result:{tool_name:g,result:u.content||"",display_preference:"Default"},isError:y,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(p);continue}}return o},av=(e,t)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,processingChats:new Set,autoGenerateTitles:!0,isUpdatingAutoTitlePreference:!1,subSessionsByParent:{},addChat:async s=>{var u,h,f,g,y,p;const n=(s.title||as.t("chat.sidebar.newSession")).trim(),o=((h=(u=s.config)==null?void 0:u.baseSystemPrompt)==null?void 0:h.trim())||"",a=(f=Yt.getState().getActiveModel())==null?void 0:f.trim(),i=((y=(g=s.config)==null?void 0:g.model)==null?void 0:y.trim())||a||void 0,l=((p=s.config)==null?void 0:p.reasoningEffort)??void 0,c=await nn.createSession({title:n,system_prompt:o||void 0,model:i,reasoning_effort:l||void 0}),d={...Gi(c.session),title:n,config:{...s.config,model:c.session.model,reasoningEffort:c.session.reasoning_effort??null,baseSystemPrompt:o||df},messages:[],currentInteraction:null};return e(x=>{const b=[d,...x.chats.filter(S=>S.id!==d.id)];return{...x,chats:b,currentSessionId:d.id,latestActiveSessionId:d.id}}),d.id},selectSession:s=>{const n=t();n.currentSessionId===s&&n.latestActiveSessionId===s||e({currentSessionId:s,latestActiveSessionId:s})},deleteSession:async s=>{try{await nn.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,"reasoningEffort")){const d=n.config.reasoningEffort;d?c.reasoning_effort=d:c.clear_reasoning_effort=!0}Object.keys(c).length>0&&nn.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 nn.deleteSessionMessage(s,n)}catch(a){return console.warn(`[ChatSlice] Failed to delete message ${n} from session ${s}:`,a),a instanceof Wn?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 nn.listSessions()).sessions.map(Gi);e(o=>{const a=new Map(o.chats.map(l=>[l.id,l])),i=n.map(l=>{var x,b,S,w;const c=a.get(l.id);if(!c)return l;const d=ou(c.updatedAt),u=ou(l.updatedAt),h=d!==null&&u!==null&&d>u,f=c.config||{},g=l.config||{},y=Object.prototype.hasOwnProperty.call(f,"model"),p=Object.prototype.hasOwnProperty.call(f,"reasoningEffort");return{...l,title:h?c.title:l.title,pinned:h?c.pinned:l.pinned,updatedAt:h?c.updatedAt:l.updatedAt,messages:c.messages,config:{...f,...g,model:h&&y?f.model:g.model,reasoningEffort:h&&p?f.reasoningEffort:g.reasoningEffort,compressionEvents:((x=c.config)==null?void 0:x.compressionEvents)??((b=l.config)==null?void 0:b.compressionEvents),syncCursor:((S=c.config)==null?void 0:S.syncCursor)??((w=l.config)==null?void 0:w.syncCursor)}}});return{...o,chats:i}})},loadChats:async()=>{var l;const s=localStorage.getItem(ru),n=s===null?t().autoGenerateTitles:s==="true";let o=await nn.listSessions();(!o.sessions||o.sessions.length===0)&&(o={sessions:[(await nn.createSession({title:as.t("chat.sidebar.newSession")})).session]});const a=o.sessions.map(Gi),i=((l=a[0])==null?void 0:l.id)??null;e({chats:a,latestActiveSessionId:i,currentSessionId:i,processingChats:new Set,autoGenerateTitles:n}),i&&await t().loadChatHistory(i)},loadChatHistory:async(s,n)=>{var l,c,d,u,h,f,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 p=t().chats.find(w=>w.id===s);if(!p)return;const x=await nn.getHistory(s),b=(l=x.messages[x.messages.length-1])==null?void 0:l.role;if(n!=null&&n.waitForAssistant&&b==="user"&&y<a){const w=i>0?i*(y+1):200*(y+1);await new Promise(k=>setTimeout(k,w));continue}const S=ov(s,x.messages);if(o==="monotonic"){const w=p.messages||[],k=w.length,j=S.length,C=(c=S[S.length-1])==null?void 0:c.role,P=(d=w[w.length-1])==null?void 0:d.role,v=w[w.length-1],M=S[S.length-1],E=v==null?void 0:v.id,_=M==null?void 0:M.id;let R=!1;if(j>k?R=!0:j===k&&(R=P==="user"&&C!=="user"||typeof E=="string"&&typeof _=="string"&&E!==_),!R){t().updateSession(s,{messageCount:Math.max(p.messageCount??0,x.messages.length)});return}}t().updateSession(s,{messages:S,messageCount:x.messages.length,config:{...p.config||{},compressionEvents:(x.compression_events||[]).map(w=>({id:w.id,createdAt:w.created_at,messagesCompressed:w.messages_compressed,segmentsRemoved:w.segments_removed})),syncCursor:{messageCount:x.messages.length,lastMessageId:((u=x.messages[x.messages.length-1])==null?void 0:u.id)??null,hasPendingQuestion:((h=t().pendingQuestionRespond)==null?void 0:h.sessionId)===s,pendingQuestionToolCallId:((f=t().pendingQuestionRespond)==null?void 0:f.sessionId)===s?((g=t().pendingQuestionRespond)==null?void 0:g.toolCallId)??null:null}}});return}catch(p){if(y>=a){console.warn(`[ChatSlice] Failed to load history for ${s}:`,p);return}const x=i>0?i*(y+1):200*(y+1);await new Promise(b=>setTimeout(b,x))}},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(ru,String(s))}catch(o){throw console.warn("[ChatSlice] Failed to update auto-title preference:",o),e({autoGenerateTitles:n}),o}finally{e({isUpdatingAutoTitlePreference:!1})}}});class ai extends Error{constructor(s="Proxy authentication required"){super(s);Ye(this,"code","proxy_auth_required");this.name="ProxyAuthRequiredError"}}const $n=class $n{constructor(){}static getInstance(){return $n.instance||($n.instance=new $n),$n.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 rd({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 Wn){if(n.status===428)throw new ai(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 ai(((s=o.error)==null?void 0:s.message)||n.message)}throw n}}};Ye($n,"instance");let ii=$n;const Ri=ii.getInstance(),iv=Object.freeze(Object.defineProperty({__proto__:null,ModelService:ii,ProxyAuthRequiredError:ai,modelService:Ri},Symbol.toStringTag,{value:"Module"})),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)},cv=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")},ds=async e=>{try{await lv(e);return}catch(t){try{cv(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 dv{async copyToClipboard(t){await ds(t)}async getBambooConfig(){try{return await we.get("bamboo/config")}catch(t){return console.error("Failed to fetch Bamboo config:",t),{}}}async getBambooTools(){try{return await we.get("bamboo/tools")}catch(t){return console.error("Failed to fetch Bamboo tools:",t),{tools:[]}}}async getModelLimitDefaults(){try{return await we.get("bamboo/model-limits/defaults")}catch(t){return console.error("Failed to fetch model limit defaults:",t),{model_limits:[]}}}async setBambooConfig(t){return we.post("bamboo/config",t)}async validateBambooConfigPatch(t){return we.post("bamboo/config/validate",t)}async setProxyAuth(t){return we.post("bamboo/proxy-auth",t)}async getProxyAuthStatus(){try{return await we.get("bamboo/proxy-auth/status")}catch(t){return console.error("Failed to fetch proxy auth status:",t),{configured:!1,username:null}}}async clearProxyAuth(){return we.post("bamboo/proxy-auth",{username:"",password:""})}async getAnthropicModelMapping(){try{return await we.get("bamboo/anthropic-model-mapping")}catch(t){return console.error("Failed to fetch Anthropic model mapping:",t),{mappings:{}}}}async setAnthropicModelMapping(t){return we.post("bamboo/anthropic-model-mapping",t)}async resetBambooConfig(){return we.post("bamboo/config/reset",{})}async saveWorkflow(t,s){return we.post("bamboo/workflows",{name:t,content:s})}async deleteWorkflow(t){return we.delete(`bamboo/workflows/${encodeURIComponent(t)}`)}async getKeywordMaskingConfig(){try{return await we.get("bamboo/keyword-masking")}catch(t){return console.error("Failed to fetch keyword masking config:",t),{entries:[]}}}async updateKeywordMaskingConfig(t){return we.post("bamboo/keyword-masking",t)}async validateKeywordEntries(t){return we.post("bamboo/keyword-masking/validate",t)}async getSetupStatus(){return await we.get("bamboo/setup/status")}async markSetupComplete(){return we.post("bamboo/setup/complete",{})}async resetSetupStatus(){await we.post("bamboo/setup/incomplete",{})}}const Dn=class Dn{constructor(){Ye(this,"httpUtilityService",new dv)}static getInstance(){return Dn.instance||(Dn.instance=new Dn),Dn.instance}getUtilityService(){return{copyToClipboard:t=>this.httpUtilityService.copyToClipboard(t),getBambooConfig:()=>this.httpUtilityService.getBambooConfig(),getBambooTools:()=>this.httpUtilityService.getBambooTools(),getModelLimitDefaults:()=>this.httpUtilityService.getModelLimitDefaults(),setBambooConfig:t=>this.httpUtilityService.setBambooConfig(t),validateBambooConfigPatch:t=>this.httpUtilityService.validateBambooConfigPatch(t),setProxyAuth:t=>this.httpUtilityService.setProxyAuth(t),getProxyAuthStatus:()=>this.httpUtilityService.getProxyAuthStatus(),clearProxyAuth:()=>this.httpUtilityService.clearProxyAuth(),getAnthropicModelMapping:()=>this.httpUtilityService.getAnthropicModelMapping(),setAnthropicModelMapping:t=>this.httpUtilityService.setAnthropicModelMapping(t),resetBambooConfig:()=>this.httpUtilityService.resetBambooConfig(),resetSetupStatus:()=>this.httpUtilityService.resetSetupStatus(),saveWorkflow:(t,s)=>this.httpUtilityService.saveWorkflow(t,s),deleteWorkflow:t=>this.httpUtilityService.deleteWorkflow(t),getKeywordMaskingConfig:()=>this.httpUtilityService.getKeywordMaskingConfig(),updateKeywordMaskingConfig:t=>this.httpUtilityService.updateKeywordMaskingConfig(t),validateKeywordEntries:t=>this.httpUtilityService.validateKeywordEntries(t),getSetupStatus:()=>this.httpUtilityService.getSetupStatus(),markSetupComplete:()=>this.httpUtilityService.markSetupComplete()}}async copyToClipboard(t){return this.getUtilityService().copyToClipboard(t)}async getBambooConfig(){return this.getUtilityService().getBambooConfig()}async getBambooTools(){return this.getUtilityService().getBambooTools()}async getModelLimitDefaults(){return this.getUtilityService().getModelLimitDefaults()}async setBambooConfig(t){return this.getUtilityService().setBambooConfig(t)}async validateBambooConfigPatch(t){return this.getUtilityService().validateBambooConfigPatch(t)}async setProxyAuth(t){return this.getUtilityService().setProxyAuth(t)}async getProxyAuthStatus(){return this.getUtilityService().getProxyAuthStatus()}async clearProxyAuth(){return this.getUtilityService().clearProxyAuth()}async getAnthropicModelMapping(){return this.getUtilityService().getAnthropicModelMapping()}async setAnthropicModelMapping(t){return this.getUtilityService().setAnthropicModelMapping(t)}async resetBambooConfig(){return this.getUtilityService().resetBambooConfig()}async resetSetupStatus(){return this.getUtilityService().resetSetupStatus()}async saveWorkflow(t,s){return this.getUtilityService().saveWorkflow(t,s)}async deleteWorkflow(t){return this.getUtilityService().deleteWorkflow(t)}async getKeywordMaskingConfig(){return this.getUtilityService().getKeywordMaskingConfig()}async updateKeywordMaskingConfig(t){return this.getUtilityService().updateKeywordMaskingConfig(t)}async validateKeywordEntries(t){return this.getUtilityService().validateKeywordEntries(t)}async getSetupStatus(){return this.getUtilityService().getSetupStatus()}async markSetupComplete(){return this.getUtilityService().markSetupComplete()}};Ye(Dn,"instance");let Nt=Dn;const Je=Nt.getInstance();let Pr=null,Er=null;const Ji=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,bs=xn((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(Pr)return Pr;Pr=(async()=>{e({isLoadingConfig:!0,error:null});try{const o=await Je.getBambooConfig()??{};return e({config:o,lastLoadedAt:Date.now(),error:null}),o}catch(o){const a=Ji(o,"Failed to load Bamboo config");throw e({error:a}),o}finally{e({isLoadingConfig:!1})}})();try{return await Pr}finally{Pr=null}},saveConfig:async s=>{e({isLoadingConfig:!0,error:null,config:s});try{const n=await Je.setBambooConfig(s);return e({config:n,lastLoadedAt:Date.now(),error:null}),n}catch(n){const o=Ji(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(Er)return Er;Er=(async()=>{e({isLoadingProxyAuthStatus:!0,error:null});try{const o=await Je.getProxyAuthStatus();return e({proxyAuthStatus:o,error:null}),o}catch(o){const a=Ji(o,"Failed to load proxy auth status");throw e({error:a}),o}finally{e({isLoadingProxyAuthStatus:!1})}})();try{return await Er}finally{Er=null}},applyProxyAuth:async s=>{await Je.setProxyAuth(s),await t().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await Je.clearProxyAuth(),await t().loadProxyAuthStatus({force:!0})}}));let Rr=null;const uv=(e,t)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:s=>{e({selectedModel:s})},loadConfigModel:async()=>{try{const s=await bs.getState().loadConfig(),n=typeof(s==null?void 0:s.model)=="string"?s.model:void 0;n&&e({configModel:n})}catch(s){console.error("Failed to load model from config:",s)}},fetchModels:async()=>{if(Rr)return Rr;Rr=(async()=>{e({isLoadingModels:!0,modelsError:null});try{try{if(!(await Je.getSetupStatus()).is_complete){Ke("[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 Ri.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 ai){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 Rr}finally{Rr=null}}}),mv=["system_prompt","system_prompt_selected_id"],Qi=e=>({id:e.id,name:e.name||e.id,content:e.content||"",description:e.description,isDefault:!!e.is_default}),un=class un{constructor(){Ye(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return un.instance||(un.instance=new un),un.instance.cleanupDeprecatedPromptStorageKeys(),un.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const t of mv)localStorage.removeItem(t)}catch(t){console.warn("[SystemPromptService] Failed to cleanup deprecated prompt storage keys:",t)}}}async getSystemPromptPresets(){try{const t=await ye.get("prompt-presets"),n=(Array.isArray(t==null?void 0:t.prompts)?t.prompts:[]).filter(o=>o.id&&o.id.trim().length>0).map(Qi);if(n.length>0)return n}catch(t){console.error("Failed to load prompt presets from backend:",t)}return oi()}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 ye.post("prompt-presets",s);if(!(n!=null&&n.prompt))throw new Error("Backend did not return created prompt preset");return Qi(n.prompt)}async updateSystemPromptPreset(t){const s=encodeURIComponent(t.id),n={name:t.name,content:t.content,description:t.description},o=await ye.patch(`prompt-presets/${s}`,n);if(!(o!=null&&o.prompt))throw new Error("Backend did not return updated prompt preset");return Qi(o.prompt)}async deleteSystemPromptPreset(t){const s=encodeURIComponent(t);await ye.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)||""}};Ye(un,"instance");let li=un;const au="copilot_last_selected_prompt_id",mf="copilot_custom_system_prompts_v2",hf="copilot_custom_system_prompts_v2_migrated_to_backend",pf="general_assistant",od=80,lr=li.getInstance();let ba=null;function ad(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,od)}function ff(e){if(typeof e!="string")return null;const t=e.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return t?t.slice(0,od):null}function gf(e,t){if(!t.has(e))return e;let s=2;for(;;){const n=`_${s}`,a=`${e.slice(0,Math.max(0,od-n.length))}${n}`;if(!t.has(a))return a;s+=1}}function yf(){try{const e=localStorage.getItem(mf);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=ff(o==null?void 0:o.id)||ad(a),d=gf(c,s);d!==pf&&(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 xf(){try{return localStorage.getItem(hf)==="1"}catch(e){return console.error("[promptSlice] Failed to read migration marker:",e),!1}}function iu(){try{localStorage.setItem(hf,"1")}catch(e){console.error("[promptSlice] Failed to write migration marker:",e)}}function lu(){try{localStorage.removeItem(mf)}catch(e){console.error("[promptSlice] Failed to clear legacy custom prompts:",e)}}async function hv(){var o,a;if(xf())return;const e=yf();if(e.length===0){lu(),iu();return}const t=await lr.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===pf||i.isDefault)continue;const d=ff(i.id)||ad(l),u=gf(d,s);try{const h=await lr.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||(lu(),iu())}async function pv(){ba||(ba=hv().finally(()=>{ba=null})),await ba}const fv=(e,t)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(au)||null,loadSystemPrompts:async()=>{try{await pv()}catch(o){console.warn("[promptSlice] Legacy prompt migration skipped:",o)}let s=[];try{s=await lr.getSystemPromptPresets()}catch(o){console.error("Failed to load system prompts from backend:",o)}let n=s.length?s:oi();if(!xf()){const o=yf();n=gv(n,o)}n.length===0&&(n=oi()),e({systemPrompts:n})},addSystemPrompt:async s=>{try{await lr.createSystemPromptPreset({id:ad(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 lr.updateSystemPromptPreset(s),await t().loadSystemPrompts()}catch(n){throw console.error("Failed to update system prompt:",n),n}},deleteSystemPrompt:async s=>{try{await lr.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(au,s)}catch(n){console.error("Failed to save last selected prompt ID to localStorage:",n)}}}),gv=(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())},yv=(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 xv{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 we.get(a)}async getSkill(t){return we.get(`skills/${t}`)}async getFilteredTools(t){const s=t?`?session_id=${encodeURIComponent(t)}`:"";return(await we.get(`skills/filtered-tools${s}`)).tools??[]}}const tc=new xv,bv=(e,t)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(s,n)=>{e({isLoadingSkills:!0,skillsError:null});try{const o=await tc.listSkills(s,n);e({skills:o.skills,isLoadingSkills:!1})}catch(o){e({skillsError:o instanceof Error?o.message:as.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async s=>{e({isLoadingSkills:!0,skillsError:null});try{const n=await tc.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:as.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}})}),Sv=(e,t)=>({taskLists:{},taskListVersions:{},activeItems:{},evaluationStates:{},setTaskList:(s,n)=>e(o=>({taskLists:{...o.taskLists,[s]:n},taskListVersions:{...o.taskListVersions,[s]:n.version||0}})),updateTaskListDelta:(s,n)=>e(o=>{const a=o.taskListVersions[s]||0;if(n.version<=a)return o;const i=o.taskLists[s];if(!i)return o;const l=i.items.map(c=>c.id===n.item_id?{...c,status:n.status,tool_calls_count:n.tool_calls_count}:c);return{taskLists:{...o.taskLists,[s]:{...i,items:l,updated_at:new Date().toISOString()}},taskListVersions:{...o.taskListVersions,[s]:n.version},activeItems:{...o.activeItems,[s]:n.status==="in_progress"?n.item_id:null}}}),clearTaskList:s=>e(n=>{const{[s]:o,...a}=n.taskLists,{[s]:i,...l}=n.taskListVersions,{[s]:c,...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}})}),sc=e=>Array.isArray(e)?e.map(t=>String(t??"")):[],Oa=({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o})=>JSON.stringify({sessionId:e??null,question:t??"",options:sc(s),allowCustom:n??!0,toolCallId:o??null}),wv=(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=sc(e.options),n=sc(t.options);return s.length!==n.length?!1:s.every((o,a)=>o===n[a])},bf="chat_input_reasoning_by_session_v1",vf="chat_input_reasoning_last_used_v1",cu={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},id=e=>e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",Sf=()=>{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||{}))id(o)&&(s[n]=o);return s}catch{return{}}},_v=e=>{if(!(typeof window>"u"))try{localStorage.setItem(bf,JSON.stringify(e))}catch{}},Tv=()=>{if(!(typeof window>"u"))try{const e=localStorage.getItem(vf);return id(e)?e:void 0}catch{return}},kv=e=>{if(!(typeof window>"u"))try{localStorage.setItem(vf,e)}catch{}},ld=e=>{const t=Sf();return id(t[e])?t[e]:Tv()},Ar=e=>({...cu,reasoningEffort:ld(e)??cu.reasoningEffort}),jv=(e,t)=>({inputStates:{},pendingQuestionRespond:null,setInputContent:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Ar(s),content:n}}})),setReferenceText:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Ar(s),referenceText:n}}})),setAttachments:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Ar(s),attachments:n}}})),setInputReasoningEffort:(s,n)=>{e(a=>({inputStates:{...a.inputStates,[s]:{...a.inputStates[s]||Ar(s),reasoningEffort:n}}}));const o=Sf();o[s]=n,_v(o),kv(n)},clearInputState:s=>e(n=>{const{[s]:o,...a}=n.inputStates;return{inputStates:a}}),getInputState:s=>t().inputStates[s]||Ar(s),setPendingQuestionRespond:s=>e(n=>wv(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}})}),Cv="bamboo_proxy_auth",Mv=()=>{try{const e=localStorage.getItem(Cv);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}},Pv="auto",Ev="required",Rv=1e4,Av=2e3,Iv=Ss.getInstance();let du=null,Ir=null,uu=null,$r=null;const mu=new WeakMap,N=xn()(Nb(Wb((e,t,s)=>({...av(e,t),...uv(e,t),...fv(e,t),...yv(e,t),...bv(e,t),...vv(e),...Sv(e,t),...jv(e,t),agentAvailability:null,setAgentAvailability:n=>{e({agentAvailability:n})},checkAgentAvailability:async()=>{if(Ir)return Ir;Ir=(async()=>{const n=await Iv.healthCheck();return t().agentAvailability!==n&&e({agentAvailability:n}),n})();try{return await Ir}finally{Ir=null}},startAgentHealthCheck:()=>{du||(t().checkAgentAvailability(),du=setInterval(()=>{t().checkAgentAvailability()},Rv))},refreshSessionsIndex:async()=>{if($r)return $r;$r=(async()=>{try{await t().refreshChats()}catch(n){console.warn("[AppStore] refreshChats failed:",n)}})();try{return await $r}finally{$r=null}},startSessionsIndexSync:()=>{uu||(t().refreshSessionsIndex(),uu=setInterval(()=>{t().refreshSessionsIndex()},Av))}})),{name:"AppStore"})),wf=e=>{const t=mu.get(e);if(t)return t;const s=new Map(e.map(n=>[n.id,n]));return mu.set(e,s),s},Vn=e=>t=>e?wf(t.chats).get(e)??null:null,$v=e=>e.currentSessionId?wf(e.chats).get(e.currentSessionId)??null:null,hu=async()=>{const e=Mv();if(!e)return!1;try{return await Je.setProxyAuth(e),!0}catch(t){return console.error("Failed to apply stored proxy auth during startup:",t),!1}},Dv=async()=>{try{const e=await bs.getState().loadConfig();if((typeof(e==null?void 0:e.proxy_auth_mode)=="string"?e.proxy_auth_mode:Pv)!==Ev)return await hu(),!1;const s=await bs.getState().loadProxyAuthStatus({force:!0});return s!=null&&s.configured||await hu()?!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 pu=!1;const Fv=async(e=!1)=>{if(pu&&!e)return;pu=!0,N.getState().startAgentHealthCheck(),N.getState().startSessionsIndexSync(),await N.getState().loadChats(),await Dv()||await N.getState().fetchModels(),await N.getState().loadSystemPrompts()},qn={'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:fu,Paragraph:Lv}=ce,Ov=({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(vs,{remarkPlugins:[ki],components:{p:({children:o})=>r.jsx(Lv,{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(fu,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block"},children:o}),h2:({children:o})=>r.jsx(fu,{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(pr,{style:qn,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:Zi,Paragraph:zv}=ce,Nv=({prompt:e,token:t,isSelected:s,isExpanded:n,onSelect:o,onToggleExpand:a,onCopy:i})=>{const{t:l}=se(),c=e.content||"",{nonEmptyLineCount:d,wordCount:u,characterCount:h,showGradient:f}=m.useMemo(()=>{const y=(c?c.split(/\r?\n/):[]).filter(b=>b.trim().length>0).length,p=c.trim()?c.trim().split(/\s+/).filter(Boolean).length:0,x=c.length;return{nonEmptyLineCount:y,wordCount:p,characterCount:x,showGradient:!n&&x>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(H,{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(H,{align:"start",children:[r.jsx(is,{checked:s,onChange:()=>o(e.id),onClick:g=>g.stopPropagation()}),r.jsxs("div",{children:[r.jsx(Zi,{strong:!0,children:e.name||e.id}),r.jsx("div",{children:r.jsx(Zi,{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(H,{size:"small",children:[r.jsx(U,{type:"text",size:"small",icon:n?r.jsx(zx,{}):r.jsx(Vc,{}),onClick:g=>{g.stopPropagation(),a(e.id)},children:l(n?"chat.systemPromptSelector.hide":"chat.systemPromptSelector.preview")}),r.jsx(U,{type:"text",size:"small",icon:r.jsx(ls,{}),onClick:g=>i(g,e),children:l("chat.systemPromptSelector.copy")})]})]}),e.description?r.jsx(Zi,{type:"secondary",style:{marginLeft:t.marginLG,fontSize:t.fontSizeSM},children:e.description}):null,r.jsxs(H,{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(Ov,{content:c,token:t,showGradient:f,onClick:g=>g.stopPropagation()}):r.jsx(zv,{type:"secondary",ellipsis:{rows:3},style:{marginLeft:t.marginLG,marginBottom:0,color:t.colorTextSecondary},children:c||l("chat.systemPromptSelector.noContent")})]})},e.id)},{Text:Bv}=ce,{useToken:Wv}=pe,Uv=({open:e,onClose:t,onSelect:s,prompts:n,title:o,showCancelButton:a=!0})=>{const{t:i}=se(),{token:l}=Wv(),[c,d]=fe.useMessage(),u=N(j=>j.lastSelectedPromptId),h=N(j=>j.setLastSelectedPromptId),[f,g]=m.useState(null),[y,p]=m.useState(null),x=m.useMemo(()=>n.filter(j=>j.id&&j.id.trim()!==""),[n]),b=async(j,C)=>{j.stopPropagation();const P=C.content??"";try{await ds(P),c.success(i("success.promptCopied",{name:C.name}))}catch(v){console.error("[SystemPromptSelector] Failed to copy prompt:",v),c.error(i("error.copyPromptFailed"))}},S=o??i("chat.prompt.selectorTitle");m.useEffect(()=>{if(e){const j=x.find(P=>P.isDefault),C=u||(j==null?void 0:j.id)||(x.length>0?x[0].id:null);g(C)}},[e,u,x.length]);const w=j=>{g(j.id),h(j.id),s(j),t()},k=()=>{t()};return r.jsxs(r.Fragment,{children:[d,r.jsxs(Lt,{title:r.jsxs(H,{children:[r.jsx(vr,{}),S]}),open:e,onCancel:k,width:700,footer:r.jsx(Eb,{buttons:[...a?[Rb(k)]:[],Ab(()=>{const j=x.find(C=>C.id===f);j&&w(j)},{text:i("chat.prompt.createButton"),disabled:!f})]}),styles:{body:{maxHeight:"70vh",overflowY:"auto",padding:l.paddingMD}},children:[r.jsx("div",{style:{marginBottom:l.marginMD},children:r.jsx(Bv,{type:"secondary",style:{fontSize:l.fontSizeSM},children:i("chat.prompt.helperText")})}),x.length===0?r.jsx(Pt,{description:i("chat.prompt.emptyDescription"),style:{margin:l.marginLG}}):r.jsx("div",{children:x.map(j=>r.jsx(Nv,{prompt:j,token:l,isSelected:f===j.id,isExpanded:y===j.id,onSelect:C=>g(C),onToggleExpand:C=>p(y===C?null:C),onCopy:b},j.id))})]})]})},qv=({chat:e,isSelected:t,onSelect:s,onDelete:n,onPin:o,onUnpin:a,onEdit:i,onGenerateTitle:l,isGeneratingTitle:c,titleGenerationError:d})=>{const{t:u}=se(),[h,f]=m.useState(!1),[g,y]=m.useState(e.title),[p,x]=m.useState(!1),[b,S]=m.useState(!1),{token:w}=pe.useToken(),k=m.useCallback(_=>{_.stopPropagation(),i&&g.trim()&&i(e.id,g.trim()),f(!1)},[e.id,g,i]),j=m.useCallback(_=>{_.stopPropagation(),y(e.title),f(!1)},[e.title]),C=[{key:"pin",icon:e.pinned?r.jsx(Jl,{style:{color:w.colorWarning}}):r.jsx(Kc,{}),label:e.pinned?u("chat.actions.unpin"):u("chat.actions.pin"),onClick:({domEvent:_})=>{_.stopPropagation(),e.pinned?a(e.id):o(e.id)}},{key:"edit",icon:r.jsx(Sr,{}),label:u("chat.chatItem.edit"),onClick:({domEvent:_})=>{_.stopPropagation(),f(!0)}},...l?[{key:"generate-title",icon:c?r.jsx(ra,{}):r.jsx(Hp,{style:d?{color:w.colorError}:void 0}),label:d||u("chat.actions.generateTitle"),disabled:c,onClick:({domEvent:_})=>{_.stopPropagation(),l(e.id)}}]:[],{type:"divider"},{key:"delete",icon:r.jsx(yn,{}),label:u("common.delete"),danger:!0,onClick:({domEvent:_})=>{_.stopPropagation(),n(e.id)}}],P={padding:"8px 12px",borderRadius:w.borderRadiusSM,marginBottom:w.marginXXS,cursor:"pointer",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)",backgroundColor:t?"var(--lotus-primary-soft)":p||b?"var(--lotus-item-hover-bg)":"transparent",border:"1px solid transparent",borderColor:t?"var(--lotus-tool-card-border)":p||b?w.colorBorderSecondary:"transparent",position:"relative",overflow:"visible",boxShadow:t?"var(--lotus-tool-card-shadow)":"none",transform:p&&!t?"translateX(2px)":"none"},v={flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontSize:13,fontWeight:t?600:500,color:t?"var(--lotus-primary)":w.colorText},M={flex:1,fontSize:w.fontSizeSM,marginRight:w.marginSM},E=h?[r.jsx(U,{type:"text",size:"small",icon:r.jsx(Nx,{style:{color:w.colorSuccess}}),onClick:k,"aria-label":u("common.save")},"save"),r.jsx(U,{type:"text",size:"small",icon:r.jsx(wr,{style:{color:w.colorError}}),onClick:j,"aria-label":u("common.cancel")},"cancel")]:p||b?[r.jsx(fr,{menu:{items:C,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:b,onOpenChange:_=>S(_),children:r.jsx(U,{type:"text",size:"small",icon:r.jsx(Bx,{}),"aria-label":u("common.moreActions","More actions"),onClick:_=>_.stopPropagation(),style:{color:w.colorTextSecondary,borderRadius:w.borderRadiusSM,background:w.colorFillTertiary,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return r.jsx(nt.Item,{style:P,tabIndex:0,onClick:()=>!h&&s(e.id),onKeyDown:_=>{_.key==="Enter"&&!h?(_.preventDefault(),s(e.id)):(_.key==="Delete"||_.key==="Backspace")&&!h&&_.metaKey&&(_.preventDefault(),n(e.id))},onMouseEnter:()=>x(!0),onMouseLeave:()=>{b||x(!1)},onFocus:()=>x(!0),onBlur:()=>{b||x(!1)},actions:E,"data-testid":"chat-item",role:"option","aria-selected":t,"aria-label":e.title||u("chat.sidebar.untitledChat"),children:r.jsx(nt.Item.Meta,{title:h?r.jsx(he,{value:g,onChange:_=>y(_.target.value),onClick:_=>_.stopPropagation(),onPressEnter:_=>{_.preventDefault(),k(_)},autoFocus:!0,style:M,variant:"borderless",size:"small"}):r.jsxs("div",{style:{...v,display:"flex",alignItems:"center",gap:w.marginXS,minWidth:0},children:[e.pinned&&r.jsx(Jl,{style:{color:w.colorWarning,fontSize:11,flexShrink:0}}),r.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.title}),e.kind==="child"?r.jsx(oe,{color:"processing",style:{marginInlineEnd:0,flex:"0 0 auto"},children:u("chat.chatItem.childTag")}):null]})})})},Hv=(e,t)=>e.chat.id===t.chat.id&&e.chat.title===t.chat.title&&e.chat.pinned===t.chat.pinned&&e.isSelected===t.isSelected&&e.isGeneratingTitle===t.isGeneratingTitle&&e.titleGenerationError===t.titleGenerationError,nc=m.memo(qv,Hv);nc.displayName="ChatItem";const gu=e=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[e]??4,Yv=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},Xv=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:gu(s)-gu(n)})},Vv=(e,t)=>e[t]?e[t].map(s=>s.id):[],_f=(e,t)=>e[t]?e[t].length:0,yu=e=>e.pinned?"Pinned":e.createdByScheduleId?"Scheduled":new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),xu=(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},Kv=({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:f,onEditTitle:g,onGenerateTitle:y,titleGenerationState:p,token:x,hasActiveFilters:b})=>{const{t:S}=se(),w=m.useMemo(()=>o.length?o.map(j=>{const C=e[j],P=_f(e,j);return{dateKey:j,dateGroup:C,totalChatsInDate:P}}):[],[e,o]);if(!o.length)return r.jsx(Pt,{image:Pt.PRESENTED_IMAGE_SIMPLE,description:r.jsxs(H,{direction:"vertical",size:4,align:"center",children:[r.jsx("span",{style:{color:x.colorTextSecondary},children:b?S("chat.sidebar.empty.noMatches","No matching sessions"):S("chat.sidebar.empty.noSessions")}),r.jsx("span",{style:{color:x.colorTextSecondary,fontSize:12},children:b?S("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):S("chat.sidebar.empty.hint")}),b&&r.jsx(U,{size:"small",type:"link",onClick:()=>{var C;const j=document.querySelector('[data-testid="sidebar-search-input"] input, .lotus-sidebar-search input');if(j){const P=(C=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value"))==null?void 0:C.set;P==null||P.call(j,""),j.dispatchEvent(new Event("input",{bubbles:!0}))}},children:S("chat.sidebar.empty.clearFilters","Clear filters")})]})});const k=new Set(a);return r.jsx(H,{direction:"vertical",size:"small",style:{width:"100%"},children:w.map(({dateKey:j,dateGroup:C,totalChatsInDate:P})=>{const v=k.has(j);return r.jsxs("div",{style:{borderRadius:x.borderRadiusSM,background:v?x.colorFillTertiary:"transparent",padding:4},children:[r.jsxs(J,{align:"center",justify:"space-between",style:{cursor:"pointer",padding:"8px 12px",borderRadius:x.borderRadiusSM,transition:"all 0.2s ease",border:"1px solid transparent"},role:"button",tabIndex:0,"aria-expanded":v,"aria-label":`${xu(j,S)} (${P})`,onKeyDown:M=>{if(M.key==="Enter"||M.key===" "){M.preventDefault();const E=new Set(k);E.has(j)?E.delete(j):E.add(j),i(Array.from(E))}},onMouseEnter:M=>{M.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.92))",M.currentTarget.style.borderColor="var(--lotus-sidebar-item-hover-border, rgba(13, 148, 136, 0.28))";const E=M.currentTarget.querySelector(".chat-sidebar-date-group-delete");E&&(E.style.opacity="1")},onMouseLeave:M=>{M.currentTarget.style.background="transparent",M.currentTarget.style.borderColor="transparent";const E=M.currentTarget.querySelector(".chat-sidebar-date-group-delete");E&&(E.style.opacity="0")},onClick:()=>{const M=new Set(k);M.has(j)?M.delete(j):M.add(j),i(Array.from(M))},className:"chat-sidebar-date-group-header",children:[r.jsxs(J,{align:"center",gap:"small",style:{minWidth:0},children:[v?r.jsx(cs,{style:{fontSize:12,opacity:.6}}):r.jsx(Ks,{style:{fontSize:12,opacity:.6}}),r.jsxs("span",{style:{fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:j==="Today"?"var(--lotus-primary)":x.colorTextSecondary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[xu(j,S)," (",P,")"]})]}),r.jsx(U,{type:"text",size:"small",icon:r.jsx(yn,{}),className:"chat-sidebar-date-group-delete",style:{color:x.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:M=>{M.stopPropagation(),u(j)}})]}),v?r.jsx("div",{style:{marginTop:4},children:r.jsx(nt,{itemLayout:"horizontal",dataSource:C,split:!1,renderItem:M=>{var E,_,R,T,D;return r.jsxs("div",{children:[r.jsxs(J,{align:"center",gap:6,children:[(E=t[M.id])!=null&&E.length?r.jsx(U,{size:"small",type:"text",style:{padding:0,width:22},"aria-label":s.has(M.id)?S("chat.sidebar.actions.collapseChildren"):S("chat.sidebar.actions.expandChildren"),onClick:$=>{$.preventDefault(),$.stopPropagation(),n(M.id)},children:s.has(M.id)?r.jsx(cs,{}):r.jsx(Ks,{})}):r.jsx("div",{style:{width:22}}),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsx(nc,{chat:M,isSelected:M.id===l,onSelect:c,onDelete:d,onPin:h,onUnpin:f,onEdit:g,onGenerateTitle:y,isGeneratingTitle:((_=p[M.id])==null?void 0:_.status)==="loading",titleGenerationError:((R=p[M.id])==null?void 0:R.status)==="error"?(T=p[M.id])==null?void 0:T.error:void 0})})]}),s.has(M.id)&&(((D=t[M.id])==null?void 0:D.length)??0)>0?r.jsx("div",{style:{marginLeft:22,marginTop:2},children:r.jsx(nt,{itemLayout:"horizontal",dataSource:t[M.id],split:!1,renderItem:$=>{var I,O,A;return r.jsx("div",{style:{paddingLeft:12},children:r.jsx(nc,{chat:$,isSelected:$.id===l,onSelect:c,onDelete:d,onPin:h,onUnpin:f,onEdit:g,onGenerateTitle:y,isGeneratingTitle:((I=p[$.id])==null?void 0:I.status)==="loading",titleGenerationError:((O=p[$.id])==null?void 0:O.status)==="error"?(A=p[$.id])==null?void 0:A.error:void 0})},$.id)}})}):null]},M.id)}})}):null]},j)})})},Gv="copilot_ui_theme_v1";function Jv(){var e;try{const t=localStorage.getItem(Gv);if(t==="light"||t==="dark")return t}catch{}return(e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const Hn=xn(e=>({themeMode:Jv(),setThemeMode:t=>e({themeMode:t}),toggleTheme:()=>e(t=>({themeMode:t.themeMode==="dark"?"light":"dark"}))})),Qv="2026.4.5",Zv={version:Qv},cd=Zv.version,{Text:eS}=ce,tS=({collapsed:e,onNewChat:t,onOpenSettings:s,screens:n,token:o})=>{const{t:a}=se(),i=Hn(h=>h.themeMode),l=Hn(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(J,{vertical:!0,gap:e?"small":"middle",style:{padding:e?10:16,background:"transparent",borderTop:`1px solid ${o.colorBorderSecondary}`},children:[r.jsx(U,{"data-testid":"new-chat",type:"primary",icon:r.jsx(Gs,{}),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(J,{gap:8,align:"center",children:[r.jsx(U,{"data-testid":"open-settings",icon:r.jsx(ji,{}),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(U,{"data-testid":"toggle-theme",type:"text",icon:i==="dark"?r.jsx(Wx,{}):r.jsx(Ux,{}),onClick:l,"aria-label":u,className:"lotus-toolbar-icon",style:{width:44,height:44,borderRadius:o.borderRadiusLG,flexShrink:0}})})]}),!e&&r.jsxs(eS,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:o.fontSizeSM,textAlign:"center",userSelect:"text"},children:[a("settings.appTab.runningVersion","Running version"),": v",cd]})]})},bu="provider",pn=xn(e=>({isOpen:!1,origin:"chat",activeTabKey:bu,open:(t,s=bu)=>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 W(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 Tf=function(){const{crypto:e}=globalThis;if(e!=null&&e.randomUUID)return Tf=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 rc(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const oc=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 kt extends Se{constructor(t,s,n,o){super(`${kt.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 Ai({message:n,cause:oc(s)});const a=s==null?void 0:s.error;return t===400?new kf(t,a,n,o):t===401?new jf(t,a,n,o):t===403?new Cf(t,a,n,o):t===404?new Mf(t,a,n,o):t===409?new Pf(t,a,n,o):t===422?new Ef(t,a,n,o):t===429?new Rf(t,a,n,o):t>=500?new Af(t,a,n,o):new kt(t,a,n,o)}}class rs extends kt{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class Ai extends kt{constructor({message:t,cause:s}){super(void 0,void 0,t||"Connection error.",void 0),s&&(this.cause=s)}}class dd extends Ai{constructor({message:t}={}){super({message:t??"Request timed out."})}}class kf extends kt{}class jf extends kt{}class Cf extends kt{}class Mf extends kt{}class Pf extends kt{}class Ef extends kt{}class Rf extends kt{}class Af extends kt{}class If extends Se{constructor(){super("Could not parse response content as the length limit was reached")}}class $f extends Se{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Io extends Error{constructor(t){super(t)}}const sS=/^[a-z][a-z0-9+.-]*:/i,nS=e=>sS.test(e);let zt=e=>(zt=Array.isArray,zt(e)),vu=zt;function rS(e){return typeof e!="object"?{}:e??{}}function oS(e){if(!e)return!0;for(const t in e)return!1;return!0}function aS(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function el(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}const iS=(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}},ca=e=>new Promise(t=>setTimeout(t,e)),or="5.10.2",cS=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function dS(){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 uS=()=>{var s;const e=dS();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":or,"X-Stainless-OS":wu(Deno.build.os),"X-Stainless-Arch":Su(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":or,"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":or,"X-Stainless-OS":wu(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Su(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=mS();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":or,"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":or,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function mS(){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 Su=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",wu=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 _u;const hS=()=>_u??(_u=uS());function pS(){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 Df(...e){const t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Ff(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Df({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 Lf(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 fS(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 gS=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),Of="RFC3986",zf=e=>String(e),Tu={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:zf},yS="RFC1738";let ac=(e,t)=>(ac=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),ac(e,t));const Cs=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),tl=1024,xS=(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+=tl){const c=a.length>=tl?a.slice(l,l+tl):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===yS&&(h===40||h===41)){d[d.length]=c.charAt(u);continue}if(h<128){d[d.length]=Cs[h];continue}if(h<2048){d[d.length]=Cs[192|h>>6]+Cs[128|h&63];continue}if(h<55296||h>=57344){d[d.length]=Cs[224|h>>12]+Cs[128|h>>6&63]+Cs[128|h&63];continue}u+=1,h=65536+((h&1023)<<10|c.charCodeAt(u)&1023),d[d.length]=Cs[240|h>>18]+Cs[128|h>>12&63]+Cs[128|h>>6&63]+Cs[128|h&63]}i+=d.join("")}return i};function bS(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function ku(e,t){if(zt(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}const Nf={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},Bf=function(e,t){Array.prototype.push.apply(e,zt(t)?t:[t])};let ju;const mt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:xS,encodeValuesOnly:!1,format:Of,formatter:zf,indices:!1,serializeDate(e){return(ju??(ju=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 sl={};function Wf(e,t,s,n,o,a,i,l,c,d,u,h,f,g,y,p,x,b){let S=e,w=b,k=0,j=!1;for(;(w=w.get(sl))!==void 0&&!j;){const E=w.get(e);if(k+=1,typeof E<"u"){if(E===k)throw new RangeError("Cyclic object value");j=!0}typeof w.get(sl)>"u"&&(k=0)}if(typeof d=="function"?S=d(t,S):S instanceof Date?S=f==null?void 0:f(S):s==="comma"&&zt(S)&&(S=ku(S,function(E){return E instanceof Date?f==null?void 0:f(E):E})),S===null){if(a)return c&&!p?c(t,mt.encoder,x,"key",g):t;S=""}if(vS(S)||bS(S)){if(c){const E=p?t:c(t,mt.encoder,x,"key",g);return[(y==null?void 0:y(E))+"="+(y==null?void 0:y(c(S,mt.encoder,x,"value",g)))]}return[(y==null?void 0:y(t))+"="+(y==null?void 0:y(String(S)))]}const C=[];if(typeof S>"u")return C;let P;if(s==="comma"&&zt(S))p&&c&&(S=ku(S,c)),P=[{value:S.length>0?S.join(",")||null:void 0}];else if(zt(d))P=d;else{const E=Object.keys(S);P=u?E.sort(u):E}const v=l?String(t).replace(/\./g,"%2E"):String(t),M=n&&zt(S)&&S.length===1?v+"[]":v;if(o&&zt(S)&&S.length===0)return M+"[]";for(let E=0;E<P.length;++E){const _=P[E],R=typeof _=="object"&&typeof _.value<"u"?_.value:S[_];if(i&&R===null)continue;const T=h&&l?_.replace(/\./g,"%2E"):_,D=zt(S)?typeof s=="function"?s(M,T):M:M+(h?"."+T:"["+T+"]");b.set(e,k);const $=new WeakMap;$.set(sl,b),Bf(C,Wf(R,D,s,n,o,a,i,l,s==="comma"&&p&&zt(S)?null:c,d,u,h,f,g,y,p,x,$))}return C}function SS(e=mt){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||mt.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=Of;if(typeof e.format<"u"){if(!ac(Tu,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const n=Tu[s];let o=mt.filter;(typeof e.filter=="function"||zt(e.filter))&&(o=e.filter);let a;if(e.arrayFormat&&e.arrayFormat in Nf?a=e.arrayFormat:"indices"in e?a=e.indices?"indices":"repeat":a=mt.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:mt.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:mt.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:mt.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:mt.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?mt.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:mt.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:mt.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:mt.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:mt.encodeValuesOnly,filter:o,format:s,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:mt.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:mt.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:mt.strictNullHandling}}function wS(e,t={}){let s=e;const n=SS(t);let o,a;typeof n.filter=="function"?(a=n.filter,s=a("",s)):zt(n.filter)&&(a=n.filter,o=a);const i=[];if(typeof s!="object"||s===null)return"";const l=Nf[n.arrayFormat],c=l==="comma"&&n.commaRoundTrip;o||(o=Object.keys(s)),n.sort&&o.sort(n.sort);const d=new WeakMap;for(let f=0;f<o.length;++f){const g=o[f];n.skipNulls&&s[g]===null||Bf(i,Wf(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 _S(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 Cu;function ud(e){let t;return(Cu??(t=new globalThis.TextEncoder,Cu=t.encode.bind(t)))(e)}let Mu;function Pu(e){let t;return(Mu??(t=new globalThis.TextDecoder,Mu=t.decode.bind(t)))(e)}var Wt,Ut;class Ii{constructor(){Wt.set(this,void 0),Ut.set(this,void 0),ve(this,Wt,new Uint8Array),ve(this,Ut,null)}decode(t){if(t==null)return[];const s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?ud(t):t;ve(this,Wt,_S([W(this,Wt,"f"),s]));const n=[];let o;for(;(o=TS(W(this,Wt,"f"),W(this,Ut,"f")))!=null;){if(o.carriage&&W(this,Ut,"f")==null){ve(this,Ut,o.index);continue}if(W(this,Ut,"f")!=null&&(o.index!==W(this,Ut,"f")+1||o.carriage)){n.push(Pu(W(this,Wt,"f").subarray(0,W(this,Ut,"f")-1))),ve(this,Wt,W(this,Wt,"f").subarray(W(this,Ut,"f"))),ve(this,Ut,null);continue}const a=W(this,Ut,"f")!==null?o.preceding-1:o.preceding,i=Pu(W(this,Wt,"f").subarray(0,a));n.push(i),ve(this,Wt,W(this,Wt,"f").subarray(o.index)),ve(this,Ut,null)}return n}flush(){return W(this,Wt,"f").length?this.decode(`
|
|
13
|
+
`):[]}}Wt=new WeakMap,Ut=new WeakMap;Ii.NEWLINE_CHARS=new Set([`
|
|
14
|
+
`,"\r"]);Ii.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function TS(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 kS(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 ci={off:0,error:200,warn:300,info:400,debug:500},Eu=(e,t,s)=>{if(e){if(aS(ci,e))return e;_t(s).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(ci))}`)}};function $o(){}function va(e,t,s){return!t||ci[e]>ci[s]?$o:t[e].bind(t)}const jS={error:$o,warn:$o,info:$o,debug:$o};let Ru=new WeakMap;function _t(e){const t=e.logger,s=e.logLevel??"off";if(!t)return jS;const n=Ru.get(t);if(n&&n[0]===s)return n[1];const o={error:va("error",t,s),warn:va("warn",t,s),info:va("info",t,s),debug:va("debug",t,s)};return Ru.set(t,[s,o]),o}const Cn=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 Dr;class Ds{constructor(t,s,n){this.iterator=t,Dr.set(this,void 0),this.controller=s,ve(this,Dr,n)}static fromSSEResponse(t,s,n){let o=!1;const a=n?_t(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 CS(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 kt(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 kt(void 0,d.error,d.message,void 0);yield{event:c.event,data:d}}}l=!0}catch(c){if(rc(c))return;throw c}finally{l||s.abort()}}return new Ds(i,s,n)}static fromReadableStream(t,s,n){let o=!1;async function*a(){const l=new Ii,c=Lf(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(rc(c))return;throw c}finally{l||s.abort()}}return new Ds(i,s,n)}[(Dr=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 Ds(()=>o(t),this.controller,W(this,Dr,"f")),new Ds(()=>o(s),this.controller,W(this,Dr,"f"))]}toReadableStream(){const t=this;let s;return Df({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=ud(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*CS(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 PS,n=new Ii,o=Lf(e.body);for await(const a of MS(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*MS(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"?ud(s):s;let o=new Uint8Array(t.length+n.length);o.set(t),o.set(n,t.length),t=o;let a;for(;(a=kS(t))!==-1;)yield t.slice(0,a),t=t.slice(a)}t.length>0&&(yield t)}class PS{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]=ES(t,":");return o.startsWith(" ")&&(o=o.substring(1)),s==="event"?this.event=o:s==="data"&&this.data.push(o),null}}function ES(e,t){const s=e.indexOf(t);return s!==-1?[e.substring(0,s),t,e.substring(s+t.length)]:[e,"",""]}async function Uf(e,t){const{response:s,requestLogID:n,retryOfRequestLogID:o,startTime:a}=t,i=await(async()=>{var h;if(t.options.stream)return _t(e).debug("response",s.status,s.url,s.headers,s.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(s,t.controller,e):Ds.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 f=await s.json();return qf(f,s)}return await s.text()})();return _t(e).debug(`[${n}] response parsed`,Cn({retryOfRequestLogID:o,url:s.url,status:s.status,body:i,durationMs:Date.now()-a})),i}function qf(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 Do;class $i extends Promise{constructor(t,s,n=Uf){super(o=>{o(null)}),this.responsePromise=s,this.parseResponse=n,Do.set(this,void 0),ve(this,Do,t)}_thenUnwrap(t){return new $i(W(this,Do,"f"),this.responsePromise,async(s,n)=>qf(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(W(this,Do,"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)}}Do=new WeakMap;var Sa;class Hf{constructor(t,s,n,o){Sa.set(this,void 0),ve(this,Sa,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 W(this,Sa,"f").requestAPIList(this.constructor,t)}async*iterPages(){let t=this;for(yield t;t.hasNextPage();)t=await t.getNextPage(),yield t}async*[(Sa=new WeakMap,Symbol.asyncIterator)](){for await(const t of this.iterPages())for(const s of t.getPaginatedItems())yield s}}class RS extends $i{constructor(t,s,n){super(t,s,async(o,a)=>new n(o,a.response,await Uf(o,a),a.options))}async*[Symbol.asyncIterator](){const t=await this;for await(const s of t)yield s}}class Di extends Hf{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 dt extends Hf{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:{...rS(this.options.query),after:s}}:null}}const Yf=()=>{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 Ho(e,t,s){return Yf(),new File(e,t??"unknown_file",s)}function za(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 Xf=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",Yn=async(e,t)=>({...e,body:await IS(e.body,t)}),Au=new WeakMap;function AS(e){const t=typeof e=="function"?e:e.fetch,s=Au.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 Au.set(t,n),n}const IS=async(e,t)=>{if(!await AS(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])=>ic(s,n,o))),s},$S=e=>e instanceof Blob&&"name"in e,ic=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,Ho([await s.blob()],za(s)));else if(Xf(s))e.append(t,Ho([await new Response(Ff(s)).blob()],za(s)));else if($S(s))e.append(t,s,za(s));else if(Array.isArray(s))await Promise.all(s.map(n=>ic(e,t+"[]",n)));else if(typeof s=="object")await Promise.all(Object.entries(s).map(([n,o])=>ic(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`)}},Vf=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",DS=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&Vf(e),FS=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function LS(e,t,s){if(Yf(),e=await e,DS(e))return e instanceof File?e:Ho([await e.arrayBuffer()],e.name);if(FS(e)){const o=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Ho(await lc(o),t,s)}const n=await lc(e);if(t||(t=za(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 Ho(n,t,s)}async function lc(e){var s;let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Vf(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Xf(e))for await(const n of e)t.push(...await lc(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}`:""}${OS(e)}`)}return t}function OS(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(s=>`"${s}"`).join(", ")}]`}class _e{constructor(t){this._client=t}}function Kf(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Iu=Object.freeze(Object.create(null)),zS=(e=Kf)=>function(s,...n){if(s.length===1)return s[0];let o=!1;const a=[],i=s.reduce((u,h,f)=>{var p;/[?#]/.test(h)&&(o=!0);const g=n[f];let y=(o?encodeURIComponent:e)(""+g);return f!==n.length&&(g==null||typeof g=="object"&&g.toString===((p=Object.getPrototypeOf(Object.getPrototypeOf(g.hasOwnProperty??Iu)??Iu))==null?void 0:p.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+(f===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((f,g)=>{const y=" ".repeat(g.start-u),p="^".repeat(g.length);return u=g.start+g.length,f+y+p},"");throw new Se(`Path parameters result in path with invalid segments:
|
|
17
|
+
${a.map(f=>f.error).join(`
|
|
18
|
+
`)}
|
|
19
|
+
${i}
|
|
20
|
+
${h}`)}return i},re=zS(Kf);let Gf=class extends _e{list(t,s={},n){return this._client.getAPIList(re`/chat/completions/${t}/messages`,dt,{query:s,...n})}};function NS(e){return typeof e.parse=="function"}const di=e=>(e==null?void 0:e.role)==="assistant",Jf=e=>(e==null?void 0:e.role)==="tool";var cc,Na,Ba,Fo,Lo,Wa,Oo,Xs,zo,ui,mi,ar,Qf;class md{constructor(){cc.add(this),this.controller=new AbortController,Na.set(this,void 0),Ba.set(this,()=>{}),Fo.set(this,()=>{}),Lo.set(this,void 0),Wa.set(this,()=>{}),Oo.set(this,()=>{}),Xs.set(this,{}),zo.set(this,!1),ui.set(this,!1),mi.set(this,!1),ar.set(this,!1),ve(this,Na,new Promise((t,s)=>{ve(this,Ba,t,"f"),ve(this,Fo,s,"f")})),ve(this,Lo,new Promise((t,s)=>{ve(this,Wa,t,"f"),ve(this,Oo,s,"f")})),W(this,Na,"f").catch(()=>{}),W(this,Lo,"f").catch(()=>{})}_run(t){setTimeout(()=>{t().then(()=>{this._emitFinal(),this._emit("end")},W(this,cc,"m",Qf).bind(this))},0)}_connected(){this.ended||(W(this,Ba,"f").call(this),this._emit("connect"))}get ended(){return W(this,zo,"f")}get errored(){return W(this,ui,"f")}get aborted(){return W(this,mi,"f")}abort(){this.controller.abort()}on(t,s){return(W(this,Xs,"f")[t]||(W(this,Xs,"f")[t]=[])).push({listener:s}),this}off(t,s){const n=W(this,Xs,"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(W(this,Xs,"f")[t]||(W(this,Xs,"f")[t]=[])).push({listener:s,once:!0}),this}emitted(t){return new Promise((s,n)=>{ve(this,ar,!0),t!=="error"&&this.once("error",n),this.once(t,s)})}async done(){ve(this,ar,!0),await W(this,Lo,"f")}_emit(t,...s){if(W(this,zo,"f"))return;t==="end"&&(ve(this,zo,!0),W(this,Wa,"f").call(this));const n=W(this,Xs,"f")[t];if(n&&(W(this,Xs,"f")[t]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...s))),t==="abort"){const o=s[0];!W(this,ar,"f")&&!(n!=null&&n.length)&&Promise.reject(o),W(this,Fo,"f").call(this,o),W(this,Oo,"f").call(this,o),this._emit("end");return}if(t==="error"){const o=s[0];!W(this,ar,"f")&&!(n!=null&&n.length)&&Promise.reject(o),W(this,Fo,"f").call(this,o),W(this,Oo,"f").call(this,o),this._emit("end")}}_emitFinal(){}}Na=new WeakMap,Ba=new WeakMap,Fo=new WeakMap,Lo=new WeakMap,Wa=new WeakMap,Oo=new WeakMap,Xs=new WeakMap,zo=new WeakMap,ui=new WeakMap,mi=new WeakMap,ar=new WeakMap,cc=new WeakSet,Qf=function(t){if(ve(this,ui,!0),t instanceof Error&&t.name==="AbortError"&&(t=new rs),t instanceof rs)return ve(this,mi,!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 hd(e){return(e==null?void 0:e.$brand)==="auto-parseable-response-format"}function da(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function BS(e,t){return!t||!Zf(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}}))}:pd(e,t)}function pd(e,t){const s=e.choices.map(n=>{var o;if(n.finish_reason==="length")throw new If;if(n.finish_reason==="content_filter")throw new $f;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((o=n.message.tool_calls)==null?void 0:o.map(a=>US(t,a)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?WS(t,n.message.content):null}}});return{...e,choices:s}}function WS(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 US(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:da(s)?s.$parseRaw(t.function.arguments):s!=null&&s.function.strict?JSON.parse(t.function.arguments):null}}}function qS(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 da(s)||(s==null?void 0:s.function.strict)||!1}function Zf(e){var t;return hd(e.response_format)?!0:((t=e.tools)==null?void 0:t.some(s=>da(s)||s.type==="function"&&s.function.strict===!0))??!1}function HS(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 It,dc,hi,uc,mc,hc,eg,tg;const YS=10;class sg extends md{constructor(){super(...arguments),It.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(t){var n;this._chatCompletions.push(t),this._emit("chatCompletion",t);const s=(n=t.choices[0])==null?void 0:n.message;return s&&this._addMessage(s),t}_addMessage(t,s=!0){if("content"in t||(t.content=null),this.messages.push(t),s){if(this._emit("message",t),Jf(t)&&t.content)this._emit("functionToolCallResult",t.content);else if(di(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(),W(this,It,"m",dc).call(this)}async finalMessage(){return await this.done(),W(this,It,"m",hi).call(this)}async finalFunctionToolCall(){return await this.done(),W(this,It,"m",uc).call(this)}async finalFunctionToolCallResult(){return await this.done(),W(this,It,"m",mc).call(this)}async totalUsage(){return await this.done(),W(this,It,"m",hc).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const t=this._chatCompletions[this._chatCompletions.length-1];t&&this._emit("finalChatCompletion",t);const s=W(this,It,"m",hi).call(this);s&&this._emit("finalMessage",s);const n=W(this,It,"m",dc).call(this);n&&this._emit("finalContent",n);const o=W(this,It,"m",uc).call(this);o&&this._emit("finalFunctionToolCall",o);const a=W(this,It,"m",mc).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",W(this,It,"m",hc).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())),W(this,It,"m",eg).call(this,s);const a=await t.chat.completions.create({...s,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(pd(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,p;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=YS}=n||{},u=s.tools.map(x=>{if(da(x)){if(!x.$callback)throw new Se("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:x.$callback,name:x.function.name,description:x.function.description||"",parameters:x.function.parameters,parse:x.$parseRaw,strict:!0}}}return x}),h={};for(const x of u)x.type==="function"&&(h[x.function.name||x.function.function.name]=x.function);const f="tools"in s?u.map(x=>x.type==="function"?{type:"function",function:{name:x.function.name||x.function.function.name,parameters:x.function.parameters,description:x.function.description,strict:x.function.strict}}:x):void 0;for(const x of s.messages)this._addMessage(x,!1);for(let x=0;x<d;++x){const S=(y=(await this._createChatCompletion(t,{...l,tool_choice:a,tools:f,messages:[...this.messages]},n)).choices[0])==null?void 0:y.message;if(!S)throw new Se("missing message in ChatCompletion response");if(!((p=S.tool_calls)!=null&&p.length))return;for(const w of S.tool_calls){if(w.type!=="function")continue;const k=w.id,{name:j,arguments:C}=w.function,P=h[j];if(P){if(c&&c!==j){const _=`Invalid tool_call: ${JSON.stringify(j)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:o,tool_call_id:k,content:_});continue}}else{const _=`Invalid tool_call: ${JSON.stringify(j)}. Available options are: ${Object.keys(h).map(R=>JSON.stringify(R)).join(", ")}. Please try again`;this._addMessage({role:o,tool_call_id:k,content:_});continue}let v;try{v=NS(P)?await P.parse(C):C}catch(_){const R=_ instanceof Error?_.message:String(_);this._addMessage({role:o,tool_call_id:k,content:R});continue}const M=await P.function(v,this),E=W(this,It,"m",tg).call(this,M);if(this._addMessage({role:o,tool_call_id:k,content:E}),c)return}}}}It=new WeakSet,dc=function(){return W(this,It,"m",hi).call(this).content??null},hi=function(){let t=this.messages.length;for(;t-- >0;){const s=this.messages[t];if(di(s))return{...s,content:s.content??null,refusal:s.refusal??null}}throw new Se("stream ended without producing a ChatCompletionMessage with role=assistant")},uc=function(){var t,s;for(let n=this.messages.length-1;n>=0;n--){const o=this.messages[n];if(di(o)&&((t=o==null?void 0:o.tool_calls)!=null&&t.length))return(s=o.tool_calls.at(-1))==null?void 0:s.function}},mc=function(){for(let t=this.messages.length-1;t>=0;t--){const s=this.messages[t];if(Jf(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}},hc=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},eg=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.")},tg=function(t){return typeof t=="string"?t:t===void 0?"undefined":JSON.stringify(t)};class fd extends sg{static runTools(t,s,n){const o=new fd,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),di(t)&&t.content&&this._emit("content",t.content)}}const ng=1,rg=2,og=4,ag=8,ig=16,lg=32,cg=64,dg=128,ug=256,mg=dg|ug,hg=ig|lg|mg|cg,pg=ng|rg|hg,fg=og|ag,XS=pg|fg,yt={STR:ng,NUM:rg,ARR:og,OBJ:ag,NULL:ig,BOOL:lg,NAN:cg,INFINITY:dg,MINUS_INFINITY:ug,INF:mg,SPECIAL:hg,ATOM:pg,COLLECTION:fg,ALL:XS};class VS extends Error{}class KS extends Error{}function GS(e,t=yt.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return JS(e.trim(),t)}const JS=(e,t)=>{const s=e.length;let n=0;const o=f=>{throw new VS(`${f} at position ${n}`)},a=f=>{throw new KS(`${f} 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"||yt.NULL&t&&s-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):e.substring(n,n+4)==="true"||yt.BOOL&t&&s-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):e.substring(n,n+5)==="false"||yt.BOOL&t&&s-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):e.substring(n,n+8)==="Infinity"||yt.INFINITY&t&&s-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):e.substring(n,n+9)==="-Infinity"||yt.MINUS_INFINITY&t&&1<s-n&&s-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):e.substring(n,n+3)==="NaN"||yt.NAN&t&&s-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):u()),l=()=>{const f=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(f,++n-Number(g)))}catch(y){a(String(y))}else if(yt.STR&t)try{return JSON.parse(e.substring(f,n-Number(g))+'"')}catch{return JSON.parse(e.substring(f,e.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},c=()=>{n++,h();const f={};try{for(;e[n]!=="}";){if(h(),n>=s&&yt.OBJ&t)return f;const g=l();h(),n++;try{const y=i();Object.defineProperty(f,g,{value:y,writable:!0,enumerable:!0,configurable:!0})}catch(y){if(yt.OBJ&t)return f;throw y}h(),e[n]===","&&n++}}catch{if(yt.OBJ&t)return f;o("Expected '}' at end of object")}return n++,f},d=()=>{n++;const f=[];try{for(;e[n]!=="]";)f.push(i()),h(),e[n]===","&&n++}catch{if(yt.ARR&t)return f;o("Expected ']' at end of array")}return n++,f},u=()=>{if(n===0){e==="-"&&yt.NUM&t&&o("Not sure what '-' is");try{return JSON.parse(e)}catch(g){if(yt.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 f=n;for(e[n]==="-"&&n++;e[n]&&!",]}".includes(e[n]);)n++;n==s&&!(yt.NUM&t)&&o("Unterminated number literal");try{return JSON.parse(e.substring(f,n))}catch{e.substring(f,n)==="-"&&yt.NUM&t&&o("Not sure what '-' is");try{return JSON.parse(e.substring(f,e.lastIndexOf("e")))}catch(y){a(String(y))}}},h=()=>{for(;n<s&&`
|
|
21
|
+
\r `.includes(e[n]);)n++};return i()},$u=e=>GS(e,yt.ALL^yt.NUM);var ut,Ws,Gn,rn,nl,wa,rl,ol,al,_a,il,Du;class ea extends sg{constructor(t){super(),ut.add(this),Ws.set(this,void 0),Gn.set(this,void 0),rn.set(this,void 0),ve(this,Ws,t),ve(this,Gn,[])}get currentChatCompletionSnapshot(){return W(this,rn,"f")}static fromReadableStream(t){const s=new ea(null);return s._run(()=>s._fromReadableStream(t)),s}static createChatCompletion(t,s,n){const o=new ea(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())),W(this,ut,"m",nl).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)W(this,ut,"m",rl).call(this,l);if((i=a.controller.signal)!=null&&i.aborted)throw new rs;return this._addChatCompletion(W(this,ut,"m",_a).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())),W(this,ut,"m",nl).call(this),this._connected();const o=Ds.fromReadableStream(t,this.controller);let a;for await(const l of o)a&&a!==l.id&&this._addChatCompletion(W(this,ut,"m",_a).call(this)),W(this,ut,"m",rl).call(this,l),a=l.id;if((i=o.controller.signal)!=null&&i.aborted)throw new rs;return this._addChatCompletion(W(this,ut,"m",_a).call(this))}[(Ws=new WeakMap,Gn=new WeakMap,rn=new WeakMap,ut=new WeakSet,nl=function(){this.ended||ve(this,rn,void 0)},wa=function(s){let n=W(this,Gn,"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},W(this,Gn,"f")[s.index]=n,n)},rl=function(s){var o,a,i,l,c,d,u,h,f,g,y,p,x,b,S;if(this.ended)return;const n=W(this,ut,"m",Du).call(this,s);this._emit("chunk",s,n);for(const w of s.choices){const k=n.choices[w.index];w.delta.content!=null&&((o=k.message)==null?void 0:o.role)==="assistant"&&((a=k.message)!=null&&a.content)&&(this._emit("content",w.delta.content,k.message.content),this._emit("content.delta",{delta:w.delta.content,snapshot:k.message.content,parsed:k.message.parsed})),w.delta.refusal!=null&&((i=k.message)==null?void 0:i.role)==="assistant"&&((l=k.message)!=null&&l.refusal)&&this._emit("refusal.delta",{delta:w.delta.refusal,snapshot:k.message.refusal}),((c=w.logprobs)==null?void 0:c.content)!=null&&((d=k.message)==null?void 0:d.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(u=w.logprobs)==null?void 0:u.content,snapshot:((h=k.logprobs)==null?void 0:h.content)??[]}),((f=w.logprobs)==null?void 0:f.refusal)!=null&&((g=k.message)==null?void 0:g.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(y=w.logprobs)==null?void 0:y.refusal,snapshot:((p=k.logprobs)==null?void 0:p.refusal)??[]});const j=W(this,ut,"m",wa).call(this,k);k.finish_reason&&(W(this,ut,"m",al).call(this,k),j.current_tool_call_index!=null&&W(this,ut,"m",ol).call(this,k,j.current_tool_call_index));for(const C of w.delta.tool_calls??[])j.current_tool_call_index!==C.index&&(W(this,ut,"m",al).call(this,k),j.current_tool_call_index!=null&&W(this,ut,"m",ol).call(this,k,j.current_tool_call_index)),j.current_tool_call_index=C.index;for(const C of w.delta.tool_calls??[]){const P=(x=k.message.tool_calls)==null?void 0:x[C.index];P!=null&&P.type&&((P==null?void 0:P.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(b=P.function)==null?void 0:b.name,index:C.index,arguments:P.function.arguments,parsed_arguments:P.function.parsed_arguments,arguments_delta:((S=C.function)==null?void 0:S.arguments)??""}):(P==null||P.type,void 0))}}},ol=function(s,n){var i,l,c;if(W(this,ut,"m",wa).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=W(this,Ws,"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:da(d)?d.$parseRaw(a.function.arguments):d!=null&&d.function.strict?JSON.parse(a.function.arguments):null})}else a.type},al=function(s){var o,a;const n=W(this,ut,"m",wa).call(this,s);if(s.message.content&&!n.content_done){n.content_done=!0;const i=W(this,ut,"m",il).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}))},_a=function(){if(this.ended)throw new Se("stream has ended, this shouldn't happen");const s=W(this,rn,"f");if(!s)throw new Se("request ended without sending any chunks");return ve(this,rn,void 0),ve(this,Gn,[]),QS(s,W(this,Ws,"f"))},il=function(){var n;const s=(n=W(this,Ws,"f"))==null?void 0:n.response_format;return hd(s)?s:null},Du=function(s){var n,o,a,i;let l=W(this,rn,"f");const{choices:c,...d}=s;l?Object.assign(l,d):l=ve(this,rn,{...d,choices:[]});for(const{delta:u,finish_reason:h,index:f,logprobs:g=null,...y}of s.choices){let p=l.choices[f];if(p||(p=l.choices[f]={finish_reason:h,index:f,message:{},logprobs:g,...y}),g)if(!p.logprobs)p.logprobs=Object.assign({},g);else{const{content:C,refusal:P,...v}=g;Object.assign(p.logprobs,v),C&&((n=p.logprobs).content??(n.content=[]),p.logprobs.content.push(...C)),P&&((o=p.logprobs).refusal??(o.refusal=[]),p.logprobs.refusal.push(...P))}if(h&&(p.finish_reason=h,W(this,Ws,"f")&&Zf(W(this,Ws,"f")))){if(h==="length")throw new If;if(h==="content_filter")throw new $f}if(Object.assign(p,y),!u)continue;const{content:x,refusal:b,function_call:S,role:w,tool_calls:k,...j}=u;if(Object.assign(p.message,j),b&&(p.message.refusal=(p.message.refusal||"")+b),w&&(p.message.role=w),S&&(p.message.function_call?(S.name&&(p.message.function_call.name=S.name),S.arguments&&((a=p.message.function_call).arguments??(a.arguments=""),p.message.function_call.arguments+=S.arguments)):p.message.function_call=S),x&&(p.message.content=(p.message.content||"")+x,!p.message.refusal&&W(this,ut,"m",il).call(this)&&(p.message.parsed=$u(p.message.content))),k){p.message.tool_calls||(p.message.tool_calls=[]);for(const{index:C,id:P,type:v,function:M,...E}of k){const _=(i=p.message.tool_calls)[C]??(i[C]={});Object.assign(_,E),P&&(_.id=P),v&&(_.type=v),M&&(_.function??(_.function={name:M.name??"",arguments:""})),M!=null&&M.name&&(_.function.name=M.name),M!=null&&M.arguments&&(_.function.arguments+=M.arguments,qS(W(this,Ws,"f"),_)&&(_.function.parsed_arguments=$u(_.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 Ds(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function QS(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:f,...g})=>{if(!u)throw new Se(`missing finish_reason for choice ${h}`);const{content:y=null,function_call:p,tool_calls:x,...b}=d,S=d.role;if(!S)throw new Se(`missing role for choice ${h}`);if(p){const{arguments:w,name:k}=p;if(w==null)throw new Se(`missing function_call.arguments for choice ${h}`);if(!k)throw new Se(`missing function_call.name for choice ${h}`);return{...g,message:{content:y,function_call:{arguments:w,name:k},role:S,refusal:d.refusal??null},finish_reason:u,index:h,logprobs:f}}return x?{...g,index:h,finish_reason:u,logprobs:f,message:{...b,role:S,content:y,refusal:d.refusal??null,tool_calls:x.map((w,k)=>{const{function:j,type:C,id:P,...v}=w,{arguments:M,name:E,..._}=j||{};if(P==null)throw new Se(`missing choices[${h}].tool_calls[${k}].id
|
|
22
|
+
${Ta(e)}`);if(C==null)throw new Se(`missing choices[${h}].tool_calls[${k}].type
|
|
23
|
+
${Ta(e)}`);if(E==null)throw new Se(`missing choices[${h}].tool_calls[${k}].function.name
|
|
24
|
+
${Ta(e)}`);if(M==null)throw new Se(`missing choices[${h}].tool_calls[${k}].function.arguments
|
|
25
|
+
${Ta(e)}`);return{...v,id:P,type:C,function:{..._,name:E,arguments:M}}})}}:{...g,message:{...b,content:y,role:S,refusal:d.refusal??null},finish_reason:u,index:h,logprobs:f}}),created:o,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return BS(c,t)}function Ta(e){return JSON.stringify(e)}class pi extends ea{static fromReadableStream(t){const s=new pi(null);return s._run(()=>s._fromReadableStream(t)),s}static runTools(t,s,n){const o=new pi(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 gd=class extends _e{constructor(){super(...arguments),this.messages=new Gf(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(re`/chat/completions/${t}`,s)}update(t,s,n){return this._client.post(re`/chat/completions/${t}`,{body:s,...n})}list(t={},s){return this._client.getAPIList("/chat/completions",dt,{query:t,...s})}delete(t,s){return this._client.delete(re`/chat/completions/${t}`,s)}parse(t,s){return HS(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=>pd(n,t))}runTools(t,s){return t.stream?pi.runTools(this._client,t,s):fd.runTools(this._client,t,s)}stream(t,s){return ea.createChatCompletion(this._client,t,s)}};gd.Messages=Gf;class yd extends _e{constructor(){super(...arguments),this.completions=new gd(this._client)}}yd.Completions=gd;const gg=Symbol("brand.privateNullableHeaders");function*ZS(e){if(!e)return;if(gg 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():vu(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=vu(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 xe=e=>{const t=new Headers,s=new Set;for(const n of e){const o=new Set;for(const[a,i]of ZS(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{[gg]:!0,values:t,nulls:s}};class yg extends _e{create(t,s){return this._client.post("/audio/speech",{body:t,...s,headers:xe([{Accept:"application/octet-stream"},s==null?void 0:s.headers]),__binaryResponse:!0})}}class xg extends _e{create(t,s){return this._client.post("/audio/transcriptions",Yn({body:t,...s,stream:t.stream??!1,__metadata:{model:t.model}},this._client))}}class bg extends _e{create(t,s){return this._client.post("/audio/translations",Yn({body:t,...s,__metadata:{model:t.model}},this._client))}}class ua extends _e{constructor(){super(...arguments),this.transcriptions=new xg(this._client),this.translations=new bg(this._client),this.speech=new yg(this._client)}}ua.Transcriptions=xg;ua.Translations=bg;ua.Speech=yg;class vg extends _e{create(t,s){return this._client.post("/batches",{body:t,...s})}retrieve(t,s){return this._client.get(re`/batches/${t}`,s)}list(t={},s){return this._client.getAPIList("/batches",dt,{query:t,...s})}cancel(t,s){return this._client.post(re`/batches/${t}/cancel`,s)}}class Sg extends _e{create(t,s){return this._client.post("/assistants",{body:t,...s,headers:xe([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,s){return this._client.get(re`/assistants/${t}`,{...s,headers:xe([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,s,n){return this._client.post(re`/assistants/${t}`,{body:s,...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t={},s){return this._client.getAPIList("/assistants",dt,{query:t,...s,headers:xe([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}delete(t,s){return this._client.delete(re`/assistants/${t}`,{...s,headers:xe([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class wg extends _e{create(t,s){return this._client.post("/realtime/sessions",{body:t,...s,headers:xe([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class _g extends _e{create(t,s){return this._client.post("/realtime/transcription_sessions",{body:t,...s,headers:xe([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class Fi extends _e{constructor(){super(...arguments),this.sessions=new wg(this._client),this.transcriptionSessions=new _g(this._client)}}Fi.Sessions=wg;Fi.TranscriptionSessions=_g;class Tg extends _e{create(t,s,n){return this._client.post(re`/threads/${t}/messages`,{body:s,...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,s,n){const{thread_id:o}=s;return this._client.get(re`/threads/${o}/messages/${t}`,{...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,s,n){const{thread_id:o,...a}=s;return this._client.post(re`/threads/${o}/messages/${t}`,{body:a,...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s={},n){return this._client.getAPIList(re`/threads/${t}/messages`,dt,{query:s,...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,s,n){const{thread_id:o}=s;return this._client.delete(re`/threads/${o}/messages/${t}`,{...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class kg extends _e{retrieve(t,s,n){const{thread_id:o,run_id:a,...i}=s;return this._client.get(re`/threads/${o}/runs/${a}/steps/${t}`,{query:i,...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s,n){const{thread_id:o,...a}=s;return this._client.getAPIList(re`/threads/${o}/runs/${t}/steps`,dt,{query:a,...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}const ew=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 ll={};const Jn=e=>{var t,s,n,o;if(typeof globalThis.process<"u")return((t=ll==null?void 0:ll[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 Tt,zn,pc,Rs,Ua,ys,Nn,cr,Rn,fi,qt,qa,Ha,Yo,No,Bo,Fu,Lu,Ou,zu,Nu,Bu,Wu;class Xo extends md{constructor(){super(...arguments),Tt.add(this),pc.set(this,[]),Rs.set(this,{}),Ua.set(this,{}),ys.set(this,void 0),Nn.set(this,void 0),cr.set(this,void 0),Rn.set(this,void 0),fi.set(this,void 0),qt.set(this,void 0),qa.set(this,void 0),Ha.set(this,void 0),Yo.set(this,void 0)}[(pc=new WeakMap,Rs=new WeakMap,Ua=new WeakMap,ys=new WeakMap,Nn=new WeakMap,cr=new WeakMap,Rn=new WeakMap,fi=new WeakMap,qt=new WeakMap,qa=new WeakMap,Ha=new WeakMap,Yo=new WeakMap,Tt=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 zn;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=Ds.fromReadableStream(t,this.controller);for await(const i of o)W(this,Tt,"m",No).call(this,i);if((a=o.controller.signal)!=null&&a.aborted)throw new rs;return this._addRun(W(this,Tt,"m",Bo).call(this))}toReadableStream(){return new Ds(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,s,n,o){const a=new zn;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)W(this,Tt,"m",No).call(this,d);if((c=l.controller.signal)!=null&&c.aborted)throw new rs;return this._addRun(W(this,Tt,"m",Bo).call(this))}static createThreadAssistantStream(t,s,n){const o=new zn;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 zn;return a._run(()=>a._runAssistantStream(t,s,n,{...o,headers:{...o==null?void 0:o.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return W(this,qa,"f")}currentRun(){return W(this,Ha,"f")}currentMessageSnapshot(){return W(this,ys,"f")}currentRunStepSnapshot(){return W(this,Yo,"f")}async finalRunSteps(){return await this.done(),Object.values(W(this,Rs,"f"))}async finalMessages(){return await this.done(),Object.values(W(this,Ua,"f"))}async finalRun(){if(await this.done(),!W(this,Nn,"f"))throw Error("Final run was not received.");return W(this,Nn,"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)W(this,Tt,"m",No).call(this,c);if((l=i.controller.signal)!=null&&l.aborted)throw new rs;return this._addRun(W(this,Tt,"m",Bo).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)W(this,Tt,"m",No).call(this,d);if((c=l.controller.signal)!=null&&c.aborted)throw new rs;return this._addRun(W(this,Tt,"m",Bo).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(el(a)&&el(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(!el(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)}}zn=Xo,No=function(t){if(!this.ended)switch(ve(this,qa,t),W(this,Tt,"m",Ou).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":W(this,Tt,"m",Wu).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":W(this,Tt,"m",Lu).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":W(this,Tt,"m",Fu).call(this,t);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Bo=function(){if(this.ended)throw new Se("stream has ended, this shouldn't happen");if(!W(this,Nn,"f"))throw Error("Final run has not been received");return W(this,Nn,"f")},Fu=function(t){const[s,n]=W(this,Tt,"m",Nu).call(this,t,W(this,ys,"f"));ve(this,ys,s),W(this,Ua,"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!=W(this,cr,"f")){if(W(this,Rn,"f"))switch(W(this,Rn,"f").type){case"text":this._emit("textDone",W(this,Rn,"f").text,W(this,ys,"f"));break;case"image_file":this._emit("imageFileDone",W(this,Rn,"f").image_file,W(this,ys,"f"));break}ve(this,cr,o.index)}ve(this,Rn,s.content[o.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(W(this,cr,"f")!==void 0){const o=t.data.content[W(this,cr,"f")];if(o)switch(o.type){case"image_file":this._emit("imageFileDone",o.image_file,W(this,ys,"f"));break;case"text":this._emit("textDone",o.text,W(this,ys,"f"));break}}W(this,ys,"f")&&this._emit("messageDone",t.data),ve(this,ys,void 0)}},Lu=function(t){const s=W(this,Tt,"m",zu).call(this,t);switch(ve(this,Yo,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==W(this,fi,"f")?this._emit("toolCallDelta",a,s.step_details.tool_calls[a.index]):(W(this,qt,"f")&&this._emit("toolCallDone",W(this,qt,"f")),ve(this,fi,a.index),ve(this,qt,s.step_details.tool_calls[a.index]),W(this,qt,"f")&&this._emit("toolCallCreated",W(this,qt,"f")));this._emit("runStepDelta",t.data.delta,s);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":ve(this,Yo,void 0),t.data.step_details.type=="tool_calls"&&W(this,qt,"f")&&(this._emit("toolCallDone",W(this,qt,"f")),ve(this,qt,void 0)),this._emit("runStepDone",t.data,s);break}},Ou=function(t){W(this,pc,"f").push(t),this._emit("event",t)},zu=function(t){switch(t.event){case"thread.run.step.created":return W(this,Rs,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let s=W(this,Rs,"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=zn.accumulateDelta(s,n.delta);W(this,Rs,"f")[t.data.id]=o}return W(this,Rs,"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":W(this,Rs,"f")[t.data.id]=t.data;break}if(W(this,Rs,"f")[t.data.id])return W(this,Rs,"f")[t.data.id];throw new Error("No snapshot available")},Nu=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]=W(this,Tt,"m",Bu).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")},Bu=function(t,s){return zn.accumulateDelta(s,t)},Wu=function(t){switch(ve(this,Ha,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,Nn,t.data),W(this,qt,"f")&&(this._emit("toolCallDone",W(this,qt,"f")),ve(this,qt,void 0));break}};let xd=class extends _e{constructor(){super(...arguments),this.steps=new kg(this._client)}create(t,s,n){const{include:o,...a}=s;return this._client.post(re`/threads/${t}/runs`,{query:{include:o},body:a,...n,headers:xe([{"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(re`/threads/${o}/runs/${t}`,{...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,s,n){const{thread_id:o,...a}=s;return this._client.post(re`/threads/${o}/runs/${t}`,{body:a,...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s={},n){return this._client.getAPIList(re`/threads/${t}/runs`,dt,{query:s,...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(t,s,n){const{thread_id:o}=s;return this._client.post(re`/threads/${o}/runs/${t}/cancel`,{...n,headers:xe([{"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 Xo.createAssistantStream(t,this._client.beta.threads.runs,s,n)}async poll(t,s,n){var a;const o=xe([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 ca(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(t,s,n){return Xo.createAssistantStream(t,this._client.beta.threads.runs,s,n)}submitToolOutputs(t,s,n){const{thread_id:o,...a}=s;return this._client.post(re`/threads/${o}/runs/${t}/submit_tool_outputs`,{body:a,...n,headers:xe([{"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 Xo.createToolAssistantStream(t,this._client.beta.threads.runs,s,n)}};xd.Steps=kg;class Li extends _e{constructor(){super(...arguments),this.runs=new xd(this._client),this.messages=new Tg(this._client)}create(t={},s){return this._client.post("/threads",{body:t,...s,headers:xe([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,s){return this._client.get(re`/threads/${t}`,{...s,headers:xe([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,s,n){return this._client.post(re`/threads/${t}`,{body:s,...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,s){return this._client.delete(re`/threads/${t}`,{...s,headers:xe([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}createAndRun(t,s){return this._client.post("/threads/runs",{body:t,...s,headers:xe([{"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 Xo.createThreadAssistantStream(t,this._client.beta.threads,s)}}Li.Runs=xd;Li.Messages=Tg;class ma extends _e{constructor(){super(...arguments),this.realtime=new Fi(this._client),this.assistants=new Sg(this._client),this.threads=new Li(this._client)}}ma.Realtime=Fi;ma.Assistants=Sg;ma.Threads=Li;class jg extends _e{create(t,s){return this._client.post("/completions",{body:t,...s,stream:t.stream??!1})}}let Cg=class extends _e{retrieve(t,s,n){const{container_id:o}=s;return this._client.get(re`/containers/${o}/files/${t}/content`,{...n,headers:xe([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}},bd=class extends _e{constructor(){super(...arguments),this.content=new Cg(this._client)}create(t,s,n){return this._client.post(re`/containers/${t}/files`,Yn({body:s,...n},this._client))}retrieve(t,s,n){const{container_id:o}=s;return this._client.get(re`/containers/${o}/files/${t}`,n)}list(t,s={},n){return this._client.getAPIList(re`/containers/${t}/files`,dt,{query:s,...n})}delete(t,s,n){const{container_id:o}=s;return this._client.delete(re`/containers/${o}/files/${t}`,{...n,headers:xe([{Accept:"*/*"},n==null?void 0:n.headers])})}};bd.Content=Cg;class vd extends _e{constructor(){super(...arguments),this.files=new bd(this._client)}create(t,s){return this._client.post("/containers",{body:t,...s})}retrieve(t,s){return this._client.get(re`/containers/${t}`,s)}list(t={},s){return this._client.getAPIList("/containers",dt,{query:t,...s})}delete(t,s){return this._client.delete(re`/containers/${t}`,{...s,headers:xe([{Accept:"*/*"},s==null?void 0:s.headers])})}}vd.Files=bd;class Mg extends _e{create(t,s){const n=!!t.encoding_format;let o=n?t.encoding_format:"base64";n&&_t(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:(_t(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=ew(c)}),i)))}}class Pg extends _e{retrieve(t,s,n){const{eval_id:o,run_id:a}=s;return this._client.get(re`/evals/${o}/runs/${a}/output_items/${t}`,n)}list(t,s,n){const{eval_id:o,...a}=s;return this._client.getAPIList(re`/evals/${o}/runs/${t}/output_items`,dt,{query:a,...n})}}class Sd extends _e{constructor(){super(...arguments),this.outputItems=new Pg(this._client)}create(t,s,n){return this._client.post(re`/evals/${t}/runs`,{body:s,...n})}retrieve(t,s,n){const{eval_id:o}=s;return this._client.get(re`/evals/${o}/runs/${t}`,n)}list(t,s={},n){return this._client.getAPIList(re`/evals/${t}/runs`,dt,{query:s,...n})}delete(t,s,n){const{eval_id:o}=s;return this._client.delete(re`/evals/${o}/runs/${t}`,n)}cancel(t,s,n){const{eval_id:o}=s;return this._client.post(re`/evals/${o}/runs/${t}`,n)}}Sd.OutputItems=Pg;class wd extends _e{constructor(){super(...arguments),this.runs=new Sd(this._client)}create(t,s){return this._client.post("/evals",{body:t,...s})}retrieve(t,s){return this._client.get(re`/evals/${t}`,s)}update(t,s,n){return this._client.post(re`/evals/${t}`,{body:s,...n})}list(t={},s){return this._client.getAPIList("/evals",dt,{query:t,...s})}delete(t,s){return this._client.delete(re`/evals/${t}`,s)}}wd.Runs=Sd;let Eg=class extends _e{create(t,s){return this._client.post("/files",Yn({body:t,...s},this._client))}retrieve(t,s){return this._client.get(re`/files/${t}`,s)}list(t={},s){return this._client.getAPIList("/files",dt,{query:t,...s})}delete(t,s){return this._client.delete(re`/files/${t}`,s)}content(t,s){return this._client.get(re`/files/${t}/content`,{...s,headers:xe([{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 ca(s),i=await this.retrieve(t),Date.now()-a>n)throw new dd({message:`Giving up on waiting for file ${t} to finish processing after ${n} milliseconds.`});return i}};class Rg extends _e{}let Ag=class extends _e{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 _d extends _e{constructor(){super(...arguments),this.graders=new Ag(this._client)}}_d.Graders=Ag;class Ig extends _e{create(t,s,n){return this._client.getAPIList(re`/fine_tuning/checkpoints/${t}/permissions`,Di,{body:s,method:"post",...n})}retrieve(t,s={},n){return this._client.get(re`/fine_tuning/checkpoints/${t}/permissions`,{query:s,...n})}delete(t,s,n){const{fine_tuned_model_checkpoint:o}=s;return this._client.delete(re`/fine_tuning/checkpoints/${o}/permissions/${t}`,n)}}let Td=class extends _e{constructor(){super(...arguments),this.permissions=new Ig(this._client)}};Td.Permissions=Ig;class $g extends _e{list(t,s={},n){return this._client.getAPIList(re`/fine_tuning/jobs/${t}/checkpoints`,dt,{query:s,...n})}}class kd extends _e{constructor(){super(...arguments),this.checkpoints=new $g(this._client)}create(t,s){return this._client.post("/fine_tuning/jobs",{body:t,...s})}retrieve(t,s){return this._client.get(re`/fine_tuning/jobs/${t}`,s)}list(t={},s){return this._client.getAPIList("/fine_tuning/jobs",dt,{query:t,...s})}cancel(t,s){return this._client.post(re`/fine_tuning/jobs/${t}/cancel`,s)}listEvents(t,s={},n){return this._client.getAPIList(re`/fine_tuning/jobs/${t}/events`,dt,{query:s,...n})}pause(t,s){return this._client.post(re`/fine_tuning/jobs/${t}/pause`,s)}resume(t,s){return this._client.post(re`/fine_tuning/jobs/${t}/resume`,s)}}kd.Checkpoints=$g;class jr extends _e{constructor(){super(...arguments),this.methods=new Rg(this._client),this.jobs=new kd(this._client),this.checkpoints=new Td(this._client),this.alpha=new _d(this._client)}}jr.Methods=Rg;jr.Jobs=kd;jr.Checkpoints=Td;jr.Alpha=_d;class Dg extends _e{}class jd extends _e{constructor(){super(...arguments),this.graderModels=new Dg(this._client)}}jd.GraderModels=Dg;class Fg extends _e{createVariation(t,s){return this._client.post("/images/variations",Yn({body:t,...s},this._client))}edit(t,s){return this._client.post("/images/edits",Yn({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 Lg extends _e{retrieve(t,s){return this._client.get(re`/models/${t}`,s)}list(t){return this._client.getAPIList("/models",Di,t)}delete(t,s){return this._client.delete(re`/models/${t}`,s)}}class Og extends _e{create(t,s){return this._client.post("/moderations",{body:t,...s})}}function tw(e,t){return!t||!nw(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)}:zg(e,t)}function zg(e,t){const s=e.output.map(o=>{if(o.type==="function_call")return{...o,parsed_arguments:aw(t,o)};if(o.type==="message"){const a=o.content.map(i=>i.type==="output_text"?{...i,parsed:sw(t,i.text)}:i);return{...o,content:a}}return o}),n=Object.assign({},e,{output:s});return Object.getOwnPropertyDescriptor(e,"output_text")||fc(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 sw(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 nw(e){var t;return!!hd((t=e.text)==null?void 0:t.format)}function rw(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function ow(e,t){return e.find(s=>s.type==="function"&&s.name===t)}function aw(e,t){const s=ow(e.tools??[],t.name);return{...t,...t,parsed_arguments:rw(s)?s.$parseRaw(t.arguments):s!=null&&s.strict?JSON.parse(t.arguments):null}}function fc(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 Qn,ka,on,ja,Uu,qu,Hu,Yu;class Cd extends md{constructor(t){super(),Qn.add(this),ka.set(this,void 0),on.set(this,void 0),ja.set(this,void 0),ve(this,ka,t)}static createResponse(t,s,n){const o=new Cd(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())),W(this,Qn,"m",Uu).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)W(this,Qn,"m",qu).call(this,c,i);if((l=a.controller.signal)!=null&&l.aborted)throw new rs;return W(this,Qn,"m",Hu).call(this)}[(ka=new WeakMap,on=new WeakMap,ja=new WeakMap,Qn=new WeakSet,Uu=function(){this.ended||ve(this,on,void 0)},qu=function(s,n){if(this.ended)return;const o=(i,l)=>{(n==null||l.sequence_number>n)&&this._emit(i,l)},a=W(this,Qn,"m",Yu).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}},Hu=function(){if(this.ended)throw new Se("stream has ended, this shouldn't happen");const s=W(this,on,"f");if(!s)throw new Se("request ended without sending any events");ve(this,on,void 0);const n=iw(s,W(this,ka,"f"));return ve(this,ja,n),n},Yu=function(s){let n=W(this,on,"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,on,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,on,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=W(this,ja,"f");if(!t)throw new Se("stream ended without producing a ChatCompletion");return t}}function iw(e,t){return tw(e,t)}class Ng extends _e{list(t,s={},n){return this._client.getAPIList(re`/responses/${t}/input_items`,dt,{query:s,...n})}}class Md extends _e{constructor(){super(...arguments),this.inputItems=new Ng(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"&&fc(n),n))}retrieve(t,s={},n){return this._client.get(re`/responses/${t}`,{query:s,...n,stream:(s==null?void 0:s.stream)??!1})._thenUnwrap(o=>("object"in o&&o.object==="response"&&fc(o),o))}delete(t,s){return this._client.delete(re`/responses/${t}`,{...s,headers:xe([{Accept:"*/*"},s==null?void 0:s.headers])})}parse(t,s){return this._client.responses.create(t,s)._thenUnwrap(n=>zg(n,t))}stream(t,s){return Cd.createResponse(this._client,t,s)}cancel(t,s){return this._client.post(re`/responses/${t}/cancel`,s)}}Md.InputItems=Ng;class Bg extends _e{create(t,s,n){return this._client.post(re`/uploads/${t}/parts`,Yn({body:s,...n},this._client))}}class Pd extends _e{constructor(){super(...arguments),this.parts=new Bg(this._client)}create(t,s){return this._client.post("/uploads",{body:t,...s})}cancel(t,s){return this._client.post(re`/uploads/${t}/cancel`,s)}complete(t,s,n){return this._client.post(re`/uploads/${t}/complete`,{body:s,...n})}}Pd.Parts=Bg;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 Wg extends _e{create(t,s,n){return this._client.post(re`/vector_stores/${t}/file_batches`,{body:s,...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,s,n){const{vector_store_id:o}=s;return this._client.get(re`/vector_stores/${o}/file_batches/${t}`,{...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(t,s,n){const{vector_store_id:o}=s;return this._client.post(re`/vector_stores/${o}/file_batches/${t}/cancel`,{...n,headers:xe([{"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(re`/vector_stores/${o}/file_batches/${t}/files`,dt,{query:a,...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async poll(t,s,n){var a;const o=xe([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 ca(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(f){for(let g of f){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 Ug extends _e{create(t,s,n){return this._client.post(re`/vector_stores/${t}/files`,{body:s,...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,s,n){const{vector_store_id:o}=s;return this._client.get(re`/vector_stores/${o}/files/${t}`,{...n,headers:xe([{"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(re`/vector_stores/${o}/files/${t}`,{body:a,...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s={},n){return this._client.getAPIList(re`/vector_stores/${t}/files`,dt,{query:s,...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,s,n){const{vector_store_id:o}=s;return this._client.delete(re`/vector_stores/${o}/files/${t}`,{...n,headers:xe([{"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=xe([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 ca(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(re`/vector_stores/${o}/files/${t}/content`,Di,{...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class Oi extends _e{constructor(){super(...arguments),this.files=new Ug(this._client),this.fileBatches=new Wg(this._client)}create(t,s){return this._client.post("/vector_stores",{body:t,...s,headers:xe([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,s){return this._client.get(re`/vector_stores/${t}`,{...s,headers:xe([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,s,n){return this._client.post(re`/vector_stores/${t}`,{body:s,...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t={},s){return this._client.getAPIList("/vector_stores",dt,{query:t,...s,headers:xe([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}delete(t,s){return this._client.delete(re`/vector_stores/${t}`,{...s,headers:xe([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}search(t,s,n){return this._client.getAPIList(re`/vector_stores/${t}/search`,Di,{body:s,method:"post",...n,headers:xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}Oi.Files=Ug;Oi.FileBatches=Wg;var ir,qg,Ya;class Hg extends _e{constructor(){super(...arguments),ir.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");W(this,ir,"m",qg).call(this,n);const a=xe([s]).values,i=W(this,ir,"m",Ya).call(this,a,"webhook-signature"),l=W(this,ir,"m",Ya).call(this,a,"webhook-timestamp"),c=W(this,ir,"m",Ya).call(this,a,"webhook-id"),d=parseInt(l,10);if(isNaN(d))throw new Io("Invalid webhook timestamp format");const u=Math.floor(Date.now()/1e3);if(u-d>o)throw new Io("Webhook timestamp is too old");if(d>u+o)throw new Io("Webhook timestamp is too new");const h=i.split(" ").map(p=>p.startsWith("v1,")?p.substring(3):p),f=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",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const p of h)try{const x=Buffer.from(p,"base64");if(await crypto.subtle.verify("HMAC",y,x,new TextEncoder().encode(g)))return}catch{continue}throw new Io("The given webhook signature does not match the expected signature")}}ir=new WeakSet,qg=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")},Ya=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 gc,Ed,Xa,Yg;class Ie{constructor({baseURL:t=Jn("OPENAI_BASE_URL"),apiKey:s=Jn("OPENAI_API_KEY"),organization:n=Jn("OPENAI_ORG_ID")??null,project:o=Jn("OPENAI_PROJECT_ID")??null,webhookSecret:a=Jn("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(gc.add(this),Xa.set(this,void 0),this.completions=new jg(this),this.chat=new yd(this),this.embeddings=new Mg(this),this.files=new Eg(this),this.images=new Fg(this),this.audio=new ua(this),this.moderations=new Og(this),this.models=new Lg(this),this.fineTuning=new jr(this),this.graders=new jd(this),this.vectorStores=new Oi(this),this.webhooks=new Hg(this),this.beta=new ma(this),this.batches=new vg(this),this.uploads=new Pd(this),this.responses=new Md(this),this.evals=new wd(this),this.containers=new vd(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&&cS())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??Ed.DEFAULT_TIMEOUT,this.logger=l.logger??console;const c="warn";this.logLevel=c,this.logLevel=Eu(l.logLevel,"ClientOptions.logLevel",this)??Eu(Jn("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??pS(),ve(this,Xa,gS),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 xe([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return wS(t,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${or}`}defaultIdempotencyKey(){return`stainless-node-retry-${Tf()}`}makeStatusError(t,s,n,o){return kt.generate(t,s,n,o)}buildURL(t,s,n){const o=!W(this,gc,"m",Yg).call(this)&&n||this.baseURL,a=nS(t)?new URL(t):new URL(o+(o.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),i=this.defaultQuery();return oS(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 $i(this,this.makeRequest(t,s,void 0))}async makeRequest(t,s,n){var b,S;const o=await t,a=o.maxRetries??this.maxRetries;s==null&&(s=a),await this.prepareOptions(o);const{req:i,url:l,timeout:c}=await this.buildRequest(o,{retryCount:a-s});await this.prepareRequest(i,{url:l,options:o});const d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,h=Date.now();if(_t(this).debug(`[${d}] sending request`,Cn({retryOfRequestLogID:n,method:o.method,url:l,options:o,headers:i.headers})),(b=o.signal)!=null&&b.aborted)throw new rs;const f=new AbortController,g=await this.fetchWithTimeout(l,i,c,f).catch(oc),y=Date.now();if(g instanceof Error){const w=`retrying, ${s} attempts remaining`;if((S=o.signal)!=null&&S.aborted)throw new rs;const k=rc(g)||/timed? ?out/i.test(String(g)+("cause"in g?String(g.cause):""));if(s)return _t(this).info(`[${d}] connection ${k?"timed out":"failed"} - ${w}`),_t(this).debug(`[${d}] connection ${k?"timed out":"failed"} (${w})`,Cn({retryOfRequestLogID:n,url:l,durationMs:y-h,message:g.message})),this.retryRequest(o,s,n??d);throw _t(this).info(`[${d}] connection ${k?"timed out":"failed"} - error; no more retries left`),_t(this).debug(`[${d}] connection ${k?"timed out":"failed"} (error; no more retries left)`,Cn({retryOfRequestLogID:n,url:l,durationMs:y-h,message:g.message})),k?new dd:new Ai({cause:g})}const p=[...g.headers.entries()].filter(([w])=>w==="x-request-id").map(([w,k])=>", "+w+": "+JSON.stringify(k)).join(""),x=`[${d}${u}${p}] ${i.method} ${l} ${g.ok?"succeeded":"failed"} with status ${g.status} in ${y-h}ms`;if(!g.ok){const w=await this.shouldRetry(g);if(s&&w){const M=`retrying, ${s} attempts remaining`;return await fS(g.body),_t(this).info(`${x} - ${M}`),_t(this).debug(`[${d}] response error (${M})`,Cn({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:y-h})),this.retryRequest(o,s,n??d,g.headers)}const k=w?"error; no more retries left":"error; not retryable";_t(this).info(`${x} - ${k}`);const j=await g.text().catch(M=>oc(M).message),C=lS(j),P=C?void 0:j;throw _t(this).debug(`[${d}] response error (${k})`,Cn({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,message:P,durationMs:Date.now()-h})),this.makeStatusError(g.status,C,P,g.headers)}return _t(this).info(x),_t(this).debug(`[${d}] response start`,Cn({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:y-h})),{response:g,options:o,controller:f,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 RS(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 ca(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&&iS("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=xe([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))}:{},...hS(),"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=xe([s]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:Ff(t)}:W(this,Xa,"f").call(this,{body:t,headers:n})}}Ed=Ie,Xa=new WeakMap,gc=new WeakSet,Yg=function(){return this.baseURL!=="https://api.openai.com/v1"};Ie.OpenAI=Ed;Ie.DEFAULT_TIMEOUT=6e5;Ie.OpenAIError=Se;Ie.APIError=kt;Ie.APIConnectionError=Ai;Ie.APIConnectionTimeoutError=dd;Ie.APIUserAbortError=rs;Ie.NotFoundError=Mf;Ie.ConflictError=Pf;Ie.RateLimitError=Rf;Ie.BadRequestError=kf;Ie.AuthenticationError=jf;Ie.InternalServerError=Af;Ie.PermissionDeniedError=Cf;Ie.UnprocessableEntityError=Ef;Ie.InvalidWebhookSignatureError=Io;Ie.toFile=LS;Ie.Completions=jg;Ie.Chat=yd;Ie.Embeddings=Mg;Ie.Files=Eg;Ie.Images=Fg;Ie.Audio=ua;Ie.Moderations=Og;Ie.Models=Lg;Ie.FineTuning=jr;Ie.Graders=jd;Ie.VectorStores=Oi;Ie.Webhooks=Hg;Ie.Beta=ma;Ie.Batches=vg;Ie.Uploads=Pd;Ie.Responses=Md;Ie.Evals=wd;Ie.Containers=vd;let Ca=null,cl=null;const cw=()=>{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`},Xg=()=>{const e=cw();return Ca?cl!==e&&(Ca=new Ie({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),cl=e):(Ca=new Ie({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),cl=e),Ca};function zi(e){const t=Yt(a=>a.currentProvider),s=Yt(a=>a.providerConfig),n=N(Vn(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 Vg(e){const t=zi(e),s=Yt(o=>o.currentProvider),n=Yt(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])}const dl="__BODHI_PROMPT_TITLE__",Va=e=>e.trim().toLowerCase(),dw=(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},ul=e=>{const t=new Set,s=as.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=dw(o,e);if(!a)return;const i=Va(a);i&&t.add(i)}),Array.from(t))},uw=e=>{const t=new Set(["new session","new chat","main"]),s=new Set(["new session","new chat"]),n=[],o=i=>{const l=Va(i);l&&(t.add(l),s.add(l))},a=i=>{const l=Va(i);if(l){if(l.includes("{{prompt}}")){const[c,d]=l.split("{{prompt}}",2);n.push({prefix:c,suffix:d});return}if(l.includes(dl.toLowerCase())){const[c,d]=l.split(dl.toLowerCase(),2);n.push({prefix:c,suffix:d});return}s.add(l)}};return ul(["chat","sidebar","newSession"]).forEach(o),ul(["chat","session","defaultTitle"]).forEach(o),ul(["chat","sidebar","newSessionWithPrompt"]).forEach(a),o(e("chat.sidebar.newSession")),o(e("chat.session.defaultTitle")),a(e("chat.sidebar.newSessionWithPrompt",{prompt:dl})),i=>{if(!i)return!0;const l=Va(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}},Rd=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 f;return(f=h==null?void 0:h.description)==null?void 0:f.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""},Xu=e=>e.filter(t=>t.role!=="user"&&t.role!=="assistant"?!1:Rd(t).length>0);function Ad(e){const{message:t}=us.useApp(),{t:s}=se(),n=N(p=>p.autoGenerateTitles),o=Vg(),a=zi(),i=N(p=>p.setAutoGenerateTitlesPreference),l=N(p=>p.isUpdatingAutoTitlePreference),c=m.useRef(new Set),d=m.useRef(new Set),[u,h]=m.useState({}),f=m.useMemo(()=>uw((p,x)=>s(p,x)),[s]),g=m.useCallback(p=>f(p),[f]),y=m.useCallback(async(p,x)=>{var j,C;let b=e.chats.find(P=>P.id===p);if(!b)return!1;let S=Xu(b.messages);if(x!=null&&x.force&&S.length===0){await N.getState().loadChatHistory(p,{mode:"replace"});const P=N.getState().chats.find(v=>v.id===p);P&&(b=P,S=Xu(P.messages))}const w=!(x!=null&&x.force);if(w&&!n||w&&(d.current.has(p)||c.current.has(p)||!g(b.title)||S.length===0||S.length>6))return!1;d.current.add(p),h(P=>({...P,[p]:{status:"loading"}}));try{const P=(o==null?void 0:o.trim())||"",v=(a==null?void 0:a.trim())||"";let M,E="";if(P)try{E=await Ku(S,P)}catch(_){M=_}if(!E&&v&&v!==P)try{E=await Ku(S,v)}catch(_){M||(M=_)}if(E||(E=fw(S)),!E){if(w)return h(_=>({..._,[p]:{status:"idle"}})),!1;throw M instanceof Error?M:new Error(s("chat.title.generateFailed"))}return e.updateSession(p,{title:E}),(!w||E.toLowerCase()!=="new chat")&&c.current.add(p),h(_=>({..._,[p]:{status:"idle"}})),x!=null&&x.force&&((j=t==null?void 0:t.success)==null||j.call(t,s("chat.title.updated"))),!0}catch(P){const v=P instanceof Error?P.message:s("chat.title.generateFailed");throw h(M=>({...M,[p]:{status:"error",error:v}})),x!=null&&x.force?(C=t==null?void 0:t.error)==null||C.call(t,v):console.warn("[ChatTitleGeneration] Auto title generation failed:",v),P instanceof Error?P:new Error(v)}finally{d.current.delete(p)}},[t,n,g,o,a,e,s]);return{titleGenerationState:u,autoGenerateTitles:n,isUpdatingAutoTitlePreference:l,generateChatTitle:y,setAutoGenerateTitlesPreference:i,isDefaultTitle:g}}const yc=60,mw=20,hw=8,Vu=220,pw=e=>e.slice(0,hw).map(n=>{const o=n.role==="user"?"User":"Assistant",a=Rd(n);if(!a)return"";const i=a.length>Vu?`${a.slice(0,Vu-3)}...`:a;return`${o}: ${i}`}).filter(n=>n.length>0).join(`
|
|
35
|
+
`),fw=e=>{const t=[...e.filter(s=>s.role==="user"),...e.filter(s=>s.role!=="user")];for(const s of t){const n=Rd(s).replace(/\s+/g," ").trim();if(!n)continue;const o=Kg(n);if(o)return o}return""},Kg=e=>{var n;const s=(((n=e.split(/\r?\n/)[0])==null?void 0:n.trim())??"").replace(/^["']+|["']+$/g,"");return s.length<=yc?s:`${s.slice(0,yc-3)}...`},gw=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:""},Ku=async(e,t)=>{var l,c;const s=pw(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 Xg().chat.completions.create({model:n,temperature:.2,max_tokens:mw,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 ${yc} characters) for this chat:
|
|
37
|
+
|
|
38
|
+
${s}`}]}),i=gw((c=(l=a.choices)==null?void 0:l[0])==null?void 0:c.message).trim();return Kg(i)},Ma={THEME:"copilot_ui_theme_v1",LAYOUT:"copilot_ui_layout_v1"};class yw{getTheme(){try{return localStorage.getItem(Ma.THEME)}catch(t){return console.error("Failed to get theme:",t),null}}setTheme(t){try{localStorage.setItem(Ma.THEME,t)}catch(s){console.error("Failed to set theme:",s)}}getLayout(){try{return localStorage.getItem(Ma.LAYOUT)}catch(t){return console.error("Failed to get layout:",t),null}}setLayout(t){try{localStorage.setItem(Ma.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 Gg=new yw,Id={collapsed:!1,widthPx:260,collapsedWidthPx:72,minWidthPx:180,maxWidthPx:520},Jg={v:2,sidebar:Id,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:null},splitSizesPx:{}},Gu=e=>{const t=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return`${e}-${t}`},Ht=e=>e.type==="leaf"?[e.id]:[...Ht(e.children[0]),...Ht(e.children[1])],ta=e=>e.type==="leaf"?[]:[e.id,...ta(e.children[0]),...ta(e.children[1])],xw=(e,t)=>{for(const[s,n]of Object.entries(e))if(n===t)return s;return null},bw=(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},xc=(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:[xc(e.children[0],t,s,n,o),xc(e.children[1],t,s,n,o)]},bc=(e,t)=>{if(e.type==="leaf")return e.id===t?{node:null,removed:!0}:{node:e,removed:!1};const s=bc(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=bc(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}),Sw=e=>{try{Gg.setLayout(JSON.stringify(e))}catch(t){console.warn("[uiLayoutStore] Failed to persist layout:",t)}},Us=e=>{const t=vw(e);return Sw(t),t},ww=e=>{var f,g,y,p,x,b,S,w,k,j,C;const t={...Id,...e.sidebar||{}},s=((f=e.view)==null?void 0:f.mode)??"single",n=((g=e.view)==null?void 0:g.twoDirection)??"horizontal",o={...((y=e.panes)==null?void 0:y.sessionIds)||{}},a=((p=e.panes)==null?void 0:p.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 P="split-root",v=n,M=v==="horizontal"?{type:"split",id:P,layout:v,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"rt"}]}:{type:"split",id:P,layout:v,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},E=v==="horizontal"?((x=e.split)==null?void 0:x.twoHorizontalPx)||((b=e.split)==null?void 0:b.columnsPx)||null:((S=e.split)==null?void 0:S.twoVerticalPx)||((w=e.split)==null?void 0:w.leftRowsPx)||null;E&&(i[P]=E);const _=Ht(M);return{v:2,sidebar:t,tree:M,activeLeafId:_.includes(a)?a:_[0],leafSessionIds:Object.fromEntries(_.map(R=>[R,o[R]??null])),splitSizesPx:i}}const l="split-root",c="split-left",d="split-right",u={type:"split",id:l,layout:"horizontal",children:[{type:"split",id:c,layout:"vertical",children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},{type:"split",id:d,layout:"vertical",children:[{type:"leaf",id:"rt"},{type:"leaf",id:"rb"}]}]};(k=e.split)!=null&&k.columnsPx&&(i[l]=e.split.columnsPx),(j=e.split)!=null&&j.leftRowsPx&&(i[c]=e.split.leftRowsPx),(C=e.split)!=null&&C.rightRowsPx&&(i[d]=e.split.rightRowsPx);const h=Ht(u);return{v:2,sidebar:t,tree:u,activeLeafId:h.includes(a)?a:h[0],leafSessionIds:Object.fromEntries(h.map(P=>[P,o[P]??null])),splitSizesPx:i}},_w=e=>{if(!e)return null;try{const t=JSON.parse(e);if(!t||typeof t!="object")return null;if(t.v===2){const s={...Id,...t.sidebar||{}},n=t.tree||Jg.tree,o=Ht(n),a=ta(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 f;const h=(f=t.splitSizesPx)==null?void 0:f[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=bw(o,i);return{v:2,sidebar:s,tree:n,activeLeafId:c,leafSessionIds:d,splitSizesPx:l}}return t.v===1?ww(t):null}catch{return null}},Tw=()=>_w(Gg.getLayout())??Jg,$e=xn(e=>({...Tw(),setSidebarCollapsed:t=>{e(s=>s.sidebar.collapsed===t?s:Us({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:Us({sidebar:{...s.sidebar,widthPx:n},tree:s.tree,activeLeafId:s.activeLeafId,leafSessionIds:s.leafSessionIds,splitSizesPx:s.splitSizesPx})})},setActiveLeafId:t=>{e(s=>s.activeLeafId===t||!Ht(s.tree).includes(t)?s:(ns("setActiveLeafId",{from:s.activeLeafId,to:t}),Us({sidebar:s.sidebar,tree:s.tree,activeLeafId:t,leafSessionIds:s.leafSessionIds,splitSizesPx:s.splitSizesPx})))},setLeafSessionId:(t,s)=>{e(n=>{const o=Ht(n.tree);if(!o.includes(t)||(n.leafSessionIds[t]??null)===s)return n;const a=[];ns("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&&ns("setLeafSessionId dedupe",{sessionId:s,clearedLeafIds:a,assignedLeafId:t}),o.forEach(l=>{l in i||(i[l]=null)}),Us({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?Us({sidebar:s.sidebar,tree:s.tree,activeLeafId:s.activeLeafId,leafSessionIds:n,splitSizesPx:s.splitSizesPx}):s})},splitLeaf:(t,s)=>{e(n=>{const o=Ht(n.tree);if(!o.includes(t)||o.length>=4)return n;const a=Gu("split"),i=Gu("pane"),l=xc(n.tree,t,s,a,i),c={...n.leafSessionIds,[i]:null};return Us({sidebar:n.sidebar,tree:l,activeLeafId:i,leafSessionIds:c,splitSizesPx:n.splitSizesPx})})},closeLeaf:t=>{e(s=>{const n=Ht(s.tree);if(!n.includes(t)||n.length<=1)return s;const o=bc(s.tree,t);if(!o.removed||!o.node)return s;const a=o.node,i=Ht(a),l=ta(a),c={};i.forEach(h=>{c[h]=s.leafSessionIds[h]??null});const d={};l.forEach(h=>{const f=s.splitSizesPx[h];f&&(d[h]=f)});const u=s.activeLeafId===t?i[0]:i.includes(s.activeLeafId)?s.activeLeafId:i[0];return Us({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:Us({sidebar:n.sidebar,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:{...n.splitSizesPx,[t]:s}})})},pruneSplitSizes:()=>{e(t=>{const s=new Set(ta(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:Us({sidebar:t.sidebar,tree:t.tree,activeLeafId:t.activeLeafId,leafSessionIds:t.leafSessionIds,splitSizesPx:n})})}})),kw=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)},Ni=(e,t)=>{const{activeLeafId:s,leafSessionIds:n,setLeafSessionId:o,setActiveLeafId:a}=$e.getState(),i=xw(n,e),l=n[s]??null;ns("openSession (input)",{activeLeafId:s,activeLeafSessionId:l,sessionId:e,existingLeafId:i}),i?i===s?ns("openSession (decision)",{action:"noop_already_active",leafId:s,sessionId:e}):(a(i),ns("openSession (decision)",{action:"focus_existing_leaf",leafId:i,sessionId:e})):(o(s,e),ns("openSession (decision)",{action:"assign_to_active_leaf",leafId:s,sessionId:e})),N.getState().selectSession(e),kw(e,t)},ml=(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))},hl=(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}},jw=()=>{const{t:e}=se(),t=N(X=>X.chats),s=N(X=>X.currentSessionId),n=N(X=>X.deleteSession),o=N(X=>X.deleteSessions),a=N(X=>X.pinSession),i=N(X=>X.unpinSession),l=N(X=>X.updateSession),c=N(X=>X.addChat),d=N(X=>X.lastSelectedPromptId),u=N(X=>X.systemPrompts),h=$e(X=>X.sidebar.collapsed),f=$e(X=>X.setSidebarCollapsed),g=$e(X=>X.clearSessionFromAllLeaves),{generateChatTitle:y,titleGenerationState:p}=Ad({chats:t,updateSession:l}),x=m.useCallback(async(X,ue)=>{var it,bt;const ie=u.find(st=>st.id===d),le=(ie==null?void 0:ie.id)||(u.length>0?((it=u.find(st=>st.id==="general_assistant"))==null?void 0:it.id)||u[0].id:""),Ae={title:X||e("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:le,baseSystemPrompt:(ie==null?void 0:ie.content)||(u.length>0?((bt=u.find(st=>st.id==="general_assistant"))==null?void 0:bt.content)||u[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null,...ue},Et=await c(Ae),{activeLeafId:Ct}=$e.getState();$e.getState().setLeafSessionId(Ct,Et),$e.getState().setActiveLeafId(Ct)},[c,d,u,e]),[b,S]=m.useState(!1),[w,k]=m.useState(new Set(["Today"])),[j,C]=m.useState(""),[P,v]=m.useState("all"),M=N(Vn(s)),E=m.useMemo(()=>M?yu(M):null,[M]),_=m.useMemo(()=>{const X=new Set(w);return E&&X.add(E),Array.from(X)},[E,w]),R=X=>{const ue=new Set(Array.isArray(X)?X:[X]);k(ie=>{if(ie.size!==ue.size)return ue;for(const le of ue)if(!ie.has(le))return ue;return ie})},T=j.trim().toLowerCase(),D=T.length>0||P!=="all",$=m.useMemo(()=>t.filter(X=>X.kind!=="child"),[t]),I=m.useMemo(()=>{const X={};for(const ue of t){if(ue.kind!=="child")continue;const ie=ue.parentSessionId||ue.rootSessionId;ie&&(X[ie]||(X[ie]=[]),X[ie].push(ue))}return Object.keys(X).forEach(ue=>{X[ue].sort((ie,le)=>{if(ie.pinned!==le.pinned)return ie.pinned?-1:1;const Ae=Date.parse(ie.updatedAt||"")||ie.createdAt||0;return(Date.parse(le.updatedAt||"")||le.createdAt||0)-Ae})}),X},[t]),O=m.useMemo(()=>D?$.filter(X=>ml(X,T)&&hl(X,P)?!0:(I[X.id]||[]).some(le=>ml(le,T)&&hl(le,P))):$,[I,D,T,$,P]),A=m.useMemo(()=>{if(!D)return I;const X={};for(const ue of O){const ie=I[ue.id]||[];X[ue.id]=ie.filter(le=>ml(le,T)&&hl(le,P))}return X},[I,O,D,T,P]),z=Yv(O),L=Xv(z),Y=m.useCallback(X=>{a(X),k(ue=>{if(ue.has("Pinned"))return ue;const ie=new Set(ue);return ie.add("Pinned"),ie})},[a]),F=m.useCallback(X=>{const ue=t.find(le=>le.id===X),ie=ue?yu({...ue,pinned:!1}):null;i(X),ie&&k(le=>{if(le.has(ie))return le;const Ae=new Set(le);return Ae.add(ie),Ae})},[t,i]),q=X=>{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:()=>{g(X),n(X)}})},K=pn(X=>X.open),G=()=>{K("chat")},be=m.useCallback(X=>{C(X)},[]),Pe=m.useCallback(X=>{v(X)},[]),Ee=(X,ue)=>{l(X,{title:ue})},Te=async X=>{try{await y(X,{force:!0})}catch(ue){console.error("Failed to generate title:",ue)}},ge=X=>{const ue=Vv(z,X),ie=_f(z,X);Lt.confirm({title:e("chat.sidebar.deleteByDate.title",{date:X}),content:e("chat.sidebar.deleteByDate.confirm",{count:ie,date:X}),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{ue.forEach(le=>g(le)),o(ue)}})},je=()=>{S(!0)},Be=()=>{S(!1)},Qe=async X=>{try{await x(e("chat.sidebar.newSessionWithPrompt",{prompt:X.name}),{config:{systemPromptId:X.id,baseSystemPrompt:X.content,lastUsedEnhancedPrompt:null}}),S(!1)}catch(ue){console.error("Failed to create chat:",ue),Lt.error({title:e("chat.sidebar.createFailedTitle"),content:ue instanceof Error?ue.message:e("chat.sidebar.createFailedUnknown")})}},jt=m.useCallback(X=>Ni(X),[]),[Ze,Bt]=m.useState(new Set),B=m.useMemo(()=>{var ie;const X=new Set(Ze),ue=t.find(le=>le.id===s);if(ue){const le=ue.kind==="child"?ue.parentSessionId||ue.rootSessionId:ue.id;le&&X.add(le)}for(const le of t)if(le.kind==="child"&&le.pinned){const Ae=le.parentSessionId||le.rootSessionId;Ae&&X.add(Ae)}if(D)for(const le of O)(((ie=A[le.id])==null?void 0:ie.length)??0)>0&&X.add(le.id);return X},[t,A,s,Ze,O,D]),Me=m.useCallback(X=>{Bt(ue=>{const ie=new Set(ue);return ie.has(X)?ie.delete(X):ie.add(X),ie})},[]);return{chats:O,childrenByRoot:A,expandedRootIds:B,toggleRootExpanded:Me,collapsed:h,currentSessionId:s,expandedKeys:_,groupedChatsByDate:z,hasActiveFilters:D,handleCollapseChange:R,handleDelete:q,handleDeleteByDate:ge,handleEditTitle:Ee,handleGenerateTitle:Te,handleNewChat:je,handleNewChatSelectorClose:Be,handleOpenSettings:G,handleSearchQueryChange:be,handleStatusFilterChange:Pe,handleSystemPromptSelect:Qe,isNewChatSelectorOpen:b,pinSession:Y,searchQuery:j,selectSession:jt,setCollapsed:f,sortedDateKeys:L,statusFilter:P,systemPrompts:u,titleGenerationState:p,unpinSession:F}},{useBreakpoint:Cw}=Ci,{useToken:Mw}=pe,Pw=()=>{const{token:e}=Mw(),{t}=se(),s=Cw(),{childrenByRoot:n,expandedRootIds:o,toggleRootExpanded:a,collapsed:i,currentSessionId:l,expandedKeys:c,groupedChatsByDate:d,handleCollapseChange:u,handleDelete:h,handleDeleteByDate:f,handleEditTitle:g,handleGenerateTitle:y,handleNewChat:p,handleNewChatSelectorClose:x,handleOpenSettings:b,handleSearchQueryChange:S,handleStatusFilterChange:w,handleSystemPromptSelect:k,hasActiveFilters:j,isNewChatSelectorOpen:C,pinSession:P,searchQuery:v,selectSession:M,setCollapsed:E,sortedDateKeys:_,statusFilter:R,systemPrompts:T,titleGenerationState:D,unpinSession:$}=jw(),{xs:I,sm:O}=s;return m.useEffect(()=>{typeof I!="boolean"||typeof O!="boolean"||I===!1&&O===!1&&E(!0)},[O,I,E]),i?null:r.jsxs("nav",{"aria-label":t("chat.sidebar.title","Chat sidebar"),style:{width:"100%",height:"100%",background:"transparent",borderRight:`1px solid ${e.colorBorderSecondary}`,position:"relative",overflow:"hidden",display:"flex",flexDirection:"column",minHeight:0},children:[r.jsx(J,{justify:"flex-end",style:{flexShrink:0,padding:"10px 12px 2px 12px",minHeight:40},children:r.jsx(U,{type:"text",icon:r.jsx(Yp,{}),onClick:()=>E(!0),size:s.xs?"small":"middle",className:"lotus-toolbar-icon","aria-label":t("chat.sidebar.collapse","Collapse sidebar")})}),r.jsxs(J,{vertical:!0,gap:"small",style:{flexShrink:0,padding:"10px 12px 8px 12px"},children:[r.jsx(he,{allowClear:!0,value:v,onChange:A=>S(A.target.value),prefix:r.jsx(Qo,{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(qx,{block:!0,size:s.xs?"middle":"small",value:R,onChange:A=>w(A),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(J,{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(Kv,{groupedChatsByDate:d,childrenByRoot:n,expandedRootIds:o,onToggleRootExpanded:a,sortedDateKeys:_,expandedKeys:c,onCollapseChange:u,currentSessionId:l,onSelectChat:M,onDeleteChat:h,onDeleteByDate:f,onPinChat:P,onUnpinChat:$,onEditTitle:g,onGenerateTitle:y,titleGenerationState:D,token:e,hasActiveFilters:j})}),r.jsx(tS,{collapsed:!1,onNewChat:p,onOpenSettings:b,screens:s,token:e}),r.jsx(Uv,{open:C,onClose:x,onSelect:k,prompts:T,title:t("chat.prompt.newSessionSelectorTitle"),showCancelButton:!0})]})},Ju=e=>Symbol.iterator in e,Qu=e=>"entries"in e,Zu=(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},Ew=(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 Rw(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:Ju(e)&&Ju(t)?Qu(e)&&Qu(t)?Zu(e,t):Ew(e,t):Zu({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Aw(e){const t=pt.useRef(void 0);return s=>{const n=e(s);return Rw(t.current,n)?t.current:t.current=n}}function Iw(){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:f,setSessionProcessing:g}=N(Aw(w=>({chats:w.chats,currentSessionId:w.currentSessionId,currentChat:$v(w),addMessage:w.addMessage,selectSession:w.selectSession,deleteSession:w.deleteSession,deleteSessions:w.deleteSessions,deleteMessage:w.deleteMessage,updateSession:w.updateSession,pinSession:w.pinSession,unpinSession:w.unpinSession,loadChats:w.loadChats,processingChats:w.processingChats,setSessionProcessing:w.setSessionProcessing}))),y=t?f.has(t):!1,p=m.useMemo(()=>(s==null?void 0:s.messages)||[],[s]),x=m.useMemo(()=>e.filter(w=>w.pinned),[e]),b=m.useMemo(()=>e.filter(w=>!w.pinned),[e]),S=e.length;return{chats:e,currentSessionId:t,currentChat:s,isProcessing:y,baseMessages:p,pinnedChats:x,unpinnedChats:b,chatCount:S,addMessage:n,deleteMessage:l,selectSession:o,deleteSession:a,deleteSessions:i,pinSession:d,unpinSession:u,updateSession:c,loadChats:h,setSessionProcessing:g}}function $w(e){const t=N(f=>f.addChat),s=N(f=>f.lastSelectedPromptId),n=N(f=>f.systemPrompts),o=Ss.getInstance(),a=m.useCallback(async(f,g)=>{var b,S;const y=n.find(w=>w.id===s),p=(y==null?void 0:y.id)||(n.length>0?((b=n.find(w=>w.id==="general_assistant"))==null?void 0:b.id)||n[0].id:""),x={title:f||"New Session",createdAt:Date.now(),messages:[],config:{systemPromptId:p,baseSystemPrompt:(y==null?void 0:y.content)||(n.length>0?((S=n.find(w=>w.id==="general_assistant"))==null?void 0:S.content)||n[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null,...g};await t(x)},[t,s,n]),i=m.useCallback(async f=>{Ke("[ChatOps]","[useChatOperations] createChatWithSystemPrompt started with prompt:",f);const g={title:`New Session - ${f.name}`,createdAt:Date.now(),messages:[],config:{systemPromptId:f.id,baseSystemPrompt:f.content,lastUsedEnhancedPrompt:null},currentInteraction:null};Ke("[ChatOps]","[useChatOperations] Calling addChat with newChatData.config:",g.config),await t(g)},[t]),l=m.useCallback(f=>{const g=e.chats.find(y=>y.id===f);g&&(g.pinned?e.unpinSession(f):e.pinSession(f))},[e]),c=m.useCallback((f,g)=>{e.updateSession(f,{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 Wo=new Map,Ka=new Set,Zn=new Map,Vo=new Map;let vc=null;const Qg=(e,t)=>{const s=Wo.get(e);s&&s.forEach(n=>n(t))},Dw=()=>{if(vc=null,Vo.size===0)return;const e=Array.from(Vo.values());Vo.clear(),e.forEach(t=>{Qg(t.messageId,t.content),Ka.forEach(s=>s(t))})},ze={getLatest(e){return Zn.get(e)??null},subscribeMessage(e,t){let s=Wo.get(e);return s||(s=new Set,Wo.set(e,s)),s.add(t),Zn.has(e)&&t(Zn.get(e)??null),()=>{const n=Wo.get(e);n&&(n.delete(t),n.size===0&&Wo.delete(e))}},subscribe(e){return Ka.add(e),()=>{Ka.delete(e)}},publish(e){e.content===null?Zn.delete(e.messageId):Zn.set(e.messageId,e.content),Vo.set(e.messageId,e),vc===null&&(vc=requestAnimationFrame(Dw))},clear(e,t){Zn.delete(t),Vo.delete(t),Qg(t,null),Ka.forEach(s=>s({sessionId:e,messageId:t,content:null}))}},Zg="mermaid_enhancement_enabled",Sc=()=>localStorage.getItem(Zg)!=="false",Fw=e=>{localStorage.setItem(Zg,e.toString())},Lw=()=>`
|
|
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.`,wc="task_enhancement_enabled",em="todo_enhancement_enabled",Ow=e=>e==="false",_c=()=>{let e=localStorage.getItem(wc);if(e===null){const t=localStorage.getItem(em);t!==null&&(e=t,localStorage.setItem(wc,t),localStorage.removeItem(em))}return!Ow(e)},zw=e=>{localStorage.setItem(wc,e.toString())},Nw=()=>`
|
|
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
|
+
`,ey=()=>{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"},Bw=e=>{switch(e){case"windows":return"Windows";case"macos":return"macOS";case"linux":return"Linux";default:return"Unknown OS"}},Ww=()=>{const e=ey(),s=`## 🖥️ Operating System Information
|
|
75
|
+
|
|
76
|
+
You are running on **${Bw(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",gi=()=>localStorage.getItem(ty)==="true",Uw=e=>{try{localStorage.setItem(ty,e.toString())}catch(t){console.error("[copilotConclusionWithOptionsEnhancement] Failed to persist setting:",t)}},qw=()=>"\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",Hw=()=>["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(" "),sy="bamboo_system_prompt_enhancement",Yw=()=>["## 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
|
+
`),Xw=e=>e.map(s=>s.trim()).filter(s=>s.length>0).join(`
|
|
109
|
+
|
|
110
|
+
`),ny=()=>{try{return localStorage.getItem(sy)??""}catch(e){return console.error("Failed to load system prompt enhancement:",e),""}},Vw=e=>{try{const t=e.trim()?e:"";localStorage.setItem(sy,t)}catch(t){console.error("Failed to save system prompt enhancement:",t)}},Kw=e=>{const t=[];t.push(Ww().trim()),t.push(Yw().trim());const s=ny().trim();return s&&t.push(s),Sc()&&t.push(Lw().trim()),_c()&&t.push(Nw().trim()),(e??"").trim().toLowerCase()==="copilot"&&gi()&&t.push(qw().trim()),t},Gw=e=>Xw(Kw(e)),Tc=e=>{const t=(e??"").trim().toLowerCase();return t.includes("completion policy violation")&&t.includes("conclusion_with_options")},kc=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 ry(e){const{modal:t,message:s}=us.useApp(),{t:n}=se(),o=m.useRef(null),a=m.useRef(null),i=m.useRef(""),l=m.useRef(new Ss),c=N(v=>v.agentAvailability),d=N(v=>v.setAgentAvailability),u=N(v=>v.checkAgentAvailability),h=N(v=>v.startAgentHealthCheck),f=zi(e.sessionId),g=Yt(v=>v.currentProvider),y=N(v=>e.sessionId&&v.chats.find(M=>M.id===e.sessionId)||null);m.useEffect(()=>{h()},[h]);const p=m.useCallback(()=>{var M;(M=o.current)==null||M.abort();const v=y==null?void 0:y.id;v&&l.current.stopGeneration(v).catch(E=>{console.error("[useMessageStreaming] Failed to stop generation:",E)})},[y==null?void 0:y.id]),x=m.useCallback(v=>{var O;const M=N.getState(),_=(Array.isArray(M.chats)?M.chats:[]).find(A=>A.id===v),R=M.pendingQuestionRespond,T=(R==null?void 0:R.sessionId)===v?R:null,D=(O=_==null?void 0:_.config)==null?void 0:O.syncCursor,$=!!T||!!(D!=null&&D.hasPendingQuestion),I=(T==null?void 0:T.toolCallId)??(D==null?void 0:D.pendingQuestionToolCallId)??null;return{client_message_count:(D==null?void 0:D.messageCount)??(_==null?void 0:_.messageCount)??0,client_last_message_id:(D==null?void 0:D.lastMessageId)??null,client_has_pending_question:$,client_pending_question_tool_call_id:I}},[]),b=m.useCallback((v,M)=>{const E=M.sync;if(!E)return;const _=N.getState(),T=(Array.isArray(_.chats)?_.chats:[]).find(D=>D.id===v);T&&e.updateSession(v,{messageCount:E.server_message_count,config:{...T.config||{},syncCursor:{messageCount:E.server_message_count,lastMessageId:E.server_last_message_id??null,hasPendingQuestion:E.has_pending_question,pendingQuestionToolCallId:E.pending_question_tool_call_id??null}}})},[e]),S=m.useCallback(async v=>{try{return await ye.get(`respond/${v}/pending`)}catch(M){return console.warn(`[useMessageStreaming] Failed to fetch pending question for ${v}:`,M),{has_pending_question:!1}}},[]),w=m.useCallback(async(v,M,E)=>{var I,O;e.setSessionProcessing(v,!1),await N.getState().loadChatHistory(v,{mode:"replace"});const _=await S(v),R=N.getState().setPendingQuestionRespond,T=N.getState().clearPendingQuestionRespondForSession;if(_.has_pending_question){R({sessionId:v,question:_.question||"",options:_.options||[],allowCustom:_.allow_custom??!0,toolCallId:_.tool_call_id??null});const A=N.getState().chats.find(z=>z.id===v);return A&&e.updateSession(v,{config:{...A.config||{},syncCursor:{messageCount:A.messageCount??A.messages.length,lastMessageId:((O=(I=A.config)==null?void 0:I.syncCursor)==null?void 0:O.lastMessageId)??null,hasPendingQuestion:!0,pendingQuestionToolCallId:_.tool_call_id??null}}}),null}if(T(v),!((M==null?void 0:M.has_pending_user_message)??!1))return null;e.setSessionProcessing(v,!0),await new Promise(A=>setTimeout(A,0));const $=E?await l.current.execute(v,void 0,E,x(v)):await l.current.execute(v,void 0,void 0,x(v));return b(v,$),$},[b,x,e,S]),k=m.useCallback(async(v,M,E)=>{var D,$;let _=M;b(v,_);const R=2;let T=0;for(;(D=_.sync)!=null&&D.need_sync&&T<R;){const I=await w(v,_.sync,E);if(T+=1,!I){e.setSessionProcessing(v,!1);return}_=I,b(v,_)}if(($=_.sync)!=null&&$.need_sync){console.warn(`[useMessageStreaming] Execute remains out-of-sync after ${R} recovery attempt(s) for session ${v}.`,_.sync),e.setSessionProcessing(v,!1);return}if(!["started","already_running"].includes(_.status)){if(_.status==="completed"){Ke("[Streaming]","[Agent] Session already completed"),e.setSessionProcessing(v,!1);return}throw console.error("[Agent] Execute failed:",_.status),e.setSessionProcessing(v,!1),new Error(`Execute failed: ${_.status}`)}},[b,e,w]),j=m.useCallback(async(v,M,E,_,R)=>{var D,$;if(!f)throw new Error(n("chat.model.noModelSelected"));const T=new AbortController;o.current=T;try{const I=Gw(g).trim(),O=(g??"").trim().toLowerCase()==="copilot"&&gi(),z=(((D=y==null?void 0:y.config)==null?void 0:D.workspacePath)||"").trim().replace(/\/+$/,"").replace(/\\+$/,""),L=await l.current.sendMessage({message:v,session_id:M,enhance_prompt:I||void 0,copilot_conclusion_with_options_enhancement_enabled:O,workspace_path:z||void 0,selected_skill_ids:R&&R.length>0?R:void 0,images:($=E.images)==null?void 0:$.filter(q=>!!q.base64).map(q=>({base64:q.base64,name:q.name,size:q.size,type:q.type})),model:f}),{session_id:Y}=L;Y!==M&&console.warn(`[useMessageStreaming] Backend returned unexpected session_id=${Y} for sessionId=${M}`),await N.getState().loadChatHistory(M,{mode:"replace"}),e.setSessionProcessing(M,!0),await new Promise(q=>setTimeout(q,0));const F=_?await l.current.execute(M,void 0,_,x(M)):await l.current.execute(M,void 0,void 0,x(M));Ke("[Streaming]","[Agent] Execute status:",F.status),await k(M,F,_)}catch(I){throw I}},[f,x,y,g,e,k,n]),C=m.useCallback(async(v,M,E,_)=>{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(!f){t.error({title:n("chat.model.noModelSelected"),content:n("chat.model.selectModelBeforeSend")});return}let R=c;if(R===null&&(R=await u()),!R){s.error(n("chat.streaming.agentUnavailable"));return}if(!f){s.error(n("chat.streaming.modelConfigNotLoaded"));return}const T=e.sessionId,D=(M==null?void 0:M.map(I=>({id:I.id,base64:I.base64,name:I.name,size:I.size,type:I.type})))||[],$={role:"user",content:v,id:crypto.randomUUID(),createdAt:new Date().toISOString(),images:D};await e.addMessage(T,$);try{Ke("[Streaming]","[useChatStreaming] Using Agent Server"),await j(v,T,$,E,_)}catch(I){if(a.current&&ze.clear(T,a.current),a.current=null,i.current="",I instanceof Error&&I.name==="AbortError")s.info(n("chat.streaming.requestCancelled"));else{console.error("[useChatStreaming] Failed to send message:",I);const O=I instanceof Error?I.message:String(I??"");Tc(O)?s.error(kc(O)):(s.error(n("chat.streaming.sendFailed")),d(!1))}e.setSessionProcessing(T,!1)}finally{o.current=null,a.current&&ze.clear(T,a.current),a.current=null,i.current=""}},[c,s,u,y,e,t,j,d,f,n]),P=m.useCallback(async(v,M="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(!f){t.error({title:n("chat.model.noModelSelected"),content:n("chat.model.selectModelBeforeRetry")});return}let E=c;if(E===null&&(E=await u()),!E){s.error(n("chat.streaming.agentUnavailable"));return}const _=e.sessionId;a.current&&ze.clear(_,a.current),a.current=null,i.current="";try{const R=M==="error_retry"?"error_retry":"after_last_user",T=await l.current.truncateSessionMessages(_,{mode:R});(M==="regenerate"||(T.messages_removed??0)>0)&&await N.getState().loadChatHistory(_,{mode:"replace"}),e.setSessionProcessing(_,!0);const D=v?await l.current.execute(_,void 0,v,x(_)):await l.current.execute(_,void 0,void 0,x(_));await k(_,D,v)}catch(R){console.error("[useMessageStreaming] Retry failed:",R);const T=R instanceof Error?R.message:String(R??"");Tc(T)?s.error(kc(T)):s.error(n("chat.streaming.retryFailed")),e.setSessionProcessing(_,!1)}finally{o.current=null}},[f,c,s,x,u,y,e,k,t,n]);return{sendMessage:C,retryLastTurn:P,cancel:p,agentAvailable:c}}function Jw(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 Qw=()=>{const e=Iw(),t=Ad(e),s=$w(e),n=ry({sessionId:e.currentSessionId,addMessage:e.addMessage,setSessionProcessing:e.setSessionProcessing,updateSession:e.updateSession}),o=Jw(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}},oy="lotus_vdi_safe_mode",yi=()=>{try{return localStorage.getItem(oy)==="true"}catch{return!1}},Zw=e=>{try{localStorage.setItem(oy,e.toString())}catch(t){console.error("[vdiSafeMode] Failed to persist setting:",t)}},{Text:Pa}=ce,{useToken:e_}=pe,t_=({httpProxy:e,httpsProxy:t,onHttpProxyChange:s,onHttpsProxyChange:n,onReload:o,onSave:a,isLoading:i})=>{const{t:l}=se(),{token:c}=e_(),d=bs(k=>k.proxyAuthStatus),u=bs(k=>k.isLoadingProxyAuthStatus),h=bs(k=>k.loadProxyAuthStatus),f=bs(k=>k.applyProxyAuth),g=bs(k=>k.clearProxyAuth),[y,p]=m.useState({username:"",password:""}),[x,b]=m.useState(!1);m.useEffect(()=>{h()},[]);const S=async()=>{const k=y.username.trim();if(k){b(!0);try{await f({username:k,password:y.password}),p({username:"",password:""})}catch(j){console.error("Failed to apply proxy auth:",j)}finally{b(!1)}}},w=async()=>{b(!0);try{await g()}catch(k){console.error("Failed to clear proxy auth:",k)}finally{b(!1)}};return r.jsx(ee,{size:"small",title:r.jsx(Pa,{strong:!0,children:l("settings.networkCard.title")}),className:"lotus-settings-card",children:r.jsxs(H,{direction:"vertical",size:c.marginSM,style:{width:"100%"},children:[r.jsxs(H,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[r.jsx(Pa,{type:"secondary",children:l("settings.networkCard.httpProxy")}),r.jsx(he,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:k=>s(k.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),r.jsxs(H,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[r.jsx(Pa,{type:"secondary",children:l("settings.networkCard.httpsProxy")}),r.jsx(he,{style:{width:"100%"},value:t,onChange:k=>n(k.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(H,{direction:"vertical",style:{width:"100%"},children:[r.jsx(Ne,{type:"success",message:l("settings.networkCard.proxyConfiguredForUser",{username:d.username??""}),showIcon:!0}),r.jsx(U,{onClick:w,loading:x||u,danger:!0,children:l("settings.networkCard.clearCredentials")})]}):r.jsxs(H,{direction:"vertical",size:c.marginXS,style:{width:"100%"},children:[r.jsx(he,{placeholder:l("settings.networkCard.username"),value:y.username,onChange:k=>p(j=>({...j,username:k.target.value}))}),r.jsx(he.Password,{placeholder:l("settings.networkCard.password"),value:y.password,onChange:k=>p(j=>({...j,password:k.target.value}))}),r.jsx(U,{type:"primary",onClick:S,loading:x||u,disabled:!y.username.trim(),children:l("settings.networkCard.apply")})]})}),r.jsx(Pa,{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(U,{onClick:()=>Promise.resolve(o()).finally(()=>h({force:!0})),disabled:i,children:l("settings.networkCard.reload")}),r.jsx(U,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(a()).finally(()=>h({force:!0})),disabled:i,children:l("settings.networkCard.save")})]})]})})},{Text:Vt}=ce,{useToken:s_}=pe,n_=5*60*1e3,r_=()=>{const{t:e}=se(),{token:t}=s_(),[s,n]=m.useState({}),[o,a]=m.useState([]),[i,l]=m.useState(!1),[c,d]=m.useState(""),[u,h]=m.useState(null),[f,g]=fe.useMessage(),[y,p]=m.useState({}),[x,b]=m.useState(!1),[S,w]=m.useState(""),[k,j]=m.useState("");m.useEffect(()=>{(async()=>{try{const $=await $t.getProviderConfig();d($.provider||"copilot")}catch($){console.error("Failed to load provider config:",$),h(e("settings.modelMappingCard.loadProviderFailed"))}})()},[e]),m.useEffect(()=>{const $=setInterval(async()=>{try{const O=(await $t.getProviderConfig()).provider||"copilot";O!==c&&c!==""&&(Ke("[ModelMapping]",`Provider changed from ${c} to ${O}`),d(O),h(null))}catch(I){console.error("Failed to check provider change:",I)}},1e4);return()=>clearInterval($)},[c]),m.useEffect(()=>{(async()=>{try{const $=await Je.getAnthropicModelMapping();n($.mappings||{})}catch($){console.error("Failed to load model mappings:",$),f.error(e("settings.modelMappingCard.loadMappingsFailed"))}})()},[f,e]);const C=m.useCallback(async(D=!1)=>{if(c){if(!D&&y[c]){const $=y[c];if(Date.now()-$.timestamp<n_){Ke("[ModelMapping]",`Using cached models for ${c}`),a($.models),h(null);return}}l(!0),h(null);try{let $;if(c==="copilot"){const{modelService:I}=await Ft(async()=>{const{modelService:O}=await Promise.resolve().then(()=>iv);return{modelService:O}},void 0,import.meta.url);$=await I.getModels()}else $=await $t.fetchProviderModels(c);a($),p(I=>({...I,[c]:{models:$,timestamp:Date.now()}})),Ke("[ModelMapping]",`Fetched ${$.length} models for ${c}`)}catch($){console.error("Failed to fetch models:",$);const I=$ instanceof Error?$.message:e("settings.modelMappingCard.loadModelsFailed");h(I),f.error(e("settings.modelMappingCard.loadModelsHint")),a([])}finally{l(!1)}}},[c,y,f,e]);m.useEffect(()=>{c&&C()},[c,C]);const P=async(D,$)=>{if($==="__custom__"){w(D),j(""),b(!0);return}if(!$)return;const I={...s,[D]:$};n(I);try{await Je.setAnthropicModelMapping({mappings:I}),f.success(e("settings.modelMappingCard.mappingSaved"))}catch(O){console.error("Failed to save model mapping:",O),f.error(e("settings.modelMappingCard.mappingSaveFailed"))}},v=async()=>{if(!k.trim()){f.warning(e("settings.modelMappingCard.enterModelName"));return}const D={...s,[S]:k.trim()};n(D);try{await Je.setAnthropicModelMapping({mappings:D}),f.success(e("settings.modelMappingCard.customMappingSaved")),b(!1),j("")}catch($){console.error("Failed to save custom model mapping:",$),f.error(e("settings.modelMappingCard.customMappingSaveFailed"))}},M=()=>{C(!0)},E=D=>{const $=s[D];return $?o.includes($):!0},_=[{key:"opus",label:e("settings.modelMappingCard.modelTypeOpus"),description:e("settings.modelMappingCard.modelTypeOpusDescription")},{key:"sonnet",label:e("settings.modelMappingCard.modelTypeSonnet"),description:e("settings.modelMappingCard.modelTypeSonnetDescription")},{key:"haiku",label:e("settings.modelMappingCard.modelTypeHaiku"),description:e("settings.modelMappingCard.modelTypeHaikuDescription")}],R=c.charAt(0).toUpperCase()+c.slice(1),T=[{key:"1",label:e("settings.modelMappingCard.collapseTitle"),children:r.jsxs(H,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(Vt,{type:"secondary",children:e("settings.modelMappingCard.description",{provider:R})}),u&&r.jsx(Ne,{type:"error",message:e("settings.modelMappingCard.loadModelsErrorTitle"),description:u,showIcon:!0,action:r.jsx(U,{size:"small",icon:r.jsx(Fs,{}),onClick:M,loading:i,children:e("settings.modelMappingCard.retry")})}),i&&!u&&r.jsx("div",{style:{textAlign:"center",padding:t.paddingMD},children:r.jsx(ht,{tip:e("settings.modelMappingCard.loadingModels")})}),!i&&!u&&_.map(({key:D,label:$,description:I})=>{const O=E(D),A=s[D];return r.jsxs(H,{direction:"vertical",size:t.marginXXS,style:{width:"100%"},children:[r.jsxs(Vt,{type:"secondary",children:[$," (",I,")"]}),r.jsx(Fe,{style:{width:"100%"},value:A||void 0,onChange:z=>P(D,z),placeholder:e("settings.modelMappingCard.selectModelPlaceholder",{label:$}),loading:i,disabled:i||o.length===0,showSearch:!0,allowClear:!0,optionFilterProp:"children",options:[...o.map(z=>({label:z,value:z})),{label:r.jsxs("span",{children:[r.jsx(Sr,{style:{marginRight:6}}),e("settings.modelMappingCard.customModelOption")]}),value:"__custom__"}],status:O?void 0:"warning",filterOption:(z,L)=>((L==null?void 0:L.label)??"").toString().toLowerCase().includes(z.toLowerCase())}),!O&&A&&r.jsx(Vt,{type:"warning",style:{fontSize:t.fontSizeSM},children:e("settings.modelMappingCard.mappedModelNotFound",{model:A})})]},D)}),r.jsx(Dt,{style:{margin:`${t.marginSM} 0`}}),r.jsx(H,{style:{width:"100%",justifyContent:"flex-end"},children:r.jsx(U,{size:"small",icon:r.jsx(Fs,{}),onClick:M,loading:i,disabled:!c,children:e("settings.modelMappingCard.refreshModels")})}),r.jsxs(H,{direction:"vertical",size:t.marginXXS,style:{width:"100%"},children:[r.jsxs(Vt,{type:"secondary",style:{fontSize:t.fontSizeSM},children:[e("settings.modelMappingCard.currentProvider"),":"," ",r.jsx(Vt,{strong:!0,children:c||e("settings.modelMappingCard.loadingProvider")})]}),r.jsxs(Vt,{type:"secondary",style:{fontSize:t.fontSizeSM},children:[e("settings.modelMappingCard.availableModels"),":"," ",r.jsx(Vt,{strong:!0,children:o.length}),y[c]&&r.jsx(Vt,{type:"secondary",style:{marginLeft:t.marginXXS},children:e("settings.modelMappingCard.cached")})]}),r.jsxs(Vt,{type:"secondary",style:{fontSize:t.fontSizeSM},children:[e("settings.modelMappingCard.storedIn"),":"," ",r.jsx(Vt,{code:!0,children:"~/.bamboo/anthropic-model-mapping.json"})]})]})]})}];return r.jsxs(r.Fragment,{children:[g,r.jsx(ws,{size:"small",items:T,className:"lotus-settings-card",style:{marginBottom:t.marginSM}}),r.jsx(Lt,{title:e("settings.modelMappingCard.customModalTitle"),open:x,onOk:v,onCancel:()=>{b(!1),j("")},okText:e("settings.modelMappingCard.save"),cancelText:e("settings.modelMappingCard.cancel"),children:r.jsxs(H,{direction:"vertical",style:{width:"100%"},children:[r.jsx(Vt,{type:"secondary",children:e("settings.modelMappingCard.customModalDescription",{modelType:S})}),r.jsx(he,{placeholder:e("settings.modelMappingCard.customModalPlaceholder"),value:k,onChange:D=>j(D.target.value),onPressEnter:v,autoFocus:!0}),r.jsx(Vt,{type:"secondary",style:{fontSize:t.fontSizeSM},children:e("settings.modelMappingCard.customModalNote")})]})})]})},{Text:Kt}=ce,{useToken:o_}=pe,tm="http://127.0.0.1:9562/v1",Uo=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)?Uo(t.filter(n=>typeof n=="string")):[]},i_=({msgApi:e,locale:t,onLocaleChange:s})=>{const{t:n}=se(),{token:o}=o_(),[a,i]=m.useState({http_proxy:"",https_proxy:"",memory:{auto_dream_enabled:!1,background_model:""}}),[l,c]=m.useState(tm),[d,u]=m.useState([]),[h,f]=m.useState([]),[g,y]=m.useState([]),[p,x]=m.useState(!1),[b,S]=m.useState(!1),w=m.useCallback(async()=>{var I,O;x(!0);try{const[A,z]=await Promise.all([Je.getBambooConfig(),Je.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:((O=A.memory)==null?void 0:O.background_model)||""}});const L=a_(A);f(L),y(L),u(Uo(z.tools||[]))}catch(A){console.error("Failed to load config:",A),e.error(n("settings.configTab.loadConfigFailed"))}finally{x(!1)}},[e,n]);m.useEffect(()=>{w()},[w]);const k=I=>{i(O=>({...O,http_proxy:I}))},j=I=>{i(O=>({...O,https_proxy:I}))},C=I=>{i(O=>({...O,memory:{...O.memory,auto_dream_enabled:I}}))},P=I=>{i(O=>({...O,memory:{...O.memory,background_model:I}}))},v=async()=>{var I,O;x(!0);try{const A=await Je.validateBambooConfigPatch(a);if(!A.valid){const L=((O=(I=A.errors)==null?void 0:I.proxy)==null?void 0:O[0])??Object.values(A.errors||{}).flat().filter(Boolean)[0];e.error((L==null?void 0:L.message)||n("settings.configTab.invalidConfig"));return}await Je.setBambooConfig(a),e.success(n("settings.configTab.saveConfigSuccess"))}catch(A){console.error("Failed to save config:",A);const z=A instanceof Error&&A.message.trim()?A.message:n("settings.configTab.saveConfigFailed");e.error(z)}finally{x(!1)}},M=async()=>{e.success(n("settings.configTab.backendSaved"))},E=()=>{c(tm),e.success(n("settings.configTab.backendResetDefault"))},_=(I,O)=>{f(A=>{const z=new Set(A);return O?z.delete(I):z.add(I),Uo([...z])})},R=async()=>{S(!0);try{const I=await Je.getBambooTools();u(Uo(I.tools||[])),e.success(n("settings.configTab.toolsReloadSuccess"))}catch(I){console.error("Failed to reload tools:",I),e.error(n("settings.configTab.toolsLoadFailed"))}finally{S(!1)}},T=async()=>{S(!0);try{const I=Uo(h);await Je.setBambooConfig({tools:{disabled:I}}),f(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{S(!1)}},D=JSON.stringify(h)!==JSON.stringify(g),$=new Set(h);return r.jsx(ht,{spinning:p,tip:n("settings.common.loading"),children:r.jsx(ei,{items:[{key:"general",label:n("settings.configTab.tabs.general"),children:r.jsxs(H,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(Ne,{message:n("settings.configTab.providerMovedTitle"),description:n("settings.configTab.providerMovedDescription"),type:"info",showIcon:!0,closable:!0}),r.jsx(t_,{httpProxy:a.http_proxy,httpsProxy:a.https_proxy,onHttpProxyChange:k,onHttpsProxyChange:j,onReload:w,onSave:v,isLoading:p}),r.jsx(r_,{}),r.jsx(ee,{size:"small",className:"lotus-settings-card",title:r.jsx(Kt,{strong:!0,children:n("settings.configTab.language")}),children:r.jsx(Fe,{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(Kt,{strong:!0,children:n("settings.configTab.memoryTitle")}),children:r.jsxs(H,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(Kt,{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(Kt,{strong:!0,children:n("settings.configTab.autoDreamEnabled")}),r.jsx("div",{children:r.jsx(Kt,{type:"secondary",style:{fontSize:o.fontSizeSM},children:n("settings.configTab.autoDreamEnabledHint")})})]}),r.jsx(ct,{"data-testid":"auto-dream-toggle",checked:a.memory.auto_dream_enabled,onChange:C})]}),r.jsxs(H,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:[r.jsx(Kt,{strong:!0,children:n("settings.configTab.backgroundModel")}),r.jsx(he,{"data-testid":"auto-dream-background-model-input",value:a.memory.background_model,onChange:I=>P(I.target.value),placeholder:n("settings.configTab.backgroundModelPlaceholder")}),r.jsx(Kt,{type:"secondary",style:{fontSize:o.fontSizeSM},children:n("settings.configTab.backgroundModelHint")})]}),r.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:r.jsx(U,{"data-testid":"save-memory-settings",type:"primary",onClick:v,loading:p,children:n("settings.configTab.save")})})]})}),r.jsx(ee,{size:"small",title:r.jsx(Kt,{strong:!0,children:n("settings.configTab.backendApiBaseUrlTitle")}),children:r.jsxs(H,{direction:"vertical",size:o.marginSM,style:{width:"100%"},children:[r.jsx(H,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:r.jsx(he,{style:{width:"100%"},value:l,onChange:I=>c(I.target.value),placeholder:n("settings.configTab.backendApiPlaceholder")})}),r.jsx(Kt,{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(U,{"data-testid":"reset-to-defaults",onClick:E,children:n("settings.configTab.resetToDefault")}),r.jsx(U,{"data-testid":"save-api-settings",type:"primary",onClick:M,children:n("settings.configTab.save")})]})]})})]})},{key:"tools",label:n("settings.configTab.tabs.tools"),children:r.jsx(ee,{size:"small",title:r.jsx(Kt,{strong:!0,children:n("settings.configTab.toolsTitle")}),children:r.jsxs(H,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(Kt,{type:"secondary",children:n("settings.configTab.toolsDescription")}),d.length===0?r.jsx(Ne,{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(ct,{checked:!$.has(I),onChange:O=>_(I,O)},`${I}-switch`)],children:r.jsx(Kt,{code:!0,children:I})})}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:o.marginSM},children:[r.jsx(U,{onClick:R,loading:b,children:n("settings.configTab.reloadTools")}),r.jsx(U,{type:"primary",onClick:T,loading:b,disabled:!D,children:n("settings.configTab.save")})]})]})})}]})})},sm={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},$d=xn()(Hb(e=>({settings:sm,updateSettings:t=>e(s=>({settings:{...s.settings,...t}})),resetSettings:()=>e({settings:sm})}),{name:"mermaid-settings"})),Bi=()=>$d(t=>t.settings),l_=()=>$d(e=>e.updateSettings),c_=()=>$d(e=>e.resetSettings),{Title:d_,Text:pl}=ce,{useToken:u_}=pe,m_=()=>{const{t:e}=se(),{token:t}=u_(),s=Bi(),n=l_(),o=c_(),[a]=Z.useForm();pt.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(d_,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),r.jsx(pl,{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(ss,{gutter:16,children:r.jsx(Le,{span:24,children:r.jsx(Z.Item,{name:"theme",label:r.jsxs(H,{children:[e("settings.mermaidTab.themeLabel"),r.jsx(ke,{title:e("settings.mermaidTab.themeTooltip"),children:r.jsx(Ot,{style:{color:t.colorTextSecondary}})})]}),children:r.jsxs(Fe,{children:[r.jsx(Fe.Option,{value:"default",children:e("settings.mermaidTab.themeOptions.default")}),r.jsx(Fe.Option,{value:"neutral",children:e("settings.mermaidTab.themeOptions.neutral")}),r.jsx(Fe.Option,{value:"dark",children:e("settings.mermaidTab.themeOptions.dark")}),r.jsx(Fe.Option,{value:"forest",children:e("settings.mermaidTab.themeOptions.forest")}),r.jsx(Fe.Option,{value:"base",children:e("settings.mermaidTab.themeOptions.base")})]})})})}),r.jsxs(pl,{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(ss,{gutter:16,children:[r.jsx(Le,{span:12,children:r.jsx(Z.Item,{name:"fontSize",label:r.jsxs(H,{children:[e("settings.mermaidTab.fontSizeLabel"),r.jsx(ke,{title:e("settings.mermaidTab.fontSizeTooltip"),children:r.jsx(Ot,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(ot,{min:10,max:32,step:1,style:{width:"100%"},addonAfter:"px"})})}),r.jsx(Le,{span:12,children:r.jsx(Z.Item,{name:"defaultScale",label:r.jsxs(H,{children:[e("settings.mermaidTab.defaultZoomLabel"),r.jsx(ke,{title:e("settings.mermaidTab.defaultZoomTooltip"),children:r.jsx(Ot,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(ot,{min:.1,max:3,step:.1,style:{width:"100%"}})})})]}),r.jsx(Z.Item,{name:"useMaxWidth",label:r.jsxs(H,{children:[e("settings.mermaidTab.responsiveWidthLabel"),r.jsx(ke,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:r.jsx(Ot,{style:{color:t.colorTextSecondary}})})]}),valuePropName:"checked",children:r.jsx(ct,{})})]}),r.jsx(ee,{title:e("settings.mermaidTab.flowchartCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(ss,{gutter:16,children:[r.jsx(Le,{span:8,children:r.jsx(Z.Item,{name:"flowchartNodeSpacing",label:r.jsxs(H,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),r.jsx(ke,{title:e("settings.mermaidTab.flowchartNodeSpacingTooltip"),children:r.jsx(Ot,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(ot,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Le,{span:8,children:r.jsx(Z.Item,{name:"flowchartRankSpacing",label:r.jsxs(H,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),r.jsx(ke,{title:e("settings.mermaidTab.flowchartRankSpacingTooltip"),children:r.jsx(Ot,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(ot,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Le,{span:8,children:r.jsx(Z.Item,{name:"flowchartCurve",label:r.jsxs(H,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),r.jsx(ke,{title:e("settings.mermaidTab.flowchartCurveTypeTooltip"),children:r.jsx(Ot,{style:{color:t.colorTextSecondary}})})]}),children:r.jsxs(Fe,{children:[r.jsx(Fe.Option,{value:"basis",children:e("settings.mermaidTab.flowchartCurveOptions.basis")}),r.jsx(Fe.Option,{value:"linear",children:e("settings.mermaidTab.flowchartCurveOptions.linear")}),r.jsx(Fe.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(ss,{gutter:16,children:[r.jsx(Le,{span:6,children:r.jsx(Z.Item,{name:"sequenceActorMargin",label:r.jsxs(H,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),r.jsx(ke,{title:e("settings.mermaidTab.sequenceActorMarginTooltip"),children:r.jsx(Ot,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(ot,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Le,{span:6,children:r.jsx(Z.Item,{name:"sequenceMessageMargin",label:r.jsxs(H,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),r.jsx(ke,{title:e("settings.mermaidTab.sequenceMessageMarginTooltip"),children:r.jsx(Ot,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(ot,{min:10,max:100,step:5,style:{width:"100%"}})})}),r.jsx(Le,{span:6,children:r.jsx(Z.Item,{name:"sequenceWidth",label:r.jsxs(H,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),r.jsx(ke,{title:e("settings.mermaidTab.sequenceActorWidthTooltip"),children:r.jsx(Ot,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(ot,{min:100,max:300,step:10,style:{width:"100%"}})})}),r.jsx(Le,{span:6,children:r.jsx(Z.Item,{name:"sequenceHeight",label:r.jsxs(H,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),r.jsx(ke,{title:e("settings.mermaidTab.sequenceActorHeightTooltip"),children:r.jsx(Ot,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(ot,{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(ss,{gutter:16,children:[r.jsx(Le,{span:12,children:r.jsx(Z.Item,{name:"ganttBarHeight",label:r.jsxs(H,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),r.jsx(ke,{title:e("settings.mermaidTab.ganttBarHeightTooltip"),children:r.jsx(Ot,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(ot,{min:10,max:50,step:5,style:{width:"100%"},addonAfter:"px"})})}),r.jsx(Le,{span:12,children:r.jsx(Z.Item,{name:"ganttTopPadding",label:r.jsxs(H,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),r.jsx(ke,{title:e("settings.mermaidTab.ganttTopPaddingTooltip"),children:r.jsx(Ot,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(ot,{min:20,max:100,step:10,style:{width:"100%"}})})})]})}),r.jsx(H,{children:r.jsx(U,{icon:r.jsx(Hx,{}),onClick:l,children:e("settings.mermaidTab.resetToDefaults")})}),r.jsx(Dt,{}),r.jsx(ee,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsx(pl,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},h_=m.lazy(()=>Ft(()=>import("./index-BKrbsGr5.js"),__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url)),{Text:Sn}=ce,{useToken:p_}=pe,f_=({promptEnhancement:e,onPromptEnhancementChange:t,mermaidEnhancementEnabled:s,taskEnhancementEnabled:n,showCopilotConclusionWithOptionsEnhancement:o,copilotConclusionWithOptionsEnhancementEnabled:a,onMermaidToggle:i,onTaskToggle:l,onCopilotConclusionWithOptionsToggle:c,onSaveEnhancement:d})=>{const{t:u}=se(),{token:h}=p_(),f=h.marginLG;return r.jsxs(J,{vertical:!0,gap:f,children:[r.jsx(ee,{size:"small",className:"lotus-settings-card",children:r.jsx(m.Suspense,{fallback:r.jsx(ht,{size:"small"}),children:r.jsx(h_,{})})}),r.jsx(ee,{size:"small",className:"lotus-settings-card",children:r.jsxs(H,{direction:"vertical",size:h.marginXS,style:{width:"100%"},children:[r.jsx(Sn,{strong:!0,children:u("settings.promptsTab.title")}),r.jsxs(J,{align:"center",gap:h.marginSM,children:[r.jsx(Sn,{strong:!0,children:u("settings.promptsTab.mermaidEnhancement")}),r.jsx(ct,{checked:s,onChange:i})]}),r.jsxs(J,{align:"center",gap:h.marginSM,children:[r.jsx(Sn,{strong:!0,children:u("settings.promptsTab.taskListRules")}),r.jsx(ct,{checked:n,onChange:l})]}),o&&r.jsxs(H,{direction:"vertical",size:h.marginXXS,style:{width:"100%"},children:[r.jsxs(J,{align:"center",gap:h.marginSM,children:[r.jsx(Sn,{strong:!0,children:u("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),r.jsx(ct,{checked:a,onChange:c})]}),r.jsx(Sn,{type:"secondary",style:{fontSize:h.fontSizeSM},children:u("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:Hw()})})]}),r.jsx(he.TextArea,{rows:6,placeholder:u("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:g=>t(g.target.value)}),r.jsx(J,{justify:"flex-end",children:r.jsx(U,{type:"primary",onClick:d,children:u("settings.promptsTab.saveEnhancement")})}),r.jsx(Sn,{type:"secondary",style:{fontSize:h.fontSizeSM},children:u("settings.promptsTab.description")})]})}),s&&r.jsx(ws,{size:"small",items:[{key:"mermaid",label:r.jsx(Sn,{strong:!0,children:u("settings.mermaidTab.title")}),children:r.jsx(m_,{})}]})]})},{Text:Ms}=ce,{useToken:g_}=pe,y_=({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}=se(),{token:f}=g_();return r.jsx(ee,{size:"small",className:"lotus-settings-card",children:r.jsxs(H,{direction:"vertical",size:f.marginSM,style:{width:"100%"},children:[r.jsxs(J,{align:"center",gap:f.marginSM,children:[r.jsx(Ms,{strong:!0,children:h("settings.appTab.autoGenerateTitle")}),r.jsx(ct,{checked:e,loading:t,onChange:s})]}),r.jsx(Ms,{type:"secondary",style:{fontSize:f.fontSizeSM},children:h("settings.appTab.autoGenerateTitleDesc")}),r.jsxs(J,{align:"center",justify:"space-between",gap:f.marginSM,children:[r.jsx(Ms,{strong:!0,children:h("settings.appTab.runningVersion","Running version")}),r.jsxs(Ms,{code:!0,"data-testid":"settings-app-version",children:["v",cd]})]}),r.jsx(Ms,{type:"secondary",style:{fontSize:f.fontSizeSM},children:h("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),r.jsxs(J,{align:"center",gap:f.marginSM,children:[r.jsx(Ms,{strong:!0,children:h("settings.appTab.darkMode")}),r.jsx(ct,{"data-testid":"dark-mode-toggle",checked:n==="dark",onChange:g=>{const y=g?"dark":"light";o(y),localStorage.setItem(u,y)}})]}),r.jsxs(J,{align:"center",gap:f.marginSM,children:[r.jsx(Ms,{strong:!0,children:h("settings.appTab.vdiSafeMode","Graphics compatibility mode")}),r.jsx(ct,{"data-testid":"vdi-safe-mode-toggle",checked:a,onChange:i})]}),r.jsx(Ms,{type:"secondary",style:{fontSize:f.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(ti,{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(U,{danger:!0,block:!0,icon:r.jsx(yn,{}),children:h("settings.appTab.clearLocalStorageButton")})}),r.jsx(Dt,{style:{margin:`${f.marginSM}px 0`}}),r.jsxs(J,{align:"center",gap:f.marginSM,children:[r.jsx(oa,{style:{color:f.colorError}}),r.jsx(Ms,{strong:!0,style:{color:f.colorError},children:h("settings.appTab.dangerZone")})]}),r.jsx(Ms,{type:"secondary",style:{fontSize:f.fontSizeSM},children:h("settings.appTab.dangerDescription")}),r.jsx(ti,{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(U,{"data-testid":"reset-to-defaults",danger:!0,block:!0,type:"primary",icon:r.jsx(Xp,{}),loading:d,children:h("settings.appTab.resetButton")})})]})})},{Text:wn}=ce,{useToken:x_}=pe,nm=[{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,}"}],b_=(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:as.t("settings.keywordMaskingTab.invalidRegexPattern")}}},v_=()=>{const{t:e}=se(),{token:t}=x_(),[s,n]=m.useState([]),[o,a]=m.useState(!1),[i,l]=m.useState(null),[c,d]=m.useState(""),[u,h]=m.useState("exact"),[f,g]=m.useState(!0),[y,p]=m.useState(),[x,b]=m.useState("My token is sk-123"),S=m.useCallback(async()=>{try{a(!0);const R=await Nt.getInstance().getKeywordMaskingConfig();n(R.entries)}catch(_){fe.error(e("settings.keywordMaskingTab.loadFailed")),console.error(_)}finally{a(!1)}},[e]);m.useEffect(()=>{S()},[S]);const w=async _=>{try{const R=Nt.getInstance(),T=await R.validateKeywordEntries(_);if(!T.valid&&T.errors){const $=T.errors.map(I=>`Entry ${I.index+1}: ${I.message}`).join("; ");return fe.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${$}`),!1}const D=await R.updateKeywordMaskingConfig(_);return n(D.entries),fe.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch(R){return fe.error(R instanceof Error?R.message:e("settings.keywordMaskingTab.saveFailed")),!1}},k=async()=>{const _={pattern:"",match_type:"exact",enabled:!0},R=[...s,_];n(R),l(R.length-1),d(""),h("exact"),g(!0),p(void 0)},j=_=>{const R=s[_];l(_),d(R.pattern),h(R.match_type),g(R.enabled),p(void 0)},C=async()=>{if(i===null)return;if(!c.trim()){fe.error(e("settings.keywordMaskingTab.patternRequired"));return}const _=[...s];_[i]={pattern:c.trim(),match_type:u,enabled:f},await w(_)&&l(null)},P=()=>{var _;i!==null&&!((_=s[i])!=null&&_.pattern)&&n(s.filter((R,T)=>T!==i)),l(null)},v=async _=>{const R=s.filter((T,D)=>D!==_);await w(R)},M=async(_,R)=>{const T=[...s];T[_]={...T[_],enabled:R},await w(T)},E=b_(x,c,u);return r.jsx(ee,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:r.jsx(U,{"data-testid":"add-keyword",type:"primary",icon:r.jsx(Gs,{}),onClick:k,loading:o,children:e("settings.keywordMaskingTab.addKeyword")}),children:r.jsxs(H,{direction:"vertical",style:{width:"100%"},size:"large",children:[r.jsx(wn,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),r.jsx(nt,{loading:o,dataSource:s,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(_,R)=>r.jsx(nt.Item,{style:{backgroundColor:t.colorFillAlter,marginBottom:8,borderRadius:t.borderRadius,padding:12},actions:i===R?[r.jsx(U,{"data-testid":"save-keyword",type:"primary",icon:r.jsx(Mi,{}),onClick:C,"aria-label":e("settings.keywordMaskingTab.save")},"save"),r.jsx(U,{onClick:P,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[r.jsx(U,{icon:r.jsx(Sr,{}),onClick:()=>j(R),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),r.jsx(U,{"data-testid":`delete-keyword-${R}`,danger:!0,icon:r.jsx(yn,{}),onClick:()=>v(R),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:r.jsx(J,{vertical:!0,style:{width:"100%"},gap:8,children:i===R?r.jsxs(r.Fragment,{children:[r.jsx(he,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:c,onChange:T=>d(T.target.value),autoFocus:!0}),r.jsxs(J,{gap:8,align:"center",wrap:"wrap",children:[r.jsx(Fe,{"data-testid":"keyword-examples-select","aria-label":e("settings.keywordMaskingTab.examples"),placeholder:e("settings.keywordMaskingTab.examples"),value:y,onChange:T=>{p(T);const D=nm.find($=>$.value===T);D&&(d(D.pattern),h(D.match_type))},options:nm.map(T=>({value:T.value,label:e(T.labelKey)})),style:{minWidth:220}}),r.jsx(Fe,{value:u,onChange:h,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),r.jsx(ct,{checked:f,onChange:g})]}),r.jsxs(J,{vertical:!0,gap:6,children:[r.jsx(wn,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),r.jsx(he,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:x,onChange:T=>b(T.target.value)}),r.jsx(wn,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),r.jsx(he,{readOnly:!0,value:E.masked,status:E.error?"error":void 0}),E.error&&r.jsx(wn,{type:"danger",children:E.error})]})]}):r.jsxs(J,{justify:"space-between",align:"center",children:[r.jsxs(J,{vertical:!0,gap:4,children:[r.jsx(wn,{strong:!0,children:_.pattern||e("settings.keywordMaskingTab.emptyPattern")}),r.jsxs(J,{gap:8,children:[r.jsx(wn,{type:"secondary",style:{fontSize:12},children:_.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!_.enabled&&r.jsx(wn,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),r.jsx(ct,{checked:_.enabled,onChange:T=>M(R,T),size:"small"})]})})})})]})})},{Text:er,Paragraph:S_}=ce,w_=/^[A-Za-z_][A-Za-z0-9_]*$/,__=()=>{const{t:e}=se(),[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 $t.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 w;const S={name:b.name.trim(),value:b.value,secret:b.secret??!1,description:((w=b.description)==null?void 0:w.trim())||void 0};try{const k=await $t.upsertEnvVar(S);s(k.entries),fe.success(l?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),p()}catch(k){fe.error((k instanceof Error?k.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},f=async b=>{try{const S=await $t.deleteEnvVar(b);s(S.entries),fe.success(e("settings.envVars.deleted","Variable deleted"))}catch(S){fe.error((S instanceof Error?S.message:void 0)||e("settings.envVars.deleteError","Failed to delete variable"))}},g=()=>{c(null),d.resetFields(),d.setFieldsValue({secret:!1}),i(!0)},y=b=>{c(b.name),d.setFieldsValue({name:b.name,value:"",secret:b.secret,description:b.description??""}),i(!0)},p=()=>{i(!1),c(null),d.resetFields()},x=[{title:e("settings.envVars.name","Name"),dataIndex:"name",key:"name",render:b=>r.jsx(er,{code:!0,children:b})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(b,S)=>S.secret?r.jsxs(er,{type:"secondary",children:[r.jsx(Kd,{style:{marginRight:4}}),S.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):r.jsx(er,{children:b||r.jsx(er,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(b,S)=>S.secret?r.jsx(oe,{color:"warning",icon:r.jsx(Kd,{}),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(er,{type:"secondary",children:b}):r.jsx(er,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(b,S)=>r.jsxs(H,{size:"small",children:[r.jsx(U,{type:"text",size:"small",icon:r.jsx(Sr,{}),onClick:()=>y(S),"aria-label":e("settings.envVars.edit","Edit")}),r.jsx(ti,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>f(S.name),okText:e("settings.envVars.yes","Yes"),cancelText:e("settings.envVars.no","No"),children:r.jsx(U,{type:"text",size:"small",danger:!0,icon:r.jsx(yn,{}),"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(U,{type:"primary",icon:r.jsx(Gs,{}),onClick:g,children:e("settings.envVars.addButton","Add Variable")}),children:[r.jsx(S_,{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(Js,{dataSource:t,columns:x,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:p,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:w_,message:e("settings.envVars.nameInvalid","Must start with a letter or underscore, followed by letters, digits, or underscores")}],children:r.jsx(he,{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(he.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(ct,{})}),r.jsx(Z.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:r.jsx(he,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},Fn=class Fn{constructor(){}static getInstance(){return Fn.instance||(Fn.instance=new Fn),Fn.instance}async listWorkflows(){try{Ke("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const t=await we.get("bamboo/workflows"),s=Array.isArray(t)?t:[];return Ke("[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{Ke("[WorkflowManager]","[WorkflowManagerService] Getting workflow: "+t);const s=await we.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 Ke("[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),Gb(s)&&s.status===404?new Error("Workflow '"+t+"' not found"):s instanceof Error&&s.message.includes("404")?new Error("Workflow '"+t+"' not found"):s}}};Ye(Fn,"instance");let jc=Fn;const{Text:fl}=ce,{TextArea:T_}=he,{useToken:k_}=pe,j_=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),C_=()=>{const{t:e}=se(),{token:t}=k_(),[s,n]=fe.useMessage(),[o,a]=m.useState([]),[i,l]=m.useState(!1),[c,d]=m.useState(!1),[u,h]=m.useState(!1),[f,g]=m.useState(null),[y,p]=m.useState(""),[x,b]=m.useState(""),[S,w]=m.useState(!1),k=m.useMemo(()=>jc.getInstance(),[]),j=m.useCallback(async()=>{l(!0);try{const E=await k.listWorkflows();return a(E),E}catch{return s.error(e("settings.workflowsTab.loadFailed")),[]}finally{l(!1)}},[s,e,k]);m.useEffect(()=>{j()},[j]);const C=m.useCallback(async E=>{g(E),p(E.name),w(!1),d(!0);try{const _=await k.getWorkflow(E.name);b(_.content??"")}catch{s.error(e("settings.workflowsTab.loadContentFailed")),b("")}finally{d(!1)}},[s,e,k]),P=()=>{g(null),p(""),b(""),w(!1)},v=m.useCallback(async()=>{if(!j_(y)){s.error(e("settings.workflowsTab.invalidName"));return}const E=o.some(_=>_.name===y);if(!f&&E){s.error(e("settings.workflowsTab.nameAlreadyExists"));return}h(!0);try{await Nt.getInstance().saveWorkflow(y,x),s.success(e("settings.workflowsTab.saved")),w(!1);const T=(await j()).find(D=>D.name===y);T&&g(T)}catch(_){s.error(_ instanceof Error?_.message:e("settings.workflowsTab.saveFailed"))}finally{h(!1)}},[x,y,j,s,f,e,o]),M=m.useCallback(async E=>{try{await Nt.getInstance().deleteWorkflow(E.name),s.success(e("settings.workflowsTab.deleted")),(f==null?void 0:f.name)===E.name&&P(),await j()}catch(_){s.error(_ instanceof Error?_.message:e("settings.workflowsTab.deleteFailed"))}},[j,s,f,e]);return r.jsxs("div",{style:{padding:"24px"},children:[n,r.jsxs(ee,{title:e("settings.workflowsTab.title"),extra:r.jsxs(H,{children:[r.jsx(U,{icon:r.jsx(Fs,{}),onClick:j,loading:i,children:e("settings.workflowsTab.refresh")}),r.jsx(U,{"data-testid":"create-workflow",icon:r.jsx(Gs,{}),onClick:P,children:e("settings.workflowsTab.newWorkflow")}),r.jsx(U,{"data-testid":"save-workflow",type:"primary",icon:r.jsx(Mi,{}),onClick:v,loading:u,disabled:!S,children:e("settings.workflowsTab.save")})]}),children:[r.jsx(fl,{type:"secondary",children:e("settings.workflowsTab.description")}),r.jsxs(J,{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:E=>r.jsx(nt.Item,{style:{cursor:"pointer",backgroundColor:(f==null?void 0:f.name)===E.name?t.colorFillSecondary:"transparent",borderRadius:t.borderRadius,padding:t.paddingSM},onClick:()=>C(E),actions:[r.jsx(U,{"data-testid":`delete-workflow-${E.name}`,type:"text",danger:!0,size:"small",icon:r.jsx(yn,{}),onClick:_=>{_.stopPropagation(),M(E)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:r.jsxs(H,{direction:"vertical",size:0,children:[r.jsxs(fl,{strong:!0,children:["/",E.name]}),r.jsx(fl,{type:"secondary",style:{fontSize:12},children:E.filename})]})})})}),r.jsx("div",{style:{flex:1},children:r.jsxs(H,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(he,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:y,onChange:E=>{p(E.target.value),w(!0)},disabled:!!f,prefix:r.jsx(Sr,{})}),r.jsx(T_,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:x,onChange:E=>{b(E.target.value),w(!0)},autoSize:{minRows:12},disabled:c})]})})]})]})]})};var me=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))(me||{});const ha=6e4,pa=3e4,sa=2e4,xi=1e4,Wi=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:sa},request_timeout_ms:ha,healthcheck_interval_ms:pa,allowed_tools:[],denied_tools:[]}),M_=()=>({status:"stopped",tool_count:0,restart_count:0}),P_=e=>{switch(typeof e=="string"?e.trim().toLowerCase():""){case me.Connecting:return me.Connecting;case me.Ready:return me.Ready;case me.Degraded:return me.Degraded;case me.Error:return me.Error;case me.Stopped:default:return me.Stopped}},Vs=(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},E_=(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:Vs(s.connect_timeout_ms,xi)}}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:Vs(s.startup_timeout_ms,sa)}},R_=(e,t)=>{const s=Wi(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:Vs(n.request_timeout_ms,ha),healthcheck_interval_ms:Vs(n.healthcheck_interval_ms,pa),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:Vs(n.reconnect.initial_backoff_ms,1e3),max_backoff_ms:Vs(n.reconnect.max_backoff_ms,3e4),max_attempts:Vs(n.reconnect.max_attempts,0)}:void 0,transport:E_(n.transport,s.transport)}},A_=e=>{const t=M_(),n=e.runtime??{},o=n.status??e.status;return{status:P_(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:Vs(n.tool_count??e.tool_count,t.tool_count),restart_count:Vs(n.restart_count??e.restart_count,t.restart_count),last_ping_at:typeof n.last_ping_at=="string"?n.last_ping_at:void 0}},I_=e=>{const t=R_(e,e.config);return{id:e.id,name:typeof e.name=="string"?e.name:typeof t.name=="string"?t.name:e.id,enabled:typeof e.enabled=="boolean"?e.enabled:t.enabled,config:t,runtime:A_(e)}},$_=(e,t)=>`mcp__${e}__${t}`,D_=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}},F_=(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"?D_(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?$_(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,f=c||l||`mcp_tool_${s}`;return{alias:f,server_id:i||"unknown",original_name:l||f,description:d,parameters:h}};class L_{async getServers(){const t=await ye.get("mcp/servers");return Array.isArray(t.servers)?t.servers.map(I_):[]}async addServer(t){return ye.post("mcp/servers",t)}async updateServer(t,s){const n={...s,id:t};return ye.put(`mcp/servers/${t}`,n)}async deleteServer(t){return ye.delete(`mcp/servers/${t}`)}async connectServer(t){return ye.post(`mcp/servers/${t}/connect`)}async disconnectServer(t){return ye.post(`mcp/servers/${t}/disconnect`)}async refreshTools(t){return ye.post(`mcp/servers/${t}/refresh`)}async getTools(t){const s=t?`mcp/servers/${t}/tools`:"mcp/tools",n=await ye.get(s);return(Array.isArray(n.tools)?n.tools:[]).map((a,i)=>F_(a,t,i)).filter(a=>!!a)}async importServers(t){return ye.post("mcp/servers/import",t)}}const ay=new L_,O_=5e3,qs=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,rm=(e,t)=>`${e}:${t}`,z_=(e={})=>{const{service:t=ay,autoRefreshMs:s=O_,autoRefreshEnabled:n=!0}=e,[o,a]=m.useState([]),[i,l]=m.useState(null),[c,d]=m.useState({}),[u,h]=m.useState({}),[f,g]=m.useState({}),[y,p]=m.useState(!1),[x,b]=m.useState(!1),[S,w]=m.useState(!1),[k,j]=m.useState(null),C=m.useRef({}),P=m.useCallback(F=>{const q=new Set(F.map(G=>G.id)),K=F.map(G=>{const Pe=C.current[G.id]??G.config,Ee={...Pe,id:G.id,name:Pe.name??G.name};return C.current[G.id]=Ee,{...G,name:G.name||Ee.name||G.id,enabled:G.enabled??Ee.enabled,config:Ee}});return Object.keys(C.current).forEach(G=>{q.has(G)||delete C.current[G]}),K},[]),v=m.useCallback(async({silent:F=!1}={})=>{F||p(!0);try{const q=await t.getServers(),K=P(q);a(K),l(G=>{var be;return G&&K.some(Pe=>Pe.id===G)?G:((be=K[0])==null?void 0:be.id)??null}),j(null)}catch(q){throw j(qs(q,"Failed to load MCP servers")),q}finally{F||p(!1)}},[P,t]),M=m.useCallback(async(F,q=!1)=>{if(!F)return[];if(!q&&c[F])return c[F];h(K=>({...K,[F]:!0}));try{const K=await t.getTools(F);return d(G=>({...G,[F]:K})),j(null),K}catch(K){throw j(qs(K,"Failed to load MCP tools")),K}finally{h(K=>({...K,[F]:!1}))}},[t,c]),E=m.useCallback((F,q,K)=>{const G=rm(F,q);g(be=>({...be,[G]:K}))},[]),_=m.useCallback(async F=>{b(!0);try{await t.addServer(F),C.current[F.id]=F,await v()}catch(q){throw j(qs(q,"Failed to add MCP server")),q}finally{b(!1)}},[v,t]),R=m.useCallback(async(F,q)=>{b(!0);try{const K={...q,id:F};await t.updateServer(F,K),C.current[F]=K,await v()}catch(K){throw j(qs(K,"Failed to update MCP server")),K}finally{b(!1)}},[v,t]),T=m.useCallback(async F=>{E(F,"delete",!0);try{await t.deleteServer(F),d(q=>{const K={...q};return delete K[F],K}),delete C.current[F],await v()}catch(q){throw j(qs(q,"Failed to delete MCP server")),q}finally{E(F,"delete",!1)}},[v,t,E]),D=m.useCallback(async F=>{E(F,"connect",!0);try{await t.connectServer(F),await v({silent:!0})}catch(q){throw j(qs(q,"Failed to connect MCP server")),q}finally{E(F,"connect",!1)}},[v,t,E]),$=m.useCallback(async F=>{E(F,"disconnect",!0);try{await t.disconnectServer(F),await v({silent:!0})}catch(q){throw j(qs(q,"Failed to disconnect MCP server")),q}finally{E(F,"disconnect",!1)}},[v,t,E]),I=m.useCallback(async F=>{E(F,"refresh",!0);try{await t.refreshTools(F),await M(F,!0),await v({silent:!0})}catch(q){throw j(qs(q,"Failed to refresh MCP tools")),q}finally{E(F,"refresh",!1)}},[M,v,t,E]),O=m.useCallback(async()=>{w(!0);try{const F=o.map(q=>q.id);await Promise.all(F.map(async q=>{try{await t.refreshTools(q)}catch{}})),await v(),i&&await M(i,!0)}catch(F){throw j(qs(F,"Failed to refresh MCP status")),F}finally{w(!1)}},[M,v,i,o,t]),A=m.useCallback(F=>{l(F)},[]),z=m.useCallback((F,q)=>!!f[rm(F,q)],[f]),L=m.useMemo(()=>i?c[i]??[]:[],[i,c]),Y=m.useMemo(()=>i?!!u[i]:!1,[i,u]);return m.useEffect(()=>{v().catch(()=>{})},[v]),m.useEffect(()=>{if(!n||s<=0)return;const F=window.setInterval(()=>{v({silent:!0}).catch(()=>{})},s);return()=>{window.clearInterval(F)}},[n,s,v]),m.useEffect(()=>{i&&M(i).catch(()=>{})},[M,i]),{servers:o,selectedServerId:i,selectedServerTools:L,isLoadingServers:y,isMutatingConfig:x,isRefreshingAll:S,isSelectedServerToolsLoading:Y,error:k,setSelectedServerId:A,refreshServers:v,addServer:_,updateServer:R,deleteServer:T,connectServer:D,disconnectServer:$,refreshServerTools:I,refreshAll:O,isServerActionLoading:z}},N_={[me.Connecting]:"blue",[me.Ready]:"green",[me.Degraded]:"orange",[me.Stopped]:"default",[me.Error]:"red"},B_=e=>e===me.Connecting||e===me.Ready||e===me.Degraded,W_=e=>{if(!e)return;const t=e.replace(/\s+/g," ").trim();if(t)return t.length>180?`${t.slice(0,180)}...`:t},U_=({servers:e,loading:t=!1,selectedServerId:s,onSelectServer:n,onEditServer:o,onDeleteServer:a,onConnectServer:i,onDisconnectServer:l,onRefreshTools:c,isServerActionLoading:d})=>{const{t:u}=se(),{token:h}=pe.useToken(),f=m.useMemo(()=>({[me.Connecting]:u("settings.mcpTab.statusHelp.connecting"),[me.Ready]:u("settings.mcpTab.statusHelp.ready"),[me.Degraded]:u("settings.mcpTab.statusHelp.degraded"),[me.Stopped]:u("settings.mcpTab.statusHelp.stopped"),[me.Error]:u("settings.mcpTab.statusHelp.error")}),[u]),g=m.useMemo(()=>[{key:"name",title:u("settings.mcpServerTable.columns.name"),render:(y,p)=>p.name||p.id},{key:"transport",title:u("settings.mcpServerTable.columns.transportType"),render:(y,p)=>p.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,p)=>{var k,j;const x=((k=p.runtime)==null?void 0:k.status)??me.Stopped,b=W_((j=p.runtime)==null?void 0:j.last_error),S=f[x],w={[me.Connecting]:u("settings.mcpTab.status.connecting"),[me.Ready]:u("settings.mcpTab.status.ready"),[me.Degraded]:u("settings.mcpTab.status.degraded"),[me.Stopped]:u("settings.mcpTab.status.stopped"),[me.Error]:u("settings.mcpTab.status.error")};return r.jsx(ke,{title:b?`${S} ${u("settings.mcpTab.statusLastError",{error:b})}`:S,children:r.jsx(oe,{color:x===me.Stopped?void 0:N_[x],style:{marginInlineEnd:0,cursor:"help",...x===me.Stopped?{background:h.colorFillSecondary,borderColor:h.colorBorderSecondary,color:h.colorTextSecondary}:void 0},children:w[x]})})},width:120},{key:"toolCount",title:u("settings.mcpServerTable.columns.toolCount"),render:(y,p)=>{var x;return((x=p.runtime)==null?void 0:x.tool_count)??0},width:100},{key:"actions",title:u("settings.mcpServerTable.columns.actions"),width:360,render:(y,p)=>{var S;const x=((S=p.runtime)==null?void 0:S.status)??me.Stopped,b=B_(x);return r.jsxs(H,{size:h.marginXS,children:[r.jsx(U,{size:"small",onClick:w=>{w.stopPropagation(),o==null||o(p)},children:u("settings.mcpServerTable.actions.edit")}),r.jsx(ti,{title:u("settings.mcpServerTable.deleteTitle"),description:u("settings.mcpServerTable.deleteDescription",{name:p.name||p.id}),onConfirm:()=>a==null?void 0:a(p),okText:u("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:d==null?void 0:d(p.id,"delete")},children:r.jsx(U,{size:"small",danger:!0,loading:d==null?void 0:d(p.id,"delete"),onClick:w=>w.stopPropagation(),children:u("settings.mcpServerTable.actions.delete")})}),b?r.jsx(U,{size:"small",onClick:w=>{w.stopPropagation(),l==null||l(p)},loading:d==null?void 0:d(p.id,"disconnect"),children:u("settings.mcpServerTable.actions.disconnect")}):r.jsx(U,{size:"small",type:"primary",ghost:!0,onClick:w=>{w.stopPropagation(),i==null||i(p)},loading:d==null?void 0:d(p.id,"connect"),children:u("settings.mcpServerTable.actions.connect")}),r.jsx(U,{size:"small",onClick:w=>{w.stopPropagation(),c==null||c(p)},loading:d==null?void 0:d(p.id,"refresh"),children:u("settings.mcpServerTable.actions.refreshTools")})]})}}],[d,i,a,l,o,c,f,u,h.colorBorderSecondary,h.colorFillSecondary,h.colorTextSecondary,h.marginXS]);return r.jsx(Js,{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:om}=ce,{TextArea:q_}=he,am=e=>{const t=e??Wi(""),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||ha,healthcheckIntervalMs:t.healthcheck_interval_ms||pa,allowedTools:t.allowed_tools||[],deniedTools:t.denied_tools||[]}},H_=e=>e.reduce((t,s)=>{var o;const n=(o=s.key)==null?void 0:o.trim();return n&&(t[n]=s.value??""),t},{}),Y_=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??""}}),im=(e,t,s)=>{var u,h,f;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)??ha,i=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(s==null?void 0:s.healthcheck_interval_ms)??pa,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:Y_(e.headerEntries||[]),connect_timeout_ms:(s==null?void 0:s.transport.type)==="sse"?s.transport.connect_timeout_ms??xi:xi}:{type:"stdio",command:((f=e.command)==null?void 0:f.trim())||"",args:e.args||[],env:H_(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??sa:sa};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}},lm=e=>JSON.stringify(e||Wi(""),null,2),gl=(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:ha,l=typeof n.healthcheck_interval_ms=="number"?n.healthcheck_interval_ms:pa,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,f=Array.isArray(h)?h.map(y=>{if(!y||typeof y!="object")return null;const p=y,x=typeof p.name=="string"?p.name:"",b=typeof p.value=="string"?p.value:"";return x.trim()?{name:x,value:b}:null}).filter(y=>!!y):h&&typeof h=="object"?Object.entries(h).filter(([y])=>y.trim()).map(([y,p])=>({name:y,value:typeof p=="string"?p:""})):[],g=typeof n.connect_timeout_ms=="number"?n.connect_timeout_ms:xi;return{valid:!0,config:{id:o,name:u,enabled:a,transport:{type:"sse",url:n.url,headers:f,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(p=>typeof p=="string"):[],f=n.env,g=f&&typeof f=="object"?Object.entries(f).reduce((p,[x,b])=>(typeof b=="string"&&(p[x]=b),p),{}):{},y=typeof n.startup_timeout_ms=="number"?n.startup_timeout_ms:sa;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")})}}},X_=({open:e,mode:t,initialConfig:s,confirmLoading:n=!1,onCancel:o,onSubmit:a})=>{const{t:i}=se(),[l]=Z.useForm(),[c,d]=m.useState("form"),[u,h]=m.useState(""),[f,g]=m.useState(null),y=m.useMemo(()=>am(s),[s]),p=Z.useWatch("transportType",l)??"stdio";m.useEffect(()=>{e&&(l.setFieldsValue(y),h(lm(s)),g(null),d("form"))},[l,y,s,e]);const x=()=>{l.resetFields(),h(""),g(null),o()},b=async()=>{if(c==="json"){const k=gl(u,i);if(!k.valid){g(k.error);return}g(null);try{await a(k.config),h("")}catch(j){console.error("MCP server JSON submission error:",j)}return}try{const k=await l.validateFields(),j=im(k,t,s);await a(j),l.resetFields()}catch(k){console.error("MCP server form submission error:",k)}},S=k=>{h(k),f&&gl(k,i).valid&&g(null)},w=k=>{if(k==="json")try{const j=l.getFieldsValue(),C=im(j,t,s);h(JSON.stringify(C,null,2))}catch{h(lm(s))}else{const j=gl(u,i);j.valid&&l.setFieldsValue(am(j.config))}d(k),g(null)};return r.jsxs(Lt,{title:i(t==="edit"?"settings.mcpServerForm.editTitle":"settings.mcpServerForm.addTitle"),open:e,onCancel:x,onOk:()=>{b()},okText:i("settings.mcpServerForm.save"),destroyOnClose:!0,confirmLoading:n,width:720,children:[r.jsx("div",{style:{marginBottom:16},children:r.jsxs(is.Group,{value:c,onChange:k=>w(k.target.value),optionType:"button",buttonStyle:"solid",children:[r.jsxs(is.Button,{value:"form",children:[r.jsx(Yx,{})," ",i("settings.mcpServerForm.modeForm")]}),r.jsxs(is.Button,{value:"json",children:[r.jsx(Pi,{})," ",i("settings.mcpServerForm.modeJson")]})]})}),c==="json"&&f&&r.jsx(Ne,{type:"error",message:i("settings.mcpServerForm.jsonError"),description:f,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>g(null)}),c==="json"?r.jsx(q_,{value:u,onChange:k=>S(k.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(Wi("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(he,{placeholder:"filesystem",disabled:t==="edit",autoComplete:"off"})}),r.jsx(Z.Item,{name:"name",label:i("settings.mcpServerForm.displayName"),children:r.jsx(he,{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(ct,{})}),r.jsx(Z.Item,{name:"transportType",label:i("settings.mcpServerForm.transportType"),rules:[{required:!0,message:i("settings.mcpServerForm.transportTypeRequired")}],children:r.jsx(Fe,{options:[{label:i("settings.mcpServerForm.transportOptions.stdio"),value:"stdio"},{label:i("settings.mcpServerForm.transportOptions.sse"),value:"sse"}]})}),p==="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(he,{placeholder:"npx",autoComplete:"off"})}),r.jsx(Z.Item,{name:"args",label:i("settings.mcpServerForm.arguments"),children:r.jsx(Fe,{mode:"tags",tokenSeparators:[","],placeholder:i("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),r.jsx(Z.List,{name:"envEntries",children:(k,{add:j,remove:C})=>r.jsxs(H,{direction:"vertical",style:{width:"100%"},children:[r.jsxs(H,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[r.jsx(om,{strong:!0,children:i("settings.mcpServerForm.envVars")}),r.jsx(U,{icon:r.jsx(Gs,{}),onClick:()=>j({key:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addEnv")})]}),k.map(P=>r.jsxs(H,{align:"baseline",style:{display:"flex"},children:[r.jsx(Z.Item,{...P,name:[P.name,"key"],rules:[{required:!0,message:i("settings.mcpServerForm.keyRequired")}],children:r.jsx(he,{placeholder:"MCP_ROOT",autoComplete:"off"})}),r.jsx(Z.Item,{...P,name:[P.name,"value"],children:r.jsx(he,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),r.jsx(U,{danger:!0,type:"text",icon:r.jsx(Ql,{}),onClick:()=>C(P.name),"aria-label":i("settings.mcpServerForm.removeEnv","Remove environment variable")})]},P.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(k,j)=>{if(j)try{new URL(j)}catch{throw new Error(i("settings.mcpServerForm.validUrlRequired"))}}}],children:r.jsx(he,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),r.jsx(Z.List,{name:"headerEntries",children:(k,{add:j,remove:C})=>r.jsxs(H,{direction:"vertical",style:{width:"100%"},children:[r.jsxs(H,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[r.jsx(om,{strong:!0,children:i("settings.mcpServerForm.headers")}),r.jsx(U,{icon:r.jsx(Gs,{}),onClick:()=>j({name:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addHeader")})]}),k.map(P=>r.jsxs(H,{align:"baseline",style:{display:"flex"},children:[r.jsx(Z.Item,{...P,name:[P.name,"name"],rules:[{required:!0,message:i("settings.mcpServerForm.headerNameRequired")}],children:r.jsx(he,{placeholder:"Authorization",autoComplete:"off"})}),r.jsx(Z.Item,{...P,name:[P.name,"value"],children:r.jsx(he,{placeholder:"Bearer token",autoComplete:"off"})}),r.jsx(U,{danger:!0,type:"text",icon:r.jsx(Ql,{}),onClick:()=>C(P.name),"aria-label":i("settings.mcpServerForm.removeHeader","Remove header")})]},P.key))]})})]})]})]})},V_={maxLines:8,maxCharacters:500},mn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),an=e=>typeof e=="string"?e:void 0,An=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,cm=e=>typeof e=="boolean"?e:void 0,Dd=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const s=JSON.parse(t);return mn(s)?s:null}catch{return null}},iy=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,$s=e=>Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>iy(t).trim()).filter(Boolean):[],xt=e=>{if(typeof e!="string")return;const t=iy(e).trim();return t.length>0?t:void 0},K_=e=>{if(!mn(e))return;const t=xt(e.graph);if(t)return{title:xt(e.title),graph:t}},G_=e=>{if(!mn(e))return;const t=xt(e.summary)??xt(e.conclusion);if(t)return{title:xt(e.title)||"Conclusion",summary:t,key_points:$s(e.key_points),next_steps:$s(e.next_steps),confidence:xt(e.confidence),mermaid:K_(e.mermaid)}},J_=e=>{const t=Dd(e);if(!t)return null;const s=xt(t.conclusion);return!s||t.type!=null&&t.type!=="conclusion"?null:{type:"conclusion",title:xt(t.title)||"Conclusion",conclusion:s,key_points:$s(t.key_points),next_steps:$s(t.next_steps),confidence:xt(t.confidence)}},Q_=e=>{const t=Dd(e);if(!t)return null;const s=xt(t.question);if(!s)return null;const n=xt(t.status);return n&&n!=="awaiting_user_input"&&n!=="awaiting_permission_approval"?null:{question:s,options:$s(t.options),allow_custom:typeof t.allow_custom=="boolean"?t.allow_custom:!0,conclusion:G_(t.conclusion)}},Z_=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
|
+
`)},ly=e=>{const t=J_(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
|
+
`)},fa=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const s=JSON.parse(t);if(!mn(s))return null;const n=an(s.file_path),o=an(s.operation),a=s.diff;if(!n||!o||!mn(a))return null;const i=an(a.unified);if(!i)return null;const l=s.checkpoint,c=mn(l)?{created:cm(l.created)??!1,id:an(l.id),path:an(l.path),size_bytes:An(l.size_bytes),reason:an(l.reason)}:void 0;return{operation:o,message:an(s.message),file_path:n,workspace:an(s.workspace),checkpoint:c,diff:{unified:i,old_line_count:An(a.old_line_count),new_line_count:An(a.new_line_count),added_lines:An(a.added_lines),removed_lines:An(a.removed_lines),truncated:cm(a.truncated)}}}catch{return null}},cy=e=>{const t=Dd(e);if(!t)return null;const s=xt(t.action);if(s!=="inspect"&&s!=="rebuild")return null;const n=t.data;if(!mn(n))return null;const o=xt(n.scope),a=An(n.total_memories);if(!o||typeof a!="number")return null;const i=l=>mn(l)?Object.fromEntries(Object.entries(l).filter(c=>typeof c[0]=="string"&&typeof c[1]=="number")):{};return{action:s,scope:xt(t.scope),project_key:xt(t.project_key),data:{scope:o,project_key:xt(n.project_key),total_memories:a,by_type:i(n.by_type),by_status:i(n.by_status),recent_ids:$s(n.recent_ids),view_files:$s(n.view_files),index_files:$s(n.index_files),state_files:$s(n.state_files),stale_candidate_count:An(n.stale_candidate_count)??0,last_reindex_at:xt(n.last_reindex_at),last_dream_at:xt(n.last_dream_at),topic_paths:$s(n.topic_paths)}}},Cc=e=>e.startsWith("-")&&!e.startsWith("---"),Mc=e=>e.startsWith("+")&&!e.startsWith("+++"),dy=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(Cc(o)){const a=[];for(;n<t.length&&Cc(t[n]??"");)a.push(t[n]??""),n+=1;const i=[];for(;n<t.length&&Mc(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(Mc(o)){s.push({kind:"add",text:o}),n+=1;continue}s.push({kind:"context",text:o}),n+=1}return s},e0=e=>{let t=0,s=0;for(const n of e.split(`
|
|
129
|
+
`)){if(Mc(n)){t+=1;continue}Cc(n)&&(s+=1)}return{added:t,removed:s}},Pc=e=>{const t=fa(e);if(!t)return null;const s=e0(t.diff.unified);return{added:t.diff.added_lines??s.added,removed:t.diff.removed_lines??s.removed}},Ec=e=>{if(typeof e=="string")return e.replace(/\\n/g,`
|
|
130
|
+
`).replace(/\\t/g," ");if(Array.isArray(e))return e.map(Ec);if(e!==null&&typeof e=="object"){const t={};for(const[s,n]of Object.entries(e))t[s]=Ec(n);return t}return e},Rc=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=Ec(s);return{isJson:!0,formattedText:JSON.stringify(n,null,2),parsedJson:n}}catch{return{isJson:!1,formattedText:e}}},t0=(e,t={})=>{const s={...V_,...t};return e?e.split(/\r?\n/).length>s.maxLines?!0:e.length>s.maxCharacters:!1},s0=(e,t=320)=>e?e.length<=t?{preview:e,isTruncated:!1}:{preview:e.substring(0,t).trimEnd()+"…",isTruncated:!0}:{preview:"",isTruncated:!1},n0=e=>{if(!e)return"No content";const t=60,s=e.trim(),n=fa(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=cy(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()+"…"},uy=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)}},Ga=e=>!!e&&typeof e=="object"&&!Array.isArray(e),_n=(e,t)=>{const s=e[t];return typeof s=="string"?s:void 0},dm=(e,t)=>{const s=e[t];return typeof s=="boolean"?s:void 0},r0=(e,t)=>{const s=e[t];return Array.isArray(s)?s:void 0},qo=e=>{if(!Ga(e))return"any";const t=e.type;if(typeof t=="string"){if(t==="array"){const a=e.items;return`array<${qo(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(qo).join(" | ")||"any";const n=Array.isArray(e.anyOf)?e.anyOf:null;if(n)return n.map(qo).join(" | ")||"any";const o=Array.isArray(e.allOf)?e.allOf:null;return o&&o.map(qo).join(" & ")||"any"},o0=e=>{if(!Ga(e))return null;const t=e.properties;if(!Ga(t))return{schemaUri:_n(e,"$schema"),title:_n(e,"title"),description:_n(e,"description"),additionalProperties:dm(e,"additionalProperties"),fields:[]};const s=new Set((r0(e,"required")??[]).filter(o=>typeof o=="string").map(o=>o)),n=Object.entries(t).map(([o,a])=>{const i=Ga(a)?a:void 0;return{name:o,type:qo(a),required:s.has(o),description:i?_n(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:_n(e,"$schema"),title:_n(e,"title"),description:_n(e,"description"),additionalProperties:dm(e,"additionalProperties"),fields:n}},{Text:Ps}=ce,a0=e=>e===void 0?"":e===null?"null":typeof e=="string"?e:xr(e,0),i0=({schema:e})=>{const{token:t}=pe.useToken(),{t:s}=se(),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(Ps,{code:!0,children:i})},{title:s("components.jsonSchema.type"),dataIndex:"type",key:"type",width:140,render:i=>r.jsx(Ps,{children:i})},{title:s("components.jsonSchema.required"),dataIndex:"required",key:"required",width:110,render:i=>i?r.jsx(Ps,{strong:!0,style:{color:t.colorError},children:s("components.jsonSchema.yes")}):r.jsx(Ps,{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(Ps,{type:"secondary",children:"-"}):r.jsx(Ps,{children:a0(i)})},{title:s("components.jsonSchema.description"),dataIndex:"description",key:"description",render:i=>i?r.jsx(Ps,{style:{whiteSpace:"pre-wrap"},children:i}):r.jsx(Ps,{type:"secondary",children:"-"})}],a=(n.fields??[]).map(i=>({...i,key:i.name}));return r.jsxs("div",{style:{width:"100%"},children:[r.jsx(At,{size:"small",column:1,items:[n.schemaUri?{key:"schema",label:"$schema",children:r.jsx(Ps,{code:!0,children:n.schemaUri})}:null,typeof n.additionalProperties=="boolean"?{key:"additionalProperties",label:"additionalProperties",children:r.jsx(Ps,{children:n.additionalProperties?"true":"false"})}:null].filter(Boolean)}),r.jsx(Js,{size:"small",pagination:!1,columns:o,dataSource:a,locale:{emptyText:s("components.jsonSchema.noProperties")},style:{marginTop:t.marginSM}})]})},{Text:Fr}=ce,l0=(e,t)=>`mcp__${e}__${t}`,c0=({server:e,tools:t,loading:s=!1})=>{const{t:n}=se();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=l0(o.server_id,o.original_name);return r.jsx(nt.Item,{children:r.jsxs(H,{direction:"vertical",size:2,style:{width:"100%"},children:[r.jsx(Fr,{strong:!0,children:o.original_name}),r.jsx(Fr,{type:"secondary",children:o.description||n("settings.mcpToolList.noDescription")}),r.jsx(Fr,{code:!0,children:o.alias}),r.jsxs(Fr,{type:"secondary",children:[n("settings.mcpToolList.aliasMapping"),": ",r.jsx(Fr,{code:!0,children:a})]}),o.parameters!==void 0&&r.jsx(ws,{size:"small",items:[{key:"schema",label:n("settings.mcpToolList.parametersSchema"),children:r.jsx(i0,{schema:o.parameters})}]})]})})}}):r.jsx(Pt,{image:Pt.PRESENTED_IMAGE_SIMPLE,description:n("settings.mcpToolList.selectServerHint")})})},{Text:Lr}=ce,{useToken:d0}=pe,{TextArea:u0}=he,um={[me.Connecting]:"processing",[me.Ready]:"success",[me.Degraded]:"warning",[me.Stopped]:"default",[me.Error]:"error"},m0=()=>({[me.Connecting]:0,[me.Ready]:0,[me.Degraded]:0,[me.Stopped]:0,[me.Error]:0}),Tn=(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 f={url:d.url};c&&(f.disabled=!0),Object.keys(h).length&&(f.headers=h),t[i]=f;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}},p0=()=>{const{t:e}=se(),{token:t}=d0(),[s,n]=fe.useMessage(),{servers:o,selectedServerId:a,selectedServerTools:i,isLoadingServers:l,isMutatingConfig:c,isRefreshingAll:d,isSelectedServerToolsLoading:u,error:h,setSelectedServerId:f,addServer:g,updateServer:y,deleteServer:p,connectServer:x,disconnectServer:b,refreshServerTools:S,refreshAll:w,isServerActionLoading:k}=z_(),j=m.useMemo(()=>({[me.Connecting]:e("settings.mcpTab.status.connecting"),[me.Ready]:e("settings.mcpTab.status.ready"),[me.Degraded]:e("settings.mcpTab.status.degraded"),[me.Stopped]:e("settings.mcpTab.status.stopped"),[me.Error]:e("settings.mcpTab.status.error")}),[e]),C=m.useMemo(()=>({[me.Connecting]:e("settings.mcpTab.statusHelp.connecting"),[me.Ready]:e("settings.mcpTab.statusHelp.ready"),[me.Degraded]:e("settings.mcpTab.statusHelp.degraded"),[me.Stopped]:e("settings.mcpTab.statusHelp.stopped"),[me.Error]:e("settings.mcpTab.statusHelp.error")}),[e]),[P,v]=m.useState(!1),[M,E]=m.useState("create"),[_,R]=m.useState(null),[T,D]=m.useState(!1),[$,I]=m.useState("merge"),[O,A]=m.useState(""),[z,L]=m.useState(null),[Y,F]=m.useState(!1),q=m.useMemo(()=>a?o.find(B=>B.id===a)??null:null,[a,o]),K=m.useMemo(()=>{const B=m0();let Me=0;return o.forEach(X=>{var ie,le;const ue=((ie=X.runtime)==null?void 0:ie.status)??me.Stopped;B[ue]+=1,Me+=((le=X.runtime)==null?void 0:le.tool_count)??0}),{byStatus:B,totalServers:o.length,totalTools:Me}},[o]),G={background:t.colorFillSecondary,borderColor:t.colorBorderSecondary,color:t.colorTextSecondary},be=async B=>{try{await p(B.id),s.success(e("settings.mcpTab.serverDeleted"))}catch(Me){s.error(Tn(Me,e("settings.mcpTab.deleteServerFailed")))}},Pe=async B=>{try{await x(B.id),s.success(e("settings.mcpTab.connectedTo",{name:B.name||B.id}))}catch(Me){s.error(Tn(Me,e("settings.mcpTab.connectServerFailed")))}},Ee=async B=>{try{await b(B.id),s.success(e("settings.mcpTab.disconnected",{name:B.name||B.id}))}catch(Me){s.error(Tn(Me,e("settings.mcpTab.disconnectServerFailed")))}},Te=async B=>{try{await S(B.id),s.success(e("settings.mcpTab.toolsRefreshedFor",{name:B.name||B.id}))}catch(Me){s.error(Tn(Me,e("settings.mcpTab.refreshToolsFailed")))}},ge=async()=>{try{await w(),s.success(e("settings.mcpTab.statusRefreshed"))}catch(B){s.error(Tn(B,e("settings.mcpTab.refreshStatusFailed")))}},je=()=>{R(null),E("create"),v(!0)},Be=B=>{R(B),E("edit"),v(!0)},Qe=async B=>{try{if(M==="edit"){if(!_){s.error(e("settings.mcpTab.noServerForEditing"));return}await y(_.id,B),s.success(e("settings.mcpTab.savedServer",{name:_.name||_.id}))}else await g(B),s.success(e("settings.mcpTab.addedServer",{name:B.name||B.id}));v(!1),R(null)}catch(Me){s.error(Tn(Me,e("settings.mcpTab.saveServerFailed")))}},jt=()=>{D(!0),L(null),I("merge"),A("")},Ze=async()=>{const B=h0(o),Me=JSON.stringify(B,null,2);try{await ds(Me),s.success(e("settings.mcpTab.copiedConfig"))}catch{D(!0),L(null),I("merge"),A(Me),s.warning(e("settings.mcpTab.clipboardUnavailable"))}},Bt=async()=>{var ue;L(null);let B;try{B=JSON.parse(O)}catch(ie){L(`${e("settings.mcpTab.invalidJsonPrefix")}: ${ie instanceof Error?ie.message:e("settings.mcpTab.unknownError")}`);return}if(!B||typeof B!="object"){L(e("settings.mcpTab.jsonMustBeObject"));return}const X=B.mcpServers;if(!X||typeof X!="object"){L(e("settings.mcpTab.missingMcpServers"));return}F(!0);try{const ie=await ay.importServers({mcpServers:X,mode:$}),le=((ue=ie.start_errors)==null?void 0:ue.length)??0;s.success(e("settings.mcpTab.importSummary",{count:ie.server_ids.length,added:ie.added,updated:ie.updated,removed:ie.removed,failed:le})),le&&s.warning(e("settings.mcpTab.importStartFailures")),D(!1),A(""),await ge()}catch(ie){L(Tn(ie,e("settings.mcpTab.importFailed")))}finally{F(!1)}};return r.jsxs(H,{direction:"vertical",size:t.marginMD,style:{width:"100%"},children:[n,h?r.jsx(Ne,{type:"error",showIcon:!0,message:h}):null,r.jsx(ee,{size:"small",title:e("settings.mcpTab.overviewTitle"),children:r.jsxs(H,{direction:"vertical",size:t.marginXS,style:{width:"100%"},children:[r.jsx(Lr,{type:"secondary",children:e("settings.mcpTab.overviewDescription")}),r.jsxs(H,{wrap:!0,children:[r.jsx(oe,{style:G,children:e("settings.mcpTab.totalServers",{count:K.totalServers})}),r.jsx(oe,{style:G,children:e("settings.mcpTab.totalTools",{count:K.totalTools})}),Object.values(me).map(B=>r.jsx(ke,{title:C[B],children:r.jsxs(oe,{color:B===me.Stopped?void 0:um[B],style:{cursor:"help",...B===me.Stopped?G:void 0},children:[j[B],": ",K.byStatus[B]]})},B))]}),r.jsx(Lr,{type:"secondary",children:e("settings.mcpTab.statusGuideTitle")}),r.jsx(H,{direction:"vertical",size:2,style:{width:"100%"},children:Object.values(me).map(B=>r.jsxs(Lr,{type:"secondary",children:[r.jsx(oe,{color:B===me.Stopped?void 0:um[B],style:{marginInlineEnd:8,...B===me.Stopped?G:void 0},children:j[B]}),C[B]]},`guide-${B}`))})]})}),r.jsx(ee,{size:"small",title:e("settings.mcpTab.serversTitle"),extra:r.jsxs(H,{children:[r.jsx(U,{type:"primary",onClick:je,children:e("settings.mcpTab.addServer")}),r.jsx(U,{icon:r.jsx(Fs,{}),loading:d,onClick:()=>{ge()},children:e("settings.mcpTab.refreshAll")}),r.jsx(U,{icon:r.jsx(ls,{}),onClick:()=>void Ze(),children:e("settings.mcpTab.export")}),r.jsx(U,{icon:r.jsx(Xx,{}),onClick:jt,children:e("settings.mcpTab.import")})]}),children:r.jsx(U_,{servers:o,loading:l,selectedServerId:a,onSelectServer:f,onEditServer:Be,onDeleteServer:be,onConnectServer:Pe,onDisconnectServer:Ee,onRefreshTools:Te,isServerActionLoading:k})}),r.jsx(c0,{server:q,tools:i,loading:u}),r.jsx(X_,{open:P,mode:M,initialConfig:(_==null?void 0:_.config)??null,confirmLoading:c,onCancel:()=>{c||(v(!1),R(null))},onSubmit:B=>void Qe(B)}),r.jsx(Lt,{open:T,title:e("settings.mcpTab.importModalTitle"),okText:e("settings.mcpTab.import"),onOk:()=>void Bt(),okButtonProps:{loading:Y},onCancel:()=>{Y||(D(!1),L(null))},width:800,destroyOnClose:!1,children:r.jsxs(H,{direction:"vertical",style:{width:"100%"},size:"middle",children:[r.jsxs(Lr,{type:"secondary",children:[e("settings.mcpTab.importHint"),r.jsx("br",{}),r.jsx(Lr,{code:!0,children:'{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "..."] } } }'})]}),r.jsxs(is.Group,{value:$,onChange:B=>I(B.target.value),optionType:"button",buttonStyle:"solid",children:[r.jsx(is.Button,{value:"merge",children:e("settings.mcpTab.importModeMerge")}),r.jsx(is.Button,{value:"replace",children:e("settings.mcpTab.importModeReplace")})]}),$==="replace"?r.jsx(Ne,{type:"warning",showIcon:!0,message:e("settings.mcpTab.replaceWarning")}):null,z?r.jsx(Ne,{type:"error",showIcon:!0,message:z}):null,r.jsx(u0,{value:O,onChange:B=>A(B.target.value),rows:14,placeholder:'{"mcpServers": { "filesystem": { "command": "...", "args": [], "env": {} } }}',spellCheck:!1})]})})]})},Gt=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 f0{async getSummary(t={}){const s=Gt({start_date:t.startDate,end_date:t.endDate});return ye.get(`metrics/summary${s}`)}async getByModel(t={}){const s=Gt({start_date:t.startDate,end_date:t.endDate});return ye.get(`metrics/by-model${s}`)}async getSessions(t={}){const s=Gt({start_date:t.startDate,end_date:t.endDate,model:t.model,limit:t.limit});return ye.get(`metrics/sessions${s}`)}async getSessionDetail(t){try{return await ye.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=Gt({start_date:t.startDate,end_date:t.endDate,model:t.model});return ye.get(`metrics/usage-breakdown${s}`)}async getDaily(t={}){const s=Gt({days:t.days,end_date:t.endDate,granularity:t.granularity});return ye.get(`metrics/daily${s}`)}async getForwardSummary(t={}){const s=Gt({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return ye.get(`metrics/forward/summary${s}`)}async getForwardByEndpoint(t={}){const s=Gt({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return ye.get(`metrics/forward/by-endpoint${s}`)}async getForwardRequests(t={}){const s=Gt({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return ye.get(`metrics/forward/requests${s}`)}async getMemorySummary(t={}){const s=Gt({scope:t.scope,project_key:t.projectKey});return ye.get(`metrics/memory/summary${s}`)}async getMemoryTimeline(t={}){const s=Gt({scope:t.scope,project_key:t.projectKey,days:t.days,end_date:t.endDate,granularity:t.granularity});return ye.get(`metrics/memory/timeline${s}`)}async getUnifiedSummary(t={}){const s=Gt({start_date:t.startDate,end_date:t.endDate});return ye.get(`metrics/v2/summary${s}`)}async getUnifiedTimeline(t={}){const s=Gt({days:t.days,end_date:t.endDate,granularity:t.granularity});return ye.get(`metrics/v2/timeline${s}`)}}const Ko=new f0,my=1,g0=365,hy=e=>Number.isFinite(e)?Math.min(g0,Math.max(my,Math.floor(e??30))):30,yl=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},Or=e=>e.toISOString().slice(0,10),y0=(e,t)=>{const s=new Date(e.getTime());return s.setUTCDate(s.getUTCDate()+t),s},x0=(e,t)=>{const s=t.getTime()-e.getTime(),n=Math.floor(s/864e5)+1;return hy(n)},Fd=(e,t=new Date)=>{const s=hy(e.days),n=Or(t),o=yl(e.endDate)??yl(n);if(!o)return{startDate:n,endDate:n,days:my};const a=yl(e.startDate);if(a){const l=o<a?a:o;return{startDate:Or(a),endDate:Or(l),days:x0(a,l)}}const i=y0(o,-(s-1));return{startDate:Or(i),endDate:Or(o),days:s}},b0=15e3,v0=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,S0=(e={})=>{const{filters:t,autoRefreshMs:s=b0}=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(()=>Fd({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,f]=m.useState(!1),[g,y]=m.useState(!1),[p,x]=m.useState(null),b=m.useCallback(async w=>{w?f(!0):y(!0);try{const k={startDate:o.startDate,endDate:o.endDate,endpoint:n.endpoint,model:n.model,limit:n.limit},[j,C,P]=await Promise.all([Ko.getForwardSummary(k),Ko.getForwardByEndpoint(k),Ko.getForwardRequests(k)]);i(j),c(C),u(P),x(null)}catch(k){x(v0(k,"Failed to load forward metrics"))}finally{w?f(!1):y(!1)}},[n.endpoint,n.model,n.limit,o.endDate,o.startDate]),S=m.useCallback(async()=>{await b(!1)},[b]);return m.useEffect(()=>{b(!0)},[b]),m.useEffect(()=>{if(s<=0)return;const w=window.setInterval(()=>{b(!1)},s);return()=>{window.clearInterval(w)}},[s,b]),{summary:a,endpointMetrics:l,requests:d,isLoading:h,isRefreshing:g,error:p,refresh:S}},w0=15e3,mm=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,_0=(e={})=>{const{filters:t,autoRefreshMs:s=w0,service:n=Ko}=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(()=>Fd({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([]),[f,g]=m.useState([]),[y,p]=m.useState(null),[x,b]=m.useState([]),[S,w]=m.useState(null),[k,j]=m.useState(!1),[C,P]=m.useState(!1),[v,M]=m.useState(!1),[E,_]=m.useState(null),R=m.useCallback(async I=>{I?P(!0):M(!0);try{const O=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([]),[z,L,Y,F,q,K]=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}),O,A]);l(z),d(L),h(Y),g(F),p(q),b(K),_(null)}catch(O){_(mm(O,"Failed to load metrics"))}finally{I?P(!1):M(!1)}},[o.granularity,o.model,o.sessionLimit,a.days,a.endDate,a.startDate,n]),T=m.useCallback(async()=>{await R(!1)},[R]),D=m.useCallback(async I=>{j(!0);try{const O=await n.getSessionDetail(I);w(O)}catch(O){_(mm(O,"Failed to load session detail"))}finally{j(!1)}},[n]),$=m.useCallback(()=>{w(null)},[]);return m.useEffect(()=>{R(!0)},[R]),m.useEffect(()=>{if(s<=0)return;const I=window.setInterval(()=>{R(!1)},s);return()=>{window.clearInterval(I)}},[s,R]),{summary:i,modelMetrics:c,sessions:u,timeline:f,memorySummary:y,memoryTimeline:x,sessionDetail:S,isLoading:C,isRefreshing:v,isSessionDetailLoading:k,error:E,refresh:T,loadSessionDetail:D,clearSessionDetail:$}},T0=15e3,k0=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,j0=(e={})=>{const{filters:t,autoRefreshMs:s=T0}=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(()=>Fd({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,f]=m.useState(null),g=m.useCallback(async p=>{p?c(!0):u(!0);try{const x=await Ko.getUsageBreakdown({startDate:o.startDate,endDate:o.endDate,model:n.model});i(x),f(null)}catch(x){f(k0(x,"Failed to load usage breakdown"))}finally{p?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 p=window.setInterval(()=>{g(!1)},s);return()=>{window.clearInterval(p)}},[s,g]),{data:a,isLoading:l,isRefreshing:d,error:h,refresh:y}},{useToken:C0}=pe,M0=({data:e,loading:t})=>{const{t:s}=se(),{token:n}=C0();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(td,{data:o,children:[r.jsx(aa,{strokeDasharray:"3 3"}),r.jsx(ia,{dataKey:"endpoint"}),r.jsx(la,{}),r.jsx(Tr,{formatter:(a,i)=>[`${a}`,i.charAt(0).toUpperCase()+i.slice(1)]}),r.jsx(sd,{}),r.jsx(ri,{dataKey:"successful",fill:"var(--lotus-chart-secondary)",name:s("settings.common.successful"),fillOpacity:.9,radius:[4,4,0,0]}),r.jsx(ri,{dataKey:"failed",fill:"var(--lotus-chart-danger)",name:s("settings.common.failed"),fillOpacity:.9,radius:[4,4,0,0]})]})})})})},{useToken:P0}=pe,E0=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`},hm=({summary:e,loading:t})=>{const{t:s}=se(),{token:n}=P0();if(t)return r.jsx(en,{active:!0,paragraph:{rows:1}});const o=e&&e.total_requests>0?(e.successful_requests/e.total_requests*100).toFixed(1):"0.0";return r.jsxs(ss,{gutter:[n.marginSM,n.marginSM],children:[r.jsx(Le,{xs:24,sm:12,xl:6,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(at,{title:s("settings.forwardMetricsCards.totalForwardRequests"),value:(e==null?void 0:e.total_requests)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),r.jsx(Le,{xs:24,sm:12,xl:6,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(at,{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(Le,{xs:24,sm:12,xl:6,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(at,{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(Le,{xs:24,sm:12,xl:6,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(at,{title:s("settings.forwardMetricsCards.avgResponseTime"),value:E0(e==null?void 0:e.avg_duration_ms),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:kn}=ce,R0=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`},A0=e=>new Date(e).toLocaleString(),I0=({requests:e,loading:t})=>{const{t:s}=se(),n=[{title:s("settings.metricsTable.forward.columns.id"),dataIndex:"forward_id",key:"forward_id",width:120,render:o=>r.jsxs(kn,{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(Gc,{status:i,text:a.status_code?r.jsxs("span",{children:[a.status,r.jsxs(kn,{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(kn,{children:a.token_usage.total_tokens.toLocaleString()}):r.jsx(kn,{type:"secondary",children:"-"})},{title:s("settings.metricsTable.forward.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",width:100,render:o=>R0(o)},{title:s("settings.metricsTable.forward.columns.started"),dataIndex:"started_at",key:"started_at",width:160,render:o=>r.jsx(kn,{type:"secondary",style:{fontSize:12},children:A0(o)})},{title:s("settings.metricsTable.forward.columns.error"),dataIndex:"error",key:"error",width:200,render:o=>o?r.jsx(kn,{type:"danger",ellipsis:!0,style:{maxWidth:180},children:o}):r.jsx(kn,{type:"secondary",children:"-"})}];return r.jsx(Js,{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:$0}=pe,D0=e=>{if(!e)return"-";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},pm=({summary:e,loading:t})=>{const{t:s}=se(),{token:n}=$0();return t?r.jsx(en,{active:!0,paragraph:{rows:1}}):r.jsxs(ss,{gutter:[n.marginSM,n.marginSM],children:[r.jsx(Le,{xs:24,sm:12,lg:8,xl:6,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(at,{title:s("settings.unifiedMetricsCards.totalMemories"),value:(e==null?void 0:e.total_memories)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),r.jsx(Le,{xs:24,sm:12,lg:8,xl:6,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(at,{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(Le,{xs:24,sm:12,lg:8,xl:6,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(at,{title:s("settings.unifiedMetricsCards.memoryProjects"),value:(e==null?void 0:e.project_count)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),r.jsx(Le,{xs:24,sm:12,lg:8,xl:6,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(at,{title:s("settings.unifiedMetricsCards.lastReindex"),value:D0(e==null?void 0:e.last_reindex_at),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:F0}=ce,L0=({data:e,loading:t})=>{const{t:s}=se();return t?r.jsx(ee,{size:"small",className:"lotus-metric-card",title:s("settings.charts.memoryTrendTitle"),children:r.jsx(en,{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(Pt,{image:Pt.PRESENTED_IMAGE_SIMPLE,description:s("settings.charts.noMemoryTrend")}):r.jsxs(r.Fragment,{children:[r.jsx(F0,{type:"secondary",children:s("settings.charts.memoryTrendDescription")}),r.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:r.jsx(_r,{children:r.jsxs(of,{data:e,children:[r.jsx(aa,{strokeDasharray:"3 3"}),r.jsx(ia,{dataKey:"label",minTickGap:24}),r.jsx(la,{allowDecimals:!1}),r.jsx(Tr,{}),r.jsx(sd,{}),r.jsx(ur,{type:"monotone",dataKey:"total_memories",name:s("settings.charts.totalMemories"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),r.jsx(ur,{type:"monotone",dataKey:"created_memories",name:s("settings.charts.createdMemories"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),r.jsx(ur,{type:"monotone",dataKey:"updated_memories",name:s("settings.charts.updatedMemories"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{useToken:O0}=pe,z0=e=>{const t=Math.floor(e/1e3),s=Math.floor(t/60),n=t%60;return s>0?`${s}m ${n}s`:`${n}s`},N0=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)},fm=({summary:e,sessions:t,loading:s})=>{const{t:n}=se(),{token:o}=O0();if(s)return r.jsx(en,{active:!0,paragraph:{rows:1}});const a=N0(t);return r.jsxs(ss,{gutter:[o.marginSM,o.marginSM],children:[r.jsx(Le,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(at,{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(Le,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(at,{title:n("settings.metricsCards.totalSessions"),value:(e==null?void 0:e.total_sessions)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),r.jsx(Le,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(at,{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(Le,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(at,{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(Le,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(at,{title:n("settings.metricsCards.avgSessionDuration"),value:a>0?z0(a):"-",valueStyle:{color:"var(--lotus-chart-accent)"}})})})]})},{Text:B0}=ce,gm=["var(--lotus-chart-primary)","var(--lotus-chart-secondary)","var(--lotus-chart-accent)","var(--lotus-chart-purple)","var(--lotus-chart-cyan)"],W0=({data:e,loading:t})=>{const{t:s}=se();if(t)return r.jsx(ee,{size:"small",className:"lotus-metric-card",title:s("settings.charts.modelDistribution"),children:r.jsx(en,{active:!0,paragraph:{rows:5}})});const n=e.map(o=>({name:o.model,value:o.tokens.total_tokens}));return r.jsx(ee,{size:"small",className:"lotus-metric-card",title:s("settings.charts.modelDistribution"),children:n.length===0?r.jsx(Pt,{image:Pt.PRESENTED_IMAGE_SIMPLE,description:s("settings.charts.noModelMetrics")}):r.jsxs(r.Fragment,{children:[r.jsx(B0,{type:"secondary",children:s("settings.charts.modelDistributionDescription")}),r.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:r.jsx(_r,{children:r.jsxs(Cb,{children:[r.jsx(Mb,{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(Pb,{fill:gm[a%gm.length]},`${o.name}-${a}`))}),r.jsx(Tr,{})]})})})]})})},U0=e=>{if(!e)return"-";const t=new Date(e);return Number.isNaN(t.getTime())?"-":t.toLocaleString()},q0=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`},H0=e=>{switch(e){case"completed":return"success";case"running":return"processing";case"error":return"error";case"cancelled":return"warning";default:return"default"}},Y0=({sessions:e,loading:t,onSelectSession:s})=>{const{t:n}=se(),o=[{title:n("settings.metricsTable.session.columns.session"),dataIndex:"session_id",key:"session_id",render:a=>r.jsx(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:H0(a),children:a})},{title:n("settings.metricsTable.session.columns.started"),dataIndex:"started_at",key:"started_at",render:a=>U0(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=>q0(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(U,{type:"link",onClick:()=>{s(i.session_id)},children:n("settings.metricsTable.session.view")})}];return r.jsx(Js,{rowKey:"session_id",size:"small",className:"lotus-metric-table",columns:o,loading:t,dataSource:e,pagination:{pageSize:10,showSizeChanger:!1},scroll:{x:1100}})},{Text:X0}=ce,ym={message_count:"Message Count",last_message_id:"Last Message",pending_question:"Pending Question"},V0=e=>ym[e]?ym[e]:e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" "),K0=({breakdown:e,loading:t})=>{const{t:s}=se();if(t)return r.jsx(ee,{size:"small",className:"lotus-metric-card",title:s("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),children:r.jsx(en,{active:!0,paragraph:{rows:5}})});const n=Object.entries(e??{}).map(([o,a])=>({reason:o,label:s(`settings.syncMismatchReasons.${o}`,{defaultValue:V0(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(X0,{type:"secondary",children:s("settings.metricsDashboard.syncMismatchBreakdownSubtitle",{defaultValue:"Grouped by execute sync mismatch reason"})}),children:n.length===0?r.jsx(Pt,{image:Pt.PRESENTED_IMAGE_SIMPLE,description:s("settings.metricsDashboard.noSyncMismatchBreakdown",{defaultValue:"No sync mismatches recorded for the selected range"})}):r.jsx("div",{style:{width:"100%",minWidth:0,height:280,minHeight:280},children:r.jsx(_r,{children:r.jsxs(td,{data:n,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[r.jsx(aa,{strokeDasharray:"3 3"}),r.jsx(ia,{type:"number",allowDecimals:!1}),r.jsx(la,{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(ri,{dataKey:"count",fill:"var(--lotus-chart-danger)",radius:[0,6,6,0],name:s("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})})]})})})})},{Text:G0}=ce,J0=({data:e,loading:t})=>{const{t:s}=se();return t?r.jsx(ee,{size:"small",className:"lotus-metric-card",title:s("settings.charts.tokenUsageOverTime"),children:r.jsx(en,{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(Pt,{image:Pt.PRESENTED_IMAGE_SIMPLE,description:s("settings.charts.noTokenUsage")}):r.jsxs(r.Fragment,{children:[r.jsx(G0,{type:"secondary",children:s("settings.charts.tokenUsageDescription")}),r.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:r.jsx(_r,{children:r.jsxs(of,{data:e,children:[r.jsx(aa,{strokeDasharray:"3 3"}),r.jsx(ia,{dataKey:"label",minTickGap:24}),r.jsx(la,{allowDecimals:!1}),r.jsx(Tr,{}),r.jsx(sd,{}),r.jsx(ur,{type:"monotone",dataKey:"totalTokens",name:s("settings.charts.total"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),r.jsx(ur,{type:"monotone",dataKey:"promptTokens",name:s("settings.charts.prompt"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),r.jsx(ur,{type:"monotone",dataKey:"completionTokens",name:s("settings.charts.completion"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{Text:Q0}=ce,zr=({title:e,subtitle:t,emptyText:s,color:n="var(--lotus-chart-primary)",data:o,loading:a,countLabel:i})=>{const{t:l}=se();return a?r.jsx(ee,{size:"small",className:"lotus-metric-card",title:e,children:r.jsx(en,{active:!0,paragraph:{rows:5}})}):r.jsx(ee,{size:"small",className:"lotus-metric-card",title:e,children:o.length===0?r.jsx(Pt,{image:Pt.PRESENTED_IMAGE_SIMPLE,description:s}):r.jsxs(r.Fragment,{children:[t?r.jsx(Q0,{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(td,{data:o,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[r.jsx(aa,{strokeDasharray:"3 3"}),r.jsx(ia,{type:"number",allowDecimals:!1}),r.jsx(la,{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,f;const u=(f=(h=d==null?void 0:d[0])==null?void 0:h.payload)==null?void 0:f.meta;return u?`${c} · ${u}`:String(c)}}),r.jsx(ri,{dataKey:"count",fill:n,radius:[0,6,6,0],name:i??l("settings.metricsDashboard.calls",{defaultValue:"Calls"})})]})})})]})})},{useToken:Z0}=pe,xm=({summary:e,loading:t})=>{const{t:s}=se(),{token:n}=Z0();return t?r.jsx(en,{active:!0,paragraph:{rows:1}}):r.jsxs(ss,{gutter:[n.marginSM,n.marginSM],children:[r.jsx(Le,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(at,{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(Le,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(at,{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(Le,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(at,{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(Le,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(at,{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(Le,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(at,{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(Le,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(ee,{size:"small",className:"lotus-metric-card",children:r.jsx(at,{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:tr}=ce,{useToken:eT}=pe,bm=70,vm=130,Sm=2,wm=1.2,_m=.65,Tm=45,km=1.8,jm=e=>"date"in e?e.date:e.label,tT=(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)"},Nr=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`},Cm=e=>{if(!e)return"-";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},xl=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(" • ")},bl=(e,t=320)=>({width:"100%",display:"grid",gridTemplateColumns:`repeat(auto-fit, minmax(${t}px, 1fr))`,gap:e}),sT=()=>{const{t:e}=se(),{token:t}=eT(),s=Hn(B=>B.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,f]=m.useState("daily"),{summary:g,modelMetrics:y,sessions:p,timeline:x,memorySummary:b,memoryTimeline:S,sessionDetail:w,isLoading:k,isRefreshing:j,isSessionDetailLoading:C,error:P,refresh:v,loadSessionDetail:M,clearSessionDetail:E}=_0({filters:{startDate:n,endDate:a,model:l,days:d,granularity:h}}),{summary:_,endpointMetrics:R,requests:T,isLoading:D,isRefreshing:$,error:I,refresh:O}=S0({filters:{startDate:n,endDate:a,days:d,model:l}}),{data:A,isLoading:z,isRefreshing:L,error:Y,refresh:F}=j0({filters:{startDate:n,endDate:a,days:d,model:l}}),q=m.useMemo(()=>x.map(B=>({label:jm(B),promptTokens:B.total_token_usage.prompt_tokens,completionTokens:B.total_token_usage.completion_tokens,totalTokens:B.total_token_usage.total_tokens})),[x]),K=m.useMemo(()=>y.map(B=>({label:B.model,value:B.model})),[y]),G=m.useMemo(()=>{const B=x.map(X=>({label:jm(X),sessions:X.total_sessions,tokens:X.total_token_usage.total_tokens})),Me=B.reduce((X,ue)=>Math.max(X,ue.sessions),0);return{points:B,maxSessions:Me}},[x]),be=m.useMemo(()=>{const B=T.map(X=>X.duration_ms).filter(X=>typeof X=="number"&&X>0).sort((X,ue)=>X-ue);if(B.length===0)return null;const Me=Math.ceil(B.length*.95)-1;return B[Math.max(0,Math.min(Me,B.length-1))]},[T]),Pe=m.useMemo(()=>[{title:e("settings.metricsDashboard.roundColumns.round"),dataIndex:"round_id",key:"round_id",render:B=>`${B.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:B=>Nr(B)},{title:e("settings.metricsDashboard.roundColumns.tokens"),key:"tokens",render:(B,Me)=>Me.token_usage.total_tokens.toLocaleString()},{title:e("settings.metricsDashboard.roundColumns.toolCalls"),key:"tool_calls",render:(B,Me)=>Me.tool_calls.length}],[e]),Ee=m.useMemo(()=>{const B=(g==null?void 0:g.total_sessions)??0,Me=(g==null?void 0:g.total_tokens.total_tokens)??0,X=(g==null?void 0:g.total_tool_calls)??0,ue=(g==null?void 0:g.active_sessions)??0,ie=p.reduce((de,ae)=>de+ae.total_rounds,0),le=(_==null?void 0:_.total_requests)??0,Ae=(_==null?void 0:_.total_tokens.total_tokens)??0,Et=(_==null?void 0:_.failed_requests)??0,Ct=T.filter(de=>de.is_stream).length,it=B>0?ue/B*100:0,bt=le>0?Et/le*100:0,st=T.length>0?Ct/T.length*100:0,vt=Me/bm+X*Sm,Xt=Me/vm+X*wm,Mt=Math.max(0,vt-Xt)*_m,ms=Math.max(Xt,vt-Mt),hs=Nr(Mt*6e4),tn=Number((Mt/(8*60)).toFixed(2)),V=vt>0?Math.min(Tm,Number((Mt/vt*100).toFixed(1))):0,Q=ms>0?Math.min(km,Number((vt/ms).toFixed(2))):1;return[{title:e("settings.metricsDashboard.compactStats.avgTokensPerSession"),value:B>0?Math.round(Me/B):0},{title:e("settings.metricsDashboard.compactStats.estimatedTimeSaved"),value:hs},{title:e("settings.metricsDashboard.compactStats.estimatedEfficiencyLift"),value:V,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.estimatedSpeedMultiplier"),value:Q,suffix:e("settings.metricsDashboard.multiplierSuffix")},{title:e("settings.metricsDashboard.compactStats.estimatedSavedWorkdays"),value:tn},{title:e("settings.metricsDashboard.compactStats.avgRoundsPerSession"),value:B>0?Number((ie/B).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.toolCallsPerSession"),value:B>0?Number((X/B).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.activeSessionRate"),value:Number(it.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.avgTokensPerForward"),value:le>0?Math.round(Ae/le):0},{title:e("settings.metricsDashboard.compactStats.forwardErrorRate"),value:Number(bt.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.streamingRatio"),value:Number(st.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.p95ForwardLatency"),value:Nr(be)},{title:e("settings.metricsDashboard.compactStats.modelCoverage"),value:y.length},{title:e("settings.metricsDashboard.compactStats.endpointCoverage"),value:R.length}]},[R.length,T,_,y.length,be,p,g,e]),Te=m.useMemo(()=>{const B=(_==null?void 0:_.total_requests)??0,Me=(_==null?void 0:_.failed_requests)??0,X=T.filter(le=>le.is_stream).length,ue=T.length>0?X/T.length*100:0,ie=B>0?Me/B*100:0;return[{title:e("settings.metricsDashboard.forward.performance.p95Latency",{defaultValue:"P95 Latency"}),value:Nr(be)},{title:e("settings.metricsDashboard.forward.performance.errorRate",{defaultValue:"Error Rate"}),value:Number(ie.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.streamingRatio",{defaultValue:"Streaming Ratio"}),value:Number(ue.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.endpointCoverage",{defaultValue:"Endpoint Coverage"}),value:R.length}]},[R.length,T,_,be,e]),ge=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(B=>B.count>0):[],[e,A]),je=m.useMemo(()=>((A==null?void 0:A.top_skills)??[]).map(B=>({label:B.skill_id,count:B.count})),[A]),Be=m.useMemo(()=>((A==null?void 0:A.top_mcp_servers)??[]).map(B=>({label:B.server_id,count:B.count,meta:e("settings.metricsDashboard.skillsAndMcp.meta.uniqueTools",{defaultValue:"{{count}} tools",count:B.unique_tools})})),[e,A]),Qe=m.useMemo(()=>((A==null?void 0:A.top_mcp_tools)??[]).map(B=>({label:B.tool_name,count:B.count,meta:B.server_id})),[A]),jt=m.useMemo(()=>((A==null?void 0:A.top_core_tools)??[]).map(B=>({label:B.name,count:B.count})),[A]),Ze=w==null?void 0:w.session,Bt=j||$||L;return r.jsxs(H,{direction:"vertical",size:t.marginMD,style:{width:"100%"},children:[P?r.jsx(Ne,{type:"error",showIcon:!0,message:P}):null,I?r.jsx(Ne,{type:"error",showIcon:!0,message:I}):null,Y?r.jsx(Ne,{type:"error",showIcon:!0,message:Y}):null,r.jsx(ee,{size:"small",title:e("settings.metricsDashboard.filtersTitle"),extra:r.jsx(U,{icon:r.jsx(Fs,{}),loading:Bt,onClick:()=>{v(),O(),F()},children:e("settings.metricsDashboard.refresh")}),children:r.jsxs(H,{wrap:!0,children:[r.jsx(Gd,{placeholder:e("settings.metricsDashboard.startDate"),onChange:B=>{o(B?B.format("YYYY-MM-DD"):void 0)}}),r.jsx(Gd,{placeholder:e("settings.metricsDashboard.endDate"),onChange:B=>{i(B?B.format("YYYY-MM-DD"):void 0)}}),r.jsx(Fe,{allowClear:!0,style:{minWidth:180},placeholder:e("settings.metricsDashboard.model"),value:l,options:K,onChange:B=>{c(B)}}),r.jsx(Fe,{style:{width:120},value:d,options:[7,14,30,90].map(B=>({label:e("settings.metricsDashboard.daysOption",{value:B}),value:B})),onChange:B=>{u(B)}}),r.jsx(Fe,{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:B=>{f(B)}})]})}),r.jsx(ee,{size:"small",title:e("settings.metricsDashboard.dashboardTitle"),children:r.jsx(ei,{size:"small",destroyInactiveTabPane:!0,items:[{key:"overview",label:e("settings.metricsDashboard.tabs.overview"),children:r.jsxs(H,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(fm,{summary:g,sessions:p,loading:k}),r.jsx(hm,{summary:_,loading:D}),r.jsx(xm,{summary:A,loading:z}),r.jsx(pm,{summary:b,loading:k}),r.jsxs(ee,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.derivedMetricsTitle"),extra:r.jsx(tr,{type:"secondary",children:e("settings.metricsDashboard.derivedMetricsSubtitle")}),children:[r.jsx(ss,{gutter:[t.marginSM,t.marginSM],children:Ee.map(B=>r.jsx(Le,{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(at,{title:B.title,value:B.value,suffix:B.suffix,valueStyle:{fontSize:t.fontSizeHeading4}})})},B.title))}),r.jsx(tr,{type:"secondary",style:{display:"block",marginTop:t.marginXS},children:e("settings.metricsDashboard.efficiencyHint",{manualTpm:bm,manualToolMinutes:Sm,assistedTpm:vm,assistedToolMinutes:wm,realization:Math.round(_m*100),maxLift:Tm,maxMultiplier:km})})]})]})},{key:"chat",label:e("settings.metricsDashboard.tabs.chat",{defaultValue:"Chat"}),children:r.jsxs(H,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(fm,{summary:g,sessions:p,loading:k}),r.jsxs("div",{style:bl(t.marginSM,360),children:[r.jsx(J0,{data:q,loading:k}),r.jsx(W0,{data:y,loading:k})]}),r.jsxs("div",{style:bl(t.marginSM,360),children:[r.jsx(K0,{breakdown:g==null?void 0:g.sync_mismatch_breakdown,loading:k}),r.jsx(ee,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.activityHeatmapTitle"),children:G.points.length===0?r.jsx(tr,{type:"secondary",children:e("settings.metricsDashboard.noActivity")}):r.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))",gap:t.marginXS},children:G.points.map(B=>r.jsxs("div",{style:{borderRadius:t.borderRadiusSM,padding:t.paddingXS,background:tT(B.sessions,G.maxSessions),minHeight:64,color:B.sessions>0?"var(--lotus-metric-text-strong)":t.colorTextSecondary},children:[r.jsx("div",{style:{fontSize:12,lineHeight:1.2},children:B.label}),r.jsx("div",{style:{fontWeight:600,marginTop:4},children:e("settings.metricsDashboard.sessionsCount",{count:B.sessions})}),r.jsx("div",{style:{fontSize:12},children:e("settings.metricsDashboard.tokensAmount",{value:B.tokens.toLocaleString()})})]},B.label))})})]})]})},{key:"skills-and-mcp",label:e("settings.metricsDashboard.tabs.skillsAndMcp",{defaultValue:"Skills & MCP"}),children:r.jsxs(H,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(xm,{summary:A,loading:z}),r.jsxs("div",{style:bl(t.marginSM,360),children:[r.jsx(zr,{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:ge,loading:z,color:"var(--lotus-chart-primary)"}),r.jsx(zr,{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:je,loading:z,color:"var(--lotus-chart-purple)"}),r.jsx(zr,{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:Be,loading:z,color:"var(--lotus-chart-cyan)"}),r.jsx(zr,{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:Qe,loading:z,color:"var(--lotus-chart-accent)"}),r.jsx(zr,{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:jt,loading:z,color:"var(--lotus-chart-secondary)"})]})]})},{key:"forward",label:e("settings.metricsDashboard.tabs.forward",{defaultValue:"Forward"}),children:r.jsxs(H,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(hm,{summary:_,loading:D}),r.jsx(ee,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.forward.performanceTitle",{defaultValue:"Forward Performance"}),children:r.jsx(ss,{gutter:[t.marginSM,t.marginSM],children:Te.map(B=>r.jsx(Le,{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(at,{title:B.title,value:B.value,suffix:B.suffix,valueStyle:{fontSize:t.fontSizeHeading4}})})},B.title))})}),r.jsx(M0,{data:R,loading:D})]})},{key:"memory",label:e("settings.metricsDashboard.tabs.memory",{defaultValue:"Memory"}),children:r.jsxs(H,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(pm,{summary:b,loading:k}),r.jsx(L0,{data:S,loading:k}),r.jsx(ee,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.memory.breakdownTitle",{defaultValue:"Memory Breakdown"}),children:r.jsxs(At,{size:"small",bordered:!0,column:1,children:[r.jsx(At.Item,{label:e("settings.metricsDashboard.memory.byType",{defaultValue:"By Type"}),children:xl(b==null?void 0:b.by_type)}),r.jsx(At.Item,{label:e("settings.metricsDashboard.memory.byStatus",{defaultValue:"By Status"}),children:xl(b==null?void 0:b.by_status)}),r.jsx(At.Item,{label:e("settings.metricsDashboard.memory.byScope",{defaultValue:"By Scope"}),children:xl(b==null?void 0:b.by_scope)}),r.jsx(At.Item,{label:e("settings.metricsDashboard.memory.lastDream",{defaultValue:"Last Dream"}),children:Cm(b==null?void 0:b.last_dream_at)}),r.jsx(At.Item,{label:e("settings.metricsDashboard.memory.lastReindex",{defaultValue:"Last Reindex"}),children:Cm(b==null?void 0:b.last_reindex_at)})]})})]})},{key:"records",label:e("settings.metricsDashboard.tabs.records"),children:r.jsx(ei,{size:"small",destroyInactiveTabPane:!0,items:[{key:"sessions",label:e("settings.metricsDashboard.sessionsTabLabel",{count:p.length}),children:r.jsx(ee,{size:"small",extra:r.jsx(tr,{type:"secondary",children:e("settings.metricsDashboard.sessionsHint")}),children:r.jsx(Y0,{sessions:p,loading:k,onSelectSession:B=>{M(B)}})})},{key:"forward-requests",label:e("settings.metricsDashboard.forwardTabLabel",{count:T.length}),children:r.jsx(ee,{size:"small",children:r.jsx(I0,{requests:T,loading:D})})}]})}]})}),r.jsx(Lt,{title:e("settings.metricsDashboard.sessionMetricsTitle"),open:!!w,onCancel:E,onOk:E,width:960,destroyOnClose:!0,children:C?r.jsx(tr,{children:e("settings.metricsDashboard.loadingSessionDetails")}):Ze?r.jsxs(H,{direction:"vertical",style:{width:"100%"},size:t.marginMD,children:[r.jsxs(At,{size:"small",bordered:!0,column:2,children:[r.jsx(At.Item,{label:e("settings.metricsDashboard.sessionDetail.sessionId"),span:2,children:Ze.session_id}),r.jsx(At.Item,{label:e("settings.metricsDashboard.sessionDetail.model"),children:Ze.model}),r.jsx(At.Item,{label:e("settings.metricsDashboard.sessionDetail.status"),children:Ze.status}),r.jsx(At.Item,{label:e("settings.metricsDashboard.sessionDetail.duration"),children:Nr(Ze.duration_ms)}),r.jsx(At.Item,{label:e("settings.metricsDashboard.sessionDetail.messages"),children:Ze.message_count}),r.jsx(At.Item,{label:e("settings.metricsDashboard.sessionDetail.totalTokens"),children:Ze.total_token_usage.total_tokens.toLocaleString()}),r.jsx(At.Item,{label:e("settings.metricsDashboard.sessionDetail.toolCalls"),children:Ze.tool_call_count})]}),r.jsx(Js,{rowKey:"round_id",size:"small",columns:Pe,dataSource:w.rounds,pagination:{pageSize:6,showSizeChanger:!1}})]}):r.jsx(tr,{type:"secondary",children:e("settings.metricsDashboard.noDetail")})})]})},{Text:Ea}=ce,{useToken:nT}=pe,rT=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},aT=()=>{const{t:e}=se(),{token:t}=nT(),[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 p=await Je.getBambooConfig();l(oT(p)),d(rT(p))}catch(p){s.error(p instanceof Error?p.message:e("settings.hooksTab.loadFailed"))}finally{a(!1)}},[s,e]),f=m.useCallback(async(p,x)=>{await Je.setBambooConfig({hooks:{image_fallback:{enabled:p,mode:x}}})},[]),g=m.useCallback(async p=>{a(!0);try{await f(p,c),s.success(e(p?"settings.hooksTab.enabled":"settings.hooksTab.disabled")),await h()}catch(x){s.error(x instanceof Error?x.message:e("settings.hooksTab.updateFailed"))}finally{a(!1)}},[h,c,s,f,e]),y=m.useCallback(async p=>{var x;a(!0);try{await f(i,p),s.success(e("settings.hooksTab.modeUpdated",{mode:((x=u.find(b=>b.value===p))==null?void 0:x.label)??p})),await h()}catch(b){s.error(b instanceof Error?b.message:e("settings.hooksTab.modeUpdateFailed"))}finally{a(!1)}},[i,h,u,s,f,e]);return m.useEffect(()=>{h()},[h]),r.jsxs(J,{vertical:!0,gap:t.marginLG,children:[n,r.jsx(ee,{size:"small",loading:o,children:r.jsxs(J,{vertical:!0,gap:t.marginXS,children:[r.jsx(Ea,{strong:!0,children:e("settings.hooksTab.title")}),r.jsxs(J,{align:"center",justify:"space-between",children:[r.jsx(Ea,{children:e("settings.hooksTab.enableImagePreflight")}),r.jsx(ct,{checked:i,onChange:g})]}),r.jsxs(J,{align:"center",justify:"space-between",children:[r.jsx(Ea,{children:e("settings.hooksTab.modeLabel")}),r.jsx(Fe,{style:{width:180},value:c,options:u,onChange:y,disabled:!i})]}),r.jsx(Ea,{type:"secondary",style:{fontSize:t.fontSizeSM},children:e("settings.hooksTab.description")})]})})]})},{Text:St}=ce,Hs=Ss.getInstance();function iT(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 lT=[{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 gt(e){return String(e??"").trim()||void 0}function cT(e){return(e==null?void 0:e.type)==="interval"?e.every_seconds:null}function py(e){return{type:"interval",every_seconds:e}}function dT(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 mT(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 pT(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 fT(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 gT(e){const t=gt(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 Mm(e){switch(e.trigger_type){case"interval":{const t=Number(e.interval_seconds||0);return t<=0?{errorKey:"settings.schedulesTab.validation.intervalRequired"}:{trigger:py(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}=gT(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=gt(e.cron_expr);return t?{trigger:{type:"cron",expr:t}}:{errorKey:"settings.schedulesTab.validation.cronRequired"}}default:return{errorKey:"settings.schedulesTab.validation.triggerRequired"}}}function Pm(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 yT(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 xT(){const{t:e}=se(),[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,f]=m.useState({open:!1,schedule:null,saving:!1}),g=pn(E=>E.close),[y]=Z.useForm(),[p]=Z.useForm(),x=Z.useWatch("trigger_type",y),b=Z.useWatch("misfire_policy",y),S=Z.useWatch("trigger_type",p),w=Z.useWatch("misfire_policy",p),k=m.useCallback(async()=>{o(!0);try{const E=await Hs.listSchedules();i(E.schedules||[])}catch(E){console.error("[Schedules] Failed to load schedules:",E),t.error(e("settings.schedulesTab.loadFailed"))}finally{o(!1)}},[t,e]);m.useEffect(()=>{k()},[k]);const j=[{value:"interval",label:e("settings.schedulesTab.triggerTypes.interval")},{value:"daily",label:e("settings.schedulesTab.triggerTypes.daily")},{value:"weekly",label:e("settings.schedulesTab.triggerTypes.weekly")},{value:"monthly",label:e("settings.schedulesTab.triggerTypes.monthly")},{value:"cron",label:e("settings.schedulesTab.triggerTypes.cron")}],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")}],P=[{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")}],v=(E,_)=>r.jsxs(r.Fragment,{children:[r.jsxs(J,{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(he,{})}),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(Fe,{options:j})}),r.jsx(Z.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",style:{width:120},children:r.jsx(ct,{})})]}),E==="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(ot,{min:1,style:{width:"100%"}})}):null,E==="daily"?r.jsxs(J,{gap:12,wrap:"wrap",children:[r.jsx(Z.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"daily_hour",style:{width:180},children:r.jsx(ot,{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(ot,{min:0,max:59,style:{width:"100%"}})})]}):null,E==="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(Fe,{mode:"multiple",options:lT})}),r.jsxs(J,{gap:12,wrap:"wrap",children:[r.jsx(Z.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"weekly_hour",style:{width:180},children:r.jsx(ot,{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(ot,{min:0,max:59,style:{width:"100%"}})})]})]}):null,E==="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(he,{placeholder:e("settings.schedulesTab.form.monthlyDaysPlaceholder")})}),r.jsxs(J,{gap:12,wrap:"wrap",children:[r.jsx(Z.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"monthly_hour",style:{width:180},children:r.jsx(ot,{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(ot,{min:0,max:59,style:{width:"100%"}})})]})]}):null,E==="cron"?r.jsx(Z.Item,{label:e("settings.schedulesTab.form.cronExpr"),name:"cron_expr",children:r.jsx(he,{placeholder:e("settings.schedulesTab.form.cronExprPlaceholder")})}):null,r.jsxs(J,{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(he,{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(he,{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(he,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})})]}),r.jsxs(J,{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(Fe,{options:C})}),r.jsx(Z.Item,{label:e("settings.schedulesTab.form.overlapPolicy"),name:"overlap_policy",style:{flex:"1 1 240px"},children:r.jsx(Fe,{options:P})})]}),_==="catch_up_window"?r.jsxs(J,{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(ot,{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(ot,{min:1,style:{width:"100%"}})})]}):null,r.jsx(Z.Item,{label:e("settings.schedulesTab.form.taskMessage"),name:"task_message",children:r.jsx(he.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(he.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})}),r.jsxs(J,{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(he,{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(he,{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(ct,{})})]}),r.jsx(Z.Item,{label:e("settings.schedulesTab.form.enhancePrompt"),name:"enhance_prompt",children:r.jsx(he.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})})]}),M=m.useMemo(()=>[{title:e("settings.schedulesTab.columns.name"),key:"name",render:(E,_)=>r.jsxs(J,{vertical:!0,gap:6,children:[r.jsx(St,{strong:!0,children:_.name}),r.jsxs(J,{gap:6,wrap:"wrap",children:[r.jsx(oe,{children:dT(_.trigger)}),_.timezone?r.jsx(oe,{color:"blue",children:_.timezone}):null,r.jsx(oe,{children:uT(_.misfire_policy)}),r.jsx(oe,{children:mT(_.overlap_policy)})]})]})},{title:e("settings.schedulesTab.columns.status"),key:"status",render:(E,_)=>{const R=fT(_);return r.jsxs(J,{vertical:!0,gap:4,children:[r.jsx(oe,{color:R.color,children:R.label}),R.detail?r.jsx(St,{type:"secondary",children:R.detail}):null]})}},{title:e("settings.schedulesTab.columns.activity"),key:"activity",render:(E,_)=>{var R,T,D,$;return r.jsxs(J,{vertical:!0,gap:2,children:[r.jsxs(St,{type:"secondary",children:["queued: ",((R=_.state)==null?void 0:R.queued_run_count)??0]}),r.jsxs(St,{type:"secondary",children:["running: ",((T=_.state)==null?void 0:T.running_run_count)??0]}),r.jsxs(St,{type:"secondary",children:["ok: ",((D=_.state)==null?void 0:D.total_success_count)??0]}),r.jsxs(St,{type:"secondary",children:["fail: ",(($=_.state)==null?void 0:$.total_failure_count)??0]})]})}},{title:e("settings.schedulesTab.columns.nextRun"),key:"next_run_at",render:(E,_)=>r.jsx(St,{type:"secondary",children:hT(_)})},{title:e("settings.schedulesTab.columns.lastRun"),key:"last_run_at",render:(E,_)=>r.jsx(St,{type:"secondary",children:pT(_)})},{title:e("settings.schedulesTab.columns.autoExecute"),key:"auto_execute",render:(E,_)=>{var R,T;return r.jsx(St,{type:(R=_.run_config)!=null&&R.auto_execute?void 0:"secondary",children:(T=_.run_config)!=null&&T.auto_execute?e("settings.schedulesTab.yes"):e("settings.schedulesTab.no")})}},{title:e("settings.schedulesTab.columns.model"),key:"model",render:(E,_)=>{var R;return r.jsx(St,{type:"secondary",children:(R=_.run_config)!=null&&R.model?String(_.run_config.model):"-"})}},{title:e("settings.schedulesTab.columns.enabled"),key:"enabled",render:(E,_)=>r.jsx(ct,{checked:_.enabled,onChange:async R=>{try{await Hs.patchSchedule(_.id,{enabled:R}),await k()}catch(T){console.error("[Schedules] Failed to toggle:",T),t.error(e("settings.schedulesTab.updateFailed"))}}})},{title:e("settings.schedulesTab.columns.actions"),key:"actions",render:(E,_)=>{const R=r.jsx(ot,{min:1,value:cT(_.trigger)??void 0,disabled:_.trigger.type!=="interval",onChange:async T=>{const D=typeof T=="number"?T:null;if(!(!D||D<=0))try{await Hs.patchSchedule(_.id,{trigger:py(D)}),await k()}catch($){console.error("[Schedules] Failed to patch interval:",$),t.error(e("settings.schedulesTab.updateFailed"))}}});return r.jsxs(J,{vertical:!0,gap:8,children:[r.jsxs(J,{gap:8,wrap:"wrap",children:[r.jsx(U,{size:"small",onClick:()=>{f({open:!0,schedule:_,saving:!1}),p.setFieldsValue(yT(_))},children:e("settings.schedulesTab.actions.edit")}),r.jsx(U,{size:"small",onClick:async()=>{try{await Hs.runScheduleNow(_.id),t.success(e("settings.schedulesTab.enqueuedRun")),await k()}catch(T){console.error("[Schedules] Failed to run now:",T),t.error(e("settings.schedulesTab.runNowFailed"))}},children:e("settings.schedulesTab.actions.runNow")}),r.jsx(U,{size:"small",onClick:async()=>{c(T=>({...T,open:!0,scheduleId:_.id,loading:!0,sessions:[]}));try{const T=await Hs.listScheduleSessions(_.id);c(D=>({...D,open:!0,scheduleId:_.id,loading:!1,sessions:(T.sessions||[]).map($=>({id:$.id,title:$.title,updated_at:$.updated_at}))}))}catch(T){console.error("[Schedules] Failed to list sessions:",T),t.error(e("settings.schedulesTab.loadSessionsFailed")),c(D=>({...D,loading:!1}))}},children:e("settings.schedulesTab.actions.sessions")}),r.jsx(U,{size:"small",onClick:async()=>{u(T=>({...T,open:!0,scheduleId:_.id,loading:!0,runs:[]}));try{const T=await Hs.listScheduleRuns(_.id);u(D=>({...D,open:!0,scheduleId:_.id,loading:!1,runs:T.runs||[]}))}catch(T){console.error("[Schedules] Failed to list runs:",T),t.error(e("settings.schedulesTab.loadRunsFailed")),u(D=>({...D,loading:!1}))}},children:e("settings.schedulesTab.actions.runs")}),r.jsx(U,{danger:!0,size:"small",onClick:async()=>{try{await Hs.deleteSchedule(_.id),t.success(e("settings.schedulesTab.deleted")),await k()}catch(T){console.error("[Schedules] Failed to delete:",T),t.error(e("settings.schedulesTab.deleteFailed"))}},children:e("settings.schedulesTab.actions.delete")})]}),r.jsxs(J,{gap:8,align:"center",wrap:"wrap",children:[r.jsx(St,{type:"secondary",children:e("settings.schedulesTab.columns.intervalSeconds")}),_.trigger.type==="interval"?R:r.jsx(ke,{title:e("settings.schedulesTab.nonIntervalReadOnly"),children:r.jsx("span",{children:R})})]})]})}}],[p,t,k,e]);return r.jsxs(J,{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 E=>{try{const _=!!E.auto_execute,R=gt(E.task_message),T=gt(E.model);if(_&&!R){t.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:D,errorKey:$}=Mm(E);if(!D){t.error(e($||"settings.schedulesTab.validation.triggerRequired"));return}await Hs.createSchedule({name:String(E.name||"").trim(),trigger:D,timezone:gt(E.timezone),start_at:gt(E.start_at),end_at:gt(E.end_at),misfire_policy:Pm(E),overlap_policy:E.overlap_policy,enabled:!!E.enabled,run_config:{system_prompt:gt(E.system_prompt),task_message:R,model:T,workspace_path:gt(E.workspace_path),enhance_prompt:gt(E.enhance_prompt),auto_execute:_}}),t.success(e("settings.schedulesTab.created")),y.resetFields(),await k()}catch(_){console.error("[Schedules] Failed to create schedule:",_),t.error(e("settings.schedulesTab.createFailed"))}},children:[v(x,b),r.jsx(U,{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(U,{onClick:()=>void k(),loading:n,children:e("settings.schedulesTab.actions.refresh")}),children:r.jsx(Js,{rowKey:"id",columns:M,dataSource:a,loading:n,pagination:{pageSize:10},scroll:{x:1500}})}),r.jsx(Lt,{title:e("settings.schedulesTab.scheduleSessionsTitle"),open:l.open,onCancel:()=>c(E=>({...E,open:!1,scheduleId:null})),footer:null,children:l.loading?r.jsx(St,{type:"secondary",children:e("settings.schedulesTab.loading")}):r.jsx(J,{vertical:!0,gap:8,children:l.sessions.length===0?r.jsx(St,{type:"secondary",children:e("settings.schedulesTab.noSessionsYet")}):l.sessions.map(E=>r.jsxs(J,{justify:"space-between",align:"center",children:[r.jsxs(J,{vertical:!0,style:{minWidth:0},children:[r.jsx(St,{strong:!0,ellipsis:!0,children:E.title}),r.jsxs(St,{type:"secondary",ellipsis:!0,children:[E.id," • ",E.updated_at]})]}),r.jsx(U,{size:"small",onClick:()=>{Ni(E.id,{forceRefreshIndex:!0,forceLoadHistory:!0,subscribeIfRunning:!0,forceSubscribe:!0}),g()},children:e("settings.schedulesTab.actions.open")})]},E.id))})}),r.jsx(Lt,{title:e("settings.schedulesTab.scheduleRunsTitle"),open:d.open,onCancel:()=>u(E=>({...E,open:!1,scheduleId:null})),footer:null,width:960,children:d.loading?r.jsx(St,{type:"secondary",children:e("settings.schedulesTab.loading")}):d.runs.length===0?r.jsx(St,{type:"secondary",children:e("settings.schedulesTab.noRunsYet")}):r.jsx(Js,{rowKey:"run_id",pagination:{pageSize:8},dataSource:d.runs,columns:[{title:e("settings.schedulesTab.runHistory.columns.status"),key:"status",render:(E,_)=>r.jsx(oe,{color:iT(_.status),children:_.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:(E,_)=>_.started_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.completedAt"),key:"completed_at",render:(E,_)=>_.completed_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.session"),key:"session_id",render:(E,_)=>_.session_id||"-"},{title:e("settings.schedulesTab.runHistory.columns.duration"),key:"execution_duration_ms",render:(E,_)=>_.execution_duration_ms!=null?`${_.execution_duration_ms}ms`:"-"},{title:e("settings.schedulesTab.runHistory.columns.outcome"),key:"outcome_reason",render:(E,_)=>_.outcome_reason||(_.was_catch_up?"catch-up":"-")}]})}),r.jsx(Lt,{title:e("settings.schedulesTab.editTitle"),open:h.open,onCancel:()=>f({open:!1,schedule:null,saving:!1}),okText:e("settings.schedulesTab.actions.save"),confirmLoading:h.saving,onOk:()=>p.submit(),children:r.jsx(Z,{form:p,layout:"vertical",onFinish:async E=>{const _=h.schedule;if(!_)return;const R=!!E.auto_execute,T=gt(E.task_message),D=gt(E.model);if(R&&!T){t.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:$,errorKey:I}=Mm(E);if(!$){t.error(e(I||"settings.schedulesTab.validation.triggerRequired"));return}f(O=>({...O,saving:!0}));try{await Hs.patchSchedule(_.id,{name:String(E.name||"").trim()||void 0,enabled:!!E.enabled,trigger:$,timezone:gt(E.timezone),start_at:gt(E.start_at),end_at:gt(E.end_at),misfire_policy:Pm(E),overlap_policy:E.overlap_policy,run_config:{system_prompt:gt(E.system_prompt),task_message:T,model:D,workspace_path:gt(E.workspace_path),enhance_prompt:gt(E.enhance_prompt),auto_execute:R}}),t.success(e("settings.schedulesTab.updated")),f({open:!1,schedule:null,saving:!1}),await k()}catch(O){console.error("[Schedules] Failed to patch schedule:",O),t.error(e("settings.schedulesTab.updateFailed")),f(A=>({...A,saving:!1}))}},children:v(S,w)})})]})}const{Text:Br}=ce,Wr=Ss.getInstance();function bT(){const{t:e}=se(),{modal:t,message:s}=us.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),f=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(J,{vertical:!0,gap:16,children:[r.jsx(ee,{size:"small",title:e("settings.sessionsTab.currentSessionTitle"),children:f?r.jsxs(J,{vertical:!0,gap:4,children:[r.jsx(Br,{strong:!0,ellipsis:!0,children:f.title}),r.jsxs(Br,{type:"secondary",ellipsis:!0,children:[e("settings.sessionsTab.id"),": ",f.id," ","•"," ",e("settings.sessionsTab.kind"),": ",f.kind]}),r.jsx(J,{gap:8,wrap:"wrap",style:{marginTop:8},children:r.jsx(U,{danger:!0,loading:u,onClick:()=>{t.confirm({title:e("settings.sessionsTab.clearMessagesTitle"),content:e("settings.sessionsTab.clearMessagesContent"),okText:e("settings.sessionsTab.clear"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await g(async()=>{await Wr.clearSession(f.id),await l(f.id),await a(),s.success(e("settings.sessionsTab.sessionCleared"))})}})},children:e("settings.sessionsTab.clearMessages")})})]}):r.jsx(Br,{type:"secondary",children:e("settings.sessionsTab.noActiveSession")})}),r.jsxs(ee,{size:"small",title:e("settings.sessionsTab.bulkCleanupTitle"),children:[r.jsxs(J,{align:"center",gap:8,style:{marginBottom:12},children:[r.jsx(Br,{children:e("settings.sessionsTab.keepPinned")}),r.jsx(ct,{checked:c,onChange:d})]}),r.jsxs(J,{gap:8,wrap:"wrap",children:[r.jsx(U,{danger:!0,loading:u,onClick:()=>{t.confirm({title:e("settings.sessionsTab.deleteAllTitle"),content:e(c?"settings.sessionsTab.deleteAllKeepPinned":"settings.sessionsTab.deleteAllIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await g(async()=>{await Wr.cleanupSessions("all",c),await i(),s.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteAll")}),r.jsx(U,{danger:!0,loading:u,onClick:()=>{t.confirm({title:e("settings.sessionsTab.deleteEmptyTitle"),content:e(c?"settings.sessionsTab.deleteEmptyKeepPinned":"settings.sessionsTab.deleteEmptyIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await g(async()=>{await Wr.cleanupSessions("empty",c),await i(),s.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteEmpty")}),r.jsx(U,{danger:!0,loading:u,onClick:()=>{t.confirm({title:e("settings.sessionsTab.deleteChildrenTitle"),content:e(c?"settings.sessionsTab.deleteChildrenKeepPinned":"settings.sessionsTab.deleteChildrenIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await g(async()=>{await Wr.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(Br,{type:"secondary",children:e("settings.sessionsTab.devResetDescription")}),r.jsx(J,{style:{marginTop:12},children:r.jsx(U,{danger:!0,type:"primary",loading:u,onClick:()=>{t.confirm({title:e("settings.sessionsTab.devResetConfirmTitle"),content:e("settings.sessionsTab.devResetConfirmContent"),okText:e("settings.sessionsTab.reset"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await g(async()=>{await Wr.devResetSessions(),await i(),s.success(e("settings.sessionsTab.devResetDone"))})}})},children:e("settings.sessionsTab.devResetAction")})})]})]})}const{Text:Ra,Paragraph:vT}=ce,ST=({open:e,onCancel:t,onComplete:s,onCopyCode:n,completingAuth:o,copiedUserCode:a,deviceCodeInfo:i,timeRemaining:l,token:c})=>{const{t:d}=se();return r.jsx(Lt,{title:d("settings.providerTab.copilotAuthModalTitle"),open:e,onCancel:t,footer:[r.jsx(U,{onClick:t,children:d("settings.providerTab.cancel")},"cancel"),r.jsx(U,{type:"primary",onClick:s,loading:o,children:d("settings.providerTab.completedAuthorization")},"complete")],children:i&&r.jsxs(H,{direction:"vertical",size:"large",style:{width:"100%"},children:[r.jsx(Ne,{message:d("settings.providerTab.browserOpened"),description:r.jsxs("ol",{children:[r.jsx("li",{children:d("settings.providerTab.authStep1")}),r.jsx("li",{children:d("settings.providerTab.authStep2")}),r.jsx("li",{children:d("settings.providerTab.authStep3")})]}),type:"info"}),r.jsx(ee,{size:"small",className:"lotus-settings-card",children:r.jsxs(H,{direction:"vertical",style:{width:"100%"},children:[r.jsx(Ra,{type:"secondary",children:d("settings.providerTab.visitUrl")}),r.jsx(H,{children:r.jsx(Ra,{copyable:{text:i.verification_uri},children:i.verification_uri})})]})}),r.jsx(ee,{style:{textAlign:"center",background:c.colorFillTertiary,borderColor:c.colorBorderSecondary},children:r.jsxs(H,{direction:"vertical",style:{width:"100%"},children:[r.jsx(Ra,{type:"secondary",children:d("settings.providerTab.enterCode")}),r.jsxs(H,{children:[r.jsx(Ra,{style:{color:c.colorText,fontSize:"32px",fontFamily:"monospace",fontWeight:"bold",letterSpacing:"4px"},children:i.user_code}),r.jsx(U,{icon:a?r.jsx(Qs,{}):r.jsx(ls,{}),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(Zs,{style:{marginRight:4}}),"Expires in ",Math.floor(l/60),":",(l%60).toString().padStart(2,"0")]})})]})}),r.jsx(vT,{type:"secondary",children:d("settings.providerTab.afterContinueHint")})]})})},vl={copilot:"GitHub Copilot",openai:"OpenAI",anthropic:"Anthropic",gemini:"Google Gemini"},Ac=[{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"}],Ic=[{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"}],$c=[{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"}],fy=[{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4o-mini",label:"GPT-4o Mini"}],{Option:jn}=Fe,{Password:Em}=he,{Text:ts,Paragraph:Sl}=ce,Rm=e=>r.jsxs(H,{direction:"vertical",size:4,children:[r.jsxs(ts,{type:"secondary",children:[e("settings.providerTab.responsesOnlyHelp1")," ",r.jsx(ts,{code:!0,children:"/responses"}),"."]}),r.jsx(ts,{type:"secondary",children:e("settings.providerTab.responsesOnlyHelp2")})]}),Am=["openai","anthropic","gemini","copilot"],wT=e=>e.map(t=>({value:t,label:t})),_T=()=>{const{t:e}=se(),{token:t}=pe.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,f]=m.useState(null),[g,y]=m.useState(!1),[p,x]=m.useState(!1),[b,S]=m.useState(null),[w,k]=m.useState(!1),[j,C]=m.useState(!1),[P,v]=m.useState(0),[M,E]=m.useState(!1),[_,R]=m.useState(!1),[T,D]=m.useState([]),[$,I]=m.useState(null),[O,A]=m.useState(!1),[z,L]=m.useState([]),[Y,F]=m.useState("idle"),[q,K]=m.useState(null);m.useEffect(()=>{if(Y!=="success")return;const V=setTimeout(()=>{F("idle"),K(null)},2e3);return()=>clearTimeout(V)},[Y]);const G=Z.useWatch(["providers","openai","api_key"],s),be=Z.useWatch(["providers","openai","base_url"],s),Pe=Z.useWatch(["providers","anthropic","api_key"],s),Ee=Z.useWatch(["providers","anthropic","base_url"],s),Te=Z.useWatch(["providers","gemini","api_key"],s),ge=Z.useWatch(["providers","gemini","base_url"],s);m.useEffect(()=>{l==="openai"&&(D([]),I(null),A(!1))},[l,G,be]),m.useEffect(()=>{l==="anthropic"&&(D([]),I(null),A(!1))},[l,Pe,Ee]),m.useEffect(()=>{l==="gemini"&&(D([]),I(null),A(!1))},[l,Te,ge]),m.useEffect(()=>{if(!w||!b){v(0);return}v(b.expires_in);const V=setInterval(()=>{v(Q=>Q<=1?(clearInterval(V),0):Q-1)},1e3);return()=>clearInterval(V)},[w,b]);const je=m.useCallback(async()=>{try{o(!0);const V=await $t.getProviderConfig(),Q={provider:V.provider,providers:V.providers||{}};if(Q.provider==="copilot"){const ae=Q.providers.copilot??{};ae.model||(Q.providers.copilot={...ae,model:"gpt-4o"})}Ke("[Provider]","Loaded provider config:",Q);const de={...Q.providers||{}};Am.forEach(ae=>{const Re=de[ae];Re&&Re.request_overrides&&typeof Re.request_overrides=="object"&&(Re.request_overrides_json=JSON.stringify(Re.request_overrides,null,2))}),c(Q.provider),s.setFieldsValue({...Q,providers:de}),u(!0)}catch(V){fe.error(e("settings.providerTab.loadConfigFailed")),console.error("Failed to load provider config:",V)}finally{o(!1)}},[s,e]),Be=m.useCallback(async()=>{try{const V=await $t.getEnvVars();L(V.entries||[])}catch(V){console.warn("Failed to load env vars for provider overrides:",V)}},[]),Qe=m.useCallback(async()=>{try{y(!0);const V=await $t.getCopilotAuthStatus();f(V)}catch(V){console.error("Failed to check Copilot auth status:",V),f({authenticated:!1,message:e("settings.providerTab.checkStatusFailed")})}finally{y(!1)}},[e]);m.useEffect(()=>{je(),Be()},[je,Be]),m.useEffect(()=>{l==="copilot"&&Qe()},[l,Qe]);const jt=async()=>{try{x(!0);const V=await $t.startCopilotAuth();S(V),k(!0)}catch(V){fe.error(e("settings.providerTab.startCopilotAuthFailed")),console.error("Failed to start Copilot authentication:",V)}finally{x(!1)}},Ze=async()=>{if(b)try{C(!0),await $t.completeCopilotAuth({device_code:b.device_code,interval:b.interval||5,expires_in:b.expires_in}),fe.success(e("settings.providerTab.copilotAuthSuccess")),k(!1),S(null),await Qe()}catch(V){fe.error(e("settings.providerTab.completeAuthFailed")),console.error("Authentication completion failed:",V)}finally{C(!1)}},Bt=async()=>{if(b)try{await ds(b.user_code),E(!0),fe.success(e("settings.providerTab.userCodeCopied")),setTimeout(()=>E(!1),2e3)}catch{fe.error(`${e("settings.providerTab.copyCodeFailedPrefix")} ${b.user_code}`)}},B=async()=>{try{x(!0),await $t.logoutCopilot(),fe.success(e("settings.providerTab.logoutSuccess")),await Qe()}catch(V){fe.error(e("settings.providerTab.logoutFailed")),console.error("Failed to logout:",V)}finally{x(!1)}},Me=V=>{c(V),s.setFieldsValue({provider:V}),D([]),I(null),A(!1),F("idle"),K(null)},X=V=>Kb(V)||V instanceof Error?V.message:e("settings.providerTab.unknownError"),ue=V=>{s.setFields([{name:["provider"],errors:[]},{name:["providers",V,"api_key"],errors:[]},{name:["providers",V,"model"],errors:[]}])},ie=V=>{const Q=V.trim();return Q?Q.includes(".")?Q.split(".").filter(Boolean):Q==="provider"?["provider"]:Q==="provider/providers"?["provider"]:null:null},le=(V,Q)=>{if(!V.length)return;const de=V.map(ae=>{const Re=ie(ae.path);return Re?{name:Re,errors:[ae.message]}:ae.message.toLowerCase().includes("api key")?{name:["providers",Q,"api_key"],errors:[ae.message]}:{name:["provider"],errors:[ae.message]}}).filter((ae,Re,Xe)=>Xe.findIndex(rt=>JSON.stringify(rt.name)===JSON.stringify(ae.name))===Re);de.length&&s.setFields(de)},Ae=async V=>{var de;const Q=V.provider||l;ue(Q);try{const Re=await Nt.getInstance().validateBambooConfigPatch({provider:V.provider,providers:V.providers||{}});if(Re.valid)return{valid:!0};const Xe=((de=Re.errors)==null?void 0:de.provider)||[];le(Xe,Q);const rt=Xe[0];return{valid:!1,message:(rt==null?void 0:rt.message)||e("settings.providerTab.invalidConfig")}}catch(ae){return console.warn("Config validation failed, falling back to save:",ae),{valid:!0}}},Et=async(V,Q)=>{const de={openai:e("settings.providerTab.providerNames.openai"),anthropic:e("settings.providerTab.providerNames.anthropic"),gemini:e("settings.providerTab.providerNames.gemini"),copilot:e("settings.providerTab.providerNames.copilot")},ae=e(V==="copilot"?"settings.providerTab.fetchModelsCopilotFailed":"settings.providerTab.fetchModelsFailed");if(!(!(Q!=null&&Q.force)&&T.length>0))try{R(!0),I(null),A(!0);const Re=V==="copilot"?await Ri.getModels():await $t.fetchProviderModels(V),Xe=wT(Re);if(D(Xe),V==="copilot"&&Xe.length===0){const rt=e("settings.providerTab.noModelsReturned");I(rt),(Q==null?void 0:Q.showMessage)!==!1&&fe.warning(rt);return}(Q==null?void 0:Q.showMessage)!==!1&&fe.success(e("settings.providerTab.foundModels",{count:Xe.length}))}catch(Re){const Xe=X(Re);I(Xe),(Q==null?void 0:Q.showMessage)!==!1&&fe.error(Xe?`${e("settings.providerTab.fetchModelsErrorPrefix")}: ${Xe}`:ae),console.error(`Failed to fetch ${de[V]} models:`,Re)}finally{R(!1)}},Ct=async(V,Q)=>{try{o(!0);const de={provider:V.provider,providers:{...V.providers||{}}},ae=de.providers;for(const rt of Am){const ps=ae[rt];if(!ps)continue;const ne=ps.request_overrides_json;if(typeof ne!="string")continue;const Ce=ne.trim();if(!Ce)delete ps.request_overrides;else try{ps.request_overrides=JSON.parse(Ce)}catch(De){const He=`Invalid request_overrides JSON for ${rt}: ${De.message}`;if(s.setFields([{name:["providers",rt,"request_overrides_json"],errors:[He]}]),(Q==null?void 0:Q.showMessage)!==!1&&fe.error(He),Q!=null&&Q.throwOnError)throw De;return}delete ps.request_overrides_json}const Re={provider:de.provider,providers:de.providers||{}},Xe=await Ae(de);if(!Xe.valid){const rt=Xe.message||e("settings.providerTab.invalidConfig");if((Q==null?void 0:Q.showMessage)!==!1&&fe.error(`${e("settings.providerTab.invalidConfigPrefix")}: ${rt}`),Q!=null&&Q.throwOnError)throw new Error(rt);return}Ke("[Provider]","Saving provider config:",Re),await $t.saveProviderConfig(Re),(Q==null?void 0:Q.showMessage)!==!1&&fe.success(e("settings.providerTab.saveConfigSuccess"))}catch(de){const ae=X(de);if((Q==null?void 0:Q.showMessage)!==!1&&fe.error(ae?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${ae}`:e("settings.providerTab.saveConfigFailed")),console.error("Failed to save configuration:",de),Q!=null&&Q.throwOnError)throw de}finally{o(!1)}},it=async V=>{try{i(!0);const{useProviderStore:Q}=await Ft(async()=>{const{useProviderStore:de}=await Promise.resolve().then(()=>Zb);return{useProviderStore:de}},void 0,import.meta.url);await Q.getState().loadProviderConfig(),(V==null?void 0:V.showMessage)!==!1&&fe.success(e("settings.providerTab.applyConfigSuccess"))}catch(Q){const de=X(Q);if((V==null?void 0:V.showMessage)!==!1&&fe.error(de?`${e("settings.providerTab.applyConfigErrorPrefix")}: ${de}`:e("settings.providerTab.applyConfigFailed")),console.error("Failed to apply configuration:",Q),V!=null&&V.throwOnError)throw Q}finally{i(!1)}},bt=async V=>{try{await Ct(V,{throwOnError:!0}),await it({throwOnError:!0})}catch{}},st=async(V,Q)=>{if(!(!(Q!=null&&Q.force)&&T.length>0)){try{const de=s.getFieldsValue(!0);await Ct(de,{showMessage:!1,throwOnError:!0})}catch(de){const ae=X(de);I(ae),A(!0),fe.error(ae?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${ae}`:e("settings.providerTab.saveConfigFailed"));return}await Et(V,{force:Q==null?void 0:Q.force})}},vt=async(V,Q)=>{Q&&(_||T.length>0||O&&$||await st(V))},Xt=async(V,Q)=>{if(Q&&Y!=="saving"){F("saving"),K(null);try{const de=s.getFieldsValue(!0),ae=de.providers||{},Re=ae;Re[V]={...Re[V]??{},model:Q},de.providers=ae,await Ct(de,{showMessage:!1,throwOnError:!0}),await it({showMessage:!1,throwOnError:!0}),F("success"),fe.success(e("settings.providerTab.modelUpdated"))}catch(de){const ae=X(de);F("error"),K(ae),fe.error(ae?`${e("settings.providerTab.updateModelErrorPrefix")}: ${ae}`:e("settings.providerTab.updateModelFailed"))}}},Ls=async(V,Q,de)=>{if(Y!=="saving"){F("saving"),K(null);try{const ae=s.getFieldsValue(!0),Re=ae.providers||{},Xe=Re;Xe[V]={...Xe[V]??{},[Q]:de||void 0},ae.providers=Re,await Ct(ae,{showMessage:!1,throwOnError:!0}),await it({showMessage:!1,throwOnError:!0}),F("success"),fe.success(e("settings.providerTab.modelUpdated"))}catch(ae){const Re=X(ae);F("error"),K(Re),fe.error(Re?`${e("settings.providerTab.updateModelErrorPrefix")}: ${Re}`:e("settings.providerTab.updateModelFailed"))}}},Mt=(V,Q)=>{const de=T.length>0?T:Q;return r.jsxs(r.Fragment,{children:[r.jsx(Z.Item,{name:["providers",V,"fast_model"],label:e("settings.providerTab.fastModel"),extra:r.jsx(ts,{type:"secondary",children:e("settings.providerTab.fastModelHelp")}),children:r.jsx(Fe,{placeholder:e("settings.providerTab.sameAsDefault"),allowClear:!0,showSearch:!0,loading:_,disabled:Y==="saving",notFoundContent:_?r.jsx(ht,{size:"small"}):null,onDropdownVisibleChange:ae=>vt(V,ae),onChange:ae=>Ls(V,"fast_model",ae),children:de.map(ae=>r.jsx(jn,{value:ae.value,children:ae.label},ae.value))})}),r.jsx(Z.Item,{name:["providers",V,"vision_model"],label:e("settings.providerTab.visionModel"),extra:r.jsx(ts,{type:"secondary",children:e("settings.providerTab.visionModelHelp")}),children:r.jsx(Fe,{placeholder:e("settings.providerTab.sameAsDefault"),allowClear:!0,showSearch:!0,loading:_,disabled:Y==="saving",notFoundContent:_?r.jsx(ht,{size:"small"}):null,onDropdownVisibleChange:ae=>vt(V,ae),onChange:ae=>Ls(V,"vision_model",ae),children:de.map(ae=>r.jsx(jn,{value:ae.value,children:ae.label},ae.value))})})]})},ms=(V,Q)=>r.jsxs(H,{direction:"vertical",size:4,children:[r.jsxs(H,{size:"small",children:[r.jsx(U,{type:"link",size:"small",onClick:()=>st(V,{force:!0}),loading:_,style:{padding:0},children:_?e("settings.providerTab.fetchingModels"):T.length>0?e("settings.providerTab.refreshModelsFrom",{source:Q}):e("settings.providerTab.fetchModelsFrom",{source:Q})}),Y==="saving"&&r.jsx(ht,{size:"small"}),Y==="success"&&r.jsx(Qs,{style:{color:"var(--lotus-chart-secondary)"}}),Y==="error"&&r.jsx(ke,{title:q||e("settings.providerTab.saveModelChangeFailed"),children:r.jsx(Zl,{style:{color:"var(--lotus-chart-danger)"}})})]}),$&&r.jsxs(H,{size:"small",children:[r.jsx(ke,{title:$,children:r.jsx(ts,{type:"danger",children:e("settings.providerTab.fetchModelsFailedShort")})}),r.jsx(U,{size:"small",onClick:()=>st(V,{force:!0}),loading:_,children:e("settings.providerTab.retry")})]})]}),hs=V=>{const Q=z.map(ae=>ae.name);return r.jsx(Z.Item,{name:["providers",V,"request_overrides_json"],label:"Advanced Request Overrides (JSON)",extra:r.jsxs(H,{direction:"vertical",size:4,children:[r.jsx(ts,{type:"secondary",children:"Customize provider request headers/body patch rules. Supports endpoint scoping and model-based rules."}),r.jsxs(ts,{type:"secondary",children:["Env var injection:"," ",r.jsx(ts,{code:!0,children:'{ "type": "env_ref", "name": "YOUR_ENV_NAME" }'})]}),Q.length>0&&r.jsx(H,{wrap:!0,size:[6,6],children:Q.map(ae=>r.jsx(oe,{children:ae},ae))})]}),children:r.jsx(he.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"}})})},tn=()=>{switch(l){case"openai":return r.jsxs(r.Fragment,{children:[r.jsx(Ne,{message:e("settings.providerTab.openaiConfigTitle"),description:e("settings.providerTab.openaiConfigDescription"),type:"info",showIcon:!0,style:{marginBottom:16}}),r.jsx(Z.Item,{name:["providers","openai","api_key"],label:e("settings.providerTab.openaiApiKey"),rules:[{required:!0,message:e("settings.providerTab.openaiApiKeyRequired")}],children:r.jsx(he.Password,{"data-testid":"api-key-input",placeholder:"sk-...",prefix:r.jsx(Yi,{})})}),r.jsx(Z.Item,{name:["providers","openai","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.openaiBaseUrlHelp"),children:r.jsx(he,{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")}],extra:ms("openai","API"),children:r.jsx(Fe,{placeholder:e("settings.providerTab.selectModel"),allowClear:!0,showSearch:!0,loading:_,disabled:Y==="saving",notFoundContent:_?r.jsx(ht,{size:"small"}):null,onDropdownVisibleChange:V=>vt("openai",V),onChange:V=>Xt("openai",V),children:(T.length>0?T:Ac).map(V=>r.jsx(jn,{value:V.value,children:V.label},V.value))})}),r.jsx(Z.Item,{name:["providers","openai","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:Rm(e),children:r.jsx(Fe,{mode:"tags",placeholder:'e.g. "gpt-5.3-codex", "gpt-5*"',tokenSeparators:[","," ",`
|
|
149
|
+
`," "]})}),r.jsx(Dt,{dashed:!0}),Mt("openai",Ac),hs("openai")]});case"anthropic":return r.jsxs(r.Fragment,{children:[r.jsx(Ne,{message:e("settings.providerTab.anthropicConfigTitle"),description:e("settings.providerTab.anthropicConfigDescription"),type:"info",showIcon:!0,style:{marginBottom:16}}),r.jsx(Z.Item,{name:["providers","anthropic","api_key"],label:e("settings.providerTab.anthropicApiKey"),rules:[{required:!0,message:e("settings.providerTab.anthropicApiKeyRequired")}],children:r.jsx(Em,{placeholder:"sk-ant-...",prefix:r.jsx(Yi,{})})}),r.jsx(Z.Item,{name:["providers","anthropic","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.anthropicBaseUrlHelp"),children:r.jsx(he,{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")}],extra:ms("anthropic","API"),children:r.jsx(Fe,{placeholder:e("settings.providerTab.selectModel"),allowClear:!0,showSearch:!0,loading:_,disabled:Y==="saving",notFoundContent:_?r.jsx(ht,{size:"small"}):null,onDropdownVisibleChange:V=>vt("anthropic",V),onChange:V=>Xt("anthropic",V),children:(T.length>0?T:Ic).map(V=>r.jsx(jn,{value:V.value,children:V.label},V.value))})}),r.jsx(Z.Item,{name:["providers","anthropic","max_tokens"],label:e("settings.providerTab.maxTokensOptional"),extra:e("settings.providerTab.maxTokensHelp"),children:r.jsx(he,{type:"number",placeholder:"4096",min:1,max:1e5})}),r.jsx(Dt,{dashed:!0}),Mt("anthropic",Ic),hs("anthropic")]});case"gemini":return r.jsxs(r.Fragment,{children:[r.jsx(Ne,{message:e("settings.providerTab.geminiConfigTitle"),description:e("settings.providerTab.geminiConfigDescription"),type:"info",showIcon:!0,style:{marginBottom:16}}),r.jsx(Z.Item,{name:["providers","gemini","api_key"],label:e("settings.providerTab.geminiApiKey"),rules:[{required:!0,message:e("settings.providerTab.geminiApiKeyRequired")}],children:r.jsx(Em,{placeholder:"AIza...",prefix:r.jsx(Yi,{})})}),r.jsx(Z.Item,{name:["providers","gemini","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.geminiBaseUrlHelp"),children:r.jsx(he,{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")}],extra:ms("gemini","API"),children:r.jsx(Fe,{placeholder:e("settings.providerTab.selectModel"),allowClear:!0,showSearch:!0,loading:_,disabled:Y==="saving",notFoundContent:_?r.jsx(ht,{size:"small"}):null,onDropdownVisibleChange:V=>vt("gemini",V),onChange:V=>Xt("gemini",V),children:(T.length>0?T:$c).map(V=>r.jsx(jn,{value:V.value,children:V.label},V.value))})}),r.jsx(Dt,{dashed:!0}),Mt("gemini",$c),hs("gemini")]});case"copilot":{const V=s.getFieldValue(["providers","copilot","model"]),Q=T.length>0?T:V?[{value:V,label:V}]:[];return r.jsxs(r.Fragment,{children:[r.jsx(Ne,{message:e("settings.providerTab.copilotConfigTitle"),description:e("settings.providerTab.copilotConfigDescription"),type:"info",showIcon:!0}),r.jsxs(ee,{size:"small",style:{marginTop:16,marginBottom:16},title:e("settings.providerTab.authStatusTitle"),extra:g?r.jsx(ht,{size:"small"}):h!=null&&h.authenticated?r.jsx(oe,{icon:r.jsx(Qs,{}),color:"success",children:e("settings.providerTab.authenticated")}):r.jsx(oe,{icon:r.jsx(Zl,{}),color:"error",children:e("settings.providerTab.notAuthenticated")}),children:[(h==null?void 0:h.message)&&r.jsx(Sl,{type:"secondary",style:{marginBottom:16},children:h.message}),r.jsxs(H,{children:[h!=null&&h.authenticated?r.jsx(U,{danger:!0,icon:r.jsx(Vx,{}),onClick:B,loading:p,children:e("settings.providerTab.logoutCopilot")}):r.jsx(U,{type:"primary",icon:r.jsx(Kx,{}),onClick:jt,loading:p,children:e("settings.providerTab.authenticateCopilot")}),r.jsx(U,{onClick:Qe,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(ct,{})}),r.jsx(Z.Item,{name:["providers","copilot","model"],label:e("settings.providerTab.defaultModel"),rules:[{required:!0,message:e("settings.providerTab.selectModelRequired")}],extra:ms("copilot","backend"),children:r.jsx(Fe,{placeholder:e("settings.providerTab.selectModel"),allowClear:!0,showSearch:!0,loading:_,disabled:Y==="saving",notFoundContent:_?r.jsx(ht,{size:"small"}):r.jsx(ts,{type:"secondary",children:h!=null&&h.authenticated?e("settings.providerTab.noModelsLoaded"):e("settings.providerTab.authFirstThenFetch")}),onDropdownVisibleChange:de=>vt("copilot",de),onChange:de=>Xt("copilot",de),children:Q.map(de=>r.jsx(jn,{value:de.value,children:de.label},de.value))})}),r.jsx(Z.Item,{name:["providers","copilot","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:Rm(e),children:r.jsx(Fe,{mode:"tags",placeholder:'e.g. "gpt-5.3-codex", "gpt-5*"',tokenSeparators:[","," ",`
|
|
150
|
+
`," "]})}),r.jsx(Dt,{dashed:!0}),Mt("copilot",fy),hs("copilot"),r.jsxs(Sl,{type:"secondary",children:[e("settings.providerTab.copilotUsageTitle"),r.jsxs("ul",{style:{marginTop:8,marginBottom:0},children:[r.jsx("li",{children:e("settings.providerTab.copilotUsageStep1")}),r.jsx("li",{children:e("settings.providerTab.copilotUsageStep2")}),r.jsx("li",{children:e("settings.providerTab.copilotUsageStep3")})]})]})]})}default:return null}};return r.jsxs(ee,{title:e("settings.providerTab.title"),loading:n&&!d,className:"lotus-settings-card",extra:r.jsxs(ts,{type:"secondary",children:[e("settings.providerTab.currentProvider"),":"," ",r.jsx(ts,{strong:!0,children:vl[l]})]}),children:[r.jsx(Sl,{type:"secondary",children:e("settings.providerTab.description")}),r.jsx(Dt,{}),r.jsxs(Z,{form:s,layout:"vertical",onFinish:bt,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(Fe,{"data-testid":"provider-select",onChange:Me,size:"large",children:Object.keys(vl).map(V=>r.jsx(jn,{value:V,children:vl[V]},V))})}),r.jsx(Dt,{}),tn(),r.jsx(Dt,{}),r.jsx(H,{size:"middle",children:r.jsx(U,{"data-testid":"save-api-settings",type:"primary",htmlType:"submit",icon:r.jsx(Mi,{}),loading:n||a,size:"large",children:e("settings.providerTab.saveAndApply")})})]}),r.jsx(ST,{open:w,onCancel:()=>k(!1),onComplete:Ze,onCopyCode:Bt,completingAuth:j,copiedUserCode:M,deviceCodeInfo:b,timeRemaining:P,token:t})]})},{Text:Im}=ce,TT=({skill:e,disabled:t=!1,busy:s=!1,onToggleDisabled:n})=>{const{t:o}=se(),{token:a}=pe.useToken();return r.jsx(ee,{title:r.jsxs(H,{size:a.marginXS,wrap:!0,style:{width:"100%",justifyContent:"space-between"},children:[r.jsxs(H,{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(ct,{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(H,{direction:"vertical",size:a.marginXS,style:{width:"100%"},children:[r.jsx(Im,{type:"secondary",children:e.description}),e.compatibility&&r.jsxs(Im,{type:"secondary",children:["Compatibility: ",e.compatibility]}),e.tool_refs.length>0&&r.jsx(H,{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))})]})})},kT=3e4,jT=()=>{const{t:e}=se(),t=bs(C=>C.config),s=bs(C=>C.loadConfig),n=bs(C=>C.saveConfig),[o,a]=m.useState([]),[i,l]=m.useState(!1),[c,d]=m.useState(null),[u,h]=m.useState(null),[f,g]=m.useState(""),[y,p]=m.useState(new Date),x=m.useMemo(()=>{var C;return new Set((((C=t==null?void 0:t.skills)==null?void 0:C.disabled)??[]).map(P=>P.trim()).filter(Boolean))},[t]),b=m.useCallback(async(C=!0)=>{l(!0),d(null);try{const[P]=await Promise.all([tc.listSkills({includeDisabled:!0},C),s({force:C})]);a(P.skills),p(new Date)}catch(P){const v=P instanceof Error?P.message:e("components.skillManager.loadFailed");d(v)}finally{l(!1)}},[s,e]);m.useEffect(()=>{b(!0);const C=setInterval(()=>{b(!0)},kT);return()=>clearInterval(C)},[b]),m.useEffect(()=>{const C=()=>{b(!0)};return window.addEventListener("focus",C),()=>window.removeEventListener("focus",C)},[b]);const S=m.useCallback(async()=>{await b(!0),fe.success(e("components.skillManager.skillsRefreshed"))},[b,e]);m.useEffect(()=>{c&&(fe.error(c),d(null))},[c]);const w=m.useCallback(async(C,P)=>{var v;h(C);try{const M=await s({force:!0}),E=((v=M==null?void 0:M.skills)==null?void 0:v.disabled)??[],_=Array.from(new Set((P?[...E,C]:E.filter(R=>R!==C)).map(R=>R.trim()).filter(Boolean))).sort();await n({...M??{},skills:{...(M==null?void 0:M.skills)??{},disabled:_}}),fe.success(e("components.skillManager.skillStateSaved"))}catch(M){fe.error(M instanceof Error?M.message:e("components.skillManager.saveFailed"))}finally{h(null)}},[s,n,e]),k=o.filter(C=>{const P=f.trim().toLowerCase();return!(P&&![C.name,C.description,C.license??"",C.compatibility??"",...C.tool_refs].join(" ").toLowerCase().includes(P))}),j=()=>{const P=new Date().getTime()-y.getTime(),v=Math.floor(P/1e3);if(v<5)return e("components.skillManager.justNow");if(v<60)return e("components.skillManager.secondsAgo",{count:v});const M=Math.floor(v/60);return M<60?e("components.skillManager.minutesAgo",{count:M}):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(U,{icon:r.jsx(Fs,{spin:i}),onClick:S,loading:i,size:"small",children:e("components.skillManager.refresh")}),r.jsx("span",{className:"lotus-settings-note",style:{fontSize:"12px",marginLeft:"auto"},children:e("components.skillManager.lastUpdated",{value:j()})})]}),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(ss,{style:{marginBottom:"24px"},children:r.jsx(he,{placeholder:e("components.skillManager.searchPlaceholder"),prefix:r.jsx(Qo,{}),value:f,onChange:C=>g(C.target.value),allowClear:!0})}),r.jsx(ht,{spinning:i,children:k.length===0?r.jsx(Pt,{description:e(f?"components.skillManager.noMatch":"components.skillManager.noSkillsFound")}):r.jsx(nt,{grid:{gutter:16,xs:1,sm:2,md:3,lg:3,xl:4},dataSource:k,renderItem:C=>r.jsx(nt.Item,{children:r.jsx(TT,{skill:C,disabled:x.has(C.id),busy:u===C.id,onToggleDisabled:w})})})})]})})},{Title:CT,Text:wl,Paragraph:MT}=ce,$m="model_limits",Dc="modelLimitsConfigs",Dm="defaultBudgetStrategy",es=1e3;function Fm(e){return[{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5.4-thinking",max_context_tokens:1e6,max_output_tokens:128e3,safety_margin:es,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:es,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:es,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:es,note:e("settings.modelLimits.defaults.gpt5Mini")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4.1",max_context_tokens:128e3,max_output_tokens:16384,safety_margin:es,note:e("settings.modelLimits.defaults.gpt41")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4o",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:es,note:e("settings.modelLimits.defaults.gpt4o")},{vendor:"Google",model_pattern:"gemini-2.5-pro",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:es,note:e("settings.modelLimits.defaults.gemini25Pro")},{vendor:"Moonshot",model_pattern:"kimi-k2.5",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:es,note:e("settings.modelLimits.defaults.kimiK25")},{vendor:"Moonshot",model_pattern:"kimi-for-coding",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:es,note:e("settings.modelLimits.defaults.kimiCoding")},{vendor:"Zhipu",model_pattern:"glm-5",max_context_tokens:2e5,max_output_tokens:128e3,safety_margin:es,note:e("settings.modelLimits.defaults.glm5")}]}function PT(e){return Array.isArray(e)?Ld(e):[]}function Lm(e,t){if(typeof e!="number"||!Number.isFinite(e))return t;const s=Math.floor(e);return s>0?s:t}function ET(e,t){if(typeof e!="number"||!Number.isFinite(e))return t;const s=Math.floor(e);return s>=0?s:t}function RT(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=Lm(t.max_context_tokens??t.maxContextTokens,128e3),o=Lm(t.max_output_tokens??t.maxOutputTokens,Math.min(4096,Math.floor(n/4))),a=ET(t.safety_margin??t.safetyMargin,es);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 Ld(e){return Array.isArray(e)?e.map(t=>RT(t)).filter(t=>!!t):[]}function AT(){const e=localStorage.getItem(Dc);if(!e)return[];try{const t=JSON.parse(e);return Ld(t)}catch{return[]}}function IT(e){const t=Object.prototype.hasOwnProperty.call(e,$m);return t?{hasModelLimitsKey:t,modelLimits:Ld(e[$m])}:{hasModelLimitsKey:!1,modelLimits:[]}}function $T(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 DT=()=>{const{t:e}=se(),[t,s]=m.useState(()=>Fm(e)),[n,o]=m.useState(!1),[a,i]=fe.useMessage(),l=m.useCallback((p,x)=>{s(b=>b.map((S,w)=>w===p?{...S,...x}:S))},[]),c=m.useCallback(()=>{s(p=>[...p,{vendor:"",model_pattern:"",max_context_tokens:128e3,max_output_tokens:4096,safety_margin:es,note:""}])},[]),d=m.useCallback(p=>{s(x=>x.filter((b,S)=>S!==p))},[]),u=m.useCallback(async()=>{const p=Fm(e),x=await Je.getModelLimitDefaults(),b=PT(x.model_limits);return b.length>0?b:p},[e]),h=m.useCallback(async()=>{o(!0);try{const p=await Je.getBambooConfig(),{hasModelLimitsKey:x,modelLimits:b}=IT(p);if(b.length>0){s(b);return}if(x){s(await u());return}const S=AT();if(S.length>0){await Je.setBambooConfig({model_limits:S}),localStorage.removeItem(Dc),localStorage.removeItem(Dm),s(S),a.info(e("settings.modelLimits.migratedFromLocalStorage"));return}s(await u())}catch(p){console.error("Failed to load model limits settings:",p),a.error(e("settings.modelLimits.loadFailed")),s(await u())}finally{o(!1)}},[u,a,e]);m.useEffect(()=>{h()},[h]);const f=async()=>{const p=$T(t,e);if(p){a.error(p);return}o(!0);try{await Je.setBambooConfig({model_limits:t}),a.success(e("settings.modelLimits.saveSuccess"))}catch(x){console.error("Failed to save model limits settings:",x),a.error(e("settings.modelLimits.saveFailed"))}finally{o(!1)}},g=async()=>{o(!0);try{const p=await u();await Je.setBambooConfig({model_limits:p}),s(p),localStorage.removeItem(Dc),localStorage.removeItem(Dm),a.success(e("settings.modelLimits.resetSuccess"))}catch(p){console.error("Failed to reset model limits settings:",p),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:(p,x,b)=>r.jsx(he,{value:p,placeholder:e("settings.modelLimits.placeholders.vendor"),onChange:S=>l(b,{vendor:S.target.value})})},{title:e("settings.modelLimits.columns.model"),dataIndex:"model_pattern",key:"model_pattern",width:220,render:(p,x,b)=>r.jsx(he,{value:p,placeholder:e("settings.modelLimits.placeholders.model"),onChange:S=>l(b,{model_pattern:S.target.value})})},{title:e("settings.modelLimits.columns.contextWindow"),dataIndex:"max_context_tokens",key:"max_context_tokens",width:180,render:(p,x,b)=>r.jsx(ot,{value:p,onChange:S=>l(b,{max_context_tokens:Math.max(1e3,Number(S)||128e3)}),min:1e3,max:2e6,step:1e3,style:{width:"100%"}})},{title:e("settings.modelLimits.columns.maxOutput"),dataIndex:"max_output_tokens",key:"max_output_tokens",width:160,render:(p,x,b)=>r.jsx(ot,{value:p,onChange:S=>l(b,{max_output_tokens:Math.max(1,Number(S)||4096)}),min:1,max:2e6,step:256,style:{width:"100%"}})},{title:e("settings.modelLimits.columns.notes"),dataIndex:"note",key:"note",width:240,render:(p,x,b)=>r.jsx(he,{value:p,placeholder:e("settings.modelLimits.placeholders.optional"),onChange:S=>l(b,{note:S.target.value})})},{title:e("settings.modelLimits.columns.actions"),key:"actions",width:100,render:(p,x,b)=>r.jsx(U,{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(CT,{level:4,children:e("settings.modelLimits.title")}),r.jsxs(MT,{type:"secondary",children:[e("settings.modelLimits.descriptionPrefix")," ",r.jsx(wl,{code:!0,children:"config.json"})," ",e("settings.modelLimits.descriptionSuffix")]}),r.jsx(Dt,{}),r.jsxs(H,{direction:"vertical",size:"small",style:{width:"100%"},children:[r.jsx(wl,{strong:!0,children:e("settings.modelLimits.defaultsTitle")}),r.jsx(wl,{type:"secondary",children:e("settings.modelLimits.defaultsDescription")})]}),r.jsx(Js,{dataSource:t,columns:y,rowKey:(p,x)=>`${p.model_pattern}-${x}`,pagination:!1,size:"small",style:{margin:"16px 0"},scroll:{x:1150}}),r.jsxs(H,{children:[r.jsx(U,{onClick:c,children:e("settings.modelLimits.actions.addRow")}),r.jsx(U,{type:"primary",icon:r.jsx(Mi,{}),onClick:()=>void f(),loading:n,children:e("settings.modelLimits.actions.save")}),r.jsx(U,{icon:r.jsx(Fs,{}),onClick:()=>void g(),loading:n,children:e("settings.modelLimits.actions.resetToDefaults")}),r.jsx(U,{onClick:()=>void h(),loading:n,children:e("settings.modelLimits.actions.reload")})]})]})]})},Fc="lotus_experience_mode_v1",gy=new Set(["skills","hooks","masking","env-vars","metrics","sessions","config"]);function Om(){try{const e=localStorage.getItem(Fc);if(e==="simple"||e==="advanced")return e}catch{}return"advanced"}const bi=xn(e=>({mode:Om(),isAdvanced:Om()==="advanced",setMode:t=>{try{localStorage.setItem(Fc,t)}catch{}e({mode:t,isAdvanced:t==="advanced"})},toggleMode:()=>e(t=>{const s=t.mode==="simple"?"advanced":"simple";try{localStorage.setItem(Fc,s)}catch{}return{mode:s,isAdvanced:s==="advanced"}})})),{Text:_l}=ce,{useToken:FT}=pe,LT="bamboo_dark_mode",OT=({themeMode:e,onThemeModeChange:t,locale:s,onLocaleChange:n,onBack:o})=>{const{t:a}=se(),{token:i}=FT(),{deleteAllChats:l,autoGenerateTitles:c,setAutoGenerateTitlesPreference:d,isUpdatingAutoTitlePreference:u}=Qw(),[h,f]=m.useState(!1),[g,y]=fe.useMessage(),[p,x]=m.useState(""),[b,S]=m.useState(Sc()),[w,k]=m.useState(_c()),[j,C]=m.useState(gi()),[P,v]=m.useState(yi()),E=Yt(G=>G.currentProvider)==="copilot",_=pn(G=>G.activeTabKey),R=pn(G=>G.setActiveTabKey),T=bi(G=>G.isAdvanced),D=i.paddingSM,$=(G,be)=>({key:G,label:r.jsx(_l,{type:"secondary",style:{fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em",cursor:"default",userSelect:"none"},children:be}),disabled:!0,children:null}),I=(G,be)=>r.jsx("span",{"data-testid":`settings-tab-${G}`,children:be}),O=()=>{localStorage.clear(),g.success(a("settings.notifications.localStorageCleared"))},A=async()=>{f(!0);try{await l(),await Je.resetSetupStatus(),await Je.resetBambooConfig(),localStorage.clear(),g.success(a("settings.notifications.resetSuccessReloading")),setTimeout(()=>{window.location.reload()},1500)}catch(G){console.error("Failed to reset application:",G),g.error(G instanceof Error?G.message:a("settings.notifications.resetFailed")),f(!1)}},z=async G=>{try{await d(G),g.success(a(G?"settings.notifications.autoTitleEnabled":"settings.notifications.autoTitleDisabled"))}catch{g.error(a("settings.notifications.autoTitleUpdateFailed"))}},L=()=>{Vw(p),g.success(a("settings.notifications.promptEnhancementSaved"))},Y=G=>{S(G),Fw(G)},F=G=>{k(G),zw(G)},q=G=>{C(G),Uw(G)},K=G=>{v(G),Zw(G),window.dispatchEvent(new Event("lotus-vdi-safe-mode-change")),g.success(G?a("settings.appTab.vdiSafeModeEnabled","Graphics compatibility mode enabled"):a("settings.appTab.vdiSafeModeDisabled","Graphics compatibility mode disabled"))};return m.useEffect(()=>{x(ny()),S(Sc()),k(_c()),C(gi()),v(yi())},[]),r.jsxs(J,{vertical:!0,role:"region","aria-label":a("settings.page.title"),style:{height:"100vh",overflow:"hidden",background:i.colorBgContainer},children:[y,r.jsxs(J,{align:"center",justify:"space-between",style:{padding:i.padding,paddingTop:i.padding+D,borderBottom:`1px solid ${i.colorBorderSecondary}`},children:[r.jsxs(J,{align:"center",gap:i.marginSM,children:[r.jsx(U,{icon:r.jsx(Gx,{}),onClick:o,"aria-label":a("settings.page.back"),children:a("settings.page.back")}),r.jsx(_l,{strong:!0,"data-testid":"settings-page-title",children:a("settings.page.title")})]}),r.jsxs(_l,{type:"secondary","data-testid":"settings-page-version",children:[a("settings.appTab.runningVersion","Running version"),": v",cd]})]}),r.jsx(dr.Content,{style:{flex:1,minHeight:0,overflow:"auto",padding:i.padding},children:r.jsx(ei,{tabPosition:"left",activeKey:_,onChange:G=>R(G),items:[$("group-ai",a("settings.page.groups.ai")),{key:"provider",label:I("provider",a("settings.page.tabs.provider")),children:r.jsx(_T,{})},{key:"model-limits",label:I("model-limits",a("settings.page.tabs.modelLimits")),children:r.jsx(DT,{})},{key:"prompts",label:I("prompts",a("settings.page.tabs.prompts")),children:r.jsx(f_,{promptEnhancement:p,onPromptEnhancementChange:x,mermaidEnhancementEnabled:b,taskEnhancementEnabled:w,showCopilotConclusionWithOptionsEnhancement:E,copilotConclusionWithOptionsEnhancementEnabled:j,onMermaidToggle:Y,onTaskToggle:F,onCopilotConclusionWithOptionsToggle:q,onSaveEnhancement:L})},$("group-tools",a("settings.page.groups.toolsAndExtensions")),{key:"skills",label:I("skills",a("settings.page.tabs.skills")),children:r.jsx(jT,{})},{key:"mcp",label:I("mcp",a("settings.page.tabs.mcp")),children:r.jsx(p0,{})},{key:"workflows",label:I("workflows",a("settings.page.tabs.workflows")),children:r.jsx(C_,{})},{key:"hooks",label:I("hooks",a("settings.page.tabs.hooks")),children:r.jsx(aT,{})},$("group-security",a("settings.page.groups.securityAndPrivacy")),{key:"masking",label:I("masking",a("settings.page.tabs.masking")),children:r.jsx(v_,{})},{key:"env-vars",label:I("env-vars",a("settings.page.tabs.envVars")),children:r.jsx(__,{})},$("group-monitoring",a("settings.page.groups.monitoring")),{key:"metrics",label:I("metrics",a("settings.page.tabs.metrics")),children:r.jsx(sT,{})},{key:"sessions",label:I("sessions",a("settings.page.tabs.sessions")),children:r.jsx(bT,{})},$("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(xT,{})},{key:"app",label:I("app",a("settings.page.tabs.app")),children:r.jsx(y_,{autoGenerateTitles:c,isUpdatingAutoTitlePreference:u,onAutoTitleToggle:z,themeMode:e,onThemeModeChange:t,vdiSafeMode:P,onVdiSafeModeToggle:K,onClearLocalStorage:O,onResetApp:A,isResetting:h,darkModeKey:LT})}].filter(G=>!(!T&&G.key&&gy.has(G.key)||!T&&(G.key==="group-security"||G.key==="group-monitoring")))})})]})},{Text:zm,Paragraph:zT}=ce;class vi extends m.Component{constructor(s){super(s);Ye(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(NT,{error:n,onReset:this.handleReset})}}const NT=({error:e,onReset:t})=>{const{token:s}=pe.useToken(),[n,o]=pt.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(Vp,{style:{fontSize:36,color:s.colorWarning}}),r.jsx(zm,{strong:!0,style:{fontSize:16},children:"Something went wrong"}),r.jsx(zm,{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(U,{type:"primary",icon:r.jsx(Fs,{}),onClick:t,"aria-label":"Retry rendering this section",children:"Try Again"}),r.jsx(U,{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(zT,{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}`:""]})]})},BT=15e3,WT=()=>{const e=N(a=>a.chats),t=N(a=>a.updateSession),{generateChatTitle:s}=Ad({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<BT||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},UT=()=>{const{token:e}=pe.useToken(),t=Bi(),s=m.useRef("");m.useEffect(()=>{const n=qT(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),nd.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 qT(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}nd.initialize({startOnLoad:!1,theme:"dark",securityLevel:"loose",suppressErrorRendering:!0});nd.parseError=function(e){console.warn("Mermaid parse error (handled gracefully):",e)};const Nm=new Map,HT=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,YT=e=>e.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),XT=e=>(HT.test(e)?YT(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}]`}),VT=200,As=new Map,Ja=new Map;let Tl=null;const KT=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 GT(){Tl||(Tl=Ft(()=>import("./vendor-mermaid-7RLh-Mwz.js").then(t=>t.bd),__vite__mapDeps([7,1,2,3,6]),import.meta.url));const e=await Tl;return e.default??e}function JT(e,t){if(As.has(e)&&As.delete(e),As.set(e,t),As.size>VT){const s=As.keys().next().value;s&&As.delete(s)}}function Qa(e){const t=As.get(e);return t?(As.delete(e),As.set(e,t),t):null}function Bm(){As.clear(),Ja.clear()}function QT(e,t){const s=Qa(e);if(s)return Promise.resolve(s);const n=Ja.get(e);if(n)return n;const o=(async()=>{var S,w;const a=await GT();await a.parse(t);const i=`mermaid-${e}`,l=document.createElement("div"),c=Math.max(1600,window.innerWidth||0,((S=document.documentElement)==null?void 0:S.clientWidth)||0);l.style.cssText=["position:absolute","left:-9999px","top:-9999px",`width:${c}px`,`min-width:${c}px`,"visibility:hidden","pointer-events:none","overflow:visible"].join(";"),document.body.appendChild(l);let d;try{d=await a.render(i,t,l)}finally{document.body.removeChild(l)}const u=typeof d=="object"&&"svg"in d?d.svg:String(d),h=KT(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 p=800,x=300;if(y){const k=y.getAttribute("viewBox");if(k){const j=k.split(/\s+/).map(Number);j.length===4&&(p=j[2]||800,x=j[3]||300)}if(p===800&&x===300){const j=document.createElement("div");j.style.cssText="position:absolute;visibility:hidden;width:800px;",j.innerHTML=u,document.body.appendChild(j);const C=(w=j.querySelector("svg"))==null?void 0:w.getBoundingClientRect();C&&(p=C.width,x=C.height),document.body.removeChild(j)}}const b={svg:u,width:p,height:x};return JT(e,b),b})().finally(()=>{Ja.delete(e)});return Ja.set(e,o),o}const ZT=e=>{const t=e;return(t==null?void 0:t.name)==="AbortError"||(t==null?void 0:t.code)===20},Wm=220,Um=e=>{const t=e.replace(/\s+/g," ").trim();return t.length<=Wm?t:`${t.slice(0,Wm)}...`},ek=e=>e==="pending"||e==="in_progress"||e==="completed"||e==="blocked",qm=e=>{const t=e.trim().toLowerCase();return t==="memory_note"||t==="session_note"};function tk(){const e=N(v=>v.processingChats),t=N(v=>v.addMessage),s=N(v=>v.setSessionProcessing),n=N(v=>v.updateTokenUsage),o=N(v=>v.setTruncationInfo),a=N(v=>v.updateSession),i=N(v=>v.updateMessage),l=N(v=>v.setTaskList),c=N(v=>v.updateTaskListDelta),d=N(v=>v.setEvaluationState),u=N(v=>v.upsertSubSessionProgress),h=N(v=>v.refreshChats),f=m.useRef(new Ss),g=m.useRef(new Map),y=m.useRef(new Map),p=m.useRef(new Map),x=m.useRef(new Map),b=m.useRef(new Map),S=m.useRef(new Set),w=m.useRef(new Map),k=m.useCallback(v=>{const M=w.current.get(v);M!=null&&M.timer&&clearTimeout(M.timer),w.current.delete(v)},[]),j=m.useCallback((v,M)=>{k(v),S.current.delete(v);const E=g.current.get(v);if(!E)return;g.current.delete(v),E.controller.abort();const _=y.current.get(E.sessionId);_?(M!=null&&M.clearDraft&&(ze.clear(_.sessionId,_.messageId),ze.clear(_.sessionId,_.reasoningMessageId),ze.clear(_.sessionId,_.statusMessageId)),y.current.delete(E.sessionId)):M!=null&&M.clearDraft&&(ze.clear(v,`streaming-${v}`),ze.clear(v,`streaming-reasoning-${v}`),ze.clear(v,`streaming-status-${v}`))},[k]),C=m.useCallback(v=>{k(v);const M=new AbortController;g.current.set(v,{sessionId:v,controller:M});const E=`streaming-${v}`,_=`streaming-reasoning-${v}`,R=`streaming-status-${v}`,T=ze.getLatest(E),D=ze.getLatest(_),$=ze.getLatest(R);y.current.set(v,{sessionId:v,messageId:E,content:T??"",reasoningMessageId:_,reasoningContent:D??"",statusMessageId:R,status:$??""});const I=A=>{const z=y.current.get(v);if(!z)return;const L=(A??"").trim();if(!L){if(!z.status)return;z.status="",ze.clear(z.sessionId,z.statusMessageId);return}z.status!==L&&(z.status=L,ze.publish({sessionId:z.sessionId,messageId:z.statusMessageId,content:z.status}))};T===null&&ze.publish({sessionId:v,messageId:E,content:""});const O=()=>{const A=w.current.get(v),z=(A==null?void 0:A.attempt)??0,L=Math.min(5e3,250*Math.pow(2,z));j(v,{clearDraft:!1});const Y=setTimeout(()=>{var K;if(w.current.delete(v),!N.getState().processingChats.has(v))return;const F=N.getState().chats.find(G=>G.id===v),q=(K=F==null?void 0:F.id)==null?void 0:K.trim();q&&C(q)},L);w.current.set(v,{attempt:z+1,timer:Y})};f.current.subscribeToEvents(v,{onToken:A=>{const z=y.current.get(v);z&&(I(null),z.content+=A,ze.publish({sessionId:z.sessionId,messageId:z.messageId,content:z.content}))},onReasoningToken:A=>{const z=y.current.get(v);z&&(z.reasoningContent+=A,ze.publish({sessionId:z.sessionId,messageId:z.reasoningMessageId,content:z.reasoningContent}))},onToolStart:(A,z,L)=>{var Ee,Te;const Y=y.current.get(v),F=(Y==null?void 0:Y.content)||"",q=(Y==null?void 0:Y.reasoningContent)||"",K=F.trim().length>0,G=q.trim().length>0;if(K||G){const ge=N.getState().chats.find(jt=>jt.id===v),je=(Ee=ge==null?void 0:ge.messages)==null?void 0:Ee[ge.messages.length-1],Be=typeof((Te=je==null?void 0:je.metadata)==null?void 0:Te.reasoning)=="string"?je.metadata.reasoning:"";(je==null?void 0:je.role)==="assistant"&&(je==null?void 0:je.type)==="text"&&typeof(je==null?void 0:je.content)=="string"&&je.content===F&&Be===q||t(v,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:F,createdAt:new Date().toISOString(),metadata:{sessionId:v,model:"agent",...G?{reasoning:q}:{}}}),Y&&(Y.content="",Y.reasoningContent="",Y.status&&(Y.status="",ze.clear(Y.sessionId,Y.statusMessageId)),ze.publish({sessionId:Y.sessionId,messageId:Y.messageId,content:""}),ze.publish({sessionId:Y.sessionId,messageId:Y.reasoningMessageId,content:""}))}x.current.set(A,z);const be=z.trim().toLowerCase();qm(z)?I("memory_updating"):I(`tool_running:${be||"tool"}`);const Pe=crypto.randomUUID();b.current.set(A,Pe),t(v,{id:Pe,role:"assistant",type:"tool_call",toolCalls:[{toolCallId:A,toolName:z,parameters:L||{},streamingOutput:""}],metadata:{},createdAt:new Date().toISOString()})},onToolToken:(A,z)=>{const L=b.current.get(A);if(!L)return;const Y=N.getState().chats.find(K=>K.id===v);if(!Y)return;const F=Y==null?void 0:Y.messages.find(K=>K.id===L);if(!F||!("type"in F)||F.type!=="tool_call"||!("toolCalls"in F)||!Array.isArray(F.toolCalls))return;const q=F.toolCalls.map(K=>{if(K.toolCallId!==A)return K;const G=(K.streamingOutput||"")+(z||"");return{...K,streamingOutput:G}});i(v,L,{toolCalls:q})},onToolComplete:(A,z)=>{const L=x.current.get(A)||"unknown";x.current.delete(A),b.current.delete(A),I(null);const Y=(z==null?void 0:z.display_preference)||"Default";t(v,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:L,toolCallId:A,result:{tool_name:L,result:(z==null?void 0:z.result)??"",display_preference:Y},isError:!(z!=null&&z.success),createdAt:new Date().toISOString()})},onToolError:(A,z)=>{x.current.delete(A),b.current.delete(A),I(null),t(v,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:"unknown",toolCallId:A,result:{tool_name:"unknown",result:z,display_preference:"Default"},isError:!0,createdAt:new Date().toISOString()})},onToolLifecycle:(A,z,L,Y,F)=>{if(L==="begin"){const q=(z||"").trim().toLowerCase();qm(z||"")?I("memory_updating"):I(`tool_running:${q||"tool"}`)}if(L==="finished"||L==="error"||L==="cancelled"){const q=b.current.get(A);q&&i(v,q,{metadata:{elapsed_ms:Y,is_mutating:F}}),I(null)}},onContextCompressionStatus:(A,z)=>{if(z==="started"){I("context_compacting");return}if(z==="degraded_sections"){I("context_compaction_degraded");return}if(z==="failed"){I("context_compaction_failed");return}I(null)},onTokenBudgetUpdated:A=>{const z=typeof A.max_context_tokens=="number"&&A.max_context_tokens>0?A.max_context_tokens:void 0,L={systemTokens:A.system_tokens,summaryTokens:A.summary_tokens,windowTokens:A.window_tokens,totalTokens:A.total_tokens,budgetLimit:A.budget_limit,...z?{maxContextTokens:z}:{},...typeof A.prompt_cached_tool_outputs=="number"&&A.prompt_cached_tool_outputs>0?{promptCachedToolOutputs:A.prompt_cached_tool_outputs}:{}};n(v,L),o(v,A.truncation_occurred,A.segments_removed);const Y=N.getState().chats.find(F=>F.id===v);Y&&a(v,{config:{...Y.config,tokenUsage:L,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,z,L)=>{fe.success(`All tasks completed! Total rounds: ${z}, Tool calls: ${L}`,3)},onTaskEvaluationStarted:(A,z)=>{d(A,{isEvaluating:!0,reasoning:null,timestamp:Date.now()}),fe.info(`Evaluating ${z} task(s)...`,2)},onTaskEvaluationCompleted:(A,z,L)=>{const Y=Um(L);d(A,{isEvaluating:!1,reasoning:z>0?Y:null,timestamp:Date.now()}),z>0?fe.success(`Evaluation complete: ${z} task(s) updated.`,3):fe.info("Evaluation complete: No updates needed",2)},onComplete:()=>{const A=M;(async()=>{var be,Pe,Ee;const z=()=>{const Te=g.current.get(v);return Te!=null&&Te.controller!==A};if(z())return;const L=y.current.get(v),Y=(L==null?void 0:L.content)||"",F=(L==null?void 0:L.reasoningContent)||"",q=Y.trim().length>0,K=F.trim().length>0;if(q||K){const Te=N.getState().chats.find(Qe=>Qe.id===v),ge=(be=Te==null?void 0:Te.messages)==null?void 0:be[Te.messages.length-1],je=typeof((Pe=ge==null?void 0:ge.metadata)==null?void 0:Pe.reasoning)=="string"?ge.metadata.reasoning:"";(ge==null?void 0:ge.role)==="assistant"&&(ge==null?void 0:ge.type)==="text"&&typeof(ge==null?void 0:ge.content)=="string"&&ge.content===Y&&je===F||await t(v,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:Y,createdAt:new Date().toISOString(),metadata:{sessionId:v,model:"agent",...K?{reasoning:F}:{}}})}if(z()||(await N.getState().loadChatHistory(v,{mode:"monotonic",retries:4,retryDelayMs:200,waitForAssistant:!0}),z()))return;if(K){const Te=N.getState().chats.find(Be=>Be.id===v),ge=[...(Te==null?void 0:Te.messages)||[]].reverse().find(Be=>(Be==null?void 0:Be.role)==="assistant"&&(Be==null?void 0:Be.type)==="text"),je=typeof((Ee=ge==null?void 0:ge.metadata)==null?void 0:Ee.reasoning)=="string"&&ge.metadata.reasoning.trim().length>0;ge!=null&&ge.id&&!je&&i(v,ge.id,{metadata:{...ge.metadata||{},reasoning:F}})}if(z())return;const G=p.current.get(v)??{children:new Set};if(p.current.set(v,{children:new Set(G.children),parentDone:!0}),G.children.size===0)j(v,{clearDraft:!0}),s(v,!1);else{const Te=g.current.get(v);Te&&(ze.clear(v,`streaming-${v}`),ze.clear(v,`streaming-reasoning-${v}`),ze.clear(v,`streaming-status-${v}`),y.current.delete(Te.sessionId))}})()},onError:async A=>{I(null);const z=Tc(A)?kc(A):A;await t(v,{id:`error-${Date.now()}`,role:"assistant",type:"text",content:`❌ **Error**: ${z}`,createdAt:new Date().toISOString(),finishReason:"error"});const L=p.current.get(v)??{children:new Set};p.current.set(v,{children:new Set(L.children),parentDone:!0}),L.children.size===0&&(j(v,{clearDraft:!0}),s(v,!1))},onSubSessionStarted:(A,z,L)=>{const Y=p.current.get(A)??{children:new Set,parentDone:!1},F=new Set(Y.children);F.add(z),p.current.set(A,{children:F,parentDone:Y.parentDone}),s(v,!0),u(A,z,{title:L,status:"pending",lastEventAt:new Date().toISOString()}),h()},onSubSessionEvent:(A,z,L)=>{var Y,F,q;if(L.type==="task_list_updated"&&L.task_list){const K=L.task_list.session_id||A;l(K,L.task_list);return}if(L.type==="task_list_item_progress"){const K=L.session_id||A;typeof L.item_id=="string"&&ek(L.status)&&typeof L.tool_calls_count=="number"&&typeof L.version=="number"&&c(K,{session_id:K,item_id:L.item_id,status:L.status,tool_calls_count:L.tool_calls_count,version:L.version});return}if(L.type==="task_evaluation_started"){const K=L.session_id||A;d(K,{isEvaluating:!0,reasoning:null,timestamp:Date.now()});return}if(L.type==="task_evaluation_completed"){const K=L.session_id||A,G=L.updates_count??0;d(K,{isEvaluating:!1,reasoning:G>0?Um(L.reasoning??""):null,timestamp:Date.now()});return}if(L.type==="token"&&typeof L.content=="string"){const G=((((q=(F=(Y=N.getState().subSessionsByParent)==null?void 0:Y[A])==null?void 0:F[z])==null?void 0:q.outputPreview)||"")+L.content).slice(-2e3);u(A,z,{status:"running",outputPreview:G,lastEventAt:new Date().toISOString()})}else u(A,z,{status:"running",lastEventAt:new Date().toISOString()})},onSubSessionHeartbeat:(A,z,L)=>{u(A,z,{status:"running",lastHeartbeatAt:L})},onSubSessionCompleted:(A,z,L,Y)=>{const F=p.current.get(A)??{children:new Set,parentDone:!1},q=new Set(F.children);q.delete(z),p.current.set(A,{children:q,parentDone:F.parentDone}),u(A,z,{status:L,error:Y,lastEventAt:new Date().toISOString()}),F.parentDone&&q.size===0&&(j(v,{clearDraft:!0}),s(v,!1)),h()}},M).then(()=>{if(M.signal.aborted)return;const A=g.current.get(v);if(A&&A.controller!==M)return;if(!N.getState().processingChats.has(v)){j(v,{clearDraft:!0});return}O()}).catch(A=>{if(!M.signal.aborted){if(ZT(A)){if(!N.getState().processingChats.has(v)){j(v,{clearDraft:!0});return}O();return}console.error("[useAgentEventSubscription] Subscription error:",A),j(v,{clearDraft:!0}),s(v,!1)}})},[t,j,k,h,d,s,l,o,i,a,c,n,u]),P=m.useCallback(v=>{const M=v.trim();if(!M)return;S.current.delete(M);const E=g.current.get(M);(E==null?void 0:E.sessionId)===M&&!E.controller.signal.aborted||(E&&j(M,{clearDraft:!1}),C(M))},[j,C]);m.useEffect(()=>{e.forEach(v=>P(v));for(const v of Array.from(g.current.keys()))e.has(v)||j(v,{clearDraft:!0});for(const v of Array.from(S.current))e.has(v)||S.current.delete(v)},[e,P,j]),m.useEffect(()=>N.subscribe(v=>v.chats,()=>{if(S.current.size!==0)for(const v of Array.from(S.current)){if(!N.getState().processingChats.has(v)){S.current.delete(v);continue}P(v)}}),[P]),m.useEffect(()=>{const v=g.current;return()=>{const M=Array.from(v.keys());for(const E of M)j(E,{clearDraft:!0})}},[j])}const yy=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_result",sk=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_call",nk=e=>e.role==="assistant"&&"type"in e&&e.type==="workflow_result",rk=e=>e.role==="user"&&"type"in e&&e.type==="file_reference",ok=e=>e.role==="assistant"&&"type"in e&&e.type==="task_list",Si=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/bmp"],Hm=10*1024*1024,ak=2048,ik=2048,lk=.82,ck=512*1024,dk=e=>Si.includes(e.type)?e.size>Hm?{isValid:!1,error:`Image size too large: ${(e.size/1024/1024).toFixed(2)}MB. Maximum size: ${Hm/1024/1024}MB`}:{isValid:!0}:{isValid:!1,error:`Unsupported image type: ${e.type}. Supported types: ${Si.join(", ")}`},uk=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}),Ym=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)}),mk=e=>URL.createObjectURL(e),hk=(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))},pk=async(e,t)=>{const s=await uk(e),n=document.createElement("canvas");return hk(n,s,ak,ik),yk(n,t)},fk=async e=>{const t=dk(e);if(!t.isValid)throw new Error(t.error);const s=mk(e);try{let n;if(e.type==="image/gif"||e.size<ck)n=await Ym(e);else try{n=await pk(s,lk)}catch(a){console.warn("[imageUtils] Failed to re-encode image, using original:",a),n=await Ym(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 xy(s),n}},gk=async e=>{const t=Array.from(e),s=[];for(const n of t)try{const o=await fk(n);s.push(o)}catch(o){console.error(`Failed to process image ${n.name}:`,o)}return s},yk=(e,t=.8)=>e.toDataURL("image/jpeg",t),xy=e=>{e.startsWith("blob:")&&URL.revokeObjectURL(e)},Xm=e=>{e.forEach(t=>xy(t.preview))},xk=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]},bk=e=>!e.files||e.files.length===0?!1:Array.from(e.files).some(t=>Si.includes(t.type)),vk=e=>e.files?Array.from(e.files).filter(t=>Si.includes(t.type)):[],{Text:Sk,Title:wk}=ce,_k=({visible:e,images:t,currentIndex:s=0,onClose:n,onDownload:o})=>{const{token:a}=pe.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 f=document.createElement("a");f.href=c.base64,f.download=c.name,document.body.appendChild(f),f.click(),document.body.removeChild(f)}},u=()=>{l(f=>f>0?f-1:t.length-1)},h=()=>{l(f=>f<t.length-1?f+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(wk,{level:5,style:{margin:0},children:c.name}),r.jsxs(Sk,{type:"secondary",style:{fontSize:a.fontSizeSM},children:[xk(c.size)," • ",c.type,t.length>1&&` • ${i+1} of ${t.length}`]})]}),r.jsxs(H,{children:[t.length>1&&r.jsxs(r.Fragment,{children:[r.jsx(U,{icon:r.jsx(Jd,{}),onClick:u,disabled:t.length<=1}),r.jsx(U,{icon:r.jsx(Ks,{}),onClick:h,disabled:t.length<=1})]}),r.jsx(U,{icon:r.jsx(gr,{}),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(Jx,{dots:!1,arrows:!0,infinite:!0,afterChange:l,style:{width:"100%",height:"100%"},children:t.map(f=>r.jsx("div",{children:r.jsx("div",{style:{height:"70vh",display:"flex",justifyContent:"center",alignItems:"center"},children:r.jsx("img",{src:f.preview,alt:f.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}})})},f.id))}),t.length>1&&r.jsxs(r.Fragment,{children:[r.jsx(U,{type:"primary",shape:"circle",icon:r.jsx(Jd,{}),onClick:u,style:{position:"absolute",left:20,top:"50%",transform:"translateY(-50%)",zIndex:10}}),r.jsx(U,{type:"primary",shape:"circle",icon:r.jsx(Ks,{}),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((f,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:f.preview,alt:f.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},f.id))})]})},Ur=e=>/\s/.test(e),Tk=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||Ur(a)),l=o==="@"&&(n===0||Ur(a));if(!i&&!l){let u=n;for(;n<s&&!((e[n]==="/"||e[n]==="@")&&(n===0||Ur(e[n-1])));)n+=1;t.push({text:e.slice(u,n),type:"text"});continue}let c=n+1;for(;c<s&&!Ur(e[c]);)c+=1;const d=e.slice(n,c);i?c===s||Ur(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"}]},kk=/(\/)([a-zA-Z0-9_-]*)$/,jk=e=>{if(!e)return{command:null,isTriggerActive:!1,searchText:""};const t=e.match(kk);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}},Ck=/@([a-zA-Z0-9._\-\/\\]*)$/,Mk=e=>{if(!e)return{isTriggerActive:!1,searchText:"",tokenStart:null};const t=e.match(Ck);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}},Pk=(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:Ek}=ce,Rk=({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(H,{direction:"vertical",align:"center",children:[r.jsx(Qx,{style:{fontSize:32,color:t.colorPrimary}}),r.jsx(Ek,{style:{color:t.colorPrimary,fontWeight:500},children:"Drop images here"})]})}):null,{Text:Vm}=ce,Ak=({images:e,token:t,allowImages:s,onPreview:n,onClear:o})=>{const{t:a}=se();return!s||e.length===0?null:r.jsx("div",{style:{marginBottom:t.marginSM,padding:`${t.paddingXXS}px ${t.paddingXS}px`,borderRadius:999,border:`1px solid ${t.colorBorderSecondary}`,background:t.colorFillSecondary},children:r.jsxs(J,{align:"center",wrap:"wrap",gap:t.marginXS,children:[r.jsx(Vm,{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(Vm,{type:"secondary",style:{fontSize:t.fontSizeSM},children:a("chat.input.moreImages",{count:e.length-3})}),r.jsx(U,{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:Ik}=he,$k=({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(p=>p.type!=="text"),f="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:f,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((p,x)=>{let b;return p.type==="workflow"?b={backgroundColor:n.colorPrimaryBg,color:"transparent",WebkitTextFillColor:"transparent",fontWeight:400,textDecoration:"underline",textDecorationStyle:"dotted",textDecorationColor:n.colorPrimary}:p.type==="file"&&(b={backgroundColor:n.colorSuccessBg,color:"transparent",WebkitTextFillColor:"transparent"}),r.jsx("span",{style:b,children:p.text},`segment-${x}`)}),e.endsWith(`
|
|
153
|
+
`)?`
|
|
154
|
+
`:null]}):null,r.jsx(Ik,{"data-testid":"chat-input",ref:a,value:e,onChange:p=>l(p.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:f,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"}})]})},Dk=({allowImages:e,disabled:t,isStreaming:s,token:n,fileInputRef:o,onFileInputChange:a,onFileReferenceButtonClick:i,extraControl:l})=>{const{t:c}=se();return r.jsxs(J,{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(U,{type:"text",icon:r.jsx(Gs,{}),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(U,{type:"text",icon:r.jsx(yr,{}),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]})},Fk=({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:f})=>{const{t:g}=se(),y=!l.trim()&&c.length===0,p=s||n||!o,x=f??g("chat.actions.sendMessage");return r.jsxs(J,{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(fr,{trigger:["click"],menu:{items:[{key:"regenerate",label:g("chat.actions.regenerate"),icon:r.jsx(Fs,{})},{key:"error_retry",label:g("chat.actions.retryFailed"),icon:r.jsx(Ei,{})}],onClick:({key:b})=>o==null?void 0:o(b)},disabled:p,children:r.jsx(U,{"data-testid":"regenerate-button",type:"text",icon:r.jsx(Jc,{spin:s}),disabled:p,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(U,{"data-testid":s?"cancel-button":"send-button",type:"primary",icon:s?r.jsx(Zx,{}):r.jsx(eb,{}),onClick:s?a:i,loading:s&&!a,disabled:s?!a||n:y||n||d,size:"small",danger:s,className:s?"message-input-send-button":"message-input-send-button lotus-primary-cta",style:{minWidth:50,padding:0,height:50,width:50,borderRadius:25,display:"inline-flex",alignItems:"center",justifyContent:"center",background:s?void 0:"linear-gradient(135deg, var(--lotus-primary) 0%, var(--lotus-accent-secondary) 100%)",border:s?void 0:"none",boxShadow:s?void 0:"var(--lotus-send-btn-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",transform:"scale(1)"},title:s?g("chat.actions.cancelRequest"):x,"aria-label":s?g("chat.actions.cancelRequest"):x})]})},{Text:Km}=ce,Lk=({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(J,{justify:"flex-end",style:{marginTop:a.marginXXS},children:r.jsxs(Km,{type:s?"danger":n?"warning":"secondary",style:{fontSize:a.fontSizeSM},children:[e.toLocaleString()," / ",t.toLocaleString()]})}),o&&r.jsxs(H,{size:"small",style:{marginTop:a.marginXS},children:[r.jsx(ht,{size:"small"}),r.jsx(Km,{type:"secondary",children:"Processing files…"})]})]})},Ok=({onFiles:e,mode:t="images"})=>{const[s,n]=m.useState(!1),o=m.useCallback(l=>{var d,u;l.preventDefault(),l.stopPropagation(),(t==="images"?bk(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=vk(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}},zk=e=>{const{message:t}=us.useApp(),[s,n]=m.useState([]),[o,a]=m.useState(!1),[i,l]=m.useState(0),c=m.useCallback(async f=>{if(e)try{const g=await gk(f);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(f=>{const g=s.find(y=>y.id===f);g&&Xm([g]),n(y=>y.filter(p=>p.id!==f))},[s]),u=m.useCallback(f=>{const g=s.findIndex(y=>y.id===f.id);l(g>=0?g:0),a(!0)},[s]),h=m.useCallback(()=>{Xm(s),n([])},[s]);return{images:s,setImages:n,previewModalVisible:o,setPreviewModalVisible:a,previewImageIndex:i,handleImageFiles:c,handleRemoveImage:d,handleImagePreview:u,clearImages:h}},Nk=({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])}),wt=[];for(let e=0;e<256;++e)wt.push((e+256).toString(16).slice(1));function Bk(e,t=0){return(wt[e[t+0]]+wt[e[t+1]]+wt[e[t+2]]+wt[e[t+3]]+"-"+wt[e[t+4]]+wt[e[t+5]]+"-"+wt[e[t+6]]+wt[e[t+7]]+"-"+wt[e[t+8]]+wt[e[t+9]]+"-"+wt[e[t+10]]+wt[e[t+11]]+wt[e[t+12]]+wt[e[t+13]]+wt[e[t+14]]+wt[e[t+15]]).toLowerCase()}let kl;const Wk=new Uint8Array(16);function Uk(){if(!kl){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");kl=crypto.getRandomValues.bind(crypto)}return kl(Wk)}const qk=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Gm={randomUUID:qk};function Jm(e,t,s){var o;if(Gm.randomUUID&&!e)return Gm.randomUUID();e=e||{};const n=e.random??((o=e.rng)==null?void 0:o.call(e))??Uk();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,Bk(n)}const Hk=["text/","application/json","application/xml"],Yk=[".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"],Xk=200*1024,by=e=>e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`,Qm=e=>{const t=e.toLowerCase();return Yk.some(s=>t.endsWith(s))},Vk=e=>!e.type&&Qm(e.name)?!0:Hk.some(t=>e.type.startsWith(t))||Qm(e.name),Kk=e=>new Promise((t,s)=>{const n=new FileReader;n.onerror=()=>s(n.error),n.onload=()=>t(n.result),n.readAsText(e)}),Zm=async(e,t)=>{const s=Xk,n=[],o=[];for(const a of e)try{if(Vk(a)&&a.size<=s){const i=await Kk(a);n.push({id:Jm(),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:Jm(),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}},Gk=e=>{const t=[],s=[];return e.forEach(n=>{n.type.startsWith("image/")?t.push(n):s.push(n)}),{images:t,others:s}},Jk=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
|
+
`),Qk=({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:f}=zk(e),g=m.useCallback(async k=>{if(!k||k.length===0)return;const{images:j,others:C}=Gk(k);if(j.length>0&&await u(j),C.length>0&&t){o(!0);const{processed:P,errors:v}=await Zm(C);P.length>0&&(t(P),s.success(`Added ${P.length} file(s)`)),v.forEach(M=>s.error(M)),o(!1)}},[u,s,t]),{isDragOver:y,handleDragOver:p,handleDragLeave:x,handleDrop:b}=Ok({onFiles:g,mode:"any"}),{handlePaste:S}=Nk({onImages:u,onAttachments:t?async k=>{o(!0);const{processed:j,errors:C}=await Zm(k);j.length>0&&(t(j),s.success(`Attached ${j.length} file(s)`)),C.forEach(P=>s.error(P)),o(!1)}:void 0,allowImages:e}),w=m.useCallback(k=>{const j=k.target.files;j&&j.length>0&&u(j),k.target.value=""},[u]);return{images:a,setImages:i,previewModalVisible:l,setPreviewModalVisible:c,previewImageIndex:d,handleImageFiles:u,handleImagePreview:h,clearImages:f,isProcessingAttachments:n,isDragOver:y,handleDragOver:p,handleDragLeave:x,handleDrop:b,handlePaste:S,handleFileInputChange:w}},Zk=({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(jk(t))},[t,s]),m.useEffect(()=>{n&&n(Mk(t))},[t,n]),m.useEffect(()=>{o&&o(a)},[a,o]),m.useEffect(()=>{i&&l(i)},[i,l])},ej=({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:f,clearImages:g,textAreaRef:y})=>{const p=m.useCallback(()=>{const S=e.trim();if(!(!S&&t.length===0||s||n)){if(u){const w=typeof h=="number"?h.toLocaleString():"configured";f.error(`Message exceeds the maximum length of ${w} characters.`);return}if(d){const w=d(S);if(!w.isValid){f.error(w.errorMessage||"Message format is incorrect");return}}i(S,t.length>0?t:void 0),g()}},[g,n,t,u,s,h,f,i,d,e]),x=m.useCallback(S=>{if(c&&!n&&!s&&!S.shiftKey&&(S.key==="ArrowUp"||S.key==="ArrowDown")){const w=S.key==="ArrowUp"?"previous":"next",k=c(w,e);if(k!=null){S.preventDefault(),a(k),requestAnimationFrame(()=>{var C,P;const j=((P=(C=y.current)==null?void 0:C.resizableTextArea)==null?void 0:P.textArea)||null;if(j){const v=k.length;j.setSelectionRange(v,v)}});return}}S.key==="Enter"&&!S.shiftKey&&!s&&!n&&!o&&(S.preventDefault(),p())},[n,p,s,o,a,c,y,e]),b=m.useCallback((S="regenerate")=>{s||n||!l||l(S)},[n,s,l]);return{handleKeyDown:x,handleSubmit:p,handleRetry:b}},tj=({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:f,onAttachmentsAdded:g,onWorkflowCommandChange:y,onFileReferenceChange:p,onFileReferenceButtonClick:x,maxCharCount:b,leftControlsExtra:S,submitButtonLabel:w})=>{const{t:k}=se(),{isStreaming:j,hasMessages:C,allowRetry:P=!0,onRetry:v,onCancel:M,onHistoryNavigate:E}=n,_=m.useRef(null),R=m.useRef(null),T=u||R,D=m.useRef(null),{token:$}=pe.useToken(),I=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",[O,A]=fe.useMessage(),z=e.length,L=typeof b=="number"&&Number.isFinite(b)&&b>0,Y=L?z>b:!1,F=L?!Y&&z>=b*.9:!1,{images:q,setImages:K,previewModalVisible:G,setPreviewModalVisible:be,previewImageIndex:Pe,handleImagePreview:Ee,clearImages:Te,isProcessingAttachments:ge,isDragOver:je,handleDragOver:Be,handleDragLeave:Qe,handleDrop:jt,handlePaste:Ze,handleFileInputChange:Bt}=Qk({allowImages:c,onAttachmentsAdded:g,messageApi:O}),B=Pk(e,80),Me=m.useMemo(()=>Tk(e),[e]),X=()=>{var bt,st;const Et=(st=(bt=T.current)==null?void 0:bt.resizableTextArea)==null?void 0:st.textArea;if(!Et||!D.current)return;const Ct=Et.scrollTop,it=Et.scrollLeft;D.current.style.transform=`translate(${-it}px, ${-Ct}px)`};Zk({value:e,debouncedValue:B,onWorkflowCommandChange:y,onFileReferenceChange:p,onImagesChange:l,images:q,propImages:i,setImages:K,syncOverlayScroll:X});const{handleKeyDown:ue,handleSubmit:ie,handleRetry:le}=ej({value:e,images:q,isStreaming:j,disabled:a,isWorkflowSelectorVisible:d,onChange:t,onSubmit:s,onRetry:v,onHistoryNavigate:E,validateMessage:f,isOverCharLimit:Y,maxCharCount:b,messageApi:O,clearImages:Te,textAreaRef:T}),Ae=o??k("chat.input.placeholder");return r.jsxs(r.Fragment,{children:[A,r.jsxs("div",{className:`message-input-container lotus-message-input-shell ${je?"is-drag-over":""}`,role:"group","aria-label":k("chat.input.messageComposer","Message composer"),style:{position:"relative",border:`1px solid ${je?"var(--lotus-input-border-active)":"var(--lotus-input-border)"}`,borderRadius:26,background:je?"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:Be,onDragLeave:Qe,onDrop:jt,children:[r.jsx(Ak,{images:q,token:$,allowImages:c,onPreview:Ee,onClear:Te}),r.jsx(Rk,{visible:je,token:$}),r.jsxs(J,{vertical:!0,style:{gap:$.marginXS,minHeight:132,width:"100%"},children:[r.jsx($k,{value:e,placeholder:Ae,disabled:a,token:$,highlightSegments:Me,textAreaRef:T,highlightOverlayRef:D,onChange:t,onKeyDown:ue,onPaste:Ze,onScrollSync:X}),r.jsxs(J,{align:"center",justify:"space-between",gap:$.marginSM,children:[r.jsx(J,{align:"center",gap:$.marginXS,style:{minWidth:0,flex:1},children:r.jsx(Dk,{allowImages:c,disabled:a,isStreaming:j,token:$,fileInputRef:_,onFileInputChange:Bt,onFileReferenceButtonClick:x,extraControl:S})}),r.jsx(Fk,{allowRetry:P,hasMessages:C,isStreaming:j,disabled:a,onRetry:le,onCancel:M,onSubmit:ie,value:e,images:q,isOverCharLimit:Y,token:$,statusIndicator:h,submitButtonLabel:w})]})]})]}),r.jsx(Lk,{charCount:z,maxCharCount:b,isOverCharLimit:Y,isNearCharLimit:F,isProcessingAttachments:ge,token:$}),c&&r.jsx(_k,{visible:G,images:q,currentIndex:Pe,onClose:()=>be(!1)})]})},{Text:eh}=ce,{useToken:sj}=pe,nj=({text:e,onClose:t})=>{const{token:s}=sj(),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(H,{style:{width:"100%",justifyContent:"space-between",alignItems:"flex-start"},children:[r.jsxs("div",{style:{flex:1},children:[r.jsx(eh,{style:{fontSize:s.fontSizeSM,color:s.colorPrimary},children:"Referencing"}),r.jsx(eh,{style:{fontSize:s.fontSizeSM,color:s.colorTextSecondary,marginLeft:s.marginSM},ellipsis:!0,children:o})]}),r.jsx(U,{type:"text",size:"small",icon:r.jsx(wr,{}),onClick:t,style:{marginLeft:s.marginXS,color:s.colorTextSecondary,borderRadius:999}})]})})},rj=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 f=[...h,u].slice(-50);t.current.set(e,f),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 f=u.trim();if(d==="previous"){if(f.length>0&&n===null)return{value:null,applied:!1};const y=n??h.length,p=Math.max(0,y-1);return p===n?{value:null,applied:!1}:(o(p),s.current=!0,{value:h[p]??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}},Ln=class Ln{constructor(){Ye(this,"cache",null);Ye(this,"cacheTime",0);Ye(this,"CACHE_TTL",3e4)}static getInstance(){return Ln.instance||(Ln.instance=new Ln),Ln.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 we.get("commands");if(!Array.isArray(n.commands))throw new Error("Invalid command list response");return this.cache=n.commands,this.cacheTime=s,Ke("[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 we.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}};Ye(Ln,"instance");let Go=Ln;const Xn=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}},oj=({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 f=m.useCallback((j,C)=>{const P=j.trimStart(),v=`/${C}`;if(!P.startsWith(v))return!1;const M=P.charAt(v.length);return!M||/\s/.test(M)},[]),g=m.useCallback(()=>{h(null),t==null||t(null)},[t]),y=m.useCallback((j,C)=>{if(!f(j,C.name))return;const P=`/${C.name}`,M=j.trim().slice(P.length).trim(),E=[C.content,M].filter(Boolean).join(`
|
|
165
|
+
|
|
166
|
+
`);t==null||t({...C,content:E})},[f,t]),p=m.useCallback(j=>{s(),u&&!f(j,u.name)&&g(),u&&f(j,u.name)&&y(j,u),e(j)},[s,g,f,u,y,e]),x=m.useCallback(j=>{l(j.isTriggerActive),d(j.isTriggerActive?j.searchText:"")},[]),b=m.useCallback(async j=>{var $,I,O,A,z,L;l(!1);const P=(Y=>{var K;if(Y.type!=="mcp")return Y.name;const F=(K=Y.metadata)==null?void 0:K.originalName;if(typeof F=="string"&&F.trim())return F.trim();const q=Xn(Y.name);return q!=null&&q.toolName?q.toolName:Y.displayName||Y.name})(j),v=(I=($=o.current)==null?void 0:$.resizableTextArea)==null?void 0:I.textArea,M=(v==null?void 0:v.selectionStart)??a.length;let E,_;const T=a.substring(0,M).match(/\/([a-zA-Z0-9_-]*)$/);if(T){const Y=M-T[0].length,F=a.substring(0,Y),q=a.substring(M);E=`${F}/${P} ${q}`,_=`${F}/${P} `.length}else if(a.trim()==="")E=`/${P} `,_=E.length;else{const Y=a.substring(0,M),F=a.substring(M);E=`${Y}/${P} ${F}`,_=`${Y}/${P} `.length}if(e(E),setTimeout(()=>{v&&(v.selectionStart=_,v.selectionEnd=_,v.focus())},0),j.type!=="workflow"){const Y={id:`command-draft-${j.id}`,name:P,content:"",createdAt:new Date().toISOString(),type:j.type,displayName:j.displayName,mcpAlias:j.type==="mcp"?j.name:void 0,mcpServerId:j.type==="mcp"?(O=j.metadata)==null?void 0:O.serverId:void 0,mcpServerName:j.type==="mcp"?(A=j.metadata)==null?void 0:A.serverName:void 0,mcpOriginalName:j.type==="mcp"?(z=j.metadata)==null?void 0:z.originalName:void 0};h(Y),t==null||t(Y);return}const D=Go.getInstance();try{const Y=j.id.startsWith("workflow-")?j.id.slice(9):j.id,q=((L=(await D.getCommand(j.type,Y)).content)==null?void 0:L.trim())||"";if(q){const K={id:`command-draft-${j.id}`,name:j.name,content:q,createdAt:new Date().toISOString(),type:j.type,displayName:j.displayName};h(K),t==null||t(K)}else g()}catch(Y){console.error(`[InputContainer] Failed to apply command '${j.name}':`,Y),g()}},[g,t,e,a,o]),S=m.useCallback(async j=>{try{const v=(await Go.getInstance().listCommands()).find(M=>M.id===j.id&&M.type===j.type);if(!v){console.error(`[InputContainer] Command '${j.id}' of type '${j.type}' not found`),e(`/${j.name} `),g();return}await b(v)}catch(C){console.error(`[InputContainer] Failed to select command '${j.name}':`,C),e(`/${j.name} `),g()}},[b,g,e]),w=m.useCallback(()=>{l(!1)},[]),k=m.useCallback(async j=>{l(!1);try{const v=(await Go.getInstance().listCommands()).find(M=>M.name===j);v?await b(v):(console.error(`[InputContainer] Command '${j}' not found in auto-complete`),e(`/${j} `),g())}catch(C){console.error(`[InputContainer] Failed to load command '${j}' in auto-complete:`,C),e(`/${j} `),g()}},[b,g,e]);return{selectedCommand:u,showCommandSelector:i,commandSearchText:c,clearCommandDraft:g,matchesCommandToken:f,handleInputChange:p,handleCommandChange:x,handleCommandSelect:S,handleCommandSelectorCancel:w,handleAutoComplete:k,setShowCommandSelector:l}};class aj{constructor(t={}){Ye(this,"cache",null);Ye(this,"options");Ye(this,"validateWorkspacePath",this.validatePath.bind(this));Ye(this,"getRecentWorkspaces",this.getRecent.bind(this));Ye(this,"addRecentWorkspace",this.addRecent.bind(this));Ye(this,"removeRecentWorkspace",this.removeRecent.bind(this));Ye(this,"clearRecentWorkspaces",this.clearRecent.bind(this));Ye(this,"getWorkspaceSuggestions",this.getCombinedSuggestions.bind(this));Ye(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 we.post("workspace/validate",{path:t})}async getRecent(){var t;if(this.isCacheValid())return this.cache.recentWorkspaces;try{const s=await we.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 we.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 we.get("workspace/suggestions")}async browseFolder(t){return we.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 we.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 we.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 ij=new aj,lj=({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),[f,g]=m.useState(""),[y,p]=m.useState(!1),[x,b]=m.useState(""),[S,w]=m.useState(!1),[k,j]=m.useState(null),[C,P]=m.useState(!1),v=m.useRef(null);m.useEffect(()=>{y&&b((n==null?void 0:n.config.workspacePath)??"")},[y,n==null?void 0:n.config.workspacePath]),m.useEffect(()=>{h(!1),g(""),d([]),l(new Map),v.current=(n==null?void 0:n.config.workspacePath)??null},[s,n==null?void 0:n.config.workspacePath]);const M=m.useCallback(async(I,O)=>{w(!0),d([]),j(null);try{const A=await ij.listWorkspaceFiles(O);d(A),v.current=O}catch(A){console.error("Failed to load workspace files:",A),j(A instanceof Error?A.message:"Workspace file browsing is unavailable.")}finally{w(!1)}},[]),E=m.useCallback(I=>{if(g(I.searchText),!I.isTriggerActive){h(!1);return}if(!s||!n){h(!1);return}const O=n.config.workspacePath;if(!O){b(""),p(!0),h(!1);return}h(!0),(v.current!==O||c.length===0)&&M(s,O)},[n,s,M,c.length]),_=m.useCallback(I=>{const O=e.lastIndexOf("@");let A;O>=0&&e.substring(O).match(/^@[a-zA-Z0-9._\\-\\/\\\\]*$/)?A=`${e.slice(0,O)}@${I.name} `:A=e.trim()?`${e.trim()} @${I.name} `:`@${I.name} `,t(A),l(z=>{const L=new Map(z);return L.set(I.name,I),L}),h(!1),g("")},[e,t]),R=m.useCallback(()=>{h(!1)},[]),T=m.useCallback(()=>{if(!s||!n)return;const I=n.config.workspacePath;if(!I){b(""),p(!0),h(!1);return}g(""),h(!0),(v.current!==I||c.length===0)&&M(s,I)},[n,s,M,c.length]),D=m.useCallback(()=>{p(!1),b("")},[]),$=m.useCallback(async I=>{if(!n||!s)return;const O=I.trim();if(!O){a.error("Workspace path cannot be empty");return}P(!0);try{o(s,{config:{...n.config,workspacePath:O}}),p(!1),b(""),h(!1),j(null)}catch(A){const z=A instanceof Error?A.message:"Unable to save workspace path";a.error(z)}finally{P(!1)}},[n,s,a,o]);return{fileReferences:i,setFileReferences:l,workspaceFiles:c,showFileSelector:u,setShowFileSelector:h,fileSearchText:f,isWorkspaceLoading:S,workspaceError:k,isWorkspaceModalVisible:y,workspacePathInput:x,isSavingWorkspace:C,setWorkspacePathInput:b,setIsWorkspaceModalVisible:p,handleFileReferenceChange:E,handleFileReferenceSelect:_,handleFileSelectorCancel:R,handleFileReferenceButtonClick:T,handleWorkspaceModalCancel:D,handleWorkspaceModalSubmit:$,fetchWorkspaceFiles:M}},cj=()=>{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}},dj=({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:f})=>({handleSubmit:m.useCallback(async(y,p)=>{const x=y.trim(),b=Jk(e),S=(t==null?void 0:t.trim())??"";let w=x,k;if(s!=null&&s.content&&s.type==="workflow"){const C=`/${s.name}`;if(n(x,s.name)){const v=x.slice(C.length).trim();w=[s.content,v].filter(Boolean).join(`
|
|
167
|
+
|
|
168
|
+
`)}}else if((s==null?void 0:s.type)==="skill"){const C=`/${s.name}`;if(n(x,s.name)){const v=x.slice(C.length).trim();w=[`[User explicitly selected skill: ${s.displayName||s.name} (ID: ${s.name})]`,v].filter(Boolean).join(`
|
|
169
|
+
|
|
170
|
+
`),k=[s.name]}}else if((s==null?void 0:s.type)==="mcp"){const C=`/${s.name}`;if(n(x,s.name)){const v=x.slice(C.length).trim();w=[`[User explicitly selected MCP tool: ${s.mcpAlias||s.displayName||s.name}]`,v].filter(Boolean).join(`
|
|
171
|
+
|
|
172
|
+
`)}}if(!w&&!b&&(!p||p.length===0))return;const j=[S,w,b].filter(Boolean).join(`
|
|
173
|
+
|
|
174
|
+
`);if(l(j),d(""),c(),o.size>0){const C=Array.from(j.matchAll(/@([^\\s]+)/g));if(C.length>0){const P=[];for(const v of C){const M=v[1],E=o.get(M);E&&P.push(E)}if(P.length>0){const v=JSON.stringify({type:"file_reference",paths:P.map(M=>M.path),display_text:j});await i(v,p,a,k)}else await i(j,p,a,k)}else await i(j,p,a,k)}else await i(j,p,a,k);u(null),h([]),f(new Map)},[e,c,o,n,l,a,s,i,h,d,f,u,t])}),uj=({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}},mj=({referenceText:e,isToolSpecificMode:t,isRestrictConversation:s,allowedTools:n,autoToolPrefix:o,t:a})=>a(e?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows"),Lc="chat-toggle-batch-export-selection",Oc="chat-focus-input",hr="chat-pending-question-resolved",hj=m.lazy(()=>Ft(()=>import("./index-Cd0gm8C7.js"),__vite__mapDeps([8,1,2,3]),import.meta.url)),pj=m.lazy(()=>Ft(()=>import("./index-Bd-pro36.js"),__vite__mapDeps([9,1,2,3,4,5,6,7,10]),import.meta.url)),fj=m.lazy(()=>Ft(()=>import("./index-BAfth62E.js"),__vite__mapDeps([11,1,2,3,4,5,6,7]),import.meta.url)),gj=m.lazy(()=>Ft(()=>import("./index-oVXhS3BO.js"),__vite__mapDeps([12,1,2,3]),import.meta.url)),{useToken:yj}=pe,th="chat-send-message",sh="reference-text",xj="chat-model-options-cache-v1",bj=24*60*60*1e3,vj=["low","medium","high","xhigh","max"],Sj=[],vy=e=>`${xj}:${e}`,wj=e=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(vy(e));if(!t)return null;const s=JSON.parse(t);return!s||!Array.isArray(s.options)||Date.now()-s.timestamp>bj?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}},_j=(e,t)=>{if(!(typeof window>"u"))try{const s={timestamp:Date.now(),options:t};localStorage.setItem(vy(e),JSON.stringify(s))}catch{}},Tj=({sessionId:e,onWorkflowDraftChange:t,statusIndicator:s})=>{var Yd;const{t:n}=se(),o=m.useRef(null),{token:a}=yj(),i=pn(te=>te.open),l=N(te=>e??te.currentSessionId),c=N(te=>te.currentSessionId),d=N(Vn(l)),u=(d==null?void 0:d.messages)||[],h=N(te=>te.addMessage),f=N(te=>te.updateSession),g=N(te=>te.processingChats),y=N(te=>te.setSessionProcessing),p=N(te=>te.pendingQuestionRespond),x=N(te=>te.clearPendingQuestionRespondForSession),b=zi(l),S=N(te=>l?te.inputStates[l]:void 0),w=N(te=>te.setInputContent),k=N(te=>te.setReferenceText),j=N(te=>te.setInputReasoningEffort),C=Yt(te=>te.currentProvider),P=Yt(te=>te.providerConfig),[v,M]=m.useState([]),[E,_]=m.useState(!1),[R,T]=m.useState(null),[D,$]=m.useState(!1),I=(S==null?void 0:S.content)||"",O=(S==null?void 0:S.referenceText)||null,A=m.useMemo(()=>{var te;return(te=P.providers[C])==null?void 0:te.reasoning_effort},[P,C]),z=m.useMemo(()=>l?ld(l):void 0,[l]),L=((Yd=d==null?void 0:d.config)==null?void 0:Yd.reasoningEffort)??(S==null?void 0:S.reasoningEffort)??z??A??"medium",Y=m.useCallback(te=>{l&&w(l,te)},[l,w]),F=m.useCallback(te=>{l&&k(l,te)},[l,k]),q=m.useCallback(async te=>{if(l&&(j(l,te),!!d))try{await Un.patchSession(l,{reasoning_effort:te}),f(l,{config:{...d.config,reasoningEffort:te}})}catch(We){console.warn("[InputContainer] Failed to persist reasoning effort:",We)}},[d,l,j,f]),K=l?g.has(l):!1,{sendMessage:G,retryLastTurn:be,cancel:Pe}=ry({sessionId:l,addMessage:h,setSessionProcessing:y,updateSession:f});m.useEffect(()=>{if(typeof window>"u")return;const te=lt=>lt?l===lt:l!==null&&l===c,We=lt=>{const Ue=lt;if(!Ue.detail||typeof Ue.detail.text!="string")return;const ks=typeof Ue.detail.sessionId=="string"?Ue.detail.sessionId:null;if(!te(ks))return;const sn=Ue.detail.text.trim();sn&&(Ue.detail.handled=!0,F(sn),requestAnimationFrame(()=>{var js;(js=o.current)==null||js.focus()}))},Ge=lt=>{var sn;const Ue=lt,ks=typeof((sn=Ue.detail)==null?void 0:sn.sessionId)=="string"?Ue.detail.sessionId:null;te(ks)&&(Ue.detail&&(Ue.detail.handled=!0),requestAnimationFrame(()=>{var js;(js=o.current)==null||js.focus()}))};return window.addEventListener(sh,We),window.addEventListener(Oc,Ge),()=>{window.removeEventListener(sh,We),window.removeEventListener(Oc,Ge)}},[c,l,F]);const Ee=K,{message:Te}=us.useApp(),ge=!1,je=!1,Be=Sj,Qe=void 0,{recordEntry:jt,navigate:Ze,acknowledgeManualInput:Bt}=rj(l),{attachments:B,setAttachments:Me,handleAttachmentsAdded:X,handleAttachmentRemove:ue,handleClearAttachments:ie}=cj(),le=oj({setContent:Y,onWorkflowDraftChange:t,acknowledgeManualInput:Bt,currentSessionId:l,textAreaRef:o,content:I}),Ae=lj({content:I,setContent:Y,currentSessionId:l,currentChat:d,updateSession:f,messageApi:Te}),{setShowFileSelector:Et}=Ae;m.useEffect(()=>{le.showCommandSelector&&Et(!1)},[le.showCommandSelector,Et]);const{handleSubmit:Ct}=dj({attachments:B,referenceText:O,selectedWorkflow:le.selectedCommand,matchesWorkflowToken:le.matchesCommandToken,fileReferences:Ae.fileReferences,reasoningEffort:L,sendMessage:G,recordEntry:jt,clearWorkflowDraft:le.clearCommandDraft,setContent:Y,setReferenceText:F,setAttachments:Me,setFileReferences:Ae.setFileReferences}),it=p&&p.sessionId===l?p:null,bt=!!it,st=(it==null?void 0:it.options)||[],vt=(it==null?void 0:it.allowCustom)??!0,Xt=m.useCallback(te=>{if(!te)return!1;const We=N.getState().pendingQuestionRespond;return(We==null?void 0:We.sessionId)===te},[]),Ls=m.useCallback(async te=>{const We=te.trim();if(!We||!l)return;const Ge=N.getState().pendingQuestionRespond,lt=(Ge==null?void 0:Ge.sessionId)===l?Ge:null;if(lt&&!lt.allowCustom&<.options.length>0&&!lt.options.includes(We)){Te.warning(n("components.questionDialog.selectOptionWarning"));return}try{const Ue=await ye.post(`respond/${l}`,{response:We,reasoning_effort:L});Te.success(n("components.questionDialog.responseSubmittedContinue")),Y(""),x(l),typeof window<"u"&&window.dispatchEvent(new CustomEvent(hr,{detail:{sessionId:l}}));const ks=Ue==null?void 0:Ue.auto_resume_status;ks&&["started","already_running"].includes(ks)&&y(l,!0)}catch(Ue){console.error("[InputContainer] Failed to submit respond:",Ue),Te.error(Ue instanceof Error?Ue.message:n("components.questionDialog.submitFailed"))}},[l,L,Te,Y,x,y,n]),Mt=m.useCallback(async(te,We)=>{if(Xt(l)){await Ls(te);return}await Ct(te,We)},[l,Xt,Ls,Ct]),ms=m.useCallback(async(te,We)=>{await Mt(te,We)},[Mt]);m.useEffect(()=>{if(typeof window>"u")return;const te=We=>{var sn,js,Xd;const Ge=We;if(!Ge.detail)return;const lt=typeof Ge.detail.sessionId=="string"?Ge.detail.sessionId:null;if(!(lt?l===lt:l!==null&&l===c))return;Ge.detail.handled=!0;const ks=(sn=Ge.detail)==null?void 0:sn.content;if(typeof ks!="string"||ks.trim().length===0){(Xd=(js=Ge.detail)==null?void 0:js.reject)==null||Xd.call(js,new Error("External send message content is empty"));return}Mt(ks,void 0).then(()=>{var Kn,vn;(vn=(Kn=Ge.detail)==null?void 0:Kn.resolve)==null||vn.call(Kn)}).catch(Kn=>{var vn,Vd;(Vd=(vn=Ge.detail)==null?void 0:vn.reject)==null||Vd.call(vn,Kn)})};return window.addEventListener(th,te),()=>{window.removeEventListener(th,te)}},[c,l,Mt]);const{retryLastMessage:hs,handleHistoryNavigate:tn}=uj({currentSessionId:l,currentChat:d,currentMessages:u,reasoningEffort:L,retryLastTurn:be,navigate:Ze}),V=()=>F(null),Q=m.useMemo(()=>P.providers[C],[P,C]),de=m.useMemo(()=>!Q||typeof Q!="object"?!1:C==="copilot"?Object.keys(Q).length>0:"api_key"in Q?typeof Q.api_key=="string"&&Q.api_key.trim().length>0:!1,[C,Q]),ae=m.useCallback(()=>de?!1:(i("chat"),Te.warning("Please configure provider first"),!0),[de,Te,i]);m.useEffect(()=>{const te=wj(C);M(te??[]),T(null)},[C]);const Re=m.useCallback(te=>te instanceof Error&&te.message.trim()?te.message:"Unknown error",[]),Xe=m.useMemo(()=>({openai:[...Ac],anthropic:[...Ic],gemini:[...$c],copilot:[...fy]})[C]||[],[C]),rt=m.useMemo(()=>{const We=[...v.length>0?v:Xe];return b&&!We.some(Ge=>Ge.value===b)&&We.unshift({value:b,label:b}),We},[v,Xe,b]),ps=m.useCallback(async(te,We)=>{if(!(!(We!=null&&We.force)&&v.length>0))try{_(!0),T(null);const lt=(te==="copilot"?await Ri.getModels():Xe).map(Ue=>({value:typeof Ue=="string"?Ue:Ue.value,label:typeof Ue=="string"?Ue:Ue.label}));M(lt),_j(te,lt)}catch(Ge){T(Re(Ge))}finally{_(!1)}},[Xe,Re,v.length]),ne=m.useCallback(te=>{te&&(ae()||E||v.length>0||ps(C))},[C,ps,E,v.length,ae]),Ce=m.useCallback(async te=>{var We,Ge,lt;if(!(!te||te===b)&&!D)try{if(ae())return;if($(!0),!l||!d){l&&f(l,{config:{systemPromptId:((We=d==null?void 0:d.config)==null?void 0:We.systemPromptId)||"default",baseSystemPrompt:((Ge=d==null?void 0:d.config)==null?void 0:Ge.baseSystemPrompt)||"",lastUsedEnhancedPrompt:((lt=d==null?void 0:d.config)==null?void 0:lt.lastUsedEnhancedPrompt)??null,...(d==null?void 0:d.config)||{},model:te}});return}await Un.patchSession(l,{model:te}),f(l,{config:{...d.config,model:te}}),Te.success(n("settings.providerTab.modelUpdated"))}catch(Ue){Te.error(`${n("settings.providerTab.updateModelErrorPrefix")}: ${Re(Ue)}`)}finally{$(!1)}},[b,d,Re,D,Te,ae,l,n,f]),De=m.useMemo(()=>mj({referenceText:O,isToolSpecificMode:ge,isRestrictConversation:je,allowedTools:Be,autoToolPrefix:Qe,t:n}),[O,ge,je,Be,Qe,n]),He=bt&&vt?n("chat.respond.customAnswerPlaceholder"):bt?n("components.questionDialog.selectOptionWarning"):De,Rt=bt?n("chat.respond.submitToolResult","Submit tool result"):void 0,Os=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]),zs=m.useMemo(()=>Os[L]??L,[L,Os]),fs=r.jsx(fr,{trigger:["click"],placement:"topLeft",disabled:!b||Ee,menu:{selectable:!0,selectedKeys:[L],items:vj.map(te=>({key:te,label:Os[te]})),onClick:({key:te})=>{q(te)}},children:r.jsx(U,{type:"text",size:"small",disabled:!b||Ee,style:{minWidth:88,padding:"0 12px",height:36,borderRadius:18,color:L==="medium"?a.colorTextSecondary:a.colorPrimary},title:n("chat.input.reasoningTitle",{label:zs}),children:r.jsxs(H,{size:6,children:[r.jsx(Kp,{}),r.jsx("span",{children:zs}),r.jsx(cs,{style:{fontSize:10}})]})})}),Ts=b||n(de?"chat.model.selectModel":"chat.model.configureProvider"),Ns=m.useMemo(()=>rt.length>0?rt.map(te=>({key:te.value,label:te.label})):[{key:"__no_models__",label:R||n("chat.model.noModelsAvailable"),disabled:!0}],[rt,R,n]),Bs=r.jsx(U,{type:"text",size:"small",disabled:Ee||D,onClick:()=>{de||ae()},style:{minWidth:146,padding:"0 12px",height:36,borderRadius:18,color:R?a.colorError:a.colorTextSecondary},title:Ts,children:r.jsxs(H,{size:6,children:[E?r.jsx(ra,{}):r.jsx(Qc,{}),r.jsx("span",{style:{maxWidth:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Ts}),r.jsx(cs,{style:{fontSize:10}})]})}),Rx=de?r.jsx(fr,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:b?[b]:[],items:Ns,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:te})=>{te!=="__no_models__"&&Ce(String(te))}},onOpenChange:ne,disabled:Ee||D,children:Bs}):Bs;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:[!b&&r.jsx(Ne,{type:"warning",showIcon:!0,icon:r.jsx(ji,{}),message:n(de?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:n(de?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:de?void 0:r.jsx(H,{children:r.jsx("a",{onClick:()=>i("chat"),children:n("chat.model.openSettings")})}),style:{marginBottom:a.marginSM}}),ge,O&&r.jsx(nj,{text:O,onClose:V}),B.length>0&&r.jsx(m.Suspense,{fallback:r.jsx(ht,{size:"small"}),children:r.jsx(hj,{files:B,onRemove:ue,onClear:ie})}),bt&&st.length>0&&r.jsx("div",{style:{marginBottom:a.marginSM},children:r.jsx(H,{wrap:!0,size:[8,8],children:st.map(te=>r.jsx(U,{size:"small",onClick:()=>{Ls(te)},disabled:Ee,children:te},te))})}),r.jsx(tj,{value:I,onChange:le.handleInputChange,onSubmit:ms,placeholder:He,allowImages:!0,disabled:!b||bt&&!vt&&st.length>0,statusIndicator:s,submitButtonLabel:Rt,isWorkflowSelectorVisible:le.showCommandSelector,textAreaRef:o,validateMessage:te=>({isValid:!0}),onAttachmentsAdded:X,onWorkflowCommandChange:le.handleCommandChange,onFileReferenceChange:Ae.handleFileReferenceChange,onFileReferenceButtonClick:Ae.handleFileReferenceButtonClick,leftControlsExtra:r.jsxs(H,{size:0,wrap:!0,children:[Rx,fs]}),interaction:{isStreaming:Ee,hasMessages:u.some(te=>te.role==="user"),allowRetry:!0,onRetry:hs,onCancel:Pe,onHistoryNavigate:tn}}),r.jsx(m.Suspense,{fallback:null,children:r.jsx(pj,{visible:le.showCommandSelector,onSelect:le.handleCommandSelect,onCancel:le.handleCommandSelectorCancel,onAutoComplete:le.handleAutoComplete,searchText:le.commandSearchText})}),Ae.showFileSelector&&r.jsx(m.Suspense,{fallback:r.jsx(ht,{size:"small"}),children:r.jsx(gj,{visible:Ae.showFileSelector,files:Ae.workspaceFiles,searchText:Ae.fileSearchText,loading:Ae.isWorkspaceLoading,error:Ae.workspaceError,onSelect:Ae.handleFileReferenceSelect,onCancel:Ae.handleFileSelectorCancel,onChangeWorkspace:()=>{Ae.setWorkspacePathInput((d==null?void 0:d.config.workspacePath)??""),Ae.setIsWorkspaceModalVisible(!0)}})}),r.jsx(m.Suspense,{fallback:null,children:r.jsx(fj,{open:Ae.isWorkspaceModalVisible,initialPath:Ae.workspacePathInput,loading:Ae.isSavingWorkspace,onSubmit:Ae.handleWorkspaceModalSubmit,onCancel:Ae.handleWorkspaceModalCancel})})]})},{Text:Ys}=ce,kj=220,jj="chat-session-diff-collapse:",Cj=e=>e.split(/[\\/]/).pop()||e,Sy=e=>`${jj}${e??"default"}`,jl=e=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Sy(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}},Mj=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Sy(e),JSON.stringify(t))}catch{}},Pj=({sessionDiffSummary:e,sessionId:t})=>{const{token:s}=pe.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=jl(t))==null?void 0:y.isExpanded)??!0}),[u,h]=m.useState(()=>{var y;return new Set(((y=jl(t))==null?void 0:y.expandedFiles)??[])});m.useEffect(()=>{if(n){a(!0);const p=window.setTimeout(()=>l(!0),0);return()=>window.clearTimeout(p)}l(!1);const y=window.setTimeout(()=>a(!1),kj);return()=>window.clearTimeout(y)},[n]);const f=m.useMemo(()=>e?e.files:[],[e]),g=m.useMemo(()=>{const y=new Map;return e&&e.files.forEach(p=>{y.set(p.filePath,dy(p.unifiedDiff))}),y},[e]);return m.useEffect(()=>{const y=jl(t);d((y==null?void 0:y.isExpanded)??!0),h(new Set((y==null?void 0:y.expandedFiles)??[]))},[t]),m.useEffect(()=>{Mj(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(p=>p.filePath));h(p=>{const x=new Set;let b=!1;return p.forEach(S=>{y.has(S)?x.add(S):b=!0}),!b&&x.size===p.size?p:x})},[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(H,{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(Gp,{style:{color:s.colorPrimary}}),r.jsx(Ys,{strong:!0,style:{whiteSpace:"nowrap"},children:"Session diffs"}),r.jsxs(Ys,{type:"secondary",style:{fontSize:s.fontSizeSM,whiteSpace:"nowrap"},children:["(",e.files.length," files / ",e.changedTools," tools)"]}),r.jsxs(H,{size:4,style:{marginInlineStart:s.marginXS},children:[r.jsxs(Ys,{style:{color:s.colorSuccess,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",e.totalAdded]}),r.jsxs(Ys,{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(cs,{}):r.jsx(Ks,{})})]}),c&&r.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr",gap:6,maxHeight:280,overflowY:"auto"},"data-testid":"session-diff-file-list",children:f.map(y=>{const p=u.has(y.filePath),x=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 S=new Set(b);return S.has(y.filePath)?S.delete(y.filePath):S.add(y.filePath),S})},"data-testid":"session-diff-file-header","data-file-path":y.filePath,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.marginXS,minWidth:0,flex:1},children:[r.jsx("span",{style:{color:s.colorTextSecondary},children:p?r.jsx(cs,{}):r.jsx(Ks,{})}),r.jsx(Ys,{ellipsis:{tooltip:y.filePath},style:{flex:1,minWidth:0,fontSize:s.fontSizeSM},children:Cj(y.filePath)})]}),r.jsxs(H,{size:4,children:[r.jsxs(Ys,{style:{color:s.colorSuccess,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",y.added]}),r.jsxs(Ys,{style:{color:s.colorError,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",y.removed]})]})]}),p&&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:[x.length>0?x.map((b,S)=>{const w={margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:s.fontSizeSM,lineHeight:1.5,padding:"0 8px",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"};return b.kind==="add"?w.background=s.colorSuccessBg:b.kind==="remove"?w.background=s.colorErrorBg:b.kind==="modified_add"?(w.background=s.colorWarningBg,w.borderLeft=`3px solid ${s.colorSuccess}`):b.kind==="modified_remove"?(w.background=s.colorWarningBg,w.borderLeft=`3px solid ${s.colorError}`):b.kind==="hunk"?(w.background=s.colorFillSecondary,w.color=s.colorTextSecondary):b.kind==="meta"&&(w.background=s.colorFillTertiary,w.color=s.colorTextSecondary),r.jsx("pre",{style:w,"data-testid":"session-diff-line","data-kind":b.kind,children:b.text||" "},`${y.filePath}-${S}`)}):r.jsx(Ys,{type:"secondary",style:{display:"block",padding:"8px",fontSize:s.fontSizeSM},children:"No diff preview available."}),y.truncated&&r.jsx(Ys,{type:"secondary",style:{display:"block",padding:"6px 8px 8px",fontSize:s.fontSizeSM},children:"Diff truncated for display."})]})]},y.filePath)})})]})})})},Ej=e=>{if(!e)return;const{activeLeafId:t,setLeafSessionId:s,setActiveLeafId:n}=$e.getState();s(t,e),n(t),N.getState().selectSession(e)},Rj=["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(" "),Aj=["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(" "),Ij=["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(" "),$j=["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(" "),Dj=["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(" "),Fj=["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(" "),Lj=["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(" "),Oj=["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(" "),zj=["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(" "),Nj=["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(" "),Bj=["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(" "),Wj=["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(" "),Uj=["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(" "),qj=["development","debugging","analysis","documentation","operations"],Hj={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"}},Yj=(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)||""}},wy=({sessionId:e=null,embedded:t=!1,hideHeader:s=!1,layoutMode:n="default"})=>{var _;const{t:o}=se(),{token:a}=pe.useToken(),{message:i}=us.useApp(),l=N(R=>e??R.currentSessionId),c=N(Vn(l)),d=N(R=>R.addChat),u=N(R=>R.lastSelectedPromptId),h=N(R=>R.setInputContent),f=N(R=>R.systemPrompts),g=N(R=>R.chats),[y,p]=m.useState(null),[x,b]=m.useState(""),S=(c==null?void 0:c.config.workspacePath)??((_=g.find(R=>R.config.workspacePath))==null?void 0:_.config.workspacePath),w=m.useMemo(()=>[{id:"blank",icon:r.jsx(Gs,{}),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(Pi,{}),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:Rj,category:"development",recommendWorkspace:!0},{id:"implementFeature",icon:r.jsx(vr,{}),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:Ij,category:"development",recommendWorkspace:!0},{id:"refactor",icon:r.jsx(Gp,{}),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:Lj,category:"development",recommendWorkspace:!0},{id:"bugInvestigation",icon:r.jsx(Vp,{}),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:Aj,category:"debugging",recommendWorkspace:!0},{id:"explainError",icon:r.jsx(Jp,{}),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:Dj,category:"debugging"},{id:"tokenUsage",icon:r.jsx(tb,{}),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:Uj,category:"debugging"},{id:"architectureReview",icon:r.jsx(sb,{}),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:$j,category:"analysis",recommendWorkspace:!0},{id:"compareFiles",icon:r.jsx(nb,{}),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:Fj,category:"analysis",recommendWorkspace:!0},{id:"releaseNotes",icon:r.jsx(yr,{}),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:Oj,category:"documentation",recommendWorkspace:!0},{id:"summarizeWork",icon:r.jsx(rb,{}),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:zj,category:"documentation"},{id:"writeDocs",icon:r.jsx(yr,{}),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:Nj,category:"documentation",recommendWorkspace:!0},{id:"createSchedule",icon:r.jsx(Zs,{}),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:Bj,category:"operations"},{id:"sessionReview",icon:r.jsx(Qo,{}),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:Wj,category:"operations"}],[o]),k=x.trim().toLowerCase(),j=m.useMemo(()=>k?w.filter(R=>R.title.toLowerCase().includes(k)||R.description.toLowerCase().includes(k)):w,[k,w]),C=m.useMemo(()=>{const R={};for(const T of j)R[T.category]||(R[T.category]=[]),R[T.category].push(T);return R},[j]),P=m.useCallback(R=>{typeof window>"u"||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent(Oc,{detail:{sessionId:R}}))},0)},[]),v=m.useCallback(async R=>{if(!y){p(R.id);try{const T=Yj(f,u),D=await d({title:R.sessionTitle,createdAt:Date.now(),messages:[],config:{systemPromptId:T.systemPromptId,baseSystemPrompt:R.baseSystemPrompt??T.baseSystemPrompt,lastUsedEnhancedPrompt:null,...S?{workspacePath:S}:{}},currentInteraction:null});Ej(D),R.prefill.trim().length>0&&h(D,R.prefill),P(D)}catch(T){console.error("[EmptyTaskLauncher] Failed to create session",T),i.error(T instanceof Error?T.message:o("chat.emptyLauncher.errors.createFailed","Failed to create session"))}finally{p(null)}}},[d,u,i,y,P,h,f,o,S]),M=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]),E=!!S;return r.jsxs("div",{className:`lotus-empty-task-launcher ${t?"is-embedded":""} ${s?"is-headerless":""} ${n==="staggered"?"is-staggered":""}`,style:M,children:[!s&&r.jsxs("div",{className:"lotus-empty-task-launcher__header",children:[r.jsx(ce.Title,{level:t?4:3,style:{margin:0},children:o("chat.emptyLauncher.title","Start with a task")}),r.jsx(ce.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(ce.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(he,{placeholder:o("chat.emptyLauncher.searchPlaceholder","Search templates..."),prefix:r.jsx(Qo,{style:{color:a.colorTextQuaternary}}),value:x,onChange:R=>b(R.target.value),allowClear:!0,size:"middle",variant:"filled"})}),r.jsxs("div",{className:"lotus-empty-task-launcher__categories",children:[qj.map(R=>{const T=C[R];if(!T||T.length===0)return null;const D=Hj[R];return r.jsxs("div",{className:"lotus-empty-task-launcher__category",children:[r.jsx(ce.Text,{type:"secondary",className:"lotus-empty-task-launcher__category-label",children:o(D.titleKey,D.fallback)}),r.jsx("div",{className:"lotus-empty-task-launcher__grid",children:T.map($=>{const I=y===$.id,O=$.recommendWorkspace&&E;return r.jsxs("button",{type:"button",className:"lotus-empty-task-card",onClick:()=>{v($)},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(ra,{}):$.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(ob,{className:"lotus-empty-task-card__arrow","aria-hidden":!0})]}),r.jsx("p",{className:"lotus-empty-task-card__description",children:$.description}),O&&r.jsx("div",{className:"lotus-empty-task-card__badges",children:r.jsxs("span",{className:"lotus-empty-task-card__badge",title:S,children:["📂 ",o("chat.emptyLauncher.badges.workspace","workspace")]})})]})]},$.id)})})]},R)}),j.length===0&&r.jsx("div",{className:"lotus-empty-task-launcher__no-results",children:r.jsx(ce.Text,{type:"secondary",children:o("chat.emptyLauncher.noResults","No templates match your search. Try a different keyword or start a blank session.")})})]})]})},Xj=({sessionId:e,isCenteredLayout:t,maxWidth:s,onWorkflowDraftChange:n,showMessagesView:o,sessionDiffSummary:a,contextUsageIndicator:i})=>r.jsx(J,{justify:"center",className:`chat-view-input-container-wrapper ${o?"messages-view":"centered-view"}`,children:r.jsxs("div",{style:{width:"100%",maxWidth:o?"clamp(720px, 68vw, 1240px)":s,margin:o?"0 auto":void 0,position:"relative",paddingBottom:o?12:0,display:"flex",flexDirection:"column",gap:o?0:24},children:[o&&r.jsx(Pj,{sessionDiffSummary:a,sessionId:e}),!o&&e&&r.jsx(wy,{sessionId:e}),r.jsx(Tj,{sessionId:e,isCenteredLayout:t,onWorkflowDraftChange:n,statusIndicator:i})]})});function sr(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,p)=>n[p]!==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,p=Math.round((Date.now()-g)*100)/100,x=p/16,b=(S,w)=>{for(S=String(S);S.length<w;)S=" "+S;return S};console.info(`%c⏱ ${b(p,5)} /${b(y,5)} ms`,`
|
|
175
|
+
font-size: .6rem;
|
|
176
|
+
font-weight: bold;
|
|
177
|
+
color: hsl(${Math.max(0,Math.min(120-120*x,120))}deg 100% 31%);`,s==null?void 0:s.key)}return(d=s==null?void 0:s.onChange)==null||d.call(s,o),o}return a.updateDeps=i=>{n=i},a}function nh(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const Vj=(e,t)=>Math.abs(e-t)<1.01,Kj=(e,t,s)=>{let n;return function(...o){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,o),s)}},rh=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},Gj=e=>e,Jj=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},Qj=(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(rh(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(rh(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(s,{box:"border-box"}),()=>{a.unobserve(s)}},oh={passive:!0},ah=typeof window>"u"?!0:"onscrollend"in window,Zj=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;let o=0;const a=e.options.useScrollendEvent&&ah?()=>{}:Kj(n,()=>{t(o,!1)},e.options.isScrollingResetDelay),i=u=>()=>{const{horizontal:h,isRtl:f}=e.options;o=h?s.scrollLeft*(f&&-1||1):s.scrollTop,a(),t(o,u)},l=i(!0),c=i(!1);c(),s.addEventListener("scroll",l,oh);const d=e.options.useScrollendEvent&&ah;return d&&s.addEventListener("scrollend",c,oh),()=>{s.removeEventListener("scroll",l),d&&s.removeEventListener("scrollend",c)}},eC=(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"]},tC=(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 sC{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:Gj,rangeExtractor:Jj,onChange:()=>{},measureElement:eC,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=sr(()=>(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=sr(()=>[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=sr(()=>[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),f=this.options.lanes===1?d[u-1]:this.getFurthestMeasurement(d,u),g=f?f.end+this.options.gap:n+o,y=l.get(h),p=typeof y=="number"?y:this.options.estimateSize(u),x=g+p,b=f?f.lane:u%this.options.lanes;d[u]={index:u,start:g,size:p,end:x,key:h,lane:b}}return this.measurementsCache=d,d},{key:!1,debug:()=>this.options.debug}),this.calculateRange=sr(()=>[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=sr(()=>{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=sr(()=>[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 nh(n[_y(0,n.length-1,o=>nh(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,f]=u;this._scrollToOffset(h,{adjustments:void 0,behavior:o}),this.targetWindow.requestAnimationFrame(()=>{const g=this.getScrollOffset(),y=this.getOffsetForIndex(s,f);if(!y){console.warn("Failed to get offset for index:",s);return}Vj(y[0],g)||c(f)})},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 _y=(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=_y(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 ih=typeof document<"u"?m.useLayoutEffect:m.useEffect;function rC(e){const t=m.useReducer(()=>({}),{})[1],s={...e,onChange:(o,a)=>{var i;a?ab.flushSync(t):t(),(i=e.onChange)==null||i.call(e,o,a)}},[n]=m.useState(()=>new sC(s));return n.setOptions(s),ih(()=>n._didMount(),[]),ih(()=>n._willUpdate()),n}function oC(e){return rC({observeElementRect:Qj,observeElementOffset:Zj,scrollToFn:tC,...e})}const{Text:lh,Paragraph:aC}=ce,iC=({content:e,token:t,headingColor:s})=>r.jsx(vs,{components:{p:({children:n})=>r.jsx(aC,{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(lh,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block",color:s},children:n}),h2:({children:n})=>r.jsx(lh,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block",color:s},children:n})},children:e}),ch=m.memo(iC),lC=e=>{if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null},cC=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=lC(n);return o?[{key:s,content:o}]:[]}):[],dC=({currentChat:e,message:t,systemPrompts:s})=>{var E;const[n,o]=m.useState(null),[a,i]=m.useState(null),[l,c]=m.useState(null),[d,u]=m.useState(!1),[h,f]=m.useState(!1),g=m.useMemo(()=>li.getInstance(),[]),y=m.useMemo(()=>Ss.getInstance(),[]),p=t.role==="system"&&typeof t.content=="string"?t.content:"",x=t.role==="system"&&!t.id.startsWith("system-prompt-")&&p.trim().length>0;m.useEffect(()=>{t.role==="system"&&(i(null),c(null),f(!1))},[t.id,t.role,p]);const b=(e==null?void 0:e.id)??null,S=((E=e==null?void 0:e.config)==null?void 0:E.systemPromptId)??null,w=m.useMemo(()=>S?s.find(_=>_.id===S)??null:null,[S,s]),k=(w==null?void 0:w.content)??(n==null?void 0:n.content)??"",j=(w==null?void 0:w.description)??(n==null?void 0:n.description)??"",C=m.useRef(null);m.useEffect(()=>{o(null),C.current=null},[b,S]),m.useEffect(()=>{if(!S)return;const _=S;if(w!=null&&w.content)return;const R=`${b??"no-chat"}:${_}`;if(C.current===R)return;C.current=R;let T=!1;return(async()=>{try{const $=await g.findPresetById(_);if(T)return;const I=$?{content:$.content,description:$.description}:null;o(O=>!O&&!I||O&&I&&O.content===I.content&&O.description===I.description?O:I)}catch($){console.error("Failed to load preset prompt:",$)}})(),()=>{T=!0}},[b,S,g,w==null?void 0:w.content]);const P=m.useCallback(async()=>{var _;if(!d){u(!0);try{if(b)try{const R=await y.getSessionSystemPrompt(b);c(R);const T=(_=R.effective_system_prompt)==null?void 0:_.trim();if(T){i(T),f(!0);return}}catch(R){console.warn("Failed to load backend prompt snapshot:",R)}if(x){c(null),i(p),f(!0);return}console.warn("Enhanced prompt snapshot unavailable; keeping base prompt view.")}catch(R){console.error("Failed to load enhanced prompt:",R)}finally{u(!1)}}},[y,b,x,d,p]),v=m.useMemo(()=>h&&a?a:k||j||(t.role==="system"?p:"System prompt is being prepared..."),[h,a,k,j,t.role,p]),M=m.useMemo(()=>cC(l),[l]);return{basePrompt:k,categoryDescription:j,enhancedPrompt:a,loadingEnhanced:d,loadEnhancedPrompt:P,promptSnapshot:l,promptToDisplay:v,showEnhanced:h,setShowEnhanced:f,snapshotSections:M,systemMessageContent:p}},{Text:dh}=ce,{useToken:uC}=pe,mC=(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],hC=({currentChat:e,message:t})=>{const{token:s}=uC(),{t:n}=se(),o=N(y=>y.systemPrompts),{basePrompt:a,loadingEnhanced:i,loadEnhancedPrompt:l,promptSnapshot:c,promptToDisplay:d,showEnhanced:u,setShowEnhanced:h,snapshotSections:f}=dC({currentChat:e,message:t,systemPrompts:o}),g=m.useCallback(async y=>{try{await ds(y)}catch(p){console.error("Failed to copy text:",p)}},[]);return r.jsx(ee,{style:{width:"100%",maxWidth:"100%",background:s.colorBgContainer,borderRadius:s.borderRadiusLG,boxShadow:"none"},children:r.jsxs(H,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[r.jsxs(J,{justify:"space-between",align:"center",children:[r.jsx(J,{align:"center",gap:s.marginXS,children:r.jsx(dh,{type:"secondary",strong:!0,style:{fontSize:s.fontSizeSM},children:n("chat.prompt.systemCard.title")})}),r.jsxs(H,{children:[a&&!u?r.jsx(U,{type:"text",size:"small",icon:r.jsx(Vc,{}),onClick:l,loading:i,children:n("chat.prompt.systemCard.viewEnhanced")}):null,a&&u?r.jsx(U,{type:"text",size:"small",onClick:()=>h(!1),children:n("chat.prompt.systemCard.viewBase")}):null,r.jsx(U,{type:"text",size:"small",icon:r.jsx(ls,{}),onClick:()=>g(d),children:n("chat.prompt.systemCard.copy")})]})]}),r.jsx(J,{vertical:!0,style:{maxHeight:u?400:300,overflowY:"auto",paddingRight:s.paddingXS},children:r.jsx(ch,{content:d,token:s,headingColor:s.colorPrimary})}),c&&f.length>0?r.jsxs(r.Fragment,{children:[r.jsx(Dt,{style:{margin:`${s.marginXS}px 0`}}),r.jsxs(H,{direction:"vertical",size:s.marginXS,style:{width:"100%"},children:[r.jsx(dh,{type:"secondary",strong:!0,style:{fontSize:s.fontSizeSM},children:n("chat.prompt.systemCard.snapshotTitle")}),r.jsx(ws,{defaultActiveKey:f.map(y=>y.key),items:f.map(y=>({key:y.key,label:mC(n,y.key),children:r.jsx(ch,{content:y.content,token:s,headingColor:s.colorPrimary})}))})]})]}):null]})})},Ty=m.memo(hC);Ty.displayName="SystemMessageCard";const ky=6048e5,pC=864e5,uh=Symbol.for("constructDateFrom");function fn(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&uh in e?e[uh](t):e instanceof Date?new e.constructor(t):new Date(t)}function _s(e,t){return fn(t||e,e)}let fC={};function Ui(){return fC}function na(e,t){var l,c,d,u;const s=Ui(),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=_s(e,t==null?void 0:t.in),a=o.getDay(),i=(a<n?7:0)+a-n;return o.setDate(o.getDate()-i),o.setHours(0,0,0,0),o}function wi(e,t){return na(e,{...t,weekStartsOn:1})}function jy(e,t){const s=_s(e,t==null?void 0:t.in),n=s.getFullYear(),o=fn(s,0);o.setFullYear(n+1,0,4),o.setHours(0,0,0,0);const a=wi(o),i=fn(s,0);i.setFullYear(n,0,4),i.setHours(0,0,0,0);const l=wi(i);return s.getTime()>=a.getTime()?n+1:s.getTime()>=l.getTime()?n:n-1}function mh(e){const t=_s(e),s=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return s.setUTCFullYear(t.getFullYear()),+e-+s}function gC(e,...t){const s=fn.bind(null,t.find(n=>typeof n=="object"));return t.map(s)}function hh(e,t){const s=_s(e,t==null?void 0:t.in);return s.setHours(0,0,0,0),s}function yC(e,t,s){const[n,o]=gC(s==null?void 0:s.in,e,t),a=hh(n),i=hh(o),l=+a-mh(a),c=+i-mh(i);return Math.round((l-c)/pC)}function xC(e,t){const s=jy(e,t),n=fn(e,0);return n.setFullYear(s,0,4),n.setHours(0,0,0,0),wi(n)}function bC(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function vC(e){return!(!bC(e)&&typeof e!="number"||isNaN(+_s(e)))}function SC(e,t){const s=_s(e,t==null?void 0:t.in);return s.setFullYear(s.getFullYear(),0,1),s.setHours(0,0,0,0),s}const wC={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"}},_C=(e,t,s)=>{let n;const o=wC[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 Cl(e){return(t={})=>{const s=t.width?String(t.width):e.defaultWidth;return e.formats[s]||e.formats[e.defaultWidth]}}const TC={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},kC={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},jC={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},CC={date:Cl({formats:TC,defaultWidth:"full"}),time:Cl({formats:kC,defaultWidth:"full"}),dateTime:Cl({formats:jC,defaultWidth:"full"})},MC={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},PC=(e,t,s,n)=>MC[e];function qr(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 EC={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},RC={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},AC={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"]},IC={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"]},$C={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"}},DC={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"}},FC=(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"},LC={ordinalNumber:FC,era:qr({values:EC,defaultWidth:"wide"}),quarter:qr({values:RC,defaultWidth:"wide",argumentCallback:e=>e-1}),month:qr({values:AC,defaultWidth:"wide"}),day:qr({values:IC,defaultWidth:"wide"}),dayPeriod:qr({values:$C,defaultWidth:"wide",formattingValues:DC,defaultFormattingWidth:"wide"})};function Hr(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)?zC(l,h=>h.test(i)):OC(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 OC(e,t){for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)&&t(e[s]))return s}function zC(e,t){for(let s=0;s<e.length;s++)if(t(e[s]))return s}function NC(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 BC=/^(\d+)(th|st|nd|rd)?/i,WC=/\d+/i,UC={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},qC={any:[/^b/i,/^(a|c)/i]},HC={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},YC={any:[/1/i,/2/i,/3/i,/4/i]},XC={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},VC={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]},KC={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},GC={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]},JC={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},QC={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}},ZC={ordinalNumber:NC({matchPattern:BC,parsePattern:WC,valueCallback:e=>parseInt(e,10)}),era:Hr({matchPatterns:UC,defaultMatchWidth:"wide",parsePatterns:qC,defaultParseWidth:"any"}),quarter:Hr({matchPatterns:HC,defaultMatchWidth:"wide",parsePatterns:YC,defaultParseWidth:"any",valueCallback:e=>e+1}),month:Hr({matchPatterns:XC,defaultMatchWidth:"wide",parsePatterns:VC,defaultParseWidth:"any"}),day:Hr({matchPatterns:KC,defaultMatchWidth:"wide",parsePatterns:GC,defaultParseWidth:"any"}),dayPeriod:Hr({matchPatterns:JC,defaultMatchWidth:"any",parsePatterns:QC,defaultParseWidth:"any"})},eM={code:"en-US",formatDistance:_C,formatLong:CC,formatRelative:PC,localize:LC,match:ZC,options:{weekStartsOn:0,firstWeekContainsDate:1}};function tM(e,t){const s=_s(e,t==null?void 0:t.in);return yC(s,SC(s))+1}function sM(e,t){const s=_s(e,t==null?void 0:t.in),n=+wi(s)-+xC(s);return Math.round(n/ky)+1}function Cy(e,t){var u,h,f,g;const s=_s(e,t==null?void 0:t.in),n=s.getFullYear(),o=Ui(),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=(f=o.locale)==null?void 0:f.options)==null?void 0:g.firstWeekContainsDate)??1,i=fn((t==null?void 0:t.in)||e,0);i.setFullYear(n+1,0,a),i.setHours(0,0,0,0);const l=na(i,t),c=fn((t==null?void 0:t.in)||e,0);c.setFullYear(n,0,a),c.setHours(0,0,0,0);const d=na(c,t);return+s>=+l?n+1:+s>=+d?n:n-1}function nM(e,t){var l,c,d,u;const s=Ui(),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=Cy(e,t),a=fn((t==null?void 0:t.in)||e,0);return a.setFullYear(o,0,n),a.setHours(0,0,0,0),na(a,t)}function rM(e,t){const s=_s(e,t==null?void 0:t.in),n=+na(s,t)-+nM(s,t);return Math.round(n/ky)+1}function qe(e,t){const s=e<0?"-":"",n=Math.abs(e).toString().padStart(t,"0");return s+n}const ln={y(e,t){const s=e.getFullYear(),n=s>0?s:1-s;return qe(t==="yy"?n%100:n,t.length)},M(e,t){const s=e.getMonth();return t==="M"?String(s+1):qe(s+1,2)},d(e,t){return qe(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 qe(e.getHours()%12||12,t.length)},H(e,t){return qe(e.getHours(),t.length)},m(e,t){return qe(e.getMinutes(),t.length)},s(e,t){return qe(e.getSeconds(),t.length)},S(e,t){const s=t.length,n=e.getMilliseconds(),o=Math.trunc(n*Math.pow(10,s-3));return qe(o,t.length)}},nr={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},ph={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 ln.y(e,t)},Y:function(e,t,s,n){const o=Cy(e,n),a=o>0?o:1-o;if(t==="YY"){const i=a%100;return qe(i,2)}return t==="Yo"?s.ordinalNumber(a,{unit:"year"}):qe(a,t.length)},R:function(e,t){const s=jy(e);return qe(s,t.length)},u:function(e,t){const s=e.getFullYear();return qe(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 qe(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 qe(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 ln.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 qe(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=rM(e,n);return t==="wo"?s.ordinalNumber(o,{unit:"week"}):qe(o,t.length)},I:function(e,t,s){const n=sM(e);return t==="Io"?s.ordinalNumber(n,{unit:"week"}):qe(n,t.length)},d:function(e,t,s){return t==="do"?s.ordinalNumber(e.getDate(),{unit:"date"}):ln.d(e,t)},D:function(e,t,s){const n=tM(e);return t==="Do"?s.ordinalNumber(n,{unit:"dayOfYear"}):qe(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 qe(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 qe(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 qe(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=nr.noon:n===0?o=nr.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=nr.evening:n>=12?o=nr.afternoon:n>=4?o=nr.morning:o=nr.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 ln.h(e,t)},H:function(e,t,s){return t==="Ho"?s.ordinalNumber(e.getHours(),{unit:"hour"}):ln.H(e,t)},K:function(e,t,s){const n=e.getHours()%12;return t==="Ko"?s.ordinalNumber(n,{unit:"hour"}):qe(n,t.length)},k:function(e,t,s){let n=e.getHours();return n===0&&(n=24),t==="ko"?s.ordinalNumber(n,{unit:"hour"}):qe(n,t.length)},m:function(e,t,s){return t==="mo"?s.ordinalNumber(e.getMinutes(),{unit:"minute"}):ln.m(e,t)},s:function(e,t,s){return t==="so"?s.ordinalNumber(e.getSeconds(),{unit:"second"}):ln.s(e,t)},S:function(e,t){return ln.S(e,t)},X:function(e,t,s){const n=e.getTimezoneOffset();if(n===0)return"Z";switch(t){case"X":return gh(n);case"XXXX":case"XX":return Mn(n);case"XXXXX":case"XXX":default:return Mn(n,":")}},x:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"x":return gh(n);case"xxxx":case"xx":return Mn(n);case"xxxxx":case"xxx":default:return Mn(n,":")}},O:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+fh(n,":");case"OOOO":default:return"GMT"+Mn(n,":")}},z:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+fh(n,":");case"zzzz":default:return"GMT"+Mn(n,":")}},t:function(e,t,s){const n=Math.trunc(+e/1e3);return qe(n,t.length)},T:function(e,t,s){return qe(+e,t.length)}};function fh(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+qe(a,2)}function gh(e,t){return e%60===0?(e>0?"-":"+")+qe(Math.abs(e)/60,2):Mn(e,t)}function Mn(e,t=""){const s=e>0?"-":"+",n=Math.abs(e),o=qe(Math.trunc(n/60),2),a=qe(n%60,2);return s+o+t+a}const yh=(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"})}},My=(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"})}},oM=(e,t)=>{const s=e.match(/(P+)(p+)?/)||[],n=s[1],o=s[2];if(!o)return yh(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}}",yh(n,t)).replace("{{time}}",My(o,t))},aM={p:My,P:oM},iM=/^D+$/,lM=/^Y+$/,cM=["D","DD","YY","YYYY"];function dM(e){return iM.test(e)}function uM(e){return lM.test(e)}function mM(e,t,s){const n=hM(e,t,s);if(console.warn(n),cM.includes(e))throw new RangeError(n)}function hM(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 pM=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,fM=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,gM=/^'([^]*?)'?$/,yM=/''/g,xM=/[a-zA-Z]/;function bM(e,t,s){var u,h,f,g;const n=Ui(),o=n.locale??eM,a=n.firstWeekContainsDate??((h=(u=n.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??1,i=n.weekStartsOn??((g=(f=n.locale)==null?void 0:f.options)==null?void 0:g.weekStartsOn)??0,l=_s(e,s==null?void 0:s.in);if(!vC(l))throw new RangeError("Invalid time value");let c=t.match(fM).map(y=>{const p=y[0];if(p==="p"||p==="P"){const x=aM[p];return x(y,o.formatLong)}return y}).join("").match(pM).map(y=>{if(y==="''")return{isToken:!1,value:"'"};const p=y[0];if(p==="'")return{isToken:!1,value:vM(y)};if(ph[p])return{isToken:!0,value:y};if(p.match(xM))throw new RangeError("Format string contains an unescaped latin alphabet character `"+p+"`");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 p=y.value;(uM(p)||dM(p))&&mM(p,t,String(e));const x=ph[p[0]];return x(l,p,o.localize,d)}).join("")}function vM(e){const t=e.match(gM);return t?t[1].replace(yM,"'"):e}const{useToken:SM}=pe,{Text:Aa}=ce,wM=({images:e,className:t,style:s,maxHeight:n={single:400,multiple:200}})=>{const{token:o}=SM(),{t:a}=se();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(J,{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(ib,{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(J,{align:"center",justify:"center",gap:o.marginXS,style:{color:o.colorTextLightSolid},children:[r.jsx(Vc,{}),r.jsx(Aa,{style:{color:o.colorTextLightSolid},children:a("components.imageGrid.preview")})]})}}),r.jsxs(J,{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(Aa,{style:{color:o.colorTextLightSolid},strong:!0,children:i.name}),i.size&&r.jsxs(Aa,{style:{fontSize:o.fontSizeSM*.85,opacity:.8,color:o.colorTextLightSolid},children:[(i.size/1024).toFixed(1)," KB",i.width&&i.height&&` • ${i.width}×${i.height}`]})]})]}),(i.ocrText||i.ocrError)&&r.jsx("div",{style:{padding:o.paddingSM},children:r.jsx(ws,{ghost:!0,size:"small",items:[{key:"ocr",label:a("components.imageGrid.ocr"),children:r.jsxs(r.Fragment,{children:[i.ocrError&&r.jsx(Aa,{type:"danger",children:i.ocrError}),i.ocrText&&r.jsx(ce.Paragraph,{style:{marginTop:i.ocrError?o.marginXS:0,marginBottom:0,whiteSpace:"pre-wrap"},children:i.ocrText})]})}]})})]},i.id))})})},{useToken:_M}=pe,{useBreakpoint:TM}=Ci,kM=({buttons:e,isVisible:t,className:s,style:n,position:o={bottom:"8px",right:"8px"}})=>{const{token:a}=_M(),i=TM(),l=()=>(i.xs,"small");return r.jsx(J,{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(U,{"data-testid":c["data-testid"]||c.key,icon:c.icon,size:l(),type:"text",onClick:c.onClick,disabled:c.disabled,style:{background:a.colorBgElevated,borderRadius:a.borderRadiusSM}})},c.key))})},jM=(e,t)=>({key:"copy","data-testid":"copy-message",icon:r.jsx(ls,{}),title:t||"Copy message",onClick:e}),CM=(e,t)=>({key:"reference",icon:r.jsx(Qp,{}),title:t||"Reference message",onClick:e}),{Title:xh,Text:Jt,Paragraph:bh}=ce,{useToken:MM}=pe,PM=({plan:e,contextId:t,onExecute:s,onRefine:n,timestamp:o})=>{const{t:a}=se(),{token:i}=MM(),[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(H,{children:[r.jsx(Qs,{style:{color:i.colorPrimary}}),r.jsx(Jt,{strong:!0,style:{color:i.colorPrimary},children:a("components.plan.executionPlan")})]}),extra:o?r.jsx(Jt,{type:"secondary",style:{fontSize:i.fontSizeSM},children:o}):void 0,children:[r.jsxs(J,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(xh,{level:5,style:{marginBottom:i.marginXS},children:a("components.plan.goal")}),r.jsx(bh,{style:{fontSize:15,marginBottom:0},children:e.goal})]}),r.jsxs(J,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(xh,{level:5,style:{marginBottom:i.marginMD},children:a("components.plan.steps")}),r.jsx(Zp,{direction:"vertical",current:-1,items:e.steps.map(f=>({title:r.jsxs(Jt,{strong:!0,children:[a("components.plan.stepTitle",{number:f.step_number}),": ",f.action]}),description:r.jsxs(J,{vertical:!0,children:[r.jsxs(bh,{style:{marginBottom:i.marginXS},children:[r.jsxs(Jt,{type:"secondary",children:[a("components.plan.reason"),":"]})," ",f.reason]}),r.jsxs(H,{wrap:!0,children:[r.jsxs(Jt,{type:"secondary",children:[r.jsx(vr,{})," ",a("components.plan.tools"),":"]}),f.tools_needed.map((g,y)=>r.jsx(oe,{color:"processing",children:g},y))]}),r.jsx(J,{style:{marginTop:i.marginXS},children:r.jsxs(Jt,{type:"secondary",children:[r.jsx(Zs,{})," ",a("components.plan.estimated"),": ",f.estimated_time]})})]}),icon:r.jsx(Jt,{children:f.step_number})}))})]}),r.jsxs(H,{direction:"vertical",style:{width:"100%",marginBottom:i.marginLG},children:[r.jsxs(J,{align:"center",gap:i.marginXS,wrap:"wrap",children:[r.jsxs(Jt,{type:"secondary",children:[r.jsx(Zs,{})," ",a("components.plan.totalEstimatedTime")," "]}),r.jsx(oe,{color:"processing",children:e.estimated_total_time})]}),e.prerequisites&&e.prerequisites.length>0&&r.jsxs(J,{vertical:!0,children:[r.jsxs(Jt,{type:"secondary",children:[a("components.plan.prerequisites"),":"]}),r.jsx(nt,{size:"small",dataSource:e.prerequisites,renderItem:(f,g)=>r.jsx(nt.Item,{style:{padding:0},children:r.jsx(Jt,{children:f})},`${f}-${g}`)})]})]}),e.risks&&e.risks.length>0&&r.jsx(ws,{ghost:!0,style:{marginBottom:i.marginLG},items:[{key:"risks",label:r.jsxs(H,{children:[r.jsx(oa,{style:{color:i.colorWarning}}),r.jsx(Jt,{strong:!0,children:a("components.plan.potentialRisks",{count:e.risks.length})})]}),children:r.jsx(nt,{size:"small",dataSource:e.risks,renderItem:(f,g)=>r.jsx(nt.Item,{style:{padding:0},children:r.jsx(Jt,{children:f})},`${f}-${g}`)})}]}),r.jsx(H,{style:{width:"100%",justifyContent:"flex-end"},children:l?r.jsxs(r.Fragment,{children:[r.jsx(U,{onClick:()=>c(!1),children:a("common.cancel")}),r.jsx(U,{type:"primary",onClick:h,disabled:!d.trim(),children:a("components.plan.sendFeedback")})]}):r.jsxs(r.Fragment,{children:[r.jsx(U,{onClick:()=>c(!0),children:a("components.plan.refinePlan")}),r.jsx(U,{type:"primary",icon:r.jsx(ef,{}),onClick:s,children:a("components.plan.executePlan")})]})}),l&&r.jsx(J,{vertical:!0,style:{marginTop:i.marginMD},children:r.jsx(he.TextArea,{value:d,onChange:f=>u(f.target.value),placeholder:a("components.plan.feedbackPlaceholder"),autoSize:{minRows:4,maxRows:10}})})]})},Py=m.memo(PM);Py.displayName="PlanMessageCard";const{Title:EM,Text:rr,Paragraph:RM}=ce,{useToken:AM}=pe,IM=({question:e,contextId:t,onAnswer:s,disabled:n=!1,timestamp:o})=>{const{t:a}=se(),{token:i}=AM(),[l,c]=m.useState(e.default),[d,u]=m.useState(!1),h=async()=>{if(l){u(!0);try{await s(l)}catch(p){console.error("Failed to submit answer:",p)}finally{u(!1)}}},f=()=>{switch(e.severity){case"critical":return r.jsx(Ei,{style:{color:i.colorError}});case"major":return r.jsx(oa,{style:{color:i.colorWarning}});case"minor":return r.jsx(Ot,{style:{color:i.colorInfo}});default:return r.jsx(Jp,{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(H,{children:[f(),r.jsx(rr,{strong:!0,style:{color:y()},children:a("components.question.agentQuestion")}),r.jsxs(rr,{type:"secondary",style:{fontSize:12},children:["(",e.severity,")"]})]}),extra:o?r.jsx(rr,{type:"secondary",style:{fontSize:i.fontSizeSM},children:o}):void 0,children:[r.jsx(J,{vertical:!0,style:{marginBottom:i.marginLG},children:r.jsx(EM,{level:5,style:{marginBottom:i.marginXS},children:e.question})}),e.context&&r.jsx(Ne,{message:a("components.question.context"),description:e.context,type:"info",showIcon:!0,style:{marginBottom:i.marginLG}}),r.jsxs(J,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(rr,{strong:!0,style:{display:"block",marginBottom:i.marginSM},children:a("components.question.chooseOption")}),r.jsx(is.Group,{value:l,onChange:p=>c(p.target.value),disabled:n||d,style:{width:"100%"},children:r.jsx(H,{direction:"vertical",style:{width:"100%"},children:e.options.map(p=>r.jsx(ee,{size:"small",hoverable:!n&&!d,style:{borderColor:l===p.value?i.colorPrimary:i.colorBorder,backgroundColor:l===p.value?i.colorPrimaryBg:i.colorBgContainer,cursor:n||d?"not-allowed":"pointer"},onClick:()=>!n&&!d&&c(p.value),children:r.jsx(is,{value:p.value,style:{width:"100%"},children:r.jsxs(J,{vertical:!0,children:[r.jsxs(J,{align:"center",gap:i.marginXS,wrap:"wrap",children:[r.jsx(rr,{strong:!0,children:p.label}),p.value===e.default&&r.jsx(oe,{color:"processing",style:{marginLeft:i.marginXS},children:a("components.question.recommended")})]}),r.jsx(RM,{type:"secondary",style:{marginTop:i.marginXXS,marginBottom:0},children:p.description})]})})},p.value))})})]}),e.allow_custom&&r.jsxs(J,{vertical:!0,style:{marginBottom:i.marginMD},children:[r.jsx(rr,{type:"secondary",style:{fontSize:12},children:a("components.question.customAnswerHint")}),r.jsx(he.TextArea,{value:l&&!e.options.find(p=>p.value===l)?l:"",onChange:p=>c(p.target.value),placeholder:a("components.question.customAnswerPlaceholder"),disabled:n||d,autoSize:{minRows:3,maxRows:8},style:{marginTop:i.marginXS}})]}),r.jsx(J,{justify:"flex-end",children:r.jsx(U,{type:"primary",icon:r.jsx(Qs,{}),onClick:h,loading:d,disabled:n||!l,children:a("components.question.submitAnswer")})})]})},Ey=m.memo(IM);Ey.displayName="QuestionMessageCard";const{Text:vh}=ce,$M=({paths:e,displayText:t})=>{const{token:s}=pe.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(H,{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(J,{vertical:!0,children:[r.jsxs(H,{size:s.marginXS,align:"center",wrap:!0,children:[c?r.jsx(si,{style:{color:s.colorWarning,fontSize:s.fontSizeLG}}):r.jsx(yr,{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(H,{size:4,align:"center",style:{marginTop:4},children:[r.jsx(si,{style:{color:s.colorTextTertiary,fontSize:s.fontSizeSM}}),r.jsx(vh,{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(vh,{style:{fontSize:s.fontSize,color:s.colorText,marginTop:s.marginXS,paddingTop:s.marginXS,borderTop:`1px solid ${s.colorBorderSecondary}`},children:n})]})},Ry=m.memo($M);Ry.displayName="FileReferenceCard";const DM=({taskList:e})=>{const{token:t}=pe.useToken(),{Text:s}=ce,n=l=>{switch(l){case"pending":return r.jsx(oe,{icon:r.jsx(Zs,{}),color:"default",children:"Pending"});case"in_progress":return r.jsx(oe,{icon:r.jsx(ra,{spin:!0}),color:"processing",children:"In Progress"});case"completed":return r.jsx(oe,{icon:r.jsx(Qs,{}),color:"success",children:"Completed"});case"skipped":return r.jsx(oe,{icon:r.jsx(Ql,{}),color:"default",children:"Skipped"});case"failed":return r.jsx(oe,{icon:r.jsx(Zl,{}),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=pt.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=pt.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(J,{vertical:!0,gap:t.marginSM,children:[r.jsxs(J,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[r.jsxs(H,{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(H,{direction:"vertical",size:4,children:[r.jsx(Zc,{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(J,{vertical:!0,style:{width:"100%"},gap:4,children:[r.jsxs(J,{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(J,{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]})]})})},FM=100,Pn=new Set;function LM(e){if(Pn.has(e)&&Pn.delete(e),Pn.add(e),Pn.size>FM){const t=Pn.values().next().value;t&&Pn.delete(t)}}function OM(e){let t=2166136261;for(let s=0;s<e.length;s++)t=(t^e.charCodeAt(s))*16777619;return(t>>>0).toString(36)}const zM=e=>{const{t}=se(),s=OM(e.chart),[n,o]=m.useState(()=>Pn.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)&&(LM(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(pt.Suspense,{fallback:r.jsx(ht,{size:"small",tip:t("components.mermaid.loadingDiagram")}),children:r.jsx(NM,{...e})}):r.jsx("div",{style:{minHeight:"200px"}})})},NM=e=>{const{t}=se(),[s,n]=m.useState(null);return m.useEffect(()=>{let o=!1;return Ft(()=>Promise.resolve().then(()=>hE),void 0,import.meta.url).then(a=>{o||n(()=>a.MermaidChart)}),()=>{o=!0}},[]),s?r.jsx(s,{...e}):r.jsx(ht,{size:"small",tip:t("components.mermaid.loadingDiagram")})},BM=pt.memo(zM),WM=({error:e,className:t,style:s,token:n,onFix:o,isFixing:a,fixError:i})=>{const{t:l}=se(),c=e.split(`
|
|
178
|
+
|
|
179
|
+
`);return r.jsxs("div",{className:t,style:{color:n.colorError,padding:`${n.paddingXS}px ${n.paddingSM}px`,fontSize:n.fontSizeSM,background:n.colorErrorBg,borderRadius:n.borderRadiusSM,border:`1px solid ${n.colorErrorBorder}`,margin:`${n.marginXS}px 0`,minHeight:"60px",maxHeight:"120px",display:"flex",flexDirection:"column",alignItems:"flex-start",justifyContent:"flex-start",overflow:"auto",position:"relative",maxWidth:"100%",boxSizing:"border-box",...s},title:`${l("components.mermaid.errorTitlePrefix")}: ${e}
|
|
180
|
+
|
|
181
|
+
${l("components.mermaid.checkConsoleHint")}`,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:n.marginXXS},children:[r.jsx("span",{style:{marginRight:n.marginXS,fontSize:"14px",flexShrink:0,lineHeight:1},children:r.jsx(oa,{})}),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(U,{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(Hp,{style:{marginRight:4}})," ",l("components.mermaid.checkConsoleHint")]})]})};var os=function(e,t){return Number(e.toFixed(t))},UM=function(e,t){return typeof e=="number"?e:t},et=function(e,t,s){s&&typeof s=="function"&&s(e,t)},qM=function(e){return-Math.cos(e*Math.PI)/2+.5},HM=function(e){return e},YM=function(e){return e*e},XM=function(e){return e*(2-e)},VM=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},KM=function(e){return e*e*e},GM=function(e){return--e*e*e+1},JM=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},QM=function(e){return e*e*e*e},ZM=function(e){return 1- --e*e*e*e},eP=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},tP=function(e){return e*e*e*e*e},sP=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},Ay={easeOut:qM,linear:HM,easeInQuad:YM,easeOutQuad:XM,easeInOutQuad:VM,easeInCubic:KM,easeOutCubic:GM,easeInOutCubic:JM,easeInQuart:QM,easeOutQuart:ZM,easeInOutQuart:eP,easeInQuint:tP,easeOutQuint:sP,easeInOutQuint:nP},Iy=function(e){typeof e=="number"&&cancelAnimationFrame(e)},xs=function(e){e.mounted&&(Iy(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function $y(e,t,s,n){if(e.mounted){var o=new Date().getTime(),a=1;xs(e),e.animation=function(){if(!e.mounted)return Iy(e.animation);var i=new Date().getTime()-o,l=i/s,c=Ay[t],d=c(l);i>=s?(n(a),e.animation=null):e.animation&&(n(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function rP(e){var t=e.scale,s=e.positionX,n=e.positionY;return!(Number.isNaN(t)||Number.isNaN(s)||Number.isNaN(n))}function bn(e,t,s,n){var o=rP(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,f=t.positionY-d;s===0?a(t.scale,t.positionX,t.positionY):$y(e,n,s,function(g){var y=l+u*g,p=c+h*g,x=d+f*g;a(y,p,x)})}}function oP(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 aP=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,f=c;return{minPositionX:d,maxPositionX:u,minPositionY:h,maxPositionY:f}},Od=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=oP(s,n,t),i=a.wrapperWidth,l=a.wrapperHeight,c=a.newContentWidth,d=a.newDiffWidth,u=a.newContentHeight,h=a.newDiffHeight,f=aP(i,c,d,l,u,h,!!o);return f},zc=function(e,t,s,n){return n?e<t?os(t,2):e>s?os(s,2):os(e,2):os(e,2)},Bn=function(e,t){var s=Od(e,t);return e.bounds=s,s};function ga(e,t,s,n,o,a,i){var l=s.minPositionX,c=s.minPositionY,d=s.maxPositionX,u=s.maxPositionY,h=0,f=0;i&&(h=o,f=a);var g=zc(e,l-h,d+h,n),y=zc(t,c-f,u+f,n);return{x:g,y}}function qi(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,f=d-s*u,g=ga(h,f,o,a,0,0,null);return g}function ya(e,t,s,n,o){var a=o?n:0,i=t-a;return!Number.isNaN(s)&&e>=s?s:!Number.isNaN(t)&&e<=i?i:e}var Sh=function(e,t){var s=e.setup.panning.excluded,n=e.isInitialized,o=e.wrapperComponent,a=t.target,i="shadowRoot"in a&&"composedPath"in t,l=i?t.composedPath().some(function(u){return u instanceof Element?o==null?void 0:o.contains(u):!1}):o==null?void 0:o.contains(a),c=n&&a&&l;if(!c)return!1;var d=Hi(a,s);return!d},wh=function(e){var t=e.isInitialized,s=e.isPanning,n=e.setup,o=n.panning.disabled,a=t&&s&&!o;return!!a},iP=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}},lP=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 cP(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,f=u.minPositionX,g=u.maxPositionY,y=u.minPositionY,p=s>h||s<f,x=n>g||n<y,b=s>h?d.offsetWidth:e.setup.minPositionX||0,S=n>g?d.offsetHeight:e.setup.minPositionY||0,w=qi(e,b,S,o,e.bounds,l||c),k=w.x,j=w.y;return{scale:o,positionX:p?k:s,positionY:x?j:n}}}function Dy(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 f=ga(t,s,l,a,n,o,i),g=f.x,y=f.y;e.setTransformState(d,g,y)}}var dP=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,f=i?c:u,g=l?d:h;return{x:f,y:g}},gn=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},uP=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},mP=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 hP(e,t){var s=e.setup.velocityAnimation,n=s.equalToMove,o=s.animationTime,a=s.sensitivity;return n?o*t*a:o}function _h(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:zc(e,a,i,o)}function pP(e,t){var s=1;return t?Math.min(s,e.offsetWidth/window.innerWidth):s}function fP(e,t){var s=uP(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=pP(i,l),u=t.x-n.x,h=t.y-n.y,f=u/d,g=h/d,y=c-o,p=u*u+h*h,x=Math.sqrt(p)/y;e.velocity={velocityX:f,velocityY:g,total:x}}e.lastMousePosition=t,e.velocityTime=c}}function gP(e){var t=e.velocity,s=e.bounds,n=e.setup,o=e.wrapperComponent,a=mP(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,f=s.minPositionY,g=n.limitToBounds,y=n.alignmentAnimation,p=n.zoomAnimation,x=n.panning,b=x.lockAxisY,S=x.lockAxisX,w=p.animationType,k=y.sizeX,j=y.sizeY,C=y.velocityAlignmentTime,P=C,v=hP(e,c),M=Math.max(v,P),E=gn(e,k),_=gn(e,j),R=E*o.offsetWidth/100,T=_*o.offsetHeight/100,D=d+R,$=u-R,I=h+T,O=f-T,A=e.transformState,z=new Date().getTime();$y(e,w,M,function(L){var Y=e.transformState,F=Y.scale,q=Y.positionX,K=Y.positionY,G=new Date().getTime()-z,be=G/P,Pe=Ay[y.animationType],Ee=1-Pe(Math.min(1,be)),Te=1-L,ge=q+i*Te,je=K+l*Te,Be=_h(ge,A.positionX,q,S,g,u,d,$,D,Ee),Qe=_h(je,A.positionY,K,b,g,f,h,O,I,Ee);(q!==ge||K!==je)&&e.setTransformState(F,Be,Qe)})}}function Th(e,t){var s=e.transformState.scale;xs(e),Bn(e,s),window.TouchEvent!==void 0&&t instanceof TouchEvent?lP(e,t):iP(e,t)}function zd(e,t){var s=e.transformState.scale,n=e.setup,o=n.minScale,a=n.alignmentAnimation,i=a.disabled,l=a.sizeX,c=a.sizeY,d=a.animationTime,u=a.animationType,h=i||s<o||!l&&!c;if(!h){var f=cP(e);f&&bn(e,f,t??d,u)}}function kh(e,t,s){var n=e.startCoords,o=e.setup,a=o.alignmentAnimation,i=a.sizeX,l=a.sizeY;if(n){var c=dP(e,t,s),d=c.x,u=c.y,h=gn(e,i),f=gn(e,l);fP(e,{x:d,y:u}),Dy(e,d,u,h,f)}}function yP(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,f=!t&&s&&(s==null?void 0:s.total)>.1&&h;f?gP(e):zd(e)}}function Nd(e,t,s,n){var o=e.setup,a=o.minScale,i=o.maxScale,l=o.limitToBounds,c=ya(os(t,2),a,i,0,!1),d=Bn(e,c),u=qi(e,s,n,c,d,l),h=u.x,f=u.y;return{scale:c,positionX:h,positionY:f}}function Fy(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,f=d||n>=i;if((n>=1||l)&&zd(e),!(f||!o||!e.mounted)){var g=t||o.offsetWidth/2,y=s||o.offsetHeight/2,p=Nd(e,i,g,y);p&&bn(e,p,u,h)}}var hn=function(){return hn=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},hn.apply(this,arguments)};function jh(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 Ia={scale:1,positionX:0,positionY:0},Yr={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}},Nc={wrapperClass:"react-transform-wrapper",contentClass:"react-transform-component"},Ly=function(e){var t,s,n,o;return{previousScale:(t=e.initialScale)!==null&&t!==void 0?t:Ia.scale,scale:(s=e.initialScale)!==null&&s!==void 0?s:Ia.scale,positionX:(n=e.initialPositionX)!==null&&n!==void 0?n:Ia.positionX,positionY:(o=e.initialPositionY)!==null&&o!==void 0?o:Ia.positionY}},Ch=function(e){var t=hn({},Yr);return Object.keys(e).forEach(function(s){var n=typeof e[s]<"u",o=typeof Yr[s]<"u";if(o&&n){var a=Object.prototype.toString.call(Yr[s]),i=a==="[object Object]",l=a==="[object Array]";i?t[s]=hn(hn({},Yr[s]),e[s]):l?t[s]=jh(jh([],Yr[s],!0),e[s]):t[s]=e[s]}}),t},Oy=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,f=ya(os(h,3),l,i,u,!1);return f};function zy(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,f=(u/2-c)/l,g=(h/2-d)/l,y=Oy(e,t,s),p=Nd(e,y,f,g);if(!p)return console.error("Error during zoom event. New transformation state was not calculated.");bn(e,p,n,o)}function Ny(e,t,s,n){var o=e.setup,a=e.wrapperComponent,i=o.limitToBounds,l=Ly(e.props),c=e.transformState,d=c.scale,u=c.positionX,h=c.positionY;if(a){var f=Od(e,l.scale),g=ga(l.positionX,l.positionY,f,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(),bn(e,y,t,s))}}function xP(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 bP(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(),f=xP(t,n,o,a),g=f.x,y=f.y,p=h.width/a.scale,x=h.height/a.scale,b=n.offsetWidth/p,S=n.offsetHeight/x,w=ya(s||Math.min(b,S),c,d,0,!1),k=(u.width-p*w)/2,j=(u.height-x*w)/2,C=(u.left-g)*w+k,P=(u.top-y)*w+j,v=Od(e,w),M=ga(C,P,v,l,0,0,n),E=M.x,_=M.y;return{positionX:E,positionY:_,scale:w}}var vP=function(e){return function(t,s,n){t===void 0&&(t=.5),s===void 0&&(s=300),n===void 0&&(n="easeOut"),zy(e,1,t,s,n)}},SP=function(e){return function(t,s,n){t===void 0&&(t=.5),s===void 0&&(s=300),n===void 0&&(n="easeOut"),zy(e,-1,t,s,n)}},wP=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,f=e.setup.disabled;if(!(f||!u||!h)){var g={positionX:Number.isNaN(t)?l:t,positionY:Number.isNaN(s)?c:s,scale:Number.isNaN(n)?d:n};bn(e,g,o,a)}}},_P=function(e){return function(t,s){t===void 0&&(t=200),s===void 0&&(s="easeOut"),Ny(e,t,s)}},TP=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=By(t||o.scale,a,i);bn(e,l,s,n)}}},kP=function(e){return function(t,s,n,o){n===void 0&&(n=600),o===void 0&&(o="easeOut"),xs(e);var a=e.wrapperComponent,i=typeof t=="string"?document.getElementById(t):t;if(a&&i&&a.contains(i)){var l=bP(e,i,s);bn(e,l,n,o)}}},Bc=function(e){return{instance:e,zoomIn:vP(e),zoomOut:SP(e),setTransform:wP(e),resetTransform:_P(e),centerView:TP(e),zoomToElement:kP(e)}},jP=function(e){return{instance:e,state:e.transformState}},Ve=function(e){var t={};return Object.assign(t,jP(e)),Object.assign(t,Bc(e)),t},Ml=!1;function Pl(){try{var e={get passive(){return Ml=!0,!1}};return e}catch{return Ml=!1,Ml}}var $a=".".concat(Nc.wrapperClass),Hi=function(e,t){return t.some(function(s){return e.matches("".concat($a," ").concat(s,", ").concat($a," .").concat(s,", ").concat($a," ").concat(s," *, ").concat($a," .").concat(s," *"))})},Wc=function(e){e&&clearTimeout(e)},CP=function(e,t,s){return"translate(".concat(e,"px, ").concat(t,"px) scale(").concat(s,")")},By=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 MP(e){return function(t){e.forEach(function(s){typeof s=="function"?s(t):s!=null&&(s.current=t)})}}var PP=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=Hi(d,i);return!h},EP=function(e){return e?e.deltaY<0?1:-1:0};function RP(e,t){var s=EP(e),n=UM(t,s);return n}function Wy(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 AP=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,f=u.size,g=u.disabled;if(!i)throw new Error("Wrapper is not mounted");var y=a+t*s,p=n?!1:!g,x=ya(os(y,3),d,c,f,p&&!h);return x},IP=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},$P=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=Hi(i,o);return!c},DP=function(e){var t=e.setup.pinch.disabled,s=e.isInitialized,n=e.pinchStartDistance,o=s&&!t&&n;return!!o},FP=function(e,t,s){var n=s.getBoundingClientRect(),o=e.touches,a=os(o[0].clientX-n.left,5),i=os(o[0].clientY-n.top,5),l=os(o[1].clientX-n.left,5),c=os(o[1].clientY-n.top,5);return{x:(a+l)/2/t,y:(i+c)/2/t}},Uy=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))},LP=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,f=h*s;return ya(os(f,2),i,a,d,!u&&!c)},OP=160,zP=100,NP=function(e,t){var s=e.props,n=s.onWheelStart,o=s.onZoomStart;e.wheelStopEventTimer||(xs(e),et(Ve(e),t,n),et(Ve(e),t,o))},BP=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,f=i.wheel,g=i.disablePadding,y=i.smooth,p=h.size,x=h.disabled,b=f.step,S=f.smoothStep;if(!a)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var w=RP(t,null),k=y?S*Math.abs(t.deltaY):b,j=AP(e,w,k,!t.ctrlKey);if(c!==j){var C=Bn(e,j),P=Wy(t,a,c),v=x||p===0||u||g,M=d&&v,E=qi(e,P.x,P.y,j,C,M),_=E.x,R=E.y;e.previousWheelEvent=t,e.setTransformState(j,_,R),et(Ve(e),t,n),et(Ve(e),t,o)}},WP=function(e,t){var s=e.props,n=s.onWheelStop,o=s.onZoomStop;Wc(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(Fy(e,t.x,t.y),e.wheelAnimationTimer=null)},zP);var a=IP(e,t);a&&(Wc(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,et(Ve(e),t,n),et(Ve(e),t,o))},OP))},qy=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}},UP=function(e,t){var s=Uy(t);e.pinchStartDistance=s,e.lastDistance=s,e.pinchStartScale=e.transformState.scale,e.isPanning=!1;var n=qy(t);e.pinchLastCenterX=n.x,e.pinchLastCenterY=n.y,xs(e)},qP=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,f=d.size;if(!(n===null||!s)){var g=FP(t,a,s);if(!(!Number.isFinite(g.x)||!Number.isFinite(g.y))){var y=Uy(t),p=LP(e,y),x=qy(t),b=x.x-(e.pinchLastCenterX||0),S=x.y-(e.pinchLastCenterY||0);if(!(p===a&&b===0&&S===0)){e.pinchLastCenterX=x.x,e.pinchLastCenterY=x.y;var w=Bn(e,p),k=h||f===0||c,j=l&&k,C=qi(e,g.x,g.y,p,w,j),P=C.x,v=C.y;e.pinchMidpoint=g,e.lastDistance=y;var M=u.sizeX,E=u.sizeY,_=gn(e,M),R=gn(e,E),T=P+b,D=v+S,$=ga(T,D,w,l,_,R,o),I=$.x,O=$.y;e.setTransformState(p,I,O)}}}},HP=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,Fy(e,t==null?void 0:t.x,t==null?void 0:t.y)},Hy=function(e,t){var s=e.props.onZoomStop,n=e.setup.doubleClick.animationTime;Wc(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,et(Ve(e),t,s)},n)},YP=function(e,t){var s=e.props,n=s.onZoomStart,o=s.onZoom,a=e.setup.doubleClick,i=a.animationTime,l=a.animationType;et(Ve(e),t,n),Ny(e,i,l,function(){return et(Ve(e),t,o)}),Hy(e,t)};function XP(e,t){return e==="toggle"?t===1?1:-1:e==="zoomOut"?-1:1}function VP(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,f=u.mode,g=u.step,y=u.animationTime,p=u.animationType;if(!h&&!n){if(f==="reset")return YP(e,t);if(!a)return console.error("No ContentComponent found");var x=XP(f,e.transformState.scale),b=Oy(e,x,g);if(i!==b){et(Ve(e),t,c);var S=Wy(t,a,i),w=Nd(e,b,S.x,S.y);if(!w)return console.error("Error during zoom event. New transformation state was not calculated.");et(Ve(e),t,d),bn(e,w,y,p),Hy(e,t)}}}var KP=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=Hi(c,l);return!h},GP=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,Bn(s,s.transformState.scale),s.setup=Ch(n)},this.initializeWindowEvents=function(){var n,o,a=Pl(),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=Pl(),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),xs(s),(o=s.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(n){var o=Pl();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 f=h[u];if(f.target===d)return!0}return!1};s.applyTransformation(),s.onInitCallbacks.forEach(function(c){c(Ve(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 xs(s),Bn(s,s.transformState.scale),zd(s,0)}),s.observer.observe(n),s.observer.observe(o)},this.onWheelZoom=function(n){var o=s.setup.disabled;if(!o){var a=PP(s,n);if(a){var i=s.isPressingKeys(s.setup.wheel.activationKeys);i&&(NP(s,n),BP(s,n),WP(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,f=u-n.deltaY,g=l.lockAxisX?d:h,y=l.lockAxisY?u:f,p=s.setup.alignmentAnimation,x=p.sizeX,b=p.sizeY,S=gn(s,x),w=gn(s,b);g===d&&y===u||Dy(s,g,y,S,w)}},this.onPanningStart=function(n){var o=s.setup.disabled,a=s.props.onPanningStart;if(!o){var i=Sh(s,n);if(i){var l=s.isPressingKeys(s.setup.panning.activationKeys);l&&(n.button===0&&!s.setup.panning.allowLeftClickPan||n.button===1&&!s.setup.panning.allowMiddleClickPan||n.button===2&&!s.setup.panning.allowRightClickPan||(n.preventDefault(),n.stopPropagation(),xs(s),Th(s,n),et(Ve(s),n,a)))}}},this.onPanning=function(n){var o=s.setup.disabled,a=s.props.onPanning;if(!o){var i=wh(s);if(i){var l=s.isPressingKeys(s.setup.panning.activationKeys);l&&(n.preventDefault(),n.stopPropagation(),kh(s,n.clientX,n.clientY),et(Ve(s),n,a))}}},this.onPanningStop=function(n){var o=s.props.onPanningStop;s.isPanning&&(yP(s),et(Ve(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=$P(s,n);c&&(UP(s,n),xs(s),et(Ve(s),n,i),et(Ve(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=DP(s);c&&(n.preventDefault(),n.stopPropagation(),qP(s,n),et(Ve(s),n,i),et(Ve(s),n,l))}},this.onPinchStop=function(n){var o=s.props,a=o.onPinchingStop,i=o.onZoomStop;s.pinchStartScale&&(HP(s),et(Ve(s),n,a),et(Ve(s),n,i))},this.onTouchPanningStart=function(n){var o=s.setup.disabled,a=s.props.onPanningStart;if(!o){var i=Sh(s,n);if(i){var l=s.lastTouch&&+new Date-s.lastTouch<200&&n.touches.length===1;if(!l){s.lastTouch=+new Date,xs(s);var c=n.touches,d=c.length===1,u=c.length===2;d&&(xs(s),Th(s,n),et(Ve(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=wh(s);if(!i)return;n.preventDefault(),n.stopPropagation();var l=n.touches[0];kh(s,l.clientX,l.clientY),et(Ve(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=KP(s,n);a&&VP(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=Ve(s);s.onChangeCallbacks.forEach(function(c){return c(l)}),et(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=By(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):CP(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 Ve(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,Bn(s,s.transformState.scale),s.handleInitializeWrapperEvents(n),s.handleInitialize(n,o),s.initializeWindowEvents(),s.isInitialized=!0;var a=Ve(s);et(a,void 0,s.props.onInit)},this.props=t,this.setup=Ch(this.props),this.transformState=Ly(this.props)}return e}(),Bd=pt.createContext(null),JP=function(e,t){return typeof e=="function"?e(t):e},QP=pt.forwardRef(function(e,t){var s=m.useRef(new GP(e)).current,n=JP(e.children,Bc(s));return m.useImperativeHandle(t,function(){return Bc(s)},[s]),m.useEffect(function(){s.update(e)},[s,e]),pt.createElement(Bd.Provider,{value:s},n)});pt.forwardRef(function(e,t){var s=m.useRef(null),n=m.useContext(Bd);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]),pt.createElement("div",hn({},e,{ref:MP([s,t])}))});function ZP(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 eE=`.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
|
+
`,Mh={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};ZP(eE);var tE=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,f=m.useContext(Bd),g=f.init,y=f.cleanupWindowEvents,p=m.useRef(null),x=m.useRef(null);return m.useEffect(function(){var b=p.current,S=x.current;return b!==null&&S!==null&&g&&(g==null||g(b,S)),function(){y==null||y()}},[]),pt.createElement("div",hn({},d,{ref:p,className:"".concat(Nc.wrapperClass," ").concat(Mh.wrapper," ").concat(n),style:i}),pt.createElement("div",hn({},h,{ref:x,className:"".concat(Nc.contentClass," ").concat(Mh.content," ").concat(a),style:l}),t))};const Yy=()=>typeof window<"u"&&!!window.__TAURI_INTERNALS__;class sE{async saveFile(t){const{content:s,filters:n,defaultPath:o}=t,{save:a}=await Ft(async()=>{const{save:d}=await import("./index-BmjFP0ha.js");return{save:d}},__vite__mapDeps([13,14]),import.meta.url),{writeFile:i,writeTextFile:l}=await Ft(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:Xy(c,o),success:!0}}}class nE{async saveFile(t){const{content:s,filters:n,defaultPath:o}=t,a=Xy(o,o);if(typeof window>"u"||typeof document>"u")throw new Error("File save is unavailable in this environment");const i=aE(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 rE=new sE,oE=new nE,Xy=(e,t)=>e.split(/[/\\]/).pop()||t,aE=(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"}},iE=()=>Yy()?rE:oE;class Is{static async saveFile(t){try{return await iE().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}`}}Ye(Is,"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 lE=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},cE=({svg:e,height:t,isLoading:s,initialScale:n,chartKey:o,className:a,style:i,token:l,containerRef:c})=>{const{t:d}=se(),{message:u}=us.useApp(),[h,f]=m.useState(!1),g=m.useCallback(async()=>{var p;if(!(!e||h)){f(!0);try{const x=lE(e),b=new TextEncoder().encode(x),S=o?`mermaid-${o.slice(0,8)}`:"mermaid-graph",w=Is.generateTimestampedFilename(S,"svg"),k=await Is.saveBinaryFile(b,Is.FILTERS.SVG,w);if(k.success){u.success(d("chat.messageActions.savedFile",{filename:k.filename}));return}if((p=k.error)!=null&&p.toLowerCase().includes("cancel"))return;u.error(k.error||d("chat.messageActions.exportFailed"))}catch(x){const b=x instanceof Error?x.message:d("components.mermaid.exportFailed");u.error(b)}finally{f(!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(QP,{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:p,zoomOut:x,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(U,{size:"small",type:"text",onClick:()=>p(),style:{fontSize:12,padding:"2px 6px"},children:"+"}),r.jsx(U,{size:"small",type:"text",onClick:()=>x(),style:{fontSize:12,padding:"2px 6px"},children:"-"}),r.jsx(U,{size:"small",type:"text",onClick:()=>b(),style:{fontSize:10,padding:"2px 6px"},children:"⌂"}),r.jsx(ke,{title:d("components.mermaid.exportSvg"),children:r.jsx(U,{size:"small",type:"text",icon:r.jsx(gr,{}),"aria-label":"Download chart",disabled:y,loading:h,onClick:()=>{g()},style:{fontSize:11,padding:"2px 6px"}})})]}),r.jsx(tE,{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 dE(e){let t=2166136261;for(let s=0;s<e.length;s++)t=(t^e.charCodeAt(s))*16777619;return(t>>>0).toString(36)}const uE=(e,t)=>{const s=m.useMemo(()=>XT(e),[e]),n=m.useMemo(()=>dE(s),[s]),[o,a]=m.useState(()=>{const i=Qa(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=Qa(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(Qa(n))return;let l=!1;return a(c=>({...c,isLoading:!0})),QT(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:mE}=pe,_i=pt.memo(({chart:e,id:t,className:s,style:n,onFix:o})=>{const{token:a}=mE(),i=Bi(),[l,c]=m.useState(!1),[d,u]=m.useState(""),h=m.useRef(null),{renderState:f,chartKey:g}=uE(e,!0),{svg:y,height:p,svgWidth:x,error:b,isLoading:S}=f,k=(()=>{const C=i.defaultScale;return x>1200?C*.8:x>800?C*1:C*1.2})(),j=async()=>{if(!(!o||l)){c(!0),u("");try{await o(e,b)}catch(C){const P=C instanceof Error?C.message:String(C);u(P||"Failed to fix Mermaid diagram")}finally{c(!1)}}};return b?r.jsx(WM,{error:b,className:s,style:n,token:a,onFix:o?j:void 0,isFixing:l,fixError:d}):r.jsx(cE,{svg:y,height:p,isLoading:S,initialScale:k,chartKey:g,className:s,style:n,token:a,containerRef:h})});_i.displayName="MermaidChart";const hE=Object.freeze(Object.defineProperty({__proto__:null,MermaidChart:_i,default:_i},Symbol.toStringTag,{value:"Module"}));ft.registerLanguage("javascript",Op);ft.registerLanguage("js",Op);ft.registerLanguage("typescript",zp);ft.registerLanguage("ts",zp);ft.registerLanguage("python",Np);ft.registerLanguage("py",Np);ft.registerLanguage("json",$x);ft.registerLanguage("bash",Hc);ft.registerLanguage("shell",Hc);ft.registerLanguage("sh",Hc);ft.registerLanguage("css",Dx);ft.registerLanguage("html",Bp);ft.registerLanguage("xml",Bp);ft.registerLanguage("sql",Fx);ft.registerLanguage("yaml",Wp);ft.registerLanguage("yml",Wp);ft.registerLanguage("markdown",Up);ft.registerLanguage("md",Up);const pE=()=>qn,fE=["javascript","js","typescript","ts","python","py","json","bash","shell","sh","css","html","xml","sql","yaml","yml","markdown","md"],gE=({language:e,codeString:t,token:s})=>{const{t:n}=se(),[o,a]=m.useState(!1),i=async()=>{try{await ds(t),fe.success(n("components.markdown.codeCopiedSuccess"))}catch(d){console.error("Copy failed:",d),fe.error(n("components.markdown.copyFailed"))}},l=e.toLowerCase(),c=fE.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(ft,{style:pE(),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(U,{type:"text",size:"small",icon:r.jsx(ls,{}),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"}})]})},yE=({codeString:e,token:t})=>{const{t:s}=se();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(U,{type:"text",size:"small",icon:r.jsx(ls,{}),"aria-label":"Copy code",className:"fallback-copy-btn",onClick:async()=>{try{await ds(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}})]})},xE={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"},Vy=/^(\s*%%\{[\s\S]*?\}%%\s*)+/,bE=/^(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,vE=e=>e.replace(Vy,"").trimStart(),SE=(e,t)=>{const s=e.match(Vy);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}`},wE=(e,t)=>{const s=xE[e];if(!s)return null;const n=t.trim();if(!n)return"";if(e==="mermaid")return n;const o=vE(n);return bE.test(o)?n:SE(n,s)},Ky=(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=wE(a,t);if(i!==null){const l=i.trim();return l?o==="eager"?r.jsx(_i,{chart:l,onFix:n}):r.jsx(BM,{chart:l,onFix:n}):(console.warn("Empty Mermaid chart content"),null)}return r.jsx(gE,{language:a,codeString:t,token:s})}catch(a){return console.warn("Syntax highlighting failed:",a),r.jsx(yE,{codeString:t,token:s})}},Ph=(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)},Gy=async e=>{const t=e.trim();if(!t)return;if(Yy()){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)}Ph(t,{allowLocationFallback:!1});return}Ph(t)},{Text:Eh}=ce,Jy=(e,t)=>({p:({children:s})=>r.jsx(Eh,{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(Eh,{code:!0,className:s,...a,children:n}):d.trim()?Ky(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(),Gy(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:Oe}=ce,Rh=e=>{if(!e)return;const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},_E=({content:e,toolName:t,status:s="success",timestamp:n,defaultCollapsed:o=!0,isLoading:a,errorMessage:i})=>{var b;const{t:l}=se(),{token:c}=pe.useToken(),d=m.useMemo(()=>Rc(e),[e]),u=m.useMemo(()=>typeof a=="boolean"?a:d.formattedText.trim().length===0,[d.formattedText,a]),h=m.useMemo(()=>n0(d.formattedText),[d.formattedText]),f=m.useMemo(()=>fa(e),[e]),g=m.useMemo(()=>cy(e),[e]),y=m.useMemo(()=>f?dy(f.diff.unified):[],[f]),p=async()=>{try{const S=d.isJson?xr(d.parsedJson):d.formattedText;await ds(S)}catch(S){console.error("[ToolResultCard] Failed to copy result:",S)}},x=m.useMemo(()=>{const S=e?e.slice(0,50).replace(/[^a-zA-Z0-9]/g,""):"empty";return`tool-result-${t}-${S}`},[t,e]);return r.jsx(ws,{defaultActiveKey:o?[]:[x],style:{backgroundColor:c.colorBgContainer,borderColor:c.colorBorderSecondary,borderWidth:1,borderStyle:"solid",borderRadius:c.borderRadiusLG},items:[{key:x,label:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:c.marginSM,width:"100%"},children:[r.jsx(Qc,{style:{color:c.colorPrimary,flexShrink:0}}),r.jsx(Oe,{strong:!0,style:{color:c.colorText,flexShrink:0},children:t}),r.jsx(Oe,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:c.fontSizeSM},children:u?l("components.toolResult.waiting"):h}),r.jsx(oe,{color:uy(s),style:{flexShrink:0,margin:0},children:s})]}),children:r.jsxs(H,{direction:"vertical",style:{width:"100%"},size:c.marginSM,children:[n&&r.jsx(Oe,{type:"secondary",style:{fontSize:c.fontSizeSM},children:new Date(n).toLocaleString()}),i&&r.jsx(Ne,{type:"error",message:l("components.toolResult.executionFailed"),description:i,showIcon:!0}),r.jsxs("div",{style:{position:"relative"},children:[r.jsx(ke,{title:l("components.toolResult.copyResult"),children:r.jsx(U,{type:"text",size:"small",icon:r.jsx(ls,{}),"aria-label":l("components.toolResult.copyResult"),onClick:S=>{S.stopPropagation(),p()},style:{position:"absolute",top:8,right:8,zIndex:1}})}),u?r.jsx(Oe,{type:"secondary",children:l("components.toolResult.waitingForResult")}):g?r.jsxs(H,{direction:"vertical",style:{width:"100%"},size:10,children:[r.jsxs(H,{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(Oe,{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(([S,w])=>r.jsx(oe,{children:`${S}: ${w}`},`type-${S}`)),Object.entries(g.data.by_status).map(([S,w])=>r.jsx(oe,{color:"processing",children:`${S}: ${w}`},`status-${S}`))]})]}),r.jsx(Dt,{style:{margin:`${c.marginXS}px 0`}}),r.jsxs("div",{style:{display:"grid",gap:c.marginXS},children:[r.jsxs(Oe,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Oe,{strong:!0,children:l("components.toolResult.memory.viewsLabel")})," ",g.data.view_files.length]}),r.jsxs(Oe,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Oe,{strong:!0,children:l("components.toolResult.memory.indexesLabel")})," ",g.data.index_files.length]}),r.jsxs(Oe,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Oe,{strong:!0,children:l("components.toolResult.memory.stateFilesLabel")})," ",g.data.state_files.length]}),g.data.last_reindex_at?r.jsxs(Oe,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Oe,{strong:!0,children:l("components.toolResult.memory.lastReindexLabel")})," ",Rh(g.data.last_reindex_at)]}):null,g.data.last_dream_at?r.jsxs(Oe,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Oe,{strong:!0,children:l("components.toolResult.memory.lastDreamLabel")})," ",Rh(g.data.last_dream_at)]}):null]}),g.data.view_files.length>0?r.jsxs("div",{children:[r.jsx(Oe,{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(S=>r.jsx(oe,{children:S},`view-${S}`))})]}):null,g.data.index_files.length>0?r.jsxs("div",{children:[r.jsx(Oe,{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(S=>r.jsx(oe,{children:S},`index-${S}`))})]}):null,g.data.state_files.length>0?r.jsxs("div",{children:[r.jsx(Oe,{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(S=>r.jsx(oe,{children:S},`state-${S}`))})]}):null,g.data.topic_paths.length>0?r.jsxs("div",{children:[r.jsx(Oe,{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(S=>r.jsx(oe,{children:S},`topic-${S}`))})]}):null,g.data.recent_ids.length>0?r.jsxs("div",{children:[r.jsx(Oe,{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(S=>r.jsx(oe,{color:"default",children:S},`recent-${S}`))})]}):null]}):f?r.jsxs(H,{direction:"vertical",style:{width:"100%"},size:8,children:[f.message&&r.jsx(Oe,{style:{fontSize:c.fontSizeSM},children:f.message}),r.jsxs(Oe,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(Oe,{strong:!0,children:[l("common.file"),":"]})," ",r.jsx(Oe,{code:!0,children:f.file_path})]}),f.workspace&&r.jsxs(Oe,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(Oe,{strong:!0,children:[l("common.workspace"),":"]})," ",r.jsx(Oe,{code:!0,children:f.workspace})]}),(b=f.checkpoint)!=null&&b.created?r.jsxs(Oe,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(Oe,{strong:!0,children:[l("components.toolResult.checkpoint"),":"]})," ",r.jsx(Oe,{code:!0,children:f.checkpoint.path})]}):r.jsx(Oe,{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((S,w)=>{const k={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 S.kind==="add"?k.background=c.colorSuccessBg:S.kind==="remove"?k.background=c.colorErrorBg:S.kind==="modified_add"?(k.background=c.colorWarningBg,k.borderLeft=`3px solid ${c.colorSuccess}`):S.kind==="modified_remove"?(k.background=c.colorWarningBg,k.borderLeft=`3px solid ${c.colorError}`):S.kind==="hunk"?(k.background=c.colorFillSecondary,k.color=c.colorTextSecondary):S.kind==="meta"&&(k.background=c.colorFillTertiary,k.color=c.colorTextSecondary),r.jsx("pre",{style:k,children:S.text||" "},`${w}-${S.kind}`)})}),f.diff.truncated&&r.jsx(Oe,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("components.toolResult.diffTruncated")})]}):d.isJson?r.jsx(pr,{language:"json",style:qn,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})]})]})}]})},Wd=m.memo(_E);Wd.displayName="ToolResultCard";const{Text:Es}=ce;function TE(e,t){const s=Xn(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 kE=({toolName:e,parameters:t,toolCallId:s,streamingOutput:n,defaultExpanded:o=!1,metadata:a})=>{const{t:i}=se(),{token:l}=pe.useToken(),c=m.useMemo(()=>Xn(e),[e]),[d,u]=m.useState(o?[s]:[]),h=m.useRef(!1),f=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=f.current;b&&(b.scrollTop=b.scrollHeight)},[n,d,s]);const g=m.useMemo(()=>TE(e,t),[e,t]),y=m.useMemo(()=>xr(t,2),[t]),p=async()=>{try{await ds(y)}catch(b){console.error("[ToolCallCard] Failed to copy parameters:",b)}},x=m.useMemo(()=>{const b=["path","file_path","command","pattern","query","limit"];return Object.entries(t).sort((k,j)=>{const C=b.indexOf(k[0]),P=b.indexOf(j[0]);return C!==-1&&P!==-1?C-P:C!==-1?-1:P!==-1?1:0}).slice(0,3)},[t]);return r.jsx(ws,{activeKey:d,onChange:b=>{const S=Array.isArray(b)?b.map(String):b==null?[]:[String(b)];u(S),S.includes(s)&&(h.current=!0)},style:{background:"var(--lotus-tool-card-bg)",borderColor:"var(--lotus-tool-card-border)",borderWidth:1,borderStyle:"solid",borderRadius:l.borderRadiusLG,boxShadow:"var(--lotus-tool-card-shadow)",transition:"all 0.3s ease",overflow:"hidden"},className:"tool-call-card-collapse",items:[{key:s,label: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(vr,{style:{color:l.colorPrimary,flexShrink:0}})}),c?r.jsxs(H,{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(Es,{strong:!0,style:{color:l.colorText},children:c.toolName}),r.jsx(Es,{type:"secondary",style:{fontSize:l.fontSizeSM},children:r.jsx(Es,{code:!0,style:{fontSize:l.fontSizeSM},children:c.serverId})})]}):r.jsx(Es,{strong:!0,style:{color:l.colorText,flexShrink:0},children:e}),r.jsx(Es,{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(H,{direction:"vertical",style:{width:"100%"},size:l.marginSM,children:[n&&n.trim().length>0&&r.jsxs("div",{children:[r.jsx(Es,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolCall.liveOutput")}),r.jsx("div",{ref:f,className:"lotus-code-surface",style:{marginTop:l.marginXS,borderRadius:l.borderRadiusSM,backgroundColor:l.colorBgContainer,maxHeight:240,overflow:"auto"},children:r.jsx(pr,{language:"text",style:qn,wrapLongLines:!0,customStyle:{margin:0,backgroundColor:"transparent",fontSize:l.fontSizeSM},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:n})})]}),x.length>0&&r.jsxs("div",{children:[r.jsx(Es,{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:x.map(([b,S])=>r.jsxs("li",{children:[r.jsx(Es,{code:!0,style:{fontSize:l.fontSizeSM},children:b}),r.jsxs(Es,{style:{fontSize:l.fontSizeSM},children:[": ",typeof S=="string"?S:JSON.stringify(S)]})]},b))})]}),r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:l.marginXS},children:[r.jsx(Es,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolCall.fullParameters")}),r.jsx(ke,{title:i("components.toolCall.copyParameters"),children:r.jsx(U,{type:"text",size:"small",icon:r.jsx(ls,{}),"aria-label":i("components.toolCall.copyParameters"),onClick:b=>{b.stopPropagation(),p()}})})]}),r.jsx(pr,{language:"json",style:qn,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})]})]})}]})},Ud=m.memo(kE);Ud.displayName="ToolCallCard";const{Text:El}=ce,jE=({content:e,workflowName:t,parameters:s,status:n="success",timestamp:o,onRetry:a,isLoading:i,errorMessage:l})=>{const{t:c}=se(),{token:d}=pe.useToken(),[u,h]=m.useState(!1),f=m.useMemo(()=>Rc(e),[e]),g=m.useMemo(()=>typeof i=="boolean"?i:f.formattedText.trim().length===0,[f.formattedText,i]),y=m.useMemo(()=>t0(f.formattedText),[f.formattedText]),p=f.isJson||y,x=!p||u,b=m.useMemo(()=>s0(f.formattedText),[f.formattedText]),S=m.useMemo(()=>{if(s==null)return null;if(typeof s=="string")return Rc(s);try{return{isJson:!0,formattedText:JSON.stringify(s,null,2),parsedJson:s}}catch(j){return console.error("[WorkflowResultCard] Failed to stringify parameters:",j),{isJson:!1,formattedText:String(s)}}},[s]),w=async()=>{try{const j=f.isJson?xr(f.parsedJson):f.formattedText;await ds(j)}catch(j){console.error("[WorkflowResultCard] Failed to copy content:",j)}},k=async()=>{if(S)try{const j=S.isJson?xr(S.parsedJson):S.formattedText;await ds(j)}catch(j){console.error("[WorkflowResultCard] Failed to copy parameters:",j)}};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(H,{direction:"vertical",style:{width:"100%"},size:d.marginSM,children:[r.jsxs(J,{align:"center",justify:"space-between",children:[r.jsxs(H,{size:d.marginXS,align:"center",children:[r.jsx(lb,{style:{color:d.colorWarning}}),r.jsx(El,{strong:!0,children:c("components.workflowResult.userWorkflow")}),r.jsx(oe,{color:d.colorWarning,children:t}),r.jsx(oe,{color:uy(n),children:n})]}),r.jsxs(H,{size:"small",children:[r.jsx(ke,{title:c(u?"components.workflowResult.collapseResult":"components.workflowResult.expandResult"),children:p&&r.jsx(U,{type:"text",size:"small",icon:u?r.jsx(cb,{}):r.jsx(db,{}),onClick:()=>h(j=>!j)})}),r.jsx(ke,{title:c("components.workflowResult.copyResult"),children:r.jsx(U,{type:"text",size:"small",icon:r.jsx(ls,{}),onClick:w,"aria-label":c("components.workflowResult.copyContent")})}),a&&r.jsx(ke,{title:c("components.workflowResult.retryWorkflow"),children:r.jsx(U,{type:"text",size:"small",icon:r.jsx(Fs,{}),onClick:a,"aria-label":c("components.workflowResult.retryWorkflow")})})]})]}),o&&r.jsx(El,{type:"secondary",style:{fontSize:d.fontSizeSM},children:new Date(o).toLocaleString()}),r.jsx(Dt,{style:{margin:`${d.marginXS}px 0`}}),l&&r.jsx(Ne,{type:"error",message:c("components.workflowResult.executionFailed"),description:l,showIcon:!0,style:{marginBottom:d.marginXS}}),r.jsx(J,{vertical:!0,style:{width:"100%"},children:g?r.jsx(ht,{tip:c("components.workflowResult.waitingForResult")}):f.isJson?r.jsx(pr,{language:"json",style:qn,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:x?"none":280,overflow:x?"auto":"hidden"},children:f.formattedText}):r.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,maxHeight:x?"none":280,overflow:x?"visible":"hidden",marginBottom:0},children:[x?f.formattedText:b.preview,!x&&b.isTruncated&&`
|
|
219
|
+
…`]})}),S&&r.jsxs(J,{vertical:!0,style:{width:"100%"},children:[r.jsx(Dt,{style:{margin:`${d.marginXS}px 0`},children:r.jsxs(H,{size:"small",children:[r.jsx(El,{strong:!0,children:c("common.parameters")}),r.jsx(ke,{title:c("components.workflowResult.copyParameters"),children:r.jsx(U,{type:"text",size:"small",icon:r.jsx(ls,{}),onClick:k,"aria-label":c("components.workflowResult.copyParameters")})})]})}),S.isJson?r.jsx(pr,{language:"json",style:qn,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:220,overflow:"auto"},children:S.formattedText}):r.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,marginBottom:0},children:S.formattedText})]})]})})},Qy=m.memo(jE);Qy.displayName="WorkflowResultCard";const{Text:Rl}=ce,CE=({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o,conclusionMarkdown:a,markdownComponents:i,markdownPlugins:l,rehypePlugins:c})=>{const{t:d}=se(),[u,h]=m.useState(null),f=m.useMemo(()=>Oa({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o}),[e,t,s,n,o]),g=u===f,y=N(x=>x.setPendingQuestionRespond),p=N(x=>x.clearPendingQuestionRespondForSession);return m.useEffect(()=>{if(typeof window>"u")return;const x=b=>{var k;const w=((k=b.detail)==null?void 0:k.sessionId)??null;!e||w!==e||(h(f),p(e))};return window.addEventListener(hr,x),()=>{window.removeEventListener(hr,x)}},[e,f,p]),m.useEffect(()=>{!e||g||y({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o??null})},[e,g,f,t,s,n,o,y]),m.useEffect(()=>()=>{e&&p(e)},[e,p]),r.jsxs(H,{direction:"vertical",size:"middle",style:{width:"100%"},children:[a?r.jsx(vs,{remarkPlugins:l,rehypePlugins:c,components:i,children:a}):null,r.jsxs("div",{children:[r.jsx(Rl,{strong:!0,children:d("components.questionDialog.questionLabel","Question")}),r.jsx("div",{style:{marginTop:8},children:r.jsx(vs,{remarkPlugins:l,rehypePlugins:c,components:i,children:t})})]}),g?r.jsx(Rl,{type:"secondary",children:d("components.questionDialog.responseSubmittedContinue","Response submitted. Continuing...")}):r.jsx(Rl,{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:gs}=ce,ME=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=Xn(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),f=(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:f});continue}n.push(i)}return{cleanText:n.join(`
|
|
221
|
+
`).trimStart(),hints:s}},PE=({sessionId:e,message:t,messageText:s,isUserToolCall:n,formatUserToolCall:o,markdownComponents:a,markdownPlugins:i,rehypePlugins:l})=>{var y;const{t:c}=se(),d=p=>(p??"").trim().toLowerCase()==="conclusion";if(yy(t)){const p=t.result.result??"",x=t.isError?p||c("components.toolResult.executionFailed"):void 0,b=!x&&p.trim().length===0;if(t.result.display_preference==="Hidden")return null;const S=(t.toolName??"").trim().toLowerCase(),w=S==="conclusion",k=Q_(p),j=(S==="conclusion_with_options"||S==="exitplanmode"||S==="request_permissions")&&!t.isError&&k,C=S==="conclusion"?ly(p):null;return j&&k?r.jsx(CE,{sessionId:e,question:k.question,options:k.options,allowCustom:k.allow_custom,toolCallId:t.toolCallId,conclusionMarkdown:Z_(k.conclusion),markdownComponents:a,markdownPlugins:i,rehypePlugins:l}):C?r.jsx(H,{direction:"vertical",style:{width:"100%"},size:"small",children:r.jsx(vs,{remarkPlugins:i,rehypePlugins:l,components:a,children:C})}):r.jsx(Wd,{content:p,toolName:t.toolName,status:t.isError?"error":b?"warning":"success",timestamp:t.createdAt,defaultCollapsed:!w,isLoading:b,errorMessage:x})}if(nk(t)){const p=t.content??"",x=t.status==="error"?p||c("components.workflowResult.executionFailed"):void 0,b=!x&&p.trim().length===0;return r.jsx(Qy,{content:p,workflowName:t.workflowName,parameters:t.parameters,status:b?"warning":t.status??"success",timestamp:t.createdAt,isLoading:b,errorMessage:x})}if(sk(t)){const p=t.toolCalls.filter(x=>!d(x.toolName));return p.length===0?null:r.jsx(H,{direction:"vertical",style:{width:"100%"},children:p.map(x=>r.jsx(Ud,{toolName:x.toolName,parameters:x.parameters,toolCallId:x.toolCallId,streamingOutput:x.streamingOutput,defaultExpanded:!1,metadata:t.metadata},x.toolCallId))})}if(t.isAuthError)return r.jsxs(H,{direction:"vertical",style:{width:"100%"},size:"middle",children:[r.jsx(Ne,{message:c("chat.messageCard.authRequired"),description:r.jsx(vs,{remarkPlugins:i,rehypePlugins:l,components:a,children:s}),type:"error",showIcon:!0}),r.jsx(U,{type:"primary",icon:r.jsx(ji,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:u,hints:h}=t.role==="user"?ME(s):{cleanText:s,hints:[]},f=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=f.trim().length>0;return t.role==="assistant"&&!s&&!g?r.jsx(gs,{italic:!0,children:c("chat.messageCard.assistantThinking")}):r.jsxs(H,{direction:"vertical",style:{width:"100%"},size:"small",children:[g?r.jsx(ws,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:r.jsx(gs,{strong:!0,children:c("chat.messageCard.reasoning")}),children:r.jsx(vs,{remarkPlugins:i,rehypePlugins:l,components:a,children:f})}]}):null,h.map((p,x)=>p.type==="mcp"?r.jsx(Ne,{type:"info",showIcon:!1,message:r.jsxs(H,{wrap:!0,size:"small",children:[r.jsx(oe,{color:"purple",children:"MCP"}),r.jsx(gs,{strong:!0,children:c("chat.messageCard.selectedTool")}),p.serverId&&r.jsx(gs,{type:"secondary",children:r.jsx(gs,{code:!0,children:p.serverId})}),p.toolName&&r.jsx(gs,{type:"secondary",children:r.jsx(gs,{code:!0,children:p.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${x}`):r.jsx(Ne,{type:"success",showIcon:!1,message:r.jsxs(H,{wrap:!0,size:"small",children:[r.jsx(oe,{color:"success",children:"Skill"}),r.jsx(gs,{strong:!0,children:c("chat.messageCard.selected")}),p.label&&r.jsx(gs,{children:p.label}),p.skillId&&r.jsx(gs,{type:"secondary",children:r.jsx(gs,{code:!0,children:p.skillId})})]}),style:{marginBottom:0}},`hint-skill-${x}`)),u?r.jsx(vs,{remarkPlugins:i,rehypePlugins:l,components:a,children:n?o(u):u}):null]})},EE=m.memo(PE),{Text:Al}=ce,RE=({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(J,{align:"center",justify:"space-between",gap:s.marginXS,style:{marginBottom:s.marginXS},children:[r.jsxs(J,{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(J,{vertical:!0,gap:0,children:[r.jsx(Al,{strong:!0,style:{fontSize:13,color:n?"var(--lotus-primary)":s.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:a}),r.jsx(Al,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:n?"Prompt":o?"Assistant":"System"})]})]}),t&&r.jsx(Al,{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})]})},qd=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},AE=e=>e==="text"||e==="plan"||e==="question"||e==="tool_call"||e==="tool_result",IE=(e,t)=>{if(t)return t;if("message_type"in e&&e.message_type){const s=e.message_type;if(AE(s))return s}if(e.role==="assistant"&&e.type==="text"){const s=typeof e.content=="string"?e.content:"";try{const n=qd(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"},$E=(e,t)=>{if(t!=="plan"||e.role!=="assistant"||e.type!=="text")return null;const s=e.content??"";try{const n=qd(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},DE=(e,t)=>{if(t!=="question"||e.role!=="assistant"||e.type!=="text")return null;const s=e.content??"";try{const n=qd(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},Zy=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"?ly(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""},FE=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}`},Ah=e=>e.map(t=>({name:t.name,extensions:[...t.extensions]})),Ih=e=>e.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",LE={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"},OE='[data-mermaid-loading="true"]';class ex{static async exportMessageText(t){const{format:s,content:n,sessionId:o=null,messageId:a=null,filenamePrefix:i}=t,l=i||["chat-message",o?Ih(o.slice(0,8)):null,a?Ih(a.slice(0,8)):null].filter(Boolean).join("-"),c=s==="markdown"?Is.generateTimestampedFilename(l,"md"):Is.generateTimestampedFilename(l,"pdf");if(s==="markdown"){const d=await Is.saveTextFile(n,Ah(Is.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 Is.saveBinaryFile(d,Ah(Is.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:as.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(t){if(typeof document>"u")throw new Error(as.t("chat.messageActions.pdfUnavailable"));const s=(await Ft(async()=>{const{default:g}=await import("./vendor-pdf-5uNnaI3-.js").then(y=>y.h);return{default:g}},__vite__mapDeps([16,1,2,3]),import.meta.url)).default,{jsPDF:n}=await Ft(async()=>{const{jsPDF:g}=await import("./vendor-pdf-5uNnaI3-.js").then(y=>y.j);return{jsPDF:g}},__vite__mapDeps([16,1,2,3]),import.meta.url),{createRoot:o}=await Ft(async()=>{const{createRoot:g}=await import("./main-ik_6ertt.js").then(y=>y.c);return{createRoot:g}},__vite__mapDeps([4,1,2,3,5]),import.meta.url),{flushSync:a}=await Ft(async()=>{const{flushSync:g}=await import("./vendor-antd-BlMATH2j.js").then(y=>y.R);return{flushSync:g}},__vite__mapDeps([3,2]),import.meta.url),i=Jy(LE,{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=as.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 f=o(h);a(()=>{f.render(pt.createElement(vs,{remarkPlugins:[ki,Xc],rehypePlugins:[Yc],components:i},t||""))});try{await this.waitForExportRenderReady(d);const g=await this.renderCanvasWithFallback(s,d),y=new n({unit:"pt",format:"a4",orientation:"portrait"}),p=y.internal.pageSize.getWidth(),x=y.internal.pageSize.getHeight(),b=24,S=p-b*2,w=x-b*2,k=g.width/S,j=Math.max(1,Math.floor(w*k));let C=0,P=0;for(;C<g.height;){const M=this.computeSmartSliceHeight(g,C,j),E=Math.max(1,Math.min(M,g.height-C)),_=document.createElement("canvas");_.width=g.width,_.height=E;const R=_.getContext("2d");if(!R)throw new Error("PDF render failed (no canvas context)");R.fillStyle="#ffffff",R.fillRect(0,0,_.width,_.height),R.drawImage(g,0,C,g.width,E,0,0,g.width,E);const T=_.toDataURL("image/jpeg",.92),D=E/k;P>0&&y.addPage(),y.addImage(T,"JPEG",b,b,S,D),C+=E,P+=1}const v=y.output("arraybuffer");return new Uint8Array(v)}finally{f.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(OE)){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,f=.03;let g=null,y=Number.POSITIVE_INFINITY,p=Number.POSITIVE_INFINITY;for(let x=0;x<i;x+=1){let b=0,S=0;const w=x*c;for(let v=0;v<t.width;v+=d){const M=w+v*4,E=l[M+3];if(S+=1,E<=h)continue;const _=l[M],R=l[M+1],T=l[M+2];(_<u||R<u||T<u)&&(b+=1)}if(S===0)continue;const k=b/S,j=n+x,C=Math.abs(j-s);(k<y||k===y&&C<p)&&(y=k,p=C,g=j)}return g===null||y>f?null:g}catch{return null}}}const zE=({messageText:e,messageId:t,currentSessionId:s,onDelete:n,onRestoreChat:o,onRestoreFilesAndChat:a,cardRef:i})=>{const{message:l}=us.useApp(),{t:c}=se(),[d,u]=m.useState(""),h=m.useCallback(async b=>{try{await ds(b)}catch(S){console.error("Failed to copy text:",S)}},[]),f=m.useCallback(b=>`> ${b.replace(/\n/g,`
|
|
228
|
+
> `)}`,[]),g=m.useCallback(()=>{if(!s)return;const b=f(d||e),S=new CustomEvent("reference-text",{detail:{text:b,sessionId:s}});window.dispatchEvent(S)},[f,s,e,d]),y=m.useCallback(async b=>{var k;const S=d||e;if(!S){l.warning(c("chat.messageActions.nothingToExport"));return}const w=await ex.exportMessageText({format:b,content:S,sessionId:s??null,messageId:t??null});if(w.success)l.success(c("chat.messageActions.savedFile",{filename:w.filename}));else{if((k=w.error)!=null&&k.toLowerCase().includes("cancel"))return;l.error(w.error||c("chat.messageActions.exportFailed"))}},[l,s,t,e,d,c]),p=m.useCallback(b=>{b.preventDefault(),b.stopPropagation();const S=window.getSelection(),w=S?S.toString():"";w&&i.current&&S&&i.current.contains(S.anchorNode)?u(w):u("")},[i]);return{contextMenuItems:m.useMemo(()=>{const b=[...o&&a&&s&&t?[{key:"restore-chat",label:c("chat.messageActions.restoreChat"),icon:r.jsx(ub,{}),onClick:()=>{o()}},{key:"restore-chat-files",label:c("chat.messageActions.restoreFilesAndChat"),icon:r.jsx(Xp,{}),onClick:()=>{a()}},{type:"divider"}]:[],{key:"copy",label:c("chat.messageActions.copy"),icon:r.jsx(ls,{}),onClick:()=>{h(d||e)}},{key:"reference",label:c("chat.actions.referenceMessage"),icon:r.jsx(Qp,{}),onClick:g},{type:"divider"},{key:"export-md",label:c("chat.messageActions.exportMarkdown"),icon:r.jsx(gr,{}),onClick:()=>y("markdown")},{key:"export-pdf",label:c("chat.messageActions.exportPdf"),icon:r.jsx(gr,{}),onClick:()=>y("pdf")}];return n&&t&&b.push({key:"delete",label:c("chat.messageActions.deleteMessage"),icon:r.jsx(yn,{}),onClick:()=>n(t),danger:!0}),b},[h,y,t,e,n,o,a,g,d,s,c]),handleMouseUp:p,copyToClipboard:h,referenceMessage:g}},NE=({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}},tx=e=>{const t=e.match(/```mermaid\s*([\s\S]*?)```/i);return t?t[1].trim():e.trim()},BE=(e,t,s)=>{const n=t.trim(),o=tx(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},$h="_text",Ti=e=>!!(e&&e.role==="assistant"&&"type"in e&&e.type==="text"),Dh=(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($h)){const a=e.slice(0,-$h.length);if(a&&s.some(i=>i.id===a))return a}return e},WE=(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},UE=e=>(e instanceof Error?e.message:String(e)).toLowerCase().includes("message not found"),qE=(e,t,s,n)=>{const o=e.find(a=>a.id===t);return Ti(o)?o:e.find(a=>Ti(a)&&(a.content===s||WE(a.content,n)))},HE=(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
|
+
`)},YE=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 Xg().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:HE(e,s)}],temperature:0})).choices)==null?void 0:l[0])==null?void 0:c.message)==null?void 0:d.content)??"";return tx(i)},XE=(e,t)=>{const s=Vg();return m.useCallback(async(n,o)=>{const a=N.getState(),i=t??a.currentSessionId,l=a.chats.find(x=>x.id===i);if(!i||!l)throw new Error("No active chat available");const c=l.messages.find(x=>x.id===e);if(!Ti(c))throw new Error("Mermaid fix is only available for assistant text messages");const d=await YE(n,s,o);if(!d)throw new Error("AI did not return a Mermaid fix");const u=BE(c.content,n,d);if(!u)throw new Error("Unable to locate Mermaid block to update");let h=Dh(e,c,l.messages);try{await Un.patchSessionMessage(i,h,{content:u})}catch(x){if(!UE(x))throw x;await a.loadChatHistory(i,{mode:"replace",retries:2,retryDelayMs:150,waitForAssistant:!0});const S=N.getState().chats.find(k=>k.id===i);if(!S)throw x;const w=qE(S.messages,e,c.content,n);if(!w)throw x;h=Dh(w.id,w,S.messages),await Un.patchSessionMessage(i,h,{content:u})}const f=N.getState(),g=f.chats.find(x=>x.id===i);if(!g)throw new Error("No active chat available");const y=new Set([e,h]),p=g.messages.map(x=>!y.has(x.id)||!Ti(x)?x:{...x,content:u});f.updateSession(i,{messages:p})},[e,t,s])},VE=e=>e.xs?"100%":e.sm?"95%":"800px",KE=[{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:"}],GE=({messageId:e,isVisible:t,onRetryWithVariation:s})=>{const{t:n}=se(),[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]),f=["lotus-msg-feedback",t?"is-visible":"",o!==null?"has-rating":""].filter(Boolean).join(" ");return r.jsxs("div",{className:f,"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(mb,{}):r.jsx(hb,{})})}),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(pb,{}):r.jsx(fb,{})})}),i&&s&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"lotus-msg-feedback-sep"}),r.jsx("span",{className:"lotus-msg-feedback-retry",children:KE.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:JE}=pe,{useBreakpoint:QE}=Ci,ZE="chat-send-message",e1=({sessionId:e,message:t,onDelete:s,messageType:n})=>{const{role:o,id:a}=t,{token:i}=JE(),l=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:c}=se(),{message:d}=us.useApp(),u=QE(),h=N(K=>K.updateSession),f=N(K=>K.loadChatHistory),g=N(K=>K.refreshChats),y=m.useRef(null),[p,x]=m.useState(!1),b=N(K=>e?K.processingChats.has(e):!1),S=m.useCallback(K=>typeof window>"u"?Promise.reject(new Error("window is unavailable")):new Promise((G,be)=>{const Pe={content:K,sessionId:e,handled:!1,resolve:G,reject:be};window.dispatchEvent(new CustomEvent(ZE,{detail:Pe})),Pe.handled||be(new Error("No chat message dispatcher available"))}),[e]),w=m.useMemo(()=>{if(!t.createdAt)return null;const K=new Date(t.createdAt);if(Number.isNaN(K.getTime()))return null;try{return bM(K,"MMM d, yyyy HH:mm")}catch{return K.toLocaleString()}},[t.createdAt]),k=m.useMemo(()=>IE(t,n),[t,n]),j=m.useMemo(()=>$E(t,k),[t,k]),C=m.useMemo(()=>DE(t,k),[t,k]),P=m.useMemo(()=>Zy(t),[t]),v=XE(a,e),M=m.useCallback(async K=>{var G;if(!e||!a){d.warning(c("chat.messageActions.cannotRestore"));return}try{const be=await Un.restoreSessionState(e,{target_message_id:a,restore_files:K});await f(e,{mode:"replace"}),await g();const Pe=((G=be.file_errors)==null?void 0:G.length)??0;if(Pe>0){d.warning(c("chat.messageActions.restorePartial",{count:Pe}));return}K?d.success(c("chat.messageActions.restoreFilesSuccess",{count:be.messages_removed})):d.success(c("chat.messageActions.restoreSuccess",{count:be.messages_removed}))}catch(be){const Pe=be instanceof Error?be.message:c("chat.messageActions.restoreFailed");d.error(Pe)}},[d,e,f,a,g,c]),E=m.useCallback(()=>{M(!1)},[M]),_=m.useCallback(()=>{M(!0)},[M]),{contextMenuItems:R,handleMouseUp:T,copyToClipboard:D,referenceMessage:$}=zE({messageText:P,messageId:a,currentSessionId:e,onDelete:s,onRestoreChat:E,onRestoreFilesAndChat:_,cardRef:y}),I=m.useMemo(()=>o==="user"&&P.startsWith("/"),[o,P]),O=m.useMemo(()=>Jy(i,{onFixMermaid:v}),[i,v]),A=m.useMemo(()=>[ki,Xc],[]),z=m.useMemo(()=>[Yc],[]),L=m.useMemo(()=>[jM(()=>D(P),c("chat.actions.copyMessage")),CM($,c("chat.actions.referenceMessage"))],[P,D,$,c]),{handleExecutePlan:Y,handleRefinePlan:F,handleQuestionAnswer:q}=NE({currentSessionId:e,updateSession:h,sendMessage:S});return k==="plan"&&j&&o==="assistant"?r.jsx(Py,{plan:j,contextId:e||"",onExecute:Y,onRefine:F,timestamp:w??void 0}):k==="question"&&C&&o==="assistant"?r.jsx(Ey,{question:C,contextId:e||"",onAnswer:q,disabled:b||!1,timestamp:w??void 0}):ok(t)?r.jsx(DM,{taskList:t.taskList}):rk(t)?(Ke("[MessageCard]","[MessageCard] Rendering FileReferenceCard for message:",t.id,"paths:",t.paths),r.jsx(J,{justify:"flex-end",style:{width:"100%"},children:r.jsx(Ry,{paths:t.paths,displayText:t.displayText,timestamp:w??void 0})})):r.jsxs(J,{vertical:!0,onContextMenu:K=>T(K),style:{width:"100%"},children:[r.jsx(fr,{menu:{items:R},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:VE(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:p?"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:p?"translateY(-2px) scale(1.002)":"none",overflow:"hidden"},bodyStyle:{padding:i.paddingMD},onMouseEnter:()=>x(!0),onMouseLeave:()=>x(!1),children:r.jsxs(H,{direction:"vertical",size:i.marginXS,style:{width:"100%",maxWidth:"100%"},children:[r.jsx(RE,{role:o,formattedTimestamp:w,token:i}),t.role==="user"&&t.images&&r.jsx(wM,{images:t.images}),r.jsx(J,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:r.jsx(EE,{sessionId:e,message:t,messageText:P,isUserToolCall:I,formatUserToolCall:FE,markdownComponents:O,markdownPlugins:A,rehypePlugins:z})}),r.jsx(kM,{isVisible:p,position:{bottom:i.paddingXS,right:i.paddingXS},buttons:L})]})})}),o==="assistant"&&k==="text"&&a&&r.jsx(GE,{messageId:a,isVisible:p})]})},sx=m.memo(e1,(e,t)=>e.message===t.message&&e.messageType===t.messageType&&e.onDelete===t.onDelete);sx.displayName="MessageCard";const{Text:Jo}=ce,{useToken:t1}=pe,s1=e=>({p:({children:t})=>r.jsx(Jo,{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(Jo,{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})})}):Ky(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(),Gy(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})}),nx=m.memo(({sessionId:e})=>{const{token:t}=t1(),s=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:n}=se(),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,f]=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=>{f(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 w=(b.slice(13).trim()||"tool").replace(/[_-]+/g," ");return n("chat.messageCard.assistantRunningTool",{tool:w})}return n("chat.messageCard.assistantThinking")},[h,n]),y=m.useMemo(()=>[ki,Xc],[]),p=m.useMemo(()=>[Yc],[]),x=m.useMemo(()=>s1(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(H,{direction:"vertical",size:t.marginXS,style:{width:"100%",maxWidth:"100%"},children:[r.jsx(J,{align:"baseline",justify:"space-between",gap:t.marginXS,children:r.jsx(Jo,{type:"secondary",strong:!0,style:{fontSize:t.fontSizeSM},children:n("chat.streaming.assistant")})}),r.jsxs(J,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:[d?r.jsx(ws,{size:"small",defaultActiveKey:["reasoning"],style:{marginBottom:t.marginSM,background:t.colorBgContainer,borderColor:t.colorBorderSecondary},items:[{key:"reasoning",label:r.jsx(Jo,{strong:!0,children:n("chat.messageCard.reasoning")}),children:r.jsx(vs,{remarkPlugins:y,rehypePlugins:p,components:x,children:d})}]}):null,!l||h?r.jsx(Jo,{italic:!0,className:"thinking-shimmer",children:g}):null,l?r.jsx(vs,{remarkPlugins:y,rehypePlugins:p,components:x,children:l}):null,r.jsx("span",{className:"blinking-cursor",style:{display:"inline-block",marginLeft:"0.2em",color:t.colorText}})]})]})})});nx.displayName="StreamingMessageCard";const{Text:Qt}=ce,n1="chat-session-tool-collapse:",rx=(e,t)=>`${n1}${e}:${t}`,Il=(e,t)=>{if(typeof window>"u")return null;try{const s=window.localStorage.getItem(rx(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}},r1=(e,t,s)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(rx(e,t),JSON.stringify(s))}catch{}},$l=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}`},o1=e=>{var t,s;return((s=(t=e.call.toolCalls)==null?void 0:t[0])==null?void 0:s.toolCallId)||e.call.id},a1="synthetic-tool-call:",i1=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(a1)&&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 l1(e,t,s){return e.result?e.result.isError?{icon:r.jsx(Ei,{style:{color:t.colorError}}),color:t.colorError,text:s("components.toolSession.error")}:{icon:r.jsx(Qs,{style:{color:t.colorSuccess}}),color:t.colorSuccess,text:s("components.toolSession.done")}:{icon:r.jsx(ra,{spin:!0,style:{color:t.colorPrimary}}),color:t.colorPrimary,text:s("components.toolSession.running")}}function c1(e,t){const s=Xn(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 d1=({tools:e,sessionId:t,defaultExpanded:s=!1,onDeleteMessageIds:n})=>{const{t:o}=se(),{token:a}=pe.useToken(),i=e.length===1,l=m.useMemo(()=>{var M,E,_,R;const C=e[0],P=(E=(M=C==null?void 0:C.call)==null?void 0:M.toolCalls)==null?void 0:E[0];return`${(C==null?void 0:C.callMessageId)||((_=C==null?void 0:C.call)==null?void 0:_.id)||(C==null?void 0:C.resultMessageId)||((R=C==null?void 0:C.result)==null?void 0:R.id)||"tool-message-missing"}:${(P==null?void 0:P.toolCallId)||"tool-call-missing"}`},[e]),c=m.useMemo(()=>{const C=e[0];return C?$l(C):null},[e]),[d,u]=m.useState(()=>{const C=Il(t,l);return C?C.isExpanded:s}),[h,f]=m.useState(()=>{const C=Il(t,l);return C?new Set(C.expandedTools):new Set(s&&c?[c]:[])});m.useEffect(()=>{const C=Il(t,l);if(C){u(C.isExpanded),f(new Set(C.expandedTools));return}u(s),f(new Set(s&&c?[c]:[]))},[s,c,t,l]),m.useEffect(()=>{const C=new Set(e.map(P=>$l(P)));f(P=>{const v=new Set;let M=!1;return P.forEach(E=>{C.has(E)?v.add(E):M=!0}),!M&&v.size===P.size?P:v})},[e]),m.useEffect(()=>{r1(t,l,{isExpanded:d,expandedTools:Array.from(h)})},[t,l,d,h]);const{completedCount:g,pendingCount:y,hasErrors:p}=m.useMemo(()=>{let C=0,P=0,v=!1;return e.forEach(M=>{M.result?(C++,M.result.isError&&(v=!0)):P++}),{completedCount:C,pendingCount:P,hasErrors:v}},[e]),x=m.useMemo(()=>y>0?{color:"processing",text:o("components.toolSession.completedProgress",{completed:g,total:e.length})}:p?{color:"warning",text:o("components.toolSession.completedWithErrors",{completed:g})}:{color:"success",text:o("components.toolSession.completedOnly",{completed:g})},[g,y,p,e.length,o]),b=m.useMemo(()=>{let C=0,P=0,v=0;return e.forEach(M=>{var R,T;const E=(T=(R=M.result)==null?void 0:R.result)==null?void 0:T.result;if(!E)return;const _=Pc(E);_&&(C+=_.added,P+=_.removed,v+=1)}),{added:C,removed:P,changedTools:v}},[e]),S=m.useMemo(()=>{var v,M,E;if(e.length!==1)return o("components.toolSession.title");const C=(E=(M=(v=e[0])==null?void 0:v.call)==null?void 0:M.toolCalls)==null?void 0:E[0];if(!C)return o("components.toolSession.title");const P=Xn(C.toolName);return P?`MCP ${P.serverId}: ${P.toolName}`:C.toolName||o("components.toolSession.title")},[e,o]),w=m.useMemo(()=>e.map((C,P)=>{const v=C.call.toolCalls[0];if(!v)return null;const M=l1(C,a,o),E=c1(v.toolName,v.parameters),_=Xn(v.toolName),R=C.result?Pc(C.result.result.result):null,T=C.result?fa(C.result.result.result):null,D=i1(C);return{key:$l(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:[P+1,"."]}),r.jsx("span",{style:{flexShrink:0},children:M.icon}),_?r.jsxs(H,{size:"small",wrap:!1,children:[r.jsx(oe,{color:"purple",style:{marginInlineEnd:0},children:"MCP"}),r.jsx(Qt,{strong:!0,style:{fontSize:a.fontSizeSM},children:_.toolName}),r.jsx(Qt,{type:"secondary",style:{fontSize:a.fontSizeSM},children:r.jsx(Qt,{code:!0,style:{fontSize:a.fontSizeSM},children:_.serverId})})]}):r.jsx(Qt,{strong:!0,style:{fontSize:a.fontSizeSM,flexShrink:0},children:v.toolName}),r.jsx(Qt,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:a.fontSizeSM},children:E}),T&&r.jsx(Qt,{type:"secondary",ellipsis:!0,style:{maxWidth:180,fontSize:a.fontSizeSM},children:T.file_path.split(/[\\/]/).pop()||T.file_path}),R&&r.jsxs(H,{size:4,style:{marginLeft:a.marginXS},children:[r.jsxs(Qt,{style:{color:a.colorSuccess,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",R.added]}),r.jsxs(Qt,{style:{color:a.colorError,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",R.removed]})]}),n&&r.jsx(ke,{title:D.length>0?o("components.toolSession.deleteMessage"):o("components.toolSession.noPersistedMessage"),children:r.jsx(U,{type:"text",size:"small",danger:!0,icon:r.jsx(yn,{}),"aria-label":o("components.toolSession.deleteMessage"),"data-testid":`delete-tool-message-${o1(C)}`,disabled:D.length===0,onClick:$=>{$.preventDefault(),$.stopPropagation(),D.length!==0&&n(D)}})})]}),children:r.jsxs(H,{direction:"vertical",style:{width:"100%"},size:a.marginSM,children:[r.jsx(Ud,{toolName:v.toolName,parameters:v.parameters,toolCallId:v.toolCallId,streamingOutput:v.streamingOutput,defaultExpanded:!1}),C.result&&C.result.result.display_preference!=="Hidden"&&r.jsx(Wd,{content:C.result.result.result,toolName:v.toolName,status:C.result.isError?"error":"success",timestamp:C.result.createdAt,defaultCollapsed:!1})]}),style:{borderBottom:P<e.length-1?`1px solid ${a.colorBorderSecondary}`:void 0}}}).filter(C=>C!==null),[n,o,a,e]),k=r.jsx("div",{style:{padding:a.paddingSM},children:r.jsx(ws,{ghost:!0,activeKey:Array.from(h),onChange:C=>{const P=new Set(Array.isArray(C)?C:C?[C]:[]);f(P)},items:w})}),j={backgroundColor:a.colorBgElevated,border:`1px solid ${a.colorBorder}`,borderRadius:a.borderRadiusLG,overflow:"hidden"};return i?r.jsx("div",{style:{width:"100%"},children:r.jsx("div",{style:j,children:k})}):r.jsxs("div",{style:j,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(vr,{style:{color:a.colorPrimary}}),r.jsx(Qt,{strong:!0,style:{flex:1},children:S}),r.jsx(Gc,{count:e.length,style:{backgroundColor:a.colorPrimary}}),b.changedTools>0&&r.jsxs(H,{size:4,style:{marginInlineStart:a.marginXS},children:[r.jsxs(Qt,{style:{color:a.colorSuccess,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",b.added]}),r.jsxs(Qt,{style:{color:a.colorError,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",b.removed]})]}),r.jsx(Qt,{type:"secondary",style:{fontSize:a.fontSizeSM},children:x.text}),r.jsx("div",{style:{marginLeft:a.marginXS},children:d?r.jsx(cs,{style:{color:a.colorTextSecondary}}):r.jsx(Ks,{style:{color:a.colorTextSecondary}})})]}),d&&k]})},ox=m.memo(d1);ox.displayName="ToolSessionCard";const{Content:u1}=dr,{Text:Fh}=ce,m1=24,h1=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};function Dl(e){return"type"in e&&(e.type==="tool_session"||e.type==="compression_divider")?e.id:e.message.id}const p1=({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:f,interactionState:g,padding:y,selectionMode:p,selectedMessageIds:x,selectableMessageIds:b,onToggleMessageSelection:S})=>{const{t:w}=se(),k=m.useRef(c);k.current=c;const j=m.useCallback(R=>{const T=k.current[R];return T?Dl(T):String(R)},[]),C=oC({count:c.length,getScrollElement:()=>l.current,estimateSize:()=>120,overscan:5,gap:d,getItemKey:j}),P=(R,T)=>{if(!p)return null;const D=b.has(R);return r.jsx(sf,{checked:x.has(R),disabled:!D,onChange:()=>{D&&S(R)},style:{marginTop:8,marginLeft:T==="flex-end"?8:0,marginRight:T==="flex-start"?8:0}})},v=R=>{const T=s(R);if(T.type==="compression_divider"){const D=h1(T.createdAt);return r.jsx("div",{role:"note","aria-label":w("chat.compression.timelineAria",{detail:T.label,time:D,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(J,{align:"center",justify:"space-between",gap:8,wrap:!0,children:[r.jsxs(J,{align:"center",gap:8,wrap:!0,children:[r.jsx(oe,{color:"gold",icon:r.jsx(tf,{}),children:w("chat.compression.tag","Context compressed")}),r.jsx(Fh,{strong:!0,style:{fontSize:12},children:T.label})]}),r.jsx(Fh,{type:"secondary",style:{fontSize:11},children:D})]})})}return T.type==="tool_session"?r.jsx(J,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:r.jsx("div",{id:`message-${T.id}`,style:{width:"100%",maxWidth:h.xs?"100%":"90%"},children:r.jsx(ox,{tools:T.tools,sessionId:T.sessionId,createdAt:T.createdAt,defaultExpanded:!1,onDeleteMessageIds:t?o:void 0})})}):T.message.role==="system"?r.jsxs(J,{align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[P(T.message.id,"flex-start"),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsx(Ty,{currentChat:e,message:T.message})})]}):r.jsxs(J,{justify:T.align,align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[T.align==="flex-start"&&P(T.message.id,T.align),r.jsx("div",{style:{width:T.message.role==="user"?"85%":"100%",maxWidth:h.xs?"100%":"90%"},children:r.jsx(sx,{sessionId:t,message:T.message,messageType:T.messageType,onDelete:T.message.id===f?void 0:n})}),T.align==="flex-end"&&P(T.message.id,T.align)]})},M=(u||i)&&c.length>0,E=C.getVirtualItems(),_=c.length>m1;return r.jsxs(u1,{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:[M&&(_?r.jsx("div",{style:{position:"relative",width:"100%",height:C.getTotalSize()},children:E.map(R=>{const T=c[R.index];if(!T)return null;const D=Dl(T);return r.jsx("div",{"data-chat-entry-id":D,"data-index":R.index,ref:C.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${R.start}px)`},children:r.jsx("div",{className:"messageEnter",children:v(T)})},R.key)})}):r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:d,width:"100%"},children:c.map(R=>{const T=Dl(R);return r.jsx("div",{"data-chat-entry-id":T,className:"messageEnter",children:v(R)},T)})})),g.matches("THINKING")&&t&&r.jsx("div",{className:"streaming-card-enter",style:{paddingTop:d},children:r.jsx(J,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:r.jsx("div",{style:{width:"100%",maxWidth:h.xs?"100%":"90%"},children:r.jsx(nx,{sessionId:t})})})})]})},{Text:Xr}=ce,f1=e=>({pending:{icon:r.jsx(Zs,{}),color:e.colorTextTertiary,textKey:"components.todoList.status.pending",tagColor:"default"},in_progress:{icon:r.jsx(Jc,{spin:!0}),color:e.colorPrimary,textKey:"components.todoList.status.inProgress",tagColor:"processing"},completed:{icon:r.jsx(Qs,{}),color:e.colorSuccess,textKey:"components.todoList.status.completed",tagColor:"success"},blocked:{icon:r.jsx(Ei,{}),color:e.colorError,textKey:"components.todoList.status.blocked",tagColor:"error"}}),g1=({sessionId:e,initialCollapsed:t=!0})=>{const{t:s}=se(),{token:n}=pe.useToken(),o=pt.useMemo(()=>f1(n),[n]),a=N(P=>P.chats.find(v=>v.id===e)),i=(a==null?void 0:a.kind)==="child"&&(a.parentSessionId||a.rootSessionId)||e,l=N(P=>P.taskLists[i]),c=N(P=>P.activeItems[i]),d=N(P=>P.evaluationStates[i]),[u,h]=m.useState(t),[f,g]=m.useState(!1),y=(d==null?void 0:d.isEvaluating)||!1,p=(d==null?void 0:d.reasoning)||null,x=l?{session_id:l.session_id,title:l.title,items:l.items,progress:{completed:l.items.filter(P=>P.status==="completed").length,total:l.items.length,percentage:l.items.length>0?Math.round(l.items.filter(P=>P.status==="completed").length/l.items.length*100):0}}:null;if(!x)return null;const b=()=>{f||h(!u)},S=P=>{P.stopPropagation(),g(!f),f||h(!1)},{title:w,items:k,progress:j}=x,C=j.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&&!f?.9:1},styles:{body:{padding:u?"12px 16px":16}},title:r.jsxs(H,{onClick:b,style:{cursor:"pointer",width:"100%"},children:[r.jsx(yb,{style:{color:n.colorPrimary}}),r.jsx(Xr,{strong:!0,style:{fontSize:15},children:w||s("components.todoList.title")}),y&&r.jsx(oe,{icon:r.jsx(Jc,{spin:!0}),color:"processing",children:s("components.todoList.evaluating")}),!u&&j.total>0&&r.jsx(Gc,{count:`${j.completed}/${j.total}`,style:{backgroundColor:C?n.colorSuccess:n.colorPrimary}})]}),extra:r.jsxs(H,{children:[j.total>0&&u&&r.jsxs(Xr,{type:"secondary",style:{fontSize:13},children:[j.completed,"/",j.total,C&&r.jsx(Qs,{style:{color:n.colorSuccess,marginLeft:4}})]}),r.jsx(ke,{title:s(f?"components.todoList.unpin":"components.todoList.pin"),children:r.jsx("span",{onClick:S,style:{cursor:"pointer",color:f?n.colorPrimary:n.colorTextSecondary,fontSize:16},children:f?r.jsx(Jl,{}):r.jsx(Kc,{})})}),!f&&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(Ks,{}):r.jsx(cs,{})})]}),children:!u&&r.jsxs(r.Fragment,{children:[p&&r.jsx(Ne,{icon:r.jsx(Qc,{}),message:s("components.todoList.llmEvaluation"),description:p,type:"info",showIcon:!0,style:{marginBottom:16}}),j.total>0&&r.jsx("div",{style:{marginBottom:16},children:r.jsx(Zc,{percent:j.percentage,size:"small",status:C?"success":"active",format:P=>r.jsxs(Xr,{type:"secondary",children:[P,"%"]})})}),r.jsx(nt,{size:"small",dataSource:k,renderItem:P=>{const v=o[P.status],M=c===P.id,E=s(v.textKey);return r.jsx(nt.Item,{style:{padding:"12px 0",borderLeft:M?`3px solid ${n.colorPrimary}`:"3px solid transparent",paddingLeft:M?12:15,backgroundColor:M?n.colorPrimaryBg:"transparent",borderRadius:4,marginBottom:4},children:r.jsx("div",{style:{width:"100%"},children:r.jsxs(H,{align:"start",style:{width:"100%"},children:[r.jsx(ke,{title:E,children:r.jsx("span",{style:{color:v.color,fontSize:16},children:v.icon})}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsx(Xr,{style:{textDecoration:P.status==="completed"?"line-through":"none",color:P.status==="completed"?n.colorTextSecondary:n.colorText,fontWeight:M?500:400},children:P.description}),r.jsx("div",{style:{marginTop:4},children:r.jsxs(H,{size:8,wrap:!0,children:[r.jsx(oe,{color:v.tagColor,children:E}),P.tool_calls_count!==void 0&&P.tool_calls_count>0&&r.jsxs(oe,{icon:r.jsx(vr,{}),color:"processing",children:[P.tool_calls_count," ",s("components.todoList.tools")]}),P.depends_on.length>0&&r.jsx(ke,{title:s("components.todoList.dependsOn",{deps:P.depends_on.join(", ")}),children:r.jsxs(oe,{icon:r.jsx(gb,{}),children:[P.depends_on.length," ",s("components.todoList.dependencies")]})})]})}),P.notes&&r.jsx(Xr,{type:"secondary",style:{display:"block",marginTop:6,fontSize:12,padding:"4px 8px",backgroundColor:n.colorFillQuaternary,borderRadius:4},children:P.notes})]})]})})})}})]})})},y1="_questionCard_15meh_1",x1="_questionHeader_15meh_8",b1="_headerLeft_15meh_27",v1="_questionIcon_15meh_35",S1="_questionText_15meh_40",w1="_collapseBtn_15meh_52",_1="_questionBody_15meh_57",T1="_optionsGroup_15meh_61",k1="_optionItem_15meh_65",j1="_customHint_15meh_81",C1="_questionFooter_15meh_93",Zt={questionCard:y1,questionHeader:x1,headerLeft:b1,questionIcon:v1,questionText:S1,collapseBtn:w1,questionBody:_1,optionsGroup:T1,optionItem:k1,customHint:j1,questionFooter:C1},{Text:Da}=ce,{useToken:M1}=pe,P1=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
|
+
`):""},E1=({sessionId:e,onResponseSubmitted:t,onQuestionAppeared:s})=>{var Y;const{t:n}=se(),{token:o}=M1(),[a,i]=m.useState(null),[l,c]=m.useState(null),[d,u]=m.useState(!1),[h,f]=m.useState(!0),[g,y]=m.useState(!1),p=m.useRef(0),x=m.useRef(null),b=m.useRef(s);b.current=s;const S=N(F=>F.setSessionProcessing),w=N(F=>F.setPendingQuestionRespond),k=N(F=>F.clearPendingQuestionRespondForSession),j=N(F=>F.chats.find(q=>q.id===e)||null),C=N(F=>{var q;return e?(q=F.inputStates)==null?void 0:q[e]:void 0}),P=Yt(F=>F.currentProvider),v=Yt(F=>F.providerConfig),M=m.useMemo(()=>{var F;return(F=v.providers[P])==null?void 0:F.reasoning_effort},[v,P]),E=m.useMemo(()=>e?ld(e):void 0,[e]),_=((Y=j==null?void 0:j.config)==null?void 0:Y.reasoningEffort)??(C==null?void 0:C.reasoningEffort)??E??M??"medium",R=N(F=>e?F.isSessionProcessing(e):!1),T=m.useCallback(async()=>{try{const F=await ye.get(`respond/${e}/pending`);F.has_pending_question?(i(q=>{const K=Oa({sessionId:e,question:F.question,options:F.options,allowCustom:F.allow_custom,toolCallId:F.tool_call_id});return(q!=null&&q.has_pending_question?Oa({sessionId:e,question:q.question,options:q.options,allowCustom:q.allow_custom,toolCallId:q.tool_call_id}):null)===K?q??F:F}),p.current=0):(i(null),x.current=null,p.current+=1)}catch(F){if(F instanceof Error&&F.message.includes("404")){i(null),x.current=null,p.current+=1;return}console.error("Failed to fetch pending question:",F)}finally{f(!1)}},[e]);m.useEffect(()=>{p.current=0,x.current=null,f(!0),c(null),y(!1)},[e]),m.useEffect(()=>{var F;if(a!=null&&a.has_pending_question){const q=Oa({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}),K=x.current===q;w({sessionId:e,question:(a==null?void 0:a.question)||"",options:(a==null?void 0:a.options)||[],allowCustom:(a==null?void 0:a.allow_custom)??!0,toolCallId:(a==null?void 0:a.tool_call_id)??null}),K||(c(null),y(!1),(F=b.current)==null||F.call(b)),x.current=q}else x.current=null,k(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,k]);const D=a!=null&&a.has_pending_question||R?3e3:15e3;m.useEffect(()=>{T();const F=setInterval(()=>{d||T()},D);return()=>clearInterval(F)},[T,d,D]),m.useEffect(()=>{if(typeof window>"u")return;const F=q=>{var be;const G=((be=q.detail)==null?void 0:be.sessionId)??null;!G||G!==e||(i(null),c(null),p.current=0,k(e))};return window.addEventListener(hr,F),()=>{window.removeEventListener(hr,F)}},[e,k]);const $=m.useCallback(F=>{c(F)},[]);m.useEffect(()=>()=>{k(e)},[k,e]);const I=async()=>{if(!l||l==="custom"){fe.warning(n("components.questionDialog.selectOptionWarning"));return}u(!0);try{const F=await ye.post(`respond/${e}`,{response:l,reasoning_effort:_});fe.success(n("components.questionDialog.responseSubmitted")),i(null),c(null),p.current=0,typeof window<"u"&&window.dispatchEvent(new CustomEvent(hr,{detail:{sessionId:e}}));const q=F==null?void 0:F.auto_resume_status;["started","already_running"].includes(q||"")?e&&S(e,!0):q==="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:O,options:A,allow_custom:z}=a,L=P1(O);return r.jsxs("div",{className:Zt.questionCard,style:{background:o.colorBgContainer,borderColor:o.colorBorderSecondary,border:`1px solid ${o.colorBorderSecondary}`},children:[r.jsxs("div",{className:Zt.questionHeader,"data-collapsed":g?"true":"false",onClick:()=>y(F=>!F),role:"button",tabIndex:0,onKeyDown:F=>{(F.key==="Enter"||F.key===" ")&&y(q=>!q)},children:[r.jsxs("span",{className:Zt.headerLeft,children:[r.jsx("span",{className:Zt.questionIcon,children:"🤔"}),r.jsx(Da,{strong:!0,className:Zt.questionText,style:{color:o.colorPrimary,whiteSpace:"pre-wrap"},title:g?L:void 0,children:L})]}),r.jsx(U,{type:"text",size:"small",icon:g?r.jsx(cs,{}):r.jsx(ed,{}),className:Zt.collapseBtn,tabIndex:-1})]}),!g&&r.jsxs("div",{className:Zt.questionBody,children:[r.jsx(is.Group,{className:Zt.optionsGroup,value:l,onChange:F=>$(F.target.value),children:r.jsxs(H,{direction:"vertical",size:4,style:{width:"100%"},children:[A==null?void 0:A.map((F,q)=>r.jsx(is,{value:F,className:Zt.optionItem,children:r.jsx(Da,{style:{color:o.colorText},children:F})},q)),z&&r.jsx(is,{value:"custom",className:Zt.optionItem,children:r.jsxs(H,{size:4,children:[r.jsx(Sr,{}),r.jsx(Da,{style:{color:o.colorText},children:n("components.questionDialog.otherTypeBelow")})]})})]})}),l==="custom"&&r.jsx("div",{className:Zt.customHint,children:r.jsx(Da,{type:"secondary",style:{fontSize:12},children:n("components.questionDialog.customAnswerTip")})}),l&&l!=="custom"&&r.jsx("div",{className:Zt.questionFooter,children:r.jsx(U,{type:"primary",size:"small",onClick:I,loading:d,children:n("components.questionDialog.confirm")})})]})]})};function ax(e){return typeof e.maxContextTokens=="number"&&e.maxContextTokens>0?e.maxContextTokens:e.budgetLimit>0?e.budgetLimit:0}function ix(e){const t=ax(e);return t===0?0:e.totalTokens/t*100}function R1(e){const t=ix(e);return t>=90?"error":t>=70?"warning":t>=50?"success":"default"}function Vr(e){return e.toLocaleString()}const A1=({usage:e,showDetails:t=!0,size:s="small",className:n=""})=>{const{t:o}=se(),a=ax(e),i=ix(e),l=h=>{const f=Math.round(h*10)/10;return Number.isInteger(f)?f.toFixed(0):f.toFixed(1)},c=R1(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"),":"," ",Vr(e.totalTokens)," / ",Vr(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"),": ",Vr(e.systemTokens)]}),e.summaryTokens>0&&r.jsxs("div",{children:[o("components.tokenUsage.summary"),": ",Vr(e.summaryTokens)]}),r.jsxs("div",{children:[o("components.tokenUsage.messages"),": ",Vr(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(H,{className:`token-usage-display ${n}`,size:4,align:"center",style:{lineHeight:1},children:[r.jsx(Zc,{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),"%"]})]})})},On=class On{static getInstance(){return On.instance||(On.instance=new On),On.instance}parseUserCommand(t){Ke("[ToolService]",`[ToolService] parseUserCommand: Parsing content: "${t}"`);const s=t.trim();if(!s.startsWith("/"))return Ke("[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 Ke("[ToolService]","[ToolService] parseUserCommand: Successfully parsed command:",i),i}return Ke("[ToolService]","[ToolService] parseUserCommand: Failed to parse tool name from content."),null}parseAIResponseToToolCall(t){return this.parseUserCommand(t)}async executeTool(t){Ke("[ToolService]","[ToolService] executeTool: Attempting to execute tool via HTTP with request:",t);try{const s=await we.post("tools/execute",t),n=JSON.parse(s.result);return Ke("[ToolService]","[ToolService] executeTool: Parsed structured result:",n),n}catch(s){throw console.error("[ToolService] executeTool: HTTP tool execution failed:",s),s instanceof Wn?new Error(`Workflow execution failed: ${s.message}`):s}}};Ye(On,"instance");let Uc=On;const I1=new Uc,{Text:dn}=ce,{useToken:lx}=pe,$1="chat-session-sub-sessions-collapsed:",D1=3,F1=600,Za=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"},L1=(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")},cx=e=>`${$1}${e}`,Fl=e=>{if(typeof window>"u")return!1;try{const t=window.localStorage.getItem(cx(e));return t==="1"?!0:t==="0"?!1:null}catch{return null}},O1=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(cx(e),t?"1":"0")}catch{}},z1=({parentSessionId:e})=>{const{t}=se(),{token:s}=lx(),[n,o]=m.useState(()=>Fl(e)??!1),[a,i]=m.useState(null),[l,c]=m.useState(null),[d,u]=m.useState(null),h=N(T=>T.subSessionsByParent),f=N(T=>T.chats),g=N(T=>T.loadChatHistory),y=N(T=>T.refreshChats),p=N(T=>T.setSessionProcessing),x=N(T=>T.pinSession),b=N(T=>T.unpinSession),S=N(T=>T.deleteSession),w=N(T=>T.upsertSubSessionProgress),k=N(T=>T.clearSubSessionProgress),j=m.useMemo(()=>{const T=h[e]||{};return Object.entries(T).map(([D,$])=>({childSessionId:D,...$}))},[e,h]),C=m.useMemo(()=>f.filter(T=>T.kind==="child"&&T.parentSessionId===e).sort((T,D)=>{const $=Date.parse(T.updatedAt||"")||0;return(Date.parse(D.updatedAt||"")||0)-$}),[f,e]),P=m.useMemo(()=>{const T=new Map(j.map($=>[$.childSessionId,$])),D=[];for(const $ of C){const I=T.get($.id);D.push({childSessionId:$.id,title:(I==null?void 0:I.title)||$.title,status:Za(L1($,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}),T.delete($.id)}for(const $ of T.values())D.push({childSessionId:$.childSessionId,title:$.title,status:Za($.status),error:$.error,lastHeartbeatAt:$.lastHeartbeatAt,lastEventAt:$.lastEventAt,outputPreview:$.outputPreview});return D},[C,j]);m.useEffect(()=>{o(Fl(e)??!1)},[e]),m.useEffect(()=>{Fl(e)===null&&o(P.length>D1)},[e,P.length]);const v=m.useCallback(()=>{o(T=>{const D=!T;return O1(e,D),D})},[e]),M=m.useCallback(T=>T instanceof Error&&T.message.trim()?T.message:"Failed to run child session",[]),E=m.useCallback(async(T,D="regenerate")=>{i(T),w(e,T,{status:"running",error:void 0,lastEventAt:new Date().toISOString()}),p(T,!0);try{const $=D==="error_retry"?"error_retry":"after_last_user",I=await Un.truncateSessionMessages(T,{mode:$});(D==="regenerate"||(I.messages_removed??0)>0)&&await g(T,{mode:"replace"});const O=await Un.execute(T);if(O.status==="started"||O.status==="already_running")return;if(O.status==="completed"){p(T,!1),w(e,T,{status:"completed",error:void 0,lastEventAt:new Date().toISOString()}),await y();return}throw new Error(`Execute failed: ${O.status}`)}catch($){p(T,!1),w(e,T,{status:"error",error:M($),lastEventAt:new Date().toISOString()})}finally{i($=>$===T?null:$)}},[g,e,y,p,M,w]),_=m.useCallback(async T=>{const D=typeof window<"u"?window.prompt.bind(window):null;if(!D)return;const $=D("Send a follow-up message to this child session:","Continue from where you left off.");if($===null)return;const I=$.trim();if(!I){w(e,T,{status:"error",error:"Follow-up message cannot be empty.",lastEventAt:new Date().toISOString()});return}c(T),w(e,T,{status:"running",error:void 0,lastEventAt:new Date().toISOString()}),p(T,!0);try{const O=await I1.executeTool({tool_name:"sub_session_manager",session_id:e,parameters:[{name:"action",value:"send_message"},{name:"child_session_id",value:T},{name:"message",value:I},{name:"auto_run",value:"true"}]});if(!O.success)throw new Error(O.result||"Follow-up failed");let A="running";try{JSON.parse(O.result).status==="pending"&&(A="pending")}catch{A="running"}w(e,T,{status:A,error:void 0,lastEventAt:new Date().toISOString()}),await y()}catch(O){p(T,!1),w(e,T,{status:"error",error:O instanceof Error&&O.message.trim()?O.message:"Failed to continue child session",lastEventAt:new Date().toISOString()})}finally{c(O=>O===T?null:O)}},[e,y,p,w]),R=m.useCallback(async T=>{u(T);try{await S(T),k(e,T)}finally{u(D=>D===T?null:D)}},[k,S,e]);return P.length===0?null:r.jsxs(ee,{size:"small",className:"lotus-settings-card",style:{marginBottom:s.marginMD},"data-testid":"sub-sessions-panel",title:r.jsxs(dn,{strong:!0,children:[t("chat.subSessions.title")," ",r.jsxs(dn,{type:"secondary",children:["(",P.length,")"]})]}),extra:r.jsx(U,{type:"text",size:"small",icon:n?r.jsx(cs,{}):r.jsx(ed,{}),onClick:v,"data-testid":"sub-sessions-toggle",children:t(n?"chat.subSessions.expand":"chat.subSessions.collapse")}),children:[n?r.jsx(dn,{type:"secondary","data-testid":"sub-sessions-collapsed-hint",children:t("chat.subSessions.hiddenHint",{count:P.length})}):r.jsx(J,{vertical:!0,gap:s.marginSM,"data-testid":"sub-sessions-list",style:{maxHeight:`${F1}px`,overflowY:"auto",paddingRight:s.paddingXS},children:P.map(T=>{const D=Za(T.status),$=D==="running",I=a===T.childSessionId,O=l===T.childSessionId,A=d===T.childSessionId,z=I||O||A;return r.jsxs(J,{align:"flex-start",justify:"space-between",gap:s.marginSM,className:"lotus-settings-list-item",style:{padding:s.paddingSM,borderRadius:s.borderRadiusSM},children:[r.jsxs(J,{vertical:!0,style:{flex:1,minWidth:0},children:[r.jsxs(J,{align:"center",gap:s.marginXS,style:{minWidth:0},children:[r.jsx(dn,{strong:!0,ellipsis:!0,style:{minWidth:0},children:T.title||"Child Session"}),r.jsx(oe,{color:D==="running"?"processing":D==="completed"?"success":D==="error"||D==="failed"?"error":D==="cancelled"?"warning":"default",style:{marginInlineEnd:0,flex:"0 0 auto"},children:D}),T.pinned?r.jsx(oe,{color:"warning",style:{marginInlineEnd:0,flex:"0 0 auto"},children:"Pinned"}):null]}),r.jsxs(dn,{type:"secondary",style:{fontSize:12,marginTop:2},children:[T.childSessionId.slice(0,8),T.updatedAt?` • ${T.updatedAt}`:"",T.lastHeartbeatAt?` • heartbeat: ${T.lastHeartbeatAt}`:""]}),T.outputPreview?r.jsx(dn,{type:"secondary",style:{marginTop:s.marginXS,fontSize:13},ellipsis:!0,children:T.outputPreview}):null,T.error?r.jsx(dn,{type:"danger",style:{marginTop:s.marginXS},children:T.error}):null]}),r.jsxs(J,{gap:8,children:[r.jsx(U,{size:"small",disabled:z,onClick:()=>{Ni(T.childSessionId),g(T.childSessionId)},children:t("chat.subSessions.open")}),r.jsx(U,{size:"small",loading:O,disabled:A||I||$,"data-testid":`sub-session-continue-${T.childSessionId}`,onClick:()=>{_(T.childSessionId)},children:t("chat.subSessions.continue")}),r.jsx(fr,{trigger:["click"],menu:{items:[{key:"regenerate",label:t("chat.actions.regenerate")},{key:"error_retry",label:t("chat.actions.retryFailed")}],onClick:({key:L})=>{E(T.childSessionId,L)}},disabled:A||$||O,children:r.jsx(U,{size:"small",loading:I,disabled:A||$||O,"data-testid":`sub-session-retry-${T.childSessionId}`,children:t("chat.subSessions.retry")})}),typeof T.pinned=="boolean"?r.jsx(U,{size:"small",disabled:z,onClick:()=>{T.pinned?b(T.childSessionId):x(T.childSessionId)},children:T.pinned?t("chat.actions.unpin"):t("chat.actions.pin")}):null,r.jsx(U,{danger:!0,size:"small",loading:A,disabled:I,"data-testid":`sub-session-delete-${T.childSessionId}`,onClick:()=>{R(T.childSessionId)},children:t("common.delete")})]})]},T.childSessionId)})}),!n&&P.length>1&&r.jsx(N1,{items:P})]})},N1=({items:e})=>{const{token:t}=lx(),s=e.reduce((o,a)=>{const i=Za(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(dn,{type:"secondary",style:{fontSize:11,marginTop:t.marginXS,display:"block"},children:n.join(" · ")})},{useToken:B1}=pe,W1=e=>{const t=e.replace(/\/$/,"").split("/").filter(Boolean);return t.length<=2?e:`~/${t.slice(-2).join("/")}`},U1=({sessionId:e})=>{const{t}=se(),{token:s}=B1(),n=N(Vn(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(J,{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(si,{}),bordered:!1,children:W1(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(xb,{}),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(Pi,{}),bordered:!1,children:l})})]})})},q1=new Set(["Write","Edit","apply_patch","NotebookEdit"]),H1=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},Y1=(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`},X1=e=>{var h,f;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 p=g;if(p.isError&&o++,q1.has(p.toolName)){const x=H1(((f=p.result)==null?void 0:f.result)??"");x&&c.add(x)}}if("type"in g&&g.type==="text"){s++;const p=g.content||"";p.length>0&&p.length>30&&(l=p.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?Y1(d,u):""}},V1=({sessionId:e})=>{const{t}=se(),{token:s}=pe.useToken(),[n,o]=m.useState(!1),a=N(Vn(e)),i=a==null?void 0:a.messages,l=m.useMemo(()=>!i||i.length===0?null:X1(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(bb,{})}),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(ni,{className:"lotus-session-summary-stat-icon"}),r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.messageCount})]}),l.toolCallCount>0&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(Qd,{className:"lotus-session-summary-stat-icon"}),r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolCallCount})]}),c&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(yr,{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(cs,{})})]}),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(ni,{className:"lotus-session-summary-stat-icon"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.messageCount})," ",t("sessionSummary.messages","messages")]})]}),r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx("span",{className:"lotus-session-summary-stat-icon",children:"👤"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.userMessageCount})," ",t("sessionSummary.userTurns","user")]})]}),r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx("span",{className:"lotus-session-summary-stat-icon",children:"🤖"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.assistantMessageCount})," ",t("sessionSummary.assistantTurns","assistant")]})]}),l.toolCallCount>0&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(Qd,{className:"lotus-session-summary-stat-icon"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolCallCount})," ",t("sessionSummary.toolCalls","tool calls")]})]}),l.toolErrorCount>0&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:"#ff4d4f"},children:[r.jsx(oa,{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(Zs,{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(Pi,{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(yr,{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})]})]})]})},dx="chat_scroll_anchors_v1";function K1(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 ux(){try{const e=localStorage.getItem(dx);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const s={};for(const[n,o]of Object.entries(t))K1(o)&&(s[n]=o);return s}catch{return{}}}function G1(e){try{localStorage.setItem(dx,JSON.stringify(e))}catch(t){console.warn("[ScrollAnchor] Failed to write:",t)}}function J1(e){return ux()[e]??null}function Q1(e,t){const s=ux();s[e]=t,G1(s)}const Ll=1,Z1=3,eR=2e3;function tR(e,t){const s=Math.max(0,e.scrollHeight-e.clientHeight);return Math.min(Math.max(0,t),s)}function sR(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 f=t.getBoundingClientRect(),y=h.getBoundingClientRect().top-f.top,p=tR(t,t.scrollTop+(y-n));if(Math.abs(t.scrollTop-p)>Ll)t.scrollTop=p,l=0;else{const b=Number.isFinite(d)?Math.abs(p-d)<=Ll:!1,S=Math.abs(t.scrollTop-c)<=Ll;l=b&&S?l+1:0}d=p,c=t.scrollTop;const x=performance.now()-i>eR;if(l>=Z1||x){a();return}requestAnimationFrame(u)};requestAnimationFrame(u)})}const nR=300,rR=.5;function oR(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 mx(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 Lh(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function aR(e,t){const s=Lh(e.createdAt);if(s!=null){let n=null,o=Number.POSITIVE_INFINITY;for(let a=0;a<t.length;a++){const i=Lh(mx(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 Hd(e){return Array.from(e.querySelectorAll("[data-chat-entry-id]"))}function iR(e,t){const s=Hd(e);for(const n of s)if(n.dataset.chatEntryId===t)return n;return null}function lR(e,t){const s=Hd(e);if(s.length===0)return null;const n=Math.max(0,Math.min(s.length-1,t));return s[n]??null}function cR(e){const t=Hd(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 dR(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 p=()=>{d.current=!0};return y.addEventListener("wheel",p,{passive:!0}),y.addEventListener("touchmove",p,{passive:!0}),y.addEventListener("pointerdown",p),()=>{y.removeEventListener("wheel",p),y.removeEventListener("touchmove",p),y.removeEventListener("pointerdown",p)}},[s]);const u=m.useMemo(()=>{const y=new Map;for(let p=0;p<n.length;p++){const x=oR(n[p]);x&&y.set(x,p)}return y},[n]),h=m.useCallback(()=>{const y=s.current;if(!y||n.length===0)return null;const p=cR(y);if(!p)return null;const x=p.dataset.chatEntryId;if(!x)return null;const b=y.getBoundingClientRect(),S=p.getBoundingClientRect(),w=u.get(x),k=typeof w=="number"?n[w]:void 0;return{v:1,anchorId:x,offsetPx:S.top-b.top,ts:Date.now(),indexHint:w,createdAt:k?mx(k):void 0}},[u,s,n]),f=m.useCallback(y=>{if(a.current)return;const p=h();if(!p)return;const x=c.current;x&&x.anchorId===p.anchorId&&Math.abs(x.offsetPx-p.offsetPx)<=rR||(Q1(y,p),c.current=p)},[h]),g=m.useCallback(y=>{if(!t||a.current)return;l.current&&clearTimeout(l.current);const p=t;l.current=setTimeout(()=>{f(p)},nR)},[t,f]);return m.useEffect(()=>{const y=t;return()=>{y&&(l.current&&(clearTimeout(l.current),l.current=null),f(y))}},[t,f]),m.useLayoutEffect(()=>{if(!t)return;const y=s.current;if(!y||n.length===0||o.current.has(t))return;const p=J1(t);if(!p){o.current.add(t);return}const x=u.get(p.anchorId),b=typeof x=="number"?x:aR(p,n);if(b==null){o.current.add(t);return}l.current&&(clearTimeout(l.current),l.current=null);const S=++i.current;a.current=!0,d.current=!1,y.style.overflowAnchor="none";const w=()=>i.current!==S||d.current;return sR({scrollEl:y,getAnchorElement:()=>iR(y,p.anchorId)??lR(y,b),offsetPx:p.offsetPx,isCancelled:w}).finally(()=>{i.current===S&&(a.current=!1,o.current.add(t),y.style.overflowAnchor="",f(t))}),()=>{i.current===S&&i.current++}},[t,u,n,n.length,s,f]),{handleScroll:g}}const Oh=2,zh=6,uR=({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}=dR({currentSessionId:e,messagesListRef:s,renderableMessages:n}),h=m.useCallback(x=>{const b=s.current;if(!b)return;if(n.length===0){a(!1),l(!1);return}const S=b.scrollHeight-b.scrollTop-b.clientHeight,w=b.scrollTop,k=150,j=150,C=S<k,P=w<j;a(!C),l(!P&&n.length>3),S>k*2?c.current=!0:C&&(c.current=!1),u(x)},[s,n.length,u]),f=m.useCallback(()=>{if(!s.current||n.length===0)return;let b=0,S=-1;const w=()=>{const k=s.current;if(!k)return;const j=Math.max(0,k.scrollHeight-k.clientHeight),C=Math.max(0,k.scrollHeight-k.scrollTop-k.clientHeight),P=k.scrollHeight!==S,v=C>Oh||P||b===0;v&&k.scrollTo({top:j,behavior:b===0?"smooth":"auto"}),S=k.scrollHeight,b+=1,b<zh&&v&&requestAnimationFrame(w)};requestAnimationFrame(w)},[s,n.length]),g=m.useCallback(()=>{if(!s.current)return;let b=0;const S=()=>{const w=s.current;if(!w)return;const k=w.scrollTop>Oh||b===0;k&&w.scrollTo({top:0,behavior:"auto"}),b+=1,b<zh&&k&&requestAnimationFrame(S)};requestAnimationFrame(S)},[s]),y=m.useCallback(()=>{c.current=!1},[]);m.useEffect(()=>{const x=b=>{var E,_;const w=(E=b.detail)==null?void 0:E.messageId;if(!w){console.error("No messageId provided for navigation");return}const k=n.findIndex(R=>"message"in R&&R.message?R.message.id===w:"id"in R?R.id===w:!1);if(k===-1){console.warn("Message not found for navigation:",w);return}const j=n[k],C=j&&"message"in j?j.message.id:j&&"id"in j?j.id:w,P=document.getElementById(`message-${C}`),v=Array.from(((_=s.current)==null?void 0:_.querySelectorAll("[data-chat-entry-id]"))||[]),M=P||v.find(R=>R.dataset.chatEntryId===C);if(!M){console.warn("Message element not found for navigation:",w);return}M.scrollIntoView({behavior:"smooth",block:"center"}),M.classList.add("highlight-message"),setTimeout(()=>{M.classList.remove("highlight-message")},2e3)};return window.addEventListener("navigate-to-message",x),()=>{window.removeEventListener("navigate-to-message",x)}},[s,n]);const p=m.useRef(t.value);return m.useEffect(()=>{const x=t.value;p.current==="IDLE"&&x==="THINKING"&&(y(),f()),p.current=x},[t.value,y,f]),m.useEffect(()=>ze.subscribe(x=>{x.sessionId===e&&(c.current||x.content&&f())}),[e,f]),m.useEffect(()=>{!c.current&&n.length>0&&!d.current&&f(),d.current=!1},[n.length,f]),m.useEffect(()=>{if(!s.current){a(!1),l(!1);return}if(n.length===0){a(!1),l(!1);return}const b=()=>{const w=s.current;if(!w)return;const k=w.scrollHeight-w.scrollTop-w.clientHeight,j=w.scrollTop,C=150,P=150,v=k<C,M=j<P;a(!v),l(!M&&n.length>3)};b();let S=requestAnimationFrame(()=>{b(),S=requestAnimationFrame(b)});return()=>cancelAnimationFrame(S)},[s,n.length,e]),m.useEffect(()=>{d.current=!0,c.current=!1},[e]),{handleMessagesScroll:h,resetUserScroll:y,scrollToBottom:f,scrollToTop:g,showScrollToBottom:o,showScrollToTop:i}};function mR(e){return"type"in e&&e.type==="tool_session"}function hR(e){return"type"in e&&e.type==="compression_divider"}const Nh=e=>{const t=Date.parse(e||"");return Number.isFinite(t)?t:Number.MAX_SAFE_INTEGER},pR=e=>"type"in e?e.createdAt:e.message.createdAt,fR=e=>!("type"in e)&&e.message.role==="system";function gR(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_call"}function yR(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_result"}const Bh=e=>(e??"").trim().toLowerCase()==="conclusion",xR=e=>{const t=(e??"").trim().toLowerCase();return t==="conclusion_with_options"||t==="exitplanmode"||t==="request_permissions"},bR=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"},vR=(e,t)=>{var s;return e.call.id||e.callMessageId||e.resultMessageId||((s=e.result)==null?void 0:s.id)||`tool-message-missing-${t}`},SR=(e,t)=>`tool-session-${vR(e,t)}:${bR(e)}`;function wR(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(gR(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(Bh(c.toolName)){n.add(u);return}if(xR(c.toolName)){n.add(u);const g={...i,id:`${i.id}:tool-call:${d}:${u}`,toolCalls:[{...c,toolCallId:u}]};t.push(g);return}const f={call:{...i,id:`${i.id}:tool-call:${d}:${u}`,toolCalls:[{...c,toolCallId:u}]},callMessageId:i.id};o(u,f),t.push([f])});continue}if(yR(i)){const l=i.toolCallId;if(l&&n.has(l)){n.delete(l),t.push(i);continue}if(Bh(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 _R=(e,t)=>{var l;const{t:s}=se(),n=m.useMemo(()=>{var d;const c=t.find(u=>u.role==="system");return c||((d=e==null?void 0:e.config)!=null&&d.baseSystemPrompt?{id:`system-prompt-${e.id}`,role:"system",content:e.config.baseSystemPrompt,createdAt:new Date(e.createdAt).toISOString()}:null)},[e,t]),o=m.useCallback(c=>!1,[]),a=m.useCallback(c=>{if(hR(c))return{type:"compression_divider",id:c.id,createdAt:c.createdAt,label:c.label};if(mR(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 p;const c=t.filter(x=>{const b=x.role;return!(b!=="user"&&b!=="assistant"&&b!=="system"&&b!=="tool"||o(x))}),d=wR(c),u=[];d.forEach((x,b)=>{var k,j;if(Array.isArray(x)){const C=x[0];u.push({type:"tool_session",id:C?SR(C,b):`tool-session-unknown-${b}`,sessionId:(e==null?void 0:e.id)||"default",tools:x,createdAt:((k=C==null?void 0:C.call)==null?void 0:k.createdAt)||((j=C==null?void 0:C.result)==null?void 0:j.createdAt)||new Date().toISOString()});return}const S=x;let w;if(S.role==="assistant"&&"type"in S){const C="type"in S?S.type:void 0;(C==="text"||C==="plan"||C==="question"||C==="tool_call"||C==="tool_result")&&(w=C)}u.push({message:S,messageType:w})}),!c.some(x=>x.role==="system")&&n&&u.unshift({message:n});const f=((p=e==null?void 0:e.config)==null?void 0:p.compressionEvents)||[],g=u.findIndex(x=>!fR(x)),y=g===-1?u.length:g;for(const x of f){const b={type:"compression_divider",id:`compression-divider-${x.id}`,createdAt:x.createdAt,label:s("chat.compression.timelineDetail",{count:x.messagesCompressed,defaultValue:"{{count}} messages archived"})},S=Nh(x.createdAt),w=u.findIndex((k,j)=>j>=y&&Nh(pR(k))>S);w===-1?u.push(b):u.splice(w,0,b)}return u},[(l=e==null?void 0:e.config)==null?void 0:l.compressionEvents,e==null?void 0:e.id,t,o,n,s]);return{systemPromptMessage:n,renderableMessages:i,convertRenderableEntry:a}},{useToken:TR}=pe,{useBreakpoint:kR}=Ci,{Text:jR}=ce,CR=e=>e.role==="user"?"You":e.role==="assistant"?"Assistant":e.role==="system"?"System":"Message",hx=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},MR=e=>e.map(({message:t,text:s},n)=>{const o=CR(t),a=hx(t.createdAt);return[`## ${n+1}. ${o} · ${a}`,"",s].join(`
|
|
241
|
+
`)}).join(`
|
|
242
|
+
|
|
243
|
+
---
|
|
244
|
+
|
|
245
|
+
`),PR=({sessionId:e,embedded:t=!1})=>{var Re,Xe,rt,ps;const{message:s}=us.useApp(),{t:n}=se(),o=bi(ne=>ne.isAdvanced),a=N(ne=>e??ne.currentSessionId),i=N(Vn(a)),l=N(ne=>ne.deleteMessage),c=N(ne=>ne.loadChatHistory),d=N(ne=>ne.processingChats),u=N(ne=>ne.tokenUsages),h=N(ne=>ne.truncationOccurred),f=N(ne=>ne.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]),p=N(ne=>y?!!ne.taskLists[y]:!1),x=N(ne=>{if(!a)return!1;const Ce=ne.subSessionsByParent[a];return Ce&&Object.keys(Ce).length>0?!0:ne.chats.some(De=>De.kind==="child"&&De.parentSessionId===a)});m.useEffect(()=>{if(!a)return;const ne=N.getState().chats.find(Ce=>Ce.id===a);ne&&Array.isArray(ne.messages)&&ne.messages.length>0||c(a)},[a,c]);const b=a?d.has(a):!1,S=m.useMemo(()=>{var Os;if(!g||g.length===0)return null;const ne=new Map;let Ce=0,De=0,He=0;for(const zs of g){if(!yy(zs))continue;const fs=((Os=zs.result)==null?void 0:Os.result)??"",Ts=fa(fs),Ns=Pc(fs);if(!Ts||!Ns)continue;He+=1,Ce+=Ns.added,De+=Ns.removed;const Bs=ne.get(Ts.file_path);Bs?(Bs.added+=Ns.added,Bs.removed+=Ns.removed,Bs.diffChunks.push(Ts.diff.unified),Bs.truncated=Bs.truncated||!!Ts.diff.truncated):ne.set(Ts.file_path,{added:Ns.added,removed:Ns.removed,diffChunks:[Ts.diff.unified],truncated:!!Ts.diff.truncated})}if(ne.size===0)return null;const Rt=Array.from(ne.entries()).map(([zs,fs])=>({filePath:zs,added:fs.added,removed:fs.removed,unifiedDiff:fs.diffChunks.join(`
|
|
246
|
+
|
|
247
|
+
`),truncated:fs.truncated})).sort((zs,fs)=>zs.filePath.localeCompare(fs.filePath));return{totalAdded:Ce,totalRemoved:De,files:Rt,changedTools:He}},[g]),w=m.useMemo(()=>{const ne=b?"THINKING":"IDLE";return{value:ne,context:{streamingContent:null,toolCallRequest:null,parsedParameters:null},matches:Ce=>Ce===ne}},[b]),k=m.useCallback(ne=>{if(ne.success)return null;switch(ne.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 ne.errorMessage||n("chat.messageActions.deleteFailed")}},[n]),j=m.useCallback(async(ne,Ce)=>{if(!a){const He={success:!1,sessionId:"",messageId:ne,reason:"session_not_found"};return(Ce==null?void 0:Ce.notify)!==!1&&s.error(k(He)),He}const De=await l(a,ne);return!De.success&&(Ce==null?void 0:Ce.notify)!==!1&&s.error(k(De)),De},[a,l,s,k]),C=m.useCallback(async ne=>{const Ce=Array.from(new Set(ne.map(Rt=>Rt.trim()).filter(Boolean)));if(Ce.length===0)return;const He=(await Promise.all(Ce.map(Rt=>j(Rt,{notify:!1})))).filter(Rt=>!Rt.success);if(He.length!==0){if(He.length===1){s.error(k(He[0]));return}s.error(n("chat.messageActions.deleteBatchFailed",{failed:He.length,total:Ce.length}))}},[j,s,k,n]),P=m.useRef(null),{token:v}=TR(),M=kR(),[E,_]=m.useState(null),[R,T]=m.useState(!1),[D,$]=m.useState(new Set),I=$e(ne=>ne.sidebar.collapsed),O=()=>t||M.xs||M.sm?"100%":M.md?"90%":M.lg?"85%":"1024px",A=()=>{let ne;return t?ne=v.paddingSM:M.xs?ne=v.paddingXS:M.sm?ne=v.paddingSM:ne=v.padding,!t&&I?ne+18:ne};m.useEffect(()=>{_(null),T(!1),$(new Set)},[a]);const{systemPromptMessage:z,renderableMessages:L,convertRenderableEntry:Y}=_R(i,g),F=g.length>0,q=!!(E!=null&&E.content),K=!!z,G=!!a&&(F||q),be=t?190:0,Pe=m.useMemo(()=>{if(!(E!=null&&E.content))return L;const ne={message:{id:E.id,role:"user",content:E.content,createdAt:E.createdAt},messageType:"text"};return[...L,ne]},[L,E]),Ee=m.useMemo(()=>{const ne=[];for(const Ce of Pe){if(!("message"in Ce))continue;const De=Zy(Ce.message).trim();De&&ne.push({id:Ce.message.id,message:Ce.message,text:De})}return ne},[Pe]),Te=m.useMemo(()=>new Set(Ee.map(ne=>ne.id)),[Ee]);m.useEffect(()=>{$(ne=>{let Ce=!1;const De=new Set;for(const He of ne)Te.has(He)?De.add(He):Ce=!0;return Ce?De:ne})},[Te]);const ge=m.useMemo(()=>Ee.filter(ne=>D.has(ne.id)),[Ee,D]),je=Ee.length>0,Be=m.useCallback(ne=>{$(Ce=>{const De=new Set(Ce);return De.has(ne)?De.delete(ne):De.add(ne),De})},[]),Qe=m.useCallback(()=>{if(!je){s.warning("No exportable messages");return}T(!0)},[s,je]),jt=m.useCallback(()=>{T(!1),$(new Set)},[]),Ze=m.useCallback(()=>{if(R){jt();return}Qe()},[Qe,jt,R]),Bt=m.useCallback(()=>{$(new Set(Ee.map(ne=>ne.id)))},[Ee]),B=m.useCallback(()=>{$(new Set)},[]),Me=m.useCallback(async ne=>{var He;if(!a){s.warning("No active chat");return}if(ge.length===0){s.warning("Please select at least one message");return}const Ce=MR(ge),De=await ex.exportMessageText({format:ne,content:Ce,sessionId:a,filenamePrefix:`chat-messages-${ge.length}`});if(De.success){s.success(`Saved: ${De.filename}`);return}(He=De.error)!=null&&He.toLowerCase().includes("cancel")||s.error(De.error||"Export failed")},[s,a,ge]);m.useEffect(()=>{if(typeof window>"u")return;const ne=Ce=>{var Rt;const He=((Rt=Ce.detail)==null?void 0:Rt.sessionId)??null;!a||He!==a||Ze()};return window.addEventListener(Lc,ne),()=>{window.removeEventListener(Lc,ne)}},[a,Ze]);const X=a?u[a]:null,ue=(Re=i==null?void 0:i.config)==null?void 0:Re.tokenUsage,ie=X||ue||null,le=a?h[a]:!1,Ae=(Xe=i==null?void 0:i.config)==null?void 0:Xe.truncationOccurred,Et=le||Ae||!1,Ct=a?f[a]:0,it=(rt=i==null?void 0:i.config)==null?void 0:rt.segmentsRemoved,bt=Ct||it||0,st=m.useMemo(()=>{var Ce;const ne=(Ce=i==null?void 0:i.config)==null?void 0:Ce.compressionEvents;return!ne||ne.length===0?null:ne.reduce((De,He)=>{const Rt=Date.parse(De.createdAt),Os=Date.parse(He.createdAt);return Number.isFinite(Rt)?Number.isFinite(Os)&&Os>Rt?He:De:He})},[(ps=i==null?void 0:i.config)==null?void 0:ps.compressionEvents]),vt=v.marginMD,{handleMessagesScroll:Xt,resetUserScroll:Ls,scrollToBottom:Mt,scrollToTop:ms,showScrollToBottom:hs,showScrollToTop:tn}=uR({currentSessionId:a,interactionState:w,messagesListRef:P,renderableMessages:Pe}),V=()=>M.xs?16:32,Q=!!G&&je&&(!t||R),de=st?r.jsx(ke,{title:n("chat.compression.tooltip",{count:st.messagesCompressed,time:hx(st.createdAt),defaultValue:"Latest compression at {{time}}: {{count}} messages archived"}),children:r.jsx(oe,{color:"gold",icon:r.jsx(tf,{}),style:{marginInlineEnd:0,whiteSpace:"nowrap"},children:n("chat.compression.archivedShort",{count:st.messagesCompressed,defaultValue:"{{count}} archived"})})}):null,ae=ie&&ie.budgetLimit>0?r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:v.marginXS},children:[r.jsx(A1,{usage:ie,showDetails:!0,size:"small"}),Et&&r.jsxs("span",{style:{fontSize:11,color:v.colorTextSecondary,whiteSpace:"nowrap"},children:["(",bt," truncated)"]}),de]}):de?r.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:v.marginXS},children:de}):null;return r.jsx(dr,{role:"region","aria-label":n("chat.view.chatRegion","Chat conversation"),style:{flex:1,minHeight:0,height:"100%",background:v.colorBgContainer,position:"relative",overflow:"hidden"},children:r.jsxs(J,{vertical:!0,style:{flex:1,minHeight:0,height:"100%"},children:[a&&r.jsx(U1,{sessionId:a}),o&&a&&G&&r.jsx("div",{style:{paddingTop:v.paddingXS,paddingRight:A(),paddingBottom:0,paddingLeft:A(),maxWidth:O(),margin:"0 auto",width:"100%"},children:r.jsx(V1,{sessionId:a})}),a&&p&&r.jsx("div",{style:{paddingTop:A(),paddingRight:A(),paddingBottom:0,paddingLeft:A(),maxWidth:O(),margin:"0 auto",width:"100%"},children:r.jsx(g1,{sessionId:a,initialCollapsed:!0})}),a&&x&&r.jsx("div",{style:{paddingTop:v.paddingXS,paddingRight:A(),paddingBottom:0,paddingLeft:A(),maxWidth:O(),margin:"0 auto",width:"100%"},children:r.jsx(z1,{parentSessionId:a})}),Q&&r.jsx("div",{style:{paddingTop:v.paddingXS,paddingRight:A()+be,paddingBottom:0,paddingLeft:A(),maxWidth:O(),margin:"0 auto",width:"100%"},children:R?r.jsxs(J,{align:"center",justify:"space-between",wrap:"wrap",gap:v.marginXS,children:[r.jsx(jR,{type:"secondary",children:n("chat.selectionToolbar.selectedCount",{selected:ge.length,total:Ee.length})}),r.jsxs(H,{size:v.marginXS,wrap:!0,children:[r.jsx(U,{size:"small",onClick:Bt,children:n("chat.selectionToolbar.selectAll")}),r.jsx(U,{size:"small",onClick:B,children:n("chat.selectionToolbar.clear")}),r.jsx(U,{size:"small",icon:r.jsx(gr,{}),onClick:()=>{Me("markdown")},disabled:ge.length===0,children:n("chat.selectionToolbar.exportMarkdown")}),r.jsx(U,{size:"small",type:"primary",icon:r.jsx(gr,{}),onClick:()=>{Me("pdf")},disabled:ge.length===0,children:n("chat.selectionToolbar.exportPdf")}),r.jsx(U,{size:"small",icon:r.jsx(wr,{}),onClick:Ze,children:n("chat.selectionToolbar.done")})]})]}):r.jsx(J,{justify:"flex-end",children:r.jsx(ke,{title:n("chat.selectionToolbar.selectMessages"),children:r.jsx(U,{"aria-label":n("chat.selectionToolbar.selectMessages"),icon:r.jsx(nf,{}),size:"small",onClick:Ze})})})}),r.jsx(p1,{currentChat:i,currentSessionId:a,convertRenderableEntry:Y,handleDeleteMessage:j,handleDeleteToolMessages:C,handleMessagesScroll:Xt,hasSystemPrompt:K,messagesListRef:P,renderableMessages:Pe,rowGap:vt,showMessagesView:!!G,screens:M,workflowDraftId:E==null?void 0:E.id,interactionState:w,padding:A(),selectionMode:R,selectedMessageIds:D,selectableMessageIds:Te,onToggleMessageSelection:Be}),(tn||hs)&&r.jsxs("div",{style:{position:"absolute",right:V(),bottom:M.xs?160:180,display:"flex",flexDirection:"column",gap:v.marginXS,zIndex:1e3},children:[tn&&r.jsx(Zd,{type:"default",icon:r.jsx(ed,{}),style:{position:"relative",inset:"unset"},onClick:()=>{ms()}}),hs&&r.jsx(Zd,{type:"primary",icon:r.jsx(cs,{}),style:{position:"relative",inset:"unset"},onClick:()=>{Ls(),Mt()}})]}),a&&r.jsx("div",{style:{paddingTop:v.paddingXS,paddingRight:A(),paddingBottom:0,paddingLeft:A(),maxWidth:O(),margin:"0 auto",width:"100%"},children:r.jsx(E1,{sessionId:a})}),r.jsx(Xj,{sessionId:a,isCenteredLayout:!G,maxWidth:G?O():"100%",onWorkflowDraftChange:_,showMessagesView:!!G,sessionDiffSummary:S,contextUsageIndicator:ae})]})})},ER=5,RR=5,AR=5,IR=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""}},$R=e=>e.isRunning?"is-running":e.lastRunStatus==="error"?"is-error":e.pinned?"is-pinned":"is-idle",Ol=({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 ${$R(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:IR(e.updatedAt)}),n?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"lotus-home-session-meta-sep"}),r.jsxs("span",{children:[r.jsx(si,{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(ni,{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(Ks,{className:"lotus-home-session-arrow"})]})},DR=({onOpenSession:e})=>{const{t}=se(),{token:s}=pe.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,RR),[n,o]),i=m.useMemo(()=>n.filter(d=>d.pinned&&!d.isRunning).slice(0,AR),[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,f)=>{const g=h.updatedAt?new Date(h.updatedAt).getTime():h.createdAt;return(f.updatedAt?new Date(f.updatedAt).getTime():f.createdAt)-g}).slice(0,ER)},[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(vb,{})}),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",children:r.jsx(wy,{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(ef,{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(Ol,{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(Kc,{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(Ol,{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(Zs,{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(Ol,{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]})]})})},cn=(e,t,s)=>Math.max(t,Math.min(s,e)),Fa=(e,t)=>t==="horizontal"?e.clientWidth:e.clientHeight,La=(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}},px=({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 f=m.useRef(null),g=m.useRef(null),[y,p]=m.useState(null),[x,b]=m.useState(0),[S,w]=m.useState(null),k=m.useMemo(()=>{if(!n)return null;const L=Number(n[0]);return Number.isFinite(L)?L:null},[n]),j=m.useMemo(()=>{if(!n)return null;const L=Number(n[0]),Y=Number(n[1]);if(!Number.isFinite(L)||!Number.isFinite(Y))return null;const F=L+Y;return F<=0||Y<=0?null:cn(L/F,0,1)},[n]);m.useLayoutEffect(()=>{const L=f.current;L&&b(Fa(L,e))},[e]),m.useEffect(()=>{const L=f.current;if(!L)return;const Y=()=>{const F=Fa(L,e);b(q=>q===F?q:F)};if(Y(),typeof ResizeObserver<"u"){const F=new ResizeObserver(Y);return F.observe(L),()=>F.disconnect()}return window.addEventListener("resize",Y),()=>window.removeEventListener("resize",Y)},[e]),m.useEffect(()=>{if(j!==null){w(j);return}w(L=>L??cn(o,.1,.9))},[o,j]);const C=m.useMemo(()=>La(x,a,i),[x,a,i]),P=cn(o,.1,.9),v=S??P,M=x>0?Math.round(x*v):null,E=y??(j!==null?M:null)??k??M??0,_=x>0?cn(E,C.minFirst,C.maxFirst):Math.max(0,Math.round(E)),R=m.useCallback(L=>{if(c)return;const Y=f.current;if(!Y)return;L.preventDefault(),L.stopPropagation();const F=e==="horizontal"?L.clientX:L.clientY,q=Fa(Y,e),K=La(q,a,i),G=cn(_||Math.round(q*P),K.minFirst,K.maxFirst);g.current={pointerId:L.pointerId,startPos:F,startFirstPx:G,containerSize:q};try{L.currentTarget.setPointerCapture(L.pointerId)}catch{}},[c,_,P,e,a,i]),T=m.useCallback(L=>{const Y=g.current;if(!Y||L.pointerId!==Y.pointerId)return;L.preventDefault(),L.stopPropagation();const q=(e==="horizontal"?L.clientX:L.clientY)-Y.startPos,K=Y.containerSize,G=La(K,a,i),be=cn(Math.round(Y.startFirstPx+q),G.minFirst,G.maxFirst);p(be)},[e,a,i]),D=m.useCallback(L=>{const Y=g.current;if(!Y||Y.pointerId!==L)return;const F=f.current,q=F?Fa(F,e):Y.containerSize,K=y??Y.startFirstPx,G=La(q,a,i),be=cn(K,G.minFirst,G.maxFirst),Pe=Math.max(0,q-be);p(null),q>0&&w(cn(be/q,0,1)),g.current=null,d==null||d([be,Pe])},[e,y,a,i,d]),$=m.useCallback(L=>{L.preventDefault(),L.stopPropagation(),D(L.pointerId)},[D]),I=m.useCallback(L=>{L.preventDefault(),L.stopPropagation(),D(L.pointerId)},[D]),O=e==="horizontal",A=c?"default":O?"col-resize":"row-resize",z=Math.max(0,Math.round(l));return r.jsxs("div",{ref:f,className:h,style:{display:"flex",flexDirection:O?"row":"column",height:"100%",minHeight:0,minWidth:0,width:"100%",position:"relative",...u},children:[r.jsx("div",{style:{flex:`0 0 ${_}px`,minWidth:O?C.appliedMinFirst:0,minHeight:O?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:O?C.appliedMinSecond:0,minHeight:O?0:C.appliedMinSecond,overflow:"hidden",display:"flex"},children:r.jsx("div",{style:{flex:1,minHeight:0,minWidth:0},children:s})}),z>0?r.jsx("div",{role:"separator","aria-orientation":O?"vertical":"horizontal",onPointerDown:R,onPointerMove:T,onPointerUp:$,onPointerCancel:I,style:{position:"absolute",top:O?0:`${_-z/2}px`,left:O?`${_-z/2}px`:0,width:O?`${z}px`:"100%",height:O?"100%":`${z}px`,cursor:A,touchAction:"none",background:"transparent",zIndex:5}}):null]})},{useToken:FR}=pe,LR=4,OR=({leafId:e})=>{const{token:t}=FR(),{t:s}=se(),n=$e(v=>v.tree),o=$e(v=>v.leafSessionIds),a=$e(v=>v.activeLeafId),i=$e(v=>v.setActiveLeafId),l=$e(v=>v.splitLeaf),c=$e(v=>v.closeLeaf),d=$e(v=>v.setLeafSessionId),u=N(v=>v.selectSession),h=N(v=>v.addChat),f=N(v=>v.systemPrompts),g=N(v=>v.lastSelectedPromptId),y=o[e]??null,p=m.useMemo(()=>Ht(n).length,[n]),x=p<LR,b=p>1,w=b||!!y,k=p>1,j=a===e,C=m.useCallback(v=>{d(e,v),i(e),u(v)},[e,u,i,d]),P=m.useCallback(async()=>{var _,R;const v=f.find(T=>T.id===g),M=(v==null?void 0:v.id)||(f.length>0?((_=f.find(T=>T.id==="general_assistant"))==null?void 0:_.id)||f[0].id:""),E=await h({title:s("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:M,baseSystemPrompt:(v==null?void 0:v.content)||(f.length>0?((R=f.find(T=>T.id==="general_assistant"))==null?void 0:R.content)||f[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null});d(e,E),i(e)},[h,g,f,s,e,d,i]);return r.jsxs("div",{className:"chat-pane-shell",onMouseDownCapture:()=>{ns("pane focus (mouse)",{leafId:e,sessionId:y,prevActiveLeafId:a}),i(e),y&&u(y)},onFocusCapture:()=>{ns("pane focus (focus)",{leafId:e,sessionId:y,prevActiveLeafId:a}),i(e)},style:{height:"100%",minHeight:0,border:k?`1px solid ${j?t.colorPrimaryBorder:t.colorBorderSecondary}`:"none",borderRadius:k?t.borderRadiusLG:0,overflow:"hidden",background:t.colorBgContainer,position:"relative"},children:[r.jsx("div",{className:"chat-pane-actions",style:{background:t.colorBgElevated,border:`1px solid ${t.colorBorderSecondary}`,borderRadius:10,padding:"2px 4px"},children:r.jsxs(J,{gap:t.marginXS,children:[r.jsx(U,{size:"small",type:"text",icon:r.jsx(Sb,{}),disabled:!x,title:s("chat.multiPane.splitHorizontal"),"aria-label":s("chat.multiPane.splitHorizontal"),onClick:v=>{v.preventDefault(),v.stopPropagation(),ns("pane split request",{leafId:e,layout:"horizontal"}),l(e,"horizontal");const M=$e.getState(),E=M.leafSessionIds[M.activeLeafId]??null;E&&u(E)}}),r.jsx(U,{size:"small",type:"text",icon:r.jsx(wb,{}),disabled:!x,title:s("chat.multiPane.splitVertical"),"aria-label":s("chat.multiPane.splitVertical"),onClick:v=>{v.preventDefault(),v.stopPropagation(),ns("pane split request",{leafId:e,layout:"vertical"}),l(e,"vertical");const M=$e.getState(),E=M.leafSessionIds[M.activeLeafId]??null;E&&u(E)}}),r.jsx(U,{size:"small",type:"text",icon:r.jsx(nf,{}),disabled:!y,title:s("chat.multiPane.selectMessagesToExport"),"aria-label":s("chat.multiPane.selectMessagesToExport"),onClick:v=>{v.preventDefault(),v.stopPropagation(),y&&window.dispatchEvent(new CustomEvent(Lc,{detail:{sessionId:y}}))}}),r.jsx(U,{size:"small",type:"text",danger:!0,icon:r.jsx(wr,{}),disabled:!w,title:s("chat.multiPane.closePane"),"aria-label":s("chat.multiPane.closePane"),onClick:v=>{v.preventDefault(),v.stopPropagation(),ns("pane close request",{leafId:e}),b?c(e):d(e,null);const M=$e.getState(),E=M.leafSessionIds[M.activeLeafId]??null;u(E)}})]})}),y?r.jsx(vi,{name:"ChatView",children:r.jsx(PR,{sessionId:y,embedded:!0})}):r.jsx(vi,{name:"HomeDashboard",children:r.jsx(DR,{onOpenSession:C,onCreateSession:P})})]})},zR=({node:e})=>{const t=$e(n=>n.splitSizesPx[e.id]??null),s=$e(n=>n.setSplitSizesPx);return r.jsx(px,{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(qc,{node:e.children[0]}),second:r.jsx(qc,{node:e.children[1]})})},qc=({node:e})=>e.type==="leaf"?r.jsx(OR,{leafId:e.id}):r.jsx(zR,{node:e}),NR=()=>{const e=$e(h=>h.tree),t=$e(h=>h.leafSessionIds),s=$e(h=>h.activeLeafId),n=$e(h=>h.setActiveLeafId),o=$e(h=>h.setLeafSessionId),a=$e(h=>h.clearSessionFromAllLeaves),i=N(h=>h.chats),l=N(h=>h.currentSessionId),c=m.useRef(!1),d=m.useMemo(()=>Ht(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,f]of Object.entries(t))f&&!u.has(f)&&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 f of h)u.has(f)||a(f)},[u,a,t]),r.jsx("div",{style:{height:"100%",minHeight:0,padding:0},children:r.jsx(qc,{node:e})})},BR=[{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"]}],WR=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)},UR=(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(" • ")},qR=(e,t)=>{const s=t.trim().toLowerCase();return s?e.filter(n=>[n.title,n.subtitle||"",...n.keywords].join(" ").toLowerCase().includes(s)):e},HR=e=>{if(!(e instanceof HTMLElement))return!1;const t=e.tagName.toLowerCase();return e.isContentEditable?!0:t==="input"||t==="textarea"||t==="select"},YR=()=>{const{t:e}=se(),{token:t}=pe.useToken(),s=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{message:n}=us.useApp(),o=N(R=>R.chats),a=N(R=>R.addChat),i=N(R=>R.lastSelectedPromptId),l=N(R=>R.systemPrompts),[c,d]=m.useState(!1),[u,h]=m.useState(""),[f,g]=m.useState(0),y=m.useRef(null),p=m.useRef(null),x=pn(R=>R.open),b=Hn(R=>R.toggleTheme),S=Hn(R=>R.themeMode),w=$e(R=>R.sidebar.collapsed),k=$e(R=>R.setSidebarCollapsed),j=bi(R=>R.mode),C=bi(R=>R.toggleMode),P=m.useCallback(async()=>{var A,z;const R=l.find(L=>L.id===i),T=(R==null?void 0:R.id)||(l.length>0?((A=l.find(L=>L.id==="general_assistant"))==null?void 0:A.id)||l[0].id:""),D=await a({title:e("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:T,baseSystemPrompt:(R==null?void 0:R.content)||(l.length>0?((z=l.find(L=>L.id==="general_assistant"))==null?void 0:z.content)||l[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null}),{activeLeafId:$,setLeafSessionId:I,setActiveLeafId:O}=$e.getState();I($,D),O($)},[a,i,l,e]),v=m.useMemo(()=>{const R=BR.filter(T=>!(j==="simple"&&gy.has(T.tabKey))).map(T=>({id:T.id,kind:"action",title:e(T.titleKey,T.fallbackTitle),subtitle:e(T.subtitleKey||"commandPalette.groups.settings",T.fallbackSubtitle||"System settings"),keywords:[T.tabKey,T.badge||"","settings","config",...T.keywords||[]],icon:r.jsx(ji,{}),badge:T.badge,onSelect:()=>{x("chat",T.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(Gs,{}),badge:e("commandPalette.badges.quickAction","Action"),onSelect:async()=>{await P()}},{id:"toggle-theme",kind:"action",title:S==="dark"?e("commandPalette.actions.switchToLight","Switch to Light Mode"):e("commandPalette.actions.switchToDark","Switch to Dark Mode"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["theme","dark","light","mode","appearance","toggle","color"],icon:r.jsx(_b,{}),badge:S==="dark"?"☀️":"🌙",onSelect:()=>{b()}},{id:"toggle-sidebar",kind:"action",title:w?e("commandPalette.actions.showSidebar","Show Sidebar"):e("commandPalette.actions.hideSidebar","Hide Sidebar"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["sidebar","toggle","hide","show","panel","menu"],icon:w?r.jsx(rf,{}):r.jsx(Yp,{}),badge:"Layout",onSelect:()=>{k(!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(Tb,{}),badge:"Layout",onSelect:()=>{const{tree:T,activeLeafId:D,splitLeaf:$}=$e.getState();Ht(T).length<4&&$(D,"vertical")}},...R,{id:"toggle-experience-mode",kind:"action",title:j==="simple"?e("commandPalette.actions.switchToAdvanced","Switch to Advanced Mode"):e("commandPalette.actions.switchToSimple","Switch to Simple Mode"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["mode","simple","advanced","beginner","expert","experience","complexity"],icon:r.jsx(Kp,{}),badge:j==="simple"?"Simple":"Advanced",onSelect:()=>{C()}}]},[P,x,b,S,w,k,j,C,e]),M=m.useMemo(()=>o.map(R=>({id:`session-${R.id}`,kind:"session",title:R.title,subtitle:UR(R,e("commandPalette.badges.childSession","Child session"),e("commandPalette.badges.rootSession","Session")),keywords:WR(R),icon:r.jsx(ni,{}),badge:R.pinned?e("commandPalette.badges.pinned","Pinned"):R.isRunning?e("commandPalette.badges.running","Running"):R.kind==="child"?e("commandPalette.badges.child","Child"):void 0,onSelect:()=>{Ni(R.id)}})),[o,e]),E=m.useMemo(()=>[...v,...M],[v,M]),_=m.useMemo(()=>qR(E,u).slice(0,40),[E,u]);return m.useEffect(()=>{g(R=>_.length===0?0:Math.min(R,_.length-1))},[_.length]),m.useEffect(()=>{if(!c)return;const R=window.setTimeout(()=>{var T,D;(T=y.current)==null||T.focus(),(D=y.current)==null||D.select()},0);return()=>window.clearTimeout(R)},[c]),m.useEffect(()=>{if(typeof window>"u")return;const R=T=>{if((T.metaKey||T.ctrlKey)&&T.key.toLowerCase()==="k"){T.preventDefault(),d($=>!$);return}if(c){if(T.key==="Escape"){T.preventDefault(),d(!1);return}if(!(HR(T.target)&&T.key!=="ArrowUp"&&T.key!=="ArrowDown"&&T.key!=="Enter")){if(T.key==="ArrowDown"){T.preventDefault(),g($=>_.length===0?0:($+1)%_.length);return}if(T.key==="ArrowUp"){T.preventDefault(),g($=>_.length===0?0:$===0?_.length-1:$-1);return}if(T.key==="Enter"){const $=_[f];if(!$)return;T.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",R),()=>window.removeEventListener("keydown",R)},[_,n,c,f,e]),m.useEffect(()=>{c||(h(""),g(0))},[c]),m.useEffect(()=>{const R=p.current;if(!R)return;const T=R.querySelector(`[data-command-index="${f}"]`);T==null||T.scrollIntoView({block:"nearest"})},[f]),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(Qo,{style:{color:t.colorTextTertiary,fontSize:16}}),r.jsx(he,{ref:y,value:u,onChange:R=>h(R.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(ce.Text,{type:"secondary",style:{fontSize:12},children:"⌘K"})})]}),r.jsxs("div",{className:"lotus-command-palette-hint",children:[r.jsx(Zs,{}),r.jsx("span",{children:e("commandPalette.navigationHint","Use ↑↓ to navigate, Enter to open, and Esc to close.")})]}),r.jsx("div",{ref:p,className:"lotus-command-palette-list",role:"listbox",children:_.length===0?r.jsxs("div",{className:"lotus-command-palette-empty",children:[r.jsx(kb,{}),r.jsx("span",{children:e("commandPalette.empty","No matching commands")})]}):_.map((R,T)=>{const D=T===f;return r.jsxs("button",{type:"button",className:`lotus-command-palette-item ${D?"is-selected":""}`,"data-command-index":T,onMouseEnter:()=>g(T),onClick:()=>{(async()=>{try{await R.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:R.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:R.title}),R.badge?r.jsx(oe,{bordered:!1,children:R.badge}):null]}),R.subtitle?r.jsx("span",{className:"lotus-command-palette-item-subtitle",children:R.subtitle}):null]})]},R.id)})})]})})},XR=({themeMode:e,onThemeModeChange:t,locale:s,onLocaleChange:n})=>{const o=pn(M=>M.isOpen),a=pn(M=>M.close),{t:i}=se(),{token:l}=pe.useToken(),c=Bi(),d=m.useMemo(()=>ey()==="macos",[]),u=Yt(M=>M.loadProviderConfig);m.useEffect(()=>{u()},[u]),tk(),UT(),m.useEffect(()=>{Nm.clear(),Bm()},[e]),m.useEffect(()=>{Nm.clear(),Bm()},[c]);const h=$e(M=>M.sidebar.collapsed),f=$e(M=>M.sidebar.widthPx),g=$e(M=>M.sidebar.minWidthPx),y=$e(M=>M.sidebar.maxWidthPx),p=$e(M=>M.setSidebarCollapsed),x=$e(M=>M.setSidebarWidthPx),b=18,S=0,k=!o&&h&&d?44:S,j=0,C=88,P=10,v="none";return r.jsxs(r.Fragment,{children:[r.jsx("a",{href:"#lotus-main-content",className:"lotus-skip-link",style:{position:"absolute",top:-9999,left:-9999,zIndex:1e4,padding:"8px 16px",background:"var(--lotus-main-surface, #fff)",color:"var(--ant-color-primary, #0d9488)",borderRadius:8,fontWeight:600,textDecoration:"none"},onFocus:M=>{M.currentTarget.style.top="8px",M.currentTarget.style.left="8px"},onBlur:M=>{M.currentTarget.style.top="-9999px",M.currentTarget.style.left="-9999px"},children:i("app.skipToContent","Skip to main content")}),r.jsx(YR,{}),r.jsx(dr,{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:k,paddingLeft:S,paddingRight:S,paddingBottom:S,background:"transparent"},children:[o?r.jsx(dr,{className:"lotus-shell-panel lotus-settings-panel lotus-page-enter",style:{flex:1,display:"flex",flexDirection:"column",background:"var(--lotus-main-surface)",minHeight:0,borderRadius:`${b}px 0 0 ${b}px`,border:v,overflow:"hidden"},children:r.jsx(vi,{name:"SystemSettings",children:r.jsx(OT,{themeMode:e,onThemeModeChange:t,locale:s,onLocaleChange:n,onBack:a})})}):r.jsxs(r.Fragment,{children:[r.jsx(WT,{}),r.jsx(px,{layout:"horizontal",style:{flex:1,minHeight:0,height:"100%",background:"transparent"},sizesPx:[h?j:f,0],minFirstPx:h?j:g,minSecondPx:320,disabled:h,handleSizePx:h?0:2,onResizeEnd:([M])=>{if(h)return;const E=Math.max(g,Math.min(y,M));x(E)},first:r.jsx("div",{className:"lotus-shell-panel lotus-shell-sidebar",style:{height:"100%",minHeight:0,borderRadius:`${b}px 0 0 ${b}px`,border:v,overflow:"hidden",background:"var(--lotus-sidebar-bg)"},children:r.jsx(Pw,{})}),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:v,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:r.jsx(dr,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:r.jsx(NR,{})})})})]}),!o&&h?r.jsx(U,{"data-testid":"show-sidebar",type:"text",size:"small",icon:r.jsx(rf,{}),onClick:()=>p(!1),title:i("layout.showSidebar"),"aria-label":i("layout.showSidebar"),className:"lotus-toolbar-icon lotus-floating-sidebar-toggle",style:{position:"absolute",top:P,left:C,zIndex:40,width:36,height:36,borderRadius:12,border:`1px solid ${l.colorBorderSecondary}`,background:l.colorBgElevated,boxShadow:l.boxShadowSecondary}}):null]})})]})},Wh={httpProxy:"",httpsProxy:"",proxyUsername:"",proxyPassword:"",rememberProxyAuth:!0},zl=e=>typeof e=="string"?e:"",VR=()=>{const{t:e}=se(),[t,s]=m.useState(0),[n,o]=m.useState(Wh),[a,i]=m.useState(!1),[l,c]=m.useState(!1),[d,u]=m.useState(null),[h,f]=m.useState(!1),[g,y]=m.useState(null),[p,x]=m.useState(!1);m.useEffect(()=>{(async()=>{let v=!1;try{const M=Nt.getInstance(),E=await M.getBambooConfig(),_=zl(E.http_proxy),R=zl(E.https_proxy),T=await M.getProxyAuthStatus(),D=zl(T.username);o({httpProxy:_,httpsProxy:R,proxyUsername:D,proxyPassword:"",rememberProxyAuth:Wh.rememberProxyAuth}),v=_.trim().length>0||R.trim().length>0,i(v)}catch(M){console.error("Failed to check config:",M),i(!1)}c(!0);try{const E=await Nt.getInstance().getSetupStatus();u({needsProxy:E.has_proxy_env,message:E.message}),i(v||E.has_proxy_env)}catch(M){console.error("Failed to check setup status:",M),u({needsProxy:!0,message:e("setup.error.loadStatusFailed")})}finally{c(!1)}})()},[]);const S=n.httpProxy.trim().length>0||n.httpsProxy.trim().length>0||a,w=P=>{o(v=>({...v,...P}))},k=async()=>{var R,T;const P=n.httpProxy.trim(),v=n.httpsProxy.trim(),M=!!(P||v),E=n.proxyUsername.trim(),_=!!E;try{if(y(null),x(!0),M){const $=Nt.getInstance(),I=await $.validateBambooConfigPatch({http_proxy:P,https_proxy:v});if(!I.valid){const A=((T=(R=I.errors)==null?void 0:R.proxy)==null?void 0:T[0])??Object.values(I.errors||{}).flat().filter(Boolean)[0];y((A==null?void 0:A.message)||e("setup.error.invalidProxy"));return}if(n.rememberProxyAuth&&!_&&n.proxyPassword.trim()){y(e("setup.error.credentialsUsername"));return}await $.setBambooConfig({http_proxy:P,https_proxy:v}),n.rememberProxyAuth&&_?await $.setProxyAuth({username:E,password:n.proxyPassword||""}):await $.clearProxyAuth()}await Nt.getInstance().markSetupComplete(),f(!0)}catch(D){console.error("Failed to complete setup:",D);const $=D instanceof Error&&D.message.trim()?D.message:e(M?"setup.error.saveProxyFailed":"setup.error.completeFailed");y($)}finally{x(!1)}},j=async()=>{try{y(null),x(!0),await Nt.getInstance().markSetupComplete(),f(!0)}catch(P){console.error("Failed to mark setup complete:",P),y(e("setup.error.completeFailed"))}finally{x(!1)}},C=m.useMemo(()=>[{title:e("setup.steps.welcome"),content:r.jsxs("div",{children:[r.jsx("h1",{children:e("setup.welcome.heading")}),r.jsx("p",{children:e("setup.welcome.description")}),r.jsx(Ne,{message:e("setup.welcome.skipInfo"),type:"info",showIcon:!0,style:{marginBottom:16}}),r.jsxs("div",{className:"setup-page__actions",children:[r.jsx(U,{"data-testid":"setup-next",type:"primary",onClick:()=>s(1),children:e("setup.button.next")}),r.jsx(U,{"data-testid":"setup-skip",onClick:()=>void j(),loading:p,children:e("setup.button.skipForNow")})]})]})},{title:e("setup.steps.proxy"),content:r.jsxs("div",{children:[r.jsx("h2",{children:e("setup.proxy.title")}),r.jsx(Ne,{message:e("setup.proxy.info"),type:"info",showIcon:!0}),r.jsx(Ne,{message:e("setup.proxy.providerInfo"),type:"info",showIcon:!0,style:{marginTop:16}}),l?r.jsx("div",{style:{marginTop:16},children:r.jsx(ht,{tip:e("setup.proxy.detecting")})}):null,d?r.jsx(Ne,{message:d.message,type:d.needsProxy?"warning":"success",showIcon:!0,style:{marginTop:16}}):null,!l&&!d&&!a?r.jsx(Ne,{message:e("setup.proxy.noProxyDetected"),type:"success",showIcon:!0,style:{marginTop:16}}):null,g?r.jsx(Ne,{message:g,type:"error",showIcon:!0,style:{marginTop:16}}):null,r.jsxs("div",{style:{marginTop:16},children:[r.jsx("label",{htmlFor:"setup-http-proxy",children:e("setup.proxy.httpProxyLabel")}),r.jsx(he,{id:"setup-http-proxy",value:n.httpProxy,onChange:P=>w({httpProxy:P.target.value}),placeholder:e("setup.proxy.httpProxyPlaceholder")})]}),r.jsxs("div",{style:{marginTop:16},children:[r.jsx("label",{htmlFor:"setup-https-proxy",children:e("setup.proxy.httpsProxyLabel")}),r.jsx(he,{id:"setup-https-proxy",value:n.httpsProxy,onChange:P=>w({httpsProxy:P.target.value}),placeholder:e("setup.proxy.httpsProxyPlaceholder")})]}),S?r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:{marginTop:16},children:[r.jsx("label",{htmlFor:"setup-proxy-username",children:e("setup.proxy.usernameLabel")}),r.jsx(he,{id:"setup-proxy-username",value:n.proxyUsername,onChange:P=>w({proxyUsername:P.target.value})})]}),r.jsxs("div",{style:{marginTop:16},children:[r.jsx("label",{htmlFor:"setup-proxy-password",children:e("setup.proxy.passwordLabel")}),r.jsx(he.Password,{id:"setup-proxy-password",value:n.proxyPassword,onChange:P=>w({proxyPassword:P.target.value})})]}),r.jsx("div",{style:{marginTop:16},children:r.jsx(sf,{checked:n.rememberProxyAuth,onChange:P=>w({rememberProxyAuth:P.target.checked}),children:e("setup.proxy.rememberCredentials")})})]}):null,r.jsxs("div",{className:"setup-page__actions",style:{marginTop:24},children:[r.jsx(U,{"data-testid":"setup-back",onClick:()=>s(0),children:e("setup.button.back")}),r.jsx(U,{"data-testid":"setup-skip",onClick:()=>void j(),loading:p,children:e("setup.button.skipForNow")}),r.jsx(U,{"data-testid":"setup-complete",onClick:()=>void k(),type:"primary",loading:p,children:e("setup.button.completeSetup")})]})]})}],[n,d,g,l,p,a,S,e]);return h?r.jsxs("div",{"data-testid":"setup-complete",className:"setup-complete",children:[r.jsx("h1",{children:e("setup.complete.title")}),r.jsx("p",{children:e("setup.complete.restartMessage")}),r.jsx(U,{"data-testid":"setup-restart",onClick:()=>window.location.reload(),children:e("setup.button.restart")})]}):r.jsx("div",{className:"setup-page",children:r.jsxs(ee,{style:{maxWidth:600,margin:"40px auto"},children:[r.jsx(Zp,{current:t,items:C.map(P=>({title:P.title}))}),r.jsx("div",{style:{marginTop:24},children:C[t].content})]})})};var Kr={},Nl={exports:{}},Uh;function tt(){return Uh||(Uh=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}(Nl)),Nl.exports}var Gr={},qh;function KR(){if(qh)return Gr;qh=1,Object.defineProperty(Gr,"__esModule",{value:!0}),Gr.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 Gr.default=e,Gr}var Jr={},Qr={},Zr={},Bl={exports:{}},Wl={exports:{}},Ul={exports:{}},ql={exports:{}},Hh;function GR(){return Hh||(Hh=1,function(e){var t=qp().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}(ql)),ql.exports}var Yh;function JR(){return Yh||(Yh=1,function(e){var t=qp().default,s=GR();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}(Ul)),Ul.exports}var Xh;function QR(){return Xh||(Xh=1,function(e){var t=JR();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}(Wl)),Wl.exports}var Vh;function Cr(){return Vh||(Vh=1,function(e){var t=QR();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}(Bl)),Bl.exports}var eo={},Kh;function Mr(){return Kh||(Kh=1,Object.defineProperty(eo,"__esModule",{value:!0}),eo.commonLocale=void 0,eo.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0}),eo}var Gh;function ZR(){if(Gh)return Zr;Gh=1;var e=tt().default;Object.defineProperty(Zr,"__esModule",{value:!0}),Zr.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 Zr.default=n,Zr}var to={},Jh;function fx(){if(Jh)return to;Jh=1,Object.defineProperty(to,"__esModule",{value:!0}),to.default=void 0;const e={placeholder:"Select time",rangePlaceholder:["Start time","End time"]};return to.default=e,to}var Qh;function gx(){if(Qh)return Qr;Qh=1;var e=tt().default;Object.defineProperty(Qr,"__esModule",{value:!0}),Qr.default=void 0;var t=e(ZR()),s=e(fx());const n={lang:Object.assign({placeholder:"Select date",yearPlaceholder:"Select year",quarterPlaceholder:"Select quarter",monthPlaceholder:"Select month",weekPlaceholder:"Select week",rangePlaceholder:["Start date","End date"],rangeYearPlaceholder:["Start year","End year"],rangeQuarterPlaceholder:["Start quarter","End quarter"],rangeMonthPlaceholder:["Start month","End month"],rangeWeekPlaceholder:["Start week","End week"]},t.default),timePickerLocale:Object.assign({},s.default)};return Qr.default=n,Qr}var Zh;function eA(){if(Zh)return Jr;Zh=1;var e=tt().default;Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.default=void 0;var t=e(gx());return Jr.default=t.default,Jr}var ep;function tA(){if(ep)return Kr;ep=1;var e=tt().default;Object.defineProperty(Kr,"__esModule",{value:!0}),Kr.default=void 0;var t=e(KR()),s=e(eA()),n=e(gx()),o=e(fx());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 Kr.default=i,Kr}var Hl,tp;function sA(){return tp||(tp=1,Hl=tA()),Hl}var nA=sA();const rA=br(nA);var so={},no={},sp;function oA(){if(sp)return no;sp=1,Object.defineProperty(no,"__esModule",{value:!0}),no.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 no.default=e,no}var ro={},oo={},ao={},np;function aA(){if(np)return ao;np=1;var e=tt().default;Object.defineProperty(ao,"__esModule",{value:!0}),ao.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 ao.default=n,ao}var io={},rp;function yx(){if(rp)return io;rp=1,Object.defineProperty(io,"__esModule",{value:!0}),io.default=void 0;const e={placeholder:"Sélectionner l'heure",rangePlaceholder:["Heure de début","Heure de fin"]};return io.default=e,io}var op;function xx(){if(op)return oo;op=1;var e=tt().default;Object.defineProperty(oo,"__esModule",{value:!0}),oo.default=void 0;var t=e(aA()),s=e(yx());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 oo.default=n,oo}var ap;function iA(){if(ap)return ro;ap=1;var e=tt().default;Object.defineProperty(ro,"__esModule",{value:!0}),ro.default=void 0;var t=e(xx());return ro.default=t.default,ro}var ip;function lA(){if(ip)return so;ip=1;var e=tt().default;Object.defineProperty(so,"__esModule",{value:!0}),so.default=void 0;var t=e(oA()),s=e(iA()),n=e(xx()),o=e(yx());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 so.default=i,so}var Yl,lp;function cA(){return lp||(lp=1,Yl=lA()),Yl}var dA=cA();const uA=br(dA);var lo={},co={},cp;function mA(){if(cp)return co;cp=1,Object.defineProperty(co,"__esModule",{value:!0}),co.default=void 0;var e={items_per_page:"/ पृष्ठ",jump_to:"इस पर चलें",jump_to_confirm:"पुष्टि करें",page:"",prev_page:"पिछला पृष्ठ",next_page:"अगला पृष्ठ",prev_5:"पिछले 5 पृष्ठ",next_5:"अगले 5 पृष्ठ",prev_3:"पिछले 3 पृष्ठ",next_3:"अगले 3 पेज",page_size:"Page Size"};return co.default=e,co}var uo={},mo={},ho={},dp;function hA(){if(dp)return ho;dp=1;var e=tt().default;Object.defineProperty(ho,"__esModule",{value:!0}),ho.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 ho.default=n,ho}var po={},up;function bx(){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 mp;function vx(){if(mp)return mo;mp=1;var e=tt().default;Object.defineProperty(mo,"__esModule",{value:!0}),mo.default=void 0;var t=e(hA()),s=e(bx());const n={lang:Object.assign({placeholder:"तारीख़ चुनें",yearPlaceholder:"वर्ष चुनें",quarterPlaceholder:"तिमाही चुनें",monthPlaceholder:"महीना चुनिए",weekPlaceholder:"सप्ताह चुनें",rangePlaceholder:["प्रारंभ तिथि","समाप्ति तिथि"],rangeYearPlaceholder:["आरंभिक वर्ष","अंत वर्ष"],rangeMonthPlaceholder:["आरंभिक महीना","अंत महीना"],rangeWeekPlaceholder:["आरंभिक सप्ताह","अंत सप्ताह"]},t.default),timePickerLocale:Object.assign({},s.default)};return mo.default=n,mo}var hp;function pA(){if(hp)return uo;hp=1;var e=tt().default;Object.defineProperty(uo,"__esModule",{value:!0}),uo.default=void 0;var t=e(vx());return uo.default=t.default,uo}var pp;function fA(){if(pp)return lo;pp=1;var e=tt().default;Object.defineProperty(lo,"__esModule",{value:!0}),lo.default=void 0;var t=e(mA()),s=e(pA()),n=e(vx()),o=e(bx());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 lo.default=i,lo}var Xl,fp;function gA(){return fp||(fp=1,Xl=fA()),Xl}var yA=gA();const xA=br(yA);var fo={},go={},gp;function bA(){if(gp)return go;gp=1,Object.defineProperty(go,"__esModule",{value:!0}),go.default=void 0;var e={items_per_page:"件 / ページ",jump_to:"移動",jump_to_confirm:"確認する",page:"ページ",prev_page:"前のページ",next_page:"次のページ",prev_5:"前 5ページ",next_5:"次 5ページ",prev_3:"前 3ページ",next_3:"次 3ページ",page_size:"ページサイズ"};return go.default=e,go}var yo={},xo={},bo={},yp;function vA(){if(yp)return bo;yp=1;var e=tt().default;Object.defineProperty(bo,"__esModule",{value:!0}),bo.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 bo.default=n,bo}var vo={},xp;function Sx(){if(xp)return vo;xp=1,Object.defineProperty(vo,"__esModule",{value:!0}),vo.default=void 0;const e={placeholder:"時間を選択",rangePlaceholder:["開始時間","終了時間"]};return vo.default=e,vo}var bp;function wx(){if(bp)return xo;bp=1;var e=tt().default;Object.defineProperty(xo,"__esModule",{value:!0}),xo.default=void 0;var t=e(vA()),s=e(Sx());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 xo.default=n,xo}var vp;function SA(){if(vp)return yo;vp=1;var e=tt().default;Object.defineProperty(yo,"__esModule",{value:!0}),yo.default=void 0;var t=e(wx());return yo.default=t.default,yo}var Sp;function wA(){if(Sp)return fo;Sp=1;var e=tt().default;Object.defineProperty(fo,"__esModule",{value:!0}),fo.default=void 0;var t=e(bA()),s=e(SA()),n=e(wx()),o=e(Sx());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 fo.default=i,fo}var Vl,wp;function _A(){return wp||(wp=1,Vl=wA()),Vl}var TA=_A();const kA=br(TA);var So={},wo={},_p;function jA(){if(_p)return wo;_p=1,Object.defineProperty(wo,"__esModule",{value:!0}),wo.default=void 0;var e={items_per_page:"条/页",jump_to:"跳至",jump_to_confirm:"确定",page:"页",prev_page:"上一页",next_page:"下一页",prev_5:"向前 5 页",next_5:"向后 5 页",prev_3:"向前 3 页",next_3:"向后 3 页",page_size:"页码"};return wo.default=e,wo}var _o={},To={},ko={},Tp;function CA(){if(Tp)return ko;Tp=1;var e=tt().default;Object.defineProperty(ko,"__esModule",{value:!0}),ko.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 ko.default=n,ko}var jo={},kp;function _x(){if(kp)return jo;kp=1,Object.defineProperty(jo,"__esModule",{value:!0}),jo.default=void 0;const e={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return jo.default=e,jo}var jp;function Tx(){if(jp)return To;jp=1;var e=tt().default;Object.defineProperty(To,"__esModule",{value:!0}),To.default=void 0;var t=e(CA()),s=e(_x());const n={lang:Object.assign({placeholder:"请选择日期",yearPlaceholder:"请选择年份",quarterPlaceholder:"请选择季度",monthPlaceholder:"请选择月份",weekPlaceholder:"请选择周",rangePlaceholder:["开始日期","结束日期"],rangeYearPlaceholder:["开始年份","结束年份"],rangeMonthPlaceholder:["开始月份","结束月份"],rangeQuarterPlaceholder:["开始季度","结束季度"],rangeWeekPlaceholder:["开始周","结束周"]},t.default),timePickerLocale:Object.assign({},s.default)};return n.lang.ok="确定",To.default=n,To}var Cp;function MA(){if(Cp)return _o;Cp=1;var e=tt().default;Object.defineProperty(_o,"__esModule",{value:!0}),_o.default=void 0;var t=e(Tx());return _o.default=t.default,_o}var Mp;function PA(){if(Mp)return So;Mp=1;var e=tt().default;Object.defineProperty(So,"__esModule",{value:!0}),So.default=void 0;var t=e(jA()),s=e(MA()),n=e(Tx()),o=e(_x());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 So.default=i,So}var Kl,Pp;function EA(){return Pp||(Pp=1,Kl=PA()),Kl}var RA=EA();const AA=br(RA);var Co={},Mo={},Ep;function IA(){if(Ep)return Mo;Ep=1,Object.defineProperty(Mo,"__esModule",{value:!0}),Mo.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 Mo.default=e,Mo}var Po={},Eo={},Ro={},Rp;function $A(){if(Rp)return Ro;Rp=1;var e=tt().default;Object.defineProperty(Ro,"__esModule",{value:!0}),Ro.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 Ro.default=n,Ro}var Ao={},Ap;function kx(){if(Ap)return Ao;Ap=1,Object.defineProperty(Ao,"__esModule",{value:!0}),Ao.default=void 0;const e={placeholder:"請選擇時間"};return Ao.default=e,Ao}var Ip;function jx(){if(Ip)return Eo;Ip=1;var e=tt().default;Object.defineProperty(Eo,"__esModule",{value:!0}),Eo.default=void 0;var t=e($A()),s=e(kx());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="確 定",Eo.default=n,Eo}var $p;function DA(){if($p)return Po;$p=1;var e=tt().default;Object.defineProperty(Po,"__esModule",{value:!0}),Po.default=void 0;var t=e(jx());return Po.default=t.default,Po}var Dp;function FA(){if(Dp)return Co;Dp=1;var e=tt().default;Object.defineProperty(Co,"__esModule",{value:!0}),Co.default=void 0;var t=e(IA()),s=e(DA()),n=e(jx()),o=e(kx());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 Co.default=i,Co}var Gl,Fp;function LA(){return Fp||(Fp=1,Gl=FA()),Gl}var OA=LA();const zA=br(OA),NA=e=>{switch(e){case"zh-CN":return AA;case"zh-TW":return zA;case"fr-FR":return uA;case"ja-JP":return kA;case"hi-IN":return xA;default:return rA}},BA="copilot_ui_theme_v1",Cx={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)"},Mx={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)"},Px={Tag:{defaultBg:"rgba(13, 148, 136, 0.1)",defaultColor:"#0f766e"},Table:{bodySortBg:"rgba(13, 148, 136, 0.08)"}},Ex={Tag:{defaultBg:"rgba(45, 212, 191, 0.18)",defaultColor:"#ccfbf1"},Table:{bodySortBg:"rgba(45, 212, 191, 0.14)"}},WA={...Cx,colorBgElevated:"#ffffff",colorBgSpotlight:"#0f172a",colorFillTertiary:"#f3f7f6"},UA={...Mx,colorBgElevated:"#0f1b18",colorBgSpotlight:"#22332f",colorFillTertiary:"#162622"},qA={...Px,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"}},HA={...Ex,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 YA(){const{t:e}=se(),t=Hn(x=>x.themeMode),s=Hn(x=>x.setThemeMode),[n,o]=m.useState(()=>Lx()),[a,i]=m.useState(()=>yi()),[l,c]=m.useState(null),[d,u]=m.useState(null),[h,f]=m.useState(0);if(m.useEffect(()=>{localStorage.setItem(BA,t)},[t]),m.useEffect(()=>{localStorage.setItem(Ox,n),as.changeLanguage(n)},[n]),m.useEffect(()=>{let x=!1;const b=Date.now(),S=async()=>{try{const k=await Nt.getInstance().getSetupStatus();if(x)return;u(null),c(k.is_complete)}catch(w){if(x)return;const k=Date.now()-b;if(k>=2e4){const P=kr(),v=w instanceof Error&&w.message.trim()?w.message:"Unknown error";u(e("app.backendNotReachable",{baseUrl:P,message:v}));return}const C=Math.min(500+Math.floor(k/2),2e3);setTimeout(()=>{x||S()},C)}};return S(),()=>{x=!0}},[h,e]),m.useEffect(()=>{document.body.setAttribute("data-theme",t)},[t]),m.useEffect(()=>{const x=()=>{const b=yi();i(b),document.body.setAttribute("data-vdi-safe",b?"true":"false");const S=document.getElementById("root");S&&S.setAttribute("data-vdi-safe",b?"true":"false")};return x(),window.addEventListener("storage",x),window.addEventListener("lotus-vdi-safe-mode-change",x),()=>{window.removeEventListener("storage",x),window.removeEventListener("lotus-vdi-safe-mode-change",x)}},[]),m.useEffect(()=>{var b;const x=(b=window.__TAURI_INTERNALS__)==null?void 0:b.invoke;typeof x=="function"&&x("set_window_theme",{theme:t}).catch(S=>{console.warn("[App] Failed to sync native window theme:",S)})},[t]),m.useEffect(()=>{l&&Fv()},[l]),l===null)return d?r.jsxs("div",{style:{padding:40,textAlign:"center"},children:[r.jsx("div",{style:{marginBottom:12},children:d}),r.jsx(U,{type:"primary",onClick:()=>{u(null),c(null),f(x=>x+1)},children:e("app.retry")})]}):r.jsx("div",{style:{padding:40,textAlign:"center"},children:e("app.loading")});const g=l?r.jsx(XR,{themeMode:t,onThemeModeChange:s,locale:n,onLocaleChange:o}):r.jsx(VR,{}),y=t==="dark"?a?UA:Mx:a?WA:Cx,p=t==="dark"?a?HA:Ex:a?qA:Px;return r.jsx(jb,{locale:NA(n),theme:{token:y,algorithm:t==="dark"?pe.darkAlgorithm:pe.defaultAlgorithm,components:p},children:r.jsx(us,{children:r.jsx(vi,{name:"App",children:r.jsx("div",{style:{position:"relative"},children:g})})})})}const lI=Object.freeze(Object.defineProperty({__proto__:null,default:YA},Symbol.toStringTag,{value:"Module"}));export{lI as A,Go as C,we as a,Ke as d,Xn as p,N as u,Jm as v,ij as w};
|