@bigduu/lotus 2026.5.4 → 2026.5.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-b3yZCRqq.js +250 -0
- package/dist/assets/{index-BR-Jz13T.js → index-CWu7YVPN.js} +1 -1
- package/dist/assets/{index-8MhLoQym.js → index-D-36MGco.js} +1 -1
- package/dist/assets/{index-jIgpBMFj.js → index-ytQ0KoKe.js} +1 -1
- package/dist/assets/{main-_fs1sZGu.js → main-NZYpmPsh.js} +5 -5
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/dist/assets/App-CIBUzKFV.js +0 -254
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-D-36MGco.js","./vendor-markdown-yOmFo5hK.js","./vendor-i18n-BNURlJ23.js","./vendor-antd-BpW-8RO2.js","./main-NZYpmPsh.js","./main-B6snAd4S.css","./vendor-charts-fIPNnfk-.js","./vendor-mermaid-DA4JIJaA.js","./index-CTVpEC_u.js","./index-ytQ0KoKe.js","./index-Bi-vGirQ.css","./index-CWu7YVPN.js","./index-Byt6VrzO.js","./index-BmjFP0ha.js","./core-Cfh-QHsP.js","./index-_XI0Qq6F.js","./vendor-pdf-xt0MLWhy.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var Tw=Object.defineProperty;var jw=(e,t,n)=>t in e?Tw(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Ct=(e,t,n)=>jw(e,typeof t!="symbol"?t+"":t,n);import{j as o,M as Ps,r as Lc,h as Bo,_ as Bn,S as gn,a as ab,t as ib,p as lb,b as Cw,c as _m,d as Mw,m as cb,s as Pw,y as db,e as ub,f as km,g as Tm,i as mb}from"./vendor-markdown-yOmFo5hK.js";import{a as p,R as fn,i as Es,c as Ew,g as fo,u as Ie}from"./vendor-i18n-BNURlJ23.js";import{r as Rw,A as Aw}from"./main-NZYpmPsh.js";import{S as he,B as ue,C as Ce,m as He,L as Qt,Y as bs,T as Ne,Z as Iw,$ as Fc,a0 as xs,a1 as Cr,M as Xn,E as Mn,a2 as Ui,t as Ge,a3 as ju,a4 as jm,j as Hi,O as io,a5 as hb,a6 as Ow,k as Mr,H as $w,o as Ho,a7 as lo,a8 as Dw,I as Qe,K as be,a9 as Gn,aa as Vs,i as rr,ab as Ki,n as bt,ac as Lw,ad as Fw,A as sn,ae as pb,af as $i,ag as Nw,ah as Nc,p as Ut,F as Pe,v as Rs,ai as Di,aj as St,ak as pn,al as ps,am as Et,an as Kn,ao as Zt,ap as zw,V as zn,aq as ir,ar as Bw,as as Cm,P as hc,at as Vi,au as fb,av as zc,aw as sp,ax as or,u as lr,ay as Ww,az as Bc,aA as Cu,aB as Fn,aC as qw,aD as cr,aE as nn,aF as Mm,aG as rp,Q as ar,aH as As,aI as pc,aJ as kl,aK as Uw,aL as Hw,G as Kw,aM as so,aN as gb,aO as op,aP as Wo,aQ as Vw,aR as Yw,l as qo,aS as Pm,U as Em,aT as Xw,aU as Gw,aV as yb,aW as Rm,aX as bb,aY as Jw,aZ as Qw,a_ as Zw,a$ as e_,b0 as t_,b1 as n_,b2 as s_,b3 as xb,b4 as vb,x as Sb,q as fc,b5 as Am,b6 as wb,w as r_,b7 as o_,b8 as a_,N as i_,b9 as l_,ba as c_,bb as d_,bc as u_,bd as _b,be as m_,bf as h_,bg as p_,bh as Im,bi as f_,bj as g_,bk as gc,bl as ap,bm as kb,bn as ip,bo as y_,bp as b_,bq as x_,br as v_,bs as Tb,bt as S_,bu as w_,bv as lp,bw as cp}from"./vendor-antd-BpW-8RO2.js";import{Z as Ko,_ as Om,$ as Yi,a0 as Xi,a1 as Gi,a2 as Vo,a3 as $m,a4 as yc,a5 as jb,a6 as Lo,a7 as __,a8 as k_,a9 as T_}from"./vendor-charts-fIPNnfk-.js";import{bc as Dm}from"./vendor-mermaid-DA4JIJaA.js";function Cb(e){const[t,n]=p.useState(()=>typeof window<"u"?window.matchMedia(e).matches:!1);return p.useEffect(()=>{if(typeof window>"u")return;const s=window.matchMedia(e);n(s.matches);const r=a=>{n(a.matches)};return s.addEventListener?s.addEventListener("change",r):s.addListener(r),()=>{s.removeEventListener?s.removeEventListener("change",r):s.removeListener(r)}},[e]),t}function Lm(){return Cb("(max-width: 768px)")}const j_=({buttons:e,className:t,style:n,size:s="middle",align:r="right"})=>{const a={className:t,style:{width:"100%",justifyContent:r==="left"?"flex-start":r==="center"?"center":"flex-end",...n}};return o.jsx(he,{...a,children:e.map(i=>o.jsx(ue,{type:i.type||"default",disabled:i.disabled,loading:i.loading,danger:i.danger,onClick:i.onClick,size:s,icon:i.icon,children:i.text},i.key))})},C_=(e,t)=>({key:"cancel",text:t||"Cancel",type:"default",onClick:e}),M_=(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}),dp=e=>{let t;const n=new Set,s=(u,m)=>{const f=typeof u=="function"?u(t):u;if(!Object.is(f,t)){const g=t;t=m??(typeof f!="object"||f===null)?f:Object.assign({},t,f),n.forEach(b=>b(t,g))}},r=()=>t,l={setState:s,getState:r,getInitialState:()=>c,subscribe:u=>(n.add(u),()=>n.delete(u))},c=t=e(s,r,l);return l},P_=e=>e?dp(e):dp,E_=e=>e;function R_(e,t=E_){const n=fn.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return fn.useDebugValue(n),n}const up=e=>{const t=P_(e),n=s=>R_(t,s);return Object.assign(n,t),n},Pr=e=>e?up(e):up,mp={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},Li=new Map,Tl=e=>{const t=Li.get(e);return t?Object.fromEntries(Object.entries(t.stores).map(([n,s])=>[n,s.getState()])):{}},A_=(e,t,n)=>{if(e===void 0)return{type:"untracked",connection:t.connect(n)};const s=Li.get(n.name);if(s)return{type:"tracked",store:e,...s};const r={connection:t.connect(n),stores:{}};return Li.set(n.name,r),{type:"tracked",store:e,...r}},I_=(e,t)=>{if(t===void 0)return;const n=Li.get(e);n&&(delete n.stores[t],Object.keys(n.stores).length===0&&Li.delete(e))},O_=e=>{var t,n;if(!e)return;const s=e.split(`
|
|
3
|
+
`),r=s.findIndex(i=>i.includes("api.setState"));if(r<0)return;const a=((t=s[r+1])==null?void 0:t.trim())||"";return(n=/.+ (.+) .+/.exec(a))==null?void 0:n[1]},$_=(e,t={})=>(n,s,r)=>{const{enabled:a,anonymousActionType:i,store:l,...c}=t;let u;try{u=(a??(mp?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!u)return e(n,s,r);const{connection:m,...f}=A_(l,u,c);let g=!0;r.setState=(x,T,j)=>{const w=n(x,T);if(!g)return w;const M=j===void 0?{type:i||O_(new Error().stack)||"anonymous"}:typeof j=="string"?{type:j}:j;return l===void 0?(m==null||m.send(M,s()),w):(m==null||m.send({...M,type:`${l}/${M.type}`},{...Tl(c.name),[l]:r.getState()}),w)},r.devtools={cleanup:()=>{m&&typeof m.unsubscribe=="function"&&m.unsubscribe(),I_(c.name,l)}};const b=(...x)=>{const T=g;g=!1,n(...x),g=T},S=e(r.setState,s,r);if(f.type==="untracked"?m==null||m.init(S):(f.stores[f.store]=r,m==null||m.init(Object.fromEntries(Object.entries(f.stores).map(([x,T])=>[x,x===f.store?S:T.getState()])))),r.dispatchFromDevtools&&typeof r.dispatch=="function"){let x=!1;const T=r.dispatch;r.dispatch=(...j)=>{(mp?"production":void 0)!=="production"&&j[0].type==="__setState"&&!x&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),x=!0),T(...j)}}return m.subscribe(x=>{var T;switch(x.type){case"ACTION":if(typeof x.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return Cd(x.payload,j=>{if(j.type==="__setState"){if(l===void 0){b(j.state);return}Object.keys(j.state).length!==1&&console.error(`
|
|
4
|
+
[zustand devtools middleware] Unsupported __setState action format.
|
|
5
|
+
When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
|
|
6
|
+
and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
|
|
7
|
+
`);const w=j.state[l];if(w==null)return;JSON.stringify(r.getState())!==JSON.stringify(w)&&b(w);return}r.dispatchFromDevtools&&typeof r.dispatch=="function"&&r.dispatch(j)});case"DISPATCH":switch(x.payload.type){case"RESET":return b(S),l===void 0?m==null?void 0:m.init(r.getState()):m==null?void 0:m.init(Tl(c.name));case"COMMIT":if(l===void 0){m==null||m.init(r.getState());return}return m==null?void 0:m.init(Tl(c.name));case"ROLLBACK":return Cd(x.state,j=>{if(l===void 0){b(j),m==null||m.init(r.getState());return}b(j[l]),m==null||m.init(Tl(c.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return Cd(x.state,j=>{if(l===void 0){b(j);return}JSON.stringify(r.getState())!==JSON.stringify(j[l])&&b(j[l])});case"IMPORT_STATE":{const{nextLiftedState:j}=x.payload,w=(T=j.computedStates.slice(-1)[0])==null?void 0:T.state;if(!w)return;b(l===void 0?w:w[l]),m==null||m.send(null,j);return}case"PAUSE_RECORDING":return g=!g}return}}),S},D_=$_,Cd=(e,t)=>{let n;try{n=JSON.parse(e)}catch(s){console.error("[zustand devtools middleware] Could not parse the received json",s)}n!==void 0&&t(n)},L_=e=>(t,n,s)=>{const r=s.subscribe;return s.subscribe=(i,l,c)=>{let u=i;if(l){const m=(c==null?void 0:c.equalityFn)||Object.is;let f=i(s.getState());u=g=>{const b=i(g);if(!m(f,b)){const S=f;l(f=b,S)}},c!=null&&c.fireImmediately&&l(f,f)}return r(u)},e(t,n,s)},F_=L_;function N_(e,t){let n;try{n=e()}catch{return}return{getItem:r=>{var a;const i=c=>c===null?null:JSON.parse(c,void 0),l=(a=n.getItem(r))!=null?a:null;return l instanceof Promise?l.then(i):i(l)},setItem:(r,a)=>n.setItem(r,JSON.stringify(a,void 0)),removeItem:r=>n.removeItem(r)}}const Mu=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(s){return Mu(s)(n)},catch(s){return this}}}catch(n){return{then(s){return this},catch(s){return Mu(s)(n)}}}},z_=(e,t)=>(n,s,r)=>{let a={storage:N_(()=>localStorage),partialize:x=>x,version:0,merge:(x,T)=>({...T,...x}),...t},i=!1;const l=new Set,c=new Set;let u=a.storage;if(!u)return e((...x)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),n(...x)},s,r);const m=()=>{const x=a.partialize({...s()});return u.setItem(a.name,{state:x,version:a.version})},f=r.setState;r.setState=(x,T)=>{f(x,T),m()};const g=e((...x)=>{n(...x),m()},s,r);r.getInitialState=()=>g;let b;const S=()=>{var x,T;if(!u)return;i=!1,l.forEach(w=>{var M;return w((M=s())!=null?M:g)});const j=((T=a.onRehydrateStorage)==null?void 0:T.call(a,(x=s())!=null?x:g))||void 0;return Mu(u.getItem.bind(u))(a.name).then(w=>{if(w)if(typeof w.version=="number"&&w.version!==a.version){if(a.migrate){const M=a.migrate(w.state,w.version);return M instanceof Promise?M.then(_=>[!0,_]):[!0,M]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,w.state];return[!1,void 0]}).then(w=>{var M;const[_,C]=w;if(b=a.merge(C,(M=s())!=null?M:g),n(b,!0),_)return m()}).then(()=>{j==null||j(b,void 0),b=s(),i=!0,c.forEach(w=>w(b))}).catch(w=>{j==null||j(void 0,w)})};return r.persist={setOptions:x=>{a={...a,...x},x.storage&&(u=x.storage)},clearStorage:()=>{u==null||u.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>S(),hasHydrated:()=>i,onHydrate:x=>(l.add(x),()=>{l.delete(x)}),onFinishHydration:x=>(c.add(x),()=>{c.delete(x)})},a.skipHydration||S(),b||g},B_=z_,Mb=()=>!1,Pb=e=>{if(!Mb())return!1;try{return localStorage.getItem(e)==="1"}catch{return!1}},W_=()=>Pb("bodhi_debug_ui_layout"),fs=(e,t)=>{W_()&&console.log(`[ui-layout] ${e}`,t??"")},Jt=(e,t,...n)=>{Mb()&&Pb("bodhi_debug_verbose")&&console.log(`${e} ${t}`,...n)};var Md={};const Pd="copilot_backend_base_url",Eb="http://127.0.0.1:9562/v1",q_=9562,co=e=>e.trim().replace(/\/+$/,""),U_=()=>{const t=Md==null?void 0:Md.VITE_BACKEND_BASE_URL;return t?co(t):null},Ji=()=>{const e=globalThis.location;if(!e)return null;const t=typeof e.protocol=="string"?e.protocol:"",n=typeof e.hostname=="string"?e.hostname:"";return!t||!n?null:{protocol:t,hostname:n}},Fm=e=>{const t=e.trim().toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="::1"},H_=(e=Ji())=>(e==null?void 0:e.protocol.toLowerCase())==="https:",K_=e=>{try{return new URL(co(e)).protocol.toLowerCase()==="http:"}catch{return!1}},V_=e=>{try{const t=new URL(co(e));return Fm(t.hostname)}catch{return!1}},Y_=(e=Ji())=>{if(!e)return null;const t=e.protocol.toLowerCase(),n=e.hostname.trim();return n?t==="https:"?co(`https://${n}/v1`):t==="http:"?co(`http://${n}/v1`):null:null},X_=(e,t=Ji())=>{if(!t)return!1;const n=t.hostname.trim();return n?H_(t)&&K_(e)?!0:Fm(n)?!1:V_(e):!1},G_=(e=Ji())=>{if(!e)return null;const t=e.protocol.toLowerCase();if(t!=="http:"&&t!=="https:")return null;const n=e.hostname.trim();return n?t==="https:"?Y_(e):Fm(n)?Eb:co(`http://${n}:${q_}/v1`):null},J_=()=>{const e=U_();return e||(G_()??Eb)},Yo=()=>{const e=Ji(),t=localStorage.getItem(Pd);if(t){const n=co(t);if(X_(n,e))console.warn("Ignoring stored backend override because it is incompatible with the current page origin:",n),localStorage.removeItem(Pd);else try{return new URL(n),n}catch{console.warn("Invalid stored backend URL, using default:",n),localStorage.removeItem(Pd)}}return J_()};class uo extends Error{constructor(t,n,s,r){super(t),this.status=n,this.statusText=s,this.body=r,this.name="ApiError"}}function Q_(e){return e instanceof uo}class Nm{constructor(t={}){Ct(this,"baseUrl");Ct(this,"defaultHeaders");this.baseUrl=t.baseUrl??this.resolveBaseUrl(),this.defaultHeaders=t.defaultHeaders??{"Content-Type":"application/json"}}resolveBaseUrl(){const t=Yo().trim().replace(/\/+$/,"");return t.endsWith("/v1")?t:`${t}/v1`}buildUrl(t){const n=t.replace(/^\/+/,"");return`${this.baseUrl}/${n}`}async handleResponse(t){var s,r,a;if(!t.ok){const i=await t.text().catch(()=>{});let l=t.statusText;if(i)try{const c=JSON.parse(i),u=typeof(c==null?void 0:c.error)=="object"?(s=c.error)==null?void 0:s.message:void 0;l=(typeof(c==null?void 0:c.error)=="string"?c.error:void 0)||(typeof u=="string"?u:void 0)||c.message||c.detail||t.statusText}catch{l=i||t.statusText}throw new uo(l,t.status,t.statusText,i)}return t.status===204?void 0:(((a=(r=t.headers)==null?void 0:r.get)==null?void 0:a.call(r,"content-type"))||"").includes("application/json")?t.json():typeof t.text=="function"?await t.text():t.json()}delay(t){return new Promise(n=>setTimeout(n,t))}async fetchWithRetry(t,n,s=3){let r=null;for(let a=0;a<s;a++)try{const i=await fetch(t,n);if(i.status>=500&&a<s-1){const l=1e3*Math.pow(2,a);console.warn(`Request failed with ${i.status}, retrying in ${l}ms (attempt ${a+1}/${s})`),await this.delay(l);continue}return i}catch(i){if(r=i,a<s-1){const l=1e3*Math.pow(2,a);console.warn(`Network error: ${r.message}, retrying in ${l}ms (attempt ${a+1}/${s})`),await this.delay(l)}}throw r||new Error("Max retries exceeded")}async get(t,n){const s=this.buildUrl(t),r=new AbortController,a=setTimeout(()=>r.abort(),3e4);try{const i=await this.fetchWithRetry(s,{...n,method:"GET",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",signal:r.signal},3);return this.handleResponse(i)}finally{clearTimeout(a)}}async post(t,n,s){const r=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(r,{...s,method:"POST",headers:{...this.defaultHeaders,...s==null?void 0:s.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async put(t,n,s){const r=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(r,{...s,method:"PUT",headers:{...this.defaultHeaders,...s==null?void 0:s.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async patch(t,n,s){const r=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(r,{...s,method:"PATCH",headers:{...this.defaultHeaders,...s==null?void 0:s.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async delete(t,n){const s=this.buildUrl(t),r=new AbortController,a=setTimeout(()=>r.abort(),3e4);try{const i=await this.fetchWithRetry(s,{...n,method:"DELETE",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",signal:r.signal},3);return this.handleResponse(i)}finally{clearTimeout(a)}}async request(t,n,s){const r=this.buildUrl(n),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(r,{...s,method:t,headers:{...this.defaultHeaders,...s==null?void 0:s.headers},credentials:"include",signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async fetchRaw(t,n){const s=this.buildUrl(t),r=await fetch(s,{...n,headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include"});if(!r.ok)throw new uo(`API request failed: ${r.statusText}`,r.status,r.statusText);return r}}const rt=new Nm,Ze=new Nm({baseUrl:(()=>{let e=Yo().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`})()});function Z_(e){return e instanceof uo}const Gr=class Gr{static getInstance(){return Gr.instance||(Gr.instance=new Gr),Gr.instance}async sendMessage(t){return Ze.post("chat",t)}async execute(t,n,s,r,a){const i={};return n&&(i.model=n),s&&(i.reasoning_effort=s),r&&(i.client_sync=r),a&&(i.model_ref=a,i.provider=a.provider),Ze.post(`execute/${t}`,i)}async listSessions(){return Ze.get("sessions")}async getTaskList(t){const n=encodeURIComponent(t),s=await Ze.get(`task/${n}`);if(!(typeof s.title=="string"||s.items.length>0))return null;const a=new Date().toISOString();return{session_id:s.session_id,title:s.title??"Task List",items:s.items,created_at:a,updated_at:a}}async createSession(t){return Ze.post("sessions",t)}async patchSession(t,n){const s=encodeURIComponent(t);await Ze.patch(`sessions/${s}`,n)}async regenerateSessionTitle(t){const n=encodeURIComponent(t);await Ze.post(`sessions/${n}/regenerate-title`)}async getSessionSystemPrompt(t){const n=encodeURIComponent(t);return Ze.get(`sessions/${n}/system-prompt`)}async clearSession(t){const n=encodeURIComponent(t);await Ze.post(`sessions/${n}/clear`)}async runProjectDream(t){const n=encodeURIComponent(t);return Ze.post(`sessions/${n}/project-dream/run`)}async truncateSessionMessages(t,n){const s=encodeURIComponent(t);return Ze.post(`sessions/${s}/messages/truncate`,n)}async restoreSessionState(t,n){const s=encodeURIComponent(t);return Ze.post(`sessions/${s}/restore`,n)}async patchSessionMessage(t,n,s){const r=encodeURIComponent(t),a=encodeURIComponent(n);await Ze.patch(`sessions/${r}/messages/${a}`,s)}async deleteSessionMessage(t,n){const s=encodeURIComponent(t),r=encodeURIComponent(n);await Ze.delete(`sessions/${s}/messages/${r}`)}async cleanupSessions(t,n){await Ze.post("sessions/cleanup",{mode:t,keep_pinned:n})}async devResetSessions(){await Ze.post("dev/reset")}async getRunningSessions(){return Ze.get("runs/active")}async listSchedules(){return Ze.get("schedules")}async createSchedule(t){return Ze.post("schedules",t)}async patchSchedule(t,n){const s=encodeURIComponent(t);return Ze.patch(`schedules/${s}`,n)}async deleteSchedule(t){const n=encodeURIComponent(t);await Ze.delete(`schedules/${n}`)}async runScheduleNow(t){const n=encodeURIComponent(t);await Ze.post(`schedules/${n}/run`)}async listScheduleSessions(t){const n=encodeURIComponent(t);return Ze.get(`schedules/${n}/sessions`)}async listScheduleRuns(t){const n=encodeURIComponent(t);return Ze.get(`schedules/${n}/runs`)}async subscribeToEvents(t,n,s){var a;const r=s==null?void 0:s.signal;Jt("[AgentClient]","[AgentClient] Subscribing to events for session:",t);try{const i=await Ze.fetchRaw(`events/${t}`,{signal:r});if(Jt("[AgentClient]","[AgentClient] Events subscription response:",i.status,i.statusText,"Content-Type:",i.headers.get("content-type")),!i.ok){let m=`Failed to subscribe to events: ${i.statusText}`;try{const f=await i.text();if(f)try{const g=JSON.parse(f);m=g.error||g.message||g.detail||m}catch{m=f||m}}catch(f){console.error("Failed to parse error response:",f)}throw new Error(m)}const l=(a=i.body)==null?void 0:a.getReader();if(!l)throw new Error("No response body");const c=new TextDecoder;let u="";try{for(;!(r!=null&&r.aborted);){const{done:m,value:f}=await l.read();if(m)break;u+=c.decode(f,{stream:!0});const g=u.split(`
|
|
8
|
+
`);u=g.pop()||"";for(const b of g)if(b.startsWith("data: ")){const S=b.slice(6);if(S==="[DONE]")return;try{const x=JSON.parse(S);this.handleEvent(x,n)}catch(x){console.warn("Failed to parse event:",S,x)}}}}finally{l.releaseLock()}}catch(i){if(r!=null&&r.aborted){Jt("[AgentClient]","Events subscription aborted for session:",t);return}throw console.error("[AgentClient] Events subscription error:",i),i}}handleEvent(t,n){var s,r,a,i,l,c,u,m,f,g,b,S,x,T,j,w,M,_,C,L,A,B,N,O,R,I,$;switch(t.type){case"token":(s=n.onToken)==null||s.call(n,t.content||"");break;case"reasoning_token":(r=n.onReasoningToken)==null||r.call(n,t.content||"");break;case"tool_token":(a=n.onToolToken)==null||a.call(n,t.tool_call_id||"",t.content||"");break;case"tool_start":(i=n.onToolStart)==null||i.call(n,t.tool_call_id||"",t.tool_name||"",t.arguments||{});break;case"tool_complete":t.result&&((l=n.onToolComplete)==null||l.call(n,t.tool_call_id||"",t.result));break;case"tool_error":(c=n.onToolError)==null||c.call(n,t.tool_call_id||"",t.error||"");break;case"task_list_updated":t.task_list&&((u=n.onTaskListUpdated)==null||u.call(n,t.task_list));break;case"task_list_item_progress":if(t.session_id&&t.item_id&&t.status&&t.tool_calls_count!==void 0&&t.version!==void 0){const U=t.status;if(!(U==="pending"||U==="in_progress"||U==="completed"||U==="blocked"))break;(m=n.onTaskListItemProgress)==null||m.call(n,{session_id:t.session_id,item_id:t.item_id,status:U,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&&((f=n.onTaskListCompleted)==null||f.call(n,t.session_id,t.total_rounds,t.total_tool_calls));break;case"task_evaluation_started":t.session_id&&t.items_count!==void 0&&((g=n.onTaskEvaluationStarted)==null||g.call(n,t.session_id,t.items_count));break;case"task_evaluation_completed":t.session_id&&t.updates_count!==void 0&&t.reasoning&&((b=n.onTaskEvaluationCompleted)==null||b.call(n,t.session_id,t.updates_count,t.reasoning));break;case"token_budget_updated":t.usage&&"system_tokens"in t.usage&&((S=n.onTokenBudgetUpdated)==null||S.call(n,t.usage));break;case"context_compression_status":typeof t.phase=="string"&&typeof t.status=="string"&&((x=n.onContextCompressionStatus)==null||x.call(n,t.phase,t.status));break;case"tool_lifecycle":(T=n.onToolLifecycle)==null||T.call(n,t.tool_call_id||"",t.tool_name||"",t.phase||"",t.elapsed_ms,t.is_mutating,t.auto_approved,t.summary,t.error);break;case"context_summarized":t.summary_info&&((j=n.onContextSummarized)==null||j.call(n,t.summary_info));break;case"context_pressure_notification":typeof t.percent=="number"&&typeof t.level=="string"&&((w=n.onContextPressureNotification)==null||w.call(n,t.percent,t.level,t.message||""));break;case"sub_session_started":t.parent_session_id&&t.child_session_id&&((M=n.onSubSessionStarted)==null||M.call(n,t.parent_session_id,t.child_session_id,t.title));break;case"sub_session_event":t.parent_session_id&&t.child_session_id&&t.event&&((_=n.onSubSessionEvent)==null||_.call(n,t.parent_session_id,t.child_session_id,t.event));break;case"sub_session_heartbeat":t.parent_session_id&&t.child_session_id&&t.timestamp&&((C=n.onSubSessionHeartbeat)==null||C.call(n,t.parent_session_id,t.child_session_id,t.timestamp));break;case"sub_session_completed":t.parent_session_id&&t.child_session_id&&((L=n.onSubSessionCompleted)==null||L.call(n,t.parent_session_id,t.child_session_id,typeof t.status=="string"?t.status:"completed",t.error));break;case"execution_started":(A=n.onExecutionStarted)==null||A.call(n,t.run_id||"",t.started_at);break;case"runner_progress":t.session_id&&typeof t.round_count=="number"&&((B=n.onRunnerProgress)==null||B.call(n,t.session_id,t.round_count));break;case"need_clarification":(N=n.onNeedClarification)==null||N.call(n,t);break;case"session_title_updated":t.session_id&&typeof t.title=="string"&&typeof t.title_version=="number"&&(t.source==="auto"||t.source==="manual"||t.source==="fallback")&&typeof t.updated_at=="string"&&((O=n.onSessionTitleUpdated)==null||O.call(n,{type:"session_title_updated",session_id:t.session_id,title:t.title,title_version:t.title_version,source:t.source,updated_at:t.updated_at}));break;case"session_pinned_updated":t.session_id&&typeof t.pinned=="boolean"&&typeof t.updated_at=="string"&&((R=n.onSessionPinnedUpdated)==null||R.call(n,{type:"session_pinned_updated",session_id:t.session_id,pinned:t.pinned,updated_at:t.updated_at}));break;case"complete":(I=n.onComplete)==null||I.call(n,t.usage);break;case"error":($=n.onError)==null||$.call(n,t.message||t.error||"Unknown error");break;default:console.warn("Unknown event type:",t)}}async stopGeneration(t){await Ze.post(`stop/${t}`)}async deleteSession(t){const n=encodeURIComponent(t);await Ze.delete(`sessions/${n}`)}async getHistory(t){return Ze.get(`history/${t}`)}async healthCheck(){try{return await Ze.get("health"),!0}catch{return!1}}};Ct(Gr,"instance");let Jn=Gr;const Fo=Jn.getInstance(),e0=()=>({id:"general_assistant",name:"Bodhi",description:Es.t("chat.prompt.defaultDescription"),content:`You are Bodhi, a highly capable AI assistant.
|
|
9
|
+
|
|
10
|
+
You help users solve problems quickly and correctly. Be concise, practical, and proactive.
|
|
11
|
+
If requirements are unclear, ask focused clarifying questions before proceeding.`,isDefault:!0}),bc=()=>[e0()];class t0{async getProviderConfig(){return rt.get("/bamboo/settings/provider")}async saveProviderConfig(t){return rt.post("/bamboo/settings/provider",t)}async reloadConfig(){return rt.post("/bamboo/settings/reload")}async getCopilotAuthStatus(){return rt.post("/bamboo/copilot/auth/status")}async startCopilotAuth(){return rt.post("/bamboo/copilot/auth/start")}async completeCopilotAuth(t){return rt.post("/bamboo/copilot/auth/complete",t)}async authenticateCopilot(){return rt.post("/bamboo/copilot/authenticate")}async logoutCopilot(){return rt.post("/bamboo/copilot/logout")}async fetchProviderModels(t){return(await rt.post("/bamboo/settings/provider/models",{provider:t})).models}async getProviderCatalog(){return rt.get("/bamboo/provider-catalog")}async fetchCatalogModels(t){const n=t?{provider:t}:{};return rt.post("/bamboo/provider-catalog/fetch-models",n)}async getEnvVars(){return rt.get("/bamboo/env-vars")}async upsertEnvVar(t){return rt.post("/bamboo/env-vars",t)}async deleteEnvVar(t){return rt.delete(`/bamboo/env-vars/${encodeURIComponent(t)}`)}async replaceEnvVars(t){return rt.post("/bamboo/env-vars/replace",{entries:t})}}const Vn=new t0,Mt=Pr((e,t)=>({currentProvider:"copilot",providerConfig:{provider:"copilot",defaults:void 0,providers:{}},isLoading:!1,error:null,selectedModelRef:null,catalog:null,isCatalogFetching:!1,loadProviderConfig:async()=>{var n,s;e({isLoading:!0,error:null});try{const r=await Vn.getProviderConfig();if(!((s=(n=r.defaults)==null?void 0:n.chat)!=null&&s.model)&&r.provider&&r.providers){const a=r.provider,i=r.providers[a],l=i==null?void 0:i.model;l&&(r.defaults={chat:{provider:a,model:l}})}e({providerConfig:r,currentProvider:r.provider,isLoading:!1})}catch(r){console.error("Failed to load provider config:",r),e({error:r instanceof Error?r.message:"Failed to load provider config",isLoading:!1})}},setCurrentProvider:n=>{e({currentProvider:n})},updateProviderConfig:n=>{e(s=>({providerConfig:{...s.providerConfig,...n}}))},getActiveModel:()=>{var r,a,i;return((i=(a=(r=t().providerConfig.defaults)==null?void 0:r.chat)==null?void 0:a.model)==null?void 0:i.trim())||void 0},getFastModel:()=>{var r,a,i;const n=t();return((i=(a=(r=n.providerConfig.defaults)==null?void 0:r.fast)==null?void 0:a.model)==null?void 0:i.trim())||n.getActiveModel()},getVisionModel:()=>{var r,a,i;const n=t();return((i=(a=(r=n.providerConfig.defaults)==null?void 0:r.vision)==null?void 0:a.model)==null?void 0:i.trim())||n.getActiveModel()},isProviderModelRefEnabled:()=>!0,setSelectedModelRef:n=>{e({selectedModelRef:n})},loadCatalog:async()=>{try{const n=await Vn.getProviderCatalog();e({catalog:n})}catch{}},fetchCatalogModels:async n=>{e({isCatalogFetching:!0});try{await Vn.fetchCatalogModels(n),await t().loadCatalog()}catch{}finally{e({isCatalogFetching:!1})}},getFastModelRef:()=>{var a,i,l,c;const n=t(),s=(a=n.providerConfig.defaults)==null?void 0:a.fast;if((i=s==null?void 0:s.model)!=null&&i.trim())return s;const r=(l=n.providerConfig.defaults)==null?void 0:l.chat;return(c=r==null?void 0:r.model)!=null&&c.trim()?r:null},getVisionModelRef:()=>{var a,i,l,c;const n=t(),s=(a=n.providerConfig.defaults)==null?void 0:a.vision;if((i=s==null?void 0:s.model)!=null&&i.trim())return s;const r=(l=n.providerConfig.defaults)==null?void 0:l.chat;return(c=r==null?void 0:r.model)!=null&&c.trim()?r:null},getModelsForProvider:n=>{const{catalog:s}=t();return s!=null&&s.models?s.models.filter(r=>r.reference.provider===n):[]}})),n0=Object.freeze(Object.defineProperty({__proto__:null,useProviderStore:Mt},Symbol.toStringTag,{value:"Module"}));function Rb(e){return e.type==="session_title_updated"||e.type==="session_pinned_updated"}function Pu(e,t){switch(e.type){case"session_title_updated":{typeof e.session_id=="string"&&typeof e.title=="string"&&typeof e.title_version=="number"&&t.applyServerTitle(e.session_id,e.title,e.title_version);break}case"session_pinned_updated":{typeof e.session_id=="string"&&typeof e.pinned=="boolean"&&typeof e.updated_at=="string"&&t.applyServerPinned(e.session_id,e.pinned,e.updated_at);break}}}function s0(e,t){const n=t.findIndex(s=>s.id===e.session_id);if(!(n<0))switch(e.type){case"session_title_updated":{if(typeof e.title!="string"||typeof e.title_version!="number")return;const s=e.title_version,r=t[n].titleVersion??0;if(s<=r)return;t[n]={...t[n],title:e.title,titleVersion:s};return}case"session_pinned_updated":{if(typeof e.pinned!="boolean"||typeof e.updated_at!="string")return;const s=new Date(e.updated_at).getTime(),r=new Date(t[n].updatedAt??0).getTime();if(s<r||t[n].pinned===e.pinned)return;t[n]={...t[n],pinned:e.pinned,updatedAt:e.updated_at};return}}}const r0=5e3,hp=80,o0=16,zm=e=>e!==void 0&&e!=="idle"&&e!=="completed"&&e!=="error"&&e!=="cancelled",a0=e=>e==="starting"||e==="running"||e==="streaming"||e==="running_tools"||e==="running_children"||e==="settling",i0=e=>e==="starting"||e==="running"||e==="streaming"||e==="running_tools"||e==="running_children",Ab=e=>({sessionId:e,phase:"idle",confidence:"optimistic",activeReasons:[],generation:0,backendRunId:null,stream:{hasTokens:!1,tokenCount:0,activeToolCalls:[],lastStatusHint:null},backend:{isRunning:!1,lastRunStatus:null,lastRunError:null,syncedAt:null,hasPendingQuestion:null,runningChildCount:null},interaction:{pendingQuestion:null,respondMode:null},children:{byId:{},runningCount:0},timestamps:{optimisticAt:null,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},error:null}),Dn=(e,t)=>e[t]??Ab(t),Nt=(e,t)=>[...e.length>=o0?e.slice(-15):e,t],l0=e=>e.length<=hp?e:e.slice(e.length-hp),Wc=new Set(["idle","completed","error","cancelled","settling","waiting_user_answer"]),Xo=e=>Wc.has(e.phase)?e:e.children.runningCount>0?e.phase==="running_children"?e:{...e,phase:"running_children"}:e.stream.activeToolCalls.length>0?e.phase==="running_tools"?e:{...e,phase:"running_tools"}:e.stream.hasTokens?e.phase==="streaming"?e:{...e,phase:"streaming"}:e.phase==="running"?e:{...e,phase:"running"},un=(e,t,n)=>({...e,[t]:n}),c0=(e,t)=>{if(!(t in e))return e;const n={...e};return delete n[t],n},pp=(e,t,n)=>{const s=e.timestamps.firstTokenAt??n(),r={...e,confidence:"live",stream:{...e.stream,hasTokens:!0,tokenCount:e.stream.tokenCount+1},timestamps:{...e.timestamps,firstTokenAt:s},activeReasons:Nt(e.activeReasons,t)};return Xo(r)},d0=(e,t,n,s)=>{const a=e.stream.activeToolCalls.findIndex(l=>l.toolCallId===t)>=0?e.stream.activeToolCalls:[...e.stream.activeToolCalls,{toolCallId:t,toolName:n,startedAt:s}],i={...e,confidence:"live",stream:{...e.stream,activeToolCalls:a},activeReasons:Nt(e.activeReasons,"sse:tool_start")};return Xo(i)},u0=(e,t,n)=>{const s=e.stream.activeToolCalls.findIndex(u=>u.toolCallId===t);if(s<0)return e;const r=e.stream.activeToolCalls[s],a=r.preview??"",i=l0(a+n),l={...r,preview:i},c=[...e.stream.activeToolCalls];return c[s]=l,{...e,stream:{...e.stream,activeToolCalls:c}}},m0=(e,t,n)=>{const s=e.stream.activeToolCalls.filter(a=>a.toolCallId!==t);if(s.length===e.stream.activeToolCalls.length)return e;const r={...e,stream:{...e.stream,activeToolCalls:s},activeReasons:Nt(e.activeReasons,n)};return r.timestamps.terminalAt&&r.children.runningCount===0&&r.stream.activeToolCalls.length===0&&!Wc.has(r.phase)?{...r,phase:"settling",timestamps:{...r.timestamps,settlingStartedAt:r.timestamps.settlingStartedAt??r.timestamps.terminalAt}}:Xo(r)},Ib=(e,t,n)=>{const s=e.children.byId[t],r=s!==void 0&&(s.status===void 0||s.status==="running"),a={...s,...n,status:n.status??(s==null?void 0:s.status)??"running"},l=(a.status===void 0||a.status==="running"?1:0)-(r?1:0),c={...e,confidence:"live",children:{byId:{...e.children.byId,[t]:a},runningCount:Math.max(0,e.children.runningCount+l)},activeReasons:Nt(e.activeReasons,"sse:sub_session_started")};return Xo(c)},Eu=(e,t,n)=>{const s=e.children.byId[t],r=s===void 0||s.status===void 0||s.status==="running",a={...s,...n},i=a.status===void 0||a.status==="running";let l=0;s!==void 0&&(l=(i?1:0)-(r?1:0));const c=Math.max(0,e.children.runningCount+l),u={...e,children:{byId:{...e.children.byId,[t]:a},runningCount:c}};return u.timestamps.terminalAt&&u.children.runningCount===0&&u.stream.activeToolCalls.length===0&&!Wc.has(u.phase)?{...u,phase:"settling",timestamps:{...u.timestamps,settlingStartedAt:u.timestamps.settlingStartedAt??u.timestamps.terminalAt},activeReasons:Nt(u.activeReasons,"sse:sub_session_completed")}:Xo(u)},h0=(e,t)=>{if(!(t in e.children.byId))return e;const n=e.children.byId[t],s=n.status===void 0||n.status==="running",r={...e.children.byId};delete r[t];const a={...e,children:{byId:r,runningCount:Math.max(0,e.children.runningCount-(s?1:0))}};return a.timestamps.terminalAt&&a.children.runningCount===0&&a.stream.activeToolCalls.length===0&&!Wc.has(a.phase)?{...a,phase:"settling",timestamps:{...a.timestamps,settlingStartedAt:a.timestamps.settlingStartedAt??a.timestamps.terminalAt}}:Xo(a)},fp=(e,t,n)=>{switch(t.type){case"token":return pp(e,"sse:token",n);case"reasoning_token":return pp(e,"sse:token",n);case"tool_start":{const s=t.tool_call_id??"",r=t.tool_name??"";return s?d0(e,s,r,n()):e}case"tool_token":{const s=t.tool_call_id??"";return s?u0(e,s,t.content??""):e}case"tool_complete":case"tool_error":{const s=t.tool_call_id??"";return s?m0(e,s,"sse:tool_complete"):e}case"tool_lifecycle":return e;case"sub_session_started":{const s=t.child_session_id??"";return s?Ib(e,s,{title:t.title,status:"running"}):e}case"sub_session_event":case"sub_session_heartbeat":{const s=t.child_session_id??"";if(!s)return e;const r={lastEventAt:t.timestamp??n()};return t.type==="sub_session_heartbeat"&&(r.lastHeartbeatAt=t.timestamp??n()),Eu(e,s,r)}case"sub_session_completed":{const s=t.child_session_id??"";if(!s)return e;const r=typeof t.status=="string"?t.status:"completed";return Eu(e,s,{status:r,error:t.error})}case"need_clarification":{const s={question:t.question??"",options:t.options??[],allowCustom:t.allow_custom??!1,toolCallId:t.tool_call_id??null},r=n();return{...e,phase:"waiting_user_answer",confidence:"live",interaction:{...e.interaction,pendingQuestion:{...s,receivedAt:r},respondMode:{...s,sessionId:e.sessionId}},activeReasons:Nt(e.activeReasons,"sse:need_clarification")}}case"execution_started":{const s=t.run_id;return s?e.phase!=="starting"?{...e,backendRunId:s,confidence:"live",activeReasons:Nt(e.activeReasons,"sse:execution_started")}:{...e,phase:"running",confidence:"live",backendRunId:s,timestamps:{...e.timestamps,confirmedAt:n()},activeReasons:Nt(e.activeReasons,"sse:execution_started")}:e}case"complete":{const s=n();return{...e,phase:"settling",timestamps:{...e.timestamps,terminalAt:s,settlingStartedAt:e.timestamps.settlingStartedAt??s},activeReasons:Nt(e.activeReasons,"sse:complete")}}case"error":{const s=n();return{...e,phase:"error",confidence:"terminal",timestamps:{...e.timestamps,terminalAt:s},error:{message:t.message??t.error??"Unknown error",source:"sse",occurredAt:s},activeReasons:Nt(e.activeReasons,"sse:error")}}case"task_list_updated":case"task_list_item_progress":case"task_list_completed":case"task_evaluation_started":case"task_evaluation_completed":case"token_budget_updated":case"context_compression_status":case"context_summarized":case"context_pressure_notification":return e;default:return e}},p0=e=>e==="completed"||e==="error"||e==="cancelled",f0=(e,t,n)=>{const s=t.last_run_status,r=p0(s)?s:null,a=n(),i=t.has_pending_question===void 0?null:t.has_pending_question,l=t.running_child_count===void 0?null:t.running_child_count,c={...e,backend:{...e.backend,isRunning:t.is_running,lastRunStatus:r,lastRunError:t.last_run_error??null,syncedAt:a,hasPendingQuestion:i,runningChildCount:l},backendRunId:e.backendRunId};if(t.is_running)return e.phase==="idle"||e.phase==="completed"||e.phase==="error"||e.phase==="cancelled"?{...c,phase:"running",confidence:"summary",activeReasons:Nt(c.activeReasons,"summary:is_running")}:e.phase==="starting"?{...c,phase:"running",confidence:"summary",timestamps:{...c.timestamps,confirmedAt:a},activeReasons:Nt(c.activeReasons,"summary:is_running")}:c;if(new Set(["starting","running","streaming","running_tools","running_children","settling"]).has(e.phase)){if(r==="completed")return{...c,phase:"completed",confidence:"terminal",timestamps:{...c.timestamps,settledAt:a},activeReasons:Nt(c.activeReasons,"summary:terminal")};if(r==="error")return{...c,phase:"error",confidence:"terminal",timestamps:{...c.timestamps,settledAt:a},error:{message:t.last_run_error??"Backend reported error",source:"summary",occurredAt:a},activeReasons:Nt(c.activeReasons,"summary:terminal")};if(r==="cancelled")return{...c,phase:"cancelled",confidence:"terminal",timestamps:{...c.timestamps,settledAt:a},activeReasons:Nt(c.activeReasons,"summary:terminal")};if(e.timestamps.optimisticAt){const m=Date.parse(a)-Date.parse(e.timestamps.optimisticAt);if(Number.isFinite(m)&&m<r0)return c}return{...c,phase:"idle",confidence:"summary",activeReasons:Nt(c.activeReasons,"summary:terminal")}}return c},g0=()=>new Date().toISOString(),tn=(e,t,n=g0)=>{switch(t.type){case"ensureSession":return t.sessionId in e?e:un(e,t.sessionId,Ab(t.sessionId));case"markOptimisticStart":{const s=Dn(e,t.sessionId),r=n(),a={...s,phase:"starting",confidence:"optimistic",generation:s.generation+1,stream:{hasTokens:!1,tokenCount:0,activeToolCalls:[],lastStatusHint:null},interaction:{...s.interaction,respondMode:null},error:null,timestamps:{optimisticAt:r,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},activeReasons:Nt(s.activeReasons,"optimistic:send")};return un(e,t.sessionId,a)}case"markRespondStart":{const s=Dn(e,t.sessionId),r=n(),a={...s,phase:"starting",confidence:"optimistic",generation:s.generation+1,stream:{hasTokens:!1,tokenCount:0,activeToolCalls:[],lastStatusHint:null},interaction:{...s.interaction,pendingQuestion:null,respondMode:null},error:null,timestamps:{...s.timestamps,optimisticAt:r,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},activeReasons:Nt(s.activeReasons,"optimistic:respond")};return un(e,t.sessionId,a)}case"markRetryStart":{const s=Dn(e,t.sessionId),r=n(),a={...s,phase:"starting",confidence:"optimistic",generation:s.generation+1,stream:{hasTokens:!1,tokenCount:0,activeToolCalls:[],lastStatusHint:null},error:null,timestamps:{...s.timestamps,optimisticAt:r,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},activeReasons:Nt(s.activeReasons,"optimistic:retry")};return un(e,t.sessionId,a)}case"markForceSubscribe":{const s=Dn(e,t.sessionId);if(zm(s.phase))return e;const r={...s,phase:"running",confidence:"optimistic",generation:s.generation+1,error:null,activeReasons:Nt(s.activeReasons,"optimistic:openSession.forceSubscribe")};return un(e,t.sessionId,r)}case"markCancel":{const s=Dn(e,t.sessionId),r=n(),a={...s,phase:"cancelled",confidence:"terminal",timestamps:{...s.timestamps,settledAt:r},activeReasons:Nt(s.activeReasons,"user:cancel")};return un(e,t.sessionId,a)}case"markSettleTimeout":{const s=Dn(e,t.sessionId);if(s.phase!=="starting"&&s.phase!=="settling")return e;const r={...s,phase:"idle",confidence:"optimistic",timestamps:{...s.timestamps,settledAt:n()},activeReasons:Nt(s.activeReasons,"settle:timeout")};return un(e,t.sessionId,r)}case"applyAgentEvent":{const s=Dn(e,t.sessionId);if(t.generation!==s.generation)return e;const r=fp(s,t.event,n);return r===s?e:un(e,t.sessionId,r)}case"applyExecutionStarted":{const s=Dn(e,t.sessionId);if(t.generation!==s.generation)return e;if(s.phase!=="starting")return un(e,t.sessionId,{...s,backendRunId:t.runId,confidence:"live",activeReasons:Nt(s.activeReasons,"sse:execution_started")});const r={...s,phase:"running",confidence:"live",backendRunId:t.runId,timestamps:{...s.timestamps,confirmedAt:n()},activeReasons:Nt(s.activeReasons,"sse:execution_started")};return un(e,t.sessionId,r)}case"applySessionSummary":{const s=Dn(e,t.sessionId),r=f0(s,t.summary,n);return r===s?e:un(e,t.sessionId,r)}case"applyOneShotTerminal":{const s=Dn(e,t.sessionId);if(t.generation!==s.generation||s.phase!=="idle"&&s.phase!=="starting")return e;const r=n();return t.payload.status==="completed"?un(e,t.sessionId,{...s,phase:"completed",confidence:"terminal",timestamps:{...s.timestamps,terminalAt:r,settledAt:r},activeReasons:Nt(s.activeReasons,"sse:terminal_one_shot")}):un(e,t.sessionId,{...s,phase:"error",confidence:"terminal",timestamps:{...s.timestamps,terminalAt:r,settledAt:r},error:{message:t.payload.message??"Unknown error",source:"sse",occurredAt:r},activeReasons:Nt(s.activeReasons,"sse:terminal_one_shot")})}case"beginSettle":{const s=Dn(e,t.sessionId);if(t.generation!==s.generation||s.phase!=="running"&&s.phase!=="streaming"&&s.phase!=="running_tools"&&s.phase!=="running_children")return e;const r=n();return un(e,t.sessionId,{...s,phase:"settling",timestamps:{...s.timestamps,settlingStartedAt:r,terminalAt:s.timestamps.terminalAt??r}})}case"applyChildProgress":{const s=Dn(e,t.sessionId),a=!(t.childId in s.children.byId)?Ib(s,t.childId,t.patch):Eu(s,t.childId,t.patch);return a===s?e:un(e,t.sessionId,a)}case"clearChildProgress":{const s=Dn(e,t.sessionId),r=h0(s,t.childId);return r===s?e:un(e,t.sessionId,r)}case"setPendingQuestion":{const s=Dn(e,t.sessionId),r=n(),a={...s,phase:"waiting_user_answer",confidence:"live",interaction:{...s.interaction,pendingQuestion:{...t.payload,receivedAt:r},respondMode:{...t.payload,sessionId:t.sessionId}},activeReasons:Nt(s.activeReasons,"sse:need_clarification")};return un(e,t.sessionId,a)}case"clearPendingQuestion":{const s=Dn(e,t.sessionId);if(s.interaction.pendingQuestion===null&&s.interaction.respondMode===null)return e;const r={...s,interaction:{...s.interaction,pendingQuestion:null,respondMode:null}};return un(e,t.sessionId,r)}case"resetSession":return c0(e,t.sessionId);case"applyRunningSnapshot":{let s=e;for(const r of t.sessions){const a=Dn(s,r.sessionId),i=a.generation+1;let l={...a,generation:i,backendRunId:r.runId,phase:"running",confidence:"live",timestamps:{...a.timestamps,confirmedAt:n()},activeReasons:Nt(a.activeReasons,"sse:execution_started")};for(const c of r.criticalEvents)c.type!=="execution_started"&&(l=fp(l,c,n));s=un(s,r.sessionId,l)}return s}default:return e}},xn=()=>new Date().toISOString(),y0=(e,t)=>({executionBySession:{},ensureSession:n=>{e(s=>{const r=tn(s.executionBySession,{type:"ensureSession",sessionId:n},xn);return r===s.executionBySession?{}:{executionBySession:r}})},markOptimisticStart:n=>{e(s=>{const r=tn(s.executionBySession,{type:"markOptimisticStart",sessionId:n},xn);return r===s.executionBySession?{}:{executionBySession:r}})},markRespondStart:(n,s)=>{e(r=>{const a=tn(r.executionBySession,{type:"markRespondStart",sessionId:n},xn);return a===r.executionBySession?{}:{executionBySession:a}})},markRetryStart:n=>{e(s=>{const r=tn(s.executionBySession,{type:"markRetryStart",sessionId:n},xn);return r===s.executionBySession?{}:{executionBySession:r}})},markForceSubscribe:n=>{e(s=>{const r=tn(s.executionBySession,{type:"markForceSubscribe",sessionId:n},xn);return r===s.executionBySession?{}:{executionBySession:r}})},markCancel:n=>{e(s=>{const r=tn(s.executionBySession,{type:"markCancel",sessionId:n},xn);return r===s.executionBySession?{}:{executionBySession:r}})},markSettleTimeout:n=>{e(s=>{const r=tn(s.executionBySession,{type:"markSettleTimeout",sessionId:n},xn);return r===s.executionBySession?{}:{executionBySession:r}})},applyAgentEvent:(n,s,r)=>{e(a=>{const i=tn(a.executionBySession,{type:"applyAgentEvent",sessionId:n,event:s,generation:r},xn);return i===a.executionBySession?{}:{executionBySession:i}})},applyExecutionStarted:(n,s,r)=>{e(a=>{const i=tn(a.executionBySession,{type:"applyExecutionStarted",sessionId:n,runId:s,generation:r},xn);return i===a.executionBySession?{}:{executionBySession:i}})},applySessionSummary:(n,s)=>{e(r=>{const a=tn(r.executionBySession,{type:"applySessionSummary",sessionId:n,summary:s},xn);return a===r.executionBySession?{}:{executionBySession:a}})},applyOneShotTerminal:(n,s,r)=>{e(a=>{const i=tn(a.executionBySession,{type:"applyOneShotTerminal",sessionId:n,generation:s,payload:r},xn);return i===a.executionBySession?{}:{executionBySession:i}})},beginSettle:(n,s)=>{e(r=>{const a=tn(r.executionBySession,{type:"beginSettle",sessionId:n,generation:s},xn);return a===r.executionBySession?{}:{executionBySession:a}})},applyChildProgress:(n,s,r)=>{e(a=>{const i=tn(a.executionBySession,{type:"applyChildProgress",sessionId:n,childId:s,patch:r},xn);return i===a.executionBySession?{}:{executionBySession:i}})},clearChildProgress:(n,s)=>{e(r=>{const a=tn(r.executionBySession,{type:"clearChildProgress",sessionId:n,childId:s},xn);return a===r.executionBySession?{}:{executionBySession:a}})},setPendingQuestion:(n,s)=>{e(r=>{const a=tn(r.executionBySession,{type:"setPendingQuestion",sessionId:n,payload:s},xn);return a===r.executionBySession?{}:{executionBySession:a}})},clearPendingQuestion:n=>{e(s=>{const r=tn(s.executionBySession,{type:"clearPendingQuestion",sessionId:n},xn);return r===s.executionBySession?{}:{executionBySession:r}})},resetSession:n=>{e(s=>{const r=tn(s.executionBySession,{type:"resetSession",sessionId:n},xn);return r===s.executionBySession?{}:{executionBySession:r}})},applyRunningSnapshot:n=>{const s=t(),r=n.map(a=>{const i=[];for(const l of a.criticalEvents){if(Rb(l)){Pu(l,s);continue}i.push(l)}return{...a,criticalEvents:i}});e(a=>{const i=tn(a.executionBySession,{type:"applyRunningSnapshot",sessions:r},xn);return i===a.executionBySession?{}:{executionBySession:i}})}}),Bs=Jn.getInstance(),No=bc()[0],b0=(No==null?void 0:No.id)||"general_assistant";var ob;const Ob=((ob=No==null?void 0:No.content)==null?void 0:ob.trim())||"",Ed="tool",gp=e=>{if(typeof e!="string"||!e.trim())return null;const t=Date.parse(e);return Number.isFinite(t)?t:null},x0=()=>{try{const e=globalThis.crypto;if(e!=null&&e.randomUUID)return e.randomUUID()}catch{}return`id_${Date.now()}_${Math.random().toString(16).slice(2)}`},v0=()=>{let e=Yo().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`},$b=e=>{const t=e.trim();if(!t.startsWith("bamboo-attachment://"))return null;const n=t.slice(20),[s,r]=n.split("/",2);return!s||!r?null:{sessionId:s,attachmentId:r}},S0=e=>{const t=$b(e);return t?`${v0()}/sessions/${encodeURIComponent(t.sessionId)}/attachments/${encodeURIComponent(t.attachmentId)}`:e},Vr=e=>{if(typeof e!="string")return;const t=e.trim();if(t&&t.toLowerCase()!=="unknown")return t},w0=e=>{const t=(e||"").trim();if(!t)return;const n=t.match(/tool policy blocked ['"`]([^'"`]+)['"`]/i);if(n!=null&&n[1])return Vr(n[1]);try{const s=JSON.parse(t);if(typeof(s==null?void 0:s.tool_name)=="string")return Vr(s.tool_name)}catch{}},Ru=e=>{var s,r;const t=Number.isFinite(Date.parse(e.created_at))?Date.parse(e.created_at):Date.now(),n=e.token_usage?{systemTokens:e.token_usage.system_tokens,summaryTokens:e.token_usage.summary_tokens,windowTokens:e.token_usage.window_tokens,totalTokens:e.token_usage.total_tokens,budgetLimit:e.token_usage.budget_limit,...typeof e.token_usage.max_context_tokens=="number"&&e.token_usage.max_context_tokens>0?{maxContextTokens:e.token_usage.max_context_tokens}:{},...typeof e.token_usage.prompt_cached_tool_outputs=="number"&&e.token_usage.prompt_cached_tool_outputs>0?{promptCachedToolOutputs:e.token_usage.prompt_cached_tool_outputs}:{}}:void 0;return{id:e.id,kind:e.kind,parentSessionId:e.parent_session_id??null,rootSessionId:e.root_session_id,spawnDepth:e.spawn_depth,createdByScheduleId:e.created_by_schedule_id??null,isRunning:e.is_running,updatedAt:e.updated_at,lastActivityAt:e.last_activity_at,messageCount:e.message_count,hasAttachments:e.has_attachments,lastRunStatus:e.last_run_status,lastRunError:e.last_run_error,subagentType:e.subagent_type??null,title:e.title||Es.t("chat.session.defaultTitle"),titleVersion:e.title_version??0,createdAt:t,pinned:e.pinned,messages:[],config:{systemPromptId:b0,baseSystemPrompt:Ob,lastUsedEnhancedPrompt:null,model:e.model,model_ref:e.model_ref??null,reasoningEffort:e.reasoning_effort??null,tokenUsage:n,truncationOccurred:(s=e.token_usage)==null?void 0:s.truncation_occurred,segmentsRemoved:(r=e.token_usage)==null?void 0:r.segments_removed,compressionEvents:[]}}},_0=(e,t)=>{var a,i,l,c,u;const n=new Map,s=new Map;for(const m of t)m.role==="tool"&&m.tool_call_id&&m.metadata&&s.set(m.tool_call_id,m.metadata);const r=[];for(const m of t){const f=m.created_at||new Date().toISOString();if(m.role==="system"){const g={role:"system",id:m.id,createdAt:f,content:m.content||"",isCompressed:!!m.compressed,compressedEventId:m.compressed_by_event_id};r.push(g);continue}if(m.role==="user"){const g=new Map;for(const x of m.image_ocr||[]){const T=(a=x.image_url)==null?void 0:a.trim();if(!T)continue;const w=(x.lines||[]).map(M=>((M==null?void 0:M.text)||"").trim()).filter(Boolean);g.set(T,{ocrText:w.length?w.join(`
|
|
12
|
+
`):void 0,ocrError:x.error?String(x.error):void 0})}const b=[];for(const x of m.content_parts||[]){if(x.type!=="image_url")continue;const T=((i=x.image_url)==null?void 0:i.url)||"";if(!T)continue;const j=S0(T),w=$b(T),M=g.get(T.trim());b.push({id:x0(),url:j,ocrText:M==null?void 0:M.ocrText,ocrError:M==null?void 0:M.ocrError,name:w?`attachment-${w.attachmentId}`:"image",size:0,type:"image/*"})}const S={role:"user",id:m.id,createdAt:f,content:m.content||"",images:b.length?b:void 0,isCompressed:!!m.compressed,compressedEventId:m.compressed_by_event_id};r.push(S);continue}if(m.role==="assistant"){const g=m.tool_calls||[];if(g.length>0){const x=(m.content||"").trim(),T=typeof m.reasoning=="string"&&m.reasoning.trim().length>0;if(x||T){const _=T?{reasoning:m.reasoning,backendMessageId:m.id}:{backendMessageId:m.id},C={role:"assistant",type:"text",id:`${m.id}_text`,createdAt:f,content:m.content||"",metadata:_,isCompressed:!!m.compressed,compressedEventId:m.compressed_by_event_id};r.push(C)}for(const _ of g)_.id&&n.set(_.id,Vr((l=_.function)==null?void 0:l.name)||Ed);const j=(c=g[0])==null?void 0:c.id,w=j?s.get(j):void 0,M={role:"assistant",type:"tool_call",id:m.id,createdAt:f,toolCalls:g.map(_=>{var C;return{toolCallId:_.id,toolName:Vr((C=_.function)==null?void 0:C.name)||Ed,parameters:(()=>{var L,A;try{return JSON.parse(((L=_.function)==null?void 0:L.arguments)||"{}")}catch{return{raw:((A=_.function)==null?void 0:A.arguments)||""}}})(),streamingOutput:""}}),...w?{metadata:w}:{},isCompressed:!!m.compressed,compressedEventId:m.compressed_by_event_id};r.push(M);continue}const b=typeof m.reasoning=="string"&&m.reasoning.trim().length>0?{reasoning:m.reasoning}:{},S={role:"assistant",type:"text",id:m.id,createdAt:f,content:m.content||"",metadata:b,isCompressed:!!m.compressed,compressedEventId:m.compressed_by_event_id};r.push(S);continue}if(m.role==="tool"){const g=((u=m.tool_call_id)==null?void 0:u.trim())||`orphan-tool-call:${m.id}`,b=Vr(n.get(g))||Vr(m.tool_name)||Vr(m.name)||w0(m.content)||Ed,S=m.tool_success===!1||m.tool_success==null&&typeof m.content=="string"&&m.content.trimStart().startsWith("Error:"),x={role:"assistant",type:"tool_result",id:m.id,createdAt:f,toolName:b,toolCallId:g,result:{tool_name:b,result:m.content||"",display_preference:"Default"},isError:S,isCompressed:!!m.compressed,compressedEventId:m.compressed_by_event_id};r.push(x);continue}}return r},k0=750,Ot={inFlight:null,forcedPromise:null,timer:null,trailingPromise:null,trailingResolve:null,trailingReject:null};function Db(){const e={resolve:Ot.trailingResolve,reject:Ot.trailingReject};return Ot.trailingPromise=null,Ot.trailingResolve=null,Ot.trailingReject=null,e}function yp(e,t){!t.resolve&&!t.reject||e.then(()=>{var n;return(n=t.resolve)==null?void 0:n.call(t)},n=>{var s;return(s=t.reject)==null?void 0:s.call(t,n)})}function T0(){return Ot.timer&&(clearTimeout(Ot.timer),Ot.timer=null),Db()}function j0(e,t){const n=e.map(Ru);t(s=>{let r=s.executionBySession;for(const l of e)r=tn(r,{type:"applySessionSummary",sessionId:l.id,summary:l});const a=new Map(s.chats.map(l=>[l.id,l])),i=n.map(l=>{var C,L,A,B;const c=a.get(l.id);if(!c)return l;const u=gp(c.updatedAt),m=gp(l.updatedAt),f=u!==null&&m!==null&&u>m,g=c.config||{},b=l.config||{},S=Object.prototype.hasOwnProperty.call(g,"model"),x=Object.prototype.hasOwnProperty.call(g,"model_ref"),T=Object.prototype.hasOwnProperty.call(g,"reasoningEffort"),j=Math.max(c.messageCount??0,l.messageCount??0),w=l.titleVersion??0,M=c.titleVersion??0,_=w>M?{title:l.title,titleVersion:w}:{title:c.title,titleVersion:M};return{...l,pinned:f?c.pinned:l.pinned,updatedAt:f?c.updatedAt:l.updatedAt,messages:c.messages,messageCount:j,config:{...g,...b,model:f&&S?g.model:b.model,model_ref:f&&x?g.model_ref:b.model_ref,reasoningEffort:f&&T?g.reasoningEffort:b.reasoningEffort,compressionEvents:((C=c.config)==null?void 0:C.compressionEvents)??((L=l.config)==null?void 0:L.compressionEvents),syncCursor:((A=c.config)==null?void 0:A.syncCursor)??((B=l.config)==null?void 0:B.syncCursor)},..._}});return{...s,chats:i,executionBySession:r}})}async function Gl(e){return Ot.inFlight||(Ot.inFlight=(async()=>{try{const t=await Bs.listSessions();j0(t.sessions,e)}catch(t){throw console.error("[ChatSlice] Failed to refresh sessions:",t),t}})().finally(()=>{Ot.inFlight=null})),Ot.inFlight}function C0(e){return Ot.forcedPromise||(Ot.forcedPromise=(async()=>{Ot.inFlight&&await Ot.inFlight,await Gl(e)})().finally(()=>{Ot.forcedPromise=null})),Ot.forcedPromise}const M0=(e,t)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,addChat:async n=>{var g,b,S,x,T,j,w,M,_,C,L,A;const s=(n.title||Es.t("chat.sidebar.newSession")).trim(),r=((b=(g=n.config)==null?void 0:g.baseSystemPrompt)==null?void 0:b.trim())||"",a=(S=Mt.getState().getActiveModel())==null?void 0:S.trim(),i=((T=(x=n.config)==null?void 0:x.model)==null?void 0:T.trim())||a||void 0,l=((j=n.config)==null?void 0:j.reasoningEffort)??void 0;let c,u;if(Mt.getState().isProviderModelRefEnabled()){const B=(w=n.config)==null?void 0:w.model_ref;if((M=B==null?void 0:B.provider)!=null&&M.trim()&&((_=B==null?void 0:B.model)!=null&&_.trim()))c=B,u=B.provider;else{const N=(C=Mt.getState().providerConfig.defaults)==null?void 0:C.chat;if((L=N==null?void 0:N.provider)!=null&&L.trim()&&((A=N==null?void 0:N.model)!=null&&A.trim()))c=N,u=N.provider;else{const O=Mt.getState().getActiveModel();O&&(c={provider:Mt.getState().currentProvider,model:O},u=Mt.getState().currentProvider)}}}const m=await Bs.createSession({title:s,system_prompt:r||void 0,model:i,model_ref:c,provider:u,reasoning_effort:l||void 0}),f={...Ru(m.session),title:s,config:{...n.config,model:m.session.model,model_ref:m.session.model_ref??null,reasoningEffort:m.session.reasoning_effort??null,baseSystemPrompt:r||Ob},messages:[]};return e(B=>{const N=[f,...B.chats.filter(O=>O.id!==f.id)];return{...B,chats:N,currentSessionId:f.id,latestActiveSessionId:f.id}}),f.id},selectSession:n=>{const s=t();s.currentSessionId===n&&s.latestActiveSessionId===n||e({currentSessionId:n,latestActiveSessionId:n})},deleteSession:async n=>{try{await Bs.deleteSession(n)}catch(s){console.error(`[ChatSlice] Failed to delete backend session ${n}:`,s)}e(s=>{var c;const r=new Set;for(const u of s.chats)u.id===n&&r.add(u.id),u.rootSessionId===n&&r.add(u.id);const a=s.chats.filter(u=>!r.has(u.id)),i=s.currentSessionId&&r.has(s.currentSessionId)?null:s.currentSessionId,l=s.latestActiveSessionId&&r.has(s.latestActiveSessionId)?((c=a[0])==null?void 0:c.id)??null:s.latestActiveSessionId;return{...s,chats:a,currentSessionId:i,latestActiveSessionId:l}})},deleteSessions:async n=>{for(const s of n)await t().deleteSession(s)},updateSession:(n,s)=>{const r=!!s.config&&(Object.prototype.hasOwnProperty.call(s.config,"model")||Object.prototype.hasOwnProperty.call(s.config,"reasoningEffort")),a=typeof s.title=="string"||typeof s.pinned=="boolean",l=r||a?new Date().toISOString():void 0;e(u=>{const m=u.chats.map(f=>f.id===n?{...f,...s,...l?{updatedAt:l}:{}}:f);return{...u,chats:m}});const c={};if(typeof s.title=="string"&&(c.title=s.title),typeof s.pinned=="boolean"&&(c.pinned=s.pinned),s.config&&Object.prototype.hasOwnProperty.call(s.config,"model")&&(c.model=s.config.model??null),s.config&&Object.prototype.hasOwnProperty.call(s.config,"model_ref")&&Mt.getState().isProviderModelRefEnabled()&&(c.model_ref=s.config.model_ref??null,s.config.model_ref&&(c.provider=s.config.model_ref.provider)),s.config&&Object.prototype.hasOwnProperty.call(s.config,"reasoningEffort")){const u=s.config.reasoningEffort;u?c.reasoning_effort=u:c.clear_reasoning_effort=!0}Object.keys(c).length>0&&Bs.patchSession(n,c).catch(u=>{console.warn(`[ChatSlice] Failed to patch session ${n}:`,u)})},persistSessionTitle:async(n,s)=>{var a;const r=(a=t().chats.find(i=>i.id===n))==null?void 0:a.title;e(i=>({...i,chats:i.chats.map(l=>l.id===n?{...l,title:s,updatedAt:new Date().toISOString()}:l)}));try{await Bs.patchSession(n,{title:s})}catch(i){throw typeof r=="string"&&e(l=>({...l,chats:l.chats.map(c=>c.id===n?{...c,title:r}:c)})),console.warn(`[ChatSlice] persistSessionTitle failed for ${n}:`,i),i}},applyServerTitle:(n,s,r)=>e(a=>{const i=a.chats.find(l=>l.id===n);return!i||r<=(i.titleVersion??0)?a:{...a,chats:a.chats.map(l=>l.id===n?{...l,title:s,titleVersion:r,updatedAt:new Date().toISOString()}:l)}}),applyServerPinned:(n,s,r)=>e(a=>{const i=a.chats.find(u=>u.id===n);if(!i)return a;const l=Date.parse(r),c=i.updatedAt?Date.parse(i.updatedAt):NaN;return Number.isFinite(l)&&Number.isFinite(c)&&l<c||i.pinned===s?a:{...a,chats:a.chats.map(u=>u.id===n?{...u,pinned:s,updatedAt:r}:u)}}),pinSession:n=>{t().updateSession(n,{pinned:!0})},unpinSession:n=>{t().updateSession(n,{pinned:!1})},setMessages:(n,s)=>{t().chats.find(a=>a.id===n)&&t().updateSession(n,{messages:s})},addMessage:async(n,s)=>{const r=t().chats.find(i=>i.id===n);if(!r)return;const a=[...r.messages,s];t().updateSession(n,{messages:a})},updateMessage:(n,s,r)=>{const a=t().chats.find(l=>l.id===n);if(!a)return;const i=a.messages.map(l=>{if(l.id!==s)return l;const c={...l};return Object.keys(r).forEach(u=>{Object.prototype.hasOwnProperty.call(c,u)&&(c[u]=r[u])}),c});t().updateSession(n,{messages:i})},deleteMessage:async(n,s)=>{const r=t().chats.find(a=>a.id===n);if(!r)return{success:!1,sessionId:n,messageId:s,reason:"session_not_found"};if(!r.messages.some(a=>a.id===s))return{success:!1,sessionId:n,messageId:s,reason:"message_not_found"};try{await Bs.deleteSessionMessage(n,s)}catch(a){return console.warn(`[ChatSlice] Failed to delete message ${s} from session ${n}:`,a),a instanceof uo?a.status===404?{success:!1,sessionId:n,messageId:s,reason:"backend_not_found",statusCode:a.status,errorMessage:a.message}:a.status===409?{success:!1,sessionId:n,messageId:s,reason:"session_running",statusCode:a.status,errorMessage:a.message}:{success:!1,sessionId:n,messageId:s,reason:"backend_error",statusCode:a.status,errorMessage:a.message}:{success:!1,sessionId:n,messageId:s,reason:"backend_error",errorMessage:a instanceof Error?a.message:void 0}}return e(a=>({...a,chats:a.chats.map(i=>i.id===n?{...i,messages:i.messages.filter(l=>l.id!==s)}:i)})),{success:!0,sessionId:n,messageId:s}},refreshChats:async()=>Ot.inFlight?Ot.inFlight:Ot.timer?(Ot.trailingPromise||(Ot.trailingPromise=new Promise((n,s)=>{Ot.trailingResolve=n,Ot.trailingReject=s})),Ot.trailingPromise):(Ot.timer=setTimeout(()=>{if(Ot.timer=null,Ot.trailingPromise){const n=Db();yp(Gl(e),n)}},k0),Gl(e)),refreshChatsNow:async()=>{const n=T0(),s=Ot.inFlight?C0(e):Gl(e);return yp(s,n),s},loadChats:async()=>{var i,l,c;let n=await Bs.listSessions();if(!n.sessions||n.sessions.length===0){const u=(i=Mt.getState().getActiveModel())==null?void 0:i.trim(),m=(l=Mt.getState().providerConfig.defaults)==null?void 0:l.chat;n={sessions:[(await Bs.createSession({title:Es.t("chat.sidebar.newSession"),model:u,model_ref:m,provider:m==null?void 0:m.provider})).session]}}const s=n.sessions.map(Ru),r=((c=s[0])==null?void 0:c.id)??null;let a=t().executionBySession;for(const u of n.sessions)a=tn(a,{type:"applySessionSummary",sessionId:u.id,summary:u});try{const u=await Bs.getRunningSessions();if(u.sessions.length>0){const m=u.sessions.map(f=>{const g=[];for(const b of f.last_critical_events){if(Rb(b)){s0(b,s);continue}g.push(b)}return{sessionId:f.session_id,runId:f.run_id,criticalEvents:g}});a=tn(a,{type:"applyRunningSnapshot",sessions:m},()=>new Date().toISOString())}}catch{}e({chats:s,latestActiveSessionId:r,currentSessionId:r,executionBySession:a}),r&&await t().loadChatHistory(r)},loadChatHistory:async(n,s)=>{var l,c,u,m,f,g,b,S,x,T,j,w,M;const r=(s==null?void 0:s.mode)??"replace",a=Math.max(0,(s==null?void 0:s.retries)??0),i=Math.max(0,(s==null?void 0:s.retryDelayMs)??0);for(let _=0;_<=a;_+=1)try{const C=t().chats.find(N=>N.id===n);if(!C)return;const L=await Bs.getHistory(n),A=(l=L.messages[L.messages.length-1])==null?void 0:l.role;if(s!=null&&s.waitForAssistant&&A==="user"&&_<a){const N=i>0?i*(_+1):200*(_+1);await new Promise(O=>setTimeout(O,N));continue}const B=_0(n,L.messages);if(r==="monotonic"){const N=C.messages||[],O=N.length,R=B.length,I=(c=B[B.length-1])==null?void 0:c.role,$=(u=N[N.length-1])==null?void 0:u.role,U=N[N.length-1],q=B[B.length-1],K=U==null?void 0:U.id,P=q==null?void 0:q.id;let W=!1;if(R>O?W=!0:R===O&&(W=$==="user"&&I!=="user"||typeof K=="string"&&typeof P=="string"&&K!==P),!W){t().updateSession(n,{messageCount:Math.max(C.messageCount??0,L.messages.length)});return}}t().updateSession(n,{messages:B,messageCount:L.messages.length,config:{...C.config||{},compressionEvents:(L.compression_events||[]).map(N=>({id:N.id,createdAt:N.created_at,messagesCompressed:N.messages_compressed,segmentsRemoved:N.segments_removed})),syncCursor:{messageCount:L.messages.length,lastMessageId:((m=L.messages[L.messages.length-1])==null?void 0:m.id)??null,hasPendingQuestion:((b=(g=(f=t().executionBySession)==null?void 0:f[n])==null?void 0:g.interaction.respondMode)==null?void 0:b.sessionId)===n,pendingQuestionToolCallId:((T=(x=(S=t().executionBySession)==null?void 0:S[n])==null?void 0:x.interaction.respondMode)==null?void 0:T.sessionId)===n?((M=(w=(j=t().executionBySession)==null?void 0:j[n])==null?void 0:w.interaction.respondMode)==null?void 0:M.toolCallId)??null:null}}});return}catch(C){if(_>=a){console.warn(`[ChatSlice] Failed to load history for ${n}:`,C);return}const L=i>0?i*(_+1):200*(_+1);await new Promise(A=>setTimeout(A,L))}}});class Au extends Error{constructor(n="Proxy authentication required"){super(n);Ct(this,"code","proxy_auth_required");this.name="ProxyAuthRequiredError"}}const Jr=class Jr{constructor(){}static getInstance(){return Jr.instance||(Jr.instance=new Jr),Jr.instance}resolveOpenAICompatBaseUrl(){const t=Yo().trim().replace(/\/+$/,"");return t.endsWith("/openai/v1")?t:`${t.endsWith("/v1")?t.slice(0,-3):t}/openai/v1`}async getModels(){var t,n;try{return(await new Nm({baseUrl:this.resolveOpenAICompatBaseUrl()}).get("models")).data.map(a=>a.id)}catch(s){if(console.error("Failed to fetch models from HTTP API:",s),s instanceof uo){if(s.status===428)throw new Au(s.message);let r;if(s.body)try{r=JSON.parse(s.body)}catch{}if(r&&typeof r=="object"&&"error"in r&&((t=r.error)==null?void 0:t.code)==="proxy_auth_required")throw new Au(((n=r.error)==null?void 0:n.message)||s.message)}throw s}}};Ct(Jr,"instance");let Iu=Jr;const Lb=Iu.getInstance(),P0=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)},E0=e=>{if(typeof document>"u")throw new Error("document is unavailable");const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","true"),t.style.position="fixed",t.style.top="-9999px",t.style.left="-9999px",t.style.opacity="0",document.body.appendChild(t),t.focus(),t.select();const n=document.execCommand("copy");if(document.body.removeChild(t),!n)throw new Error("document.execCommand('copy') returned false")},vs=async e=>{try{await P0(e);return}catch(t){try{E0(e);return}catch(n){const s=t instanceof Error?t.message:String(t),r=n instanceof Error?n.message:String(n);throw new Error(`Clipboard copy failed: navigator(${s}); fallback(${r})`)}}};class R0{async copyToClipboard(t){await vs(t)}async getBambooConfig(){try{return await rt.get("bamboo/config")}catch(t){return console.error("Failed to fetch Bamboo config:",t),{}}}async getBambooTools(){try{return await rt.get("bamboo/tools")}catch(t){return console.error("Failed to fetch Bamboo tools:",t),{tools:[]}}}async getModelLimitDefaults(){try{return await rt.get("bamboo/model-limits/defaults")}catch(t){return console.error("Failed to fetch model limit defaults:",t),{model_limits:[]}}}async setBambooConfig(t){return rt.post("bamboo/config",t)}async validateBambooConfigPatch(t){return rt.post("bamboo/config/validate",t)}async setProxyAuth(t){return rt.post("bamboo/proxy-auth",t)}async getProxyAuthStatus(){try{return await rt.get("bamboo/proxy-auth/status")}catch(t){return console.error("Failed to fetch proxy auth status:",t),{configured:!1,username:null}}}async clearProxyAuth(){return rt.post("bamboo/proxy-auth",{username:"",password:""})}async resetBambooConfig(){return rt.post("bamboo/config/reset",{})}async saveWorkflow(t,n){return rt.post("bamboo/workflows",{name:t,content:n})}async deleteWorkflow(t){return rt.delete(`bamboo/workflows/${encodeURIComponent(t)}`)}async getKeywordMaskingConfig(){try{return await rt.get("bamboo/keyword-masking")}catch(t){return console.error("Failed to fetch keyword masking config:",t),{entries:[]}}}async updateKeywordMaskingConfig(t){return rt.post("bamboo/keyword-masking",t)}async validateKeywordEntries(t){return rt.post("bamboo/keyword-masking/validate",t)}async getSetupStatus(){return await rt.get("bamboo/setup/status")}async markSetupComplete(){return rt.post("bamboo/setup/complete",{})}async resetSetupStatus(){await rt.post("bamboo/setup/incomplete",{})}async getAccessStatus(){return rt.get("bamboo/access/status")}async verifyAccessPassword(t){return rt.post("bamboo/access/verify",{password:t})}async updateAccessPassword(t){return rt.post("bamboo/access/password",t)}}const Qr=class Qr{constructor(){Ct(this,"httpUtilityService",new R0)}static getInstance(){return Qr.instance||(Qr.instance=new Qr),Qr.instance}getUtilityService(){return{copyToClipboard:t=>this.httpUtilityService.copyToClipboard(t),getBambooConfig:()=>this.httpUtilityService.getBambooConfig(),getBambooTools:()=>this.httpUtilityService.getBambooTools(),getModelLimitDefaults:()=>this.httpUtilityService.getModelLimitDefaults(),setBambooConfig:t=>this.httpUtilityService.setBambooConfig(t),validateBambooConfigPatch:t=>this.httpUtilityService.validateBambooConfigPatch(t),setProxyAuth:t=>this.httpUtilityService.setProxyAuth(t),getProxyAuthStatus:()=>this.httpUtilityService.getProxyAuthStatus(),clearProxyAuth:()=>this.httpUtilityService.clearProxyAuth(),resetBambooConfig:()=>this.httpUtilityService.resetBambooConfig(),resetSetupStatus:()=>this.httpUtilityService.resetSetupStatus(),saveWorkflow:(t,n)=>this.httpUtilityService.saveWorkflow(t,n),deleteWorkflow:t=>this.httpUtilityService.deleteWorkflow(t),getKeywordMaskingConfig:()=>this.httpUtilityService.getKeywordMaskingConfig(),updateKeywordMaskingConfig:t=>this.httpUtilityService.updateKeywordMaskingConfig(t),validateKeywordEntries:t=>this.httpUtilityService.validateKeywordEntries(t),getSetupStatus:()=>this.httpUtilityService.getSetupStatus(),markSetupComplete:()=>this.httpUtilityService.markSetupComplete(),getAccessStatus:()=>this.httpUtilityService.getAccessStatus(),verifyAccessPassword:t=>this.httpUtilityService.verifyAccessPassword(t),updateAccessPassword:t=>this.httpUtilityService.updateAccessPassword(t)}}async copyToClipboard(t){return this.getUtilityService().copyToClipboard(t)}async getBambooConfig(){return this.getUtilityService().getBambooConfig()}async getBambooTools(){return this.getUtilityService().getBambooTools()}async getModelLimitDefaults(){return this.getUtilityService().getModelLimitDefaults()}async setBambooConfig(t){return this.getUtilityService().setBambooConfig(t)}async validateBambooConfigPatch(t){return this.getUtilityService().validateBambooConfigPatch(t)}async setProxyAuth(t){return this.getUtilityService().setProxyAuth(t)}async getProxyAuthStatus(){return this.getUtilityService().getProxyAuthStatus()}async clearProxyAuth(){return this.getUtilityService().clearProxyAuth()}async resetBambooConfig(){return this.getUtilityService().resetBambooConfig()}async resetSetupStatus(){return this.getUtilityService().resetSetupStatus()}async saveWorkflow(t,n){return this.getUtilityService().saveWorkflow(t,n)}async deleteWorkflow(t){return this.getUtilityService().deleteWorkflow(t)}async getKeywordMaskingConfig(){return this.getUtilityService().getKeywordMaskingConfig()}async updateKeywordMaskingConfig(t){return this.getUtilityService().updateKeywordMaskingConfig(t)}async validateKeywordEntries(t){return this.getUtilityService().validateKeywordEntries(t)}async getSetupStatus(){return this.getUtilityService().getSetupStatus()}async markSetupComplete(){return this.getUtilityService().markSetupComplete()}async getAccessStatus(){return this.getUtilityService().getAccessStatus()}async verifyAccessPassword(t){return this.getUtilityService().verifyAccessPassword(t)}async updateAccessPassword(t){return this.getUtilityService().updateAccessPassword(t)}};Ct(Qr,"instance");let Is=Qr;const Yt=Is.getInstance();let ua=null,ma=null;const Rd=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,Ms=Pr((e,t)=>({config:null,proxyAuthStatus:null,isLoadingConfig:!1,isLoadingProxyAuthStatus:!1,lastLoadedAt:null,error:null,loadConfig:async({force:n=!1}={})=>{const s=t().config;if(!n&&s)return s;if(ua)return ua;ua=(async()=>{e({isLoadingConfig:!0,error:null});try{const r=await Yt.getBambooConfig()??{};return e({config:r,lastLoadedAt:Date.now(),error:null}),r}catch(r){const a=Rd(r,"Failed to load Bamboo config");throw e({error:a}),r}finally{e({isLoadingConfig:!1})}})();try{return await ua}finally{ua=null}},saveConfig:async n=>{e({isLoadingConfig:!0,error:null,config:n});try{const s=await Yt.setBambooConfig(n);return e({config:s,lastLoadedAt:Date.now(),error:null}),s}catch(s){const r=Rd(s,"Failed to save Bamboo config");throw e({error:r}),s}finally{e({isLoadingConfig:!1})}},patchConfig:async n=>{const r={...await t().loadConfig()??{},...n??{}};return t().saveConfig(r)},loadProxyAuthStatus:async({force:n=!1}={})=>{const s=t().proxyAuthStatus;if(!n&&s)return s;if(ma)return ma;ma=(async()=>{e({isLoadingProxyAuthStatus:!0,error:null});try{const r=await Yt.getProxyAuthStatus();return e({proxyAuthStatus:r,error:null}),r}catch(r){const a=Rd(r,"Failed to load proxy auth status");throw e({error:a}),r}finally{e({isLoadingProxyAuthStatus:!1})}})();try{return await ma}finally{ma=null}},applyProxyAuth:async n=>{await Yt.setProxyAuth(n),await t().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await Yt.clearProxyAuth(),await t().loadProxyAuthStatus({force:!0})}}));let ha=null;const A0=(e,t)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:n=>{e({selectedModel:n})},loadConfigModel:async()=>{try{const n=await Ms.getState().loadConfig(),s=typeof(n==null?void 0:n.model)=="string"?n.model:void 0;s&&e({configModel:s})}catch(n){console.error("Failed to load model from config:",n)}},fetchModels:async()=>{if(ha)return ha;ha=(async()=>{e({isLoadingModels:!0,modelsError:null});try{try{if(!(await Yt.getSetupStatus()).is_complete){Jt("[ModelSlice]","Setup not complete, skipping model fetch"),e({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:"Complete setup to access all models"});return}}catch(s){console.error("Failed to check setup status:",s)}const n=await Lb.getModels();e(s=>{const r=s.selectedModel;let a=s.selectedModel;return r&&n.includes(r)||(n.length>0?a=n[0]:a=void 0),{...s,models:n,selectedModel:a,modelsError:n.length>0?null:"No available model options"}}),t().models.length===0&&console.warn("No models available from service")}catch(n){const s=n instanceof Error?n.message:String(n);if(console.error("Failed to fetch models:",n),n instanceof Au){e(r=>({...r,models:r.models,selectedModel:r.selectedModel,modelsError:s||"Proxy authentication required. Please configure proxy auth."}));return}e(r=>({...r,models:[],selectedModel:r.selectedModel,modelsError:s}))}finally{e({isLoadingModels:!1})}})();try{await ha}finally{ha=null}}}),I0=["system_prompt","system_prompt_selected_id"],Ad=e=>({id:e.id,name:e.name||e.id,content:e.content||"",description:e.description,isDefault:!!e.is_default}),wr=class wr{constructor(){Ct(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return wr.instance||(wr.instance=new wr),wr.instance.cleanupDeprecatedPromptStorageKeys(),wr.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const t of I0)localStorage.removeItem(t)}catch(t){console.warn("[SystemPromptService] Failed to cleanup deprecated prompt storage keys:",t)}}}async getSystemPromptPresets(){try{const t=await Ze.get("prompt-presets"),s=(Array.isArray(t==null?void 0:t.prompts)?t.prompts:[]).filter(r=>r.id&&r.id.trim().length>0).map(Ad);if(s.length>0)return s}catch(t){console.error("Failed to load prompt presets from backend:",t)}return bc()}async createSystemPromptPreset(t){var r;const n={name:t.name,content:t.content};(r=t.id)!=null&&r.trim()&&(n.id=t.id.trim()),t.description!==void 0&&(n.description=t.description);const s=await Ze.post("prompt-presets",n);if(!(s!=null&&s.prompt))throw new Error("Backend did not return created prompt preset");return Ad(s.prompt)}async updateSystemPromptPreset(t){const n=encodeURIComponent(t.id),s={name:t.name,content:t.content,description:t.description},r=await Ze.patch(`prompt-presets/${n}`,s);if(!(r!=null&&r.prompt))throw new Error("Backend did not return updated prompt preset");return Ad(r.prompt)}async deleteSystemPromptPreset(t){const n=encodeURIComponent(t);await Ze.delete(`prompt-presets/${n}`)}async findPresetById(t){return(await this.getSystemPromptPresets()).find(s=>s.id===t)}async getCurrentSystemPromptContent(t){const n=await this.findPresetById(t);if(n)return n.content;const s=await this.getSystemPromptPresets(),r=s.find(a=>a.isDefault)||s[0];return(r==null?void 0:r.content)||""}};Ct(wr,"instance");let xc=wr;const bp="copilot_last_selected_prompt_id",Fb="copilot_custom_system_prompts_v2",Nb="copilot_custom_system_prompts_v2_migrated_to_backend",zb="general_assistant",Bm=80,$o=xc.getInstance();let jl=null;function Wm(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,Bm)}function Bb(e){if(typeof e!="string")return null;const t=e.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return t?t.slice(0,Bm):null}function Wb(e,t){if(!t.has(e))return e;let n=2;for(;;){const s=`_${n}`,a=`${e.slice(0,Math.max(0,Bm-s.length))}${s}`;if(!t.has(a))return a;n+=1}}function qb(){try{const e=localStorage.getItem(Fb);if(!e)return[];const t=JSON.parse(e);if(!Array.isArray(t))return[];const n=new Set,s=[];for(const r of t){const a=typeof(r==null?void 0:r.name)=="string"?r.name.trim():"",i=typeof(r==null?void 0:r.content)=="string"?r.content.trim():"";if(!a||!i)continue;const c=Bb(r==null?void 0:r.id)||Wm(a),u=Wb(c,n);u!==zb&&(n.add(u),s.push({id:u,name:a,content:i,description:typeof(r==null?void 0:r.description)=="string"&&r.description.trim()||void 0,isDefault:!!(r!=null&&r.isDefault)}))}return s}catch(e){return console.error("[promptSlice] Failed to read legacy custom prompts:",e),[]}}function Ub(){try{return localStorage.getItem(Nb)==="1"}catch(e){return console.error("[promptSlice] Failed to read migration marker:",e),!1}}function xp(){try{localStorage.setItem(Nb,"1")}catch(e){console.error("[promptSlice] Failed to write migration marker:",e)}}function vp(){try{localStorage.removeItem(Fb)}catch(e){console.error("[promptSlice] Failed to clear legacy custom prompts:",e)}}async function O0(){var r,a;if(Ub())return;const e=qb();if(e.length===0){vp(),xp();return}const t=await $o.getSystemPromptPresets(),n=new Set(t.map(i=>i.id));let s=!1;for(const i of e){const l=(r=i.name)==null?void 0:r.trim(),c=(a=i.content)==null?void 0:a.trim();if(!l||!c||i.id===zb||i.isDefault)continue;const u=Bb(i.id)||Wm(l),m=Wb(u,n);try{const f=await $o.createSystemPromptPreset({id:m,name:l,content:c,description:i.description});n.add(f.id)}catch(f){s=!0,console.error(`[promptSlice] Failed to migrate legacy prompt '${l}' to backend:`,f)}}s||(vp(),xp())}async function $0(){jl||(jl=O0().finally(()=>{jl=null})),await jl}const D0=(e,t)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(bp)||null,loadSystemPrompts:async()=>{try{await $0()}catch(r){console.warn("[promptSlice] Legacy prompt migration skipped:",r)}let n=[];try{n=await $o.getSystemPromptPresets()}catch(r){console.error("Failed to load system prompts from backend:",r)}let s=n.length?n:bc();if(!Ub()){const r=qb();s=L0(s,r)}s.length===0&&(s=bc()),e({systemPrompts:s})},addSystemPrompt:async n=>{try{await $o.createSystemPromptPreset({id:Wm(n.name),name:n.name,content:n.content,description:n.description}),await t().loadSystemPrompts()}catch(s){throw console.error("Failed to add system prompt:",s),s}},updateSystemPrompt:async n=>{try{await $o.updateSystemPromptPreset(n),await t().loadSystemPrompts()}catch(s){throw console.error("Failed to update system prompt:",s),s}},deleteSystemPrompt:async n=>{try{await $o.deleteSystemPromptPreset(n),await t().loadSystemPrompts()}catch(s){throw console.error("Failed to delete system prompt:",s),s}},setLastSelectedPromptId:n=>{e({lastSelectedPromptId:n});try{localStorage.setItem(bp,n)}catch(s){console.error("Failed to save last selected prompt ID to localStorage:",s)}}}),L0=(e,t)=>{const n=new Map;return e.forEach(s=>{n.set(s.id,s)}),t.forEach(s=>{n.set(s.id,s)}),Array.from(n.values())},F0=()=>({});class N0{async listSkills(t,n){const s=new URLSearchParams;t!=null&&t.search&&s.append("search",t.search),t!=null&&t.includeDisabled&&s.append("include_disabled","true"),n&&s.append("refresh","true");const r=s.toString(),a=r?`skills?${r}`:"skills";return rt.get(a)}async getSkill(t){return rt.get(`skills/${t}`)}async getFilteredTools(t){const n=t?`?session_id=${encodeURIComponent(t)}`:"";return(await rt.get(`skills/filtered-tools${n}`)).tools??[]}}const Ou=new N0,z0=(e,t)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(n,s)=>{e({isLoadingSkills:!0,skillsError:null});try{const r=await Ou.listSkills(n,s);e({skills:r.skills,isLoadingSkills:!1})}catch(r){e({skillsError:r instanceof Error?r.message:Es.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async n=>{e({isLoadingSkills:!0,skillsError:null});try{const s=await Ou.getSkill(n),r=t().skills,i=r.findIndex(l=>l.id===s.id)>=0?r.map(l=>l.id===s.id?s:l):[...r,s];e({skills:i,isLoadingSkills:!1})}catch(s){e({skillsError:s instanceof Error?s.message:Es.t("components.skillManager.getFailed"),isLoadingSkills:!1})}},clearSkillsError:()=>{e({skillsError:null})}}),B0=e=>({tokenUsages:{},truncationOccurred:{},segmentsRemoved:{},updateTokenUsage:(t,n)=>e(s=>({tokenUsages:{...s.tokenUsages,[t]:n}})),setTruncationInfo:(t,n,s)=>e(r=>({truncationOccurred:{...r.truncationOccurred,[t]:n},segmentsRemoved:{...r.segmentsRemoved,[t]:s}})),clearTokenUsage:t=>e(n=>{const{[t]:s,...r}=n.tokenUsages,{[t]:a,...i}=n.truncationOccurred,{[t]:l,...c}=n.segmentsRemoved;return{tokenUsages:r,truncationOccurred:i,segmentsRemoved:c}})}),W0=Jn.getInstance(),q0=(e,t)=>({taskLists:{},taskListVersions:{},activeItems:{},evaluationStates:{},setTaskList:(n,s)=>e(r=>({taskLists:{...r.taskLists,[n]:s},taskListVersions:{...r.taskListVersions,[n]:s.version||0}})),loadTaskList:async n=>{const s=await W0.getTaskList(n);return s?(t().setTaskList(s.session_id||n,s),s):null},updateTaskListDelta:(n,s)=>e(r=>{const a=r.taskListVersions[n]||0;if(s.version<=a)return r;const i=r.taskLists[n];if(!i)return r;const l=i.items.map(c=>c.id===s.item_id?{...c,status:s.status,tool_calls_count:s.tool_calls_count}:c);return{taskLists:{...r.taskLists,[n]:{...i,items:l,updated_at:new Date().toISOString()}},taskListVersions:{...r.taskListVersions,[n]:s.version},activeItems:{...r.activeItems,[n]:s.status==="in_progress"?s.item_id:null}}}),clearTaskList:n=>e(s=>{const{[n]:r,...a}=s.taskLists,{[n]:i,...l}=s.taskListVersions,{[n]:c,...u}=s.activeItems,{[n]:m,...f}=s.evaluationStates;return{taskLists:a,taskListVersions:l,activeItems:u,evaluationStates:f}}),getTaskListVersion:n=>t().taskListVersions[n]||0,setEvaluationState:(n,s)=>e(r=>({evaluationStates:{...r.evaluationStates,[n]:s}})),clearEvaluationState:n=>e(s=>{const{[n]:r,...a}=s.evaluationStates;return{evaluationStates:a}})});var Jl={exports:{}},U0=Jl.exports,Sp;function H0(){return Sp||(Sp=1,function(e,t){((n,s)=>{e.exports=s()})(U0,function(){var n=function(d,h){return(n=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(y,v){y.__proto__=v}:function(y,v){for(var k in v)Object.prototype.hasOwnProperty.call(v,k)&&(y[k]=v[k])}))(d,h)},s=function(){return(s=Object.assign||function(d){for(var h,y=1,v=arguments.length;y<v;y++)for(var k in h=arguments[y])Object.prototype.hasOwnProperty.call(h,k)&&(d[k]=h[k]);return d}).apply(this,arguments)};function r(d,h,y){for(var v,k=0,E=h.length;k<E;k++)!v&&k in h||((v=v||Array.prototype.slice.call(h,0,k))[k]=h[k]);return d.concat(v||Array.prototype.slice.call(h))}var a=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:Ew,i=Object.keys,l=Array.isArray;function c(d,h){return typeof h=="object"&&i(h).forEach(function(y){d[y]=h[y]}),d}typeof Promise>"u"||a.Promise||(a.Promise=Promise);var u=Object.getPrototypeOf,m={}.hasOwnProperty;function f(d,h){return m.call(d,h)}function g(d,h){typeof h=="function"&&(h=h(u(d))),(typeof Reflect>"u"?i:Reflect.ownKeys)(h).forEach(function(y){S(d,y,h[y])})}var b=Object.defineProperty;function S(d,h,y,v){b(d,h,c(y&&f(y,"get")&&typeof y.get=="function"?{get:y.get,set:y.set,configurable:!0}:{value:y,configurable:!0,writable:!0},v))}function x(d){return{from:function(h){return d.prototype=Object.create(h.prototype),S(d.prototype,"constructor",d),{extend:g.bind(null,d.prototype)}}}}var T=Object.getOwnPropertyDescriptor,j=[].slice;function w(d,h,y){return j.call(d,h,y)}function M(d,h){return h(d)}function _(d){if(!d)throw new Error("Assertion Failed")}function C(d){a.setImmediate?setImmediate(d):setTimeout(d,0)}function L(d,h){if(typeof h=="string"&&f(d,h))return d[h];if(!h)return d;if(typeof h!="string"){for(var y=[],v=0,k=h.length;v<k;++v){var E=L(d,h[v]);y.push(E)}return y}var D,z=h.indexOf(".");return z===-1||(D=d[h.substr(0,z)])==null?void 0:L(D,h.substr(z+1))}function A(d,h,y){if(d&&h!==void 0&&!("isFrozen"in Object&&Object.isFrozen(d)))if(typeof h!="string"&&"length"in h){_(typeof y!="string"&&"length"in y);for(var v=0,k=h.length;v<k;++v)A(d,h[v],y[v])}else{var E,D,z=h.indexOf(".");z!==-1?(E=h.substr(0,z),(z=h.substr(z+1))===""?y===void 0?l(d)&&!isNaN(parseInt(E))?d.splice(E,1):delete d[E]:d[E]=y:A(D=(D=d[E])&&f(d,E)?D:d[E]={},z,y)):y===void 0?l(d)&&!isNaN(parseInt(h))?d.splice(h,1):delete d[h]:d[h]=y}}function B(d){var h,y={};for(h in d)f(d,h)&&(y[h]=d[h]);return y}var N=[].concat;function O(d){return N.apply([],d)}var re="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(O([8,16,32,64].map(function(d){return["Int","Uint","Float"].map(function(h){return h+d+"Array"})}))).filter(function(d){return a[d]}),R=new Set(re.map(function(d){return a[d]})),I=null;function $(d){return I=new WeakMap,d=function h(y){if(!y||typeof y!="object")return y;var v=I.get(y);if(v)return v;if(l(y)){v=[],I.set(y,v);for(var k=0,E=y.length;k<E;++k)v.push(h(y[k]))}else if(R.has(y.constructor))v=y;else{var D,z=u(y);for(D in v=z===Object.prototype?{}:Object.create(z),I.set(y,v),y)f(y,D)&&(v[D]=h(y[D]))}return v}(d),I=null,d}var U={}.toString;function q(d){return U.call(d).slice(8,-1)}var K=typeof Symbol<"u"?Symbol.iterator:"@@iterator",P=typeof K=="symbol"?function(d){var h;return d!=null&&(h=d[K])&&h.apply(d)}:function(){return null};function W(d,h){h=d.indexOf(h),0<=h&&d.splice(h,1)}var se={};function V(d){var h,y,v,k;if(arguments.length===1){if(l(d))return d.slice();if(this===se&&typeof d=="string")return[d];if(k=P(d))for(y=[];!(v=k.next()).done;)y.push(v.value);else{if(d==null)return[d];if(typeof(h=d.length)!="number")return[d];for(y=new Array(h);h--;)y[h]=d[h]}}else for(h=arguments.length,y=new Array(h);h--;)y[h]=arguments[h];return y}var ie=typeof Symbol<"u"?function(d){return d[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},re=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],_e=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(re),fe={VersionChanged:"Database version changed by other database connection",DatabaseClosed:"Database has been closed",Abort:"Transaction aborted",TransactionInactive:"Transaction has already completed or failed",MissingAPI:"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb"};function Se(d,h){this.name=d,this.message=h}function ke(d,h){return d+". Errors: "+Object.keys(h).map(function(y){return h[y].toString()}).filter(function(y,v,k){return k.indexOf(y)===v}).join(`
|
|
13
|
+
`)}function Be(d,h,y,v){this.failures=h,this.failedKeys=v,this.successCount=y,this.message=ke(d,h)}function tt(d,h){this.name="BulkError",this.failures=Object.keys(h).map(function(y){return h[y]}),this.failuresByPos=h,this.message=ke(d,this.failures)}x(Se).from(Error).extend({toString:function(){return this.name+": "+this.message}}),x(Be).from(Se),x(tt).from(Se);var ft=_e.reduce(function(d,h){return d[h]=h+"Error",d},{}),Ht=Se,Oe=_e.reduce(function(d,h){var y=h+"Error";function v(k,E){this.name=y,k?typeof k=="string"?(this.message="".concat(k).concat(E?`
|
|
14
|
+
`+E:""),this.inner=E||null):typeof k=="object"&&(this.message="".concat(k.name," ").concat(k.message),this.inner=k):(this.message=fe[h]||y,this.inner=null)}return x(v).from(Ht),d[h]=v,d},{}),zt=(Oe.Syntax=SyntaxError,Oe.Type=TypeError,Oe.Range=RangeError,re.reduce(function(d,h){return d[h+"Error"]=Oe[h],d},{}));re=_e.reduce(function(d,h){return["Syntax","Type","Range"].indexOf(h)===-1&&(d[h+"Error"]=Oe[h]),d},{});function Ye(){}function we(d){return d}function Ke(d,h){return d==null||d===we?h:function(y){return h(d(y))}}function st(d,h){return function(){d.apply(this,arguments),h.apply(this,arguments)}}function Dt(d,h){return d===Ye?h:function(){var y=d.apply(this,arguments),v=(y!==void 0&&(arguments[0]=y),this.onsuccess),k=this.onerror,E=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return v&&(this.onsuccess=this.onsuccess?st(v,this.onsuccess):v),k&&(this.onerror=this.onerror?st(k,this.onerror):k),E!==void 0?E:y}}function F(d,h){return d===Ye?h:function(){d.apply(this,arguments);var y=this.onsuccess,v=this.onerror;this.onsuccess=this.onerror=null,h.apply(this,arguments),y&&(this.onsuccess=this.onsuccess?st(y,this.onsuccess):y),v&&(this.onerror=this.onerror?st(v,this.onerror):v)}}function ce(d,h){return d===Ye?h:function(k){var v=d.apply(this,arguments),k=(c(k,v),this.onsuccess),E=this.onerror,D=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return k&&(this.onsuccess=this.onsuccess?st(k,this.onsuccess):k),E&&(this.onerror=this.onerror?st(E,this.onerror):E),v===void 0?D===void 0?void 0:D:c(v,D)}}function ge(d,h){return d===Ye?h:function(){return h.apply(this,arguments)!==!1&&d.apply(this,arguments)}}function De(d,h){return d===Ye?h:function(){var y=d.apply(this,arguments);if(y&&typeof y.then=="function"){for(var v=this,k=arguments.length,E=new Array(k);k--;)E[k]=arguments[k];return y.then(function(){return h.apply(v,E)})}return h.apply(this,arguments)}}re.ModifyError=Be,re.DexieError=Se,re.BulkError=tt;var Le=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function me(d){Le=d}var H={},ye=100,xe=typeof Promise>"u"?[]:(_e=Promise.resolve(),typeof crypto<"u"&&crypto.subtle?[xe=crypto.subtle.digest("SHA-512",new Uint8Array([0])),u(xe),_e]:[_e,u(_e),_e]),_e=xe[0],vo=xe[1],vo=vo&&vo.then,Ue=_e&&_e.constructor,Re=!!xe[2],ut=function(d,h){rn.push([d,h]),gt&&(queueMicrotask(ur),gt=!1)},ot=!0,gt=!0,_t=[],vt=[],Bt=we,Kt={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:Ye,pgp:!1,env:{},finalize:Ye},qe=Kt,rn=[],cn=0,on=[];function ze(d){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var h=this._PSD=qe;if(typeof d!="function"){if(d!==H)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&En(this,this._value)}else this._state=null,this._value=null,++h.ref,function y(v,k){try{k(function(E){if(v._state===null){if(E===v)throw new TypeError("A promise cannot be resolved with itself.");var D=v._lib&&is();E&&typeof E.then=="function"?y(v,function(z,X){E instanceof ze?E._then(z,X):E.then(z,X)}):(v._state=!0,v._value=E,$s(v)),D&&Ss()}},En.bind(null,v))}catch(E){En(v,E)}}(this,d)}var Ar={get:function(){var d=qe,h=Rn;function y(v,k){var E=this,D=!d.global&&(d!==qe||h!==Rn),z=D&&!Ds(),X=new ze(function(oe,J){Qn(E,new as(Gt(v,d,D,z),Gt(k,d,D,z),oe,J,d))});return this._consoleTask&&(X._consoleTask=this._consoleTask),X}return y.prototype=H,y},set:function(d){S(this,"then",d&&d.prototype===H?Ar:{get:function(){return d},set:Ar.set})}};function as(d,h,y,v,k){this.onFulfilled=typeof d=="function"?d:null,this.onRejected=typeof h=="function"?h:null,this.resolve=y,this.reject=v,this.psd=k}function En(d,h){var y,v;vt.push(h),d._state===null&&(y=d._lib&&is(),h=Bt(h),d._state=!1,d._value=h,v=d,_t.some(function(k){return k._value===v._value})||_t.push(v),$s(d),y)&&Ss()}function $s(d){var h=d._listeners;d._listeners=[];for(var y=0,v=h.length;y<v;++y)Qn(d,h[y]);var k=d._PSD;--k.ref||k.finalize(),cn===0&&(++cn,ut(function(){--cn==0&&Fe()},[]))}function Qn(d,h){if(d._state===null)d._listeners.push(h);else{var y=d._state?h.onFulfilled:h.onRejected;if(y===null)return(d._state?h.resolve:h.reject)(d._value);++h.psd.ref,++cn,ut(Ys,[y,d,h])}}function Ys(d,h,y){try{var v,k=h._value;!h._state&&vt.length&&(vt=[]),v=Le&&h._consoleTask?h._consoleTask.run(function(){return d(k)}):d(k),h._state||vt.indexOf(k)!==-1||(E=>{for(var D=_t.length;D;)if(_t[--D]._value===E._value)return _t.splice(D,1)})(h),y.resolve(v)}catch(E){y.reject(E)}finally{--cn==0&&Fe(),--y.psd.ref||y.psd.finalize()}}function ur(){Lt(Kt,function(){is()&&Ss()})}function is(){var d=ot;return gt=ot=!1,d}function Ss(){var d,h,y;do for(;0<rn.length;)for(d=rn,rn=[],y=d.length,h=0;h<y;++h){var v=d[h];v[0].apply(null,v[1])}while(0<rn.length);gt=ot=!0}function Fe(){for(var d=_t,h=(_t=[],d.forEach(function(v){v._PSD.onunhandled.call(null,v._value,v)}),on.slice(0)),y=h.length;y;)h[--y]()}function yt(d){return new ze(H,!1,d)}function et(d,h){var y=qe;return function(){var v=is(),k=qe;try{return ve(y,!0),d.apply(this,arguments)}catch(E){h&&h(E)}finally{ve(k,!1),v&&Ss()}}}g(ze.prototype,{then:Ar,_then:function(d,h){Qn(this,new as(null,null,d,h,qe))},catch:function(d){var h,y;return arguments.length===1?this.then(null,d):(h=d,y=arguments[1],typeof h=="function"?this.then(null,function(v){return(v instanceof h?y:yt)(v)}):this.then(null,function(v){return(v&&v.name===h?y:yt)(v)}))},finally:function(d){return this.then(function(h){return ze.resolve(d()).then(function(){return h})},function(h){return ze.resolve(d()).then(function(){return yt(h)})})},timeout:function(d,h){var y=this;return d<1/0?new ze(function(v,k){var E=setTimeout(function(){return k(new Oe.Timeout(h))},d);y.then(v,k).finally(clearTimeout.bind(null,E))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&S(ze.prototype,Symbol.toStringTag,"Dexie.Promise"),Kt.env=$t(),g(ze,{all:function(){var d=V.apply(null,arguments).map(Ir);return new ze(function(h,y){d.length===0&&h([]);var v=d.length;d.forEach(function(k,E){return ze.resolve(k).then(function(D){d[E]=D,--v||h(d)},y)})})},resolve:function(d){return d instanceof ze?d:d&&typeof d.then=="function"?new ze(function(h,y){d.then(h,y)}):new ze(H,!0,d)},reject:yt,race:function(){var d=V.apply(null,arguments).map(Ir);return new ze(function(h,y){d.map(function(v){return ze.resolve(v).then(h,y)})})},PSD:{get:function(){return qe},set:function(d){return qe=d}},totalEchoes:{get:function(){return Rn}},newPSD:yn,usePSD:Lt,scheduler:{get:function(){return ut},set:function(d){ut=d}},rejectionMapper:{get:function(){return Bt},set:function(d){Bt=d}},follow:function(d,h){return new ze(function(y,v){return yn(function(k,E){var D=qe;D.unhandleds=[],D.onunhandled=E,D.finalize=st(function(){var z,X=this;z=function(){X.unhandleds.length===0?k():E(X.unhandleds[0])},on.push(function oe(){z(),on.splice(on.indexOf(oe),1)}),++cn,ut(function(){--cn==0&&Fe()},[])},D.finalize),d()},h,y,v)})}}),Ue&&(Ue.allSettled&&S(ze,"allSettled",function(){var d=V.apply(null,arguments).map(Ir);return new ze(function(h){d.length===0&&h([]);var y=d.length,v=new Array(y);d.forEach(function(k,E){return ze.resolve(k).then(function(D){return v[E]={status:"fulfilled",value:D}},function(D){return v[E]={status:"rejected",reason:D}}).then(function(){return--y||h(v)})})})}),Ue.any&&typeof AggregateError<"u"&&S(ze,"any",function(){var d=V.apply(null,arguments).map(Ir);return new ze(function(h,y){d.length===0&&y(new AggregateError([]));var v=d.length,k=new Array(v);d.forEach(function(E,D){return ze.resolve(E).then(function(z){return h(z)},function(z){k[D]=z,--v||y(new AggregateError(k))})})})}),Ue.withResolvers)&&(ze.withResolvers=Ue.withResolvers);var mt={awaits:0,echoes:0,id:0},_n=0,Un=[],Hn=0,Rn=0,ls=0;function yn(d,D,y,v){var k=qe,E=Object.create(k),D=(E.parent=k,E.ref=0,E.global=!1,E.id=++ls,Kt.env,E.env=Re?{Promise:ze,PromiseProp:{value:ze,configurable:!0,writable:!0},all:ze.all,race:ze.race,allSettled:ze.allSettled,any:ze.any,resolve:ze.resolve,reject:ze.reject}:{},D&&c(E,D),++k.ref,E.finalize=function(){--this.parent.ref||this.parent.finalize()},Lt(E,d,y,v));return E.ref===0&&E.finalize(),D}function An(){return mt.id||(mt.id=++_n),++mt.awaits,mt.echoes+=ye,mt.id}function Ds(){return!!mt.awaits&&(--mt.awaits==0&&(mt.id=0),mt.echoes=mt.awaits*ye,!0)}function Ir(d){return mt.echoes&&d&&d.constructor===Ue?(An(),d.then(function(h){return Ds(),h},function(h){return Ds(),Pt(h)})):d}function al(){var d=Un[Un.length-1];Un.pop(),ve(d,!1)}function ve(d,h){var y,v,k=qe;(h?!mt.echoes||Hn++&&d===qe:!Hn||--Hn&&d===qe)||queueMicrotask(h?(function(E){++Rn,mt.echoes&&--mt.echoes!=0||(mt.echoes=mt.awaits=mt.id=0),Un.push(qe),ve(E,!0)}).bind(null,d):al),d!==qe&&(qe=d,k===Kt&&(Kt.env=$t()),Re)&&(y=Kt.env.Promise,v=d.env,k.global||d.global)&&(Object.defineProperty(a,"Promise",v.PromiseProp),y.all=v.all,y.race=v.race,y.resolve=v.resolve,y.reject=v.reject,v.allSettled&&(y.allSettled=v.allSettled),v.any)&&(y.any=v.any)}function $t(){var d=a.Promise;return Re?{Promise:d,PromiseProp:Object.getOwnPropertyDescriptor(a,"Promise"),all:d.all,race:d.race,allSettled:d.allSettled,any:d.any,resolve:d.resolve,reject:d.reject}:{}}function Lt(d,h,y,v,k){var E=qe;try{return ve(d,!0),h(y,v,k)}finally{ve(E,!1)}}function Gt(d,h,y,v){return typeof d!="function"?d:function(){var k=qe;y&&An(),ve(h,!0);try{return d.apply(this,arguments)}finally{ve(k,!1),v&&queueMicrotask(Ds)}}}function Tt(d){Promise===Ue&&mt.echoes===0?Hn===0?d():enqueueNativeMicroTask(d):setTimeout(d,0)}(""+vo).indexOf("[native code]")===-1&&(An=Ds=Ye);var Pt=ze.reject,dn="",an="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",ea="String expected.",ws="__dbnames",_s="readonly",go="readwrite";function Or(d,h){return d?h?function(){return d.apply(this,arguments)&&h.apply(this,arguments)}:d:h}var Ph={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function il(d){return typeof d!="string"||/\./.test(d)?function(h){return h}:function(h){return h[d]===void 0&&d in h&&delete(h=$(h))[d],h}}function Eh(){throw Oe.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function jt(d,h){try{var y=Rh(d),v=Rh(h);if(y!==v)return y==="Array"?1:v==="Array"?-1:y==="binary"?1:v==="binary"?-1:y==="string"?1:v==="string"?-1:y==="Date"?1:v!=="Date"?NaN:-1;switch(y){case"number":case"Date":case"string":return h<d?1:d<h?-1:0;case"binary":for(var k=Ah(d),E=Ah(h),D=k.length,z=E.length,X=D<z?D:z,oe=0;oe<X;++oe)if(k[oe]!==E[oe])return k[oe]<E[oe]?-1:1;return D===z?0:D<z?-1:1;case"Array":for(var J=d,Y=h,G=J.length,ne=Y.length,Q=G<ne?G:ne,Z=0;Z<Q;++Z){var ee=jt(J[Z],Y[Z]);if(ee!==0)return ee}return G===ne?0:G<ne?-1:1}}catch{}return NaN}function Rh(d){var h=typeof d;return h=="object"&&(ArrayBuffer.isView(d)||(h=q(d))==="ArrayBuffer")?"binary":h}function Ah(d){return d instanceof Uint8Array?d:ArrayBuffer.isView(d)?new Uint8Array(d.buffer,d.byteOffset,d.byteLength):new Uint8Array(d)}function ll(d,h,y){var v=d.schema.yProps;return v?(h&&0<y.numFailures&&(h=h.filter(function(k,E){return!y.failures[E]})),Promise.all(v.map(function(k){return k=k.updatesTable,h?d.db.table(k).where("k").anyOf(h).delete():d.db.table(k).clear()})).then(function(){return y})):y}Ih.prototype.execute=function(d){var h=this["@@propmod"];if(h.add!==void 0){var y=h.add;if(l(y))return r(r([],l(d)?d:[],!0),y).sort();if(typeof y=="number")return(Number(d)||0)+y;if(typeof y=="bigint")try{return BigInt(d)+y}catch{return BigInt(0)+y}throw new TypeError("Invalid term ".concat(y))}if(h.remove!==void 0){var v=h.remove;if(l(v))return l(d)?d.filter(function(k){return!v.includes(k)}).sort():[];if(typeof v=="number")return Number(d)-v;if(typeof v=="bigint")try{return BigInt(d)-v}catch{return BigInt(0)-v}throw new TypeError("Invalid subtrahend ".concat(v))}return y=(y=h.replacePrefix)==null?void 0:y[0],y&&typeof d=="string"&&d.startsWith(y)?h.replacePrefix[1]+d.substring(y.length):d};var ta=Ih;function Ih(d){this["@@propmod"]=d}function Oh(d,h){for(var y=i(h),v=y.length,k=!1,E=0;E<v;++E){var D=y[E],z=h[D],X=L(d,D);z instanceof ta?(A(d,D,z.execute(X)),k=!0):X!==z&&(A(d,D,z),k=!0)}return k}Wt.prototype._trans=function(d,h,y){var v=this._tx||qe.trans,k=this.name,E=Le&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(d==="readonly"?"read":"write"," ").concat(this.name));function D(oe,J,Y){if(Y.schema[k])return h(Y.idbtrans,Y);throw new Oe.NotFound("Table "+k+" not part of transaction")}var z=is();try{var X=v&&v.db._novip===this.db._novip?v===qe.trans?v._promise(d,D,y):yn(function(){return v._promise(d,D,y)},{trans:v,transless:qe.transless||qe}):function oe(J,Y,G,ne){if(J.idbdb&&(J._state.openComplete||qe.letThrough||J._vip)){var Q=J._createTransaction(Y,G,J._dbSchema);try{Q.create(),J._state.PR1398_maxLoop=3}catch(Z){return Z.name===ft.InvalidState&&J.isOpen()&&0<--J._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),J.close({disableAutoOpen:!1}),J.open().then(function(){return oe(J,Y,G,ne)})):Pt(Z)}return Q._promise(Y,function(Z,ee){return yn(function(){return qe.trans=Q,ne(Z,ee,Q)})}).then(function(Z){if(Y==="readwrite")try{Q.idbtrans.commit()}catch{}return Y==="readonly"?Z:Q._completion.then(function(){return Z})})}if(J._state.openComplete)return Pt(new Oe.DatabaseClosed(J._state.dbOpenError));if(!J._state.isBeingOpened){if(!J._state.autoOpen)return Pt(new Oe.DatabaseClosed);J.open().catch(Ye)}return J._state.dbReadyPromise.then(function(){return oe(J,Y,G,ne)})}(this.db,d,[this.name],D);return E&&(X._consoleTask=E,X=X.catch(function(oe){return console.trace(oe),Pt(oe)})),X}finally{z&&Ss()}},Wt.prototype.get=function(d,h){var y=this;return d&&d.constructor===Object?this.where(d).first(h):d==null?Pt(new Oe.Type("Invalid argument to Table.get()")):this._trans("readonly",function(v){return y.core.get({trans:v,key:d}).then(function(k){return y.hook.reading.fire(k)})}).then(h)},Wt.prototype.where=function(d){if(typeof d=="string")return new this.db.WhereClause(this,d);if(l(d))return new this.db.WhereClause(this,"[".concat(d.join("+"),"]"));var h=i(d);if(h.length===1)return this.where(h[0]).equals(d[h[0]]);var y=this.schema.indexes.concat(this.schema.primKey).filter(function(z){if(z.compound&&h.every(function(oe){return 0<=z.keyPath.indexOf(oe)})){for(var X=0;X<h.length;++X)if(h.indexOf(z.keyPath[X])===-1)return!1;return!0}return!1}).sort(function(z,X){return z.keyPath.length-X.keyPath.length})[0];if(y&&this.db._maxKey!==dn)return D=y.keyPath.slice(0,h.length),this.where(D).equals(D.map(function(z){return d[z]}));!y&&Le&&console.warn("The query ".concat(JSON.stringify(d)," on ").concat(this.name," would benefit from a ")+"compound index [".concat(h.join("+"),"]"));var v=this.schema.idxByName;function k(z,X){return jt(z,X)===0}var D=h.reduce(function(J,X){var oe=J[0],J=J[1],Y=v[X],G=d[X];return[oe||Y,oe||!Y?Or(J,Y&&Y.multi?function(ne){return ne=L(ne,X),l(ne)&&ne.some(function(Q){return k(G,Q)})}:function(ne){return k(G,L(ne,X))}):J]},[null,null]),E=D[0],D=D[1];return E?this.where(E.name).equals(d[E.keyPath]).filter(D):y?this.filter(D):this.where(h).equals("")},Wt.prototype.filter=function(d){return this.toCollection().and(d)},Wt.prototype.count=function(d){return this.toCollection().count(d)},Wt.prototype.offset=function(d){return this.toCollection().offset(d)},Wt.prototype.limit=function(d){return this.toCollection().limit(d)},Wt.prototype.each=function(d){return this.toCollection().each(d)},Wt.prototype.toArray=function(d){return this.toCollection().toArray(d)},Wt.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},Wt.prototype.orderBy=function(d){return new this.db.Collection(new this.db.WhereClause(this,l(d)?"[".concat(d.join("+"),"]"):d))},Wt.prototype.reverse=function(){return this.toCollection().reverse()},Wt.prototype.mapToClass=function(d){for(var h=this.db,y=this.name,v=((this.schema.mappedClass=d).prototype instanceof Eh&&(d=(D=>{var z=J,X=D;if(typeof X!="function"&&X!==null)throw new TypeError("Class extends value "+String(X)+" is not a constructor or null");function oe(){this.constructor=z}function J(){return D!==null&&D.apply(this,arguments)||this}return n(z,X),z.prototype=X===null?Object.create(X):(oe.prototype=X.prototype,new oe),Object.defineProperty(J.prototype,"db",{get:function(){return h},enumerable:!1,configurable:!0}),J.prototype.table=function(){return y},J})(d)),new Set),k=d.prototype;k;k=u(k))Object.getOwnPropertyNames(k).forEach(function(D){return v.add(D)});function E(D){if(!D)return D;var z,X=Object.create(d.prototype);for(z in D)if(!v.has(z))try{X[z]=D[z]}catch{}return X}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=E,this.hook("reading",E),d},Wt.prototype.defineClass=function(){return this.mapToClass(function(d){c(this,d)})},Wt.prototype.add=function(d,h){var y=this,v=this.schema.primKey,k=v.auto,E=v.keyPath,D=d;return E&&k&&(D=il(E)(d)),this._trans("readwrite",function(z){return y.core.mutate({trans:z,type:"add",keys:h!=null?[h]:null,values:[D]})}).then(function(z){return z.numFailures?ze.reject(z.failures[0]):z.lastResult}).then(function(z){if(E)try{A(d,E,z)}catch{}return z})},Wt.prototype.upsert=function(d,h){var y=this,v=this.schema.primKey.keyPath;return this._trans("readwrite",function(k){return y.core.get({trans:k,key:d}).then(function(E){var D=E??{};return Oh(D,h),v&&A(D,v,d),y.core.mutate({trans:k,type:"put",values:[D],keys:[d],upsert:!0,updates:{keys:[d],changeSpecs:[h]}}).then(function(z){return z.numFailures?ze.reject(z.failures[0]):!!E})})})},Wt.prototype.update=function(d,h){return typeof d!="object"||l(d)?this.where(":id").equals(d).modify(h):(d=L(d,this.schema.primKey.keyPath))===void 0?Pt(new Oe.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(d).modify(h)},Wt.prototype.put=function(d,h){var y=this,v=this.schema.primKey,k=v.auto,E=v.keyPath,D=d;return E&&k&&(D=il(E)(d)),this._trans("readwrite",function(z){return y.core.mutate({trans:z,type:"put",values:[D],keys:h!=null?[h]:null})}).then(function(z){return z.numFailures?ze.reject(z.failures[0]):z.lastResult}).then(function(z){if(E)try{A(d,E,z)}catch{}return z})},Wt.prototype.delete=function(d){var h=this;return this._trans("readwrite",function(y){return h.core.mutate({trans:y,type:"delete",keys:[d]}).then(function(v){return ll(h,[d],v)}).then(function(v){return v.numFailures?ze.reject(v.failures[0]):void 0})})},Wt.prototype.clear=function(){var d=this;return this._trans("readwrite",function(h){return d.core.mutate({trans:h,type:"deleteRange",range:Ph}).then(function(y){return ll(d,null,y)})}).then(function(h){return h.numFailures?ze.reject(h.failures[0]):void 0})},Wt.prototype.bulkGet=function(d){var h=this;return this._trans("readonly",function(y){return h.core.getMany({keys:d,trans:y}).then(function(v){return v.map(function(k){return h.hook.reading.fire(k)})})})},Wt.prototype.bulkAdd=function(d,h,y){var v=this,k=Array.isArray(h)?h:void 0,E=(y=y||(k?void 0:h))?y.allKeys:void 0;return this._trans("readwrite",function(D){var z=v.schema.primKey,oe=z.auto,z=z.keyPath;if(z&&k)throw new Oe.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(k&&k.length!==d.length)throw new Oe.InvalidArgument("Arguments objects and keys must have the same length");var X=d.length,oe=z&&oe?d.map(il(z)):d;return v.core.mutate({trans:D,type:"add",keys:k,values:oe,wantResults:E}).then(function(J){var Y=J.numFailures,G=J.failures;if(Y===0)return E?J.results:J.lastResult;throw new tt("".concat(v.name,".bulkAdd(): ").concat(Y," of ").concat(X," operations failed"),G)})})},Wt.prototype.bulkPut=function(d,h,y){var v=this,k=Array.isArray(h)?h:void 0,E=(y=y||(k?void 0:h))?y.allKeys:void 0;return this._trans("readwrite",function(D){var z=v.schema.primKey,oe=z.auto,z=z.keyPath;if(z&&k)throw new Oe.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(k&&k.length!==d.length)throw new Oe.InvalidArgument("Arguments objects and keys must have the same length");var X=d.length,oe=z&&oe?d.map(il(z)):d;return v.core.mutate({trans:D,type:"put",keys:k,values:oe,wantResults:E}).then(function(J){var Y=J.numFailures,G=J.failures;if(Y===0)return E?J.results:J.lastResult;throw new tt("".concat(v.name,".bulkPut(): ").concat(Y," of ").concat(X," operations failed"),G)})})},Wt.prototype.bulkUpdate=function(d){var h=this,y=this.core,v=d.map(function(D){return D.key}),k=d.map(function(D){return D.changes}),E=[];return this._trans("readwrite",function(D){return y.getMany({trans:D,keys:v,cache:"clone"}).then(function(z){var X=[],oe=[],J=(d.forEach(function(Y,G){var ne=Y.key,Q=Y.changes,Z=z[G];if(Z){for(var ee=0,de=Object.keys(Q);ee<de.length;ee++){var ae=de[ee],pe=Q[ae];if(ae===h.schema.primKey.keyPath){if(jt(pe,ne)!==0)throw new Oe.Constraint("Cannot update primary key in bulkUpdate()")}else A(Z,ae,pe)}E.push(G),X.push(ne),oe.push(Z)}}),X.length);return y.mutate({trans:D,type:"put",keys:X,values:oe,updates:{keys:v,changeSpecs:k}}).then(function(Y){var G=Y.numFailures,ne=Y.failures;if(G===0)return J;for(var Q=0,Z=Object.keys(ne);Q<Z.length;Q++){var ee,de=Z[Q],ae=E[Number(de)];ae!=null&&(ee=ne[de],delete ne[de],ne[ae]=ee)}throw new tt("".concat(h.name,".bulkUpdate(): ").concat(G," of ").concat(J," operations failed"),ne)})})})},Wt.prototype.bulkDelete=function(d){var h=this,y=d.length;return this._trans("readwrite",function(v){return h.core.mutate({trans:v,type:"delete",keys:d}).then(function(k){return ll(h,d,k)})}).then(function(v){var k=v.numFailures,E=v.failures;if(k===0)return v.lastResult;throw new tt("".concat(h.name,".bulkDelete(): ").concat(k," of ").concat(y," operations failed"),E)})};var $h=Wt;function Wt(){}function na(d){function h(D,z){if(z){for(var X=arguments.length,oe=new Array(X-1);--X;)oe[X-1]=arguments[X];return y[D].subscribe.apply(null,oe),d}if(typeof D=="string")return y[D]}var y={};h.addEventType=E;for(var v=1,k=arguments.length;v<k;++v)E(arguments[v]);return h;function E(D,z,X){var oe,J;if(typeof D!="object")return z=z||ge,J={subscribers:[],fire:X=X||Ye,subscribe:function(Y){J.subscribers.indexOf(Y)===-1&&(J.subscribers.push(Y),J.fire=z(J.fire,Y))},unsubscribe:function(Y){J.subscribers=J.subscribers.filter(function(G){return G!==Y}),J.fire=J.subscribers.reduce(z,X)}},y[D]=h[D]=J;i(oe=D).forEach(function(Y){var G=oe[Y];if(l(G))E(Y,oe[Y][0],oe[Y][1]);else{if(G!=="asap")throw new Oe.InvalidArgument("Invalid event config");var ne=E(Y,we,function(){for(var Q=arguments.length,Z=new Array(Q);Q--;)Z[Q]=arguments[Q];ne.subscribers.forEach(function(ee){C(function(){ee.apply(null,Z)})})})}})}}function sa(d,h){return x(h).from({prototype:d}),h}function yo(d,h){return!(d.filter||d.algorithm||d.or)&&(h?d.justLimit:!d.replayFilter)}function sd(d,h){d.filter=Or(d.filter,h)}function rd(d,h,y){var v=d.replayFilter;d.replayFilter=v?function(){return Or(v(),h())}:h,d.justLimit=y&&!v}function cl(d,h){if(d.isPrimKey)return h.primaryKey;var y=h.getIndexByKeyPath(d.index);if(y)return y;throw new Oe.Schema("KeyPath "+d.index+" on object store "+h.name+" is not indexed")}function Dh(d,h,y){var v=cl(d,h.schema);return h.openCursor({trans:y,values:!d.keysOnly,reverse:d.dir==="prev",unique:!!d.unique,query:{index:v,range:d.range}})}function dl(d,h,y,v){var k,E,D=d.replayFilter?Or(d.filter,d.replayFilter()):d.filter;return d.or?(k={},E=function(z,X,oe){var J,Y;D&&!D(X,oe,function(G){return X.stop(G)},function(G){return X.fail(G)})||((Y=""+(J=X.primaryKey))=="[object ArrayBuffer]"&&(Y=""+new Uint8Array(J)),f(k,Y))||(k[Y]=!0,h(z,X,oe))},Promise.all([d.or._iterate(E,y),Lh(Dh(d,v,y),d.algorithm,E,!d.keysOnly&&d.valueMapper)])):Lh(Dh(d,v,y),Or(d.algorithm,D),h,!d.keysOnly&&d.valueMapper)}function Lh(d,h,y,v){var k=et(v?function(E,D,z){return y(v(E),D,z)}:y);return d.then(function(E){if(E)return E.start(function(){var D=function(){return E.continue()};h&&!h(E,function(z){return D=z},function(z){E.stop(z),D=Ye},function(z){E.fail(z),D=Ye})||k(E.value,E,function(z){return D=z}),D()})})}Rt.prototype._read=function(d,h){var y=this._ctx;return y.error?y.table._trans(null,Pt.bind(null,y.error)):y.table._trans("readonly",d).then(h)},Rt.prototype._write=function(d){var h=this._ctx;return h.error?h.table._trans(null,Pt.bind(null,h.error)):h.table._trans("readwrite",d,"locked")},Rt.prototype._addAlgorithm=function(d){var h=this._ctx;h.algorithm=Or(h.algorithm,d)},Rt.prototype._iterate=function(d,h){return dl(this._ctx,d,h,this._ctx.table.core)},Rt.prototype.clone=function(d){var h=Object.create(this.constructor.prototype),y=Object.create(this._ctx);return d&&c(y,d),h._ctx=y,h},Rt.prototype.raw=function(){return this._ctx.valueMapper=null,this},Rt.prototype.each=function(d){var h=this._ctx;return this._read(function(y){return dl(h,d,y,h.table.core)})},Rt.prototype.count=function(d){var h=this;return this._read(function(y){var v,k=h._ctx,E=k.table.core;return yo(k,!0)?E.count({trans:y,query:{index:cl(k,E.schema),range:k.range}}).then(function(D){return Math.min(D,k.limit)}):(v=0,dl(k,function(){return++v,!1},y,E).then(function(){return v}))}).then(d)},Rt.prototype.sortBy=function(d,h){var y=d.split(".").reverse(),v=y[0],k=y.length-1;function E(X,oe){return oe?E(X[y[oe]],oe-1):X[v]}var D=this._ctx.dir==="next"?1:-1;function z(X,oe){return jt(E(X,k),E(oe,k))*D}return this.toArray(function(X){return X.sort(z)}).then(h)},Rt.prototype.toArray=function(d){var h=this;return this._read(function(y){var v,k,E,D=h._ctx;return yo(D,!0)&&0<D.limit?(v=D.valueMapper,k=cl(D,D.table.core.schema),D.table.core.query({trans:y,limit:D.limit,values:!0,direction:D.dir==="prev"?"prev":void 0,query:{index:k,range:D.range}}).then(function(z){return z=z.result,v?z.map(v):z})):(E=[],dl(D,function(z){return E.push(z)},y,D.table.core).then(function(){return E}))},d)},Rt.prototype.offset=function(d){var h=this._ctx;return d<=0||(h.offset+=d,yo(h)?rd(h,function(){var y=d;return function(v,k){return y===0||(y===1?--y:k(function(){v.advance(y),y=0}),!1)}}):rd(h,function(){var y=d;return function(){return--y<0}})),this},Rt.prototype.limit=function(d){return this._ctx.limit=Math.min(this._ctx.limit,d),rd(this._ctx,function(){var h=d;return function(y,v,k){return--h<=0&&v(k),0<=h}},!0),this},Rt.prototype.until=function(d,h){return sd(this._ctx,function(y,v,k){return!d(y.value)||(v(k),h)}),this},Rt.prototype.first=function(d){return this.limit(1).toArray(function(h){return h[0]}).then(d)},Rt.prototype.last=function(d){return this.reverse().first(d)},Rt.prototype.filter=function(d){var h;return sd(this._ctx,function(y){return d(y.value)}),(h=this._ctx).isMatch=Or(h.isMatch,d),this},Rt.prototype.and=function(d){return this.filter(d)},Rt.prototype.or=function(d){return new this.db.WhereClause(this._ctx.table,d,this)},Rt.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},Rt.prototype.desc=function(){return this.reverse()},Rt.prototype.eachKey=function(d){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(y,v){d(v.key,v)})},Rt.prototype.eachUniqueKey=function(d){return this._ctx.unique="unique",this.eachKey(d)},Rt.prototype.eachPrimaryKey=function(d){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(y,v){d(v.primaryKey,v)})},Rt.prototype.keys=function(d){var h=this._ctx,y=(h.keysOnly=!h.isMatch,[]);return this.each(function(v,k){y.push(k.key)}).then(function(){return y}).then(d)},Rt.prototype.primaryKeys=function(d){var h=this._ctx;if(yo(h,!0)&&0<h.limit)return this._read(function(v){var k=cl(h,h.table.core.schema);return h.table.core.query({trans:v,values:!1,limit:h.limit,direction:h.dir==="prev"?"prev":void 0,query:{index:k,range:h.range}})}).then(function(v){return v.result}).then(d);h.keysOnly=!h.isMatch;var y=[];return this.each(function(v,k){y.push(k.primaryKey)}).then(function(){return y}).then(d)},Rt.prototype.uniqueKeys=function(d){return this._ctx.unique="unique",this.keys(d)},Rt.prototype.firstKey=function(d){return this.limit(1).keys(function(h){return h[0]}).then(d)},Rt.prototype.lastKey=function(d){return this.reverse().firstKey(d)},Rt.prototype.distinct=function(){var d,h=this._ctx,h=h.index&&h.table.schema.idxByName[h.index];return h&&h.multi&&(d={},sd(this._ctx,function(v){var v=v.primaryKey.toString(),k=f(d,v);return d[v]=!0,!k})),this},Rt.prototype.modify=function(d){var h=this,y=this._ctx;return this._write(function(v){function k(Z,ee){var de=ee.failures;G+=Z-ee.numFailures;for(var ae=0,pe=i(de);ae<pe.length;ae++){var Te=pe[ae];Y.push(de[Te])}}var E=typeof d=="function"?d:function(Z){return Oh(Z,d)},D=y.table.core,J=D.schema.primaryKey,z=J.outbound,X=J.extractKey,oe=200,J=h.db._options.modifyChunkSize,Y=(J&&(oe=typeof J=="object"?J[D.name]||J["*"]||200:J),[]),G=0,ne=[],Q=d===Fh;return h.clone().primaryKeys().then(function(Z){function ee(ae){var pe=Math.min(oe,Z.length-ae),Te=Z.slice(ae,ae+pe);return(Q?Promise.resolve([]):D.getMany({trans:v,keys:Te,cache:"immutable"})).then(function(Me){var $e=[],Ee=[],Ve=z?[]:null,Ae=Q?Te:[];if(!Q)for(var Xe=0;Xe<pe;++Xe){var je=Me[Xe],lt={value:$(je),primKey:Z[ae+Xe]};E.call(lt,lt.value,lt)!==!1&&(lt.value==null?Ae.push(Z[ae+Xe]):z||jt(X(je),X(lt.value))===0?(Ee.push(lt.value),z&&Ve.push(Z[ae+Xe])):(Ae.push(Z[ae+Xe]),$e.push(lt.value)))}return Promise.resolve(0<$e.length&&D.mutate({trans:v,type:"add",values:$e}).then(function(ct){for(var pt in ct.failures)Ae.splice(parseInt(pt),1);k($e.length,ct)})).then(function(){return(0<Ee.length||de&&typeof d=="object")&&D.mutate({trans:v,type:"put",keys:Ve,values:Ee,criteria:de,changeSpec:typeof d!="function"&&d,isAdditionalChunk:0<ae}).then(function(ct){return k(Ee.length,ct)})}).then(function(){return(0<Ae.length||de&&Q)&&D.mutate({trans:v,type:"delete",keys:Ae,criteria:de,isAdditionalChunk:0<ae}).then(function(ct){return ll(y.table,Ae,ct)}).then(function(ct){return k(Ae.length,ct)})}).then(function(){return Z.length>ae+pe&&ee(ae+oe)})})}var de=yo(y)&&y.limit===1/0&&(typeof d!="function"||Q)&&{index:y.index,range:y.range};return ee(0).then(function(){if(0<Y.length)throw new Be("Error modifying one or more objects",Y,G,ne);return Z.length})})})},Rt.prototype.delete=function(){var d=this._ctx,h=d.range;return!yo(d)||d.table.schema.yProps||!d.isPrimKey&&h.type!==3?this.modify(Fh):this._write(function(y){var v=d.table.core.schema.primaryKey,k=h;return d.table.core.count({trans:y,query:{index:v,range:k}}).then(function(E){return d.table.core.mutate({trans:y,type:"deleteRange",range:k}).then(function(X){var z=X.failures,X=X.numFailures;if(X)throw new Be("Could not delete some values",Object.keys(z).map(function(oe){return z[oe]}),E-X);return E-X})})})};var ow=Rt;function Rt(){}var Fh=function(d,h){return h.value=null};function aw(d,h){return d<h?-1:d===h?0:1}function iw(d,h){return h<d?-1:d===h?0:1}function Zn(d,h,y){return d=d instanceof zh?new d.Collection(d):d,d._ctx.error=new(y||TypeError)(h),d}function bo(d){return new d.Collection(d,function(){return Nh("")}).limit(0)}function ul(ne,h,y,v){var k,E,D,z,X,oe,J,Y=y.length;if(!y.every(function(Z){return typeof Z=="string"}))return Zn(ne,ea);function G(Z){k=Z==="next"?function(de){return de.toUpperCase()}:function(de){return de.toLowerCase()},E=Z==="next"?function(de){return de.toLowerCase()}:function(de){return de.toUpperCase()},D=Z==="next"?aw:iw;var ee=y.map(function(de){return{lower:E(de),upper:k(de)}}).sort(function(de,ae){return D(de.lower,ae.lower)});z=ee.map(function(de){return de.upper}),X=ee.map(function(de){return de.lower}),J=(oe=Z)==="next"?"":v}G("next");var ne=new ne.Collection(ne,function(){return mr(z[0],X[Y-1]+v)}),Q=(ne._ondirectionchange=function(Z){G(Z)},0);return ne._addAlgorithm(function(Z,ee,de){var ae=Z.key;if(typeof ae=="string"){var pe=E(ae);if(h(pe,X,Q))return!0;for(var Te=null,Me=Q;Me<Y;++Me){var $e=((Ee,Ve,Ae,Xe,je,lt)=>{for(var ct=Math.min(Ee.length,Xe.length),pt=-1,kt=0;kt<ct;++kt){var es=Ve[kt];if(es!==Xe[kt])return je(Ee[kt],Ae[kt])<0?Ee.substr(0,kt)+Ae[kt]+Ae.substr(kt+1):je(Ee[kt],Xe[kt])<0?Ee.substr(0,kt)+Xe[kt]+Ae.substr(kt+1):0<=pt?Ee.substr(0,pt)+Ve[pt]+Ae.substr(pt+1):null;je(Ee[kt],es)<0&&(pt=kt)}return ct<Xe.length&<==="next"?Ee+Ae.substr(Ee.length):ct<Ee.length&<==="prev"?Ee.substr(0,Ae.length):pt<0?null:Ee.substr(0,pt)+Xe[pt]+Ae.substr(pt+1)})(ae,pe,z[Me],X[Me],D,oe);$e===null&&Te===null?Q=Me+1:(Te===null||0<D(Te,$e))&&(Te=$e)}ee(Te!==null?function(){Z.continue(Te+J)}:de)}return!1}),ne}function mr(d,h,y,v){return{type:2,lower:d,upper:h,lowerOpen:y,upperOpen:v}}function Nh(d){return{type:1,lower:d,upper:d}}Object.defineProperty(bn.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),bn.prototype.between=function(d,h,y,v){y=y!==!1,v=v===!0;try{return 0<this._cmp(d,h)||this._cmp(d,h)===0&&(y||v)&&(!y||!v)?bo(this):new this.Collection(this,function(){return mr(d,h,!y,!v)})}catch{return Zn(this,an)}},bn.prototype.equals=function(d){return d==null?Zn(this,an):new this.Collection(this,function(){return Nh(d)})},bn.prototype.above=function(d){return d==null?Zn(this,an):new this.Collection(this,function(){return mr(d,void 0,!0)})},bn.prototype.aboveOrEqual=function(d){return d==null?Zn(this,an):new this.Collection(this,function(){return mr(d,void 0,!1)})},bn.prototype.below=function(d){return d==null?Zn(this,an):new this.Collection(this,function(){return mr(void 0,d,!1,!0)})},bn.prototype.belowOrEqual=function(d){return d==null?Zn(this,an):new this.Collection(this,function(){return mr(void 0,d)})},bn.prototype.startsWith=function(d){return typeof d!="string"?Zn(this,ea):this.between(d,d+dn,!0,!0)},bn.prototype.startsWithIgnoreCase=function(d){return d===""?this.startsWith(d):ul(this,function(h,y){return h.indexOf(y[0])===0},[d],dn)},bn.prototype.equalsIgnoreCase=function(d){return ul(this,function(h,y){return h===y[0]},[d],"")},bn.prototype.anyOfIgnoreCase=function(){var d=V.apply(se,arguments);return d.length===0?bo(this):ul(this,function(h,y){return y.indexOf(h)!==-1},d,"")},bn.prototype.startsWithAnyOfIgnoreCase=function(){var d=V.apply(se,arguments);return d.length===0?bo(this):ul(this,function(h,y){return y.some(function(v){return h.indexOf(v)===0})},d,dn)},bn.prototype.anyOf=function(){var d,h,y=this,v=V.apply(se,arguments),k=this._cmp;try{v.sort(k)}catch{return Zn(this,an)}return v.length===0?bo(this):((d=new this.Collection(this,function(){return mr(v[0],v[v.length-1])}))._ondirectionchange=function(E){k=E==="next"?y._ascending:y._descending,v.sort(k)},h=0,d._addAlgorithm(function(E,D,z){for(var X=E.key;0<k(X,v[h]);)if(++h===v.length)return D(z),!1;return k(X,v[h])===0||(D(function(){E.continue(v[h])}),!1)}),d)},bn.prototype.notEqual=function(d){return this.inAnyRange([[-1/0,d],[d,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},bn.prototype.noneOf=function(){var d=V.apply(se,arguments);if(d.length===0)return new this.Collection(this);try{d.sort(this._ascending)}catch{return Zn(this,an)}var h=d.reduce(function(y,v){return y?y.concat([[y[y.length-1][1],v]]):[[-1/0,v]]},null);return h.push([d[d.length-1],this.db._maxKey]),this.inAnyRange(h,{includeLowers:!1,includeUppers:!1})},bn.prototype.inAnyRange=function(d,de){var y=this,v=this._cmp,k=this._ascending,E=this._descending,D=this._min,z=this._max;if(d.length===0)return bo(this);if(!d.every(function(ae){return ae[0]!==void 0&&ae[1]!==void 0&&k(ae[0],ae[1])<=0}))return Zn(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",Oe.InvalidArgument);var X=!de||de.includeLowers!==!1,oe=de&&de.includeUppers===!0,J,Y=k;function G(ae,pe){return Y(ae[0],pe[0])}try{(J=d.reduce(function(ae,pe){for(var Te=0,Me=ae.length;Te<Me;++Te){var $e=ae[Te];if(v(pe[0],$e[1])<0&&0<v(pe[1],$e[0])){$e[0]=D($e[0],pe[0]),$e[1]=z($e[1],pe[1]);break}}return Te===Me&&ae.push(pe),ae},[])).sort(G)}catch{return Zn(this,an)}var ne=0,Q=oe?function(ae){return 0<k(ae,J[ne][1])}:function(ae){return 0<=k(ae,J[ne][1])},Z=X?function(ae){return 0<E(ae,J[ne][0])}:function(ae){return 0<=E(ae,J[ne][0])},ee=Q,de=new this.Collection(this,function(){return mr(J[0][0],J[J.length-1][1],!X,!oe)});return de._ondirectionchange=function(ae){Y=ae==="next"?(ee=Q,k):(ee=Z,E),J.sort(G)},de._addAlgorithm(function(ae,pe,Te){for(var Me,$e=ae.key;ee($e);)if(++ne===J.length)return pe(Te),!1;return!Q(Me=$e)&&!Z(Me)||(y._cmp($e,J[ne][1])===0||y._cmp($e,J[ne][0])===0||pe(function(){Y===k?ae.continue(J[ne][0]):ae.continue(J[ne][1])}),!1)}),de},bn.prototype.startsWithAnyOf=function(){var d=V.apply(se,arguments);return d.every(function(h){return typeof h=="string"})?d.length===0?bo(this):this.inAnyRange(d.map(function(h){return[h,h+dn]})):Zn(this,"startsWithAnyOf() only works with strings")};var zh=bn;function bn(){}function ks(d){return et(function(h){return ra(h),d(h.target.error),!1})}function ra(d){d.stopPropagation&&d.stopPropagation(),d.preventDefault&&d.preventDefault()}var oa="storagemutated",od="x-storagemutated-1",hr=na(null,oa),lw=(Ls.prototype._lock=function(){return _(!qe.global),++this._reculock,this._reculock!==1||qe.global||(qe.lockOwnerFor=this),this},Ls.prototype._unlock=function(){if(_(!qe.global),--this._reculock==0)for(qe.global||(qe.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var d=this._blockedFuncs.shift();try{Lt(d[1],d[0])}catch{}}return this},Ls.prototype._locked=function(){return this._reculock&&qe.lockOwnerFor!==this},Ls.prototype.create=function(d){var h=this;if(this.mode){var y=this.db.idbdb,v=this.db._state.dbOpenError;if(_(!this.idbtrans),!d&&!y)switch(v&&v.name){case"DatabaseClosedError":throw new Oe.DatabaseClosed(v);case"MissingAPIError":throw new Oe.MissingAPI(v.message,v);default:throw new Oe.OpenFailed(v)}if(!this.active)throw new Oe.TransactionInactive;_(this._completion._state===null),(d=this.idbtrans=d||(this.db.core||y).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=et(function(k){ra(k),h._reject(d.error)}),d.onabort=et(function(k){ra(k),h.active&&h._reject(new Oe.Abort(d.error)),h.active=!1,h.on("abort").fire(k)}),d.oncomplete=et(function(){h.active=!1,h._resolve(),"mutatedParts"in d&&hr.storagemutated.fire(d.mutatedParts)})}return this},Ls.prototype._promise=function(d,h,y){var v,k=this;return d==="readwrite"&&this.mode!=="readwrite"?Pt(new Oe.ReadOnly("Transaction is readonly")):this.active?this._locked()?new ze(function(E,D){k._blockedFuncs.push([function(){k._promise(d,h,y).then(E,D)},qe])}):y?yn(function(){var E=new ze(function(D,z){k._lock();var X=h(D,z,k);X&&X.then&&X.then(D,z)});return E.finally(function(){return k._unlock()}),E._lib=!0,E}):((v=new ze(function(E,D){var z=h(E,D,k);z&&z.then&&z.then(E,D)}))._lib=!0,v):Pt(new Oe.TransactionInactive)},Ls.prototype._root=function(){return this.parent?this.parent._root():this},Ls.prototype.waitFor=function(d){var h,y=this._root(),v=ze.resolve(d),k=(y._waitingFor?y._waitingFor=y._waitingFor.then(function(){return v}):(y._waitingFor=v,y._waitingQueue=[],h=y.idbtrans.objectStore(y.storeNames[0]),function E(){for(++y._spinCount;y._waitingQueue.length;)y._waitingQueue.shift()();y._waitingFor&&(h.get(-1/0).onsuccess=E)}()),y._waitingFor);return new ze(function(E,D){v.then(function(z){return y._waitingQueue.push(et(E.bind(null,z)))},function(z){return y._waitingQueue.push(et(D.bind(null,z)))}).finally(function(){y._waitingFor===k&&(y._waitingFor=null)})})},Ls.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new Oe.Abort))},Ls.prototype.table=function(d){var h=this._memoizedTables||(this._memoizedTables={});if(f(h,d))return h[d];var y=this.schema[d];if(y)return(y=new this.db.Table(d,y,this)).core=this.db.core.table(d),h[d]=y;throw new Oe.NotFound("Table "+d+" not part of transaction")},Ls);function Ls(){}function ad(d,h,y,v,k,E,D,z){return{name:d,keyPath:h,unique:y,multi:v,auto:k,compound:E,src:(y&&!D?"&":"")+(v?"*":"")+(k?"++":"")+Bh(h),type:z}}function Bh(d){return typeof d=="string"?d:d?"["+[].join.call(d,"+")+"]":""}function id(d,h,y){return{name:d,primKey:h,indexes:y,mappedClass:null,idxByName:(v=function(k){return[k.name,k]},y.reduce(function(k,E,D){return E=v(E,D),E&&(k[E[0]]=E[1]),k},{}))};var v}var aa=function(d){try{return d.only([[]]),aa=function(){return[[]]},[[]]}catch{return aa=function(){return dn},dn}};function ld(d){return d==null?function(){}:typeof d=="string"?(h=d).split(".").length===1?function(y){return y[h]}:function(y){return L(y,h)}:function(y){return L(y,d)};var h}function Wh(d){return[].slice.call(d)}var cw=0;function ia(d){return d==null?":id":typeof d=="string"?d:"[".concat(d.join("+"),"]")}function dw(d,h,D){function v(ee){if(ee.type===3)return null;if(ee.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var ne=ee.lower,Q=ee.upper,Z=ee.lowerOpen,ee=ee.upperOpen;return ne===void 0?Q===void 0?null:h.upperBound(Q,!!ee):Q===void 0?h.lowerBound(ne,!!Z):h.bound(ne,Q,!!Z,!!ee)}function k(G){var ne,Q,Z=G.name;return{name:Z,schema:G,mutate:function(ee){var de=ee.trans,ae=ee.type,pe=ee.keys,Te=ee.values,Me=ee.range;return new Promise(function($e,Ee){$e=et($e);var Ve=de.objectStore(Z),Ae=Ve.keyPath==null,Xe=ae==="put"||ae==="add";if(!Xe&&ae!=="delete"&&ae!=="deleteRange")throw new Error("Invalid operation type: "+ae);var je,lt=(pe||Te||{length:1}).length;if(pe&&Te&&pe.length!==Te.length)throw new Error("Given keys array must have same length as given values array.");if(lt===0)return $e({numFailures:0,failures:{},results:[],lastResult:void 0});function ct(Ln){++es,ra(Ln)}var pt=[],kt=[],es=0;if(ae==="deleteRange"){if(Me.type===4)return $e({numFailures:es,failures:kt,results:[],lastResult:void 0});Me.type===3?pt.push(je=Ve.clear()):pt.push(je=Ve.delete(v(Me)))}else{var Ae=Xe?Ae?[Te,pe]:[Te,null]:[pe,null],ht=Ae[0],On=Ae[1];if(Xe)for(var $n=0;$n<lt;++$n)pt.push(je=On&&On[$n]!==void 0?Ve[ae](ht[$n],On[$n]):Ve[ae](ht[$n])),je.onerror=ct;else for($n=0;$n<lt;++$n)pt.push(je=Ve[ae](ht[$n])),je.onerror=ct}function _l(Ln){Ln=Ln.target.result,pt.forEach(function(Lr,jd){return Lr.error!=null&&(kt[jd]=Lr.error)}),$e({numFailures:es,failures:kt,results:ae==="delete"?pe:pt.map(function(Lr){return Lr.result}),lastResult:Ln})}je.onerror=function(Ln){ct(Ln),_l(Ln)},je.onsuccess=_l})},getMany:function(ee){var de=ee.trans,ae=ee.keys;return new Promise(function(pe,Te){pe=et(pe);for(var Me,$e=de.objectStore(Z),Ee=ae.length,Ve=new Array(Ee),Ae=0,Xe=0,je=function(pt){pt=pt.target,Ve[pt._pos]=pt.result,++Xe===Ae&&pe(Ve)},lt=ks(Te),ct=0;ct<Ee;++ct)ae[ct]!=null&&((Me=$e.get(ae[ct]))._pos=ct,Me.onsuccess=je,Me.onerror=lt,++Ae);Ae===0&&pe(Ve)})},get:function(ee){var de=ee.trans,ae=ee.key;return new Promise(function(pe,Te){pe=et(pe);var Me=de.objectStore(Z).get(ae);Me.onsuccess=function($e){return pe($e.target.result)},Me.onerror=ks(Te)})},query:(ne=X,Q=oe,function(ee){return new Promise(function(de,ae){de=et(de);var pe,Te,Me,$e,lt=ee.trans,Ee=ee.values,Ve=ee.limit,je=ee.query,Ae=(Ae=ee.direction)!=null?Ae:"next",Xe=Ve===1/0?void 0:Ve,ct=je.index,je=je.range,lt=lt.objectStore(Z),lt=ct.isPrimaryKey?lt:lt.index(ct.name),ct=v(je);if(Ve===0)return de({result:[]});Q?(je={query:ct,count:Xe,direction:Ae},(pe=Ee?lt.getAll(je):lt.getAllKeys(je)).onsuccess=function(pt){return de({result:pt.target.result})},pe.onerror=ks(ae)):ne&&Ae==="next"?((pe=Ee?lt.getAll(ct,Xe):lt.getAllKeys(ct,Xe)).onsuccess=function(pt){return de({result:pt.target.result})},pe.onerror=ks(ae)):(Te=0,Me=!Ee&&"openKeyCursor"in lt?lt.openKeyCursor(ct,Ae):lt.openCursor(ct,Ae),$e=[],Me.onsuccess=function(){var pt=Me.result;return!pt||($e.push(Ee?pt.value:pt.primaryKey),++Te===Ve)?de({result:$e}):void pt.continue()},Me.onerror=ks(ae))})}),openCursor:function(ee){var de=ee.trans,ae=ee.values,pe=ee.query,Te=ee.reverse,Me=ee.unique;return new Promise(function($e,Ee){$e=et($e);var Xe=pe.index,Ve=pe.range,Ae=de.objectStore(Z),Ae=Xe.isPrimaryKey?Ae:Ae.index(Xe.name),Xe=Te?Me?"prevunique":"prev":Me?"nextunique":"next",je=!ae&&"openKeyCursor"in Ae?Ae.openKeyCursor(v(Ve),Xe):Ae.openCursor(v(Ve),Xe);je.onerror=ks(Ee),je.onsuccess=et(function(lt){var ct,pt,kt,es,ht=je.result;ht?(ht.___id=++cw,ht.done=!1,ct=ht.continue.bind(ht),pt=(pt=ht.continuePrimaryKey)&&pt.bind(ht),kt=ht.advance.bind(ht),es=function(){throw new Error("Cursor not stopped")},ht.trans=de,ht.stop=ht.continue=ht.continuePrimaryKey=ht.advance=function(){throw new Error("Cursor not started")},ht.fail=et(Ee),ht.next=function(){var On=this,$n=1;return this.start(function(){return $n--?On.continue():On.stop()}).then(function(){return On})},ht.start=function(On){function $n(){if(je.result)try{On()}catch(Ln){ht.fail(Ln)}else ht.done=!0,ht.start=function(){throw new Error("Cursor behind last entry")},ht.stop()}var _l=new Promise(function(Ln,Lr){Ln=et(Ln),je.onerror=ks(Lr),ht.fail=Lr,ht.stop=function(jd){ht.stop=ht.continue=ht.continuePrimaryKey=ht.advance=es,Ln(jd)}});return je.onsuccess=et(function(Ln){je.onsuccess=$n,$n()}),ht.continue=ct,ht.continuePrimaryKey=pt,ht.advance=kt,$n(),_l},$e(ht)):$e(null)},Ee)})},count:function(ee){var de=ee.query,ae=ee.trans,pe=de.index,Te=de.range;return new Promise(function(Me,$e){var Ee=ae.objectStore(Z),Ee=pe.isPrimaryKey?Ee:Ee.index(pe.name),Ve=v(Te),Ve=Ve?Ee.count(Ve):Ee.count();Ve.onsuccess=et(function(Ae){return Me(Ae.target.result)}),Ve.onerror=ks($e)})}}}E=D,z=Wh((D=d).objectStoreNames),J=0<z.length?E.objectStore(z[0]):{};var E,D={schema:{name:D.name,tables:z.map(function(G){return E.objectStore(G)}).map(function(G){var ne=G.keyPath,Q=G.autoIncrement,ee=l(ne),Z={},ee={name:G.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:ne==null,compound:ee,keyPath:ne,autoIncrement:Q,unique:!0,extractKey:ld(ne)},indexes:Wh(G.indexNames).map(function(de){return G.index(de)}).map(function(Te){var Me=Te.name,ae=Te.unique,pe=Te.multiEntry,Te=Te.keyPath,Me={name:Me,compound:l(Te),keyPath:Te,unique:ae,multiEntry:pe,extractKey:ld(Te)};return Z[ia(Te)]=Me}),getIndexByKeyPath:function(de){return Z[ia(de)]}};return Z[":id"]=ee.primaryKey,ne!=null&&(Z[ia(ne)]=ee.primaryKey),ee})},hasGetAll:0<z.length&&"getAll"in J&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604),hasIdb3Features:"getAllRecords"in J},z=D.schema,X=D.hasGetAll,oe=D.hasIdb3Features,J=z.tables.map(k),Y={};return J.forEach(function(G){return Y[G.name]=G}),{stack:"dbcore",transaction:d.transaction.bind(d),table:function(G){if(Y[G])return Y[G];throw new Error("Table '".concat(G,"' not found"))},MIN_KEY:-1/0,MAX_KEY:aa(h),schema:z}}function uw(d,h,y,v){return y=y.IDBKeyRange,h=dw(h,y,v),{dbcore:d.dbcore.reduce(function(k,E){return E=E.create,s(s({},k),E(k))},h)}}function ml(d,h){var y=h.db,y=uw(d._middlewares,y,d._deps,h);d.core=y.dbcore,d.tables.forEach(function(v){var k=v.name;d.core.schema.tables.some(function(E){return E.name===k})&&(v.core=d.core.table(k),d[k]instanceof d.Table)&&(d[k].core=v.core)})}function hl(d,h,y,v){y.forEach(function(k){var E=v[k];h.forEach(function(D){var z=function X(oe,J){return T(oe,J)||(oe=u(oe))&&X(oe,J)}(D,k);(!z||"value"in z&&z.value===void 0)&&(D===d.Transaction.prototype||D instanceof d.Transaction?S(D,k,{get:function(){return this.table(k)},set:function(X){b(this,k,{value:X,writable:!0,configurable:!0,enumerable:!0})}}):D[k]=new d.Table(k,E))})})}function cd(d,h){h.forEach(function(y){for(var v in y)y[v]instanceof d.Table&&delete y[v]})}function mw(d,h){return d._cfg.version-h._cfg.version}function hw(d,h,y,v){var k=d._dbSchema,E=(y.objectStoreNames.contains("$meta")&&!k.$meta&&(k.$meta=id("$meta",Uh("")[0],[]),d._storeNames.push("$meta")),d._createTransaction("readwrite",d._storeNames,k)),D=(E.create(y),E._completion.catch(v),E._reject.bind(E)),z=qe.transless||qe;yn(function(){if(qe.trans=E,qe.transless=z,h!==0)return ml(d,y),oe=h,((X=E).storeNames.includes("$meta")?X.table("$meta").get("version").then(function(J){return J??oe}):ze.resolve(oe)).then(function(ee){var Y=d,G=ee,ne=E,Q=y,Z=[],ee=Y._versions,de=Y._dbSchema=fl(0,Y.idbdb,Q);return(ee=ee.filter(function(ae){return ae._cfg.version>=G})).length===0?ze.resolve():(ee.forEach(function(ae){Z.push(function(){var pe,Te,Me,$e=de,Ee=ae._cfg.dbschema,Ve=(gl(Y,$e,Q),gl(Y,Ee,Q),de=Y._dbSchema=Ee,dd($e,Ee)),Ae=(Ve.add.forEach(function(Xe){ud(Q,Xe[0],Xe[1].primKey,Xe[1].indexes)}),Ve.change.forEach(function(Xe){if(Xe.recreate)throw new Oe.Upgrade("Not yet support for changing primary key");var je=Q.objectStore(Xe.name);Xe.add.forEach(function(lt){return pl(je,lt)}),Xe.change.forEach(function(lt){je.deleteIndex(lt.name),pl(je,lt)}),Xe.del.forEach(function(lt){return je.deleteIndex(lt)})}),ae._cfg.contentUpgrade);if(Ae&&ae._cfg.version>G)return ml(Y,Q),ne._memoizedTables={},pe=B(Ee),Ve.del.forEach(function(Xe){pe[Xe]=$e[Xe]}),cd(Y,[Y.Transaction.prototype]),hl(Y,[Y.Transaction.prototype],i(pe),pe),ne.schema=pe,(Te=ie(Ae))&&An(),Ee=ze.follow(function(){var Xe;(Me=Ae(ne))&&Te&&(Xe=Ds.bind(null,null),Me.then(Xe,Xe))}),Me&&typeof Me.then=="function"?ze.resolve(Me):Ee.then(function(){return Me})}),Z.push(function(pe){var Te,Me,$e=ae._cfg.dbschema;Te=$e,Me=pe,[].slice.call(Me.db.objectStoreNames).forEach(function(Ee){return Te[Ee]==null&&Me.db.deleteObjectStore(Ee)}),cd(Y,[Y.Transaction.prototype]),hl(Y,[Y.Transaction.prototype],Y._storeNames,Y._dbSchema),ne.schema=Y._dbSchema}),Z.push(function(pe){Y.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(Y.idbdb.version/10)===ae._cfg.version?(Y.idbdb.deleteObjectStore("$meta"),delete Y._dbSchema.$meta,Y._storeNames=Y._storeNames.filter(function(Te){return Te!=="$meta"})):pe.objectStore("$meta").put(ae._cfg.version,"version"))})}),function ae(){return Z.length?ze.resolve(Z.shift()(ne.idbtrans)).then(ae):ze.resolve()}().then(function(){qh(de,Q)}))}).catch(D);var X,oe;i(k).forEach(function(J){ud(y,J,k[J].primKey,k[J].indexes)}),ml(d,y),ze.follow(function(){return d.on.populate.fire(E)}).catch(D)})}function pw(d,h){qh(d._dbSchema,h),h.db.version%10!=0||h.objectStoreNames.contains("$meta")||h.db.createObjectStore("$meta").add(Math.ceil(h.db.version/10-1),"version");var y=fl(0,d.idbdb,h);gl(d,d._dbSchema,h);for(var v=0,k=dd(y,d._dbSchema).change;v<k.length;v++){var E=(D=>{if(D.change.length||D.recreate)return console.warn("Unable to patch indexes of table ".concat(D.name," because it has changes on the type of index or primary key.")),{value:void 0};var z=h.objectStore(D.name);D.add.forEach(function(X){Le&&console.debug("Dexie upgrade patch: Creating missing index ".concat(D.name,".").concat(X.src)),pl(z,X)})})(k[v]);if(typeof E=="object")return E.value}}function dd(d,h){var y,v={del:[],add:[],change:[]};for(y in d)h[y]||v.del.push(y);for(y in h){var k=d[y],E=h[y];if(k){var D={name:y,def:E,recreate:!1,del:[],add:[],change:[]};if(""+(k.primKey.keyPath||"")!=""+(E.primKey.keyPath||"")||k.primKey.auto!==E.primKey.auto)D.recreate=!0,v.change.push(D);else{var z=k.idxByName,X=E.idxByName,oe=void 0;for(oe in z)X[oe]||D.del.push(oe);for(oe in X){var J=z[oe],Y=X[oe];J?J.src!==Y.src&&D.change.push(Y):D.add.push(Y)}(0<D.del.length||0<D.add.length||0<D.change.length)&&v.change.push(D)}}else v.add.push([y,E])}return v}function ud(d,h,y,v){var k=d.db.createObjectStore(h,y.keyPath?{keyPath:y.keyPath,autoIncrement:y.auto}:{autoIncrement:y.auto});v.forEach(function(E){return pl(k,E)})}function qh(d,h){i(d).forEach(function(y){h.db.objectStoreNames.contains(y)||(Le&&console.debug("Dexie: Creating missing table",y),ud(h,y,d[y].primKey,d[y].indexes))})}function pl(d,h){d.createIndex(h.name,h.keyPath,{unique:h.unique,multiEntry:h.multi})}function fl(d,h,y){var v={};return w(h.objectStoreNames,0).forEach(function(k){for(var E=y.objectStore(k),D=ad(Bh(oe=E.keyPath),oe||"",!0,!1,!!E.autoIncrement,oe&&typeof oe!="string",!0),z=[],X=0;X<E.indexNames.length;++X){var J=E.index(E.indexNames[X]),oe=J.keyPath,J=ad(J.name,oe,!!J.unique,!!J.multiEntry,!1,oe&&typeof oe!="string",!1);z.push(J)}v[k]=id(k,D,z)}),v}function gl(d,h,y){for(var v=y.db.objectStoreNames,k=0;k<v.length;++k){var E=v[k],D=y.objectStore(E);d._hasGetAll="getAll"in D;for(var z=0;z<D.indexNames.length;++z){var X,oe=D.indexNames[z],J=D.index(oe).keyPath,J=typeof J=="string"?J:"["+w(J).join("+")+"]";h[E]&&(X=h[E].idxByName[J])&&(X.name=oe,delete h[E].idxByName[J],h[E].idxByName[oe]=X)}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&a.WorkerGlobalScope&&a instanceof a.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(d._hasGetAll=!1)}function Uh(d){return d.split(",").map(function(h,y){var k=h.split(":"),v=(v=k[1])==null?void 0:v.trim(),k=(h=k[0].trim()).replace(/([&*]|\+\+)/g,""),E=/^\[/.test(k)?k.match(/^\[(.*)\]$/)[1].split("+"):k;return ad(k,E||null,/\&/.test(h),/\*/.test(h),/\+\+/.test(h),l(E),y===0,v)})}xo.prototype._createTableSchema=id,xo.prototype._parseIndexSyntax=Uh,xo.prototype._parseStoresSpec=function(d,h){var y=this;i(d).forEach(function(v){if(d[v]!==null){var k=y._parseIndexSyntax(d[v]),E=k.shift();if(!E)throw new Oe.Schema("Invalid schema for table "+v+": "+d[v]);if(E.unique=!0,E.multi)throw new Oe.Schema("Primary key cannot be multiEntry*");k.forEach(function(D){if(D.auto)throw new Oe.Schema("Only primary key can be marked as autoIncrement (++)");if(!D.keyPath)throw new Oe.Schema("Index must have a name and cannot be an empty string")}),E=y._createTableSchema(v,E,k),h[v]=E}})},xo.prototype.stores=function(y){var h=this.db,y=(this._cfg.storesSource=this._cfg.storesSource?c(this._cfg.storesSource,y):y,h._versions),v={},k={};return y.forEach(function(E){c(v,E._cfg.storesSource),k=E._cfg.dbschema={},E._parseStoresSpec(v,k)}),h._dbSchema=k,cd(h,[h._allTables,h,h.Transaction.prototype]),hl(h,[h._allTables,h,h.Transaction.prototype,this._cfg.tables],i(k),k),h._storeNames=i(k),this},xo.prototype.upgrade=function(d){return this._cfg.contentUpgrade=De(this._cfg.contentUpgrade||Ye,d),this};var fw=xo;function xo(){}var la=(()=>{var d,h,y;return typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"?(d=new Set,h=new FinalizationRegistry(function(v){d.delete(v)}),{toArray:function(){return Array.from(d).map(function(v){return v.deref()}).filter(function(v){return v!==void 0})},add:function(v){var k=new WeakRef(v._novip);d.add(k),h.register(v._novip,k,k),d.size>v._options.maxConnections&&(k=d.values().next().value,d.delete(k),h.unregister(k))},remove:function(v){if(v)for(var k=d.values(),E=k.next();!E.done;){var D=E.value;if(D.deref()===v._novip)return d.delete(D),void h.unregister(D);E=k.next()}}}):(y=[],{toArray:function(){return y},add:function(v){y.push(v._novip)},remove:function(v){v&&(v=y.indexOf(v._novip))!==-1&&y.splice(v,1)}})})();function md(d,h){var y=d._dbNamesDB;return y||(y=d._dbNamesDB=new Xs(ws,{addons:[],indexedDB:d,IDBKeyRange:h})).version(1).stores({dbnames:"name"}),y.table("dbnames")}function hd(d){return d&&typeof d.databases=="function"}function pd(d){return yn(function(){return qe.letThrough=!0,d()})}function fd(d){return!("from"in d)}var In=function(d,h){var y;if(!this)return y=new In,d&&"d"in d&&c(y,d),y;c(this,arguments.length?{d:1,from:d,to:1<arguments.length?h:d}:{d:0})};function ca(d,h,y){var v=jt(h,y);if(!isNaN(v)){if(0<v)throw RangeError();if(fd(d))return c(d,{from:h,to:y,d:1});var v=d.l,k=d.r;if(jt(y,d.from)<0)return v?ca(v,h,y):d.l={from:h,to:y,d:1,l:null,r:null},Kh(d);if(0<jt(h,d.to))return k?ca(k,h,y):d.r={from:h,to:y,d:1,l:null,r:null},Kh(d);jt(h,d.from)<0&&(d.from=h,d.l=null,d.d=k?k.d+1:1),0<jt(y,d.to)&&(d.to=y,d.r=null,d.d=d.l?d.l.d+1:1),h=!d.r,v&&!d.l&&da(d,v),k&&h&&da(d,k)}}function da(d,h){fd(h)||function y(v,k){var E=k.from,D=k.l,z=k.r;ca(v,E,k.to),D&&y(v,D),z&&y(v,z)}(d,h)}function Hh(d,h){var y=yl(h),v=y.next();if(!v.done)for(var k=v.value,E=yl(d),D=E.next(k.from),z=D.value;!v.done&&!D.done;){if(jt(z.from,k.to)<=0&&0<=jt(z.to,k.from))return!0;jt(k.from,z.from)<0?k=(v=y.next(z.from)).value:z=(D=E.next(k.from)).value}return!1}function yl(d){var h=fd(d)?null:{s:0,n:d};return{next:function(y){for(var v=0<arguments.length;h;)switch(h.s){case 0:if(h.s=1,v)for(;h.n.l&&jt(y,h.n.from)<0;)h={up:h,n:h.n.l,s:1};else for(;h.n.l;)h={up:h,n:h.n.l,s:1};case 1:if(h.s=2,!v||jt(y,h.n.to)<=0)return{value:h.n,done:!1};case 2:if(h.n.r){h.s=3,h={up:h,n:h.n.r,s:0};continue}case 3:h=h.up}return{done:!0}}}}function Kh(d){var h,y,v,k=(((k=d.r)==null?void 0:k.d)||0)-(((k=d.l)==null?void 0:k.d)||0),k=1<k?"r":k<-1?"l":"";k&&(h=k=="r"?"l":"r",y=s({},d),v=d[k],d.from=v.from,d.to=v.to,d[k]=v[k],y[k]=v[h],(d[h]=y).d=Vh(y)),d.d=Vh(d)}function Vh(y){var h=y.r,y=y.l;return(h?y?Math.max(h.d,y.d):h.d:y?y.d:0)+1}function bl(d,h){return i(h).forEach(function(y){d[y]?da(d[y],h[y]):d[y]=function v(k){var E,D,z={};for(E in k)f(k,E)&&(D=k[E],z[E]=!D||typeof D!="object"||R.has(D.constructor)?D:v(D));return z}(h[y])}),d}function gd(d,h){return d.all||h.all||Object.keys(d).some(function(y){return h[y]&&Hh(h[y],d[y])})}g(In.prototype,((_e={add:function(d){return da(this,d),this},addKey:function(d){return ca(this,d,d),this},addKeys:function(d){var h=this;return d.forEach(function(y){return ca(h,y,y)}),this},hasKey:function(d){var h=yl(this).next(d).value;return h&&jt(h.from,d)<=0&&0<=jt(h.to,d)}})[K]=function(){return yl(this)},_e));var $r={},yd={},bd=!1;function xl(d){bl(yd,d),bd||(bd=!0,setTimeout(function(){bd=!1,xd(yd,!(yd={}))},0))}function xd(d,h){h===void 0&&(h=!1);var y=new Set;if(d.all)for(var v=0,k=Object.values($r);v<k.length;v++)Yh(z=k[v],d,y,h);else for(var E in d){var D,z,E=/^idb\:\/\/(.*)\/(.*)\//.exec(E);E&&(D=E[1],E=E[2],z=$r["idb://".concat(D,"/").concat(E)])&&Yh(z,d,y,h)}y.forEach(function(X){return X()})}function Yh(d,h,y,v){for(var k=[],E=0,D=Object.entries(d.queries.query);E<D.length;E++){for(var z=D[E],X=z[0],oe=[],J=0,Y=z[1];J<Y.length;J++){var G=Y[J];gd(h,G.obsSet)?G.subscribers.forEach(function(ee){return y.add(ee)}):v&&oe.push(G)}v&&k.push([X,oe])}if(v)for(var ne=0,Q=k;ne<Q.length;ne++){var Z=Q[ne],X=Z[0],oe=Z[1];d.queries.query[X]=oe}}function gw(d){var h=d._state,y=d._deps.indexedDB;if(h.isBeingOpened||d.idbdb)return h.dbReadyPromise.then(function(){return h.dbOpenError?Pt(h.dbOpenError):d});h.isBeingOpened=!0,h.dbOpenError=null,h.openComplete=!1;var v=h.openCanceller,k=Math.round(10*d.verno),E=!1;function D(){if(h.openCanceller!==v)throw new Oe.DatabaseClosed("db.open() was cancelled")}function z(){return new ze(function(G,ne){if(D(),!y)throw new Oe.MissingAPI;var Q=d.name,Z=h.autoSchema||!k?y.open(Q):y.open(Q,k);if(!Z)throw new Oe.MissingAPI;Z.onerror=ks(ne),Z.onblocked=et(d._fireOnBlocked),Z.onupgradeneeded=et(function(ee){var de;J=Z.transaction,h.autoSchema&&!d._options.allowEmptyDB?(Z.onerror=ra,J.abort(),Z.result.close(),(de=y.deleteDatabase(Q)).onsuccess=de.onerror=et(function(){ne(new Oe.NoSuchDatabase("Database ".concat(Q," doesnt exist")))})):(J.onerror=ks(ne),de=ee.oldVersion>Math.pow(2,62)?0:ee.oldVersion,Y=de<1,d.idbdb=Z.result,E&&pw(d,J),hw(d,de/10,J,ne))},ne),Z.onsuccess=et(function(){J=null;var ee,de,ae,pe,Te,Me,$e=d.idbdb=Z.result,Ee=w($e.objectStoreNames);if(0<Ee.length)try{var Ve=$e.transaction((Te=Ee).length===1?Te[0]:Te,"readonly");if(h.autoSchema)Me=$e,pe=Ve,(ae=d).verno=Me.version/10,pe=ae._dbSchema=fl(0,Me,pe),ae._storeNames=w(Me.objectStoreNames,0),hl(ae,[ae._allTables],i(pe),pe);else if(gl(d,d._dbSchema,Ve),de=Ve,((de=dd(fl(0,(ee=d).idbdb,de),ee._dbSchema)).add.length||de.change.some(function(Ae){return Ae.add.length||Ae.change.length}))&&!E)return console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this."),$e.close(),k=$e.version+1,E=!0,G(z());ml(d,Ve)}catch{}la.add(d),$e.onversionchange=et(function(Ae){h.vcFired=!0,d.on("versionchange").fire(Ae)}),$e.onclose=et(function(){d.close({disableAutoOpen:!1})}),Y&&(Ee=d._deps,Te=Q,hd(Me=Ee.indexedDB)||Te===ws||md(Me,Ee.IDBKeyRange).put({name:Te}).catch(Ye)),G()},ne)}).catch(function(G){switch(G==null?void 0:G.name){case"UnknownError":if(0<h.PR1398_maxLoop)return h.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),z();break;case"VersionError":if(0<k)return k=0,z()}return ze.reject(G)})}var X,oe=h.dbReadyResolve,J=null,Y=!1;return ze.race([v,(typeof navigator>"u"?ze.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(G){function ne(){return indexedDB.databases().finally(G)}X=setInterval(ne,100),ne()}).finally(function(){return clearInterval(X)}):Promise.resolve()).then(z)]).then(function(){return D(),h.onReadyBeingFired=[],ze.resolve(pd(function(){return d.on.ready.fire(d.vip)})).then(function G(){var ne;if(0<h.onReadyBeingFired.length)return ne=h.onReadyBeingFired.reduce(De,Ye),h.onReadyBeingFired=[],ze.resolve(pd(function(){return ne(d.vip)})).then(G)})}).finally(function(){h.openCanceller===v&&(h.onReadyBeingFired=null,h.isBeingOpened=!1)}).catch(function(G){h.dbOpenError=G;try{J&&J.abort()}catch{}return v===h.openCanceller&&d._close(),Pt(G)}).finally(function(){h.openComplete=!0,oe()}).then(function(){var G;return Y&&(G={},d.tables.forEach(function(ne){ne.schema.indexes.forEach(function(Q){Q.name&&(G["idb://".concat(d.name,"/").concat(ne.name,"/").concat(Q.name)]=new In(-1/0,[[[]]]))}),G["idb://".concat(d.name,"/").concat(ne.name,"/")]=G["idb://".concat(d.name,"/").concat(ne.name,"/:dels")]=new In(-1/0,[[[]]])}),hr(oa).fire(G),xd(G,!0)),d})}function vd(d){function h(E){return d.next(E)}var y=k(h),v=k(function(E){return d.throw(E)});function k(E){return function(z){var z=E(z),X=z.value;return z.done?X:X&&typeof X.then=="function"?X.then(y,v):l(X)?Promise.all(X).then(y,v):y(X)}}return k(h)()}function vl(d,h,y){for(var v=l(d)?d.slice():[d],k=0;k<y;++k)v.push(h);return v}var yw={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(d){return s(s({},d),{table:function(v){var y=d.table(v),v=y.schema,k={},E=[];function D(G,ne,Q){var ae=ia(G),Z=k[ae]=k[ae]||[],ee=G==null?0:typeof G=="string"?1:G.length,de=0<ne,ae=s(s({},Q),{name:de?"".concat(ae,"(virtual-from:").concat(Q.name,")"):Q.name,lowLevelIndex:Q,isVirtual:de,keyTail:ne,keyLength:ee,extractKey:ld(G),unique:!de&&Q.unique});return Z.push(ae),ae.isPrimaryKey||E.push(ae),1<ee&&D(ee===2?G[0]:G.slice(0,ee-1),ne+1,Q),Z.sort(function(pe,Te){return pe.keyTail-Te.keyTail}),ae}var z=D(v.primaryKey.keyPath,0,v.primaryKey);k[":id"]=[z];for(var X=0,oe=v.indexes;X<oe.length;X++){var J=oe[X];D(J.keyPath,0,J)}function Y(G){var ne,Q=G.query.index;return Q.isVirtual?s(s({},G),{query:{index:Q.lowLevelIndex,range:(ne=G.query.range,Q=Q.keyTail,{type:ne.type===1?2:ne.type,lower:vl(ne.lower,ne.lowerOpen?d.MAX_KEY:d.MIN_KEY,Q),lowerOpen:!0,upper:vl(ne.upper,ne.upperOpen?d.MIN_KEY:d.MAX_KEY,Q),upperOpen:!0})}}):G}return s(s({},y),{schema:s(s({},v),{primaryKey:z,indexes:E,getIndexByKeyPath:function(G){return(G=k[ia(G)])&&G[0]}}),count:function(G){return y.count(Y(G))},query:function(G){return y.query(Y(G))},openCursor:function(G){var ne=G.query.index,Q=ne.keyTail,Z=ne.keyLength;return ne.isVirtual?y.openCursor(Y(G)).then(function(de){return de&&ee(de)}):y.openCursor(G);function ee(de){return Object.create(de,{continue:{value:function(ae){ae!=null?de.continue(vl(ae,G.reverse?d.MAX_KEY:d.MIN_KEY,Q)):G.unique?de.continue(de.key.slice(0,Z).concat(G.reverse?d.MIN_KEY:d.MAX_KEY,Q)):de.continue()}},continuePrimaryKey:{value:function(ae,pe){de.continuePrimaryKey(vl(ae,d.MAX_KEY,Q),pe)}},primaryKey:{get:function(){return de.primaryKey}},key:{get:function(){var ae=de.key;return Z===1?ae[0]:ae.slice(0,Z)}},value:{get:function(){return de.value}}})}}})}})}};function Sd(d,h,y,v){return y=y||{},v=v||"",i(d).forEach(function(k){var E,D,z;f(h,k)?(E=d[k],D=h[k],typeof E=="object"&&typeof D=="object"&&E&&D?(z=q(E))!==q(D)?y[v+k]=h[k]:z==="Object"?Sd(E,D,y,v+k+"."):E!==D&&(y[v+k]=h[k]):E!==D&&(y[v+k]=h[k])):y[v+k]=void 0}),i(h).forEach(function(k){f(d,k)||(y[v+k]=h[k])}),y}function wd(d,h){return h.type==="delete"?h.keys:h.keys||h.values.map(d.extractKey)}var bw={stack:"dbcore",name:"HooksMiddleware",level:2,create:function(d){return s(s({},d),{table:function(h){var y=d.table(h),v=y.schema.primaryKey;return s(s({},y),{mutate:function(k){var E=qe.trans,D=E.table(h).hook,z=D.deleting,X=D.creating,oe=D.updating;switch(k.type){case"add":if(X.fire===Ye)break;return E._promise("readwrite",function(){return J(k)},!0);case"put":if(X.fire===Ye&&oe.fire===Ye)break;return E._promise("readwrite",function(){return J(k)},!0);case"delete":if(z.fire===Ye)break;return E._promise("readwrite",function(){return J(k)},!0);case"deleteRange":if(z.fire===Ye)break;return E._promise("readwrite",function(){return function Y(G,ne,Q){return y.query({trans:G,values:!1,query:{index:v,range:ne},limit:Q}).then(function(Z){var ee=Z.result;return J({type:"delete",keys:ee,trans:G}).then(function(de){return 0<de.numFailures?Promise.reject(de.failures[0]):ee.length<Q?{failures:[],numFailures:0,lastResult:void 0}:Y(G,s(s({},ne),{lower:ee[ee.length-1],lowerOpen:!0}),Q)})})}(k.trans,k.range,1e4)},!0)}return y.mutate(k);function J(Y){var G,ne,Q,Z=qe.trans,ee=Y.keys||wd(v,Y);if(ee)return(Y=Y.type==="add"||Y.type==="put"?s(s({},Y),{keys:ee}):s({},Y)).type!=="delete"&&(Y.values=r([],Y.values)),Y.keys&&(Y.keys=r([],Y.keys)),G=y,Q=ee,((ne=Y).type==="add"?Promise.resolve([]):G.getMany({trans:ne.trans,keys:Q,cache:"immutable"})).then(function(de){var ae=ee.map(function(pe,Te){var Me,$e,Ee,Ve=de[Te],Ae={onerror:null,onsuccess:null};return Y.type==="delete"?z.fire.call(Ae,pe,Ve,Z):Y.type==="add"||Ve===void 0?(Me=X.fire.call(Ae,pe,Y.values[Te],Z),pe==null&&Me!=null&&(Y.keys[Te]=pe=Me,v.outbound||A(Y.values[Te],v.keyPath,pe))):(Me=Sd(Ve,Y.values[Te]),($e=oe.fire.call(Ae,Me,pe,Ve,Z))&&(Ee=Y.values[Te],Object.keys($e).forEach(function(Xe){f(Ee,Xe)?Ee[Xe]=$e[Xe]:A(Ee,Xe,$e[Xe])}))),Ae});return y.mutate(Y).then(function(pe){for(var Te=pe.failures,Me=pe.results,$e=pe.numFailures,pe=pe.lastResult,Ee=0;Ee<ee.length;++Ee){var Ve=(Me||ee)[Ee],Ae=ae[Ee];Ve==null?Ae.onerror&&Ae.onerror(Te[Ee]):Ae.onsuccess&&Ae.onsuccess(Y.type==="put"&&de[Ee]?Y.values[Ee]:Ve)}return{failures:Te,results:Me,numFailures:$e,lastResult:pe}}).catch(function(pe){return ae.forEach(function(Te){return Te.onerror&&Te.onerror(pe)}),Promise.reject(pe)})});throw new Error("Keys missing")}}})}})}};function Xh(d,h,y){try{if(!h||h.keys.length<d.length)return null;for(var v=[],k=0,E=0;k<h.keys.length&&E<d.length;++k)jt(h.keys[k],d[E])===0&&(v.push(y?$(h.values[k]):h.values[k]),++E);return v.length===d.length?v:null}catch{return null}}var xw={stack:"dbcore",level:-1,create:function(d){return{table:function(h){var y=d.table(h);return s(s({},y),{getMany:function(v){var k;return v.cache?(k=Xh(v.keys,v.trans._cache,v.cache==="clone"))?ze.resolve(k):y.getMany(v).then(function(E){return v.trans._cache={keys:v.keys,values:v.cache==="clone"?$(E):E},E}):y.getMany(v)},mutate:function(v){return v.type!=="add"&&(v.trans._cache=null),y.mutate(v)}})}}}};function Gh(d,h){return d.trans.mode==="readonly"&&!!d.subscr&&!d.trans.explicit&&d.trans.db._options.cache!=="disabled"&&!h.schema.primaryKey.outbound}function Jh(d,h){switch(d){case"query":return h.values&&!h.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var vw={stack:"dbcore",level:0,name:"Observability",create:function(d){var h=d.schema.name,y=new In(d.MIN_KEY,d.MAX_KEY);return s(s({},d),{transaction:function(v,k,E){if(qe.subscr&&k!=="readonly")throw new Oe.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(qe.querier));return d.transaction(v,k,E)},table:function(v){function k(ee){var Z,ee=ee.query;return[Z=ee.index,new In((Z=(ee=ee.range).lower)!=null?Z:d.MIN_KEY,(Z=ee.upper)!=null?Z:d.MAX_KEY)]}var E=d.table(v),D=E.schema,z=D.primaryKey,X=D.indexes,oe=z.extractKey,J=z.outbound,Y=z.autoIncrement&&X.filter(function(Q){return Q.compound&&Q.keyPath.includes(z.keyPath)}),G=s(s({},E),{mutate:function(Q){function Z(je){return je="idb://".concat(h,"/").concat(v,"/").concat(je),Te[je]||(Te[je]=new In)}var ee,de,ae,pe=Q.trans,Te=Q.mutatedParts||(Q.mutatedParts={}),Me=Z(""),$e=Z(":dels"),Ee=Q.type,Ae=Q.type==="deleteRange"?[Q.range]:Q.type==="delete"?[Q.keys]:Q.values.length<50?[wd(z,Q).filter(function(je){return je}),Q.values]:[],Ve=Ae[0],Ae=Ae[1],Xe=Q.trans._cache;return l(Ve)?(Me.addKeys(Ve),(Ee=Ee==="delete"||Ve.length===Ae.length?Xh(Ve,Xe):null)||$e.addKeys(Ve),(Ee||Ae)&&(ee=Z,de=Ee,ae=Ae,D.indexes.forEach(function(je){var lt=ee(je.name||"");function ct(kt){return kt!=null?je.extractKey(kt):null}function pt(kt){je.multiEntry&&l(kt)?kt.forEach(function(es){return lt.addKey(es)}):lt.addKey(kt)}(de||ae).forEach(function(kt,On){var ht=de&&ct(de[On]),On=ae&&ct(ae[On]);jt(ht,On)!==0&&(ht!=null&&pt(ht),On!=null)&&pt(On)})}))):Ve?(Ae={from:(Xe=Ve.lower)!=null?Xe:d.MIN_KEY,to:(Ee=Ve.upper)!=null?Ee:d.MAX_KEY},$e.add(Ae),Me.add(Ae)):(Me.add(y),$e.add(y),D.indexes.forEach(function(je){return Z(je.name).add(y)})),E.mutate(Q).then(function(je){return!Ve||Q.type!=="add"&&Q.type!=="put"||(Me.addKeys(je.results),Y&&Y.forEach(function(lt){for(var ct=Q.values.map(function(ht){return lt.extractKey(ht)}),pt=lt.keyPath.findIndex(function(ht){return ht===z.keyPath}),kt=0,es=je.results.length;kt<es;++kt)ct[kt][pt]=je.results[kt];Z(lt.name).addKeys(ct)})),pe.mutatedParts=bl(pe.mutatedParts||{},Te),je})}}),ne={get:function(Q){return[z,new In(Q.key)]},getMany:function(Q){return[z,new In().addKeys(Q.keys)]},count:k,query:k,openCursor:k};return i(ne).forEach(function(Q){G[Q]=function(Z){var ee=qe.subscr,de=!!ee,ae=Gh(qe,E)&&Jh(Q,Z)?Z.obsSet={}:ee;if(de){var pe,ee=function(Ae){return Ae="idb://".concat(h,"/").concat(v,"/").concat(Ae),ae[Ae]||(ae[Ae]=new In)},Te=ee(""),Me=ee(":dels"),de=ne[Q](Z),$e=de[0],de=de[1];if((Q==="query"&&$e.isPrimaryKey&&!Z.values?Me:ee($e.name||"")).add(de),!$e.isPrimaryKey){if(Q!=="count")return pe=Q==="query"&&J&&Z.values&&E.query(s(s({},Z),{values:!1})),E[Q].apply(this,arguments).then(function(Ae){if(Q==="query"){if(J&&Z.values)return pe.then(function(ct){return ct=ct.result,Te.addKeys(ct),Ae});var Xe=Z.values?Ae.result.map(oe):Ae.result;(Z.values?Te:Me).addKeys(Xe)}else{var je,lt;if(Q==="openCursor")return lt=Z.values,(je=Ae)&&Object.create(je,{key:{get:function(){return Me.addKey(je.primaryKey),je.key}},primaryKey:{get:function(){var ct=je.primaryKey;return Me.addKey(ct),ct}},value:{get:function(){return lt&&Te.addKey(je.primaryKey),je.value}}})}return Ae});Me.add(y)}}return E[Q].apply(this,arguments)}}),G}})}};function Qh(d,h,y){var v;return y.numFailures===0?h:h.type==="deleteRange"||(v=h.keys?h.keys.length:"values"in h&&h.values?h.values.length:1,y.numFailures===v)?null:(v=s({},h),l(v.keys)&&(v.keys=v.keys.filter(function(k,E){return!(E in y.failures)})),"values"in v&&l(v.values)&&(v.values=v.values.filter(function(k,E){return!(E in y.failures)})),v)}function _d(d,h){return y=d,((v=h).lower===void 0||(v.lowerOpen?0<jt(y,v.lower):0<=jt(y,v.lower)))&&(y=d,(v=h).upper===void 0||(v.upperOpen?jt(y,v.upper)<0:jt(y,v.upper)<=0));var y,v}function Zh(d,h,y,v,k,E){var D,z,X,oe,J,Y,G;return!y||y.length===0||(D=h.query.index,z=D.multiEntry,X=h.query.range,oe=v.schema.primaryKey.extractKey,J=D.extractKey,Y=(D.lowLevelIndex||D).extractKey,(v=y.reduce(function(ne,Q){var Z=ne,ee=[];if(Q.type==="add"||Q.type==="put")for(var de=new In,ae=Q.values.length-1;0<=ae;--ae){var pe,Te=Q.values[ae],Me=oe(Te);!de.hasKey(Me)&&(pe=J(Te),z&&l(pe)?pe.some(function(Xe){return _d(Xe,X)}):_d(pe,X))&&(de.addKey(Me),ee.push(Te))}switch(Q.type){case"add":var $e=new In().addKeys(h.values?ne.map(function(je){return oe(je)}):ne),Z=ne.concat(h.values?ee.filter(function(je){return je=oe(je),!$e.hasKey(je)&&($e.addKey(je),!0)}):ee.map(function(je){return oe(je)}).filter(function(je){return!$e.hasKey(je)&&($e.addKey(je),!0)}));break;case"put":var Ee=new In().addKeys(Q.values.map(function(je){return oe(je)}));Z=ne.filter(function(je){return!Ee.hasKey(h.values?oe(je):je)}).concat(h.values?ee:ee.map(function(je){return oe(je)}));break;case"delete":var Ve=new In().addKeys(Q.keys);Z=ne.filter(function(je){return!Ve.hasKey(h.values?oe(je):je)});break;case"deleteRange":var Ae=Q.range;Z=ne.filter(function(je){return!_d(oe(je),Ae)})}return Z},d))===d)?d:(G=function(ne,Q){return jt(Y(ne),Y(Q))||jt(oe(ne),oe(Q))},v.sort(h.direction==="prev"||h.direction==="prevunique"?function(ne,Q){return G(Q,ne)}:G),h.limit&&h.limit<1/0&&(v.length>h.limit?v.length=h.limit:d.length===h.limit&&v.length<h.limit&&(k.dirty=!0)),E?Object.freeze(v):v)}function ep(d,h){return jt(d.lower,h.lower)===0&&jt(d.upper,h.upper)===0&&!!d.lowerOpen==!!h.lowerOpen&&!!d.upperOpen==!!h.upperOpen}function Sw(d,h){return((y,v,k,E)=>{if(y===void 0)return v!==void 0?-1:0;if(v===void 0)return 1;if((y=jt(y,v))===0){if(k&&E)return 0;if(k)return 1;if(E)return-1}return y})(d.lower,h.lower,d.lowerOpen,h.lowerOpen)<=0&&0<=((y,v,k,E)=>{if(y===void 0)return v!==void 0?1:0;if(v===void 0)return-1;if((y=jt(y,v))===0){if(k&&E)return 0;if(k)return-1;if(E)return 1}return y})(d.upper,h.upper,d.upperOpen,h.upperOpen)}function ww(d,h,y,v){d.subscribers.add(y),v.addEventListener("abort",function(){var k,E;d.subscribers.delete(y),d.subscribers.size===0&&(k=d,E=h,setTimeout(function(){k.subscribers.size===0&&W(E,k)},3e3))})}var _w={stack:"dbcore",level:0,name:"Cache",create:function(d){var h=d.schema.name;return s(s({},d),{transaction:function(y,v,k){var E,D,z=d.transaction(y,v,k);return v==="readwrite"&&(k=(E=new AbortController).signal,z.addEventListener("abort",(D=function(X){return function(){if(E.abort(),v==="readwrite"){for(var oe=new Set,J=0,Y=y;J<Y.length;J++){var G=Y[J],ne=$r["idb://".concat(h,"/").concat(G)];if(ne){var Q=d.table(G),Z=ne.optimisticOps.filter(function(je){return je.trans===z});if(z._explicit&&X&&z.mutatedParts)for(var ee=0,de=Object.values(ne.queries.query);ee<de.length;ee++)for(var ae=0,pe=($e=de[ee]).slice();ae<pe.length;ae++)gd((Ee=pe[ae]).obsSet,z.mutatedParts)&&(W($e,Ee),Ee.subscribers.forEach(function(je){return oe.add(je)}));else if(0<Z.length){ne.optimisticOps=ne.optimisticOps.filter(function(je){return je.trans!==z});for(var Te=0,Me=Object.values(ne.queries.query);Te<Me.length;Te++)for(var $e,Ee,Ve,Ae=0,Xe=($e=Me[Te]).slice();Ae<Xe.length;Ae++)(Ee=Xe[Ae]).res!=null&&z.mutatedParts&&(X&&!Ee.dirty?(Ve=Object.isFrozen(Ee.res),Ve=Zh(Ee.res,Ee.req,Z,Q,Ee,Ve),Ee.dirty?(W($e,Ee),Ee.subscribers.forEach(function(je){return oe.add(je)})):Ve!==Ee.res&&(Ee.res=Ve,Ee.promise=ze.resolve({result:Ve}))):(Ee.dirty&&W($e,Ee),Ee.subscribers.forEach(function(je){return oe.add(je)})))}}}oe.forEach(function(je){return je()})}}})(!1),{signal:k}),z.addEventListener("error",D(!1),{signal:k}),z.addEventListener("complete",D(!0),{signal:k})),z},table:function(y){var v=d.table(y),k=v.schema.primaryKey;return s(s({},v),{mutate:function(E){var D,z=qe.trans;return!k.outbound&&z.db._options.cache!=="disabled"&&!z.explicit&&z.idbtrans.mode==="readwrite"&&(D=$r["idb://".concat(h,"/").concat(y)])?(z=v.mutate(E),E.type!=="add"&&E.type!=="put"||!(50<=E.values.length||wd(k,E).some(function(X){return X==null}))?(D.optimisticOps.push(E),E.mutatedParts&&xl(E.mutatedParts),z.then(function(X){0<X.numFailures&&(W(D.optimisticOps,E),(X=Qh(0,E,X))&&D.optimisticOps.push(X),E.mutatedParts)&&xl(E.mutatedParts)}),z.catch(function(){W(D.optimisticOps,E),E.mutatedParts&&xl(E.mutatedParts)})):z.then(function(X){var oe=Qh(0,s(s({},E),{values:E.values.map(function(J,Y){var G;return X.failures[Y]?J:(A(G=(G=k.keyPath)!=null&&G.includes(".")?$(J):s({},J),k.keyPath,X.results[Y]),G)})}),X);D.optimisticOps.push(oe),queueMicrotask(function(){return E.mutatedParts&&xl(E.mutatedParts)})}),z):v.mutate(E)},query:function(E){var D,z,X,oe,J,Y,G;return Gh(qe,v)&&Jh("query",E)?(D=((X=qe.trans)==null?void 0:X.db._options.cache)==="immutable",z=(X=qe).requery,X=X.signal,Y=((ne,Q,Z,ee)=>{var de=$r["idb://".concat(ne,"/").concat(Q)];if(!de)return[];if(!(ne=de.queries[Z]))return[null,!1,de,null];var ae=ne[(ee.query?ee.query.index.name:null)||""];if(!ae)return[null,!1,de,null];switch(Z){case"query":var pe=(Te=ee.direction)!=null?Te:"next",Te=ae.find(function(Me){var $e;return Me.req.limit===ee.limit&&Me.req.values===ee.values&&(($e=Me.req.direction)!=null?$e:"next")===pe&&ep(Me.req.query.range,ee.query.range)});return Te?[Te,!0,de,ae]:[ae.find(function(Me){var $e;return("limit"in Me.req?Me.req.limit:1/0)>=ee.limit&&(($e=Me.req.direction)!=null?$e:"next")===pe&&(!ee.values||Me.req.values)&&Sw(Me.req.query.range,ee.query.range)}),!1,de,ae];case"count":return Te=ae.find(function(Me){return ep(Me.req.query.range,ee.query.range)}),[Te,!!Te,de,ae]}})(h,y,"query",E),G=Y[0],oe=Y[2],J=Y[3],G&&Y[1]?G.obsSet=E.obsSet:(Y=v.query(E).then(function(ne){var Q=ne.result;if(G&&(G.res=Q),D){for(var Z=0,ee=Q.length;Z<ee;++Z)Object.freeze(Q[Z]);Object.freeze(Q)}else ne.result=$(Q);return ne}).catch(function(ne){return J&&G&&W(J,G),Promise.reject(ne)}),G={obsSet:E.obsSet,promise:Y,subscribers:new Set,type:"query",req:E,dirty:!1},J?J.push(G):(J=[G],(oe=oe||($r["idb://".concat(h,"/").concat(y)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[E.query.index.name||""]=J)),ww(G,J,z,X),G.promise.then(function(ne){return{result:Zh(ne.result,E,oe==null?void 0:oe.optimisticOps,v,G,D)}})):v.query(E)}})}})}};function Sl(d,h){return new Proxy(d,{get:function(y,v,k){return v==="db"?h:Reflect.get(y,v,k)}})}en.prototype.version=function(d){if(isNaN(d)||d<.1)throw new Oe.Type("Given version is not a positive number");if(d=Math.round(10*d)/10,this.idbdb||this._state.isBeingOpened)throw new Oe.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,d);var h=this._versions,y=h.filter(function(v){return v._cfg.version===d})[0];return y||(y=new this.Version(d),h.push(y),h.sort(mw),y.stores({}),this._state.autoSchema=!1),y},en.prototype._whenReady=function(d){var h=this;return this.idbdb&&(this._state.openComplete||qe.letThrough||this._vip)?d():new ze(function(y,v){if(h._state.openComplete)return v(new Oe.DatabaseClosed(h._state.dbOpenError));if(!h._state.isBeingOpened){if(!h._state.autoOpen)return void v(new Oe.DatabaseClosed);h.open().catch(Ye)}h._state.dbReadyPromise.then(y,v)}).then(d)},en.prototype.use=function(k){var h=k.stack,y=k.create,v=k.level,k=k.name,E=(k&&this.unuse({stack:h,name:k}),this._middlewares[h]||(this._middlewares[h]=[]));return E.push({stack:h,create:y,level:v??10,name:k}),E.sort(function(D,z){return D.level-z.level}),this},en.prototype.unuse=function(d){var h=d.stack,y=d.name,v=d.create;return h&&this._middlewares[h]&&(this._middlewares[h]=this._middlewares[h].filter(function(k){return v?k.create!==v:!!y&&k.name!==y})),this},en.prototype.open=function(){var d=this;return Lt(Kt,function(){return gw(d)})},en.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var d=this._state;if(la.remove(this),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}d.isBeingOpened||(d.dbReadyPromise=new ze(function(h){d.dbReadyResolve=h}),d.openCanceller=new ze(function(h,y){d.cancelOpen=y}))},en.prototype.close=function(h){var h=(h===void 0?{disableAutoOpen:!0}:h).disableAutoOpen,y=this._state;h?(y.isBeingOpened&&y.cancelOpen(new Oe.DatabaseClosed),this._close(),y.autoOpen=!1,y.dbOpenError=new Oe.DatabaseClosed):(this._close(),y.autoOpen=this._options.autoOpen||y.isBeingOpened,y.openComplete=!1,y.dbOpenError=null)},en.prototype.delete=function(d){var h=this,y=(d===void 0&&(d={disableAutoOpen:!0}),0<arguments.length&&typeof arguments[0]!="object"),v=this._state;return new ze(function(k,E){function D(){h.close(d);var z=h._deps.indexedDB.deleteDatabase(h.name);z.onsuccess=et(function(){var X,oe,J;X=h._deps,oe=h.name,hd(J=X.indexedDB)||oe===ws||md(J,X.IDBKeyRange).delete(oe).catch(Ye),k()}),z.onerror=ks(E),z.onblocked=h._fireOnBlocked}if(y)throw new Oe.InvalidArgument("Invalid closeOptions argument to db.delete()");v.isBeingOpened?v.dbReadyPromise.then(D):D()})},en.prototype.backendDB=function(){return this.idbdb},en.prototype.isOpen=function(){return this.idbdb!==null},en.prototype.hasBeenClosed=function(){var d=this._state.dbOpenError;return d&&d.name==="DatabaseClosed"},en.prototype.hasFailed=function(){return this._state.dbOpenError!==null},en.prototype.dynamicallyOpened=function(){return this._state.autoSchema},Object.defineProperty(en.prototype,"tables",{get:function(){var d=this;return i(this._allTables).map(function(h){return d._allTables[h]})},enumerable:!1,configurable:!0}),en.prototype.transaction=function(){var d=(function(h,y,v){var k=arguments.length;if(k<2)throw new Oe.InvalidArgument("Too few arguments");for(var E=new Array(k-1);--k;)E[k-1]=arguments[k];return v=E.pop(),[h,O(E),v]}).apply(this,arguments);return this._transaction.apply(this,d)},en.prototype._transaction=function(d,h,y){var v,k,E=this,D=qe.trans,z=(D&&D.db===this&&d.indexOf("!")===-1||(D=null),d.indexOf("?")!==-1);d=d.replace("!","").replace("?","");try{if(k=h.map(function(oe){if(oe=oe instanceof E.Table?oe.name:oe,typeof oe!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return oe}),d=="r"||d===_s)v=_s;else{if(d!="rw"&&d!=go)throw new Oe.InvalidArgument("Invalid transaction mode: "+d);v=go}if(D){if(D.mode===_s&&v===go){if(!z)throw new Oe.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");D=null}D&&k.forEach(function(oe){if(D&&D.storeNames.indexOf(oe)===-1){if(!z)throw new Oe.SubTransaction("Table "+oe+" not included in parent transaction.");D=null}}),z&&D&&!D.active&&(D=null)}}catch(oe){return D?D._promise(null,function(J,Y){Y(oe)}):Pt(oe)}var X=(function oe(J,Y,G,ne,Q){return ze.resolve().then(function(){var ae=qe.transless||qe,Z=J._createTransaction(Y,G,J._dbSchema,ne),ae=(Z.explicit=!0,{trans:Z,transless:ae});if(ne)Z.idbtrans=ne.idbtrans;else try{Z.create(),Z.idbtrans._explicit=!0,J._state.PR1398_maxLoop=3}catch(pe){return pe.name===ft.InvalidState&&J.isOpen()&&0<--J._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),J.close({disableAutoOpen:!1}),J.open().then(function(){return oe(J,Y,G,null,Q)})):Pt(pe)}var ee,de=ie(Q),ae=(de&&An(),ze.follow(function(){var pe;(ee=Q.call(Z,Z))&&(de?(pe=Ds.bind(null,null),ee.then(pe,pe)):typeof ee.next=="function"&&typeof ee.throw=="function"&&(ee=vd(ee)))},ae));return(ee&&typeof ee.then=="function"?ze.resolve(ee).then(function(pe){return Z.active?pe:Pt(new Oe.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):ae.then(function(){return ee})).then(function(pe){return ne&&Z._resolve(),Z._completion.then(function(){return pe})}).catch(function(pe){return Z._reject(pe),Pt(pe)})})}).bind(null,this,v,k,D,y);return D?D._promise(v,X,"lock"):qe.trans?Lt(qe.transless,function(){return E._whenReady(X)}):this._whenReady(X)},en.prototype.table=function(d){if(f(this._allTables,d))return this._allTables[d];throw new Oe.InvalidTable("Table ".concat(d," does not exist"))};var Xs=en;function en(d,h){var y,v,k,E,D,z=this,X=(this._middlewares={},this.verno=0,en.dependencies),X=(this._options=h=s({addons:en.addons,autoOpen:!0,indexedDB:X.indexedDB,IDBKeyRange:X.IDBKeyRange,cache:"cloned",maxConnections:1e3},h),this._deps={indexedDB:h.indexedDB,IDBKeyRange:h.IDBKeyRange},h.addons),oe=(this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this,{dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:Ye,dbReadyPromise:null,cancelOpen:Ye,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:h.autoOpen}),J=(oe.dbReadyPromise=new ze(function(Y){oe.dbReadyResolve=Y}),oe.openCanceller=new ze(function(Y,G){oe.cancelOpen=G}),this._state=oe,this.name=d,this.on=na(this,"populate","blocked","versionchange","close",{ready:[De,Ye]}),this.once=function(Y,G){var ne=function(){for(var Q=[],Z=0;Z<arguments.length;Z++)Q[Z]=arguments[Z];z.on(Y).unsubscribe(ne),G.apply(z,Q)};return z.on(Y,ne)},this.on.ready.subscribe=M(this.on.ready.subscribe,function(Y){return function(G,ne){en.vip(function(){var Q,Z=z._state;Z.openComplete?(Z.dbOpenError||ze.resolve().then(G),ne&&Y(G)):Z.onReadyBeingFired?(Z.onReadyBeingFired.push(G),ne&&Y(G)):(Y(G),Q=z,ne||Y(function ee(){Q.on.ready.unsubscribe(G),Q.on.ready.unsubscribe(ee)}))})}}),this.Collection=(y=this,sa(ow.prototype,function(ee,Z){this.db=y;var ne=Ph,Q=null;if(Z)try{ne=Z()}catch(ae){Q=ae}var Z=ee._ctx,ee=Z.table,de=ee.hook.reading.fire;this._ctx={table:ee,index:Z.index,isPrimKey:!Z.index||ee.schema.primKey.keyPath&&Z.index===ee.schema.primKey.name,range:ne,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:Q,or:Z.or,valueMapper:de!==we?de:null}})),this.Table=(v=this,sa($h.prototype,function(Y,G,ne){this.db=v,this._tx=ne,this.name=Y,this.schema=G,this.hook=v._allTables[Y]?v._allTables[Y].hook:na(null,{creating:[Dt,Ye],reading:[Ke,we],updating:[ce,Ye],deleting:[F,Ye]})})),this.Transaction=(k=this,sa(lw.prototype,function(Y,G,ne,Q,Z){var ee=this;Y!=="readonly"&&G.forEach(function(de){de=(de=ne[de])==null?void 0:de.yProps,de&&(G=G.concat(de.map(function(ae){return ae.updatesTable})))}),this.db=k,this.mode=Y,this.storeNames=G,this.schema=ne,this.chromeTransactionDurability=Q,this.idbtrans=null,this.on=na(this,"complete","error","abort"),this.parent=Z||null,this.active=!0,this._reculock=0,this._blockedFuncs=[],this._resolve=null,this._reject=null,this._waitingFor=null,this._waitingQueue=null,this._spinCount=0,this._completion=new ze(function(de,ae){ee._resolve=de,ee._reject=ae}),this._completion.then(function(){ee.active=!1,ee.on.complete.fire()},function(de){var ae=ee.active;return ee.active=!1,ee.on.error.fire(de),ee.parent?ee.parent._reject(de):ae&&ee.idbtrans&&ee.idbtrans.abort(),Pt(de)})})),this.Version=(E=this,sa(fw.prototype,function(Y){this.db=E,this._cfg={version:Y,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(D=this,sa(zh.prototype,function(Y,G,ne){if(this.db=D,this._ctx={table:Y,index:G===":id"?null:G,or:ne},this._cmp=this._ascending=jt,this._descending=function(Q,Z){return jt(Z,Q)},this._max=function(Q,Z){return 0<jt(Q,Z)?Q:Z},this._min=function(Q,Z){return jt(Q,Z)<0?Q:Z},this._IDBKeyRange=D._deps.IDBKeyRange,!this._IDBKeyRange)throw new Oe.MissingAPI})),this.on("versionchange",function(Y){0<Y.newVersion?console.warn("Another connection wants to upgrade database '".concat(z.name,"'. Closing db now to resume the upgrade.")):console.warn("Another connection wants to delete database '".concat(z.name,"'. Closing db now to resume the delete request.")),z.close({disableAutoOpen:!1})}),this.on("blocked",function(Y){!Y.newVersion||Y.newVersion<Y.oldVersion?console.warn("Dexie.delete('".concat(z.name,"') was blocked")):console.warn("Upgrade '".concat(z.name,"' blocked by other connection holding version ").concat(Y.oldVersion/10))}),this._maxKey=aa(h.IDBKeyRange),this._createTransaction=function(Y,G,ne,Q){return new z.Transaction(Y,G,ne,z._options.chromeTransactionDurability,Q)},this._fireOnBlocked=function(Y){z.on("blocked").fire(Y),la.toArray().filter(function(G){return G.name===z.name&&G!==z&&!G._state.vcFired}).map(function(G){return G.on("versionchange").fire(Y)})},this.use(xw),this.use(_w),this.use(vw),this.use(yw),this.use(bw),new Proxy(this,{get:function(Y,G,ne){var Q;return G==="_vip"||(G==="table"?function(Z){return Sl(z.table(Z),J)}:(Q=Reflect.get(Y,G,ne))instanceof $h?Sl(Q,J):G==="tables"?Q.map(function(Z){return Sl(Z,J)}):G==="_createTransaction"?function(){return Sl(Q.apply(this,arguments),J)}:Q)}}));this.vip=J,X.forEach(function(Y){return Y(z)})}var wl,vo=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",kw=(kd.prototype.subscribe=function(d,h,y){return this._subscribe(d&&typeof d!="function"?d:{next:d,error:h,complete:y})},kd.prototype[vo]=function(){return this},kd);function kd(d){this._subscribe=d}try{wl={indexedDB:a.indexedDB||a.mozIndexedDB||a.webkitIndexedDB||a.msIndexedDB,IDBKeyRange:a.IDBKeyRange||a.webkitIDBKeyRange}}catch{wl={indexedDB:null,IDBKeyRange:null}}function tp(d){var h,y=!1,v=new kw(function(k){var E=ie(d),D,z=!1,X={},oe={},J={get closed(){return z},unsubscribe:function(){z||(z=!0,D&&D.abort(),Y&&hr.storagemutated.unsubscribe(Q))}},Y=(k.start&&k.start(J),!1),G=function(){return Tt(Z)};function ne(){return gd(oe,X)}var Q=function(ee){bl(X,ee),ne()&&G()},Z=function(){var ee,de,ae;!z&&wl.indexedDB&&(X={},ee={},D&&D.abort(),D=new AbortController,ae=(pe=>{var Te=is();try{E&&An();var Me=yn(d,pe);return Me=E?Me.finally(Ds):Me}finally{Te&&Ss()}})(de={subscr:ee,signal:D.signal,requery:G,querier:d,trans:null}),Y||(hr(oa,Q),Y=!0),Promise.resolve(ae).then(function(pe){y=!0,h=pe,z||de.signal.aborted||(ne()||(oe=ee,ne())?G():(X={},Tt(function(){return!z&&k.next&&k.next(pe)})))},function(pe){y=!1,["DatabaseClosedError","AbortError"].includes(pe==null?void 0:pe.name)||z||Tt(function(){z||k.error&&k.error(pe)})}))};return setTimeout(G,0),J});return v.hasValue=function(){return y},v.getValue=function(){return h},v}var Dr=Xs;function Td(d){var h=pr;try{pr=!0,hr.storagemutated.fire(d),xd(d,!0)}finally{pr=h}}g(Dr,s(s({},re),{delete:function(d){return new Dr(d,{addons:[]}).delete()},exists:function(d){return new Dr(d,{addons:[]}).open().then(function(h){return h.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(d){try{return h=Dr.dependencies,y=h.indexedDB,h=h.IDBKeyRange,(hd(y)?Promise.resolve(y.databases()).then(function(v){return v.map(function(k){return k.name}).filter(function(k){return k!==ws})}):md(y,h).toCollection().primaryKeys()).then(d)}catch{return Pt(new Oe.MissingAPI)}var h,y},defineClass:function(){return function(d){c(this,d)}},ignoreTransaction:function(d){return qe.trans?Lt(qe.transless||Kt,d):d()},vip:pd,async:function(d){return function(){try{var h=vd(d.apply(this,arguments));return h&&typeof h.then=="function"?h:ze.resolve(h)}catch(y){return Pt(y)}}},spawn:function(d,h,y){try{var v=vd(d.apply(y,h||[]));return v&&typeof v.then=="function"?v:ze.resolve(v)}catch(k){return Pt(k)}},currentTransaction:{get:function(){return qe.trans||null}},waitFor:function(d,h){return d=ze.resolve(typeof d=="function"?Dr.ignoreTransaction(d):d).timeout(h||6e4),qe.trans?qe.trans.waitFor(d):d},Promise:ze,debug:{get:function(){return Le},set:function(d){me(d)}},derive:x,extend:c,props:g,override:M,Events:na,on:hr,liveQuery:tp,extendObservabilitySet:bl,getByKeyPath:L,setByKeyPath:A,delByKeyPath:function(d,h){typeof h=="string"?A(d,h,void 0):"length"in h&&[].map.call(h,function(y){A(d,y,void 0)})},shallowClone:B,deepClone:$,getObjectDiff:Sd,cmp:jt,asap:C,minKey:-1/0,addons:[],connections:{get:la.toArray},errnames:ft,dependencies:wl,cache:$r,semVer:"4.4.2",version:"4.4.2".split(".").map(function(d){return parseInt(d)}).reduce(function(d,h,y){return d+h/Math.pow(10,2*y)})})),Dr.maxKey=aa(Dr.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(hr(oa,function(d){pr||(d=new CustomEvent(od,{detail:d}),pr=!0,dispatchEvent(d),pr=!1)}),addEventListener(od,function(d){d=d.detail,pr||Td(d)}));var So,pr=!1,np=function(){};return typeof BroadcastChannel<"u"&&((np=function(){(So=new BroadcastChannel(od)).onmessage=function(d){return d.data&&Td(d.data)}})(),typeof So.unref=="function"&&So.unref(),hr(oa,function(d){pr||So.postMessage(d)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(d){if(!Xs.disableBfCache&&d.persisted){Le&&console.debug("Dexie: handling persisted pagehide"),So!=null&&So.close();for(var h=0,y=la.toArray();h<y.length;h++)y[h].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(d){!Xs.disableBfCache&&d.persisted&&(Le&&console.debug("Dexie: handling persisted pageshow"),np(),Td({all:new In(-1/0,[[]])}))})),ze.rejectionMapper=function(d,h){return!d||d instanceof Se||d instanceof TypeError||d instanceof SyntaxError||!d.name||!zt[d.name]?d:(h=new zt[d.name](h||d.message,d),"stack"in d&&S(h,"stack",{get:function(){return this.inner.stack}}),h)},me(Le),s(Xs,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:Xs,Entity:Eh,PropModification:ta,RangeSet:In,add:function(d){return new ta({add:d})},cmp:jt,default:Xs,liveQuery:tp,mergeRanges:da,rangesOverlap:Hh,remove:function(d){return new ta({remove:d})},replacePrefix:function(d,h){return new ta({replacePrefix:[d,h]})}}),{default:Xs}),Xs})}(Jl)),Jl.exports}var K0=H0();const $u=fo(K0),wp=Symbol.for("Dexie"),vc=globalThis[wp]||(globalThis[wp]=$u);if($u.semVer!==vc.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${$u.semVer} and ${vc.semVer}`);const{liveQuery:qL,mergeRanges:UL,rangesOverlap:HL,RangeSet:KL,cmp:VL,Entity:YL,PropModification:XL,replacePrefix:GL,add:JL,remove:QL,DexieYProvider:ZL}=vc;class V0 extends vc{constructor(){super("LotusStorage");Ct(this,"scrollAnchors");Ct(this,"toolSessionCollapses");Ct(this,"diffCollapses");Ct(this,"inputStates");Ct(this,"modelOptionsCaches");this.version(1).stores({scrollAnchors:"sessionId, ts",toolSessionCollapses:"id, sessionId, updatedAt",diffCollapses:"sessionId, updatedAt",inputStates:"sessionId, updatedAt",modelOptionsCaches:"provider, timestamp"})}}const Y0=new V0,Zr=class Zr{constructor(){Ct(this,"db",Y0)}static getInstance(){return Zr.instance||(Zr.instance=new Zr),Zr.instance}async saveScrollAnchor(t,n){try{await this.db.scrollAnchors.put({sessionId:t,anchorId:n.anchorId,offsetPx:n.offsetPx,ts:n.ts,indexHint:n.indexHint,createdAt:n.createdAt})}catch(s){console.warn("[StorageManager] IndexedDB save failed, falling back to localStorage",s);try{localStorage.setItem(`chat_scroll_anchor_v2:${t}`,JSON.stringify(n))}catch{}}}async loadScrollAnchor(t){try{const n=await this.db.scrollAnchors.get(t);return n?{v:1,anchorId:n.anchorId,offsetPx:n.offsetPx,ts:n.ts,indexHint:n.indexHint,createdAt:n.createdAt}:null}catch{try{const n=localStorage.getItem(`chat_scroll_anchor_v2:${t}`);if(!n)return null;const s=JSON.parse(n);if(s&&s.v===1&&typeof s.anchorId=="string")return s}catch{}return null}}async clearScrollAnchor(t){try{await this.db.scrollAnchors.delete(t)}catch{}try{localStorage.removeItem(`chat_scroll_anchor_v2:${t}`)}catch{}}async saveToolSessionCollapse(t,n,s){try{await this.db.toolSessionCollapses.put({id:`${t}:${n}`,sessionId:t,toolSessionId:n,isExpanded:s.isExpanded,expandedTools:s.expandedTools,updatedAt:Date.now()})}catch(r){console.warn("[StorageManager] saveToolSessionCollapse failed",r);try{localStorage.setItem(`chat-session-tool-collapse:${t}:${n}`,JSON.stringify(s))}catch{}}}async loadToolSessionCollapse(t,n){try{const s=await this.db.toolSessionCollapses.get(`${t}:${n}`);return s?{isExpanded:s.isExpanded,expandedTools:s.expandedTools}:null}catch{try{const s=localStorage.getItem(`chat-session-tool-collapse:${t}:${n}`);if(!s)return null;const r=JSON.parse(s);if(r&&typeof r.isExpanded=="boolean")return r}catch{}return null}}async saveDiffCollapse(t,n){try{await this.db.diffCollapses.put({sessionId:t,isExpanded:n.isExpanded,expandedFiles:n.expandedFiles,updatedAt:Date.now()})}catch(s){console.warn("[StorageManager] saveDiffCollapse failed",s);try{localStorage.setItem(`chat-session-diff-collapse:${t}`,JSON.stringify(n))}catch{}}}async loadDiffCollapse(t){try{const n=await this.db.diffCollapses.get(t);return n?{isExpanded:n.isExpanded,expandedFiles:n.expandedFiles}:null}catch{try{const n=localStorage.getItem(`chat-session-diff-collapse:${t}`);if(!n)return null;const s=JSON.parse(n);if(s&&typeof s.isExpanded=="boolean")return s}catch{}return null}}async saveInputReasoning(t,n){try{const s=await this.db.inputStates.get(t);await this.db.inputStates.put({sessionId:t,reasoningEffort:n,content:s==null?void 0:s.content,referenceText:s==null?void 0:s.referenceText,updatedAt:Date.now()})}catch(s){console.warn("[StorageManager] saveInputReasoning failed",s);try{const r=localStorage.getItem("chat_input_reasoning_by_session_v1"),a=r?JSON.parse(r):{};a[t]=n,localStorage.setItem("chat_input_reasoning_by_session_v1",JSON.stringify(a))}catch{}}}async loadInputReasoning(t){try{const n=await this.db.inputStates.get(t);return(n==null?void 0:n.reasoningEffort)??null}catch{try{const n=localStorage.getItem("chat_input_reasoning_by_session_v1");return n?JSON.parse(n)[t]??null:null}catch{return null}}}async saveLastUsedReasoningEffort(t){try{await this.db.inputStates.put({sessionId:"__last_used__",reasoningEffort:t,updatedAt:Date.now()})}catch{try{localStorage.setItem("chat_input_reasoning_last_used_v1",t)}catch{}}}async loadLastUsedReasoningEffort(){try{const t=await this.db.inputStates.get("__last_used__");return(t==null?void 0:t.reasoningEffort)??null}catch{try{return localStorage.getItem("chat_input_reasoning_last_used_v1")}catch{return null}}}async saveModelOptionsCache(t,n,s){try{await this.db.modelOptionsCaches.put({provider:t,options:n,timestamp:s})}catch(r){console.warn("[StorageManager] saveModelOptionsCache failed",r);try{localStorage.setItem(`chat-model-options-cache-v1:${t}`,JSON.stringify({timestamp:s,options:n}))}catch{}}}async loadModelOptionsCache(t){try{const n=await this.db.modelOptionsCaches.get(t);return n?{options:n.options,timestamp:n.timestamp}:null}catch{try{const n=localStorage.getItem(`chat-model-options-cache-v1:${t}`);if(!n)return null;const s=JSON.parse(n);if(s&&Array.isArray(s.options))return{options:s.options,timestamp:s.timestamp}}catch{}return null}}async clearSessionData(t){try{await Promise.all([this.db.scrollAnchors.delete(t),this.db.diffCollapses.delete(t),this.db.toolSessionCollapses.where("sessionId").equals(t).delete(),this.db.inputStates.delete(t)])}catch{}}async cleanupStaleData(t=30){const n=Date.now()-t*24*60*60*1e3;try{await Promise.all([this.db.scrollAnchors.where("ts").below(n).delete(),this.db.toolSessionCollapses.where("updatedAt").below(n).delete(),this.db.diffCollapses.where("updatedAt").below(n).delete(),this.db.inputStates.where("updatedAt").below(n).delete(),this.db.modelOptionsCaches.where("timestamp").below(n).delete()])}catch{}}async getStats(){try{const[t,n,s,r,a]=await Promise.all([this.db.scrollAnchors.count(),this.db.toolSessionCollapses.count(),this.db.diffCollapses.count(),this.db.inputStates.count(),this.db.modelOptionsCaches.count()]);return{scrollAnchors:t,toolSessionCollapses:n,diffCollapses:s,inputStates:r,modelOptionsCaches:a}}catch{return{scrollAnchors:0,toolSessionCollapses:0,diffCollapses:0,inputStates:0,modelOptionsCaches:0}}}};Ct(Zr,"instance");let Wn=Zr;const Hb="chat_input_reasoning_by_session_v1",Kb="chat_input_reasoning_last_used_v1",_p={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},qm=e=>e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",Vb=()=>{if(typeof window>"u")return{};try{const e=localStorage.getItem(Hb);if(!e)return{};const t=JSON.parse(e),n={};for(const[s,r]of Object.entries(t||{}))qm(r)&&(n[s]=r);return n}catch{return{}}},X0=e=>{if(!(typeof window>"u"))try{localStorage.setItem(Hb,JSON.stringify(e))}catch{}},G0=()=>{if(!(typeof window>"u"))try{const e=localStorage.getItem(Kb);return qm(e)?e:void 0}catch{return}},J0=e=>{if(!(typeof window>"u"))try{localStorage.setItem(Kb,e)}catch{}},Um=e=>{const t=Vb();return qm(t[e])?t[e]:G0()},pa=e=>({..._p,reasoningEffort:Um(e)??_p.reasoningEffort}),Q0=(e,t)=>({inputStates:{},setInputContent:(n,s)=>e(r=>({inputStates:{...r.inputStates,[n]:{...r.inputStates[n]||pa(n),content:s}}})),setReferenceText:(n,s)=>e(r=>({inputStates:{...r.inputStates,[n]:{...r.inputStates[n]||pa(n),referenceText:s}}})),setAttachments:(n,s)=>e(r=>({inputStates:{...r.inputStates,[n]:{...r.inputStates[n]||pa(n),attachments:s}}})),setInputReasoningEffort:(n,s)=>{e(i=>({inputStates:{...i.inputStates,[n]:{...i.inputStates[n]||pa(n),reasoningEffort:s}}}));const r=Vb();r[n]=s,X0(r),J0(s);const a=Wn.getInstance();a.saveInputReasoning(n,s).catch(()=>{}),a.saveLastUsedReasoningEffort(s).catch(()=>{})},clearInputState:n=>e(s=>{const{[n]:r,...a}=s.inputStates;return{inputStates:a}}),getInputState:n=>t().inputStates[n]||pa(n)}),Z0="bamboo_proxy_auth",ek=()=>{try{const e=localStorage.getItem(Z0);if(!e)return null;const t=JSON.parse(e);if(!t||typeof t!="object")return null;const n=typeof t.username=="string"?t.username.trim():"",s=typeof t.password=="string"?t.password:"";return n?{username:n,password:s}:null}catch{return null}},Yb={byId:{},runningCount:0},tk=[],qn=(e,t)=>t?e.executionBySession[t]??null:null,Xb=e=>t=>qn(t,e),nk=e=>t=>{const n=qn(t,e);return(n==null?void 0:n.phase)??"idle"},dr=e=>t=>{const n=qn(t,e);return zm(n==null?void 0:n.phase)},sk=e=>t=>{const n=qn(t,e);return n?n.phase==="streaming"?!0:n.phase==="running_tools"&&n.stream.hasTokens:!1},rk=e=>t=>{const n=qn(t,e);return n?n.phase==="waiting_user_answer"||n.interaction.pendingQuestion!==null||n.backend.hasPendingQuestion===!0:!1},Gb=e=>t=>{const n=qn(t,e);return a0(n==null?void 0:n.phase)},Jb=e=>t=>{const n=qn(t,e);return i0(n==null?void 0:n.phase)},qr=e=>t=>{const n=qn(t,e);return zm(n==null?void 0:n.phase)},ok=e=>t=>{const n=qn(t,e);return(n==null?void 0:n.stream.activeToolCalls)??tk},Ci=e=>t=>{const n=qn(t,e);return(n==null?void 0:n.interaction.respondMode)??null},Fi=e=>t=>{const n=qn(t,e);return(n==null?void 0:n.children.byId)??Yb.byId},ak=e=>t=>{const n=qn(t,e);return(n==null?void 0:n.children)??Yb},Sc=e=>t=>{const n=qn(t,e);return(n==null?void 0:n.generation)??0},ik=Object.freeze({state:"idle",activeToolCalls:[],runningChildCount:0,hasQuestion:!1,hasError:!1,errorMessage:null,tokenCount:0,hasTokens:!1,generation:0}),lk=e=>t=>{var s;const n=qn(t,e);return n?{state:n.phase,activeToolCalls:n.stream.activeToolCalls,runningChildCount:n.children.runningCount,hasQuestion:n.interaction.pendingQuestion!==null,hasError:n.error!==null,errorMessage:((s=n.error)==null?void 0:s.message)??null,tokenCount:n.stream.tokenCount,hasTokens:n.stream.hasTokens,generation:n.generation}:ik},ck=e=>t=>e.map(n=>({sessionId:n??"",entry:qn(t,n)})),dk="auto",uk="required",mk=1e4,hk=15e3,pk=Jn.getInstance();let kp=null,fa=null,Tp=null,ga=null;const jp=new WeakMap,te=Pr()(D_(F_((e,t,n)=>({...M0(e,t),...A0(e,t),...D0(e,t),...F0(),...z0(e,t),...B0(e),...q0(e,t),...Q0(e,t),...y0(e,t),agentAvailability:null,setAgentAvailability:s=>{e({agentAvailability:s})},checkAgentAvailability:async()=>{if(fa)return fa;fa=(async()=>{const s=await pk.healthCheck();return t().agentAvailability!==s&&e({agentAvailability:s}),s})();try{return await fa}finally{fa=null}},startAgentHealthCheck:()=>{kp||(t().checkAgentAvailability(),kp=setInterval(()=>{t().checkAgentAvailability()},mk))},refreshSessionsIndex:async()=>{if(ga)return ga;ga=(async()=>{try{await t().refreshChats()}catch(s){console.warn("[AppStore] refreshChats failed:",s)}})();try{return await ga}finally{ga=null}},startSessionsIndexSync:()=>{Tp||(t().refreshSessionsIndex(),Tp=setInterval(()=>{t().refreshSessionsIndex()},hk))}})),{name:"AppStore"})),Qb=e=>{const t=jp.get(e);if(t)return t;const n=new Map(e.map(s=>[s.id,s]));return jp.set(e,n),n},Er=e=>t=>e?Qb(t.chats).get(e)??null:null,Hm=e=>e.currentSessionId?Qb(e.chats).get(e.currentSessionId)??null:null,fk=e=>{var t;return((t=Hm(e))==null?void 0:t.messages)??[]},Cp=async()=>{const e=ek();if(!e)return!1;try{return await Yt.setProxyAuth(e),!0}catch(t){return console.error("Failed to apply stored proxy auth during startup:",t),!1}},gk=async()=>{try{const e=await Ms.getState().loadConfig();if((typeof(e==null?void 0:e.proxy_auth_mode)=="string"?e.proxy_auth_mode:dk)!==uk)return await Cp(),!1;const n=await Ms.getState().loadProxyAuthStatus({force:!0});return n!=null&&n.configured||await Cp()?!1:(te.setState(r=>({...r,models:[],selectedModel:void 0,modelsError:"Proxy auth mode is set to required. Please configure proxy username/password and apply it.",isLoadingModels:!1})),!0)}catch(e){return console.error("Failed to evaluate startup proxy auth mode:",e),!1}};let Mp=!1;const Zb=async(e=!1)=>{if(Mp&&!e)return;Mp=!0,te.getState().startAgentHealthCheck(),te.getState().startSessionsIndexSync(),await Mt.getState().loadProviderConfig(),await te.getState().loadChats(),await gk()||await te.getState().fetchModels(),await te.getState().loadSystemPrompts()},yk=Object.freeze(Object.defineProperty({__proto__:null,initializeStore:Zb,selectActiveToolCalls:ok,selectCanCancel:Jb,selectChildren:Fi,selectChildrenSnapshot:ak,selectCurrentChat:Hm,selectCurrentMessages:fk,selectExecutionByPane:ck,selectExecutionPhase:nk,selectExecutionState:Xb,selectGeneration:Sc,selectIsAwaitingUser:rk,selectIsBusy:dr,selectIsInputLocked:Gb,selectIsStreaming:sk,selectRailModel:lk,selectRespondMode:Ci,selectSessionById:Er,selectShouldObserve:qr,useAppStore:te},Symbol.toStringTag,{value:"Module"})),mo={'code[class*="language-"]':{background:"hsl(220, 13%, 18%)",color:"hsl(220, 14%, 71%)",textShadow:"0 1px rgba(0, 0, 0, 0.3)",fontFamily:'"Fira Code", "Fira Mono", Menlo, Consolas, "DejaVu Sans Mono", monospace',direction:"ltr",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",lineHeight:"1.5",MozTabSize:"2",OTabSize:"2",tabSize:"2",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{background:"hsl(220, 13%, 18%)",color:"hsl(220, 14%, 71%)",textShadow:"0 1px rgba(0, 0, 0, 0.3)",fontFamily:'"Fira Code", "Fira Mono", Menlo, Consolas, "DejaVu Sans Mono", monospace',direction:"ltr",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",lineHeight:"1.5",MozTabSize:"2",OTabSize:"2",tabSize:"2",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"1em",margin:"0.5em 0",overflow:"auto",borderRadius:"0.3em"},'code[class*="language-"]::-moz-selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'code[class*="language-"] *::-moz-selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'pre[class*="language-"] *::-moz-selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'code[class*="language-"]::selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'code[class*="language-"] *::selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'pre[class*="language-"] *::selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},':not(pre) > code[class*="language-"]':{padding:"0.2em 0.3em",borderRadius:"0.3em",whiteSpace:"normal"},comment:{color:"hsl(220, 10%, 40%)",fontStyle:"italic"},prolog:{color:"hsl(220, 10%, 40%)"},cdata:{color:"hsl(220, 10%, 40%)"},doctype:{color:"hsl(220, 14%, 71%)"},punctuation:{color:"hsl(220, 14%, 71%)"},entity:{color:"hsl(220, 14%, 71%)",cursor:"help"},"attr-name":{color:"hsl(29, 54%, 61%)"},"class-name":{color:"hsl(29, 54%, 61%)"},boolean:{color:"hsl(29, 54%, 61%)"},constant:{color:"hsl(29, 54%, 61%)"},number:{color:"hsl(29, 54%, 61%)"},atrule:{color:"hsl(29, 54%, 61%)"},keyword:{color:"hsl(286, 60%, 67%)"},property:{color:"hsl(355, 65%, 65%)"},tag:{color:"hsl(355, 65%, 65%)"},symbol:{color:"hsl(355, 65%, 65%)"},deleted:{color:"hsl(355, 65%, 65%)"},important:{color:"hsl(355, 65%, 65%)"},selector:{color:"hsl(95, 38%, 62%)"},string:{color:"hsl(95, 38%, 62%)"},char:{color:"hsl(95, 38%, 62%)"},builtin:{color:"hsl(95, 38%, 62%)"},inserted:{color:"hsl(95, 38%, 62%)"},regex:{color:"hsl(95, 38%, 62%)"},"attr-value":{color:"hsl(95, 38%, 62%)"},"attr-value > .token.punctuation":{color:"hsl(95, 38%, 62%)"},variable:{color:"hsl(207, 82%, 66%)"},operator:{color:"hsl(207, 82%, 66%)"},function:{color:"hsl(207, 82%, 66%)"},url:{color:"hsl(187, 47%, 55%)"},"attr-value > .token.punctuation.attr-equals":{color:"hsl(220, 14%, 71%)"},"special-attr > .token.attr-value > .token.value.css":{color:"hsl(220, 14%, 71%)"},".language-css .token.selector":{color:"hsl(355, 65%, 65%)"},".language-css .token.property":{color:"hsl(220, 14%, 71%)"},".language-css .token.function":{color:"hsl(187, 47%, 55%)"},".language-css .token.url > .token.function":{color:"hsl(187, 47%, 55%)"},".language-css .token.url > .token.string.url":{color:"hsl(95, 38%, 62%)"},".language-css .token.important":{color:"hsl(286, 60%, 67%)"},".language-css .token.atrule .token.rule":{color:"hsl(286, 60%, 67%)"},".language-javascript .token.operator":{color:"hsl(286, 60%, 67%)"},".language-javascript .token.template-string > .token.interpolation > .token.interpolation-punctuation.punctuation":{color:"hsl(5, 48%, 51%)"},".language-json .token.operator":{color:"hsl(220, 14%, 71%)"},".language-json .token.null.keyword":{color:"hsl(29, 54%, 61%)"},".language-markdown .token.url":{color:"hsl(220, 14%, 71%)"},".language-markdown .token.url > .token.operator":{color:"hsl(220, 14%, 71%)"},".language-markdown .token.url-reference.url > .token.string":{color:"hsl(220, 14%, 71%)"},".language-markdown .token.url > .token.content":{color:"hsl(207, 82%, 66%)"},".language-markdown .token.url > .token.url":{color:"hsl(187, 47%, 55%)"},".language-markdown .token.url-reference.url":{color:"hsl(187, 47%, 55%)"},".language-markdown .token.blockquote.punctuation":{color:"hsl(220, 10%, 40%)",fontStyle:"italic"},".language-markdown .token.hr.punctuation":{color:"hsl(220, 10%, 40%)",fontStyle:"italic"},".language-markdown .token.code-snippet":{color:"hsl(95, 38%, 62%)"},".language-markdown .token.bold .token.content":{color:"hsl(29, 54%, 61%)"},".language-markdown .token.italic .token.content":{color:"hsl(286, 60%, 67%)"},".language-markdown .token.strike .token.content":{color:"hsl(355, 65%, 65%)"},".language-markdown .token.strike .token.punctuation":{color:"hsl(355, 65%, 65%)"},".language-markdown .token.list.punctuation":{color:"hsl(355, 65%, 65%)"},".language-markdown .token.title.important > .token.punctuation":{color:"hsl(355, 65%, 65%)"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},namespace:{Opacity:"0.8"},"token.tab:not(:empty):before":{color:"hsla(220, 14%, 71%, 0.15)",textShadow:"none"},"token.cr:before":{color:"hsla(220, 14%, 71%, 0.15)",textShadow:"none"},"token.lf:before":{color:"hsla(220, 14%, 71%, 0.15)",textShadow:"none"},"token.space:before":{color:"hsla(220, 14%, 71%, 0.15)",textShadow:"none"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item":{marginRight:"0.4em"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > button":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 9%, 55%)",padding:"0.1em 0.4em",borderRadius:"0.3em"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > a":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 9%, 55%)",padding:"0.1em 0.4em",borderRadius:"0.3em"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > span":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 9%, 55%)",padding:"0.1em 0.4em",borderRadius:"0.3em"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > button:hover":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > button:focus":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > a:hover":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > a:focus":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > span:hover":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > span:focus":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},".line-highlight.line-highlight":{background:"hsla(220, 100%, 80%, 0.04)"},".line-highlight.line-highlight:before":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 14%, 71%)",padding:"0.1em 0.6em",borderRadius:"0.3em",boxShadow:"0 2px 0 0 rgba(0, 0, 0, 0.2)"},".line-highlight.line-highlight[data-end]:after":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 14%, 71%)",padding:"0.1em 0.6em",borderRadius:"0.3em",boxShadow:"0 2px 0 0 rgba(0, 0, 0, 0.2)"},"pre[id].linkable-line-numbers.linkable-line-numbers span.line-numbers-rows > span:hover:before":{backgroundColor:"hsla(220, 100%, 80%, 0.04)"},".line-numbers.line-numbers .line-numbers-rows":{borderRightColor:"hsla(220, 14%, 71%, 0.15)"},".command-line .command-line-prompt":{borderRightColor:"hsla(220, 14%, 71%, 0.15)"},".line-numbers .line-numbers-rows > span:before":{color:"hsl(220, 14%, 45%)"},".command-line .command-line-prompt > span:before":{color:"hsl(220, 14%, 45%)"},".rainbow-braces .token.token.punctuation.brace-level-1":{color:"hsl(355, 65%, 65%)"},".rainbow-braces .token.token.punctuation.brace-level-5":{color:"hsl(355, 65%, 65%)"},".rainbow-braces .token.token.punctuation.brace-level-9":{color:"hsl(355, 65%, 65%)"},".rainbow-braces .token.token.punctuation.brace-level-2":{color:"hsl(95, 38%, 62%)"},".rainbow-braces .token.token.punctuation.brace-level-6":{color:"hsl(95, 38%, 62%)"},".rainbow-braces .token.token.punctuation.brace-level-10":{color:"hsl(95, 38%, 62%)"},".rainbow-braces .token.token.punctuation.brace-level-3":{color:"hsl(207, 82%, 66%)"},".rainbow-braces .token.token.punctuation.brace-level-7":{color:"hsl(207, 82%, 66%)"},".rainbow-braces .token.token.punctuation.brace-level-11":{color:"hsl(207, 82%, 66%)"},".rainbow-braces .token.token.punctuation.brace-level-4":{color:"hsl(286, 60%, 67%)"},".rainbow-braces .token.token.punctuation.brace-level-8":{color:"hsl(286, 60%, 67%)"},".rainbow-braces .token.token.punctuation.brace-level-12":{color:"hsl(286, 60%, 67%)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix)":{backgroundColor:"hsla(353, 100%, 66%, 0.15)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix)":{backgroundColor:"hsla(353, 100%, 66%, 0.15)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix)::-moz-selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix) *::-moz-selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix)::-moz-selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix) *::-moz-selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix)::selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix) *::selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix)::selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix) *::selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix)":{backgroundColor:"hsla(137, 100%, 55%, 0.15)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix)":{backgroundColor:"hsla(137, 100%, 55%, 0.15)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix)::-moz-selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix) *::-moz-selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix)::-moz-selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix) *::-moz-selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix)::selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix) *::selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix)::selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix) *::selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},".prism-previewer.prism-previewer:before":{borderColor:"hsl(224, 13%, 17%)"},".prism-previewer-gradient.prism-previewer-gradient div":{borderColor:"hsl(224, 13%, 17%)",borderRadius:"0.3em"},".prism-previewer-color.prism-previewer-color:before":{borderRadius:"0.3em"},".prism-previewer-easing.prism-previewer-easing:before":{borderRadius:"0.3em"},".prism-previewer.prism-previewer:after":{borderTopColor:"hsl(224, 13%, 17%)"},".prism-previewer-flipped.prism-previewer-flipped.after":{borderBottomColor:"hsl(224, 13%, 17%)"},".prism-previewer-angle.prism-previewer-angle:before":{background:"hsl(219, 13%, 22%)"},".prism-previewer-time.prism-previewer-time:before":{background:"hsl(219, 13%, 22%)"},".prism-previewer-easing.prism-previewer-easing":{background:"hsl(219, 13%, 22%)"},".prism-previewer-angle.prism-previewer-angle circle":{stroke:"hsl(220, 14%, 71%)",strokeOpacity:"1"},".prism-previewer-time.prism-previewer-time circle":{stroke:"hsl(220, 14%, 71%)",strokeOpacity:"1"},".prism-previewer-easing.prism-previewer-easing circle":{stroke:"hsl(220, 14%, 71%)",fill:"transparent"},".prism-previewer-easing.prism-previewer-easing path":{stroke:"hsl(220, 14%, 71%)"},".prism-previewer-easing.prism-previewer-easing line":{stroke:"hsl(220, 14%, 71%)"}},{Text:Pp,Paragraph:bk}=He,xk=({content:e,token:t,showGradient:n,onClick:s})=>o.jsx(Ce,{size:"small",style:{marginLeft:t.marginLG,marginTop:t.marginXS,backgroundColor:t.colorBgLayout,borderColor:t.colorBorderSecondary},styles:{body:{padding:t.paddingMD}},onClick:s,children:o.jsxs("div",{style:{maxHeight:"60vh",overflowY:"auto",position:"relative",paddingRight:t.paddingXS},children:[o.jsx(Ps,{remarkPlugins:[Lc],components:{p:({children:r})=>o.jsx(bk,{style:{marginBottom:t.marginSM},children:r}),ol:({children:r})=>o.jsx("ol",{style:{marginBottom:t.marginSM,paddingLeft:t.paddingLG},children:r}),ul:({children:r})=>o.jsx("ul",{style:{marginBottom:t.marginSM,paddingLeft:t.paddingLG},children:r}),li:({children:r})=>o.jsx("li",{style:{marginBottom:t.marginXS},children:r}),h1:({children:r})=>o.jsx(Pp,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block"},children:r}),h2:({children:r})=>o.jsx(Pp,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block"},children:r}),code:({inline:r,className:a,children:i,...l})=>{const c=/language-(\w+)/.exec(a||"");return r?o.jsx("code",{className:a,style:{backgroundColor:t.colorFillTertiary,padding:"0 4px",borderRadius:t.borderRadiusSM,fontSize:t.fontSizeSM},...l,children:i}):o.jsx(Bo,{style:mo,language:(c==null?void 0:c[1])||"text",PreTag:"div",wrapLongLines:!0,children:String(i).replace(/\n$/,"")})}},children:e||"No content available."}),n?o.jsx("div",{style:{position:"sticky",bottom:0,height:48,background:`linear-gradient(180deg, transparent, ${t.colorBgLayout})`,pointerEvents:"none",marginTop:-48}}):null]})}),{Text:Id,Paragraph:vk}=He,Sk=({prompt:e,token:t,isSelected:n,isExpanded:s,onSelect:r,onToggleExpand:a,onCopy:i})=>{const{t:l}=Ie(),c=e.content||"",{nonEmptyLineCount:u,wordCount:m,characterCount:f,showGradient:g}=p.useMemo(()=>{const S=(c?c.split(/\r?\n/):[]).filter(j=>j.trim().length>0).length,x=c.trim()?c.trim().split(/\s+/).filter(Boolean).length:0,T=c.length;return{nonEmptyLineCount:S,wordCount:x,characterCount:T,showGradient:!s&&T>600}},[c,s]);return o.jsx(Qt.Item,{style:{cursor:"pointer",padding:t.paddingMD,borderRadius:t.borderRadius,border:n?`2px solid ${t.colorPrimary}`:`1px solid ${t.colorBorderSecondary}`,marginBottom:t.marginXS,backgroundColor:n?t.colorPrimaryBg:t.colorBgContainer,transition:"all 0.2s ease"},onClick:()=>r(e.id),children:o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:t.marginSM,children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",width:"100%",gap:t.marginSM},children:[o.jsxs(he,{align:"start",children:[o.jsx(bs,{checked:n,onChange:()=>r(e.id),onClick:b=>b.stopPropagation()}),o.jsxs("div",{children:[o.jsx(Id,{strong:!0,children:e.name||e.id}),o.jsx("div",{children:o.jsx(Id,{code:!0,style:{fontSize:t.fontSizeSM,color:t.colorTextSecondary},children:e.id})})]}),e.isDefault?o.jsx(Ne,{color:"warning",children:l("chat.systemPromptSelector.defaultTag")}):null]}),o.jsxs(he,{size:"small",children:[o.jsx(ue,{type:"text",size:"small",icon:s?o.jsx(Iw,{}):o.jsx(Fc,{}),onClick:b=>{b.stopPropagation(),a(e.id)},children:l(s?"chat.systemPromptSelector.hide":"chat.systemPromptSelector.preview")}),o.jsx(ue,{type:"text",size:"small",icon:o.jsx(xs,{}),onClick:b=>i(b,e),children:l("chat.systemPromptSelector.copy")})]})]}),e.description?o.jsx(Id,{type:"secondary",style:{marginLeft:t.marginLG,fontSize:t.fontSizeSM},children:e.description}):null,o.jsxs(he,{size:"small",wrap:!0,style:{marginLeft:t.marginLG},children:[o.jsx(Ne,{color:"processing",children:l("chat.systemPromptSelector.lines",{count:u})}),o.jsx(Ne,{color:"purple",children:l("chat.systemPromptSelector.words",{count:m})}),o.jsx(Ne,{color:"success",children:l("chat.systemPromptSelector.chars",{count:f})})]}),s?o.jsx(xk,{content:c,token:t,showGradient:g,onClick:b=>b.stopPropagation()}):o.jsx(vk,{type:"secondary",ellipsis:{rows:3},style:{marginLeft:t.marginLG,marginBottom:0,color:t.colorTextSecondary},children:c||l("chat.systemPromptSelector.noContent")})]})},e.id)},{Text:wk}=He,{useToken:_k}=Ge,kk=({open:e,onClose:t,onSelect:n,prompts:s,title:r,showCancelButton:a=!0})=>{const{t:i}=Ie(),{token:l}=_k(),[c,u]=Cr.useMessage(),m=te(C=>C.lastSelectedPromptId),f=te(C=>C.setLastSelectedPromptId),[g,b]=p.useState(null),[S,x]=p.useState(null),T=p.useMemo(()=>s.filter(C=>C.id&&C.id.trim()!==""),[s]),j=async(C,L)=>{C.stopPropagation();const A=L.content??"";try{await vs(A),c.success(i("success.promptCopied",{name:L.name}))}catch(B){console.error("[SystemPromptSelector] Failed to copy prompt:",B),c.error(i("error.copyPromptFailed"))}},w=r??i("chat.prompt.selectorTitle");p.useEffect(()=>{if(e){const C=T.find(A=>A.isDefault),L=m||(C==null?void 0:C.id)||(T.length>0?T[0].id:null);b(L)}},[e,m,T.length]);const M=C=>{b(C.id),f(C.id),n(C),t()},_=()=>{t()};return o.jsxs(o.Fragment,{children:[u,o.jsxs(Xn,{title:o.jsxs(he,{children:[o.jsx(Ui,{}),w]}),open:e,onCancel:_,width:700,footer:o.jsx(j_,{buttons:[...a?[C_(_)]:[],M_(()=>{const C=T.find(L=>L.id===g);C&&M(C)},{text:i("chat.prompt.createButton"),disabled:!g})]}),styles:{body:{maxHeight:"70vh",overflowY:"auto",padding:l.paddingMD}},children:[o.jsx("div",{style:{marginBottom:l.marginMD},children:o.jsx(wk,{type:"secondary",style:{fontSize:l.fontSizeSM},children:i("chat.prompt.helperText")})}),T.length===0?o.jsx(Mn,{description:i("chat.prompt.emptyDescription"),style:{margin:l.marginLG}}):o.jsx("div",{children:T.map(C=>o.jsx(Sk,{prompt:C,token:l,isSelected:g===C.id,isExpanded:S===C.id,onSelect:L=>b(L),onToggleExpand:L=>x(S===L?null:L),onCopy:j},C.id))})]})]})},Tk=({chat:e,isSelected:t,onSelect:n,onDelete:s,onPin:r,onUnpin:a,onEdit:i,onGenerateTitle:l,onRunProjectDream:c,isGeneratingTitle:u,isRunningProjectDream:m,titleGenerationError:f})=>{const{t:g}=Ie(),[b,S]=p.useState(!1),[x,T]=p.useState(e.title),[j,w]=p.useState(!1),[M,_]=p.useState(!1),{token:C}=Ge.useToken(),L=p.useCallback($=>{$.stopPropagation(),i&&x.trim()&&i(e.id,x.trim()),S(!1)},[e.id,x,i]),A=p.useCallback($=>{$.stopPropagation(),T(e.title),S(!1)},[e.title]),B=[{key:"pin",icon:e.pinned?o.jsx(ju,{style:{color:C.colorWarning}}):o.jsx(jm,{}),label:e.pinned?g("chat.actions.unpin"):g("chat.actions.pin"),onClick:({domEvent:$})=>{$.stopPropagation(),e.pinned?a(e.id):r(e.id)}},{key:"edit",icon:o.jsx(Hi,{}),label:g("chat.chatItem.edit"),onClick:({domEvent:$})=>{$.stopPropagation(),S(!0)}},...l?[{key:"generate-title",icon:u?o.jsx(io,{}):o.jsx(hb,{style:f?{color:C.colorError}:void 0}),label:f||g("chat.actions.generateTitle"),disabled:u,onClick:({domEvent:$})=>{$.stopPropagation(),l(e.id)}}]:[],...c?[{key:"run-project-dream",icon:m?o.jsx(io,{}):o.jsx(Ow,{}),label:g("chat.actions.runProjectDream"),disabled:m,onClick:({domEvent:$})=>{$.stopPropagation(),c(e.id)}}]:[],{type:"divider"},{key:"delete",icon:o.jsx(Mr,{}),label:g("common.delete"),danger:!0,onClick:({domEvent:$})=>{$.stopPropagation(),s(e.id)}}],N={padding:"8px 12px",borderRadius:C.borderRadiusSM,marginBottom:C.marginXXS,cursor:"pointer",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)",backgroundColor:t?"var(--lotus-primary-soft)":j||M?"var(--lotus-item-hover-bg)":"transparent",border:"1px solid transparent",borderColor:t?"var(--lotus-tool-card-border)":j||M?C.colorBorderSecondary:"transparent",position:"relative",overflow:"visible",boxShadow:t?"var(--lotus-tool-card-shadow)":"none",transform:j&&!t?"translateX(2px)":"none"},O={flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontSize:13,fontWeight:t?600:500,color:t?"var(--lotus-primary)":C.colorText},R={flex:1,fontSize:C.fontSizeSM,marginRight:C.marginSM},I=b?[o.jsx(ue,{type:"text",size:"small",icon:o.jsx($w,{style:{color:C.colorSuccess}}),onClick:L,"aria-label":g("common.save")},"save"),o.jsx(ue,{type:"text",size:"small",icon:o.jsx(Ho,{style:{color:C.colorError}}),onClick:A,"aria-label":g("common.cancel")},"cancel")]:j||M?[o.jsx(lo,{menu:{items:B,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:M,onOpenChange:$=>_($),children:o.jsx(ue,{type:"text",size:"small",icon:o.jsx(Dw,{}),"aria-label":g("common.moreActions","More actions"),onClick:$=>$.stopPropagation(),style:{color:C.colorTextSecondary,borderRadius:C.borderRadiusSM,background:C.colorFillTertiary,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return o.jsx(Qt.Item,{style:N,tabIndex:0,onClick:()=>!b&&n(e.id),onKeyDown:$=>{$.key==="Enter"&&!b?($.preventDefault(),n(e.id)):($.key==="Delete"||$.key==="Backspace")&&!b&&$.metaKey&&($.preventDefault(),s(e.id))},onMouseEnter:()=>w(!0),onMouseLeave:()=>{M||w(!1)},onFocus:()=>w(!0),onBlur:()=>{M||w(!1)},actions:I,"data-testid":"chat-item",role:"option","aria-selected":t,"aria-label":e.title||g("chat.sidebar.untitledChat"),children:o.jsx(Qt.Item.Meta,{title:b?o.jsx(Qe,{value:x,onChange:$=>T($.target.value),onClick:$=>$.stopPropagation(),onPressEnter:$=>{$.preventDefault(),L($)},autoFocus:!0,style:R,variant:"borderless",size:"small"}):o.jsxs("div",{style:{...O,display:"flex",alignItems:"center",gap:C.marginXS,minWidth:0},children:[e.pinned&&o.jsx(ju,{style:{color:C.colorWarning,fontSize:11,flexShrink:0}}),o.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.title}),e.kind==="child"?o.jsx(Ne,{color:"processing",style:{marginInlineEnd:0,flex:"0 0 auto"},children:g("chat.chatItem.childTag")}):null]})})})},jk=(e,t)=>e.chat.id===t.chat.id&&e.chat.title===t.chat.title&&e.chat.pinned===t.chat.pinned&&e.isSelected===t.isSelected&&e.isGeneratingTitle===t.isGeneratingTitle&&e.isRunningProjectDream===t.isRunningProjectDream&&e.titleGenerationError===t.titleGenerationError,Du=p.memo(Tk,jk);Du.displayName="ChatItem";const Ep=e=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[e]??4,Ck=e=>{const t={},n=e.filter(r=>r.pinned);n.length>0&&(t.Pinned=n.sort((r,a)=>a.createdAt-r.createdAt));const s=e.filter(r=>!r.pinned&&!!r.createdByScheduleId);return s.length>0&&(t.Scheduled=s.sort((r,a)=>a.createdAt-r.createdAt)),e.filter(r=>!r.pinned&&!r.createdByScheduleId).forEach(r=>{const i=new Date(r.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});t[i]||(t[i]=[]),t[i].push(r)}),Object.keys(t).forEach(r=>{t[r].sort((a,i)=>i.createdAt-a.createdAt)}),t},Mk=e=>{const t=n=>Array.isArray(n)?n.reduce((s,r)=>Math.max(s,r.createdAt),0):Object.values(n).reduce((s,r)=>{const a=r.reduce((i,l)=>Math.max(i,l.createdAt),0);return Math.max(s,a)},0);return Object.keys(e).sort((n,s)=>{if(n==="Pinned")return-1;if(s==="Pinned")return 1;if(n==="Scheduled")return-1;if(s==="Scheduled")return 1;const r=e[n],a=e[s];if(!r||!a)return 0;const i=t(r),l=t(a);return i!==l?l-i:Ep(n)-Ep(s)})},Pk=(e,t)=>e[t]?e[t].map(n=>n.id):[],ex=(e,t)=>e[t]?e[t].length:0,Rp=e=>e.pinned?"Pinned":e.createdByScheduleId?"Scheduled":new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),Ap=(e,t)=>{const s={Today:"chat.sidebar.dateGroups.today",Yesterday:"chat.sidebar.dateGroups.yesterday","This Week":"chat.sidebar.dateGroups.thisWeek","This Month":"chat.sidebar.dateGroups.thisMonth",Pinned:"chat.sidebar.dateGroups.pinned",Scheduled:"chat.sidebar.dateGroups.scheduled"}[e];return s?t(s):e},Ek=({groupedChatsByDate:e,childrenByRoot:t,expandedRootIds:n,onToggleRootExpanded:s,sortedDateKeys:r,expandedKeys:a,onCollapseChange:i,currentSessionId:l,onSelectChat:c,onDeleteChat:u,onDeleteByDate:m,onPinChat:f,onUnpinChat:g,onEditTitle:b,onGenerateTitle:S,onRunProjectDream:x,titleGenerationState:T,projectDreamState:j,token:w,hasActiveFilters:M})=>{const{t:_}=Ie(),C=p.useMemo(()=>r.length?r.map(A=>{const B=e[A],N=ex(e,A);return{dateKey:A,dateGroup:B,totalChatsInDate:N}}):[],[e,r]);if(!r.length)return o.jsx(Mn,{image:Mn.PRESENTED_IMAGE_SIMPLE,description:o.jsxs(he,{direction:"vertical",size:4,align:"center",children:[o.jsx("span",{style:{color:w.colorTextSecondary},children:M?_("chat.sidebar.empty.noMatches","No matching sessions"):_("chat.sidebar.empty.noSessions")}),o.jsx("span",{style:{color:w.colorTextSecondary,fontSize:12},children:M?_("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):_("chat.sidebar.empty.hint")}),M&&o.jsx(ue,{size:"small",type:"link",onClick:()=>{var B;const A=document.querySelector('[data-testid="sidebar-search-input"] input, .lotus-sidebar-search input');if(A){const N=(B=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value"))==null?void 0:B.set;N==null||N.call(A,""),A.dispatchEvent(new Event("input",{bubbles:!0}))}},children:_("chat.sidebar.empty.clearFilters","Clear filters")})]})});const L=new Set(a);return o.jsx(he,{direction:"vertical",size:"small",style:{width:"100%"},children:C.map(({dateKey:A,dateGroup:B,totalChatsInDate:N})=>{const O=L.has(A);return o.jsxs("div",{style:{borderRadius:w.borderRadiusSM,background:O?w.colorFillTertiary:"transparent",padding:4},children:[o.jsxs(be,{align:"center",justify:"space-between",style:{cursor:"pointer",padding:"8px 12px",borderRadius:w.borderRadiusSM,transition:"all 0.2s ease",border:"1px solid transparent"},role:"button",tabIndex:0,"aria-expanded":O,"aria-label":`${Ap(A,_)} (${N})`,onKeyDown:R=>{if(R.key==="Enter"||R.key===" "){R.preventDefault();const I=new Set(L);I.has(A)?I.delete(A):I.add(A),i(Array.from(I))}},onMouseEnter:R=>{R.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.92))",R.currentTarget.style.borderColor="var(--lotus-sidebar-item-hover-border, rgba(13, 148, 136, 0.28))";const I=R.currentTarget.querySelector(".chat-sidebar-date-group-delete");I&&(I.style.opacity="1")},onMouseLeave:R=>{R.currentTarget.style.background="transparent",R.currentTarget.style.borderColor="transparent";const I=R.currentTarget.querySelector(".chat-sidebar-date-group-delete");I&&(I.style.opacity="0")},onClick:()=>{const R=new Set(L);R.has(A)?R.delete(A):R.add(A),i(Array.from(R))},className:"chat-sidebar-date-group-header",children:[o.jsxs(be,{align:"center",gap:"small",style:{minWidth:0},children:[O?o.jsx(Gn,{style:{fontSize:12,opacity:.6}}):o.jsx(Vs,{style:{fontSize:12,opacity:.6}}),o.jsxs("span",{style:{fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:A==="Today"?"var(--lotus-primary)":w.colorTextSecondary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[Ap(A,_)," (",N,")"]})]}),o.jsx(ue,{type:"text",size:"small",icon:o.jsx(Mr,{}),className:"chat-sidebar-date-group-delete",style:{color:w.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:R=>{R.stopPropagation(),m(A)}})]}),O?o.jsx("div",{style:{marginTop:4},children:o.jsx(Qt,{itemLayout:"horizontal",dataSource:B,split:!1,renderItem:R=>{var I,$,U,q,K,P;return o.jsxs("div",{children:[o.jsxs(be,{align:"center",gap:6,children:[(I=t[R.id])!=null&&I.length?o.jsx(ue,{size:"small",type:"text",style:{padding:0,width:22},"aria-label":n.has(R.id)?_("chat.sidebar.actions.collapseChildren"):_("chat.sidebar.actions.expandChildren"),onClick:W=>{W.preventDefault(),W.stopPropagation(),s(R.id)},children:n.has(R.id)?o.jsx(Gn,{}):o.jsx(Vs,{})}):o.jsx("div",{style:{width:22}}),o.jsx("div",{style:{flex:1,minWidth:0},children:o.jsx(Du,{chat:R,isSelected:R.id===l,onSelect:c,onDelete:u,onPin:f,onUnpin:g,onEdit:b,onGenerateTitle:S,onRunProjectDream:x,isGeneratingTitle:(($=T[R.id])==null?void 0:$.status)==="loading",isRunningProjectDream:((U=j[R.id])==null?void 0:U.status)==="loading",titleGenerationError:((q=T[R.id])==null?void 0:q.status)==="error"?(K=T[R.id])==null?void 0:K.error:void 0})})]}),n.has(R.id)&&(((P=t[R.id])==null?void 0:P.length)??0)>0?o.jsx("div",{style:{marginLeft:22,marginTop:2},children:o.jsx(Qt,{itemLayout:"horizontal",dataSource:t[R.id],split:!1,renderItem:W=>{var se,V,ie,re;return o.jsx("div",{style:{paddingLeft:12},children:o.jsx(Du,{chat:W,isSelected:W.id===l,onSelect:c,onDelete:u,onPin:f,onUnpin:g,onEdit:b,onGenerateTitle:S,onRunProjectDream:x,isGeneratingTitle:((se=T[W.id])==null?void 0:se.status)==="loading",isRunningProjectDream:((V=j[W.id])==null?void 0:V.status)==="loading",titleGenerationError:((ie=T[W.id])==null?void 0:ie.status)==="error"?(re=T[W.id])==null?void 0:re.error:void 0})},W.id)}})}):null]},R.id)}})}):null]},A)})})},Rk="copilot_ui_theme_v1";function Ak(){var e;try{const t=localStorage.getItem(Rk);if(t==="light"||t==="dark")return t}catch{}return(e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const ho=Pr(e=>({themeMode:Ak(),setThemeMode:t=>e({themeMode:t}),toggleTheme:()=>e(t=>({themeMode:t.themeMode==="dark"?"light":"dark"}))})),Ik="2026.5.5",Ok={version:Ik},Km=Ok.version,{Text:$k}=He,Dk=({collapsed:e,onNewChat:t,onOpenSettings:n,screens:s,token:r})=>{const{t:a}=Ie(),i=ho(f=>f.themeMode),l=ho(f=>f.toggleTheme),c=a("chat.sidebar.newSession"),u=a("settings.page.title"),m=i==="dark"?a("settings.app.lightMode","Light mode"):a("settings.app.darkMode","Dark mode");return o.jsxs(be,{vertical:!0,gap:e?"small":"middle",style:{padding:e?10:16,background:"transparent",borderTop:`1px solid ${r.colorBorderSecondary}`},children:[o.jsx(ue,{"data-testid":"new-chat","data-tour-id":"new-session",type:"primary",icon:o.jsx(rr,{}),onClick:t,block:!e,shape:"default",size:e?"large":s.xs?"small":"middle",title:c,"aria-label":c,className:"lotus-primary-cta",style:{...e?{width:"44px",height:"44px",margin:"0 auto"}:{},borderRadius:r.borderRadiusLG,minHeight:e?44:46,fontWeight:600},children:!e&&c}),o.jsxs(be,{gap:8,align:"center",children:[o.jsx(ue,{"data-testid":"open-settings","data-tour-id":"open-settings",icon:o.jsx(Ki,{}),onClick:n,block:!e,shape:"default",size:e?"large":s.xs?"small":"middle",title:u,"aria-label":u,className:"lotus-secondary-button",style:{...e?{width:"44px",height:"44px",margin:"0 auto"}:{},borderRadius:r.borderRadiusLG,minHeight:44,flex:e?void 0:1},children:!e&&u}),!e&&o.jsx(bt,{title:m,placement:"top",children:o.jsx(ue,{"data-testid":"toggle-theme",type:"text",icon:i==="dark"?o.jsx(Lw,{}):o.jsx(Fw,{}),onClick:l,"aria-label":m,className:"lotus-toolbar-icon",style:{width:44,height:44,borderRadius:r.borderRadiusLG,flexShrink:0}})})]}),!e&&o.jsxs($k,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:r.fontSizeSM,textAlign:"center",userSelect:"text"},children:[a("settings.appTab.runningVersion","Running version"),": v",Km]})]})},Ip="provider",sr=Pr(e=>({isOpen:!1,origin:"chat",activeTabKey:Ip,open:(t,n=Ip)=>e({isOpen:!0,origin:t,activeTabKey:n}),close:()=>e({isOpen:!1}),setActiveTabKey:t=>e({activeTabKey:t})})),Cl={THEME:"copilot_ui_theme_v1",LAYOUT:"copilot_ui_layout_v1"};class Lk{getTheme(){try{return localStorage.getItem(Cl.THEME)}catch(t){return console.error("Failed to get theme:",t),null}}setTheme(t){try{localStorage.setItem(Cl.THEME,t)}catch(n){console.error("Failed to set theme:",n)}}getLayout(){try{return localStorage.getItem(Cl.LAYOUT)}catch(t){return console.error("Failed to get layout:",t),null}}setLayout(t){try{localStorage.setItem(Cl.LAYOUT,t)}catch(n){console.error("Failed to set layout:",n)}}getStorageStats(){let t=0;for(let n=0;n<localStorage.length;n++){const s=localStorage.key(n);if(s&&s.startsWith("copilot_ui_")){const r=localStorage.getItem(s);t+=(s.length+((r==null?void 0:r.length)||0))*2}}return{estimatedSize:`${(t/1024).toFixed(1)} KB`}}}const tx=new Lk,Vm={collapsed:!1,widthPx:260,collapsedWidthPx:72,minWidthPx:180,maxWidthPx:520},nx={v:2,sidebar:Vm,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:null},splitSizesPx:{}},Op=e=>{const t=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return`${e}-${t}`},os=e=>e.type==="leaf"?[e.id]:[...os(e.children[0]),...os(e.children[1])],Ni=e=>e.type==="leaf"?[]:[e.id,...Ni(e.children[0]),...Ni(e.children[1])],Fk=(e,t)=>{for(const[n,s]of Object.entries(e))if(s===t)return n;return null},Nk=(e,t)=>{const n={},s=new Set;return e.forEach(r=>{const a=t[r]??null;if(!a||s.has(a)){n[r]=null;return}s.add(a),n[r]=a}),n},Lu=(e,t,n,s,r)=>e.type==="leaf"?e.id!==t?e:{type:"split",id:s,layout:n,children:[e,{type:"leaf",id:r}]}:{...e,children:[Lu(e.children[0],t,n,s,r),Lu(e.children[1],t,n,s,r)]},Fu=(e,t)=>{if(e.type==="leaf")return e.id===t?{node:null,removed:!0}:{node:e,removed:!1};const n=Fu(e.children[0],t);if(n.removed)return n.node?{node:{...e,children:[n.node,e.children[1]]},removed:!0}:{node:e.children[1],removed:!0};const s=Fu(e.children[1],t);return s.removed?s.node?{node:{...e,children:[e.children[0],s.node]},removed:!0}:{node:e.children[0],removed:!0}:{node:e,removed:!1}},zk=e=>({v:2,sidebar:e.sidebar,tree:e.tree,activeLeafId:e.activeLeafId,leafSessionIds:e.leafSessionIds,splitSizesPx:e.splitSizesPx}),Bk=e=>{try{tx.setLayout(JSON.stringify(e))}catch(t){console.warn("[uiLayoutStore] Failed to persist layout:",t)}},Gs=e=>{const t=zk(e);return Bk(t),t},Wk=e=>{var g,b,S,x,T,j,w,M,_,C,L;const t={...Vm,...e.sidebar||{}},n=((g=e.view)==null?void 0:g.mode)??"single",s=((b=e.view)==null?void 0:b.twoDirection)??"horizontal",r={...((S=e.panes)==null?void 0:S.sessionIds)||{}},a=((x=e.panes)==null?void 0:x.activePaneId)??"lt",i={};if(n==="single")return{v:2,sidebar:t,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:r.lt??null},splitSizesPx:{}};if(n==="two"){const A="split-root",B=s,N=B==="horizontal"?{type:"split",id:A,layout:B,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"rt"}]}:{type:"split",id:A,layout:B,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},O=B==="horizontal"?((T=e.split)==null?void 0:T.twoHorizontalPx)||((j=e.split)==null?void 0:j.columnsPx)||null:((w=e.split)==null?void 0:w.twoVerticalPx)||((M=e.split)==null?void 0:M.leftRowsPx)||null;O&&(i[A]=O);const R=os(N);return{v:2,sidebar:t,tree:N,activeLeafId:R.includes(a)?a:R[0],leafSessionIds:Object.fromEntries(R.map(I=>[I,r[I]??null])),splitSizesPx:i}}const l="split-root",c="split-left",u="split-right",m={type:"split",id:l,layout:"horizontal",children:[{type:"split",id:c,layout:"vertical",children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},{type:"split",id:u,layout:"vertical",children:[{type:"leaf",id:"rt"},{type:"leaf",id:"rb"}]}]};(_=e.split)!=null&&_.columnsPx&&(i[l]=e.split.columnsPx),(C=e.split)!=null&&C.leftRowsPx&&(i[c]=e.split.leftRowsPx),(L=e.split)!=null&&L.rightRowsPx&&(i[u]=e.split.rightRowsPx);const f=os(m);return{v:2,sidebar:t,tree:m,activeLeafId:f.includes(a)?a:f[0],leafSessionIds:Object.fromEntries(f.map(A=>[A,r[A]??null])),splitSizesPx:i}},qk=e=>{if(!e)return null;try{const t=JSON.parse(e);if(!t||typeof t!="object")return null;if(t.v===2){const n={...Vm,...t.sidebar||{}},s=t.tree||nx.tree,r=os(s),a=Ni(s),i={};r.forEach(m=>{var f;i[m]=typeof((f=t.leafSessionIds)==null?void 0:f[m])=="string"?t.leafSessionIds[m]:null});const l={};a.forEach(m=>{var g;const f=(g=t.splitSizesPx)==null?void 0:g[m];Array.isArray(f)&&f.length>=2&&(l[m]=[Number(f[0]),Number(f[1])])});const c=typeof t.activeLeafId=="string"&&r.includes(t.activeLeafId)?t.activeLeafId:r[0],u=Nk(r,i);return{v:2,sidebar:n,tree:s,activeLeafId:c,leafSessionIds:u,splitSizesPx:l}}return t.v===1?Wk(t):null}catch{return null}},Uk=()=>qk(tx.getLayout())??nx,wt=Pr(e=>({...Uk(),setSidebarCollapsed:t=>{e(n=>n.sidebar.collapsed===t?n:Gs({sidebar:{...n.sidebar,collapsed:t},tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx}))},setSidebarWidthPx:t=>{e(n=>{const s=Math.max(n.sidebar.minWidthPx,Math.min(n.sidebar.maxWidthPx,t));return n.sidebar.widthPx===s?n:Gs({sidebar:{...n.sidebar,widthPx:s},tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})})},setActiveLeafId:t=>{e(n=>n.activeLeafId===t||!os(n.tree).includes(t)?n:(fs("setActiveLeafId",{from:n.activeLeafId,to:t}),Gs({sidebar:n.sidebar,tree:n.tree,activeLeafId:t,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})))},setLeafSessionId:(t,n)=>{e(s=>{const r=os(s.tree);if(!r.includes(t)||(s.leafSessionIds[t]??null)===n)return s;const a=[];fs("setLeafSessionId",{leafId:t,fromSessionId:s.leafSessionIds[t]??null,toSessionId:n,mode:"unique_session_per_leaf"});const i={...s.leafSessionIds,[t]:n};if(n)for(const l of r)l!==t&&i[l]===n&&(i[l]=null,a.push(l));return a.length>0&&fs("setLeafSessionId dedupe",{sessionId:n,clearedLeafIds:a,assignedLeafId:t}),r.forEach(l=>{l in i||(i[l]=null)}),Gs({sidebar:s.sidebar,tree:s.tree,activeLeafId:s.activeLeafId,leafSessionIds:i,splitSizesPx:s.splitSizesPx})})},clearSessionFromAllLeaves:t=>{e(n=>{const s={...n.leafSessionIds};let r=!1;for(const[a,i]of Object.entries(s))i===t&&(s[a]=null,r=!0);return r?Gs({sidebar:n.sidebar,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:s,splitSizesPx:n.splitSizesPx}):n})},splitLeaf:(t,n)=>{e(s=>{const r=os(s.tree);if(!r.includes(t)||r.length>=4)return s;const a=Op("split"),i=Op("pane"),l=Lu(s.tree,t,n,a,i),c={...s.leafSessionIds,[i]:null};return Gs({sidebar:s.sidebar,tree:l,activeLeafId:i,leafSessionIds:c,splitSizesPx:s.splitSizesPx})})},closeLeaf:t=>{e(n=>{const s=os(n.tree);if(!s.includes(t)||s.length<=1)return n;const r=Fu(n.tree,t);if(!r.removed||!r.node)return n;const a=r.node,i=os(a),l=Ni(a),c={};i.forEach(f=>{c[f]=n.leafSessionIds[f]??null});const u={};l.forEach(f=>{const g=n.splitSizesPx[f];g&&(u[f]=g)});const m=n.activeLeafId===t?i[0]:i.includes(n.activeLeafId)?n.activeLeafId:i[0];return Gs({sidebar:n.sidebar,tree:a,activeLeafId:m,leafSessionIds:c,splitSizesPx:u})})},setSplitSizesPx:(t,n)=>{e(s=>{const r=s.splitSizesPx[t];return r&&r[0]===n[0]&&r[1]===n[1]?s:Gs({sidebar:s.sidebar,tree:s.tree,activeLeafId:s.activeLeafId,leafSessionIds:s.leafSessionIds,splitSizesPx:{...s.splitSizesPx,[t]:n}})})},pruneSplitSizes:()=>{e(t=>{const n=new Set(Ni(t.tree)),s={};for(const[i,l]of Object.entries(t.splitSizesPx))n.has(i)&&(s[i]=l);const r=Object.keys(t.splitSizesPx),a=Object.keys(s);return r.length===a.length&&r.every(i=>i in s)?t:Gs({sidebar:t.sidebar,tree:t.tree,activeLeafId:t.activeLeafId,leafSessionIds:t.leafSessionIds,splitSizesPx:s})})}})),Hk=async(e,t)=>{var i;const n=te.getState(),s=!n.chats.some(l=>l.id===e);if(t!=null&&t.forceRefreshIndex||s)try{await n.refreshChats()}catch(l){console.warn("[openSession] refreshChats failed:",l)}const r=te.getState().chats.find(l=>l.id===e);if(!r)return;if(t!=null&&t.forceLoadHistory||s||(((i=r.messages)==null?void 0:i.length)||0)===0&&(r.messageCount||0)>0)try{await n.loadChatHistory(e)}catch(l){console.warn("[openSession] loadChatHistory failed:",l)}if(t!=null&&t.forceSubscribe){n.markForceSubscribe(e);return}((t==null?void 0:t.subscribeIfRunning)??!0)&&r.isRunning&&n.markForceSubscribe(e)},qc=(e,t)=>{const{activeLeafId:n,leafSessionIds:s,setLeafSessionId:r,setActiveLeafId:a}=wt.getState(),i=Fk(s,e),l=s[n]??null;fs("openSession (input)",{activeLeafId:n,activeLeafSessionId:l,sessionId:e,existingLeafId:i}),i?i===n?fs("openSession (decision)",{action:"noop_already_active",leafId:n,sessionId:e}):(a(i),fs("openSession (decision)",{action:"focus_existing_leaf",leafId:i,sessionId:e})):(r(n,e),fs("openSession (decision)",{action:"assign_to_active_leaf",leafId:n,sessionId:e})),te.getState().selectSession(e),Hk(e,t)},Od=(e,t)=>{if(!t)return!0;const n=[e.title,e.id,e.kind||"root",e.config.workspacePath||"",e.config.systemPromptId||"",e.updatedAt||"",e.createdByScheduleId||"",e.lastRunStatus||"",e.lastRunError||"",...e.messages.filter(r=>r.role==="user"&&"content"in r).slice(0,3).map(r=>"content"in r?r.content:"")].join(" ").toLowerCase();return t.split(/\s+/).filter(Boolean).every(r=>n.includes(r))},$d=(e,t,n)=>{switch(t){case"pinned":return!!e.pinned;case"running":return n(e.id);case"child":return e.kind==="child";case"all":default:return!0}},Kk=()=>{const{t:e}=Ie(),{message:t}=sn.useApp(),n=te(H=>H.chats),s=te(H=>H.currentSessionId),r=te(H=>H.deleteSession),a=te(H=>H.deleteSessions),i=te(H=>H.pinSession),l=te(H=>H.unpinSession),c=te(H=>H.updateSession),u=te(H=>H.addChat),m=te(H=>H.refreshChats),f=te(H=>H.lastSelectedPromptId),g=te(H=>H.systemPrompts),b=p.useCallback(H=>dr(H)(te.getState()),[]),S=wt(H=>H.sidebar.collapsed),x=wt(H=>H.setSidebarCollapsed),T=wt(H=>H.clearSessionFromAllLeaves),j=p.useCallback(async(H,ye)=>{var ot,gt;const xe=g.find(_t=>_t.id===f),_e=(xe==null?void 0:xe.id)||(g.length>0?((ot=g.find(_t=>_t.id==="general_assistant"))==null?void 0:ot.id)||g[0].id:""),Ue={title:H||e("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:_e,baseSystemPrompt:(xe==null?void 0:xe.content)||(g.length>0?((gt=g.find(_t=>_t.id==="general_assistant"))==null?void 0:gt.content)||g[0].content:""),lastUsedEnhancedPrompt:null},...ye},Re=await u(Ue),{activeLeafId:ut}=wt.getState();wt.getState().setLeafSessionId(ut,Re),wt.getState().setActiveLeafId(ut)},[u,f,g,e]),[w,M]=p.useState(!1),[_,C]=p.useState(new Set(["Today"])),[L,A]=p.useState(""),[B,N]=p.useState("all"),[O,R]=p.useState({}),I=te(Er(s)),$=p.useMemo(()=>I?Rp(I):null,[I]),U=p.useMemo(()=>{const H=new Set(_);return $&&H.add($),Array.from(H)},[$,_]),q=H=>{const ye=new Set(Array.isArray(H)?H:[H]);C(xe=>{if(xe.size!==ye.size)return ye;for(const _e of ye)if(!xe.has(_e))return ye;return xe})},K=L.trim().toLowerCase(),P=K.length>0||B!=="all",W=p.useMemo(()=>n.filter(H=>H.kind!=="child"),[n]),se=p.useMemo(()=>{const H={};for(const ye of n){if(ye.kind!=="child")continue;const xe=ye.parentSessionId||ye.rootSessionId;xe&&(H[xe]||(H[xe]=[]),H[xe].push(ye))}return Object.keys(H).forEach(ye=>{H[ye].sort((xe,_e)=>{if(xe.pinned!==_e.pinned)return xe.pinned?-1:1;const Ue=Date.parse(xe.updatedAt||"")||xe.createdAt||0;return(Date.parse(_e.updatedAt||"")||_e.createdAt||0)-Ue})}),H},[n]),V=p.useMemo(()=>P?W.filter(H=>Od(H,K)&&$d(H,B,b)?!0:(se[H.id]||[]).some(_e=>Od(_e,K)&&$d(_e,B,b))):W,[se,P,b,K,W,B]),ie=p.useMemo(()=>{if(!P)return se;const H={};for(const ye of V){const xe=se[ye.id]||[];H[ye.id]=xe.filter(_e=>Od(_e,K)&&$d(_e,B,b))}return H},[se,V,P,b,K,B]),re=Ck(V),fe=Mk(re),Se=p.useCallback(H=>{i(H),C(ye=>{if(ye.has("Pinned"))return ye;const xe=new Set(ye);return xe.add("Pinned"),xe})},[i]),ke=p.useCallback(H=>{const ye=n.find(_e=>_e.id===H),xe=ye?Rp({...ye,pinned:!1}):null;l(H),xe&&C(_e=>{if(_e.has(xe))return _e;const Ue=new Set(_e);return Ue.add(xe),Ue})},[n,l]),Be=H=>{Xn.confirm({title:e("chat.sidebar.delete.title"),content:e("chat.sidebar.delete.confirm"),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{T(H),r(H)}})},tt=sr(H=>H.open),ft=()=>{tt("chat")},Ht=p.useCallback(H=>{A(H)},[]),Oe=p.useCallback(H=>{N(H)},[]),zt=(H,ye)=>{c(H,{title:ye})},Ye=p.useCallback(async H=>{try{await Jn.getInstance().regenerateSessionTitle(H)}catch(ye){console.error("Failed to regenerate session title:",ye)}},[]),we=p.useCallback(async H=>{var xe;if(((xe=O[H])==null?void 0:xe.status)==="loading")return;R(_e=>({..._e,[H]:{status:"loading"}}));const ye=t.loading(e("chat.actions.runProjectDreamRunning"),0);try{const _e=await Jn.getInstance().runProjectDream(H);ye(),_e.dream_generated?t.success(e("chat.actions.runProjectDreamSuccess")):t.info(_e.message||e("chat.actions.runProjectDreamNoChange"));try{await m()}catch(Ue){console.warn("Failed to refresh chats after project dream run:",Ue)}}catch(_e){ye();const Ue=_e instanceof Error&&_e.message?_e.message:e("chat.actions.runProjectDreamFailed");t.error(Ue),console.error("Failed to run project dream:",_e)}finally{R(_e=>({..._e,[H]:{status:"idle"}}))}},[t,O,m,e]),Ke=H=>{const ye=Pk(re,H),xe=ex(re,H);Xn.confirm({title:e("chat.sidebar.deleteByDate.title",{date:H}),content:e("chat.sidebar.deleteByDate.confirm",{count:xe,date:H}),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{ye.forEach(_e=>T(_e)),a(ye)}})},st=()=>{M(!0)},Dt=()=>{M(!1)},F=async H=>{try{await j(e("chat.sidebar.newSessionWithPrompt",{prompt:H.name}),{config:{systemPromptId:H.id,baseSystemPrompt:H.content,lastUsedEnhancedPrompt:null}}),M(!1)}catch(ye){console.error("Failed to create chat:",ye),Xn.error({title:e("chat.sidebar.createFailedTitle"),content:ye instanceof Error?ye.message:e("chat.sidebar.createFailedUnknown")})}},ce=p.useCallback(H=>qc(H),[]),[ge,De]=p.useState(new Set),Le=p.useMemo(()=>{var xe;const H=new Set(ge),ye=n.find(_e=>_e.id===s);if(ye){const _e=ye.kind==="child"?ye.parentSessionId||ye.rootSessionId:ye.id;_e&&H.add(_e)}for(const _e of n)if(_e.kind==="child"&&_e.pinned){const Ue=_e.parentSessionId||_e.rootSessionId;Ue&&H.add(Ue)}if(P)for(const _e of V)(((xe=ie[_e.id])==null?void 0:xe.length)??0)>0&&H.add(_e.id);return H},[n,ie,s,ge,V,P]),me=p.useCallback(H=>{De(ye=>{const xe=new Set(ye);return xe.has(H)?xe.delete(H):xe.add(H),xe})},[]);return{chats:V,childrenByRoot:ie,expandedRootIds:Le,toggleRootExpanded:me,collapsed:S,currentSessionId:s,expandedKeys:U,groupedChatsByDate:re,hasActiveFilters:P,handleCollapseChange:q,handleDelete:Be,handleDeleteByDate:Ke,handleEditTitle:zt,handleGenerateTitle:Ye,handleNewChat:st,handleNewChatSelectorClose:Dt,handleOpenSettings:ft,handleRunProjectDream:we,handleSearchQueryChange:Ht,handleStatusFilterChange:Oe,handleSystemPromptSelect:F,isNewChatSelectorOpen:w,pinSession:Se,projectDreamState:O,searchQuery:L,selectSession:ce,setCollapsed:x,sortedDateKeys:fe,statusFilter:B,systemPrompts:g,titleGenerationState:{},unpinSession:ke}},{useBreakpoint:Vk}=Nc,{useToken:Yk}=Ge,$p=()=>{const{token:e}=Yk(),{t}=Ie(),n=Vk(),{childrenByRoot:s,expandedRootIds:r,toggleRootExpanded:a,collapsed:i,currentSessionId:l,expandedKeys:c,groupedChatsByDate:u,handleCollapseChange:m,handleDelete:f,handleDeleteByDate:g,handleEditTitle:b,handleGenerateTitle:S,handleNewChat:x,handleNewChatSelectorClose:T,handleOpenSettings:j,handleRunProjectDream:w,handleSearchQueryChange:M,handleStatusFilterChange:_,handleSystemPromptSelect:C,hasActiveFilters:L,isNewChatSelectorOpen:A,pinSession:B,projectDreamState:N,searchQuery:O,selectSession:R,setCollapsed:I,sortedDateKeys:$,statusFilter:U,systemPrompts:q,titleGenerationState:K,unpinSession:P}=Kk(),{xs:W,sm:se}=n;return p.useEffect(()=>{typeof W!="boolean"||typeof se!="boolean"||W===!1&&se===!1&&I(!0)},[se,W,I]),i?null:o.jsxs("nav",{"data-tour-id":"sidebar","aria-label":t("chat.sidebar.title","Chat sidebar"),style:{width:"100%",height:"100%",background:"transparent",borderRight:`1px solid ${e.colorBorderSecondary}`,position:"relative",overflow:"hidden",display:"flex",flexDirection:"column",minHeight:0},children:[o.jsx(be,{justify:"flex-end",style:{flexShrink:0,padding:"10px 12px 2px 12px",minHeight:40},children:o.jsx(ue,{type:"text",icon:o.jsx(pb,{}),onClick:()=>I(!0),size:n.xs?"small":"middle",className:"lotus-toolbar-icon","aria-label":t("chat.sidebar.collapse","Collapse sidebar")})}),o.jsxs(be,{vertical:!0,gap:"small",style:{flexShrink:0,padding:"10px 12px 8px 12px"},children:[o.jsx(Qe,{allowClear:!0,value:O,onChange:V=>M(V.target.value),prefix:o.jsx($i,{style:{color:e.colorTextTertiary}}),placeholder:t("chat.sidebar.searchPlaceholder","Search sessions"),"aria-label":t("chat.sidebar.searchPlaceholder","Search sessions"),size:n.xs?"middle":"large",style:{borderRadius:e.borderRadiusLG}}),o.jsx(Nw,{block:!0,size:n.xs?"middle":"small",value:U,onChange:V=>_(V),options:[{label:t("chat.sidebar.filters.all","All"),value:"all"},{label:t("chat.sidebar.filters.pinned","Pinned"),value:"pinned"},{label:t("chat.sidebar.filters.running","Running"),value:"running"},{label:t("chat.sidebar.filters.child","Child"),value:"child"}]})]}),o.jsx(be,{vertical:!0,role:"list","aria-label":t("chat.sidebar.chatList","Chat list"),style:{flex:1,minHeight:0,overflowY:"auto",padding:"0 12px 0 12px"},children:o.jsx(Ek,{groupedChatsByDate:u,childrenByRoot:s,expandedRootIds:r,onToggleRootExpanded:a,sortedDateKeys:$,expandedKeys:c,onCollapseChange:m,currentSessionId:l,onSelectChat:R,onDeleteChat:f,onDeleteByDate:g,onPinChat:B,onUnpinChat:P,onEditTitle:b,onGenerateTitle:S,onRunProjectDream:w,titleGenerationState:K,projectDreamState:N,token:e,hasActiveFilters:L})}),o.jsx(Dk,{collapsed:!1,onNewChat:x,onOpenSettings:j,screens:n,token:e}),o.jsx(kk,{open:A,onClose:T,onSelect:C,prompts:q,title:t("chat.prompt.newSessionSelectorTitle"),showCancelButton:!0})]})},Dp=e=>Symbol.iterator in e,Lp=e=>"entries"in e,Fp=(e,t)=>{const n=e instanceof Map?e:new Map(e.entries()),s=t instanceof Map?t:new Map(t.entries());if(n.size!==s.size)return!1;for(const[r,a]of n)if(!Object.is(a,s.get(r)))return!1;return!0},Xk=(e,t)=>{const n=e[Symbol.iterator](),s=t[Symbol.iterator]();let r=n.next(),a=s.next();for(;!r.done&&!a.done;){if(!Object.is(r.value,a.value))return!1;r=n.next(),a=s.next()}return!!r.done&&!!a.done};function Gk(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:Dp(e)&&Dp(t)?Lp(e)&&Lp(t)?Fp(e,t):Xk(e,t):Fp({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Jk(e){const t=fn.useRef(void 0);return n=>{const s=e(n);return Gk(t.current,s)?t.current:t.current=s}}function Qk(){const{chats:e,currentSessionId:t,currentChat:n,addMessage:s,selectSession:r,deleteSession:a,deleteSessions:i,deleteMessage:l,updateSession:c,persistSessionTitle:u,pinSession:m,unpinSession:f,loadChats:g}=te(Jk(w=>({chats:w.chats,currentSessionId:w.currentSessionId,currentChat:Hm(w),addMessage:w.addMessage,selectSession:w.selectSession,deleteSession:w.deleteSession,deleteSessions:w.deleteSessions,deleteMessage:w.deleteMessage,updateSession:w.updateSession,persistSessionTitle:w.persistSessionTitle,pinSession:w.pinSession,unpinSession:w.unpinSession,loadChats:w.loadChats}))),b=te(dr(t)),S=p.useMemo(()=>(n==null?void 0:n.messages)||[],[n]),x=p.useMemo(()=>e.filter(w=>w.pinned),[e]),T=p.useMemo(()=>e.filter(w=>!w.pinned),[e]),j=e.length;return{chats:e,currentSessionId:t,currentChat:n,isProcessing:b,baseMessages:S,pinnedChats:x,unpinnedChats:T,chatCount:j,addMessage:s,deleteMessage:l,selectSession:r,deleteSession:a,deleteSessions:i,pinSession:m,unpinSession:f,updateSession:c,persistSessionTitle:u,loadChats:g}}function Zk(e){const t=te(g=>g.addChat),n=te(g=>g.lastSelectedPromptId),s=te(g=>g.systemPrompts),r=Jn.getInstance(),a=p.useCallback(async(g,b)=>{var j,w;const S=s.find(M=>M.id===n),x=(S==null?void 0:S.id)||(s.length>0?((j=s.find(M=>M.id==="general_assistant"))==null?void 0:j.id)||s[0].id:""),T={title:g||"New Session",createdAt:Date.now(),messages:[],config:{systemPromptId:x,baseSystemPrompt:(S==null?void 0:S.content)||(s.length>0?((w=s.find(M=>M.id==="general_assistant"))==null?void 0:w.content)||s[0].content:""),lastUsedEnhancedPrompt:null,...Mt.getState().isProviderModelRefEnabled()?{model_ref:Mt.getState().selectedModelRef}:{}},...b};await t(T)},[t,n,s]),i=p.useCallback(async g=>{Jt("[ChatOps]","[useChatOperations] createChatWithSystemPrompt started with prompt:",g);const b={title:`New Session - ${g.name}`,createdAt:Date.now(),messages:[],config:{systemPromptId:g.id,baseSystemPrompt:g.content,lastUsedEnhancedPrompt:null}};Jt("[ChatOps]","[useChatOperations] Calling addChat with newChatData.config:",b.config),await t(b)},[t]),l=p.useCallback(g=>{const b=e.chats.find(S=>S.id===g);b&&(b.pinned?e.unpinSession(g):e.pinSession(g))},[e]),c=p.useCallback((g,b)=>{e.updateSession(g,{title:b})},[e]),u=p.useCallback(async()=>{await r.cleanupSessions("empty",!0),await te.getState().loadChats()},[r]),m=p.useCallback(async()=>{await r.cleanupSessions("all",!0),await te.getState().loadChats()},[r]),f=p.useCallback(async()=>{await r.cleanupSessions("all",!1),await te.getState().loadChats()},[r]);return{createNewChat:a,createChatWithSystemPrompt:i,toggleChatPin:l,updateChatTitle:c,deleteEmptyChats:u,deleteAllUnpinnedChats:m,deleteAllChats:f}}const pi=new Map,Ql=new Set,wo=new Map,Mi=new Map;let fi=null;const sx=(e,t)=>{const n=pi.get(e);n&&n.forEach(s=>s(t))},Np=()=>{if(fi=null,Mi.size===0)return;const e=Array.from(Mi.values());Mi.clear(),e.forEach(t=>{sx(t.messageId,t.content),Ql.forEach(n=>n(t))})},It={getLatest(e){return wo.get(e)??null},subscribeMessage(e,t){let n=pi.get(e);return n||(n=new Set,pi.set(e,n)),n.add(t),wo.has(e)&&t(wo.get(e)??null),()=>{const s=pi.get(e);s&&(s.delete(t),s.size===0&&pi.delete(e))}},subscribe(e){return Ql.add(e),()=>{Ql.delete(e)}},publish(e){e.content===null?wo.delete(e.messageId):wo.set(e.messageId,e.content),Mi.set(e.messageId,e),fi===null&&(fi=requestAnimationFrame(Np))},clear(e,t){wo.delete(t),Mi.delete(t),sx(t,null),Ql.forEach(n=>n({sessionId:e,messageId:t,content:null}))},forceFlush(){fi!==null&&(cancelAnimationFrame(fi),Np())}},rx="mermaid_enhancement_enabled",Nu=()=>localStorage.getItem(rx)!=="false",eT=e=>{localStorage.setItem(rx,e.toString())},tT=()=>`
|
|
15
|
+
|
|
16
|
+
## 📊 Visual Representation Guidelines
|
|
17
|
+
|
|
18
|
+
When explaining concepts, processes, relationships, or data structures, use Mermaid diagrams to enhance understanding. Choose appropriate diagram types:
|
|
19
|
+
|
|
20
|
+
- **Flowcharts** (graph TD/LR) - processes, workflows, decision trees
|
|
21
|
+
- **Sequence Diagrams** - API interactions, communication flows
|
|
22
|
+
- **Class Diagrams** - object relationships, data models
|
|
23
|
+
- **State Diagrams** - state machines, status flows
|
|
24
|
+
- **Gantt Charts** - project timelines
|
|
25
|
+
- **ER Diagrams** - database schemas
|
|
26
|
+
- **Git Graphs** - version control workflows
|
|
27
|
+
|
|
28
|
+
**Syntax Notes:**
|
|
29
|
+
- Mermaid diagram definitions MUST be inside a fenced code block (never inline). Example:
|
|
30
|
+
\`\`\`mermaid
|
|
31
|
+
graph TD
|
|
32
|
+
A --> B
|
|
33
|
+
\`\`\`
|
|
34
|
+
- Avoid nested brackets: use \`A[Text]\` or \`A(Text)\`, NOT \`A[Text()]\`
|
|
35
|
+
- Use HTML entities for special chars: # for #, ; for ;, " for quotes
|
|
36
|
+
- Keep participant names simple (no spaces): \`participant UserService\`
|
|
37
|
+
- Arrow syntax: \`-->\` (solid), \`-.->\` (dotted), \`==>\` (thick), \`-->|label|\` (labeled)
|
|
38
|
+
|
|
39
|
+
Include relevant diagrams when discussing architecture, workflows, data flow, or relationships.`,zu="task_enhancement_enabled",zp="todo_enhancement_enabled",nT=e=>e==="false",Bu=()=>{let e=localStorage.getItem(zu);if(e===null){const t=localStorage.getItem(zp);t!==null&&(e=t,localStorage.setItem(zu,t),localStorage.removeItem(zp))}return!nT(e)},sT=e=>{localStorage.setItem(zu,e.toString())},rT=()=>`
|
|
40
|
+
|
|
41
|
+
## Task Management Rules
|
|
42
|
+
|
|
43
|
+
Use the Task tool for non-trivial or multi-step tasks.
|
|
44
|
+
Task updates are shared across the current root session and all child sessions.
|
|
45
|
+
Keep exactly one item in \`in_progress\` state whenever possible.
|
|
46
|
+
Update Task immediately when a step starts or completes; do not batch status updates.
|
|
47
|
+
When marking a task as completed, always fill in the \`summary\` field with a concise description of what was accomplished.
|
|
48
|
+
Do not use Markdown checkbox lists as a substitute for Task.
|
|
49
|
+
Skip Task only for simple one-step requests.
|
|
50
|
+
Use SubSession only when the user explicitly requests delegated/parallel sub-session work.
|
|
51
|
+
`,ox=()=>{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"},oT=e=>{switch(e){case"windows":return"Windows";case"macos":return"macOS";case"linux":return"Linux";default:return"Unknown OS"}},aT=()=>{const e=ox(),n=`## 🖥️ Operating System Information
|
|
52
|
+
|
|
53
|
+
You are running on **${oT(e)}**.`;return e==="windows"?n+`
|
|
54
|
+
|
|
55
|
+
### Windows-Specific Notes:
|
|
56
|
+
|
|
57
|
+
- **Configuration Directory**: Application configuration and data are stored in the user's home directory at \`.bamboo\` (e.g., \`C:\\Users\\[Username]\\.bamboo\`)
|
|
58
|
+
- Note: When accessing this directory programmatically, use the expanded path rather than the ~ shorthand
|
|
59
|
+
|
|
60
|
+
- **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.
|
|
61
|
+
- Example: \`~/Documents/file.txt\` should be expanded to \`C:\\Users\\[Username]\\Documents\\file.txt\`
|
|
62
|
+
- Use tools to get the actual home directory path when needed
|
|
63
|
+
- Note: This applies to leading tilde only. Windows short paths like \`C:\\PROGRA~1\\\` are valid and should NOT be modified
|
|
64
|
+
- Some Windows shells (PowerShell, Git Bash, WSL) may support ~ in specific contexts, but Windows-native paths/APIs generally do not
|
|
65
|
+
|
|
66
|
+
- **Path Separators**: Windows uses backslashes (\\) as path separators, but forward slashes (/) are also accepted in most contexts
|
|
67
|
+
- **Case Insensitivity**: Windows file paths are case-insensitive (file.txt and FILE.TXT refer to the same file)
|
|
68
|
+
- **Drive Letters**: Windows paths typically start with a drive letter (C:\\, D:\\, etc.)`:e==="macos"?n+`
|
|
69
|
+
|
|
70
|
+
### macOS-Specific Notes:
|
|
71
|
+
|
|
72
|
+
- **Configuration Directory**: Application configuration and data are stored in \`~/.bamboo\` (expands to \`/Users/[Username]/.bamboo\`)
|
|
73
|
+
|
|
74
|
+
- **File Paths**: macOS uses Unix-style paths with forward slashes (/)
|
|
75
|
+
- **Home Directory**: The tilde (~) expands to /Users/[Username]
|
|
76
|
+
- **Case Sensitivity**: macOS file system may be case-sensitive or case-insensitive depending on format (APFS is case-insensitive by default)`:e==="linux"?n+`
|
|
77
|
+
|
|
78
|
+
### Linux-Specific Notes:
|
|
79
|
+
|
|
80
|
+
- **Configuration Directory**: Application configuration and data are stored in \`~/.bamboo\` (expands to \`/home/[username]/.bamboo\`)
|
|
81
|
+
|
|
82
|
+
- **File Paths**: Linux uses Unix-style paths with forward slashes (/)
|
|
83
|
+
- **Home Directory**: The tilde (~) expands to /home/[username]
|
|
84
|
+
- **Case Sensitivity**: Linux file systems are case-sensitive (File.txt and file.txt are different files)`:n},ax="copilot_conclusion_with_options_enhancement_enabled",wc=()=>localStorage.getItem(ax)==="true",iT=e=>{try{localStorage.setItem(ax,e.toString())}catch(t){console.error("[copilotConclusionWithOptionsEnhancement] Failed to persist setting:",t)}},lT=()=>"\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",cT=()=>["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(" "),ix="bamboo_system_prompt_enhancement",dT=()=>["## 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(`
|
|
85
|
+
`),uT=e=>e.map(n=>n.trim()).filter(n=>n.length>0).join(`
|
|
86
|
+
|
|
87
|
+
`),lx=()=>{try{return localStorage.getItem(ix)??""}catch(e){return console.error("Failed to load system prompt enhancement:",e),""}},mT=e=>{try{const t=e.trim()?e:"";localStorage.setItem(ix,t)}catch(t){console.error("Failed to save system prompt enhancement:",t)}},hT=e=>{const t=[];t.push(aT().trim()),t.push(dT().trim());const n=lx().trim();return n&&t.push(n),Nu()&&t.push(tT().trim()),Bu()&&t.push(rT().trim()),(e??"").trim().toLowerCase()==="copilot"&&wc()&&t.push(lT().trim()),t},pT=e=>uT(hT(e)),Wu=e=>{const t=(e??"").trim().toLowerCase();return t.includes("completion policy violation")&&t.includes("conclusion_with_options")},qu=e=>{const t=(e??"").trim(),n=t?`
|
|
88
|
+
|
|
89
|
+
Raw error: ${t}`:"";return["Bamboo stopped this completion because Copilot conclusion_with_options confirmation is enabled for this session.","The assistant tried to finish with plain text instead of calling conclusion_with_options.","Next steps: retry the request, shorten or clarify the prompt, or temporarily disable the Copilot conclusion_with_options enhancement for this session if you do not want enforced confirmation."].join(" ")+n};function Ym(e){const t=Mt(r=>r.providerConfig),n=te(Er(e??null));return p.useMemo(()=>{var c,u,m,f,g,b,S;const r=e?(c=n==null?void 0:n.config)==null?void 0:c.model_ref:void 0,a=(u=r==null?void 0:r.model)==null?void 0:u.trim();if(a)return a;const i=e?(f=(m=n==null?void 0:n.config)==null?void 0:m.model)==null?void 0:f.trim():void 0;return i&&i!=="unknown"?i:((S=(b=(g=t.defaults)==null?void 0:g.chat)==null?void 0:b.model)==null?void 0:S.trim())||void 0},[n,t,e])}function fT(e){const t=Ym(e),n=Mt(s=>s.providerConfig);return p.useMemo(()=>{var r,a,i;return((i=(a=(r=n.defaults)==null?void 0:r.fast)==null?void 0:a.model)==null?void 0:i.trim())||t},[n,t])}function Xm(e){const t=Mt(r=>r.isProviderModelRefEnabled),n=Mt(r=>r.selectedModelRef),s=Mt(r=>r.providerConfig.defaults);return p.useMemo(()=>{var r,a;return t()?e||n||((a=(r=s==null?void 0:s.chat)==null?void 0:r.model)!=null&&a.trim()?s.chat:null):null},[e,n,s,t])}function gT(){const e=Mt(t=>t.getFastModelRef);return p.useMemo(()=>e(),[e])}function cx(e){var K;const{sessionId:t,addMessage:n,updateSession:s}=e,{modal:r,message:a}=sn.useApp(),{t:i}=Ie(),l=p.useRef(null),c=p.useRef(null),u=p.useRef(""),m=p.useRef(new Jn),f=te(P=>P.agentAvailability),g=te(P=>P.setAgentAvailability),b=te(P=>P.checkAgentAvailability),S=te(P=>P.startAgentHealthCheck),x=te(P=>P.markOptimisticStart),T=te(P=>P.markRetryStart),j=te(P=>P.markSettleTimeout),w=te(P=>P.applyExecutionStarted),M=Ym(t),_=Mt(P=>P.currentProvider),C=te(P=>t&&P.chats.find(W=>W.id===t)||null),L=Xm((K=C==null?void 0:C.config)==null?void 0:K.model_ref);p.useEffect(()=>{S()},[S]);const A=p.useCallback(()=>{var W;(W=l.current)==null||W.abort();const P=C==null?void 0:C.id;P&&m.current.stopGeneration(P).catch(se=>{console.error("[useMessageStreaming] Failed to stop generation:",se)})},[C==null?void 0:C.id]),B=p.useCallback(P=>{var Be;const W=te.getState(),V=(Array.isArray(W.chats)?W.chats:[]).find(tt=>tt.id===P),ie=Ci(P)(W),re=(ie==null?void 0:ie.sessionId)===P?ie:null,fe=(Be=V==null?void 0:V.config)==null?void 0:Be.syncCursor,Se=!!re||!!(fe!=null&&fe.hasPendingQuestion),ke=(re==null?void 0:re.toolCallId)??(fe==null?void 0:fe.pendingQuestionToolCallId)??null;return{client_message_count:(fe==null?void 0:fe.messageCount)??(V==null?void 0:V.messageCount)??0,client_last_message_id:(fe==null?void 0:fe.lastMessageId)??null,client_has_pending_question:Se,client_pending_question_tool_call_id:ke}},[]),N=p.useCallback((P,W)=>{const se=W.sync;if(!se)return;const V=te.getState(),re=(Array.isArray(V.chats)?V.chats:[]).find(fe=>fe.id===P);re&&s(P,{messageCount:se.server_message_count,config:{...re.config||{},syncCursor:{messageCount:se.server_message_count,lastMessageId:se.server_last_message_id??null,hasPendingQuestion:se.has_pending_question,pendingQuestionToolCallId:se.pending_question_tool_call_id??null}}})},[s]),O=p.useCallback(async P=>{try{return await Ze.get(`respond/${P}/pending`)}catch(W){return console.warn(`[useMessageStreaming] Failed to fetch pending question for ${P}:`,W),{has_pending_question:!1}}},[]),R=p.useCallback(async(P,W,se)=>{var ke,Be;j(P),await te.getState().loadChatHistory(P,{mode:"replace"});const V=await O(P),ie=te.getState().setPendingQuestion,re=te.getState().clearPendingQuestion;if(V.has_pending_question){ie(P,{question:V.question||"",options:V.options||[],allowCustom:V.allow_custom??!0,toolCallId:V.tool_call_id??null});const tt=te.getState().chats.find(ft=>ft.id===P);return tt&&s(P,{config:{...tt.config||{},syncCursor:{messageCount:tt.messageCount??tt.messages.length,lastMessageId:((Be=(ke=tt.config)==null?void 0:ke.syncCursor)==null?void 0:Be.lastMessageId)??null,hasPendingQuestion:!0,pendingQuestionToolCallId:V.tool_call_id??null}}}),null}if(re(P),!((W==null?void 0:W.has_pending_user_message)??!1))return null;x(P),await new Promise(tt=>setTimeout(tt,0));const Se=se?await m.current.execute(P,void 0,se,B(P),L??void 0):await m.current.execute(P,void 0,void 0,B(P),L??void 0);return N(P,Se),Se},[L,N,B,O,x,j,s]),I=p.useCallback(async(P,W,se)=>{var fe,Se;let V=W;N(P,V);const ie=2;let re=0;for(;(fe=V.sync)!=null&&fe.need_sync&&re<ie;){const ke=await R(P,V.sync,se);if(re+=1,!ke){j(P);return}V=ke,N(P,V)}if((Se=V.sync)!=null&&Se.need_sync){console.warn(`[useMessageStreaming] Execute remains out-of-sync after ${ie} recovery attempt(s) for session ${P}.`,V.sync),j(P);return}if(["started","already_running"].includes(V.status)){if(V.run_id){const ke=Sc(P)(te.getState());w(P,V.run_id,ke)}return}if(V.status==="completed"){Jt("[Streaming]","[Agent] Session already completed"),j(P);return}throw console.error("[Agent] Execute failed:",V.status),j(P),new Error(`Execute failed: ${V.status}`)},[N,R,j,w]),$=p.useCallback(async(P,W,se,V,ie)=>{var fe,Se;if(!M)throw new Error(i("chat.model.noModelSelected"));const re=new AbortController;l.current=re;try{const ke=pT(_).trim(),Be=(_??"").trim().toLowerCase()==="copilot"&&wc(),ft=(((fe=C==null?void 0:C.config)==null?void 0:fe.workspacePath)||"").trim().replace(/\/+$/,"").replace(/\\+$/,""),Ht=await m.current.sendMessage({message:P,session_id:W,enhance_prompt:ke||void 0,copilot_conclusion_with_options_enhancement_enabled:Be,workspace_path:ft||void 0,selected_skill_ids:ie&&ie.length>0?ie:void 0,images:(Se=se.images)==null?void 0:Se.filter(Ye=>!!Ye.base64).map(Ye=>({base64:Ye.base64,name:Ye.name,size:Ye.size,type:Ye.type})),model:M,...L?{model_ref:L,provider:L.provider}:{}}),{session_id:Oe}=Ht;Oe!==W&&console.warn(`[useMessageStreaming] Backend returned unexpected session_id=${Oe} for sessionId=${W}`),await te.getState().loadChatHistory(W,{mode:"replace"});const zt=V?await m.current.execute(W,void 0,V,B(W),L??void 0):await m.current.execute(W,void 0,void 0,B(W),L??void 0);Jt("[Streaming]","[Agent] Execute status:",zt.status),await I(W,zt,V)}catch(ke){throw ke}},[M,L,B,C,_,t,I,i]),U=p.useCallback(async(P,W,se,V)=>{if(!C){r.info({title:i("chat.streaming.noActiveChatTitle"),content:i("chat.streaming.noActiveChatSendContent")});return}if(!t){r.info({title:i("chat.streaming.noChatIdTitle"),content:i("chat.streaming.noChatIdSendContent")});return}if(!M){r.error({title:i("chat.model.noModelSelected"),content:i("chat.model.selectModelBeforeSend")});return}let ie=f;if(ie===null&&(ie=await b()),!ie){a.error(i("chat.streaming.agentUnavailable"));return}if(!M){a.error(i("chat.streaming.modelConfigNotLoaded"));return}const re=t,fe=(W==null?void 0:W.map(ke=>({id:ke.id,base64:ke.base64,name:ke.name,size:ke.size,type:ke.type})))||[],Se={role:"user",content:P,id:crypto.randomUUID(),createdAt:new Date().toISOString(),images:fe};await n(re,Se),x(re),await new Promise(ke=>setTimeout(ke,0));try{Jt("[Streaming]","[useChatStreaming] Using Agent Server"),await $(P,re,Se,se,V)}catch(ke){if(c.current&&It.clear(re,c.current),c.current=null,u.current="",ke instanceof Error&&ke.name==="AbortError")a.info(i("chat.streaming.requestCancelled"));else{console.error("[useChatStreaming] Failed to send message:",ke);const Be=ke instanceof Error?ke.message:String(ke??"");Wu(Be)?a.error(qu(Be)):(a.error(i("chat.streaming.sendFailed")),g(!1))}j(re)}finally{l.current=null,c.current&&It.clear(re,c.current),c.current=null,u.current=""}},[f,a,b,C,t,n,r,$,g,M,i,x,j]),q=p.useCallback(async(P,W="regenerate")=>{if(!C){r.info({title:i("chat.streaming.noActiveChatTitle"),content:i("chat.streaming.noActiveChatRetryContent")});return}if(!t){r.info({title:i("chat.streaming.noChatIdTitle"),content:i("chat.streaming.noChatIdRetryContent")});return}if(!M){r.error({title:i("chat.model.noModelSelected"),content:i("chat.model.selectModelBeforeRetry")});return}let se=f;if(se===null&&(se=await b()),!se){a.error(i("chat.streaming.agentUnavailable"));return}const V=t;c.current&&It.clear(V,c.current),c.current=null,u.current="";try{const ie=W==="error_retry"?"error_retry":"after_last_user",re=await m.current.truncateSessionMessages(V,{mode:ie});(W==="regenerate"||(re.messages_removed??0)>0)&&await te.getState().loadChatHistory(V,{mode:"replace"}),T(V);const fe=P?await m.current.execute(V,void 0,P,B(V),L??void 0):await m.current.execute(V,void 0,void 0,B(V),L??void 0);await I(V,fe,P)}catch(ie){console.error("[useMessageStreaming] Retry failed:",ie);const re=ie instanceof Error?ie.message:String(ie??"");Wu(re)?a.error(qu(re)):a.error(i("chat.streaming.retryFailed")),j(V)}finally{l.current=null}},[M,L,f,a,B,b,C,t,I,r,i,T,j]);return{sendMessage:U,retryLastTurn:q,cancel:A,agentAvailable:f}}function yT(e,t){const n=p.useMemo(()=>e.baseMessages,[e.baseMessages]),s=p.useCallback(async()=>{var u;if(!e.currentSessionId||!e.currentChat)return;const r=[...e.baseMessages];if(r.length===0)return;const a=r[r.length-1];let i=r;if((a==null?void 0:a.role)==="assistant"){if(!(await e.deleteMessage(e.currentSessionId,a.id)).success)return;i=r.slice(0,-1)}const l=[...i].reverse().find(m=>m.role==="user");if(!l)return;const c="content"in l?l.content:l.displayText;typeof c=="string"&&await((u=t==null?void 0:t.onRetry)==null?void 0:u.call(t,c))},[e,t]);return{currentMessages:n,retryLastMessage:s}}const bT=()=>{const e=Qk(),t=Zk(e),n=cx({sessionId:e.currentSessionId,addMessage:e.addMessage,updateSession:e.updateSession}),s=yT(e,{onRetry:n.sendMessage});return{chats:e.chats,currentSessionId:e.currentSessionId,currentChat:e.currentChat,pinnedChats:e.pinnedChats,unpinnedChats:e.unpinnedChats,chatCount:e.chatCount,currentMessages:s.currentMessages,agentAvailable:n.agentAvailable,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,createNewChat:t.createNewChat,createChatWithSystemPrompt:t.createChatWithSystemPrompt,toggleChatPin:t.toggleChatPin,updateChatTitle:t.updateChatTitle,deleteEmptyChats:t.deleteEmptyChats,deleteAllUnpinnedChats:t.deleteAllUnpinnedChats,deleteAllChats:t.deleteAllChats,retryLastMessage:s.retryLastMessage,sendMessage:n.sendMessage,cancelMessage:n.cancel}},dx="lotus_vdi_safe_mode",_c=()=>{try{return localStorage.getItem(dx)==="true"}catch{return!1}},xT=e=>{try{localStorage.setItem(dx,e.toString())}catch(t){console.error("[vdiSafeMode] Failed to persist setting:",t)}},{Text:Ml}=He,{useToken:vT}=Ge,ST=({httpProxy:e,httpsProxy:t,onHttpProxyChange:n,onHttpsProxyChange:s,onReload:r,onSave:a,isLoading:i})=>{const{t:l}=Ie(),{token:c}=vT(),u=Ms(_=>_.proxyAuthStatus),m=Ms(_=>_.isLoadingProxyAuthStatus),f=Ms(_=>_.loadProxyAuthStatus),g=Ms(_=>_.applyProxyAuth),b=Ms(_=>_.clearProxyAuth),[S,x]=p.useState({username:"",password:""}),[T,j]=p.useState(!1);p.useEffect(()=>{f()},[f]);const w=async()=>{const _=S.username.trim();if(_){j(!0);try{await g({username:_,password:S.password}),x({username:"",password:""})}catch(C){console.error("Failed to apply proxy auth:",C)}finally{j(!1)}}},M=async()=>{j(!0);try{await b()}catch(_){console.error("Failed to clear proxy auth:",_)}finally{j(!1)}};return o.jsx(Ce,{size:"small",title:o.jsx(Ml,{strong:!0,children:l("settings.networkCard.title")}),className:"lotus-settings-card",children:o.jsxs(he,{direction:"vertical",size:c.marginSM,style:{width:"100%"},children:[o.jsx(Ut,{message:l("settings.networkCard.guideTip"),type:"info",showIcon:!0}),o.jsxs(he,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[o.jsx(Ml,{type:"secondary",children:l("settings.networkCard.httpProxy")}),o.jsx(Qe,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:_=>n(_.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),o.jsxs(he,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[o.jsx(Ml,{type:"secondary",children:l("settings.networkCard.httpsProxy")}),o.jsx(Qe,{style:{width:"100%"},value:t,onChange:_=>s(_.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),o.jsx(Ce,{size:"small",title:l("settings.networkCard.proxyAuthTitle"),className:"lotus-settings-card",style:{marginTop:c.marginSM},children:u!=null&&u.configured?o.jsxs(he,{direction:"vertical",style:{width:"100%"},children:[o.jsx(Ut,{type:"success",message:l("settings.networkCard.proxyConfiguredForUser",{username:u.username??""}),showIcon:!0}),o.jsx(ue,{onClick:M,loading:T||m,danger:!0,children:l("settings.networkCard.clearCredentials")})]}):o.jsxs(he,{direction:"vertical",size:c.marginXS,style:{width:"100%"},children:[o.jsx(Qe,{placeholder:l("settings.networkCard.username"),value:S.username,onChange:_=>x(C=>({...C,username:_.target.value}))}),o.jsx(Qe.Password,{placeholder:l("settings.networkCard.password"),value:S.password,onChange:_=>x(C=>({...C,password:_.target.value}))}),o.jsx(ue,{type:"primary",onClick:w,loading:T||m,disabled:!S.username.trim(),children:l("settings.networkCard.apply")})]})}),o.jsx(Ml,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("settings.networkCard.credentialsStorageNote")}),o.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:c.marginSM},children:[o.jsx(ue,{onClick:()=>Promise.resolve(r()).finally(()=>f({force:!0})),disabled:i,children:l("settings.networkCard.reload")}),o.jsx(ue,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(a()).finally(()=>f({force:!0})),disabled:i,children:l("settings.networkCard.save")})]})]})})},{Text:wT}=He,{useToken:_T}=Ge,kT=({msgApi:e})=>{const{t}=Ie(),{token:n}=_T(),[s]=Pe.useForm(),[r,a]=p.useState(!1),[i,l]=p.useState(!1),[c,u]=p.useState(!1),[m,f]=p.useState(!1),[g,b]=p.useState(null),S=c&&!m,x=p.useMemo(()=>c?m?t("settings.configTab.accessPassword.helperLocalBypass","当前是本地访问,可直接修改访问密码,无需输入当前密码。"):t("settings.configTab.accessPassword.helperRemote","当前是远程访问。修改访问密码前,必须先输入当前密码。"):t("settings.configTab.accessPassword.helperNotEnabled","未设置访问密码。设置后,远程访问需要先输入密码,本地 loopback 访问可直接绕过。"),[m,c,t]),T=p.useCallback(async()=>{a(!0),b(null);try{const w=await Yt.getAccessStatus();u(w.password_enabled),f(w.local_bypass)}catch(w){const M=w instanceof Error?w.message:t("settings.configTab.accessPassword.loadStatusFailed","Failed to load access status");b(M)}finally{a(!1)}},[t]);p.useEffect(()=>{T()},[T]);const j=async()=>{var w;try{const M=await s.validateFields();l(!0),await Yt.updateAccessPassword({current_password:((w=M.currentPassword)==null?void 0:w.trim())||void 0,new_password:M.newPassword.trim()}),e.success(c?t("settings.configTab.accessPassword.updated","访问密码已更新"):t("settings.configTab.accessPassword.enabled","访问密码已设置")),s.resetFields(),await T()}catch(M){if(M.errorFields)return;const _=M instanceof Error?M.message:t("settings.configTab.accessPassword.updateFailed","Failed to update access password");e.error(_)}finally{l(!1)}};return o.jsx(Ce,{size:"small",className:"lotus-settings-card",title:o.jsx(wT,{strong:!0,children:t("settings.configTab.accessPasswordTitle","访问密码")}),children:o.jsxs(he,{direction:"vertical",size:n.marginMD,style:{width:"100%"},children:[o.jsx(Ut,{type:c?"info":"warning",showIcon:!0,message:c?t("settings.configTab.accessPassword.statusEnabled","访问密码已启用"):t("settings.configTab.accessPassword.statusDisabled","访问密码未启用"),description:x}),g?o.jsx(Ut,{type:"error",showIcon:!0,message:g}):null,o.jsxs(Pe,{form:s,layout:"vertical",disabled:r||i,children:[S?o.jsx(Pe.Item,{label:t("settings.configTab.accessPassword.currentPasswordLabel","当前密码"),name:"currentPassword",rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.currentPasswordRequired","请输入当前密码")}],children:o.jsx(Qe.Password,{autoComplete:"current-password"})}):null,o.jsx(Pe.Item,{label:c?t("settings.configTab.accessPassword.newPasswordLabel","新密码"):t("settings.configTab.accessPassword.setPasswordLabel","设置密码"),name:"newPassword",rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.newPasswordRequired","请输入新密码")},{min:4,message:t("settings.configTab.accessPassword.validation.minLength","密码长度至少 4 位")}],children:o.jsx(Qe.Password,{autoComplete:"new-password"})}),o.jsx(Pe.Item,{label:t("settings.configTab.accessPassword.confirmPasswordLabel","确认密码"),name:"confirmPassword",dependencies:["newPassword"],rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.confirmPasswordRequired","请再次输入新密码")},({getFieldValue:w})=>({validator(M,_){return!_||w("newPassword")===_?Promise.resolve():Promise.reject(new Error(t("settings.configTab.accessPassword.validation.passwordMismatch","两次输入的密码不一致")))}})],children:o.jsx(Qe.Password,{autoComplete:"new-password"})}),o.jsx(ue,{type:"primary",loading:i,onClick:()=>void j(),children:c?t("settings.configTab.accessPassword.updateAction","更新访问密码"):t("settings.configTab.accessPassword.enableAction","启用访问密码")})]})]})})},{Text:cs}=He,{useToken:TT}=Ge,Bp="http://127.0.0.1:9562/v1",gi=e=>[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort(),jT=e=>{var n;const t=(n=e.tools)==null?void 0:n.disabled;return Array.isArray(t)?gi(t.filter(s=>typeof s=="string")):[]},CT=({msgApi:e,locale:t,onLocaleChange:n})=>{const{t:s}=Ie(),{token:r}=TT(),[a,i]=p.useState({http_proxy:"",https_proxy:"",memory:{auto_dream_enabled:!1,background_model:""}}),[l,c]=p.useState(Bp),[u,m]=p.useState([]),[f,g]=p.useState([]),[b,S]=p.useState([]),[x,T]=p.useState(!1),[j,w]=p.useState(!1),M=p.useCallback(async()=>{var K,P;T(!0);try{const[W,se]=await Promise.all([Yt.getBambooConfig(),Yt.getBambooTools()]);i({http_proxy:W.http_proxy||"",https_proxy:W.https_proxy||"",memory:{auto_dream_enabled:((K=W.memory)==null?void 0:K.auto_dream_enabled)??!1,background_model:((P=W.memory)==null?void 0:P.background_model)||""}});const V=jT(W);g(V),S(V),m(gi(se.tools||[]))}catch(W){console.error("Failed to load config:",W),e.error(s("settings.configTab.loadConfigFailed"))}finally{T(!1)}},[e,s]);p.useEffect(()=>{M()},[M]);const _=K=>{i(P=>({...P,http_proxy:K}))},C=K=>{i(P=>({...P,https_proxy:K}))},L=K=>{i(P=>({...P,memory:{...P.memory,auto_dream_enabled:K}}))},A=K=>{i(P=>({...P,memory:{...P.memory,background_model:K}}))},B=async()=>{var K,P;T(!0);try{const W=await Yt.validateBambooConfigPatch(a);if(!W.valid){const V=((P=(K=W.errors)==null?void 0:K.proxy)==null?void 0:P[0])??Object.values(W.errors||{}).flat().filter(Boolean)[0];e.error((V==null?void 0:V.message)||s("settings.configTab.invalidConfig"));return}await Yt.setBambooConfig(a),e.success(s("settings.configTab.saveConfigSuccess"))}catch(W){console.error("Failed to save config:",W);const se=W instanceof Error&&W.message.trim()?W.message:s("settings.configTab.saveConfigFailed");e.error(se)}finally{T(!1)}},N=async()=>{e.success(s("settings.configTab.backendSaved"))},O=()=>{c(Bp),e.success(s("settings.configTab.backendResetDefault"))},R=(K,P)=>{g(W=>{const se=new Set(W);return P?se.delete(K):se.add(K),gi([...se])})},I=async()=>{w(!0);try{const K=await Yt.getBambooTools();m(gi(K.tools||[])),e.success(s("settings.configTab.toolsReloadSuccess"))}catch(K){console.error("Failed to reload tools:",K),e.error(s("settings.configTab.toolsLoadFailed"))}finally{w(!1)}},$=async()=>{w(!0);try{const K=gi(f);await Yt.setBambooConfig({tools:{disabled:K}}),g(K),S(K),e.success(s("settings.configTab.toolsSaveSuccess"))}catch(K){console.error("Failed to save tool settings:",K),e.error(s("settings.configTab.toolsSaveFailed"))}finally{w(!1)}},U=JSON.stringify(f)!==JSON.stringify(b),q=new Set(f);return o.jsx(Rs,{spinning:x,tip:s("settings.common.loading"),children:o.jsx(Di,{items:[{key:"general",label:s("settings.configTab.tabs.general"),children:o.jsxs(he,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[o.jsx(Ut,{message:s("settings.configTab.providerMovedTitle"),description:s("settings.configTab.providerMovedDescription"),type:"info",showIcon:!0,closable:!0}),o.jsx(ST,{httpProxy:a.http_proxy,httpsProxy:a.https_proxy,onHttpProxyChange:_,onHttpsProxyChange:C,onReload:M,onSave:B,isLoading:x}),o.jsx(Ce,{size:"small",className:"lotus-settings-card",title:o.jsx(cs,{strong:!0,children:s("settings.configTab.language")}),children:o.jsx(St,{value:t,style:{width:260},options:[{label:s("settings.configTab.languageEnglish"),value:"en-US"},{label:s("settings.configTab.languageChinese"),value:"zh-CN"},{label:s("settings.configTab.languageTraditionalChinese"),value:"zh-TW"},{label:s("settings.configTab.languageFrench"),value:"fr-FR"},{label:s("settings.configTab.languageJapanese"),value:"ja-JP"},{label:s("settings.configTab.languageHindi"),value:"hi-IN"}],onChange:K=>n(K)})}),o.jsx(Ce,{size:"small",className:"lotus-settings-card",title:o.jsx(cs,{strong:!0,children:s("settings.configTab.memoryTitle")}),children:o.jsxs(he,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[o.jsx(cs,{type:"secondary",children:s("settings.configTab.memoryDescription")}),o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:r.marginMD,flexWrap:"wrap"},children:[o.jsxs("div",{children:[o.jsx(cs,{strong:!0,children:s("settings.configTab.autoDreamEnabled")}),o.jsx("div",{children:o.jsx(cs,{type:"secondary",style:{fontSize:r.fontSizeSM},children:s("settings.configTab.autoDreamEnabledHint")})})]}),o.jsx(pn,{"data-testid":"auto-dream-toggle",checked:a.memory.auto_dream_enabled,onChange:L})]}),o.jsxs(he,{direction:"vertical",size:r.marginXXS,style:{width:"100%"},children:[o.jsx(cs,{strong:!0,children:s("settings.configTab.backgroundModel")}),o.jsx(Qe,{"data-testid":"auto-dream-background-model-input",value:a.memory.background_model,onChange:K=>A(K.target.value),placeholder:s("settings.configTab.backgroundModelPlaceholder")}),o.jsx(cs,{type:"secondary",style:{fontSize:r.fontSizeSM},children:s("settings.configTab.backgroundModelHint")})]}),o.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:o.jsx(ue,{"data-testid":"save-memory-settings",type:"primary",onClick:B,loading:x,children:s("settings.configTab.save")})})]})}),o.jsx(Ce,{size:"small",title:o.jsx(cs,{strong:!0,children:s("settings.configTab.backendApiBaseUrlTitle")}),children:o.jsxs(he,{direction:"vertical",size:r.marginSM,style:{width:"100%"},children:[o.jsx(he,{direction:"vertical",size:r.marginXXS,style:{width:"100%"},children:o.jsx(Qe,{style:{width:"100%"},value:l,onChange:K=>c(K.target.value),placeholder:s("settings.configTab.backendApiPlaceholder")})}),o.jsx(cs,{type:"secondary",style:{fontSize:r.fontSizeSM},children:s("settings.configTab.backendApiHint")}),o.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:r.marginSM},children:[o.jsx(ue,{"data-testid":"reset-to-defaults",onClick:O,children:s("settings.configTab.resetToDefault")}),o.jsx(ue,{"data-testid":"save-api-settings",type:"primary",onClick:N,children:s("settings.configTab.save")})]})]})}),o.jsx(kT,{msgApi:e})]})},{key:"tools",label:s("settings.configTab.tabs.tools"),children:o.jsx(Ce,{size:"small",title:o.jsx(cs,{strong:!0,children:s("settings.configTab.toolsTitle")}),children:o.jsxs(he,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[o.jsx(cs,{type:"secondary",children:s("settings.configTab.toolsDescription")}),u.length===0?o.jsx(Ut,{type:"info",showIcon:!0,message:s("settings.configTab.toolsEmpty")}):o.jsx(Qt,{bordered:!0,dataSource:u,renderItem:K=>o.jsx(Qt.Item,{actions:[o.jsx(pn,{checked:!q.has(K),onChange:P=>R(K,P)},`${K}-switch`)],children:o.jsx(cs,{code:!0,children:K})})}),o.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:r.marginSM},children:[o.jsx(ue,{onClick:I,loading:j,children:s("settings.configTab.reloadTools")}),o.jsx(ue,{type:"primary",onClick:$,loading:j,disabled:!U,children:s("settings.configTab.save")})]})]})})}]})})},Wp={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},Gm=Pr()(B_(e=>({settings:Wp,updateSettings:t=>e(n=>({settings:{...n.settings,...t}})),resetSettings:()=>e({settings:Wp})}),{name:"mermaid-settings"})),Uc=()=>Gm(t=>t.settings),MT=()=>Gm(e=>e.updateSettings),PT=()=>Gm(e=>e.resetSettings),{Title:ET,Text:Dd}=He,{useToken:RT}=Ge,AT=()=>{const{t:e}=Ie(),{token:t}=RT(),n=Uc(),s=MT(),r=PT(),[a]=Pe.useForm();fn.useEffect(()=>{a.setFieldsValue(n)},[n,a]);const i=c=>{s(c)},l=()=>{r(),a.resetFields()};return o.jsxs("div",{style:{padding:"24px",maxWidth:"1200px",margin:"0 auto"},children:[o.jsx(ET,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),o.jsx(Dd,{type:"secondary",style:{display:"block",marginBottom:"24px"},children:e("settings.mermaidTab.description")}),o.jsxs(Pe,{form:a,layout:"vertical",initialValues:n,onValuesChange:i,children:[o.jsxs(Ce,{title:e("settings.mermaidTab.themeCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[o.jsx(ps,{gutter:16,children:o.jsx(Et,{span:24,children:o.jsx(Pe.Item,{name:"theme",label:o.jsxs(he,{children:[e("settings.mermaidTab.themeLabel"),o.jsx(bt,{title:e("settings.mermaidTab.themeTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsxs(St,{children:[o.jsx(St.Option,{value:"default",children:e("settings.mermaidTab.themeOptions.default")}),o.jsx(St.Option,{value:"neutral",children:e("settings.mermaidTab.themeOptions.neutral")}),o.jsx(St.Option,{value:"dark",children:e("settings.mermaidTab.themeOptions.dark")}),o.jsx(St.Option,{value:"forest",children:e("settings.mermaidTab.themeOptions.forest")}),o.jsx(St.Option,{value:"base",children:e("settings.mermaidTab.themeOptions.base")})]})})})}),o.jsxs(Dd,{type:"secondary",style:{display:"block",marginTop:"8px"},children:[o.jsx("strong",{children:e("settings.mermaidTab.themeDescriptionsTitle")}),o.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.default"),o.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.neutral"),o.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.dark"),o.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.forest"),o.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.base")]})]}),o.jsxs(Ce,{title:e("settings.mermaidTab.globalCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[o.jsxs(ps,{gutter:16,children:[o.jsx(Et,{span:12,children:o.jsx(Pe.Item,{name:"fontSize",label:o.jsxs(he,{children:[e("settings.mermaidTab.fontSizeLabel"),o.jsx(bt,{title:e("settings.mermaidTab.fontSizeTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Zt,{min:10,max:32,step:1,style:{width:"100%"},addonAfter:"px"})})}),o.jsx(Et,{span:12,children:o.jsx(Pe.Item,{name:"defaultScale",label:o.jsxs(he,{children:[e("settings.mermaidTab.defaultZoomLabel"),o.jsx(bt,{title:e("settings.mermaidTab.defaultZoomTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Zt,{min:.1,max:3,step:.1,style:{width:"100%"}})})})]}),o.jsx(Pe.Item,{name:"useMaxWidth",label:o.jsxs(he,{children:[e("settings.mermaidTab.responsiveWidthLabel"),o.jsx(bt,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),valuePropName:"checked",children:o.jsx(pn,{})})]}),o.jsx(Ce,{title:e("settings.mermaidTab.flowchartCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:o.jsxs(ps,{gutter:16,children:[o.jsx(Et,{span:8,children:o.jsx(Pe.Item,{name:"flowchartNodeSpacing",label:o.jsxs(he,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),o.jsx(bt,{title:e("settings.mermaidTab.flowchartNodeSpacingTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Zt,{min:20,max:200,step:10,style:{width:"100%"}})})}),o.jsx(Et,{span:8,children:o.jsx(Pe.Item,{name:"flowchartRankSpacing",label:o.jsxs(he,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),o.jsx(bt,{title:e("settings.mermaidTab.flowchartRankSpacingTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Zt,{min:20,max:200,step:10,style:{width:"100%"}})})}),o.jsx(Et,{span:8,children:o.jsx(Pe.Item,{name:"flowchartCurve",label:o.jsxs(he,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),o.jsx(bt,{title:e("settings.mermaidTab.flowchartCurveTypeTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsxs(St,{children:[o.jsx(St.Option,{value:"basis",children:e("settings.mermaidTab.flowchartCurveOptions.basis")}),o.jsx(St.Option,{value:"linear",children:e("settings.mermaidTab.flowchartCurveOptions.linear")}),o.jsx(St.Option,{value:"cardinal",children:e("settings.mermaidTab.flowchartCurveOptions.cardinal")})]})})})]})}),o.jsx(Ce,{title:e("settings.mermaidTab.sequenceCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:o.jsxs(ps,{gutter:16,children:[o.jsx(Et,{span:6,children:o.jsx(Pe.Item,{name:"sequenceActorMargin",label:o.jsxs(he,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),o.jsx(bt,{title:e("settings.mermaidTab.sequenceActorMarginTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Zt,{min:20,max:200,step:10,style:{width:"100%"}})})}),o.jsx(Et,{span:6,children:o.jsx(Pe.Item,{name:"sequenceMessageMargin",label:o.jsxs(he,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),o.jsx(bt,{title:e("settings.mermaidTab.sequenceMessageMarginTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Zt,{min:10,max:100,step:5,style:{width:"100%"}})})}),o.jsx(Et,{span:6,children:o.jsx(Pe.Item,{name:"sequenceWidth",label:o.jsxs(he,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),o.jsx(bt,{title:e("settings.mermaidTab.sequenceActorWidthTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Zt,{min:100,max:300,step:10,style:{width:"100%"}})})}),o.jsx(Et,{span:6,children:o.jsx(Pe.Item,{name:"sequenceHeight",label:o.jsxs(he,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),o.jsx(bt,{title:e("settings.mermaidTab.sequenceActorHeightTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Zt,{min:40,max:150,step:5,style:{width:"100%"}})})})]})}),o.jsx(Ce,{title:e("settings.mermaidTab.ganttCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:o.jsxs(ps,{gutter:16,children:[o.jsx(Et,{span:12,children:o.jsx(Pe.Item,{name:"ganttBarHeight",label:o.jsxs(he,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),o.jsx(bt,{title:e("settings.mermaidTab.ganttBarHeightTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Zt,{min:10,max:50,step:5,style:{width:"100%"},addonAfter:"px"})})}),o.jsx(Et,{span:12,children:o.jsx(Pe.Item,{name:"ganttTopPadding",label:o.jsxs(he,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),o.jsx(bt,{title:e("settings.mermaidTab.ganttTopPaddingTooltip"),children:o.jsx(Kn,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Zt,{min:20,max:100,step:10,style:{width:"100%"}})})})]})}),o.jsx(he,{children:o.jsx(ue,{icon:o.jsx(zw,{}),onClick:l,children:e("settings.mermaidTab.resetToDefaults")})}),o.jsx(zn,{}),o.jsx(Ce,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:t.colorBgElevated}},children:o.jsx(Dd,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},IT=p.lazy(()=>Bn(()=>import("./index-D-36MGco.js"),__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url)),{Text:Fr}=He,{useToken:OT}=Ge,$T=({promptEnhancement:e,onPromptEnhancementChange:t,mermaidEnhancementEnabled:n,taskEnhancementEnabled:s,showCopilotConclusionWithOptionsEnhancement:r,copilotConclusionWithOptionsEnhancementEnabled:a,onMermaidToggle:i,onTaskToggle:l,onCopilotConclusionWithOptionsToggle:c,onSaveEnhancement:u})=>{const{t:m}=Ie(),{token:f}=OT(),g=f.marginLG;return o.jsxs(be,{vertical:!0,gap:g,children:[o.jsx(Ce,{size:"small",className:"lotus-settings-card",children:o.jsx(p.Suspense,{fallback:o.jsx(Rs,{size:"small"}),children:o.jsx(IT,{})})}),o.jsx(Ce,{size:"small",className:"lotus-settings-card",children:o.jsxs(he,{direction:"vertical",size:f.marginXS,style:{width:"100%"},children:[o.jsx(Fr,{strong:!0,children:m("settings.promptsTab.title")}),o.jsxs(be,{align:"center",gap:f.marginSM,children:[o.jsx(Fr,{strong:!0,children:m("settings.promptsTab.mermaidEnhancement")}),o.jsx(pn,{checked:n,onChange:i})]}),o.jsxs(be,{align:"center",gap:f.marginSM,children:[o.jsx(Fr,{strong:!0,children:m("settings.promptsTab.taskListRules")}),o.jsx(pn,{checked:s,onChange:l})]}),r&&o.jsxs(he,{direction:"vertical",size:f.marginXXS,style:{width:"100%"},children:[o.jsxs(be,{align:"center",gap:f.marginSM,children:[o.jsx(Fr,{strong:!0,children:m("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),o.jsx(pn,{checked:a,onChange:c})]}),o.jsx(Fr,{type:"secondary",style:{fontSize:f.fontSizeSM},children:m("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:cT()})})]}),o.jsx(Qe.TextArea,{rows:6,placeholder:m("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:b=>t(b.target.value)}),o.jsx(be,{justify:"flex-end",children:o.jsx(ue,{type:"primary",onClick:u,children:m("settings.promptsTab.saveEnhancement")})}),o.jsx(Fr,{type:"secondary",style:{fontSize:f.fontSizeSM},children:m("settings.promptsTab.description")})]})}),n&&o.jsx(ir,{size:"small",items:[{key:"mermaid",label:o.jsx(Fr,{strong:!0,children:m("settings.mermaidTab.title")}),children:o.jsx(AT,{})}]})]})},Jm="bodhi_onboarding_complete",DT=()=>localStorage.getItem(Jm)==="true",LT=()=>localStorage.setItem(Jm,"true"),FT=()=>localStorage.removeItem(Jm),NT=["new-session","task-templates","model-picker","sidebar","open-settings"],zT=()=>{const e={};for(const t of NT)e[t]=document.querySelector(`[data-tour-id="${t}"]`);return e},BT=({disabled:e=!1})=>{const{t}=Ie(),[n,s]=p.useState(!1),[r,a]=p.useState(null);p.useEffect(()=>{if(e||DT())return;const c=setTimeout(()=>{const u=zT();a(u),s(!0)},800);return()=>clearTimeout(c)},[e]);const i=p.useMemo(()=>[{title:t("onboarding.welcome.title"),description:t("onboarding.welcome.description"),target:null},{title:t("onboarding.newSession.title"),description:t("onboarding.newSession.description"),target:(r==null?void 0:r["new-session"])??void 0},{title:t("onboarding.taskTemplates.title"),description:t("onboarding.taskTemplates.description"),target:(r==null?void 0:r["task-templates"])??void 0},{title:t("onboarding.modelPicker.title"),description:t("onboarding.modelPicker.description"),target:(r==null?void 0:r["model-picker"])??void 0},{title:t("onboarding.sidebar.title"),description:t("onboarding.sidebar.description"),target:(r==null?void 0:r.sidebar)??void 0},{title:t("onboarding.settings.title"),description:t("onboarding.settings.description"),target:(r==null?void 0:r["open-settings"])??void 0}],[t,r]),l=()=>{LT(),s(!1)};return o.jsx(Bw,{open:n,onClose:l,steps:i})},{Text:fr}=He,{useToken:WT}=Ge,qT=({themeMode:e,onThemeModeChange:t,vdiSafeMode:n,onVdiSafeModeToggle:s,onClearLocalStorage:r,onResetApp:a,isResetting:i,darkModeKey:l})=>{const{t:c}=Ie(),{token:u}=WT();return o.jsx(Ce,{size:"small",className:"lotus-settings-card",children:o.jsxs(he,{direction:"vertical",size:u.marginSM,style:{width:"100%"},children:[o.jsxs(be,{align:"center",justify:"space-between",gap:u.marginSM,children:[o.jsx(fr,{strong:!0,children:c("settings.appTab.runningVersion","Running version")}),o.jsxs(fr,{code:!0,"data-testid":"settings-app-version",children:["v",Km]})]}),o.jsx(fr,{type:"secondary",style:{fontSize:u.fontSizeSM},children:c("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),o.jsxs(be,{align:"center",gap:u.marginSM,children:[o.jsx(fr,{strong:!0,children:c("settings.appTab.darkMode")}),o.jsx(pn,{"data-testid":"dark-mode-toggle",checked:e==="dark",onChange:m=>{const f=m?"dark":"light";t(f),localStorage.setItem(l,f)}})]}),o.jsxs(be,{align:"center",gap:u.marginSM,children:[o.jsx(fr,{strong:!0,children:c("settings.appTab.vdiSafeMode","Graphics compatibility mode")}),o.jsx(pn,{"data-testid":"vdi-safe-mode-toggle",checked:n,onChange:s})]}),o.jsx(fr,{type:"secondary",style:{fontSize:u.fontSizeSM},children:c("settings.appTab.vdiSafeModeDesc","Disables blur and glass effects that can break dropdowns and hover overlays in some virtual desktop, remote, or graphics-constrained environments.")}),o.jsx(ue,{block:!0,icon:o.jsx(Cm,{}),onClick:()=>{FT(),window.location.reload()},children:c("settings.appTab.resetStepReplayGuide")}),o.jsx(hc,{title:c("settings.appTab.clearLocalStorageTitle"),description:c("settings.appTab.clearLocalStorageDescription"),onConfirm:r,okText:c("settings.appTab.confirmClear"),cancelText:c("settings.appTab.cancel"),placement:"top",children:o.jsx(ue,{danger:!0,block:!0,icon:o.jsx(Mr,{}),children:c("settings.appTab.clearLocalStorageButton")})}),o.jsx(zn,{style:{margin:`${u.marginSM}px 0`}}),o.jsxs(be,{align:"center",gap:u.marginSM,children:[o.jsx(Vi,{style:{color:u.colorError}}),o.jsx(fr,{strong:!0,style:{color:u.colorError},children:c("settings.appTab.dangerZone")})]}),o.jsx(fr,{type:"secondary",style:{fontSize:u.fontSizeSM},children:c("settings.appTab.dangerDescription")}),o.jsx(hc,{title:c("settings.appTab.resetApplicationTitle"),description:o.jsxs("div",{children:[o.jsx("p",{children:c("settings.appTab.resetApplicationIntro")}),o.jsxs("ul",{style:{margin:0,paddingLeft:16},children:[o.jsx("li",{children:c("settings.appTab.resetStepDeleteAllSessions")}),o.jsx("li",{children:c("settings.appTab.resetStepClearStorage")}),o.jsx("li",{children:c("settings.appTab.resetStepResetConfig")}),o.jsx("li",{children:c("settings.appTab.resetStepSetupFlow")}),o.jsx("li",{children:c("settings.appTab.resetStepReload")})]})]}),onConfirm:a,okText:c("settings.appTab.resetConfirm"),cancelText:c("settings.appTab.cancel"),placement:"top",okButtonProps:{danger:!0},children:o.jsx(ue,{"data-testid":"reset-to-defaults",danger:!0,block:!0,type:"primary",icon:o.jsx(fb,{}),loading:i,children:c("settings.appTab.resetButton")})})]})})},{Text:Nr}=He,{useToken:UT}=Ge,qp=[{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,}"}],HT=(e,t,n)=>{if(!t)return{masked:e};if(n==="exact")return{masked:e.split(t).join("[MASKED]")};try{const s=new RegExp(t,"g");return{masked:e.replace(s,"[MASKED]")}}catch(s){return{masked:e,error:s instanceof Error?s.message:Es.t("settings.keywordMaskingTab.invalidRegexPattern")}}},KT=()=>{const{t:e}=Ie(),{message:t}=sn.useApp(),{token:n}=UT(),[s,r]=p.useState([]),[a,i]=p.useState(!1),[l,c]=p.useState(null),[u,m]=p.useState(""),[f,g]=p.useState("exact"),[b,S]=p.useState(!0),[x,T]=p.useState(),[j,w]=p.useState("My token is sk-123"),M=p.useCallback(async()=>{try{i(!0);const $=await Is.getInstance().getKeywordMaskingConfig();r($.entries)}catch(I){t.error(e("settings.keywordMaskingTab.loadFailed")),console.error(I)}finally{i(!1)}},[e]);p.useEffect(()=>{M()},[M]);const _=async I=>{try{const $=Is.getInstance(),U=await $.validateKeywordEntries(I);if(!U.valid&&U.errors){const K=U.errors.map(P=>`Entry ${P.index+1}: ${P.message}`).join("; ");return t.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${K}`),!1}const q=await $.updateKeywordMaskingConfig(I);return r(q.entries),t.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch($){return t.error($ instanceof Error?$.message:e("settings.keywordMaskingTab.saveFailed")),!1}},C=async()=>{const I={pattern:"",match_type:"exact",enabled:!0},$=[...s,I];r($),c($.length-1),m(""),g("exact"),S(!0),T(void 0)},L=I=>{const $=s[I];c(I),m($.pattern),g($.match_type),S($.enabled),T(void 0)},A=async()=>{if(l===null)return;if(!u.trim()){t.error(e("settings.keywordMaskingTab.patternRequired"));return}const I=[...s];I[l]={pattern:u.trim(),match_type:f,enabled:b},await _(I)&&c(null)},B=()=>{var I;l!==null&&!((I=s[l])!=null&&I.pattern)&&r(s.filter(($,U)=>U!==l)),c(null)},N=async I=>{const $=s.filter((U,q)=>q!==I);await _($)},O=async(I,$)=>{const U=[...s];U[I]={...U[I],enabled:$},await _(U)},R=HT(j,u,f);return o.jsx(Ce,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:o.jsx(ue,{"data-testid":"add-keyword",type:"primary",icon:o.jsx(rr,{}),onClick:C,loading:a,children:e("settings.keywordMaskingTab.addKeyword")}),children:o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:"large",children:[o.jsx(Nr,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),o.jsx(Qt,{loading:a,dataSource:s,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(I,$)=>o.jsx(Qt.Item,{style:{backgroundColor:n.colorFillAlter,marginBottom:8,borderRadius:n.borderRadius,padding:12},actions:l===$?[o.jsx(ue,{"data-testid":"save-keyword",type:"primary",icon:o.jsx(zc,{}),onClick:A,"aria-label":e("settings.keywordMaskingTab.save")},"save"),o.jsx(ue,{onClick:B,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[o.jsx(ue,{icon:o.jsx(Hi,{}),onClick:()=>L($),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),o.jsx(ue,{"data-testid":`delete-keyword-${$}`,danger:!0,icon:o.jsx(Mr,{}),onClick:()=>N($),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:o.jsx(be,{vertical:!0,style:{width:"100%"},gap:8,children:l===$?o.jsxs(o.Fragment,{children:[o.jsx(Qe,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:u,onChange:U=>m(U.target.value),autoFocus:!0}),o.jsxs(be,{gap:8,align:"center",wrap:"wrap",children:[o.jsx(St,{"data-testid":"keyword-examples-select","aria-label":e("settings.keywordMaskingTab.examples"),placeholder:e("settings.keywordMaskingTab.examples"),value:x,onChange:U=>{T(U);const q=qp.find(K=>K.value===U);q&&(m(q.pattern),g(q.match_type))},options:qp.map(U=>({value:U.value,label:e(U.labelKey)})),style:{minWidth:220}}),o.jsx(St,{value:f,onChange:g,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),o.jsx(pn,{checked:b,onChange:S})]}),o.jsxs(be,{vertical:!0,gap:6,children:[o.jsx(Nr,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),o.jsx(Qe,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:j,onChange:U=>w(U.target.value)}),o.jsx(Nr,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),o.jsx(Qe,{readOnly:!0,value:R.masked,status:R.error?"error":void 0}),R.error&&o.jsx(Nr,{type:"danger",children:R.error})]})]}):o.jsxs(be,{justify:"space-between",align:"center",children:[o.jsxs(be,{vertical:!0,gap:4,children:[o.jsx(Nr,{strong:!0,children:I.pattern||e("settings.keywordMaskingTab.emptyPattern")}),o.jsxs(be,{gap:8,children:[o.jsx(Nr,{type:"secondary",style:{fontSize:12},children:I.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!I.enabled&&o.jsx(Nr,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),o.jsx(pn,{checked:I.enabled,onChange:U=>O($,U),size:"small"})]})})})})]})})},{Text:_o,Paragraph:VT}=He,YT=/^[A-Za-z_][A-Za-z0-9_]*$/,XT=()=>{const{t:e}=Ie(),{message:t}=sn.useApp(),[n,s]=p.useState([]),[r,a]=p.useState(!1),[i,l]=p.useState(!1),[c,u]=p.useState(null),[m]=Pe.useForm(),f=p.useCallback(async()=>{a(!0);try{const w=await Vn.getEnvVars();s(w.entries)}catch{t.error(e("settings.envVars.fetchError","Failed to load environment variables"))}finally{a(!1)}},[e]);p.useEffect(()=>{f()},[f]);const g=async w=>{var _;const M={name:w.name.trim(),value:w.value,secret:w.secret??!1,description:((_=w.description)==null?void 0:_.trim())||void 0};try{const C=await Vn.upsertEnvVar(M);s(C.entries),t.success(c?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),T()}catch(C){t.error((C instanceof Error?C.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},b=async w=>{try{const M=await Vn.deleteEnvVar(w);s(M.entries),t.success(e("settings.envVars.deleted","Variable deleted"))}catch(M){t.error((M instanceof Error?M.message:void 0)||e("settings.envVars.deleteError","Failed to delete variable"))}},S=()=>{u(null),m.resetFields(),m.setFieldsValue({secret:!1}),l(!0)},x=w=>{u(w.name),m.setFieldsValue({name:w.name,value:"",secret:w.secret,description:w.description??""}),l(!0)},T=()=>{l(!1),u(null),m.resetFields()},j=[{title:e("settings.envVars.name","Name"),dataIndex:"name",key:"name",render:w=>o.jsx(_o,{code:!0,children:w})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(w,M)=>M.secret?o.jsxs(_o,{type:"secondary",children:[o.jsx(sp,{style:{marginRight:4}}),M.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):o.jsx(_o,{children:w||o.jsx(_o,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(w,M)=>M.secret?o.jsx(Ne,{color:"warning",icon:o.jsx(sp,{}),children:e("settings.envVars.secret","Secret")}):o.jsx(Ne,{color:"processing",children:e("settings.envVars.plain","Plain")})},{title:e("settings.envVars.descriptionCol","Description"),dataIndex:"description",key:"description",ellipsis:!0,render:w=>w?o.jsx(_o,{type:"secondary",children:w}):o.jsx(_o,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(w,M)=>o.jsxs(he,{size:"small",children:[o.jsx(ue,{type:"text",size:"small",icon:o.jsx(Hi,{}),onClick:()=>x(M),"aria-label":e("settings.envVars.edit","Edit")}),o.jsx(hc,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>b(M.name),okText:e("settings.envVars.yes","Yes"),cancelText:e("settings.envVars.no","No"),children:o.jsx(ue,{type:"text",size:"small",danger:!0,icon:o.jsx(Mr,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return o.jsxs("div",{style:{maxWidth:900},children:[o.jsxs(Ce,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:o.jsx(ue,{type:"primary",icon:o.jsx(rr,{}),onClick:S,children:e("settings.envVars.addButton","Add Variable")}),children:[o.jsx(VT,{type:"secondary",style:{marginBottom:16},children:e("settings.envVars.description","Variables are injected into Bash tool processes. Secret variables are encrypted at rest.")}),o.jsx(or,{dataSource:n,columns:j,rowKey:"name",size:"small",pagination:!1,loading:r,locale:{emptyText:e("settings.envVars.noVars","No environment variables configured")}})]}),o.jsx(Xn,{title:c?e("settings.envVars.editTitle","Edit Variable"):e("settings.envVars.addTitle","Add Environment Variable"),open:i,onCancel:T,onOk:()=>m.submit(),okText:e("settings.envVars.save","Save"),cancelText:e("settings.envVars.cancel","Cancel"),destroyOnClose:!0,children:o.jsxs(Pe,{form:m,layout:"vertical",onFinish:g,initialValues:{secret:!1},children:[o.jsx(Pe.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:YT,message:e("settings.envVars.nameInvalid","Must start with a letter or underscore, followed by letters, digits, or underscores")}],children:o.jsx(Qe,{placeholder:"GITHUB_TOKEN",disabled:c!==null,autoFocus:c===null})}),o.jsx(Pe.Item,{name:"value",label:e("settings.envVars.value","Value"),rules:[{required:c===null,message:e("settings.envVars.valueRequired","Value is required for new variables")}],extra:c?e("settings.envVars.valueEditHint","Leave empty to keep the existing value"):void 0,children:o.jsx(Qe.Password,{placeholder:c?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),o.jsx(Pe.Item,{name:"secret",label:e("settings.envVars.secret","Secret"),valuePropName:"checked",extra:e("settings.envVars.secretHint","Secret variables are encrypted on disk and masked in the UI"),children:o.jsx(pn,{})}),o.jsx(Pe.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:o.jsx(Qe,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},eo=class eo{constructor(){}static getInstance(){return eo.instance||(eo.instance=new eo),eo.instance}async listWorkflows(){try{Jt("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const t=await rt.get("bamboo/workflows"),n=Array.isArray(t)?t:[];return Jt("[WorkflowManager]","[WorkflowManagerService] Listed workflows:",n),n.map(s=>({name:String(s.name||""),filename:String(s.filename||(s.name||"workflow")+".md"),size:Number(s.size||0),modified_at:typeof s.modified_at=="string"?s.modified_at:void 0,source:"global"}))}catch(t){throw console.error("[WorkflowManagerService] Failed to list workflows:",t),t}}async getWorkflow(t){try{Jt("[WorkflowManager]","[WorkflowManagerService] Getting workflow: "+t);const n=await rt.get("bamboo/workflows/"+encodeURIComponent(t)),s=n!=null&&n.name?String(n.name):t,r={name:s,filename:String((n==null?void 0:n.filename)||s+".md"),size:Number((n==null?void 0:n.size)||0),modified_at:n==null?void 0:n.modified_at,source:"global"};return Jt("[WorkflowManager]","[WorkflowManagerService] Got workflow:",n),{name:s,content:String((n==null?void 0:n.content)||""),metadata:r}}catch(n){throw console.error("[WorkflowManagerService] Failed to get workflow "+t+":",n),Z_(n)&&n.status===404?new Error("Workflow '"+t+"' not found"):n instanceof Error&&n.message.includes("404")?new Error("Workflow '"+t+"' not found"):n}}};Ct(eo,"instance");let Uu=eo;const{Text:Ld}=He,{TextArea:GT}=Qe,{useToken:JT}=Ge,QT=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),ZT=()=>{const{t:e}=Ie(),{token:t}=JT(),[n,s]=Cr.useMessage(),[r,a]=p.useState([]),[i,l]=p.useState(!1),[c,u]=p.useState(!1),[m,f]=p.useState(!1),[g,b]=p.useState(null),[S,x]=p.useState(""),[T,j]=p.useState(""),[w,M]=p.useState(!1),_=p.useMemo(()=>Uu.getInstance(),[]),C=p.useCallback(async()=>{l(!0);try{const O=await _.listWorkflows();return a(O),O}catch{return n.error(e("settings.workflowsTab.loadFailed")),[]}finally{l(!1)}},[n,e,_]);p.useEffect(()=>{C()},[C]);const L=p.useCallback(async O=>{b(O),x(O.name),M(!1),u(!0);try{const R=await _.getWorkflow(O.name);j(R.content??"")}catch{n.error(e("settings.workflowsTab.loadContentFailed")),j("")}finally{u(!1)}},[n,e,_]),A=()=>{b(null),x(""),j(""),M(!1)},B=p.useCallback(async()=>{if(!QT(S)){n.error(e("settings.workflowsTab.invalidName"));return}const O=r.some(R=>R.name===S);if(!g&&O){n.error(e("settings.workflowsTab.nameAlreadyExists"));return}f(!0);try{await Is.getInstance().saveWorkflow(S,T),n.success(e("settings.workflowsTab.saved")),M(!1);const $=(await C()).find(U=>U.name===S);$&&b($)}catch(R){n.error(R instanceof Error?R.message:e("settings.workflowsTab.saveFailed"))}finally{f(!1)}},[T,S,C,n,g,e,r]),N=p.useCallback(async O=>{try{await Is.getInstance().deleteWorkflow(O.name),n.success(e("settings.workflowsTab.deleted")),(g==null?void 0:g.name)===O.name&&A(),await C()}catch(R){n.error(R instanceof Error?R.message:e("settings.workflowsTab.deleteFailed"))}},[C,n,g,e]);return o.jsxs("div",{style:{padding:"24px"},children:[s,o.jsxs(Ce,{title:e("settings.workflowsTab.title"),extra:o.jsxs(he,{children:[o.jsx(ue,{icon:o.jsx(lr,{}),onClick:C,loading:i,children:e("settings.workflowsTab.refresh")}),o.jsx(ue,{"data-testid":"create-workflow",icon:o.jsx(rr,{}),onClick:A,children:e("settings.workflowsTab.newWorkflow")}),o.jsx(ue,{"data-testid":"save-workflow",type:"primary",icon:o.jsx(zc,{}),onClick:B,loading:m,disabled:!w,children:e("settings.workflowsTab.save")})]}),children:[o.jsx(Ld,{type:"secondary",children:e("settings.workflowsTab.description")}),o.jsxs(be,{gap:t.marginLG,style:{marginTop:t.marginLG},children:[o.jsx("div",{style:{width:320,flexShrink:0},children:o.jsx(Qt,{loading:i,dataSource:r,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:O=>o.jsx(Qt.Item,{style:{cursor:"pointer",backgroundColor:(g==null?void 0:g.name)===O.name?t.colorFillSecondary:"transparent",borderRadius:t.borderRadius,padding:t.paddingSM},onClick:()=>L(O),actions:[o.jsx(ue,{"data-testid":`delete-workflow-${O.name}`,type:"text",danger:!0,size:"small",icon:o.jsx(Mr,{}),onClick:R=>{R.stopPropagation(),N(O)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:o.jsxs(he,{direction:"vertical",size:0,children:[o.jsxs(Ld,{strong:!0,children:["/",O.name]}),o.jsx(Ld,{type:"secondary",style:{fontSize:12},children:O.filename})]})})})}),o.jsx("div",{style:{flex:1},children:o.jsxs(he,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[o.jsx(Qe,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:S,onChange:O=>{x(O.target.value),M(!0)},disabled:!!g,prefix:o.jsx(Hi,{})}),o.jsx(GT,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:T,onChange:O=>{j(O.target.value),M(!0)},autoSize:{minRows:12},disabled:c})]})})]})]})]})};var Je=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))(Je||{});const Qi=6e4,Zi=3e4,zi=2e4,kc=1e4,Hc=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:zi},request_timeout_ms:Qi,healthcheck_interval_ms:Zi,allowed_tools:[],denied_tools:[]}),ej=()=>({status:"stopped",tool_count:0,restart_count:0}),tj=e=>{switch(typeof e=="string"?e.trim().toLowerCase():""){case Je.Connecting:return Je.Connecting;case Je.Ready:return Je.Ready;case Je.Degraded:return Je.Degraded;case Je.Error:return Je.Error;case Je.Stopped:default:return Je.Stopped}},nr=(e,t)=>{if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const n=Number(e);if(Number.isFinite(n))return n}return t},nj=(e,t)=>{if(!e||typeof e!="object")return t;const n=e;if(n.type==="sse"){const a=Array.isArray(n.headers)?n.headers.map(i=>{if(!i||typeof i!="object")return null;const l=i;return typeof l.name!="string"||typeof l.value!="string"?null:{name:l.name,value:l.value}}).filter(i=>!!i):[];return{type:"sse",url:typeof n.url=="string"?n.url:"",headers:a,connect_timeout_ms:nr(n.connect_timeout_ms,kc)}}const s=Array.isArray(n.args)?n.args.filter(a=>typeof a=="string"):[],r=n.env&&typeof n.env=="object"?Object.entries(n.env):[];return{type:"stdio",command:typeof n.command=="string"?n.command:"",args:s,cwd:typeof n.cwd=="string"?n.cwd:void 0,env:r.reduce((a,[i,l])=>(typeof l=="string"&&(a[i]=l),a),{}),startup_timeout_ms:nr(n.startup_timeout_ms,zi)}},sj=(e,t)=>{const n=Hc(e.id),s=t??{};return{...n,...s,id:e.id,name:typeof s.name=="string"?s.name:typeof e.name=="string"?e.name:void 0,enabled:typeof e.enabled=="boolean"?e.enabled:typeof s.enabled=="boolean"?s.enabled:!0,request_timeout_ms:nr(s.request_timeout_ms,Qi),healthcheck_interval_ms:nr(s.healthcheck_interval_ms,Zi),allowed_tools:Array.isArray(s.allowed_tools)?s.allowed_tools.filter(a=>typeof a=="string"):[],denied_tools:Array.isArray(s.denied_tools)?s.denied_tools.filter(a=>typeof a=="string"):[],reconnect:s.reconnect&&typeof s.reconnect=="object"?{enabled:typeof s.reconnect.enabled=="boolean"?s.reconnect.enabled:!0,initial_backoff_ms:nr(s.reconnect.initial_backoff_ms,1e3),max_backoff_ms:nr(s.reconnect.max_backoff_ms,3e4),max_attempts:nr(s.reconnect.max_attempts,0)}:void 0,transport:nj(s.transport,n.transport)}},rj=e=>{const t=ej(),s=e.runtime??{},r=s.status??e.status;return{status:tj(r),last_error:typeof s.last_error=="string"?s.last_error:typeof e.last_error=="string"?e.last_error:void 0,connected_at:typeof s.connected_at=="string"?s.connected_at:void 0,disconnected_at:typeof s.disconnected_at=="string"?s.disconnected_at:void 0,tool_count:nr(s.tool_count??e.tool_count,t.tool_count),restart_count:nr(s.restart_count??e.restart_count,t.restart_count),last_ping_at:typeof s.last_ping_at=="string"?s.last_ping_at:void 0}},oj=e=>{const t=sj(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:rj(e)}},aj=(e,t)=>`mcp__${e}__${t}`,ij=e=>{if(!e.startsWith("mcp__"))return null;const t=e.slice(5),n=t.indexOf("__");if(n<=0)return null;const s=t.slice(0,n),r=t.slice(n+2);return!s||!r?null:{server_id:s,original_name:r}},lj=(e,t,n=0)=>{if(!e||typeof e!="object")return null;const s=e,r=typeof s.alias=="string"?s.alias:typeof s.name=="string"&&s.name.startsWith("mcp__")?s.name:void 0,a=r&&typeof r=="string"?ij(r):null,i=(typeof s.server_id=="string"?s.server_id:void 0)??(typeof s.serverId=="string"?s.serverId:void 0)??(a==null?void 0:a.server_id)??t??"",l=(typeof s.original_name=="string"?s.original_name:void 0)??(typeof s.originalName=="string"?s.originalName:void 0)??(a==null?void 0:a.original_name)??(typeof s.name=="string"?s.name:void 0)??"",c=r??(i&&l?aj(i,l):""),u=typeof s.description=="string"?s.description:"",m=s,f="parameters"in m?m.parameters:"inputSchema"in m?m.inputSchema:"input_schema"in m?m.input_schema:void 0,g=c||l||`mcp_tool_${n}`;return{alias:g,server_id:i||"unknown",original_name:l||g,description:u,parameters:f}};class cj{async getServers(){const t=await Ze.get("mcp/servers");return Array.isArray(t.servers)?t.servers.map(oj):[]}async addServer(t){return Ze.post("mcp/servers",t)}async updateServer(t,n){const s={...n,id:t};return Ze.put(`mcp/servers/${t}`,s)}async deleteServer(t){return Ze.delete(`mcp/servers/${t}`)}async connectServer(t){return Ze.post(`mcp/servers/${t}/connect`)}async disconnectServer(t){return Ze.post(`mcp/servers/${t}/disconnect`)}async refreshTools(t){return Ze.post(`mcp/servers/${t}/refresh`)}async getTools(t){const n=t?`mcp/servers/${t}/tools`:"mcp/tools",s=await Ze.get(n);return(Array.isArray(s.tools)?s.tools:[]).map((a,i)=>lj(a,t,i)).filter(a=>!!a)}async importServers(t){return Ze.post("mcp/servers/import",t)}}const ux=new cj,dj=5e3,Js=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,Up=(e,t)=>`${e}:${t}`,uj=(e={})=>{const{service:t=ux,autoRefreshMs:n=dj,autoRefreshEnabled:s=!0}=e,[r,a]=p.useState([]),[i,l]=p.useState(null),[c,u]=p.useState({}),[m,f]=p.useState({}),[g,b]=p.useState({}),[S,x]=p.useState(!1),[T,j]=p.useState(!1),[w,M]=p.useState(!1),[_,C]=p.useState(null),L=p.useRef({}),A=p.useCallback(re=>{const fe=new Set(re.map(ke=>ke.id)),Se=re.map(ke=>{const tt=L.current[ke.id]??ke.config,ft={...tt,id:ke.id,name:tt.name??ke.name};return L.current[ke.id]=ft,{...ke,name:ke.name||ft.name||ke.id,enabled:ke.enabled??ft.enabled,config:ft}});return Object.keys(L.current).forEach(ke=>{fe.has(ke)||delete L.current[ke]}),Se},[]),B=p.useCallback(async({silent:re=!1}={})=>{re||x(!0);try{const fe=await t.getServers(),Se=A(fe);a(Se),l(ke=>{var Be;return ke&&Se.some(tt=>tt.id===ke)?ke:((Be=Se[0])==null?void 0:Be.id)??null}),C(null)}catch(fe){throw C(Js(fe,"Failed to load MCP servers")),fe}finally{re||x(!1)}},[A,t]),N=p.useCallback(async(re,fe=!1)=>{if(!re)return[];if(!fe&&c[re])return c[re];f(Se=>({...Se,[re]:!0}));try{const Se=await t.getTools(re);return u(ke=>({...ke,[re]:Se})),C(null),Se}catch(Se){throw C(Js(Se,"Failed to load MCP tools")),Se}finally{f(Se=>({...Se,[re]:!1}))}},[t,c]),O=p.useCallback((re,fe,Se)=>{const ke=Up(re,fe);b(Be=>({...Be,[ke]:Se}))},[]),R=p.useCallback(async re=>{j(!0);try{await t.addServer(re),L.current[re.id]=re,await B()}catch(fe){throw C(Js(fe,"Failed to add MCP server")),fe}finally{j(!1)}},[B,t]),I=p.useCallback(async(re,fe)=>{j(!0);try{const Se={...fe,id:re};await t.updateServer(re,Se),L.current[re]=Se,await B()}catch(Se){throw C(Js(Se,"Failed to update MCP server")),Se}finally{j(!1)}},[B,t]),$=p.useCallback(async re=>{O(re,"delete",!0);try{await t.deleteServer(re),u(fe=>{const Se={...fe};return delete Se[re],Se}),delete L.current[re],await B()}catch(fe){throw C(Js(fe,"Failed to delete MCP server")),fe}finally{O(re,"delete",!1)}},[B,t,O]),U=p.useCallback(async re=>{O(re,"connect",!0);try{await t.connectServer(re),await B({silent:!0})}catch(fe){throw C(Js(fe,"Failed to connect MCP server")),fe}finally{O(re,"connect",!1)}},[B,t,O]),q=p.useCallback(async re=>{O(re,"disconnect",!0);try{await t.disconnectServer(re),await B({silent:!0})}catch(fe){throw C(Js(fe,"Failed to disconnect MCP server")),fe}finally{O(re,"disconnect",!1)}},[B,t,O]),K=p.useCallback(async re=>{O(re,"refresh",!0);try{await t.refreshTools(re),await N(re,!0),await B({silent:!0})}catch(fe){throw C(Js(fe,"Failed to refresh MCP tools")),fe}finally{O(re,"refresh",!1)}},[N,B,t,O]),P=p.useCallback(async()=>{M(!0);try{const re=r.map(fe=>fe.id);await Promise.all(re.map(async fe=>{try{await t.refreshTools(fe)}catch{}})),await B(),i&&await N(i,!0)}catch(re){throw C(Js(re,"Failed to refresh MCP status")),re}finally{M(!1)}},[N,B,i,r,t]),W=p.useCallback(re=>{l(re)},[]),se=p.useCallback((re,fe)=>!!g[Up(re,fe)],[g]),V=p.useMemo(()=>i?c[i]??[]:[],[i,c]),ie=p.useMemo(()=>i?!!m[i]:!1,[i,m]);return p.useEffect(()=>{B().catch(()=>{})},[B]),p.useEffect(()=>{if(!s||n<=0)return;const re=window.setInterval(()=>{B({silent:!0}).catch(()=>{})},n);return()=>{window.clearInterval(re)}},[s,n,B]),p.useEffect(()=>{i&&N(i).catch(()=>{})},[N,i]),{servers:r,selectedServerId:i,selectedServerTools:V,isLoadingServers:S,isMutatingConfig:T,isRefreshingAll:w,isSelectedServerToolsLoading:ie,error:_,setSelectedServerId:W,refreshServers:B,addServer:R,updateServer:I,deleteServer:$,connectServer:U,disconnectServer:q,refreshServerTools:K,refreshAll:P,isServerActionLoading:se}},mj={[Je.Connecting]:"blue",[Je.Ready]:"green",[Je.Degraded]:"orange",[Je.Stopped]:"default",[Je.Error]:"red"},hj=e=>e===Je.Connecting||e===Je.Ready||e===Je.Degraded,pj=e=>{if(!e)return;const t=e.replace(/\s+/g," ").trim();if(t)return t.length>180?`${t.slice(0,180)}...`:t},fj=({servers:e,loading:t=!1,selectedServerId:n,onSelectServer:s,onEditServer:r,onDeleteServer:a,onConnectServer:i,onDisconnectServer:l,onRefreshTools:c,isServerActionLoading:u})=>{const{t:m}=Ie(),{token:f}=Ge.useToken(),g=p.useMemo(()=>({[Je.Connecting]:m("settings.mcpTab.statusHelp.connecting"),[Je.Ready]:m("settings.mcpTab.statusHelp.ready"),[Je.Degraded]:m("settings.mcpTab.statusHelp.degraded"),[Je.Stopped]:m("settings.mcpTab.statusHelp.stopped"),[Je.Error]:m("settings.mcpTab.statusHelp.error")}),[m]),b=p.useMemo(()=>[{key:"name",title:m("settings.mcpServerTable.columns.name"),render:(S,x)=>x.name||x.id},{key:"transport",title:m("settings.mcpServerTable.columns.transportType"),render:(S,x)=>x.config.transport.type==="sse"?m("settings.mcpServerTable.transportOptions.sse"):m("settings.mcpServerTable.transportOptions.stdio"),width:140},{key:"status",title:m("settings.mcpServerTable.columns.status"),render:(S,x)=>{var _,C;const T=((_=x.runtime)==null?void 0:_.status)??Je.Stopped,j=pj((C=x.runtime)==null?void 0:C.last_error),w=g[T],M={[Je.Connecting]:m("settings.mcpTab.status.connecting"),[Je.Ready]:m("settings.mcpTab.status.ready"),[Je.Degraded]:m("settings.mcpTab.status.degraded"),[Je.Stopped]:m("settings.mcpTab.status.stopped"),[Je.Error]:m("settings.mcpTab.status.error")};return o.jsx(bt,{title:j?`${w} ${m("settings.mcpTab.statusLastError",{error:j})}`:w,children:o.jsx(Ne,{color:T===Je.Stopped?void 0:mj[T],style:{marginInlineEnd:0,cursor:"help",...T===Je.Stopped?{background:f.colorFillSecondary,borderColor:f.colorBorderSecondary,color:f.colorTextSecondary}:void 0},children:M[T]})})},width:120},{key:"toolCount",title:m("settings.mcpServerTable.columns.toolCount"),render:(S,x)=>{var T;return((T=x.runtime)==null?void 0:T.tool_count)??0},width:100},{key:"actions",title:m("settings.mcpServerTable.columns.actions"),width:360,render:(S,x)=>{var w;const T=((w=x.runtime)==null?void 0:w.status)??Je.Stopped,j=hj(T);return o.jsxs(he,{size:f.marginXS,children:[o.jsx(ue,{size:"small",onClick:M=>{M.stopPropagation(),r==null||r(x)},children:m("settings.mcpServerTable.actions.edit")}),o.jsx(hc,{title:m("settings.mcpServerTable.deleteTitle"),description:m("settings.mcpServerTable.deleteDescription",{name:x.name||x.id}),onConfirm:()=>a==null?void 0:a(x),okText:m("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:u==null?void 0:u(x.id,"delete")},children:o.jsx(ue,{size:"small",danger:!0,loading:u==null?void 0:u(x.id,"delete"),onClick:M=>M.stopPropagation(),children:m("settings.mcpServerTable.actions.delete")})}),j?o.jsx(ue,{size:"small",onClick:M=>{M.stopPropagation(),l==null||l(x)},loading:u==null?void 0:u(x.id,"disconnect"),children:m("settings.mcpServerTable.actions.disconnect")}):o.jsx(ue,{size:"small",type:"primary",ghost:!0,onClick:M=>{M.stopPropagation(),i==null||i(x)},loading:u==null?void 0:u(x.id,"connect"),children:m("settings.mcpServerTable.actions.connect")}),o.jsx(ue,{size:"small",onClick:M=>{M.stopPropagation(),c==null||c(x)},loading:u==null?void 0:u(x.id,"refresh"),children:m("settings.mcpServerTable.actions.refreshTools")})]})}}],[u,i,a,l,r,c,g,m,f.colorBorderSecondary,f.colorFillSecondary,f.colorTextSecondary,f.marginXS]);return o.jsx(or,{rowKey:"id",columns:b,dataSource:e,loading:t,pagination:!1,locale:{emptyText:m("settings.mcpServerTable.empty")},onRow:S=>({onClick:()=>s==null?void 0:s(S.id),style:{cursor:s?"pointer":"default",backgroundColor:n===S.id?f.colorFillSecondary:void 0}})})},{Text:Hp}=He,{TextArea:gj}=Qe,Kp=e=>{const t=e??Hc(""),n=t.transport,s=n.type==="stdio"?Object.entries(n.env??{}).map(([a,i])=>({key:a,value:i})):[],r=n.type==="sse"?n.headers.map(a=>({name:a.name,value:a.value})):[];return{id:t.id,name:t.name,enabled:t.enabled,transportType:n.type,command:n.type==="stdio"?n.command:void 0,args:n.type==="stdio"?n.args:[],envEntries:s,url:n.type==="sse"?n.url:void 0,headerEntries:r,requestTimeoutMs:t.request_timeout_ms||Qi,healthcheckIntervalMs:t.healthcheck_interval_ms||Zi,allowedTools:t.allowed_tools||[],deniedTools:t.denied_tools||[]}},yj=e=>e.reduce((t,n)=>{var r;const s=(r=n.key)==null?void 0:r.trim();return s&&(t[s]=n.value??""),t},{}),bj=e=>e.filter(t=>{var n;return(n=t.name)==null?void 0:n.trim()}).map(t=>{var n;return{name:((n=t.name)==null?void 0:n.trim())||"",value:t.value??""}}),Vp=(e,t,n)=>{var m,f,g;const s=t==="edit"&&(n==null?void 0:n.id)||e.id,r=(m=e.name)==null?void 0:m.trim(),a=typeof e.requestTimeoutMs=="number"?e.requestTimeoutMs:(n==null?void 0:n.request_timeout_ms)??Qi,i=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(n==null?void 0:n.healthcheck_interval_ms)??Zi,l=Array.isArray(e.allowedTools)?e.allowedTools:(n==null?void 0:n.allowed_tools)??[],c=Array.isArray(e.deniedTools)?e.deniedTools:(n==null?void 0:n.denied_tools)??[],u=e.transportType==="sse"?{type:"sse",url:((f=e.url)==null?void 0:f.trim())||"",headers:bj(e.headerEntries||[]),connect_timeout_ms:(n==null?void 0:n.transport.type)==="sse"?n.transport.connect_timeout_ms??kc:kc}:{type:"stdio",command:((g=e.command)==null?void 0:g.trim())||"",args:e.args||[],env:yj(e.envEntries||[]),cwd:(n==null?void 0:n.transport.type)==="stdio"?n.transport.cwd:void 0,startup_timeout_ms:(n==null?void 0:n.transport.type)==="stdio"?n.transport.startup_timeout_ms??zi:zi};return{id:s,name:r||void 0,enabled:e.enabled,transport:u,request_timeout_ms:a,healthcheck_interval_ms:i,allowed_tools:l,denied_tools:c,reconnect:n==null?void 0:n.reconnect}},Yp=e=>JSON.stringify(e||Hc(""),null,2),Fd=(e,t)=>{try{const n=JSON.parse(e);if(!n||typeof n!="object")return{valid:!1,error:t("settings.mcpServerForm.jsonMustBeObject")};const s=n;if(s.mcpServers&&typeof s.mcpServers=="object")return{valid:!1,error:t("settings.mcpServerForm.detectedBulkConfig")};const r=typeof s.id=="string"?s.id:"";if(!r.trim())return{valid:!1,error:t("settings.mcpServerForm.missingIdField")};if(s.transport&&typeof s.transport=="object"){const f=s;return!f.transport||typeof f.transport!="object"?{valid:!1,error:t("settings.mcpServerForm.missingTransportField")}:{valid:!0,config:f}}const a=typeof s.enabled=="boolean"?s.enabled:typeof s.disabled=="boolean"?!s.disabled:!0,i=typeof s.request_timeout_ms=="number"?s.request_timeout_ms:Qi,l=typeof s.healthcheck_interval_ms=="number"?s.healthcheck_interval_ms:Zi,c=Array.isArray(s.allowed_tools)?s.allowed_tools.filter(f=>typeof f=="string"):[],u=Array.isArray(s.denied_tools)?s.denied_tools.filter(f=>typeof f=="string"):[],m=typeof s.name=="string"?s.name:void 0;if(typeof s.url=="string"){const f=s.headers,g=Array.isArray(f)?f.map(S=>{if(!S||typeof S!="object")return null;const x=S,T=typeof x.name=="string"?x.name:"",j=typeof x.value=="string"?x.value:"";return T.trim()?{name:T,value:j}:null}).filter(S=>!!S):f&&typeof f=="object"?Object.entries(f).filter(([S])=>S.trim()).map(([S,x])=>({name:S,value:typeof x=="string"?x:""})):[],b=typeof s.connect_timeout_ms=="number"?s.connect_timeout_ms:kc;return{valid:!0,config:{id:r,name:m,enabled:a,transport:{type:"sse",url:s.url,headers:g,connect_timeout_ms:b},request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:u,reconnect:void 0}}}if(typeof s.command=="string"){const f=Array.isArray(s.args)?s.args.filter(x=>typeof x=="string"):[],g=s.env,b=g&&typeof g=="object"?Object.entries(g).reduce((x,[T,j])=>(typeof j=="string"&&(x[T]=j),x),{}):{},S=typeof s.startup_timeout_ms=="number"?s.startup_timeout_ms:zi;return{valid:!0,config:{id:r,name:m,enabled:a,transport:{type:"stdio",command:s.command,args:f,cwd:typeof s.cwd=="string"?s.cwd:void 0,env:b,startup_timeout_ms:S},request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:u,reconnect:void 0}}}return{valid:!1,error:t("settings.mcpServerForm.missingTransportInfo")}}catch(n){return{valid:!1,error:t("settings.mcpServerForm.invalidJson",{message:n instanceof Error?n.message:t("settings.mcpServerForm.unknownError")})}}},xj=({open:e,mode:t,initialConfig:n,confirmLoading:s=!1,onCancel:r,onSubmit:a})=>{const{t:i}=Ie(),[l]=Pe.useForm(),[c,u]=p.useState("form"),[m,f]=p.useState(""),[g,b]=p.useState(null),S=p.useMemo(()=>Kp(n),[n]),x=Pe.useWatch("transportType",l)??"stdio";p.useEffect(()=>{e&&(l.setFieldsValue(S),f(Yp(n)),b(null),u("form"))},[l,S,n,e]);const T=()=>{l.resetFields(),f(""),b(null),r()},j=async()=>{if(c==="json"){const _=Fd(m,i);if(!_.valid){b(_.error);return}b(null);try{await a(_.config),f("")}catch(C){console.error("MCP server JSON submission error:",C)}return}try{const _=await l.validateFields(),C=Vp(_,t,n);await a(C),l.resetFields()}catch(_){console.error("MCP server form submission error:",_)}},w=_=>{f(_),g&&Fd(_,i).valid&&b(null)},M=_=>{if(_==="json")try{const C=l.getFieldsValue(),L=Vp(C,t,n);f(JSON.stringify(L,null,2))}catch{f(Yp(n))}else{const C=Fd(m,i);C.valid&&l.setFieldsValue(Kp(C.config))}u(_),b(null)};return o.jsxs(Xn,{title:i(t==="edit"?"settings.mcpServerForm.editTitle":"settings.mcpServerForm.addTitle"),open:e,onCancel:T,onOk:()=>{j()},okText:i("settings.mcpServerForm.save"),destroyOnClose:!0,forceRender:!0,confirmLoading:s,width:720,children:[o.jsx("div",{style:{marginBottom:16},children:o.jsxs(bs.Group,{value:c,onChange:_=>M(_.target.value),optionType:"button",buttonStyle:"solid",children:[o.jsxs(bs.Button,{value:"form",children:[o.jsx(Ww,{})," ",i("settings.mcpServerForm.modeForm")]}),o.jsxs(bs.Button,{value:"json",children:[o.jsx(Bc,{})," ",i("settings.mcpServerForm.modeJson")]})]})}),c==="json"&&g&&o.jsx(Ut,{type:"error",message:i("settings.mcpServerForm.jsonError"),description:g,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>b(null)}),c==="json"?o.jsx(gj,{value:m,onChange:_=>w(_.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(Hc("example-server"),null,2)}):o.jsxs(Pe,{layout:"vertical",form:l,preserve:!0,initialValues:S,children:[o.jsx(Pe.Item,{name:"id",label:i("settings.mcpServerForm.serverId"),rules:[{required:!0,message:i("settings.mcpServerForm.serverIdRequired")},{pattern:/^[a-zA-Z0-9_-]+$/,message:i("settings.mcpServerForm.serverIdPatternError")}],children:o.jsx(Qe,{placeholder:"filesystem",disabled:t==="edit",autoComplete:"off"})}),o.jsx(Pe.Item,{name:"name",label:i("settings.mcpServerForm.displayName"),children:o.jsx(Qe,{placeholder:"Filesystem MCP",autoComplete:"off"})}),o.jsx(Pe.Item,{name:"enabled",label:i("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:i("settings.mcpServerForm.enabledHelp"),children:o.jsx(pn,{})}),o.jsx(Pe.Item,{name:"transportType",label:i("settings.mcpServerForm.transportType"),rules:[{required:!0,message:i("settings.mcpServerForm.transportTypeRequired")}],children:o.jsx(St,{options:[{label:i("settings.mcpServerForm.transportOptions.stdio"),value:"stdio"},{label:i("settings.mcpServerForm.transportOptions.sse"),value:"sse"}]})}),x==="stdio"?o.jsxs(o.Fragment,{children:[o.jsx(Pe.Item,{name:"command",label:i("settings.mcpServerForm.command"),rules:[{required:!0,message:i("settings.mcpServerForm.commandRequired")}],children:o.jsx(Qe,{placeholder:"npx",autoComplete:"off"})}),o.jsx(Pe.Item,{name:"args",label:i("settings.mcpServerForm.arguments"),children:o.jsx(St,{mode:"tags",tokenSeparators:[","],placeholder:i("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),o.jsx(Pe.List,{name:"envEntries",children:(_,{add:C,remove:L})=>o.jsxs(he,{direction:"vertical",style:{width:"100%"},children:[o.jsxs(he,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[o.jsx(Hp,{strong:!0,children:i("settings.mcpServerForm.envVars")}),o.jsx(ue,{icon:o.jsx(rr,{}),onClick:()=>C({key:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addEnv")})]}),_.map(A=>o.jsxs(he,{align:"baseline",style:{display:"flex"},children:[o.jsx(Pe.Item,{...A,name:[A.name,"key"],rules:[{required:!0,message:i("settings.mcpServerForm.keyRequired")}],children:o.jsx(Qe,{placeholder:"MCP_ROOT",autoComplete:"off"})}),o.jsx(Pe.Item,{...A,name:[A.name,"value"],children:o.jsx(Qe,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),o.jsx(ue,{danger:!0,type:"text",icon:o.jsx(Cu,{}),onClick:()=>L(A.name),"aria-label":i("settings.mcpServerForm.removeEnv","Remove environment variable")})]},A.key))]})})]}):o.jsxs(o.Fragment,{children:[o.jsx(Pe.Item,{name:"url",label:i("settings.mcpServerForm.sseUrl"),rules:[{required:!0,message:i("settings.mcpServerForm.sseUrlRequired")},{validator:async(_,C)=>{if(C)try{new URL(C)}catch{throw new Error(i("settings.mcpServerForm.validUrlRequired"))}}}],children:o.jsx(Qe,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),o.jsx(Pe.List,{name:"headerEntries",children:(_,{add:C,remove:L})=>o.jsxs(he,{direction:"vertical",style:{width:"100%"},children:[o.jsxs(he,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[o.jsx(Hp,{strong:!0,children:i("settings.mcpServerForm.headers")}),o.jsx(ue,{icon:o.jsx(rr,{}),onClick:()=>C({name:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addHeader")})]}),_.map(A=>o.jsxs(he,{align:"baseline",style:{display:"flex"},children:[o.jsx(Pe.Item,{...A,name:[A.name,"name"],rules:[{required:!0,message:i("settings.mcpServerForm.headerNameRequired")}],children:o.jsx(Qe,{placeholder:"Authorization",autoComplete:"off"})}),o.jsx(Pe.Item,{...A,name:[A.name,"value"],children:o.jsx(Qe,{placeholder:"Bearer token",autoComplete:"off"})}),o.jsx(ue,{danger:!0,type:"text",icon:o.jsx(Cu,{}),onClick:()=>L(A.name),"aria-label":i("settings.mcpServerForm.removeHeader","Remove header")})]},A.key))]})})]})]})]})},vj={maxLines:8,maxCharacters:500},_r=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),gr=e=>typeof e=="string"?e:void 0,Yr=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Xp=e=>typeof e=="boolean"?e:void 0,Qm=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const n=JSON.parse(t);return _r(n)?n:null}catch{return null}},mx=e=>/\\u[0-9a-fA-F]{4}|\\n|\\t|\\r/.test(e)?e.replace(/\\u([0-9a-fA-F]{4})/g,(t,n)=>String.fromCharCode(parseInt(n,16))).replace(/\\n/g,`
|
|
90
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r"):e,Hs=e=>Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>mx(t).trim()).filter(Boolean):[],wn=e=>{if(typeof e!="string")return;const t=mx(e).trim();return t.length>0?t:void 0},Sj=e=>{if(!_r(e))return;const t=wn(e.graph);if(t)return{title:wn(e.title),graph:t}},wj=e=>{if(!_r(e))return;const t=wn(e.summary)??wn(e.conclusion);if(t)return{title:wn(e.title)||"Conclusion",summary:t,key_points:Hs(e.key_points),next_steps:Hs(e.next_steps),confidence:wn(e.confidence),mermaid:Sj(e.mermaid)}},_j=e=>{const t=Qm(e);if(!t)return null;const n=wn(t.conclusion);return!n||t.type!=null&&t.type!=="conclusion"?null:{type:"conclusion",title:wn(t.title)||"Conclusion",conclusion:n,key_points:Hs(t.key_points),next_steps:Hs(t.next_steps),confidence:wn(t.confidence)}},kj=e=>{const t=Qm(e);if(!t)return null;const n=wn(t.question);if(!n)return null;const s=wn(t.status);return s&&s!=="awaiting_user_input"&&s!=="awaiting_permission_approval"?null:{question:n,options:Hs(t.options),allow_custom:typeof t.allow_custom=="boolean"?t.allow_custom:!0,conclusion:wj(t.conclusion)}},Tj=e=>{var n;if(!e)return null;const t=[`## ${e.title}`,e.summary];if(e.confidence&&t.push(`**Confidence:** ${e.confidence}`),e.key_points.length>0&&t.push(["**Key points**",...e.key_points.map(s=>`- ${s}`)].join(`
|
|
91
|
+
`)),e.next_steps.length>0&&t.push(["**Next steps**",...e.next_steps.map((s,r)=>`${r+1}. ${s}`)].join(`
|
|
92
|
+
`)),(n=e.mermaid)!=null&&n.graph){const s=e.mermaid.title?`**${e.mermaid.title}**
|
|
93
|
+
|
|
94
|
+
`:`**Flow**
|
|
95
|
+
|
|
96
|
+
`;t.push(`${s}\`\`\`mermaid
|
|
97
|
+
${e.mermaid.graph}
|
|
98
|
+
\`\`\``)}return t.join(`
|
|
99
|
+
|
|
100
|
+
`)},hx=e=>{const t=_j(e);if(!t)return null;const n=[`## ${t.title}`,t.conclusion];return t.confidence&&n.push(`**Confidence:** ${t.confidence}`),t.key_points.length>0&&n.push(["**Key points**",...t.key_points.map(s=>`- ${s}`)].join(`
|
|
101
|
+
`)),t.next_steps.length>0&&n.push(["**Next steps**",...t.next_steps.map((s,r)=>`${r+1}. ${s}`)].join(`
|
|
102
|
+
`)),n.join(`
|
|
103
|
+
|
|
104
|
+
`)},Kc=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const n=JSON.parse(t);if(!_r(n))return null;const s=gr(n.file_path),r=gr(n.operation),a=n.diff;if(!s||!r||!_r(a))return null;const i=gr(a.unified);if(!i)return null;const l=n.checkpoint,c=_r(l)?{created:Xp(l.created)??!1,id:gr(l.id),path:gr(l.path),size_bytes:Yr(l.size_bytes),reason:gr(l.reason)}:void 0;return{operation:r,message:gr(n.message),file_path:s,workspace:gr(n.workspace),checkpoint:c,diff:{unified:i,old_line_count:Yr(a.old_line_count),new_line_count:Yr(a.new_line_count),added_lines:Yr(a.added_lines),removed_lines:Yr(a.removed_lines),truncated:Xp(a.truncated)}}}catch{return null}},px=e=>{const t=Qm(e);if(!t)return null;const n=wn(t.action);if(n!=="inspect"&&n!=="rebuild")return null;const s=t.data;if(!_r(s))return null;const r=wn(s.scope),a=Yr(s.total_memories);if(!r||typeof a!="number")return null;const i=l=>_r(l)?Object.fromEntries(Object.entries(l).filter(c=>typeof c[0]=="string"&&typeof c[1]=="number")):{};return{action:n,scope:wn(t.scope),project_key:wn(t.project_key),data:{scope:r,project_key:wn(s.project_key),total_memories:a,by_type:i(s.by_type),by_status:i(s.by_status),recent_ids:Hs(s.recent_ids),view_files:Hs(s.view_files),index_files:Hs(s.index_files),state_files:Hs(s.state_files),stale_candidate_count:Yr(s.stale_candidate_count)??0,last_reindex_at:wn(s.last_reindex_at),last_dream_at:wn(s.last_dream_at),topic_paths:Hs(s.topic_paths)}}},Hu=e=>e.startsWith("-")&&!e.startsWith("---"),Ku=e=>e.startsWith("+")&&!e.startsWith("+++"),fx=e=>{const t=e.split(`
|
|
105
|
+
`),n=[];let s=0;for(;s<t.length;){const r=t[s]??"";if(r.startsWith("--- ")||r.startsWith("+++ ")){n.push({kind:"meta",text:r}),s+=1;continue}if(r.startsWith("@@")){n.push({kind:"hunk",text:r}),s+=1;continue}if(Hu(r)){const a=[];for(;s<t.length&&Hu(t[s]??"");)a.push(t[s]??""),s+=1;const i=[];for(;s<t.length&&Ku(t[s]??"");)i.push(t[s]??""),s+=1;i.length>0?(a.forEach(l=>n.push({kind:"modified_remove",text:l})),i.forEach(l=>n.push({kind:"modified_add",text:l}))):a.forEach(l=>n.push({kind:"remove",text:l}));continue}if(Ku(r)){n.push({kind:"add",text:r}),s+=1;continue}n.push({kind:"context",text:r}),s+=1}return n},jj=e=>{let t=0,n=0;for(const s of e.split(`
|
|
106
|
+
`)){if(Ku(s)){t+=1;continue}Hu(s)&&(n+=1)}return{added:t,removed:n}},gx=e=>{const t=Kc(e);if(!t)return null;const n=jj(t.diff.unified);return{added:t.diff.added_lines??n.added,removed:t.diff.removed_lines??n.removed}},Vu=e=>{if(typeof e=="string")return e.replace(/\\n/g,`
|
|
107
|
+
`).replace(/\\t/g," ");if(Array.isArray(e))return e.map(Vu);if(e!==null&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=Vu(s);return t}return e},Yu=e=>{if(!e)return{isJson:!1,formattedText:""};const t=e.trim();if(!t)return{isJson:!1,formattedText:""};if(!(t.startsWith("{")&&t.endsWith("}"))&&!(t.startsWith("[")&&t.endsWith("]")))return{isJson:!1,formattedText:e};try{const n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===1){const r=Object.keys(n)[0];if((r==="content"||r==="result"||r==="output")&&typeof n[r]=="string")return{isJson:!1,formattedText:n[r].replace(/\\n/g,`
|
|
108
|
+
`).replace(/\\t/g," "),parsedJson:n}}const s=Vu(n);return{isJson:!0,formattedText:JSON.stringify(s,null,2),parsedJson:s}}catch{return{isJson:!1,formattedText:e}}},Cj=(e,t={})=>{const n={...vj,...t};return e?e.split(/\r?\n/).length>n.maxLines?!0:e.length>n.maxCharacters:!1},Mj=(e,t=320)=>e?e.length<=t?{preview:e,isTruncated:!1}:{preview:e.substring(0,t).trimEnd()+"…",isTruncated:!0}:{preview:"",isTruncated:!1},Pj=e=>{if(!e)return"No content";const t=60,n=e.trim(),s=Kc(n);if(s){const a=s.file_path.split(/[\\/]/).pop()||s.file_path,i=`${s.operation}: ${a}`;return i.length<=t?i:i.substring(0,t).trimEnd()+"…"}const r=px(n);if(r){const a=r.data.project_key||r.data.scope,i=`Memory ${r.action}: ${a} (${r.data.total_memories})`;return i.length<=t?i:i.substring(0,t).trimEnd()+"…"}if(n.length<=t)return n;if(n.startsWith("{")||n.startsWith("["))try{const a=JSON.parse(n);if(typeof a=="object"&&a!==null){if(a.type==="mermaid"&&typeof a.chart=="string"&&a.chart.trim().length>0){const u=`Diagram: ${typeof a.title=="string"&&a.title.trim().length>0?a.title.trim():"Mermaid diagram"}`;return u.length<=t?u:u.substring(0,t).trimEnd()+"…"}if(a.type==="conclusion"&&typeof a.conclusion=="string"&&a.conclusion.trim().length>0){const c=a.conclusion.trim();return c.length<=t?c:c.substring(0,t).trimEnd()+"…"}const i=["content","result","output","message","data"].find(c=>c in a&&typeof a[c]=="string");if(i){const c=a[i];return c.length<=t?c:c.substring(0,t).trimEnd()+"…"}if(Array.isArray(a))return`Array with ${a.length} items`;const l=Object.keys(a);return`Object with ${l.length} propert${l.length===1?"y":"ies"}`}}catch{}return n.substring(0,t).trimEnd()+"…"},yx=e=>{switch(e){case"success":return"green";case"error":return"red";case"warning":return"orange";default:return"blue"}},Uo=(e,t=2)=>{if(typeof e=="string")return e;try{return JSON.stringify(e,null,t)}catch(n){return console.error("[resultFormatters] Failed to stringify value:",n),String(e)}},Zl=e=>!!e&&typeof e=="object"&&!Array.isArray(e),zr=(e,t)=>{const n=e[t];return typeof n=="string"?n:void 0},Gp=(e,t)=>{const n=e[t];return typeof n=="boolean"?n:void 0},Ej=(e,t)=>{const n=e[t];return Array.isArray(n)?n:void 0},yi=e=>{if(!Zl(e))return"any";const t=e.type;if(typeof t=="string"){if(t==="array"){const a=e.items;return`array<${yi(a)}>`}return t==="object"?"object":t}if(Array.isArray(t)){const a=t.filter(i=>typeof i=="string").map(i=>i==="array"?"array<any>":i);return a.length>0?a.join(" | "):"any"}const n=Array.isArray(e.oneOf)?e.oneOf:null;if(n)return n.map(yi).join(" | ")||"any";const s=Array.isArray(e.anyOf)?e.anyOf:null;if(s)return s.map(yi).join(" | ")||"any";const r=Array.isArray(e.allOf)?e.allOf:null;return r&&r.map(yi).join(" & ")||"any"},Rj=e=>{if(!Zl(e))return null;const t=e.properties;if(!Zl(t))return{schemaUri:zr(e,"$schema"),title:zr(e,"title"),description:zr(e,"description"),additionalProperties:Gp(e,"additionalProperties"),fields:[]};const n=new Set((Ej(e,"required")??[]).filter(r=>typeof r=="string").map(r=>r)),s=Object.entries(t).map(([r,a])=>{const i=Zl(a)?a:void 0;return{name:r,type:yi(a),required:n.has(r),description:i?zr(i,"description"):void 0,defaultValue:i?i.default:void 0,enumValues:i&&Array.isArray(i.enum)?i.enum:void 0}});return s.sort((r,a)=>r.required!==a.required?r.required?-1:1:r.name.localeCompare(a.name)),{schemaUri:zr(e,"$schema"),title:zr(e,"title"),description:zr(e,"description"),additionalProperties:Gp(e,"additionalProperties"),fields:s}},{Text:Fs}=He,Aj=e=>e===void 0?"":e===null?"null":typeof e=="string"?e:Uo(e,0),Ij=({schema:e})=>{const{token:t}=Ge.useToken(),{t:n}=Ie(),s=p.useMemo(()=>Rj(e),[e]);if(!s)return o.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:Uo(e,2)});const r=[{title:n("components.jsonSchema.field"),dataIndex:"name",key:"name",width:180,render:i=>o.jsx(Fs,{code:!0,children:i})},{title:n("components.jsonSchema.type"),dataIndex:"type",key:"type",width:140,render:i=>o.jsx(Fs,{children:i})},{title:n("components.jsonSchema.required"),dataIndex:"required",key:"required",width:110,render:i=>i?o.jsx(Fs,{strong:!0,style:{color:t.colorError},children:n("components.jsonSchema.yes")}):o.jsx(Fs,{type:"secondary",children:n("components.jsonSchema.no")})},{title:n("components.jsonSchema.default"),dataIndex:"defaultValue",key:"default",width:160,render:i=>i===void 0?o.jsx(Fs,{type:"secondary",children:"-"}):o.jsx(Fs,{children:Aj(i)})},{title:n("components.jsonSchema.description"),dataIndex:"description",key:"description",render:i=>i?o.jsx(Fs,{style:{whiteSpace:"pre-wrap"},children:i}):o.jsx(Fs,{type:"secondary",children:"-"})}],a=(s.fields??[]).map(i=>({...i,key:i.name}));return o.jsxs("div",{style:{width:"100%"},children:[o.jsx(Fn,{size:"small",column:1,items:[s.schemaUri?{key:"schema",label:"$schema",children:o.jsx(Fs,{code:!0,children:s.schemaUri})}:null,typeof s.additionalProperties=="boolean"?{key:"additionalProperties",label:"additionalProperties",children:o.jsx(Fs,{children:s.additionalProperties?"true":"false"})}:null].filter(Boolean)}),o.jsx(or,{size:"small",pagination:!1,columns:r,dataSource:a,locale:{emptyText:n("components.jsonSchema.noProperties")},style:{marginTop:t.marginSM}})]})},{Text:ya}=He,Oj=(e,t)=>`mcp__${e}__${t}`,$j=({server:e,tools:t,loading:n=!1})=>{const{t:s}=Ie();return o.jsx(Ce,{title:s("settings.mcpToolList.title"),size:"small",children:e?o.jsx(Qt,{loading:n,dataSource:t,locale:{emptyText:s("settings.mcpToolList.empty")},renderItem:r=>{const a=Oj(r.server_id,r.original_name);return o.jsx(Qt.Item,{children:o.jsxs(he,{direction:"vertical",size:2,style:{width:"100%"},children:[o.jsx(ya,{strong:!0,children:r.original_name}),o.jsx(ya,{type:"secondary",children:r.description||s("settings.mcpToolList.noDescription")}),o.jsx(ya,{code:!0,children:r.alias}),o.jsxs(ya,{type:"secondary",children:[s("settings.mcpToolList.aliasMapping"),": ",o.jsx(ya,{code:!0,children:a})]}),r.parameters!==void 0&&o.jsx(ir,{size:"small",items:[{key:"schema",label:s("settings.mcpToolList.parametersSchema"),children:o.jsx(Ij,{schema:r.parameters})}]})]})})}}):o.jsx(Mn,{image:Mn.PRESENTED_IMAGE_SIMPLE,description:s("settings.mcpToolList.selectServerHint")})})},{Text:ba}=He,{useToken:Dj}=Ge,{TextArea:Lj}=Qe,Jp={[Je.Connecting]:"processing",[Je.Ready]:"success",[Je.Degraded]:"warning",[Je.Stopped]:"default",[Je.Error]:"error"},Fj=()=>({[Je.Connecting]:0,[Je.Ready]:0,[Je.Degraded]:0,[Je.Stopped]:0,[Je.Error]:0}),Br=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,Nj=e=>{var n,s,r;const t={};for(const a of e){const i=(n=a.id)==null?void 0:n.trim();if(!i)continue;const c=!(a.enabled??a.config.enabled),u=a.config.transport;if(u.type==="sse"){const f={};for(const b of u.headers??[]){const S=(s=b.name)==null?void 0:s.trim();S&&(f[S]=b.value??"")}const g={url:u.url};c&&(g.disabled=!0),Object.keys(f).length&&(g.headers=f),t[i]=g;continue}const m={command:u.command};c&&(m.disabled=!0),(r=u.args)!=null&&r.length&&(m.args=u.args),u.cwd&&(m.cwd=u.cwd),u.env&&Object.keys(u.env).length&&(m.env=u.env),t[i]=m}return{mcpServers:t}},zj=()=>{const{t:e}=Ie(),{token:t}=Dj(),[n,s]=Cr.useMessage(),{servers:r,selectedServerId:a,selectedServerTools:i,isLoadingServers:l,isMutatingConfig:c,isRefreshingAll:u,isSelectedServerToolsLoading:m,error:f,setSelectedServerId:g,addServer:b,updateServer:S,deleteServer:x,connectServer:T,disconnectServer:j,refreshServerTools:w,refreshAll:M,isServerActionLoading:_}=uj(),C=p.useMemo(()=>({[Je.Connecting]:e("settings.mcpTab.status.connecting"),[Je.Ready]:e("settings.mcpTab.status.ready"),[Je.Degraded]:e("settings.mcpTab.status.degraded"),[Je.Stopped]:e("settings.mcpTab.status.stopped"),[Je.Error]:e("settings.mcpTab.status.error")}),[e]),L=p.useMemo(()=>({[Je.Connecting]:e("settings.mcpTab.statusHelp.connecting"),[Je.Ready]:e("settings.mcpTab.statusHelp.ready"),[Je.Degraded]:e("settings.mcpTab.statusHelp.degraded"),[Je.Stopped]:e("settings.mcpTab.statusHelp.stopped"),[Je.Error]:e("settings.mcpTab.statusHelp.error")}),[e]),[A,B]=p.useState(!1),[N,O]=p.useState("create"),[R,I]=p.useState(null),[$,U]=p.useState(!1),[q,K]=p.useState("merge"),[P,W]=p.useState(""),[se,V]=p.useState(null),[ie,re]=p.useState(!1),fe=p.useMemo(()=>a?r.find(F=>F.id===a)??null:null,[a,r]),Se=p.useMemo(()=>{const F=Fj();let ce=0;return r.forEach(ge=>{var Le,me;const De=((Le=ge.runtime)==null?void 0:Le.status)??Je.Stopped;F[De]+=1,ce+=((me=ge.runtime)==null?void 0:me.tool_count)??0}),{byStatus:F,totalServers:r.length,totalTools:ce}},[r]),ke={background:t.colorFillSecondary,borderColor:t.colorBorderSecondary,color:t.colorTextSecondary},Be=async F=>{try{await x(F.id),n.success(e("settings.mcpTab.serverDeleted"))}catch(ce){n.error(Br(ce,e("settings.mcpTab.deleteServerFailed")))}},tt=async F=>{try{await T(F.id),n.success(e("settings.mcpTab.connectedTo",{name:F.name||F.id}))}catch(ce){n.error(Br(ce,e("settings.mcpTab.connectServerFailed")))}},ft=async F=>{try{await j(F.id),n.success(e("settings.mcpTab.disconnected",{name:F.name||F.id}))}catch(ce){n.error(Br(ce,e("settings.mcpTab.disconnectServerFailed")))}},Ht=async F=>{try{await w(F.id),n.success(e("settings.mcpTab.toolsRefreshedFor",{name:F.name||F.id}))}catch(ce){n.error(Br(ce,e("settings.mcpTab.refreshToolsFailed")))}},Oe=async()=>{try{await M(),n.success(e("settings.mcpTab.statusRefreshed"))}catch(F){n.error(Br(F,e("settings.mcpTab.refreshStatusFailed")))}},zt=()=>{I(null),O("create"),B(!0)},Ye=F=>{I(F),O("edit"),B(!0)},we=async F=>{try{if(N==="edit"){if(!R){n.error(e("settings.mcpTab.noServerForEditing"));return}await S(R.id,F),n.success(e("settings.mcpTab.savedServer",{name:R.name||R.id}))}else await b(F),n.success(e("settings.mcpTab.addedServer",{name:F.name||F.id}));B(!1),I(null)}catch(ce){n.error(Br(ce,e("settings.mcpTab.saveServerFailed")))}},Ke=()=>{U(!0),V(null),K("merge"),W("")},st=async()=>{const F=Nj(r),ce=JSON.stringify(F,null,2);try{await vs(ce),n.success(e("settings.mcpTab.copiedConfig"))}catch{U(!0),V(null),K("merge"),W(ce),n.warning(e("settings.mcpTab.clipboardUnavailable"))}},Dt=async()=>{var De;V(null);let F;try{F=JSON.parse(P)}catch(Le){V(`${e("settings.mcpTab.invalidJsonPrefix")}: ${Le instanceof Error?Le.message:e("settings.mcpTab.unknownError")}`);return}if(!F||typeof F!="object"){V(e("settings.mcpTab.jsonMustBeObject"));return}const ge=F.mcpServers;if(!ge||typeof ge!="object"){V(e("settings.mcpTab.missingMcpServers"));return}re(!0);try{const Le=await ux.importServers({mcpServers:ge,mode:q}),me=((De=Le.start_errors)==null?void 0:De.length)??0;n.success(e("settings.mcpTab.importSummary",{count:Le.server_ids.length,added:Le.added,updated:Le.updated,removed:Le.removed,failed:me})),me&&n.warning(e("settings.mcpTab.importStartFailures")),U(!1),W(""),await Oe()}catch(Le){V(Br(Le,e("settings.mcpTab.importFailed")))}finally{re(!1)}};return o.jsxs(he,{direction:"vertical",size:t.marginMD,style:{width:"100%"},children:[s,f?o.jsx(Ut,{type:"error",showIcon:!0,message:f}):null,o.jsx(Ce,{size:"small",title:e("settings.mcpTab.overviewTitle"),children:o.jsxs(he,{direction:"vertical",size:t.marginXS,style:{width:"100%"},children:[o.jsx(ba,{type:"secondary",children:e("settings.mcpTab.overviewDescription")}),o.jsxs(he,{wrap:!0,children:[o.jsx(Ne,{style:ke,children:e("settings.mcpTab.totalServers",{count:Se.totalServers})}),o.jsx(Ne,{style:ke,children:e("settings.mcpTab.totalTools",{count:Se.totalTools})}),Object.values(Je).map(F=>o.jsx(bt,{title:L[F],children:o.jsxs(Ne,{color:F===Je.Stopped?void 0:Jp[F],style:{cursor:"help",...F===Je.Stopped?ke:void 0},children:[C[F],": ",Se.byStatus[F]]})},F))]}),o.jsx(ba,{type:"secondary",children:e("settings.mcpTab.statusGuideTitle")}),o.jsx(he,{direction:"vertical",size:2,style:{width:"100%"},children:Object.values(Je).map(F=>o.jsxs(ba,{type:"secondary",children:[o.jsx(Ne,{color:F===Je.Stopped?void 0:Jp[F],style:{marginInlineEnd:8,...F===Je.Stopped?ke:void 0},children:C[F]}),L[F]]},`guide-${F}`))})]})}),o.jsx(Ce,{size:"small",title:e("settings.mcpTab.serversTitle"),extra:o.jsxs(he,{children:[o.jsx(ue,{type:"primary",onClick:zt,children:e("settings.mcpTab.addServer")}),o.jsx(ue,{icon:o.jsx(lr,{}),loading:u,onClick:()=>{Oe()},children:e("settings.mcpTab.refreshAll")}),o.jsx(ue,{icon:o.jsx(xs,{}),onClick:()=>void st(),children:e("settings.mcpTab.export")}),o.jsx(ue,{icon:o.jsx(qw,{}),onClick:Ke,children:e("settings.mcpTab.import")})]}),children:o.jsx(fj,{servers:r,loading:l,selectedServerId:a,onSelectServer:g,onEditServer:Ye,onDeleteServer:Be,onConnectServer:tt,onDisconnectServer:ft,onRefreshTools:Ht,isServerActionLoading:_})}),o.jsx($j,{server:fe,tools:i,loading:m}),o.jsx(xj,{open:A,mode:N,initialConfig:(R==null?void 0:R.config)??null,confirmLoading:c,onCancel:()=>{c||(B(!1),I(null))},onSubmit:F=>void we(F)}),o.jsx(Xn,{open:$,title:e("settings.mcpTab.importModalTitle"),okText:e("settings.mcpTab.import"),onOk:()=>void Dt(),okButtonProps:{loading:ie},onCancel:()=>{ie||(U(!1),V(null))},width:800,destroyOnClose:!1,children:o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:"middle",children:[o.jsxs(ba,{type:"secondary",children:[e("settings.mcpTab.importHint"),o.jsx("br",{}),o.jsx(ba,{code:!0,children:'{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "..."] } } }'})]}),o.jsxs(bs.Group,{value:q,onChange:F=>K(F.target.value),optionType:"button",buttonStyle:"solid",children:[o.jsx(bs.Button,{value:"merge",children:e("settings.mcpTab.importModeMerge")}),o.jsx(bs.Button,{value:"replace",children:e("settings.mcpTab.importModeReplace")})]}),q==="replace"?o.jsx(Ut,{type:"warning",showIcon:!0,message:e("settings.mcpTab.replaceWarning")}):null,se?o.jsx(Ut,{type:"error",showIcon:!0,message:se}):null,o.jsx(Lj,{value:P,onChange:F=>W(F.target.value),rows:14,placeholder:'{"mcpServers": { "filesystem": { "command": "...", "args": [], "env": {} } }}',spellCheck:!1})]})})]})},ds=e=>{const t=new URLSearchParams;Object.entries(e).forEach(([s,r])=>{r===void 0||r===""||t.set(s,String(r))});const n=t.toString();return n?`?${n}`:""};class Bj{async getSummary(t={}){const n=ds({start_date:t.startDate,end_date:t.endDate});return Ze.get(`metrics/summary${n}`)}async getByModel(t={}){const n=ds({start_date:t.startDate,end_date:t.endDate});return Ze.get(`metrics/by-model${n}`)}async getSessions(t={}){const n=ds({start_date:t.startDate,end_date:t.endDate,model:t.model,limit:t.limit});return Ze.get(`metrics/sessions${n}`)}async getSessionDetail(t){try{return await Ze.get(`metrics/sessions/${encodeURIComponent(t)}`)}catch(n){if(n instanceof Error&&n.message.includes("not found"))return null;throw n}}async getUsageBreakdown(t={}){const n=ds({start_date:t.startDate,end_date:t.endDate,model:t.model});return Ze.get(`metrics/usage-breakdown${n}`)}async getDaily(t={}){const n=ds({days:t.days,end_date:t.endDate,granularity:t.granularity});return Ze.get(`metrics/daily${n}`)}async getForwardSummary(t={}){const n=ds({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return Ze.get(`metrics/forward/summary${n}`)}async getForwardByEndpoint(t={}){const n=ds({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return Ze.get(`metrics/forward/by-endpoint${n}`)}async getForwardRequests(t={}){const n=ds({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return Ze.get(`metrics/forward/requests${n}`)}async getMemorySummary(t={}){const n=ds({scope:t.scope,project_key:t.projectKey});return Ze.get(`metrics/memory/summary${n}`)}async getMemoryTimeline(t={}){const n=ds({scope:t.scope,project_key:t.projectKey,days:t.days,end_date:t.endDate,granularity:t.granularity});return Ze.get(`metrics/memory/timeline${n}`)}async getUnifiedSummary(t={}){const n=ds({start_date:t.startDate,end_date:t.endDate});return Ze.get(`metrics/v2/summary${n}`)}async getUnifiedTimeline(t={}){const n=ds({days:t.days,end_date:t.endDate,granularity:t.granularity});return Ze.get(`metrics/v2/timeline${n}`)}}const Pi=new Bj,bx=1,Wj=365,xx=e=>Number.isFinite(e)?Math.min(Wj,Math.max(bx,Math.floor(e??30))):30,Nd=e=>{if(!e)return null;const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=Number(t[1]),s=Number(t[2]),r=Number(t[3]),a=new Date(Date.UTC(n,s-1,r));return a.getUTCFullYear()!==n||a.getUTCMonth()!==s-1||a.getUTCDate()!==r?null:a},xa=e=>e.toISOString().slice(0,10),qj=(e,t)=>{const n=new Date(e.getTime());return n.setUTCDate(n.getUTCDate()+t),n},Uj=(e,t)=>{const n=t.getTime()-e.getTime(),s=Math.floor(n/864e5)+1;return xx(s)},Zm=(e,t=new Date)=>{const n=xx(e.days),s=xa(t),r=Nd(e.endDate)??Nd(s);if(!r)return{startDate:s,endDate:s,days:bx};const a=Nd(e.startDate);if(a){const l=r<a?a:r;return{startDate:xa(a),endDate:xa(l),days:Uj(a,l)}}const i=qj(r,-(n-1));return{startDate:xa(i),endDate:xa(r),days:n}},Hj=15e3,Kj=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,Vj=(e={})=>{const{filters:t,autoRefreshMs:n=Hj}=e,s=p.useMemo(()=>({startDate:t==null?void 0:t.startDate,endDate:t==null?void 0:t.endDate,days:(t==null?void 0:t.days)??30,endpoint:t==null?void 0:t.endpoint,model:t==null?void 0:t.model,limit:(t==null?void 0:t.limit)??100}),[t==null?void 0:t.startDate,t==null?void 0:t.endDate,t==null?void 0:t.days,t==null?void 0:t.endpoint,t==null?void 0:t.model,t==null?void 0:t.limit]),r=p.useMemo(()=>Zm({startDate:s.startDate,endDate:s.endDate,days:s.days}),[s.days,s.endDate,s.startDate]),[a,i]=p.useState(null),[l,c]=p.useState([]),[u,m]=p.useState([]),[f,g]=p.useState(!1),[b,S]=p.useState(!1),[x,T]=p.useState(null),j=p.useCallback(async M=>{M?g(!0):S(!0);try{const _={startDate:r.startDate,endDate:r.endDate,endpoint:s.endpoint,model:s.model,limit:s.limit},[C,L,A]=await Promise.all([Pi.getForwardSummary(_),Pi.getForwardByEndpoint(_),Pi.getForwardRequests(_)]);i(C),c(L),m(A),T(null)}catch(_){T(Kj(_,"Failed to load forward metrics"))}finally{M?g(!1):S(!1)}},[s.endpoint,s.model,s.limit,r.endDate,r.startDate]),w=p.useCallback(async()=>{await j(!1)},[j]);return p.useEffect(()=>{j(!0)},[j]),p.useEffect(()=>{if(n<=0)return;const M=window.setInterval(()=>{j(!1)},n);return()=>{window.clearInterval(M)}},[n,j]),{summary:a,endpointMetrics:l,requests:u,isLoading:f,isRefreshing:b,error:x,refresh:w}},Yj=15e3,Qp=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,Xj=(e={})=>{const{filters:t,autoRefreshMs:n=Yj,service:s=Pi}=e,r=p.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=p.useMemo(()=>Zm({startDate:r.startDate,endDate:r.endDate,days:r.days}),[r.days,r.endDate,r.startDate]),[i,l]=p.useState(null),[c,u]=p.useState([]),[m,f]=p.useState([]),[g,b]=p.useState([]),[S,x]=p.useState(null),[T,j]=p.useState([]),[w,M]=p.useState(null),[_,C]=p.useState(!1),[L,A]=p.useState(!1),[B,N]=p.useState(!1),[O,R]=p.useState(null),I=p.useCallback(async K=>{K?A(!0):N(!0);try{const P=s.getMemorySummary?s.getMemorySummary().catch(()=>null):Promise.resolve(null),W=s.getMemoryTimeline?s.getMemoryTimeline({days:a.days,endDate:a.endDate,granularity:r.granularity}).catch(()=>[]):Promise.resolve([]),[se,V,ie,re,fe,Se]=await Promise.all([s.getSummary({startDate:a.startDate,endDate:a.endDate}),s.getByModel({startDate:a.startDate,endDate:a.endDate}),s.getSessions({startDate:a.startDate,endDate:a.endDate,model:r.model,limit:r.sessionLimit}),s.getDaily({days:a.days,endDate:a.endDate,granularity:r.granularity}),P,W]);l(se),u(V),f(ie),b(re),x(fe),j(Se),R(null)}catch(P){R(Qp(P,"Failed to load metrics"))}finally{K?A(!1):N(!1)}},[r.granularity,r.model,r.sessionLimit,a.days,a.endDate,a.startDate,s]),$=p.useCallback(async()=>{await I(!1)},[I]),U=p.useCallback(async K=>{C(!0);try{const P=await s.getSessionDetail(K);M(P)}catch(P){R(Qp(P,"Failed to load session detail"))}finally{C(!1)}},[s]),q=p.useCallback(()=>{M(null)},[]);return p.useEffect(()=>{I(!0)},[I]),p.useEffect(()=>{if(n<=0)return;const K=window.setInterval(()=>{I(!1)},n);return()=>{window.clearInterval(K)}},[n,I]),{summary:i,modelMetrics:c,sessions:m,timeline:g,memorySummary:S,memoryTimeline:T,sessionDetail:w,isLoading:L,isRefreshing:B,isSessionDetailLoading:_,error:O,refresh:$,loadSessionDetail:U,clearSessionDetail:q}},Gj=15e3,Jj=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,Qj=(e={})=>{const{filters:t,autoRefreshMs:n=Gj}=e,s=p.useMemo(()=>({startDate:t==null?void 0:t.startDate,endDate:t==null?void 0:t.endDate,days:(t==null?void 0:t.days)??30,model:t==null?void 0:t.model}),[t==null?void 0:t.days,t==null?void 0:t.endDate,t==null?void 0:t.model,t==null?void 0:t.startDate]),r=p.useMemo(()=>Zm({startDate:s.startDate,endDate:s.endDate,days:s.days}),[s.days,s.endDate,s.startDate]),[a,i]=p.useState(null),[l,c]=p.useState(!1),[u,m]=p.useState(!1),[f,g]=p.useState(null),b=p.useCallback(async x=>{x?c(!0):m(!0);try{const T=await Pi.getUsageBreakdown({startDate:r.startDate,endDate:r.endDate,model:s.model});i(T),g(null)}catch(T){g(Jj(T,"Failed to load usage breakdown"))}finally{x?c(!1):m(!1)}},[s.model,r.endDate,r.startDate]),S=p.useCallback(async()=>{await b(!1)},[b]);return p.useEffect(()=>{b(!0)},[b]),p.useEffect(()=>{if(n<=0)return;const x=window.setInterval(()=>{b(!1)},n);return()=>{window.clearInterval(x)}},[n,b]),{data:a,isLoading:l,isRefreshing:u,error:f,refresh:S}},{useToken:Zj}=Ge,eC=({data:e,loading:t})=>{const{t:n}=Ie(),{token:s}=Zj();if(t)return o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.charts.endpointDistribution"),children:o.jsx("div",{style:{width:"100%",height:240},children:o.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100%",color:s.colorTextSecondary},children:n("settings.common.loading")})})});if(e.length===0)return o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.charts.endpointDistribution"),children:o.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:240,color:s.colorTextSecondary},children:n("settings.charts.noForwardMetrics")})});const r=e.map(a=>({endpoint:a.endpoint.split(".").pop()||a.endpoint,requests:a.requests,successful:a.successful,failed:a.failed}));return o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.charts.endpointDistribution"),children:o.jsx("div",{style:{width:"100%",height:240},children:o.jsx(Ko,{children:o.jsxs(Om,{data:r,children:[o.jsx(Yi,{strokeDasharray:"3 3"}),o.jsx(Xi,{dataKey:"endpoint"}),o.jsx(Gi,{}),o.jsx(Vo,{formatter:(a,i)=>[`${a}`,i.charAt(0).toUpperCase()+i.slice(1)]}),o.jsx($m,{}),o.jsx(yc,{dataKey:"successful",fill:"var(--lotus-chart-secondary)",name:n("settings.common.successful"),fillOpacity:.9,radius:[4,4,0,0]}),o.jsx(yc,{dataKey:"failed",fill:"var(--lotus-chart-danger)",name:n("settings.common.failed"),fillOpacity:.9,radius:[4,4,0,0]})]})})})})},{useToken:tC}=Ge,nC=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),n=Math.floor(t/60),s=t%60;if(n>=60){const r=Math.floor(n/60),a=n%60;return`${r}h ${a}m`}return n>0?`${n}m ${s}s`:`${s}s`},Zp=({summary:e,loading:t})=>{const{t:n}=Ie(),{token:s}=tC();if(t)return o.jsx(cr,{active:!0,paragraph:{rows:1}});const r=e&&e.total_requests>0?(e.successful_requests/e.total_requests*100).toFixed(1):"0.0";return o.jsxs(ps,{gutter:[s.marginSM,s.marginSM],children:[o.jsx(Et,{xs:24,sm:12,xl:6,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(nn,{title:n("settings.forwardMetricsCards.totalForwardRequests"),value:(e==null?void 0:e.total_requests)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),o.jsx(Et,{xs:24,sm:12,xl:6,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(nn,{title:n("settings.forwardMetricsCards.successRate"),value:r,suffix:"%",valueStyle:{color:Number(r)>=95?"var(--lotus-chart-secondary)":Number(r)>=80?"var(--lotus-chart-accent)":"var(--lotus-chart-danger)"}})})}),o.jsx(Et,{xs:24,sm:12,xl:6,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(nn,{title:n("settings.forwardMetricsCards.forwardTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),o.jsx(Et,{xs:24,sm:12,xl:6,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(nn,{title:n("settings.forwardMetricsCards.avgResponseTime"),value:nC(e==null?void 0:e.avg_duration_ms),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:Wr}=He,sC=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),n=Math.floor(t/60),s=t%60;return n>0?`${n}m ${s}s`:`${s}s`},rC=e=>new Date(e).toLocaleString(),oC=({requests:e,loading:t})=>{const{t:n}=Ie(),s=[{title:n("settings.metricsTable.forward.columns.id"),dataIndex:"forward_id",key:"forward_id",width:120,render:r=>o.jsxs(Wr,{style:{fontSize:12},copyable:!0,children:[r.slice(0,8),"..."]})},{title:n("settings.metricsTable.forward.columns.endpoint"),dataIndex:"endpoint",key:"endpoint",width:150,render:r=>o.jsx(Ne,{color:"processing",children:r.split(".").pop()||r})},{title:n("settings.metricsTable.forward.columns.model"),dataIndex:"model",key:"model",width:120},{title:n("settings.metricsTable.forward.columns.type"),dataIndex:"is_stream",key:"is_stream",width:80,render:r=>o.jsx(Ne,{color:r?"purple":"processing",children:n(r?"settings.metricsTable.forward.typeStream":"settings.metricsTable.forward.typeSync")})},{title:n("settings.metricsTable.forward.columns.status"),key:"status",width:100,render:(r,a)=>{const i=a.status==="success"?"success":a.status==="error"?"error":"default";return o.jsx(Mm,{status:i,text:a.status_code?o.jsxs("span",{children:[a.status,o.jsxs(Wr,{type:"secondary",style:{marginLeft:4},children:["(",a.status_code,")"]})]}):a.status||"-"})}},{title:n("settings.metricsTable.forward.columns.tokens"),key:"tokens",width:100,render:(r,a)=>a.token_usage?o.jsx(Wr,{children:a.token_usage.total_tokens.toLocaleString()}):o.jsx(Wr,{type:"secondary",children:"-"})},{title:n("settings.metricsTable.forward.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",width:100,render:r=>sC(r)},{title:n("settings.metricsTable.forward.columns.started"),dataIndex:"started_at",key:"started_at",width:160,render:r=>o.jsx(Wr,{type:"secondary",style:{fontSize:12},children:rC(r)})},{title:n("settings.metricsTable.forward.columns.error"),dataIndex:"error",key:"error",width:200,render:r=>r?o.jsx(Wr,{type:"danger",ellipsis:!0,style:{maxWidth:180},children:r}):o.jsx(Wr,{type:"secondary",children:"-"})}];return o.jsx(or,{rowKey:"forward_id",className:"lotus-metric-table",columns:s,dataSource:e,loading:t,size:"small",pagination:{pageSize:10,showSizeChanger:!0,showTotal:r=>n("settings.metricsTable.forward.totalRequests",{total:r}),pageSizeOptions:["10","20","50","100"]},scroll:{x:1200},locale:{emptyText:n("settings.metricsTable.forward.empty")}})},{useToken:aC}=Ge,iC=e=>{if(!e)return"-";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},ef=({summary:e,loading:t})=>{const{t:n}=Ie(),{token:s}=aC();return t?o.jsx(cr,{active:!0,paragraph:{rows:1}}):o.jsxs(ps,{gutter:[s.marginSM,s.marginSM],children:[o.jsx(Et,{xs:24,sm:12,lg:8,xl:6,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(nn,{title:n("settings.unifiedMetricsCards.totalMemories"),value:(e==null?void 0:e.total_memories)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:6,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(nn,{title:n("settings.unifiedMetricsCards.staleCandidates"),value:(e==null?void 0:e.stale_candidate_count)??0,precision:0,valueStyle:{color:((e==null?void 0:e.stale_candidate_count)??0)>0?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:6,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(nn,{title:n("settings.unifiedMetricsCards.memoryProjects"),value:(e==null?void 0:e.project_count)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:6,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(nn,{title:n("settings.unifiedMetricsCards.lastReindex"),value:iC(e==null?void 0:e.last_reindex_at),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:lC}=He,cC=({data:e,loading:t})=>{const{t:n}=Ie();return t?o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.charts.memoryTrendTitle"),children:o.jsx(cr,{active:!0,paragraph:{rows:5}})}):o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.charts.memoryTrendTitle"),children:e.length===0?o.jsx(Mn,{image:Mn.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noMemoryTrend")}):o.jsxs(o.Fragment,{children:[o.jsx(lC,{type:"secondary",children:n("settings.charts.memoryTrendDescription")}),o.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:o.jsx(Ko,{children:o.jsxs(jb,{data:e,children:[o.jsx(Yi,{strokeDasharray:"3 3"}),o.jsx(Xi,{dataKey:"label",minTickGap:24}),o.jsx(Gi,{allowDecimals:!1}),o.jsx(Vo,{}),o.jsx($m,{}),o.jsx(Lo,{type:"monotone",dataKey:"total_memories",name:n("settings.charts.totalMemories"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),o.jsx(Lo,{type:"monotone",dataKey:"created_memories",name:n("settings.charts.createdMemories"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),o.jsx(Lo,{type:"monotone",dataKey:"updated_memories",name:n("settings.charts.updatedMemories"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{useToken:dC}=Ge,uC=e=>{const t=Math.floor(e/1e3),n=Math.floor(t/60),s=t%60;return n>0?`${n}m ${s}s`:`${s}s`},mC=e=>{const t=e.filter(s=>typeof s.duration_ms=="number"&&s.duration_ms>0);if(t.length===0)return 0;const n=t.reduce((s,r)=>s+(r.duration_ms??0),0);return Math.floor(n/t.length)},tf=({summary:e,sessions:t,loading:n})=>{const{t:s}=Ie(),{token:r}=dC();if(n)return o.jsx(cr,{active:!0,paragraph:{rows:1}});const a=mC(t);return o.jsxs(ps,{gutter:[r.marginSM,r.marginSM],children:[o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(nn,{title:s("settings.metricsCards.syncMismatches",{defaultValue:"Sync Mismatches"}),value:(e==null?void 0:e.total_sync_mismatches)??0,precision:0,valueStyle:{color:((e==null?void 0:e.total_sync_mismatches)??0)>0?"var(--lotus-chart-danger)":"var(--lotus-chart-secondary)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(nn,{title:s("settings.metricsCards.totalSessions"),value:(e==null?void 0:e.total_sessions)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(nn,{title:s("settings.metricsCards.chatTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(nn,{title:s("settings.metricsCards.totalToolCalls"),value:(e==null?void 0:e.total_tool_calls)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(nn,{title:s("settings.metricsCards.avgSessionDuration"),value:a>0?uC(a):"-",valueStyle:{color:"var(--lotus-chart-accent)"}})})})]})},{Text:hC}=He,nf=["var(--lotus-chart-primary)","var(--lotus-chart-secondary)","var(--lotus-chart-accent)","var(--lotus-chart-purple)","var(--lotus-chart-cyan)"],pC=({data:e,loading:t})=>{const{t:n}=Ie();if(t)return o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.charts.modelDistribution"),children:o.jsx(cr,{active:!0,paragraph:{rows:5}})});const s=e.map(r=>({name:r.model,value:r.tokens.total_tokens}));return o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.charts.modelDistribution"),children:s.length===0?o.jsx(Mn,{image:Mn.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noModelMetrics")}):o.jsxs(o.Fragment,{children:[o.jsx(hC,{type:"secondary",children:n("settings.charts.modelDistributionDescription")}),o.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:o.jsx(Ko,{children:o.jsxs(__,{children:[o.jsx(k_,{data:s,cx:"50%",cy:"50%",outerRadius:90,fill:"var(--lotus-chart-primary)",dataKey:"value",nameKey:"name",label:!0,children:s.map((r,a)=>o.jsx(T_,{fill:nf[a%nf.length]},`${r.name}-${a}`))}),o.jsx(Vo,{})]})})})]})})},fC=e=>{if(!e)return"-";const t=new Date(e);return Number.isNaN(t.getTime())?"-":t.toLocaleString()},gC=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),n=Math.floor(t/60),s=t%60;if(n>=60){const r=Math.floor(n/60),a=n%60;return`${r}h ${a}m`}return n>0?`${n}m ${s}s`:`${s}s`},yC=e=>{switch(e){case"completed":return"success";case"running":return"processing";case"error":return"error";case"cancelled":return"warning";default:return"default"}},bC=({sessions:e,loading:t,onSelectSession:n})=>{const{t:s}=Ie(),r=[{title:s("settings.metricsTable.session.columns.session"),dataIndex:"session_id",key:"session_id",render:a=>o.jsx(bt,{title:a,children:o.jsxs("span",{children:[a.slice(0,8),"..."]})}),width:120},{title:s("settings.metricsTable.session.columns.model"),dataIndex:"model",key:"model",width:160},{title:s("settings.metricsTable.session.columns.status"),dataIndex:"status",key:"status",width:120,render:a=>o.jsx(Ne,{color:yC(a),children:a})},{title:s("settings.metricsTable.session.columns.started"),dataIndex:"started_at",key:"started_at",render:a=>fC(a),width:200,sorter:(a,i)=>new Date(a.started_at).getTime()-new Date(i.started_at).getTime(),defaultSortOrder:"descend"},{title:s("settings.metricsTable.session.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",render:a=>gC(a),width:120},{title:s("settings.metricsTable.session.columns.tokens"),key:"tokens",render:(a,i)=>i.total_token_usage.total_tokens.toLocaleString(),width:120,sorter:(a,i)=>a.total_token_usage.total_tokens-i.total_token_usage.total_tokens},{title:s("settings.metricsTable.session.columns.toolCalls"),dataIndex:"tool_call_count",key:"tool_call_count",width:120,sorter:(a,i)=>a.tool_call_count-i.tool_call_count},{title:s("settings.metricsTable.session.columns.messages"),dataIndex:"message_count",key:"message_count",width:120,sorter:(a,i)=>a.message_count-i.message_count},{title:s("settings.metricsTable.session.columns.action"),key:"action",fixed:"right",width:120,render:(a,i)=>o.jsx(ue,{type:"link",onClick:()=>{n(i.session_id)},children:s("settings.metricsTable.session.view")})}];return o.jsx(or,{rowKey:"session_id",size:"small",className:"lotus-metric-table",columns:r,loading:t,dataSource:e,pagination:{pageSize:10,showSizeChanger:!1},scroll:{x:1100}})},{Text:xC}=He,sf={message_count:"Message Count",last_message_id:"Last Message",pending_question:"Pending Question"},vC=e=>sf[e]?sf[e]:e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" "),SC=({breakdown:e,loading:t})=>{const{t:n}=Ie();if(t)return o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),children:o.jsx(cr,{active:!0,paragraph:{rows:5}})});const s=Object.entries(e??{}).map(([r,a])=>({reason:r,label:n(`settings.syncMismatchReasons.${r}`,{defaultValue:vC(r)}),count:a})).sort((r,a)=>a.count-r.count);return o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),extra:o.jsx(xC,{type:"secondary",children:n("settings.metricsDashboard.syncMismatchBreakdownSubtitle",{defaultValue:"Grouped by execute sync mismatch reason"})}),children:s.length===0?o.jsx(Mn,{image:Mn.PRESENTED_IMAGE_SIMPLE,description:n("settings.metricsDashboard.noSyncMismatchBreakdown",{defaultValue:"No sync mismatches recorded for the selected range"})}):o.jsx("div",{style:{width:"100%",minWidth:0,height:280,minHeight:280},children:o.jsx(Ko,{children:o.jsxs(Om,{data:s,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[o.jsx(Yi,{strokeDasharray:"3 3"}),o.jsx(Xi,{type:"number",allowDecimals:!1}),o.jsx(Gi,{dataKey:"label",type:"category",width:110}),o.jsx(Vo,{formatter:r=>[r.toLocaleString(),n("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})],labelFormatter:r=>n("settings.metricsDashboard.syncMismatchReasonLabel",{defaultValue:"Reason: {{label}}",label:r})}),o.jsx(yc,{dataKey:"count",fill:"var(--lotus-chart-danger)",radius:[0,6,6,0],name:n("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})})]})})})})},{Text:wC}=He,_C=({data:e,loading:t})=>{const{t:n}=Ie();return t?o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.charts.tokenUsageOverTime"),children:o.jsx(cr,{active:!0,paragraph:{rows:5}})}):o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:n("settings.charts.tokenUsageOverTime"),children:e.length===0?o.jsx(Mn,{image:Mn.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noTokenUsage")}):o.jsxs(o.Fragment,{children:[o.jsx(wC,{type:"secondary",children:n("settings.charts.tokenUsageDescription")}),o.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:o.jsx(Ko,{children:o.jsxs(jb,{data:e,children:[o.jsx(Yi,{strokeDasharray:"3 3"}),o.jsx(Xi,{dataKey:"label",minTickGap:24}),o.jsx(Gi,{allowDecimals:!1}),o.jsx(Vo,{}),o.jsx($m,{}),o.jsx(Lo,{type:"monotone",dataKey:"totalTokens",name:n("settings.charts.total"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),o.jsx(Lo,{type:"monotone",dataKey:"promptTokens",name:n("settings.charts.prompt"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),o.jsx(Lo,{type:"monotone",dataKey:"completionTokens",name:n("settings.charts.completion"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{Text:kC}=He,va=({title:e,subtitle:t,emptyText:n,color:s="var(--lotus-chart-primary)",data:r,loading:a,countLabel:i})=>{const{t:l}=Ie();return a?o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:e,children:o.jsx(cr,{active:!0,paragraph:{rows:5}})}):o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:e,children:r.length===0?o.jsx(Mn,{image:Mn.PRESENTED_IMAGE_SIMPLE,description:n}):o.jsxs(o.Fragment,{children:[t?o.jsx(kC,{type:"secondary",children:t}):null,o.jsx("div",{style:{width:"100%",minWidth:0,height:280,marginTop:t?12:0},children:o.jsx(Ko,{children:o.jsxs(Om,{data:r,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[o.jsx(Yi,{strokeDasharray:"3 3"}),o.jsx(Xi,{type:"number",allowDecimals:!1}),o.jsx(Gi,{dataKey:"label",type:"category",width:110}),o.jsx(Vo,{formatter:c=>[c.toLocaleString(),i??l("settings.metricsDashboard.calls",{defaultValue:"Calls"})],labelFormatter:(c,u)=>{var f,g;const m=(g=(f=u==null?void 0:u[0])==null?void 0:f.payload)==null?void 0:g.meta;return m?`${c} · ${m}`:String(c)}}),o.jsx(yc,{dataKey:"count",fill:s,radius:[0,6,6,0],name:i??l("settings.metricsDashboard.calls",{defaultValue:"Calls"})})]})})})]})})},{useToken:TC}=Ge,rf=({summary:e,loading:t})=>{const{t:n}=Ie(),{token:s}=TC();return t?o.jsx(cr,{active:!0,paragraph:{rows:1}}):o.jsxs(ps,{gutter:[s.marginSM,s.marginSM],children:[o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(nn,{title:n("settings.metricsDashboard.skillsAndMcp.cards.skillLoadCalls",{defaultValue:"Skill Loads"}),value:(e==null?void 0:e.skill_load_calls)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(nn,{title:n("settings.metricsDashboard.skillsAndMcp.cards.uniqueSkills",{defaultValue:"Unique Skills"}),value:(e==null?void 0:e.unique_skills)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(nn,{title:n("settings.metricsDashboard.skillsAndMcp.cards.mcpCalls",{defaultValue:"MCP Calls"}),value:(e==null?void 0:e.mcp_calls)??0,precision:0,valueStyle:{color:"var(--lotus-chart-accent)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(nn,{title:n("settings.metricsDashboard.skillsAndMcp.cards.uniqueMcpServers",{defaultValue:"MCP Servers"}),value:(e==null?void 0:e.unique_mcp_servers)??0,precision:0,valueStyle:{color:"var(--lotus-chart-cyan)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(nn,{title:n("settings.metricsDashboard.skillsAndMcp.cards.uniqueMcpTools",{defaultValue:"MCP Tools"}),value:(e==null?void 0:e.unique_mcp_tools)??0,precision:0,valueStyle:{color:"var(--lotus-chart-secondary)"}})})}),o.jsx(Et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(Ce,{size:"small",className:"lotus-metric-card",children:o.jsx(nn,{title:n("settings.metricsDashboard.skillsAndMcp.cards.coreToolCalls",{defaultValue:"Core Tool Calls"}),value:(e==null?void 0:e.core_tool_calls)??0,precision:0,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})})]})},{Text:ko}=He,{useToken:jC}=Ge,of=70,af=130,lf=2,cf=1.2,df=.65,uf=45,mf=1.8,hf=e=>"date"in e?e.date:e.label,CC=(e,t)=>{if(t<=0||e<=0)return"var(--lotus-heat-0)";const n=e/t;return n>=.8?"var(--lotus-heat-4)":n>=.6?"var(--lotus-heat-3)":n>=.4?"var(--lotus-heat-2)":n>=.2?"var(--lotus-heat-1)":"var(--lotus-heat-0)"},Sa=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),n=Math.floor(t/60),s=t%60;if(n>=60){const r=Math.floor(n/60),a=n%60;return`${r}h ${a}m`}return n>0?`${n}m ${s}s`:`${s}s`},pf=e=>{if(!e)return"-";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},zd=e=>{const t=Object.entries(e??{}).sort((n,s)=>s[1]-n[1]);return t.length===0?"-":t.slice(0,6).map(([n,s])=>`${n}: ${s.toLocaleString()}`).join(" • ")},Bd=(e,t=320)=>({width:"100%",display:"grid",gridTemplateColumns:`repeat(auto-fit, minmax(${t}px, 1fr))`,gap:e}),MC=()=>{const{t:e}=Ie(),{token:t}=jC(),n=ho(F=>F.themeMode)==="dark",[s,r]=p.useState(void 0),[a,i]=p.useState(void 0),[l,c]=p.useState(void 0),[u,m]=p.useState(30),[f,g]=p.useState("daily"),{summary:b,modelMetrics:S,sessions:x,timeline:T,memorySummary:j,memoryTimeline:w,sessionDetail:M,isLoading:_,isRefreshing:C,isSessionDetailLoading:L,error:A,refresh:B,loadSessionDetail:N,clearSessionDetail:O}=Xj({filters:{startDate:s,endDate:a,model:l,days:u,granularity:f}}),{summary:R,endpointMetrics:I,requests:$,isLoading:U,isRefreshing:q,error:K,refresh:P}=Vj({filters:{startDate:s,endDate:a,days:u,model:l}}),{data:W,isLoading:se,isRefreshing:V,error:ie,refresh:re}=Qj({filters:{startDate:s,endDate:a,days:u,model:l}}),fe=p.useMemo(()=>T.map(F=>({label:hf(F),promptTokens:F.total_token_usage.prompt_tokens,completionTokens:F.total_token_usage.completion_tokens,totalTokens:F.total_token_usage.total_tokens})),[T]),Se=p.useMemo(()=>S.map(F=>({label:F.model,value:F.model})),[S]),ke=p.useMemo(()=>{const F=T.map(ge=>({label:hf(ge),sessions:ge.total_sessions,tokens:ge.total_token_usage.total_tokens})),ce=F.reduce((ge,De)=>Math.max(ge,De.sessions),0);return{points:F,maxSessions:ce}},[T]),Be=p.useMemo(()=>{const F=$.map(ge=>ge.duration_ms).filter(ge=>typeof ge=="number"&&ge>0).sort((ge,De)=>ge-De);if(F.length===0)return null;const ce=Math.ceil(F.length*.95)-1;return F[Math.max(0,Math.min(ce,F.length-1))]},[$]),tt=p.useMemo(()=>[{title:e("settings.metricsDashboard.roundColumns.round"),dataIndex:"round_id",key:"round_id",render:F=>`${F.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:F=>Sa(F)},{title:e("settings.metricsDashboard.roundColumns.tokens"),key:"tokens",render:(F,ce)=>ce.token_usage.total_tokens.toLocaleString()},{title:e("settings.metricsDashboard.roundColumns.toolCalls"),key:"tool_calls",render:(F,ce)=>ce.tool_calls.length}],[e]),ft=p.useMemo(()=>{const F=(b==null?void 0:b.total_sessions)??0,ce=(b==null?void 0:b.total_tokens.total_tokens)??0,ge=(b==null?void 0:b.total_tool_calls)??0,De=(b==null?void 0:b.active_sessions)??0,Le=x.reduce((cn,on)=>cn+on.total_rounds,0),me=(R==null?void 0:R.total_requests)??0,H=(R==null?void 0:R.total_tokens.total_tokens)??0,ye=(R==null?void 0:R.failed_requests)??0,xe=$.filter(cn=>cn.is_stream).length,_e=F>0?De/F*100:0,Ue=me>0?ye/me*100:0,Re=$.length>0?xe/$.length*100:0,ut=ce/of+ge*lf,ot=ce/af+ge*cf,_t=Math.max(0,ut-ot)*df,vt=Math.max(ot,ut-_t),Bt=Sa(_t*6e4),Kt=Number((_t/(8*60)).toFixed(2)),qe=ut>0?Math.min(uf,Number((_t/ut*100).toFixed(1))):0,rn=vt>0?Math.min(mf,Number((ut/vt).toFixed(2))):1;return[{title:e("settings.metricsDashboard.compactStats.avgTokensPerSession"),value:F>0?Math.round(ce/F):0},{title:e("settings.metricsDashboard.compactStats.estimatedTimeSaved"),value:Bt},{title:e("settings.metricsDashboard.compactStats.estimatedEfficiencyLift"),value:qe,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.estimatedSpeedMultiplier"),value:rn,suffix:e("settings.metricsDashboard.multiplierSuffix")},{title:e("settings.metricsDashboard.compactStats.estimatedSavedWorkdays"),value:Kt},{title:e("settings.metricsDashboard.compactStats.avgRoundsPerSession"),value:F>0?Number((Le/F).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.toolCallsPerSession"),value:F>0?Number((ge/F).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.activeSessionRate"),value:Number(_e.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.avgTokensPerForward"),value:me>0?Math.round(H/me):0},{title:e("settings.metricsDashboard.compactStats.forwardErrorRate"),value:Number(Ue.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.streamingRatio"),value:Number(Re.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.p95ForwardLatency"),value:Sa(Be)},{title:e("settings.metricsDashboard.compactStats.modelCoverage"),value:S.length},{title:e("settings.metricsDashboard.compactStats.endpointCoverage"),value:I.length}]},[I.length,$,R,S.length,Be,x,b,e]),Ht=p.useMemo(()=>{const F=(R==null?void 0:R.total_requests)??0,ce=(R==null?void 0:R.failed_requests)??0,ge=$.filter(me=>me.is_stream).length,De=$.length>0?ge/$.length*100:0,Le=F>0?ce/F*100:0;return[{title:e("settings.metricsDashboard.forward.performance.p95Latency",{defaultValue:"P95 Latency"}),value:Sa(Be)},{title:e("settings.metricsDashboard.forward.performance.errorRate",{defaultValue:"Error Rate"}),value:Number(Le.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.streamingRatio",{defaultValue:"Streaming Ratio"}),value:Number(De.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.endpointCoverage",{defaultValue:"Endpoint Coverage"}),value:I.length}]},[I.length,$,R,Be,e]),Oe=p.useMemo(()=>W?[{label:e("settings.metricsDashboard.skillsAndMcp.mix.coreTools",{defaultValue:"Core Tools"}),count:W.core_tool_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.skillLoads",{defaultValue:"Skill Loads"}),count:W.skill_load_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.mcpCalls",{defaultValue:"MCP Calls"}),count:W.mcp_calls}].filter(F=>F.count>0):[],[e,W]),zt=p.useMemo(()=>((W==null?void 0:W.top_skills)??[]).map(F=>({label:F.skill_id,count:F.count})),[W]),Ye=p.useMemo(()=>((W==null?void 0:W.top_mcp_servers)??[]).map(F=>({label:F.server_id,count:F.count,meta:e("settings.metricsDashboard.skillsAndMcp.meta.uniqueTools",{defaultValue:"{{count}} tools",count:F.unique_tools})})),[e,W]),we=p.useMemo(()=>((W==null?void 0:W.top_mcp_tools)??[]).map(F=>({label:F.tool_name,count:F.count,meta:F.server_id})),[W]),Ke=p.useMemo(()=>((W==null?void 0:W.top_core_tools)??[]).map(F=>({label:F.name,count:F.count})),[W]),st=M==null?void 0:M.session,Dt=C||q||V;return o.jsxs(he,{direction:"vertical",size:t.marginMD,style:{width:"100%"},children:[A?o.jsx(Ut,{type:"error",showIcon:!0,message:A}):null,K?o.jsx(Ut,{type:"error",showIcon:!0,message:K}):null,ie?o.jsx(Ut,{type:"error",showIcon:!0,message:ie}):null,o.jsx(Ce,{size:"small",title:e("settings.metricsDashboard.filtersTitle"),extra:o.jsx(ue,{icon:o.jsx(lr,{}),loading:Dt,onClick:()=>{B(),P(),re()},children:e("settings.metricsDashboard.refresh")}),children:o.jsxs(he,{wrap:!0,children:[o.jsx(rp,{placeholder:e("settings.metricsDashboard.startDate"),onChange:F=>{r(F?F.format("YYYY-MM-DD"):void 0)}}),o.jsx(rp,{placeholder:e("settings.metricsDashboard.endDate"),onChange:F=>{i(F?F.format("YYYY-MM-DD"):void 0)}}),o.jsx(St,{allowClear:!0,style:{minWidth:180},placeholder:e("settings.metricsDashboard.model"),value:l,options:Se,onChange:F=>{c(F)}}),o.jsx(St,{style:{width:120},value:u,options:[7,14,30,90].map(F=>({label:e("settings.metricsDashboard.daysOption",{value:F}),value:F})),onChange:F=>{m(F)}}),o.jsx(St,{style:{width:140},value:f,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:F=>{g(F)}})]})}),o.jsx(Ce,{size:"small",title:e("settings.metricsDashboard.dashboardTitle"),children:o.jsx(Di,{size:"small",destroyInactiveTabPane:!0,items:[{key:"overview",label:e("settings.metricsDashboard.tabs.overview"),children:o.jsxs(he,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[o.jsx(tf,{summary:b,sessions:x,loading:_}),o.jsx(Zp,{summary:R,loading:U}),o.jsx(rf,{summary:W,loading:se}),o.jsx(ef,{summary:j,loading:_}),o.jsxs(Ce,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.derivedMetricsTitle"),extra:o.jsx(ko,{type:"secondary",children:e("settings.metricsDashboard.derivedMetricsSubtitle")}),children:[o.jsx(ps,{gutter:[t.marginSM,t.marginSM],children:ft.map(F=>o.jsx(Et,{xs:24,sm:12,md:8,xl:6,children:o.jsx("div",{style:{borderRadius:t.borderRadiusSM,padding:t.paddingXS,background:n?"rgba(255, 255, 255, 0.05)":"rgba(255, 255, 255, 0.82)",border:n?"1px solid rgba(255,255,255,0.08)":"1px solid rgba(148,163,184,0.18)"},children:o.jsx(nn,{title:F.title,value:F.value,suffix:F.suffix,valueStyle:{fontSize:t.fontSizeHeading4}})})},F.title))}),o.jsx(ko,{type:"secondary",style:{display:"block",marginTop:t.marginXS},children:e("settings.metricsDashboard.efficiencyHint",{manualTpm:of,manualToolMinutes:lf,assistedTpm:af,assistedToolMinutes:cf,realization:Math.round(df*100),maxLift:uf,maxMultiplier:mf})})]})]})},{key:"chat",label:e("settings.metricsDashboard.tabs.chat",{defaultValue:"Chat"}),children:o.jsxs(he,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[o.jsx(tf,{summary:b,sessions:x,loading:_}),o.jsxs("div",{style:Bd(t.marginSM,360),children:[o.jsx(_C,{data:fe,loading:_}),o.jsx(pC,{data:S,loading:_})]}),o.jsxs("div",{style:Bd(t.marginSM,360),children:[o.jsx(SC,{breakdown:b==null?void 0:b.sync_mismatch_breakdown,loading:_}),o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.activityHeatmapTitle"),children:ke.points.length===0?o.jsx(ko,{type:"secondary",children:e("settings.metricsDashboard.noActivity")}):o.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))",gap:t.marginXS},children:ke.points.map(F=>o.jsxs("div",{style:{borderRadius:t.borderRadiusSM,padding:t.paddingXS,background:CC(F.sessions,ke.maxSessions),minHeight:64,color:F.sessions>0?"var(--lotus-metric-text-strong)":t.colorTextSecondary},children:[o.jsx("div",{style:{fontSize:12,lineHeight:1.2},children:F.label}),o.jsx("div",{style:{fontWeight:600,marginTop:4},children:e("settings.metricsDashboard.sessionsCount",{count:F.sessions})}),o.jsx("div",{style:{fontSize:12},children:e("settings.metricsDashboard.tokensAmount",{value:F.tokens.toLocaleString()})})]},F.label))})})]})]})},{key:"skills-and-mcp",label:e("settings.metricsDashboard.tabs.skillsAndMcp",{defaultValue:"Skills & MCP"}),children:o.jsxs(he,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[o.jsx(rf,{summary:W,loading:se}),o.jsxs("div",{style:Bd(t.marginSM,360),children:[o.jsx(va,{title:e("settings.metricsDashboard.skillsAndMcp.usageMixTitle",{defaultValue:"Usage Mix"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.usageMixSubtitle",{defaultValue:"Compare core tools, skill loads, and MCP calls in one view."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noUsageMix",{defaultValue:"No usage data available for this range."}),data:Oe,loading:se,color:"var(--lotus-chart-primary)"}),o.jsx(va,{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:zt,loading:se,color:"var(--lotus-chart-purple)"}),o.jsx(va,{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:Ye,loading:se,color:"var(--lotus-chart-cyan)"}),o.jsx(va,{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:we,loading:se,color:"var(--lotus-chart-accent)"}),o.jsx(va,{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:Ke,loading:se,color:"var(--lotus-chart-secondary)"})]})]})},{key:"forward",label:e("settings.metricsDashboard.tabs.forward",{defaultValue:"Forward"}),children:o.jsxs(he,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[o.jsx(Zp,{summary:R,loading:U}),o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.forward.performanceTitle",{defaultValue:"Forward Performance"}),children:o.jsx(ps,{gutter:[t.marginSM,t.marginSM],children:Ht.map(F=>o.jsx(Et,{xs:24,sm:12,xl:6,children:o.jsx("div",{style:{borderRadius:t.borderRadiusSM,padding:t.paddingXS,background:n?"rgba(255, 255, 255, 0.05)":"rgba(255, 255, 255, 0.82)",border:n?"1px solid rgba(255,255,255,0.08)":"1px solid rgba(148,163,184,0.18)"},children:o.jsx(nn,{title:F.title,value:F.value,suffix:F.suffix,valueStyle:{fontSize:t.fontSizeHeading4}})})},F.title))})}),o.jsx(eC,{data:I,loading:U})]})},{key:"memory",label:e("settings.metricsDashboard.tabs.memory",{defaultValue:"Memory"}),children:o.jsxs(he,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[o.jsx(ef,{summary:j,loading:_}),o.jsx(cC,{data:w,loading:_}),o.jsx(Ce,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.memory.breakdownTitle",{defaultValue:"Memory Breakdown"}),children:o.jsxs(Fn,{size:"small",bordered:!0,column:1,children:[o.jsx(Fn.Item,{label:e("settings.metricsDashboard.memory.byType",{defaultValue:"By Type"}),children:zd(j==null?void 0:j.by_type)}),o.jsx(Fn.Item,{label:e("settings.metricsDashboard.memory.byStatus",{defaultValue:"By Status"}),children:zd(j==null?void 0:j.by_status)}),o.jsx(Fn.Item,{label:e("settings.metricsDashboard.memory.byScope",{defaultValue:"By Scope"}),children:zd(j==null?void 0:j.by_scope)}),o.jsx(Fn.Item,{label:e("settings.metricsDashboard.memory.lastDream",{defaultValue:"Last Dream"}),children:pf(j==null?void 0:j.last_dream_at)}),o.jsx(Fn.Item,{label:e("settings.metricsDashboard.memory.lastReindex",{defaultValue:"Last Reindex"}),children:pf(j==null?void 0:j.last_reindex_at)})]})})]})},{key:"records",label:e("settings.metricsDashboard.tabs.records"),children:o.jsx(Di,{size:"small",destroyInactiveTabPane:!0,items:[{key:"sessions",label:e("settings.metricsDashboard.sessionsTabLabel",{count:x.length}),children:o.jsx(Ce,{size:"small",extra:o.jsx(ko,{type:"secondary",children:e("settings.metricsDashboard.sessionsHint")}),children:o.jsx(bC,{sessions:x,loading:_,onSelectSession:F=>{N(F)}})})},{key:"forward-requests",label:e("settings.metricsDashboard.forwardTabLabel",{count:$.length}),children:o.jsx(Ce,{size:"small",children:o.jsx(oC,{requests:$,loading:U})})}]})}]})}),o.jsx(Xn,{title:e("settings.metricsDashboard.sessionMetricsTitle"),open:!!M,onCancel:O,onOk:O,width:960,destroyOnClose:!0,children:L?o.jsx(ko,{children:e("settings.metricsDashboard.loadingSessionDetails")}):st?o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:t.marginMD,children:[o.jsxs(Fn,{size:"small",bordered:!0,column:2,children:[o.jsx(Fn.Item,{label:e("settings.metricsDashboard.sessionDetail.sessionId"),span:2,children:st.session_id}),o.jsx(Fn.Item,{label:e("settings.metricsDashboard.sessionDetail.model"),children:st.model}),o.jsx(Fn.Item,{label:e("settings.metricsDashboard.sessionDetail.status"),children:st.status}),o.jsx(Fn.Item,{label:e("settings.metricsDashboard.sessionDetail.duration"),children:Sa(st.duration_ms)}),o.jsx(Fn.Item,{label:e("settings.metricsDashboard.sessionDetail.messages"),children:st.message_count}),o.jsx(Fn.Item,{label:e("settings.metricsDashboard.sessionDetail.totalTokens"),children:st.total_token_usage.total_tokens.toLocaleString()}),o.jsx(Fn.Item,{label:e("settings.metricsDashboard.sessionDetail.toolCalls"),children:st.tool_call_count})]}),o.jsx(or,{rowKey:"round_id",size:"small",columns:tt,dataSource:M.rounds,pagination:{pageSize:6,showSizeChanger:!1}})]}):o.jsx(ko,{type:"secondary",children:e("settings.metricsDashboard.noDetail")})})]})},{Text:Pl}=He,{useToken:PC}=Ge,EC=e=>{const t=e==null?void 0:e.hooks,n=t==null?void 0:t.image_fallback,s=String((n==null?void 0:n.mode)||"placeholder").trim().toLowerCase();return s==="error"||s==="ocr"||s==="vision"?s:"placeholder"},RC=e=>{const t=e==null?void 0:e.hooks,n=t==null?void 0:t.image_fallback,s=n==null?void 0:n.enabled;return typeof s=="boolean"?s:!1},AC=()=>{const{t:e}=Ie(),{token:t}=PC(),[n,s]=Cr.useMessage(),[r,a]=p.useState(!1),[i,l]=p.useState(!0),[c,u]=p.useState("placeholder"),m=p.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]),f=p.useCallback(async()=>{a(!0);try{const x=await Yt.getBambooConfig();l(RC(x)),u(EC(x))}catch(x){n.error(x instanceof Error?x.message:e("settings.hooksTab.loadFailed"))}finally{a(!1)}},[n,e]),g=p.useCallback(async(x,T)=>{await Yt.setBambooConfig({hooks:{image_fallback:{enabled:x,mode:T}}})},[]),b=p.useCallback(async x=>{a(!0);try{await g(x,c),n.success(e(x?"settings.hooksTab.enabled":"settings.hooksTab.disabled")),await f()}catch(T){n.error(T instanceof Error?T.message:e("settings.hooksTab.updateFailed"))}finally{a(!1)}},[f,c,n,g,e]),S=p.useCallback(async x=>{var T;a(!0);try{await g(i,x),n.success(e("settings.hooksTab.modeUpdated",{mode:((T=m.find(j=>j.value===x))==null?void 0:T.label)??x})),await f()}catch(j){n.error(j instanceof Error?j.message:e("settings.hooksTab.modeUpdateFailed"))}finally{a(!1)}},[i,f,m,n,g,e]);return p.useEffect(()=>{f()},[f]),o.jsxs(be,{vertical:!0,gap:t.marginLG,children:[s,o.jsx(Ce,{size:"small",loading:r,children:o.jsxs(be,{vertical:!0,gap:t.marginXS,children:[o.jsx(Pl,{strong:!0,children:e("settings.hooksTab.title")}),o.jsxs(be,{align:"center",justify:"space-between",children:[o.jsx(Pl,{children:e("settings.hooksTab.enableImagePreflight")}),o.jsx(pn,{checked:i,onChange:b})]}),o.jsxs(be,{align:"center",justify:"space-between",children:[o.jsx(Pl,{children:e("settings.hooksTab.modeLabel")}),o.jsx(St,{style:{width:180},value:c,options:m,onChange:S,disabled:!i})]}),o.jsx(Pl,{type:"secondary",style:{fontSize:t.fontSizeSM},children:e("settings.hooksTab.description")})]})})]})},{Text:kn}=He,Qs=Jn.getInstance();function IC(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 OC=[{label:"Mon",value:"mon"},{label:"Tue",value:"tue"},{label:"Wed",value:"wed"},{label:"Thu",value:"thu"},{label:"Fri",value:"fri"},{label:"Sat",value:"sat"},{label:"Sun",value:"sun"}];function vn(e){return String(e??"").trim()||void 0}function $C(e){return(e==null?void 0:e.type)==="interval"?e.every_seconds:null}function vx(e){return{type:"interval",every_seconds:e}}function DC(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 LC(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 FC(e){switch(e){case"allow":return"allow overlap";case"skip":return"skip overlap";case"queue_one":default:return"queue one"}}function NC(e){var t;return(t=e.state)!=null&&t.next_fire_at?String(e.state.next_fire_at):"-"}function zC(e){var t,n;return(t=e.state)!=null&&t.last_success_at?String(e.state.last_success_at):(n=e.state)!=null&&n.last_finished_at?String(e.state.last_finished_at):"-"}function BC(e){var t,n,s,r;return((t=e.state)==null?void 0:t.running_run_count)>0?{color:"processing",label:"running",detail:`${e.state.running_run_count} active`}:(((n=e.state)==null?void 0:n.queued_run_count)||0)>0?{color:"gold",label:"queued",detail:`${e.state.queued_run_count} pending`}:(((s=e.state)==null?void 0:s.consecutive_failures)||0)>0?{color:"error",label:"failing",detail:`${e.state.consecutive_failures} consecutive failures`}:e.enabled?(r=e.state)!=null&&r.last_success_at?{color:"success",label:"healthy",detail:"last run succeeded"}:{color:"default",label:"idle"}:{color:"default",label:"disabled"}}function WC(e){const t=vn(e);if(!t)return{days:[],invalid:!1};const s=t.split(/[\s,]+/).filter(Boolean).map(i=>Number(i)),r=s.some(i=>!Number.isInteger(i)||i<1||i>31);return{days:Array.from(new Set(s.filter(i=>Number.isInteger(i)&&i>=1&&i<=31))),invalid:r}}function ff(e){switch(e.trigger_type){case"interval":{const t=Number(e.interval_seconds||0);return t<=0?{errorKey:"settings.schedulesTab.validation.intervalRequired"}:{trigger:vx(t)}}case"daily":{const t=e.daily_hour,n=e.daily_minute;return t==null||n==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"daily",hour:t,minute:n,second:0}}}case"weekly":{const t=e.weekly_weekdays||[],n=e.weekly_hour,s=e.weekly_minute;return t.length===0?{errorKey:"settings.schedulesTab.validation.weekdaysRequired"}:n==null||s==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"weekly",weekdays:t,hour:n,minute:s,second:0}}}case"monthly":{const{days:t,invalid:n}=WC(e.monthly_days);if(n)return{errorKey:"settings.schedulesTab.validation.invalidMonthDays"};if(t.length===0)return{errorKey:"settings.schedulesTab.validation.monthDaysRequired"};const s=e.monthly_hour,r=e.monthly_minute;return s==null||r==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"monthly",days:t,hour:s,minute:r,second:0}}}case"cron":{const t=vn(e.cron_expr);return t?{trigger:{type:"cron",expr:t}}:{errorKey:"settings.schedulesTab.validation.cronRequired"}}default:return{errorKey:"settings.schedulesTab.validation.triggerRequired"}}}function gf(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 qC(e){var n,s,r,a,i,l,c,u;const t={name:e.name,enabled:e.enabled,trigger_type:e.trigger.type,timezone:e.timezone||"",start_at:e.start_at||"",end_at:e.end_at||"",misfire_policy:((n=e.misfire_policy)==null?void 0:n.type)||"run_once",overlap_policy:e.overlap_policy||"queue_one",system_prompt:((s=e.run_config)==null?void 0:s.system_prompt)||"",task_message:((r=e.run_config)==null?void 0:r.task_message)||"",model:((a=e.run_config)==null?void 0:a.model)||"",workspace_path:((i=e.run_config)==null?void 0:i.workspace_path)||"",enhance_prompt:((l=e.run_config)==null?void 0:l.enhance_prompt)||"",auto_execute:!!((c=e.run_config)!=null&&c.auto_execute)};switch(((u=e.misfire_policy)==null?void 0:u.type)==="catch_up_window"&&(t.catch_up_window_max_runs=e.misfire_policy.max_catch_up_runs,t.catch_up_window_max_lateness_seconds=e.misfire_policy.max_lateness_seconds),e.trigger.type){case"interval":t.interval_seconds=e.trigger.every_seconds;break;case"daily":t.daily_hour=e.trigger.hour,t.daily_minute=e.trigger.minute;break;case"weekly":t.weekly_weekdays=e.trigger.weekdays,t.weekly_hour=e.trigger.hour,t.weekly_minute=e.trigger.minute;break;case"monthly":t.monthly_days=e.trigger.days.join(", "),t.monthly_hour=e.trigger.hour,t.monthly_minute=e.trigger.minute;break;case"cron":t.cron_expr=e.trigger.expr;break}return t}function UC(){const{t:e}=Ie(),[t,n]=Cr.useMessage(),[s,r]=p.useState(!1),[a,i]=p.useState([]),[l,c]=p.useState({open:!1,scheduleId:null,sessions:[],loading:!1}),[u,m]=p.useState({open:!1,scheduleId:null,runs:[],loading:!1}),[f,g]=p.useState({open:!1,schedule:null,saving:!1}),b=sr(O=>O.close),[S]=Pe.useForm(),[x]=Pe.useForm(),T=Pe.useWatch("trigger_type",S),j=Pe.useWatch("misfire_policy",S),w=Pe.useWatch("trigger_type",x),M=Pe.useWatch("misfire_policy",x),_=p.useCallback(async()=>{r(!0);try{const O=await Qs.listSchedules();i(O.schedules||[])}catch(O){console.error("[Schedules] Failed to load schedules:",O),t.error(e("settings.schedulesTab.loadFailed"))}finally{r(!1)}},[t,e]);p.useEffect(()=>{_()},[_]);const C=[{value:"interval",label:e("settings.schedulesTab.triggerTypes.interval")},{value:"daily",label:e("settings.schedulesTab.triggerTypes.daily")},{value:"weekly",label:e("settings.schedulesTab.triggerTypes.weekly")},{value:"monthly",label:e("settings.schedulesTab.triggerTypes.monthly")},{value:"cron",label:e("settings.schedulesTab.triggerTypes.cron")}],L=[{value:"run_once",label:e("settings.schedulesTab.misfirePolicyOptions.runOnce")},{value:"skip",label:e("settings.schedulesTab.misfirePolicyOptions.skip")},{value:"catch_up_all",label:e("settings.schedulesTab.misfirePolicyOptions.catchUpAll")},{value:"catch_up_window",label:e("settings.schedulesTab.misfirePolicyOptions.catchUpWindow")}],A=[{value:"queue_one",label:e("settings.schedulesTab.overlapPolicyOptions.queueOne")},{value:"skip",label:e("settings.schedulesTab.overlapPolicyOptions.skip")},{value:"allow",label:e("settings.schedulesTab.overlapPolicyOptions.allow")}],B=(O,R)=>o.jsxs(o.Fragment,{children:[o.jsxs(be,{gap:12,wrap:"wrap",children:[o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.name"),name:"name",rules:[{required:!0,message:e("settings.schedulesTab.validation.nameRequired")}],style:{flex:"1 1 260px"},children:o.jsx(Qe,{})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.triggerType"),name:"trigger_type",rules:[{required:!0,message:e("settings.schedulesTab.validation.triggerRequired")}],style:{width:220},children:o.jsx(St,{options:C})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",style:{width:120},children:o.jsx(pn,{})})]}),O==="interval"?o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.intervalSeconds"),name:"interval_seconds",rules:[{required:!0,message:e("settings.schedulesTab.validation.intervalRequired")}],style:{width:220},children:o.jsx(Zt,{min:1,style:{width:"100%"}})}):null,O==="daily"?o.jsxs(be,{gap:12,wrap:"wrap",children:[o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"daily_hour",style:{width:180},children:o.jsx(Zt,{min:0,max:23,style:{width:"100%"}})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"daily_minute",style:{width:180},children:o.jsx(Zt,{min:0,max:59,style:{width:"100%"}})})]}):null,O==="weekly"?o.jsxs(o.Fragment,{children:[o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.weeklyWeekdays"),name:"weekly_weekdays",style:{minWidth:320},children:o.jsx(St,{mode:"multiple",options:OC})}),o.jsxs(be,{gap:12,wrap:"wrap",children:[o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"weekly_hour",style:{width:180},children:o.jsx(Zt,{min:0,max:23,style:{width:"100%"}})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"weekly_minute",style:{width:180},children:o.jsx(Zt,{min:0,max:59,style:{width:"100%"}})})]})]}):null,O==="monthly"?o.jsxs(o.Fragment,{children:[o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.monthlyDays"),name:"monthly_days",style:{minWidth:320},children:o.jsx(Qe,{placeholder:e("settings.schedulesTab.form.monthlyDaysPlaceholder")})}),o.jsxs(be,{gap:12,wrap:"wrap",children:[o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"monthly_hour",style:{width:180},children:o.jsx(Zt,{min:0,max:23,style:{width:"100%"}})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"monthly_minute",style:{width:180},children:o.jsx(Zt,{min:0,max:59,style:{width:"100%"}})})]})]}):null,O==="cron"?o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.cronExpr"),name:"cron_expr",children:o.jsx(Qe,{placeholder:e("settings.schedulesTab.form.cronExprPlaceholder")})}):null,o.jsxs(be,{gap:12,wrap:"wrap",children:[o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.timezone"),name:"timezone",style:{flex:"1 1 240px"},children:o.jsx(Qe,{placeholder:e("settings.schedulesTab.form.timezonePlaceholder")})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.startAt"),name:"start_at",style:{flex:"1 1 240px"},children:o.jsx(Qe,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.endAt"),name:"end_at",style:{flex:"1 1 240px"},children:o.jsx(Qe,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})})]}),o.jsxs(be,{gap:12,wrap:"wrap",children:[o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.misfirePolicy"),name:"misfire_policy",style:{flex:"1 1 240px"},children:o.jsx(St,{options:L})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.overlapPolicy"),name:"overlap_policy",style:{flex:"1 1 240px"},children:o.jsx(St,{options:A})})]}),R==="catch_up_window"?o.jsxs(be,{gap:12,wrap:"wrap",children:[o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxRuns"),name:"catch_up_window_max_runs",style:{width:220},children:o.jsx(Zt,{min:1,style:{width:"100%"}})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxLatenessSeconds"),name:"catch_up_window_max_lateness_seconds",style:{width:260},children:o.jsx(Zt,{min:1,style:{width:"100%"}})})]}):null,o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.taskMessage"),name:"task_message",children:o.jsx(Qe.TextArea,{rows:3,placeholder:e("settings.schedulesTab.form.taskMessagePlaceholder")})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.systemPrompt"),name:"system_prompt",children:o.jsx(Qe.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})}),o.jsxs(be,{gap:12,wrap:"wrap",children:[o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.model"),name:"model",style:{flex:"1 1 240px"},children:o.jsx(Qe,{placeholder:e("settings.schedulesTab.form.modelPlaceholder")})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.workspacePath"),name:"workspace_path",style:{flex:"1 1 320px"},children:o.jsx(Qe,{placeholder:e("settings.schedulesTab.optional")})}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.autoExecute"),name:"auto_execute",valuePropName:"checked",style:{width:160},children:o.jsx(pn,{})})]}),o.jsx(Pe.Item,{label:e("settings.schedulesTab.form.enhancePrompt"),name:"enhance_prompt",children:o.jsx(Qe.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})})]}),N=p.useMemo(()=>[{title:e("settings.schedulesTab.columns.name"),key:"name",render:(O,R)=>o.jsxs(be,{vertical:!0,gap:6,children:[o.jsx(kn,{strong:!0,children:R.name}),o.jsxs(be,{gap:6,wrap:"wrap",children:[o.jsx(Ne,{children:DC(R.trigger)}),R.timezone?o.jsx(Ne,{color:"blue",children:R.timezone}):null,o.jsx(Ne,{children:LC(R.misfire_policy)}),o.jsx(Ne,{children:FC(R.overlap_policy)})]})]})},{title:e("settings.schedulesTab.columns.status"),key:"status",render:(O,R)=>{const I=BC(R);return o.jsxs(be,{vertical:!0,gap:4,children:[o.jsx(Ne,{color:I.color,children:I.label}),I.detail?o.jsx(kn,{type:"secondary",children:I.detail}):null]})}},{title:e("settings.schedulesTab.columns.activity"),key:"activity",render:(O,R)=>{var I,$,U,q;return o.jsxs(be,{vertical:!0,gap:2,children:[o.jsxs(kn,{type:"secondary",children:["queued: ",((I=R.state)==null?void 0:I.queued_run_count)??0]}),o.jsxs(kn,{type:"secondary",children:["running: ",(($=R.state)==null?void 0:$.running_run_count)??0]}),o.jsxs(kn,{type:"secondary",children:["ok: ",((U=R.state)==null?void 0:U.total_success_count)??0]}),o.jsxs(kn,{type:"secondary",children:["fail: ",((q=R.state)==null?void 0:q.total_failure_count)??0]})]})}},{title:e("settings.schedulesTab.columns.nextRun"),key:"next_run_at",render:(O,R)=>o.jsx(kn,{type:"secondary",children:NC(R)})},{title:e("settings.schedulesTab.columns.lastRun"),key:"last_run_at",render:(O,R)=>o.jsx(kn,{type:"secondary",children:zC(R)})},{title:e("settings.schedulesTab.columns.autoExecute"),key:"auto_execute",render:(O,R)=>{var I,$;return o.jsx(kn,{type:(I=R.run_config)!=null&&I.auto_execute?void 0:"secondary",children:($=R.run_config)!=null&&$.auto_execute?e("settings.schedulesTab.yes"):e("settings.schedulesTab.no")})}},{title:e("settings.schedulesTab.columns.model"),key:"model",render:(O,R)=>{var I;return o.jsx(kn,{type:"secondary",children:(I=R.run_config)!=null&&I.model?String(R.run_config.model):"-"})}},{title:e("settings.schedulesTab.columns.enabled"),key:"enabled",render:(O,R)=>o.jsx(pn,{checked:R.enabled,onChange:async I=>{try{await Qs.patchSchedule(R.id,{enabled:I}),await _()}catch($){console.error("[Schedules] Failed to toggle:",$),t.error(e("settings.schedulesTab.updateFailed"))}}})},{title:e("settings.schedulesTab.columns.actions"),key:"actions",render:(O,R)=>{const I=o.jsx(Zt,{min:1,value:$C(R.trigger)??void 0,disabled:R.trigger.type!=="interval",onChange:async $=>{const U=typeof $=="number"?$:null;if(!(!U||U<=0))try{await Qs.patchSchedule(R.id,{trigger:vx(U)}),await _()}catch(q){console.error("[Schedules] Failed to patch interval:",q),t.error(e("settings.schedulesTab.updateFailed"))}}});return o.jsxs(be,{vertical:!0,gap:8,children:[o.jsxs(be,{gap:8,wrap:"wrap",children:[o.jsx(ue,{size:"small",onClick:()=>{g({open:!0,schedule:R,saving:!1}),x.setFieldsValue(qC(R))},children:e("settings.schedulesTab.actions.edit")}),o.jsx(ue,{size:"small",onClick:async()=>{try{await Qs.runScheduleNow(R.id),t.success(e("settings.schedulesTab.enqueuedRun")),await _()}catch($){console.error("[Schedules] Failed to run now:",$),t.error(e("settings.schedulesTab.runNowFailed"))}},children:e("settings.schedulesTab.actions.runNow")}),o.jsx(ue,{size:"small",onClick:async()=>{c($=>({...$,open:!0,scheduleId:R.id,loading:!0,sessions:[]}));try{const $=await Qs.listScheduleSessions(R.id);c(U=>({...U,open:!0,scheduleId:R.id,loading:!1,sessions:($.sessions||[]).map(q=>({id:q.id,title:q.title,updated_at:q.updated_at}))}))}catch($){console.error("[Schedules] Failed to list sessions:",$),t.error(e("settings.schedulesTab.loadSessionsFailed")),c(U=>({...U,loading:!1}))}},children:e("settings.schedulesTab.actions.sessions")}),o.jsx(ue,{size:"small",onClick:async()=>{m($=>({...$,open:!0,scheduleId:R.id,loading:!0,runs:[]}));try{const $=await Qs.listScheduleRuns(R.id);m(U=>({...U,open:!0,scheduleId:R.id,loading:!1,runs:$.runs||[]}))}catch($){console.error("[Schedules] Failed to list runs:",$),t.error(e("settings.schedulesTab.loadRunsFailed")),m(U=>({...U,loading:!1}))}},children:e("settings.schedulesTab.actions.runs")}),o.jsx(ue,{danger:!0,size:"small",onClick:async()=>{try{await Qs.deleteSchedule(R.id),t.success(e("settings.schedulesTab.deleted")),await _()}catch($){console.error("[Schedules] Failed to delete:",$),t.error(e("settings.schedulesTab.deleteFailed"))}},children:e("settings.schedulesTab.actions.delete")})]}),o.jsxs(be,{gap:8,align:"center",wrap:"wrap",children:[o.jsx(kn,{type:"secondary",children:e("settings.schedulesTab.columns.intervalSeconds")}),R.trigger.type==="interval"?I:o.jsx(bt,{title:e("settings.schedulesTab.nonIntervalReadOnly"),children:o.jsx("span",{children:I})})]})]})}}],[x,t,_,e]);return o.jsxs(be,{vertical:!0,gap:16,children:[n,o.jsx(Ce,{title:e("settings.schedulesTab.createTitle"),className:"lotus-settings-card",children:o.jsxs(Pe,{form:S,layout:"vertical",initialValues:{name:e("settings.schedulesTab.defaultName"),trigger_type:"interval",interval_seconds:3600,daily_hour:9,daily_minute:0,weekly_weekdays:["mon"],weekly_hour:9,weekly_minute:0,monthly_days:"1",monthly_hour:9,monthly_minute:0,cron_expr:"",timezone:"",start_at:"",end_at:"",enabled:!1,task_message:"",model:"",auto_execute:!0,misfire_policy:"run_once",overlap_policy:"queue_one",catch_up_window_max_runs:1,catch_up_window_max_lateness_seconds:60},onFinish:async O=>{try{const R=!!O.auto_execute,I=vn(O.task_message),$=vn(O.model);if(R&&!I){t.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:U,errorKey:q}=ff(O);if(!U){t.error(e(q||"settings.schedulesTab.validation.triggerRequired"));return}await Qs.createSchedule({name:String(O.name||"").trim(),trigger:U,timezone:vn(O.timezone),start_at:vn(O.start_at),end_at:vn(O.end_at),misfire_policy:gf(O),overlap_policy:O.overlap_policy,enabled:!!O.enabled,run_config:{system_prompt:vn(O.system_prompt),task_message:I,model:$,workspace_path:vn(O.workspace_path),enhance_prompt:vn(O.enhance_prompt),auto_execute:R}}),t.success(e("settings.schedulesTab.created")),S.resetFields(),await _()}catch(R){console.error("[Schedules] Failed to create schedule:",R),t.error(e("settings.schedulesTab.createFailed"))}},children:[B(T,j),o.jsx(ue,{type:"primary",htmlType:"submit",children:e("settings.schedulesTab.actions.create")})]})}),o.jsx(Ce,{title:e("settings.schedulesTab.listTitle"),className:"lotus-settings-card",extra:o.jsx(ue,{onClick:()=>void _(),loading:s,children:e("settings.schedulesTab.actions.refresh")}),children:o.jsx(or,{rowKey:"id",columns:N,dataSource:a,loading:s,pagination:{pageSize:10},scroll:{x:1500}})}),o.jsx(Xn,{title:e("settings.schedulesTab.scheduleSessionsTitle"),open:l.open,onCancel:()=>c(O=>({...O,open:!1,scheduleId:null})),footer:null,children:l.loading?o.jsx(kn,{type:"secondary",children:e("settings.schedulesTab.loading")}):o.jsx(be,{vertical:!0,gap:8,children:l.sessions.length===0?o.jsx(kn,{type:"secondary",children:e("settings.schedulesTab.noSessionsYet")}):l.sessions.map(O=>o.jsxs(be,{justify:"space-between",align:"center",children:[o.jsxs(be,{vertical:!0,style:{minWidth:0},children:[o.jsx(kn,{strong:!0,ellipsis:!0,children:O.title}),o.jsxs(kn,{type:"secondary",ellipsis:!0,children:[O.id," • ",O.updated_at]})]}),o.jsx(ue,{size:"small",onClick:()=>{qc(O.id,{forceRefreshIndex:!0,forceLoadHistory:!0,subscribeIfRunning:!0,forceSubscribe:!0}),b()},children:e("settings.schedulesTab.actions.open")})]},O.id))})}),o.jsx(Xn,{title:e("settings.schedulesTab.scheduleRunsTitle"),open:u.open,onCancel:()=>m(O=>({...O,open:!1,scheduleId:null})),footer:null,width:960,children:u.loading?o.jsx(kn,{type:"secondary",children:e("settings.schedulesTab.loading")}):u.runs.length===0?o.jsx(kn,{type:"secondary",children:e("settings.schedulesTab.noRunsYet")}):o.jsx(or,{rowKey:"run_id",pagination:{pageSize:8},dataSource:u.runs,columns:[{title:e("settings.schedulesTab.runHistory.columns.status"),key:"status",render:(O,R)=>o.jsx(Ne,{color:IC(R.status),children:R.status})},{title:e("settings.schedulesTab.runHistory.columns.scheduledFor"),dataIndex:"scheduled_for",key:"scheduled_for"},{title:e("settings.schedulesTab.runHistory.columns.startedAt"),key:"started_at",render:(O,R)=>R.started_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.completedAt"),key:"completed_at",render:(O,R)=>R.completed_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.session"),key:"session_id",render:(O,R)=>R.session_id||"-"},{title:e("settings.schedulesTab.runHistory.columns.duration"),key:"execution_duration_ms",render:(O,R)=>R.execution_duration_ms!=null?`${R.execution_duration_ms}ms`:"-"},{title:e("settings.schedulesTab.runHistory.columns.outcome"),key:"outcome_reason",render:(O,R)=>R.outcome_reason||(R.was_catch_up?"catch-up":"-")}]})}),o.jsx(Xn,{title:e("settings.schedulesTab.editTitle"),open:f.open,onCancel:()=>g({open:!1,schedule:null,saving:!1}),okText:e("settings.schedulesTab.actions.save"),confirmLoading:f.saving,onOk:()=>x.submit(),forceRender:!0,children:o.jsx(Pe,{form:x,layout:"vertical",onFinish:async O=>{const R=f.schedule;if(!R)return;const I=!!O.auto_execute,$=vn(O.task_message),U=vn(O.model);if(I&&!$){t.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:q,errorKey:K}=ff(O);if(!q){t.error(e(K||"settings.schedulesTab.validation.triggerRequired"));return}g(P=>({...P,saving:!0}));try{await Qs.patchSchedule(R.id,{name:String(O.name||"").trim()||void 0,enabled:!!O.enabled,trigger:q,timezone:vn(O.timezone),start_at:vn(O.start_at),end_at:vn(O.end_at),misfire_policy:gf(O),overlap_policy:O.overlap_policy,run_config:{system_prompt:vn(O.system_prompt),task_message:$,model:U,workspace_path:vn(O.workspace_path),enhance_prompt:vn(O.enhance_prompt),auto_execute:I}}),t.success(e("settings.schedulesTab.updated")),g({open:!1,schedule:null,saving:!1}),await _()}catch(P){console.error("[Schedules] Failed to patch schedule:",P),t.error(e("settings.schedulesTab.updateFailed")),g(W=>({...W,saving:!1}))}},children:B(w,M)})})]})}const{Text:wa}=He,_a=Jn.getInstance();function HC(){const{t:e}=Ie(),{modal:t,message:n}=sn.useApp(),s=te(S=>S.chats),r=te(S=>S.currentSessionId),a=te(S=>S.refreshChats),i=te(S=>S.loadChats),l=te(S=>S.loadChatHistory),[c,u]=p.useState(!0),[m,f]=p.useState(!1),g=p.useMemo(()=>r?s.find(S=>S.id===r)??null:null,[s,r]),b=async S=>{if(!m){f(!0);try{await S()}finally{f(!1)}}};return o.jsxs(be,{vertical:!0,gap:16,children:[o.jsx(Ce,{size:"small",title:e("settings.sessionsTab.currentSessionTitle"),children:g?o.jsxs(be,{vertical:!0,gap:4,children:[o.jsx(wa,{strong:!0,ellipsis:!0,children:g.title}),o.jsxs(wa,{type:"secondary",ellipsis:!0,children:[e("settings.sessionsTab.id"),": ",g.id," ","•"," ",e("settings.sessionsTab.kind"),": ",g.kind]}),o.jsx(be,{gap:8,wrap:"wrap",style:{marginTop:8},children:o.jsx(ue,{danger:!0,loading:m,onClick:()=>{t.confirm({title:e("settings.sessionsTab.clearMessagesTitle"),content:e("settings.sessionsTab.clearMessagesContent"),okText:e("settings.sessionsTab.clear"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await b(async()=>{await _a.clearSession(g.id),await l(g.id),await a(),n.success(e("settings.sessionsTab.sessionCleared"))})}})},children:e("settings.sessionsTab.clearMessages")})})]}):o.jsx(wa,{type:"secondary",children:e("settings.sessionsTab.noActiveSession")})}),o.jsxs(Ce,{size:"small",title:e("settings.sessionsTab.bulkCleanupTitle"),children:[o.jsxs(be,{align:"center",gap:8,style:{marginBottom:12},children:[o.jsx(wa,{children:e("settings.sessionsTab.keepPinned")}),o.jsx(pn,{checked:c,onChange:u})]}),o.jsxs(be,{gap:8,wrap:"wrap",children:[o.jsx(ue,{danger:!0,loading:m,onClick:()=>{t.confirm({title:e("settings.sessionsTab.deleteAllTitle"),content:e(c?"settings.sessionsTab.deleteAllKeepPinned":"settings.sessionsTab.deleteAllIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await b(async()=>{await _a.cleanupSessions("all",c),await i(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteAll")}),o.jsx(ue,{danger:!0,loading:m,onClick:()=>{t.confirm({title:e("settings.sessionsTab.deleteEmptyTitle"),content:e(c?"settings.sessionsTab.deleteEmptyKeepPinned":"settings.sessionsTab.deleteEmptyIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await b(async()=>{await _a.cleanupSessions("empty",c),await i(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteEmpty")}),o.jsx(ue,{danger:!0,loading:m,onClick:()=>{t.confirm({title:e("settings.sessionsTab.deleteChildrenTitle"),content:e(c?"settings.sessionsTab.deleteChildrenKeepPinned":"settings.sessionsTab.deleteChildrenIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await b(async()=>{await _a.cleanupSessions("children",c),await i(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteChildren")})]})]}),o.jsxs(Ce,{size:"small",title:e("settings.sessionsTab.devResetTitle"),children:[o.jsx(wa,{type:"secondary",children:e("settings.sessionsTab.devResetDescription")}),o.jsx(be,{style:{marginTop:12},children:o.jsx(ue,{danger:!0,type:"primary",loading:m,onClick:()=>{t.confirm({title:e("settings.sessionsTab.devResetConfirmTitle"),content:e("settings.sessionsTab.devResetConfirmContent"),okText:e("settings.sessionsTab.reset"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await b(async()=>{await _a.devResetSessions(),await i(),n.success(e("settings.sessionsTab.devResetDone"))})}})},children:e("settings.sessionsTab.devResetAction")})})]})]})}const{Text:El,Paragraph:KC}=He,VC=({open:e,onCancel:t,onComplete:n,onCopyCode:s,completingAuth:r,copiedUserCode:a,deviceCodeInfo:i,timeRemaining:l,token:c})=>{const{t:u}=Ie();return o.jsx(Xn,{title:u("settings.providerTab.copilotAuthModalTitle"),open:e,onCancel:t,footer:[o.jsx(ue,{onClick:t,children:u("settings.providerTab.cancel")},"cancel"),o.jsx(ue,{type:"primary",onClick:n,loading:r,children:u("settings.providerTab.completedAuthorization")},"complete")],children:i&&o.jsxs(he,{direction:"vertical",size:"large",style:{width:"100%"},children:[o.jsx(Ut,{message:u("settings.providerTab.browserOpened"),description:o.jsxs("ol",{children:[o.jsx("li",{children:u("settings.providerTab.authStep1")}),o.jsx("li",{children:u("settings.providerTab.authStep2")}),o.jsx("li",{children:u("settings.providerTab.authStep3")})]}),type:"info"}),o.jsx(Ce,{size:"small",className:"lotus-settings-card",children:o.jsxs(he,{direction:"vertical",style:{width:"100%"},children:[o.jsx(El,{type:"secondary",children:u("settings.providerTab.visitUrl")}),o.jsx(he,{children:o.jsx(El,{copyable:{text:i.verification_uri},children:i.verification_uri})})]})}),o.jsx(Ce,{style:{textAlign:"center",background:c.colorFillTertiary,borderColor:c.colorBorderSecondary},children:o.jsxs(he,{direction:"vertical",style:{width:"100%"},children:[o.jsx(El,{type:"secondary",children:u("settings.providerTab.enterCode")}),o.jsxs(he,{children:[o.jsx(El,{style:{color:c.colorText,fontSize:"32px",fontFamily:"monospace",fontWeight:"bold",letterSpacing:"4px"},children:i.user_code}),o.jsx(ue,{icon:a?o.jsx(ar,{}):o.jsx(xs,{}),onClick:s,type:a?"default":"primary",children:u(a?"settings.providerTab.copied":"settings.providerTab.copyCode")})]}),o.jsx("div",{style:{marginTop:8},children:o.jsxs(Ne,{color:l<60?"error":l<180?"warning":"success",children:[o.jsx(As,{style:{marginRight:4}}),"Expires in ",Math.floor(l/60),":",(l%60).toString().padStart(2,"0")]})})]})}),o.jsx(KC,{type:"secondary",children:u("settings.providerTab.afterContinueHint")})]})})},Wd={copilot:"GitHub Copilot",openai:"OpenAI",anthropic:"Anthropic",gemini:"Google Gemini",bodhi:"Bodhi"},YC=[{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"}],XC=[{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"}],GC=[{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"}],JC=[{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4o-mini",label:"GPT-4o Mini"}];function Sx({value:e,onChange:t,disabled:n}){const s=Mt(l=>l.catalog);p.useEffect(()=>{s||Mt.getState().loadCatalog()},[s]);const r=p.useMemo(()=>{if(!(s!=null&&s.models))return[];const l={};for(const m of s.models){const f=m.reference.provider;l[f]||(l[f]={display:m.provider_display_name,models:[]}),l[f].models.push(m)}const c=[];return Object.keys(l).forEach((m,f)=>{const g=l[m];f>0&&c.push({type:"divider"}),c.push({type:"group",label:g.display,children:g.models.map(b=>({key:`${b.reference.provider}/${b.reference.model}`,label:o.jsxs(he,{size:4,children:[o.jsx("span",{children:b.display_name}),b.capabilities.supports_vision&&o.jsx(Ne,{color:"blue",style:{fontSize:10,lineHeight:"16px",padding:"0 3px"},children:"Vision"})]})}))})}),c},[s]),a=e?`${e.provider}/${e.model}`:void 0,i=p.useCallback(l=>{const[c,...u]=l.key.split("/"),m=u.join("/");c&&m&&t({provider:c,model:m})},[t]);return o.jsx(he,{size:4,"data-tour-id":"model-picker",children:o.jsx(lo,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:a?[a]:[],items:r,style:{maxHeight:"50vh",overflowY:"auto"},onClick:i},disabled:n,children:o.jsx(ue,{type:"text",size:"small",disabled:n,style:{minWidth:146,padding:"0 12px",height:36,borderRadius:18},title:e?`${e.provider}/${e.model}`:"Select model",children:o.jsxs(he,{size:4,children:[o.jsx("span",{style:{maxWidth:150,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13},children:e?`${e.provider}/${e.model}`:"Select model"}),o.jsx(Gn,{style:{fontSize:10}})]})})})})}const{Password:yf}=Qe,{Text:rs,Paragraph:qd}=He,Rl=["openai","anthropic","gemini","copilot","bodhi"],Al=()=>null,QC=e=>{var n,s;if(!e||typeof e!="object")return!1;const t=e;return!!((n=t.provider)!=null&&n.trim()&&((s=t.model)!=null&&s.trim()))},bf=e=>o.jsxs(he,{direction:"vertical",size:4,children:[o.jsxs(rs,{type:"secondary",children:[e("settings.providerTab.responsesOnlyHelp1")," ",o.jsx(rs,{code:!0,children:"/responses"}),"."]}),o.jsx(rs,{type:"secondary",children:e("settings.providerTab.responsesOnlyHelp2")})]}),ZC=()=>{const{t:e}=Ie(),{token:t}=Ge.useToken(),{message:n}=sn.useApp(),[s]=Pe.useForm(),[r,a]=p.useState(!1),[i,l]=p.useState(!1),[c,u]=p.useState("copilot"),[m,f]=p.useState(!1),[g,b]=p.useState(null),[S,x]=p.useState(!1),[T,j]=p.useState(!1),[w,M]=p.useState(null),[_,C]=p.useState(!1),[L,A]=p.useState(!1),[B,N]=p.useState(0),[O,R]=p.useState(!1),[I,$]=p.useState([]),[U,q]=p.useState(!1),[K,P]=p.useState("idle"),[W,se]=p.useState(null);p.useEffect(()=>{if(K!=="success")return;const me=setTimeout(()=>{P("idle"),se(null)},2e3);return()=>clearTimeout(me)},[K]),p.useEffect(()=>{if(!_||!w){N(0);return}N(w.expires_in);const me=setInterval(()=>{N(H=>H<=1?(clearInterval(me),0):H-1)},1e3);return()=>clearInterval(me)},[_,w]);const V=p.useCallback(async()=>{var me;try{a(!0);const H=await Vn.getProviderConfig();let ye=H.defaults;if(!((me=ye==null?void 0:ye.chat)!=null&&me.model)&&H.provider&&H.providers){const Ue=H.provider,Re=H.providers[Ue],ut=Re==null?void 0:Re.model;ut&&(ye={chat:{provider:Ue,model:ut}})}const xe={provider:H.provider,defaults:ye,providers:H.providers||{},features:H.features};Jt("[Provider]","Loaded provider config:",xe);const _e={...xe.providers||{}};Rl.forEach(Ue=>{const Re=_e[Ue];Re&&Re.request_overrides&&typeof Re.request_overrides=="object"&&(Re.request_overrides_json=JSON.stringify(Re.request_overrides,null,2))}),u(xe.provider),s.setFieldsValue({...xe,providers:_e,defaults:xe.defaults}),f(!0)}catch(H){n.error(e("settings.providerTab.loadConfigFailed")),console.error("Failed to load provider config:",H)}finally{a(!1)}},[s,e]),ie=p.useCallback(async()=>{try{const me=await Vn.getEnvVars();$(me.entries||[])}catch(me){console.warn("Failed to load env vars for provider overrides:",me)}},[]),re=p.useCallback(async()=>{try{x(!0);const me=await Vn.getCopilotAuthStatus();b(me)}catch(me){console.error("Failed to check Copilot auth status:",me),b({authenticated:!1,message:e("settings.providerTab.checkStatusFailed")})}finally{x(!1)}},[e]);p.useEffect(()=>{V(),ie(),Mt.getState().loadCatalog(),re()},[V,ie,re]);const fe=async()=>{try{j(!0);const me=await Vn.startCopilotAuth();M(me),C(!0)}catch(me){n.error(e("settings.providerTab.startCopilotAuthFailed")),console.error("Failed to start Copilot authentication:",me)}finally{j(!1)}},Se=async()=>{if(w)try{A(!0),await Vn.completeCopilotAuth({device_code:w.device_code,interval:w.interval||5,expires_in:w.expires_in}),n.success(e("settings.providerTab.copilotAuthSuccess")),C(!1),M(null),await re()}catch(me){n.error(e("settings.providerTab.completeAuthFailed")),console.error("Authentication completion failed:",me)}finally{A(!1)}},ke=async()=>{if(w)try{await vs(w.user_code),R(!0),n.success(e("settings.providerTab.userCodeCopied")),setTimeout(()=>R(!1),2e3)}catch{n.error(`${e("settings.providerTab.copyCodeFailedPrefix")} ${w.user_code}`)}},Be=async()=>{try{j(!0),await Vn.logoutCopilot(),n.success(e("settings.providerTab.logoutSuccess")),await re()}catch(me){n.error(e("settings.providerTab.logoutFailed")),console.error("Failed to logout:",me)}finally{j(!1)}},tt=p.useCallback(async()=>{q(!0);try{const me=await Vn.fetchCatalogModels();await Mt.getState().loadCatalog();const H=me.fetched.filter(xe=>xe.models&&xe.models.length>0).length;me.fetched.filter(xe=>xe.error).length>0?n.warning(e("settings.providerTab.fetchModelsPartialSuccess",{success:H,total:me.fetched.length})):n.success(e("settings.providerTab.fetchModelsSuccess",{count:H}))}catch{n.error(e("settings.providerTab.fetchModelsFailed"))}finally{q(!1)}},[e]),ft=me=>Q_(me)||me instanceof Error?me.message:e("settings.providerTab.unknownError"),Ht=me=>{s.setFields([{name:["provider"],errors:[]},{name:["providers",me,"api_key"],errors:[]},{name:["defaults","chat"],errors:[]}])},Oe=me=>{const H=me.trim();return H?H.includes(".")?H.split(".").filter(Boolean):H==="provider"?["provider"]:H==="provider/providers"?["provider"]:null:null},zt=(me,H)=>{if(!me.length)return;const ye=me.map(xe=>{const _e=Oe(xe.path);return _e?{name:_e,errors:[xe.message]}:xe.message.toLowerCase().includes("api key")?{name:["providers",H,"api_key"],errors:[xe.message]}:{name:["provider"],errors:[xe.message]}}).filter((xe,_e,Ue)=>Ue.findIndex(Re=>JSON.stringify(Re.name)===JSON.stringify(xe.name))===_e);ye.length&&s.setFields(ye)},Ye=async me=>{var ye;const H=me.provider||c;Ht(H);try{const _e=await Is.getInstance().validateBambooConfigPatch({provider:me.provider,providers:me.providers||{},defaults:me.defaults});if(_e.valid)return{valid:!0};const Ue=((ye=_e.errors)==null?void 0:ye.provider)||[];zt(Ue,H);const Re=Ue[0];return{valid:!1,message:(Re==null?void 0:Re.message)||e("settings.providerTab.invalidConfig")}}catch(xe){return console.warn("Config validation failed, falling back to save:",xe),{valid:!0}}},we=async(me,H)=>{var ye,xe;try{a(!0);const _e={provider:me.provider,defaults:me.defaults,providers:{...me.providers||{}},features:me.features},Ue=(ye=_e.defaults)==null?void 0:ye.chat;if(!QC(Ue)){const Bt=e("settings.providerTab.selectModelRequired");if(s.setFields([{name:["defaults","chat"],errors:[Bt]}]),(H==null?void 0:H.showMessage)!==!1&&n.error(Bt),H!=null&&H.throwOnError)throw new Error(Bt);return}const Re=_e.providers;for(const Bt of Rl){const Kt=Re[Bt];if(!Kt)continue;const qe=Kt.request_overrides_json;if(typeof qe!="string")continue;const rn=qe.trim();if(!rn)delete Kt.request_overrides;else try{Kt.request_overrides=JSON.parse(rn)}catch(cn){const on=`Invalid request_overrides JSON for ${Bt}: ${cn.message}`;if(s.setFields([{name:["providers",Bt,"request_overrides_json"],errors:[on]}]),(H==null?void 0:H.showMessage)!==!1&&n.error(on),H!=null&&H.throwOnError)throw cn;return}delete Kt.request_overrides_json}const ut={..._e.providers||{}},ot=_e.provider,gt=(xe=_e.defaults)==null?void 0:xe.chat;if(gt!=null&>.model&&ot){const Bt=ut[ot]||{};ut[ot]={...Bt,model:gt.model}}const _t={provider:_e.provider,defaults:_e.defaults,providers:ut,features:_e.features},vt=await Ye(_e);if(!vt.valid){const Bt=vt.message||e("settings.providerTab.invalidConfig");if((H==null?void 0:H.showMessage)!==!1&&n.error(`${e("settings.providerTab.invalidConfigPrefix")}: ${Bt}`),H!=null&&H.throwOnError)throw new Error(Bt);return}Jt("[Provider]","Saving provider config:",_t),await Vn.saveProviderConfig(_t),(H==null?void 0:H.showMessage)!==!1&&n.success(e("settings.providerTab.saveConfigSuccess"))}catch(_e){const Ue=ft(_e);if((H==null?void 0:H.showMessage)!==!1&&n.error(Ue?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${Ue}`:e("settings.providerTab.saveConfigFailed")),console.error("Failed to save configuration:",_e),H!=null&&H.throwOnError)throw _e}finally{a(!1)}},Ke=async me=>{var H,ye,xe,_e,Ue;try{l(!0);const{useProviderStore:Re}=await Bn(async()=>{const{useProviderStore:on}=await Promise.resolve().then(()=>n0);return{useProviderStore:on}},void 0,import.meta.url),{useAppStore:ut}=await Bn(async()=>{const{useAppStore:on}=await Promise.resolve().then(()=>yk);return{useAppStore:on}},void 0,import.meta.url),ot=(H=Re.getState().providerConfig.defaults)==null?void 0:H.chat;await Re.getState().loadProviderConfig();const gt=(ye=Re.getState().providerConfig.defaults)==null?void 0:ye.chat;Re.getState().setSelectedModelRef(null);const _t=ut.getState().currentSessionId,vt=_t&&ut.getState().chats.find(on=>on.id===_t)||null,Bt=ot?`${ot.provider}/${ot.model}`:null,Kt=gt?`${gt.provider}/${gt.model}`:null,qe=(xe=vt==null?void 0:vt.config)!=null&&xe.model_ref?`${vt.config.model_ref.provider}/${vt.config.model_ref.model}`:null,rn=((Ue=(_e=vt==null?void 0:vt.config)==null?void 0:_e.model)==null?void 0:Ue.trim())||null;!!(_t&&(vt!=null&&vt.config)&>&&Kt!==Bt&&(!qe||qe===Bt)&&(!rn||rn===(ot==null?void 0:ot.model)))&&_t&&(vt!=null&&vt.config)&>&&ut.getState().updateSession(_t,{config:{...vt.config,model:gt.model,model_ref:gt}}),(me==null?void 0:me.showMessage)!==!1&&n.success(e("settings.providerTab.applyConfigSuccess"))}catch(Re){const ut=ft(Re);if((me==null?void 0:me.showMessage)!==!1&&n.error(ut?`${e("settings.providerTab.applyConfigErrorPrefix")}: ${ut}`:e("settings.providerTab.applyConfigFailed")),console.error("Failed to apply configuration:",Re),me!=null&&me.throwOnError)throw Re}finally{l(!1)}},st=async me=>{try{const H=s.getFieldsValue(!0);await we(H,{throwOnError:!0}),await Ke({throwOnError:!0})}catch{}},Dt=async(me,H)=>{if(!(me==="chat"&&!H)&&K!=="saving"){P("saving"),se(null);try{const ye=s.getFieldsValue(!0),xe=ye.defaults;if(!(xe!=null&&xe.chat))throw new Error(e("settings.providerTab.selectModelRequired"));ye.defaults={...xe,[me]:H},await we(ye,{showMessage:!1,throwOnError:!0}),await Ke({showMessage:!1,throwOnError:!0}),P("success"),n.success(e("settings.providerTab.modelUpdated"))}catch(ye){const xe=ft(ye);P("error"),se(xe),n.error(xe?`${e("settings.providerTab.updateModelErrorPrefix")}: ${xe}`:e("settings.providerTab.updateModelFailed"))}}},F=p.useCallback(me=>{const H=s.getFieldValue(["providers",me]);return H?me==="copilot"?(g==null?void 0:g.authenticated)??!1:!!H.api_key:!1},[s,g]),ce=()=>{const me=H=>{const ye=s.getFieldValue(["defaults",H]);return o.jsx(Sx,{value:ye,disabled:K==="saving",onChange:xe=>{s.setFieldValue(["defaults",H],xe),Dt(H,xe)}})};return o.jsxs(Ce,{size:"small",title:e("settings.providerTab.modelPreferences","模型偏好"),style:{marginBottom:16},children:[o.jsx(Pe.Item,{name:["defaults","chat"],noStyle:!0,preserve:!0,children:o.jsx(Al,{})}),o.jsx(Pe.Item,{name:["defaults","fast"],noStyle:!0,preserve:!0,children:o.jsx(Al,{})}),o.jsx(Pe.Item,{name:["defaults","sub_session"],noStyle:!0,preserve:!0,children:o.jsx(Al,{})}),o.jsx(Pe.Item,{name:["defaults","vision"],noStyle:!0,preserve:!0,children:o.jsx(Al,{})}),o.jsxs(he,{direction:"vertical",size:16,style:{width:"100%"},children:[o.jsxs("div",{children:[o.jsx(rs,{strong:!0,children:e("settings.providerTab.defaultModel")}),o.jsx("div",{style:{marginTop:8},children:me("chat")})]}),o.jsxs("div",{children:[o.jsx(rs,{strong:!0,children:e("settings.providerTab.fastModel")}),o.jsx("div",{style:{marginTop:8},children:me("fast")}),o.jsx(rs,{type:"secondary",children:e("settings.providerTab.fastModelHelp")})]}),o.jsxs("div",{children:[o.jsx(rs,{strong:!0,children:e("settings.providerTab.subSessionModel","Sub Session Model (Optional)")}),o.jsx("div",{style:{marginTop:8},children:me("sub_session")}),o.jsx(rs,{type:"secondary",children:e("settings.providerTab.subSessionModelHelp","Default model for new Sub Sessions. Uses Fast Model when not set.")})]}),o.jsxs("div",{children:[o.jsx(rs,{strong:!0,children:e("settings.providerTab.visionModel")}),o.jsx("div",{style:{marginTop:8},children:me("vision")}),o.jsx(rs,{type:"secondary",children:e("settings.providerTab.visionModelHelp")})]})]})]})},ge=me=>{const H=I.map(xe=>xe.name);return o.jsx(Pe.Item,{name:["providers",me,"request_overrides_json"],label:"Advanced Request Overrides (JSON)",extra:o.jsxs(he,{direction:"vertical",size:4,children:[o.jsx(rs,{type:"secondary",children:"Customize provider request headers/body patch rules."}),o.jsxs(rs,{type:"secondary",children:["Env var injection:"," ",o.jsx(rs,{code:!0,children:'{ "type": "env_ref", "name": "YOUR_ENV_NAME" }'})]}),H.length>0&&o.jsx(he,{wrap:!0,size:[6,6],children:H.map(xe=>o.jsx(Ne,{children:xe},xe))})]}),children:o.jsx(Qe.TextArea,{autoSize:{minRows:8,maxRows:20},placeholder:`{
|
|
109
|
+
"common": {
|
|
110
|
+
"headers": {
|
|
111
|
+
"x-request-id": { "type": "generated", "generator": "uuid" },
|
|
112
|
+
"x-tenant": { "type": "env_ref", "name": "TENANT_ID" }
|
|
113
|
+
}
|
|
114
|
+
},
|
|
115
|
+
"rules": [
|
|
116
|
+
{
|
|
117
|
+
"model_pattern": "gpt-5*",
|
|
118
|
+
"scope": {
|
|
119
|
+
"body_patch": [
|
|
120
|
+
{ "path": "metadata.trace_id", "op": "set", "value": { "type": "generated", "generator": "uuid" } }
|
|
121
|
+
]
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
]
|
|
125
|
+
}`,style:{fontFamily:"SFMono-Regular, Menlo, Monaco, Consolas, monospace"}})})},De=me=>{switch(me){case"openai":return o.jsxs(o.Fragment,{children:[o.jsx(Pe.Item,{name:["providers","openai","api_key"],label:e("settings.providerTab.openaiApiKey"),rules:[{required:!0,message:e("settings.providerTab.openaiApiKeyRequired")}],children:o.jsx(Qe.Password,{"data-testid":"api-key-input",placeholder:"sk-...",prefix:o.jsx(kl,{})})}),o.jsx(Pe.Item,{name:["providers","openai","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.openaiBaseUrlHelp"),children:o.jsx(Qe,{placeholder:"https://api.openai.com/v1"})}),o.jsx(Pe.Item,{name:["providers","openai","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:bf(e),children:o.jsx(St,{mode:"tags",placeholder:'e.g. "gpt-5.3-codex", "gpt-5*"',tokenSeparators:[","," ",`
|
|
126
|
+
`," "]})}),o.jsx(zn,{dashed:!0}),ge("openai")]});case"anthropic":return o.jsxs(o.Fragment,{children:[o.jsx(Pe.Item,{name:["providers","anthropic","api_key"],label:e("settings.providerTab.anthropicApiKey"),rules:[{required:!0,message:e("settings.providerTab.anthropicApiKeyRequired")}],children:o.jsx(yf,{placeholder:"sk-ant-...",prefix:o.jsx(kl,{})})}),o.jsx(Pe.Item,{name:["providers","anthropic","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.anthropicBaseUrlHelp"),children:o.jsx(Qe,{placeholder:"https://api.anthropic.com/v1"})}),o.jsx(Pe.Item,{name:["providers","anthropic","max_tokens"],label:e("settings.providerTab.maxTokensOptional"),extra:e("settings.providerTab.maxTokensHelp"),children:o.jsx(Qe,{type:"number",placeholder:"4096",min:1,max:1e5})}),o.jsx(zn,{dashed:!0}),ge("anthropic")]});case"gemini":return o.jsxs(o.Fragment,{children:[o.jsx(Pe.Item,{name:["providers","gemini","api_key"],label:e("settings.providerTab.geminiApiKey"),rules:[{required:!0,message:e("settings.providerTab.geminiApiKeyRequired")}],children:o.jsx(yf,{placeholder:"AIza...",prefix:o.jsx(kl,{})})}),o.jsx(Pe.Item,{name:["providers","gemini","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.geminiBaseUrlHelp"),children:o.jsx(Qe,{placeholder:"https://generativelanguage.googleapis.com/v1beta"})}),o.jsx(zn,{dashed:!0}),ge("gemini")]});case"copilot":return o.jsxs(o.Fragment,{children:[o.jsxs(Ce,{size:"small",style:{marginBottom:16},title:e("settings.providerTab.authStatusTitle"),extra:S?o.jsx(Rs,{size:"small"}):g!=null&&g.authenticated?o.jsx(Ne,{icon:o.jsx(ar,{}),color:"success",children:e("settings.providerTab.authenticated")}):o.jsx(Ne,{icon:o.jsx(pc,{}),color:"error",children:e("settings.providerTab.notAuthenticated")}),children:[(g==null?void 0:g.message)&&o.jsx(qd,{type:"secondary",style:{marginBottom:16},children:g.message}),o.jsxs(he,{children:[g!=null&&g.authenticated?o.jsx(ue,{danger:!0,icon:o.jsx(Uw,{}),onClick:Be,loading:T,children:e("settings.providerTab.logoutCopilot")}):o.jsx(ue,{type:"primary",icon:o.jsx(Hw,{}),onClick:fe,loading:T,children:e("settings.providerTab.authenticateCopilot")}),o.jsx(ue,{onClick:re,loading:S,children:e("settings.providerTab.refreshStatus")})]})]}),o.jsx(Pe.Item,{name:["providers","copilot","headless_auth"],label:e("settings.providerTab.headlessAuth"),valuePropName:"checked",extra:e("settings.providerTab.headlessAuthHelp"),children:o.jsx(pn,{})}),o.jsx(Pe.Item,{name:["providers","copilot","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:bf(e),children:o.jsx(St,{mode:"tags",placeholder:'e.g. "gpt-5.3-codex", "gpt-5*"',tokenSeparators:[","," ",`
|
|
127
|
+
`," "]})}),o.jsx(zn,{dashed:!0}),ge("copilot"),o.jsxs(qd,{type:"secondary",children:[e("settings.providerTab.copilotUsageTitle"),o.jsxs("ul",{style:{marginTop:8,marginBottom:0},children:[o.jsx("li",{children:e("settings.providerTab.copilotUsageStep1")}),o.jsx("li",{children:e("settings.providerTab.copilotUsageStep2")}),o.jsx("li",{children:e("settings.providerTab.copilotUsageStep3")})]})]})]});case"bodhi":return o.jsxs(o.Fragment,{children:[o.jsx(Pe.Item,{name:["providers","bodhi","api_key"],label:"Bodhi API Key",rules:[{required:!0,message:"API key is required"}],children:o.jsx(Qe.Password,{"data-testid":"bodhi-api-key-input",placeholder:"bhi_sk_...",prefix:o.jsx(kl,{})})}),o.jsx(Pe.Item,{name:["providers","bodhi","base_url"],label:"Base URL",extra:"Your Bodhi Server endpoint address",children:o.jsx(Qe,{placeholder:"http://localhost:8080"})}),o.jsx(Pe.Item,{name:["providers","bodhi","target_provider"],label:"Target Provider",extra:"Which upstream provider to route through Bodhi",children:o.jsxs(St,{placeholder:"openai",allowClear:!0,children:[o.jsx(St.Option,{value:"openai",children:"OpenAI"}),o.jsx(St.Option,{value:"anthropic",children:"Anthropic"}),o.jsx(St.Option,{value:"gemini",children:"Gemini"})]})}),o.jsx(Pe.Item,{name:["providers","bodhi","reasoning_effort"],label:"Reasoning Effort (optional)",children:o.jsxs(St,{placeholder:"Default",allowClear:!0,children:[o.jsx(St.Option,{value:"low",children:"Low"}),o.jsx(St.Option,{value:"medium",children:"Medium"}),o.jsx(St.Option,{value:"high",children:"High"}),o.jsx(St.Option,{value:"xhigh",children:"Extra High"}),o.jsx(St.Option,{value:"max",children:"Max"})]})}),o.jsx(zn,{dashed:!0}),ge("bodhi")]});default:return null}},Le=me=>{const H=F(me),ye=Wd[me];return o.jsxs(he,{size:"small",children:[o.jsx("span",{style:{fontWeight:500},children:ye}),H?o.jsx(Ne,{color:"success",style:{fontSize:11},children:e("settings.providerTab.authenticated")}):o.jsx(Ne,{color:"default",style:{fontSize:11},children:e("settings.providerTab.providerNotConfigured")})]})};return o.jsxs(Ce,{title:e("settings.providerTab.title"),loading:r&&!m,className:"lotus-settings-card",children:[o.jsx(qd,{type:"secondary",children:e("settings.providerTab.description")}),o.jsx(zn,{}),o.jsxs(Pe,{form:s,layout:"vertical",onFinish:st,disabled:r&&!m,children:[o.jsx(Pe.Item,{name:"provider",label:e("settings.providerTab.activeProvider"),rules:[{required:!0,message:e("settings.providerTab.selectProviderRequired")}],children:o.jsx(St,{"data-testid":"provider-select",size:"large",children:Object.keys(Wd).map(me=>o.jsx(St.Option,{value:me,children:Wd[me]},me))})}),o.jsx(zn,{}),o.jsxs("div",{style:{marginBottom:16},children:[o.jsx(ue,{icon:o.jsx(lr,{}),onClick:tt,loading:U,children:e(U?"settings.providerTab.fetchingAllModels":"settings.providerTab.fetchAllModels")}),K==="saving"&&o.jsx(Rs,{size:"small",style:{marginLeft:8}}),K==="success"&&o.jsx(ar,{style:{color:"var(--lotus-chart-secondary)",marginLeft:8}}),K==="error"&&o.jsx(bt,{title:W,children:o.jsx(pc,{style:{color:"var(--lotus-chart-danger)",marginLeft:8}})})]}),ce(),o.jsx(ir,{defaultActiveKey:Rl.filter(me=>F(me)),ghost:!0,style:{marginBottom:16},items:Rl.map(me=>({key:me,label:Le(me),children:De(me)}))}),o.jsx(zn,{}),o.jsx(he,{size:"middle",children:o.jsx(ue,{"data-testid":"save-api-settings",type:"primary",htmlType:"submit",icon:o.jsx(zc,{}),loading:r||i,size:"large",children:e("settings.providerTab.saveAndApply")})})]}),o.jsx(VC,{open:_,onCancel:()=>C(!1),onComplete:Se,onCopyCode:ke,completingAuth:L,copiedUserCode:O,deviceCodeInfo:w,timeRemaining:B,token:t})]})},{Text:xf}=He,eM=({skill:e,disabled:t=!1,busy:n=!1,onToggleDisabled:s})=>{const{t:r}=Ie(),{token:a}=Ge.useToken();return o.jsx(Ce,{title:o.jsxs(he,{size:a.marginXS,wrap:!0,style:{width:"100%",justifyContent:"space-between"},children:[o.jsxs(he,{size:a.marginXS,wrap:!0,children:[o.jsx("span",{children:e.name}),t&&o.jsx(Ne,{color:"default",children:r("components.skillManager.disabledTag")}),e.license&&o.jsxs(Ne,{color:"processing",children:["License: ",e.license]})]}),s&&o.jsx(pn,{checked:!t,loading:n,onChange:i=>s(e.id,!i),checkedChildren:r("components.skillManager.switchEnabled"),unCheckedChildren:r("components.skillManager.switchDisabled")})]}),styles:{body:{padding:a.paddingMD}},style:{opacity:t?.72:1},children:o.jsxs(he,{direction:"vertical",size:a.marginXS,style:{width:"100%"},children:[o.jsx(xf,{type:"secondary",children:e.description}),e.compatibility&&o.jsxs(xf,{type:"secondary",children:["Compatibility: ",e.compatibility]}),e.tool_refs.length>0&&o.jsx(he,{size:a.marginXXS,wrap:!0,children:e.tool_refs.map(i=>o.jsx(Ne,{style:{background:a.colorFillSecondary,borderColor:a.colorBorderSecondary,color:a.colorText},children:i},i))})]})})},tM=3e4,nM=()=>{const{t:e}=Ie(),{message:t}=sn.useApp(),n=Ms(A=>A.config),s=Ms(A=>A.loadConfig),r=Ms(A=>A.saveConfig),[a,i]=p.useState([]),[l,c]=p.useState(!1),[u,m]=p.useState(null),[f,g]=p.useState(null),[b,S]=p.useState(""),[x,T]=p.useState(new Date),j=p.useMemo(()=>{var A;return new Set((((A=n==null?void 0:n.skills)==null?void 0:A.disabled)??[]).map(B=>B.trim()).filter(Boolean))},[n]),w=p.useCallback(async(A=!0)=>{c(!0),m(null);try{const[B]=await Promise.all([Ou.listSkills({includeDisabled:!0},A),s({force:A})]);i(B.skills),T(new Date)}catch(B){const N=B instanceof Error?B.message:e("components.skillManager.loadFailed");m(N)}finally{c(!1)}},[s,e]);p.useEffect(()=>{w(!0);const A=setInterval(()=>{w(!0)},tM);return()=>clearInterval(A)},[w]),p.useEffect(()=>{const A=()=>{w(!0)};return window.addEventListener("focus",A),()=>window.removeEventListener("focus",A)},[w]);const M=p.useCallback(async()=>{await w(!0),t.success(e("components.skillManager.skillsRefreshed"))},[w,e]);p.useEffect(()=>{u&&(t.error(u),m(null))},[u]);const _=p.useCallback(async(A,B)=>{var N;g(A);try{const O=await s({force:!0}),R=((N=O==null?void 0:O.skills)==null?void 0:N.disabled)??[],I=Array.from(new Set((B?[...R,A]:R.filter($=>$!==A)).map($=>$.trim()).filter(Boolean))).sort();await r({...O??{},skills:{...(O==null?void 0:O.skills)??{},disabled:I}}),t.success(e("components.skillManager.skillStateSaved"))}catch(O){t.error(O instanceof Error?O.message:e("components.skillManager.saveFailed"))}finally{g(null)}},[s,r,e]),C=a.filter(A=>{const B=b.trim().toLowerCase();return!(B&&![A.name,A.description,A.license??"",A.compatibility??"",...A.tool_refs].join(" ").toLowerCase().includes(B))}),L=()=>{const B=new Date().getTime()-x.getTime(),N=Math.floor(B/1e3);if(N<5)return e("components.skillManager.justNow");if(N<60)return e("components.skillManager.secondsAgo",{count:N});const O=Math.floor(N/60);return O<60?e("components.skillManager.minutesAgo",{count:O}):x.toLocaleTimeString()};return o.jsx("div",{style:{padding:"24px"},children:o.jsxs(Ce,{className:"lotus-settings-card",title:o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[o.jsx("span",{children:e("components.skillManager.title")}),o.jsx(ue,{icon:o.jsx(lr,{spin:l}),onClick:M,loading:l,size:"small",children:e("components.skillManager.refresh")}),o.jsx("span",{className:"lotus-settings-note",style:{fontSize:"12px",marginLeft:"auto"},children:e("components.skillManager.lastUpdated",{value:L()})})]}),children:[o.jsx("div",{className:"lotus-settings-note",style:{marginBottom:"16px"},children:e("components.skillManager.readOnlyHint")}),o.jsx("div",{className:"lotus-settings-note",style:{marginBottom:"16px"},children:e("components.skillManager.disabledHint")}),o.jsx(ps,{style:{marginBottom:"24px"},children:o.jsx(Qe,{placeholder:e("components.skillManager.searchPlaceholder"),prefix:o.jsx($i,{}),value:b,onChange:A=>S(A.target.value),allowClear:!0})}),o.jsx(Rs,{spinning:l,children:C.length===0?o.jsx(Mn,{description:e(b?"components.skillManager.noMatch":"components.skillManager.noSkillsFound")}):o.jsx(Qt,{grid:{gutter:16,xs:1,sm:2,md:3,lg:3,xl:4},dataSource:C,renderItem:A=>o.jsx(Qt.Item,{children:o.jsx(eM,{skill:A,disabled:j.has(A.id),busy:f===A.id,onToggleDisabled:_})})})})]})})},{Title:sM,Text:Ud,Paragraph:rM}=He,vf="model_limits",Xu="modelLimitsConfigs",Sf="defaultBudgetStrategy",hs=1e3;function wf(e){return[{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5.4-thinking",max_context_tokens:1e6,max_output_tokens:128e3,safety_margin:hs,note:e("settings.modelLimits.defaults.gpt54")},{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5.3-codex",max_context_tokens:4e5,max_output_tokens:128e3,safety_margin:hs,note:e("settings.modelLimits.defaults.gpt53Codex")},{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5.2-pro",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:hs,note:e("settings.modelLimits.defaults.gpt52Pro")},{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5-mini",max_context_tokens:4e5,max_output_tokens:128e3,safety_margin:hs,note:e("settings.modelLimits.defaults.gpt5Mini")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4.1",max_context_tokens:128e3,max_output_tokens:16384,safety_margin:hs,note:e("settings.modelLimits.defaults.gpt41")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4o",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:hs,note:e("settings.modelLimits.defaults.gpt4o")},{vendor:"Google",model_pattern:"gemini-2.5-pro",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:hs,note:e("settings.modelLimits.defaults.gemini25Pro")},{vendor:"Moonshot",model_pattern:"kimi-k2.5",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:hs,note:e("settings.modelLimits.defaults.kimiK25")},{vendor:"Moonshot",model_pattern:"kimi-for-coding",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:hs,note:e("settings.modelLimits.defaults.kimiCoding")},{vendor:"Zhipu",model_pattern:"glm-5",max_context_tokens:2e5,max_output_tokens:128e3,safety_margin:hs,note:e("settings.modelLimits.defaults.glm5")}]}function oM(e){return Array.isArray(e)?eh(e):[]}function _f(e,t){if(typeof e!="number"||!Number.isFinite(e))return t;const n=Math.floor(e);return n>0?n:t}function aM(e,t){if(typeof e!="number"||!Number.isFinite(e))return t;const n=Math.floor(e);return n>=0?n:t}function iM(e){if(!e||typeof e!="object")return null;const t=e,n=t.model_pattern??t.model;if(typeof n!="string"||!n.trim())return null;const s=_f(t.max_context_tokens??t.maxContextTokens,128e3),r=_f(t.max_output_tokens??t.maxOutputTokens,Math.min(4096,Math.floor(s/4))),a=aM(t.safety_margin??t.safetyMargin,hs);return{vendor:typeof t.vendor=="string"&&t.vendor.trim()?t.vendor.trim():"",model_pattern:n.trim(),max_context_tokens:s,max_output_tokens:r,safety_margin:a,note:typeof t.note=="string"?t.note:""}}function eh(e){return Array.isArray(e)?e.map(t=>iM(t)).filter(t=>!!t):[]}function lM(){const e=localStorage.getItem(Xu);if(!e)return[];try{const t=JSON.parse(e);return eh(t)}catch{return[]}}function cM(e){const t=Object.prototype.hasOwnProperty.call(e,vf);return t?{hasModelLimitsKey:t,modelLimits:eh(e[vf])}:{hasModelLimitsKey:!1,modelLimits:[]}}function dM(e,t){if(e.length===0)return t("settings.modelLimits.validation.atLeastOneRow");const n=new Set;for(const s of e){const r=s.model_pattern.trim();if(!r)return t("settings.modelLimits.validation.modelPatternEmpty");const a=r.toLowerCase();if(n.has(a))return t("settings.modelLimits.validation.duplicateModelPattern",{pattern:r});if(n.add(a),s.max_context_tokens<1e3)return t("settings.modelLimits.validation.contextWindowMin",{pattern:r});if(s.max_output_tokens<1)return t("settings.modelLimits.validation.maxOutputMin",{pattern:r});if(s.max_output_tokens>s.max_context_tokens)return t("settings.modelLimits.validation.maxOutputExceedsContext",{pattern:r});if(s.safety_margin<0)return t("settings.modelLimits.validation.safetyMarginNegative",{pattern:r});if(s.safety_margin>=s.max_context_tokens)return t("settings.modelLimits.validation.safetyMarginTooLarge",{pattern:r})}return null}const uM=()=>{const{t:e}=Ie(),[t,n]=p.useState(()=>wf(e)),[s,r]=p.useState(!1),[a,i]=Cr.useMessage(),l=p.useCallback((x,T)=>{n(j=>j.map((w,M)=>M===x?{...w,...T}:w))},[]),c=p.useCallback(()=>{n(x=>[...x,{vendor:"",model_pattern:"",max_context_tokens:128e3,max_output_tokens:4096,safety_margin:hs,note:""}])},[]),u=p.useCallback(x=>{n(T=>T.filter((j,w)=>w!==x))},[]),m=p.useCallback(async()=>{const x=wf(e),T=await Yt.getModelLimitDefaults(),j=oM(T.model_limits);return j.length>0?j:x},[e]),f=p.useCallback(async()=>{r(!0);try{const x=await Yt.getBambooConfig(),{hasModelLimitsKey:T,modelLimits:j}=cM(x);if(j.length>0){n(j);return}if(T){n(await m());return}const w=lM();if(w.length>0){await Yt.setBambooConfig({model_limits:w}),localStorage.removeItem(Xu),localStorage.removeItem(Sf),n(w),a.info(e("settings.modelLimits.migratedFromLocalStorage"));return}n(await m())}catch(x){console.error("Failed to load model limits settings:",x),a.error(e("settings.modelLimits.loadFailed")),n(await m())}finally{r(!1)}},[m,a,e]);p.useEffect(()=>{f()},[f]);const g=async()=>{const x=dM(t,e);if(x){a.error(x);return}r(!0);try{await Yt.setBambooConfig({model_limits:t}),a.success(e("settings.modelLimits.saveSuccess"))}catch(T){console.error("Failed to save model limits settings:",T),a.error(e("settings.modelLimits.saveFailed"))}finally{r(!1)}},b=async()=>{r(!0);try{const x=await m();await Yt.setBambooConfig({model_limits:x}),n(x),localStorage.removeItem(Xu),localStorage.removeItem(Sf),a.success(e("settings.modelLimits.resetSuccess"))}catch(x){console.error("Failed to reset model limits settings:",x),a.error(e("settings.modelLimits.resetFailed"))}finally{r(!1)}},S=p.useMemo(()=>[{title:e("settings.modelLimits.columns.vendor"),dataIndex:"vendor",key:"vendor",width:170,render:(x,T,j)=>o.jsx(Qe,{value:x,placeholder:e("settings.modelLimits.placeholders.vendor"),onChange:w=>l(j,{vendor:w.target.value})})},{title:e("settings.modelLimits.columns.model"),dataIndex:"model_pattern",key:"model_pattern",width:220,render:(x,T,j)=>o.jsx(Qe,{value:x,placeholder:e("settings.modelLimits.placeholders.model"),onChange:w=>l(j,{model_pattern:w.target.value})})},{title:e("settings.modelLimits.columns.contextWindow"),dataIndex:"max_context_tokens",key:"max_context_tokens",width:180,render:(x,T,j)=>o.jsx(Zt,{value:x,onChange:w=>l(j,{max_context_tokens:Math.max(1e3,Number(w)||128e3)}),min:1e3,max:2e6,step:1e3,style:{width:"100%"}})},{title:e("settings.modelLimits.columns.maxOutput"),dataIndex:"max_output_tokens",key:"max_output_tokens",width:160,render:(x,T,j)=>o.jsx(Zt,{value:x,onChange:w=>l(j,{max_output_tokens:Math.max(1,Number(w)||4096)}),min:1,max:2e6,step:256,style:{width:"100%"}})},{title:e("settings.modelLimits.columns.notes"),dataIndex:"note",key:"note",width:240,render:(x,T,j)=>o.jsx(Qe,{value:x,placeholder:e("settings.modelLimits.placeholders.optional"),onChange:w=>l(j,{note:w.target.value})})},{title:e("settings.modelLimits.columns.actions"),key:"actions",width:100,render:(x,T,j)=>o.jsx(ue,{danger:!0,size:"small",onClick:()=>u(j),children:e("settings.modelLimits.actions.remove")})}],[u,e,l]);return o.jsxs("div",{className:"model-limits-settings",children:[i,o.jsxs(Ce,{children:[o.jsx(sM,{level:4,children:e("settings.modelLimits.title")}),o.jsxs(rM,{type:"secondary",children:[e("settings.modelLimits.descriptionPrefix")," ",o.jsx(Ud,{code:!0,children:"config.json"})," ",e("settings.modelLimits.descriptionSuffix")]}),o.jsx(zn,{}),o.jsxs(he,{direction:"vertical",size:"small",style:{width:"100%"},children:[o.jsx(Ud,{strong:!0,children:e("settings.modelLimits.defaultsTitle")}),o.jsx(Ud,{type:"secondary",children:e("settings.modelLimits.defaultsDescription")})]}),o.jsx(or,{dataSource:t,columns:S,rowKey:(x,T)=>`${x.model_pattern}-${T}`,pagination:!1,size:"small",style:{margin:"16px 0"},scroll:{x:1150}}),o.jsxs(he,{children:[o.jsx(ue,{onClick:c,children:e("settings.modelLimits.actions.addRow")}),o.jsx(ue,{type:"primary",icon:o.jsx(zc,{}),onClick:()=>void g(),loading:s,children:e("settings.modelLimits.actions.save")}),o.jsx(ue,{icon:o.jsx(lr,{}),onClick:()=>void b(),loading:s,children:e("settings.modelLimits.actions.resetToDefaults")}),o.jsx(ue,{onClick:()=>void f(),loading:s,children:e("settings.modelLimits.actions.reload")})]})]})]})},Gu="lotus_experience_mode_v1",wx=new Set(["skills","hooks","masking","env-vars","metrics","sessions","config"]);function kf(){try{const e=localStorage.getItem(Gu);if(e==="simple"||e==="advanced")return e}catch{}return"advanced"}const Tc=Pr(e=>({mode:kf(),isAdvanced:kf()==="advanced",setMode:t=>{try{localStorage.setItem(Gu,t)}catch{}e({mode:t,isAdvanced:t==="advanced"})},toggleMode:()=>e(t=>{const n=t.mode==="simple"?"advanced":"simple";try{localStorage.setItem(Gu,n)}catch{}return{mode:n,isAdvanced:n==="advanced"}})})),{Text:Hd}=He,{useToken:mM}=Ge,hM="bamboo_dark_mode",pM=({themeMode:e,onThemeModeChange:t,locale:n,onLocaleChange:s,onBack:r})=>{const{t:a}=Ie(),{token:i}=mM(),{deleteAllChats:l}=bT(),[c,u]=p.useState(!1),[m,f]=Cr.useMessage(),[g,b]=p.useState(""),[S,x]=p.useState(Nu()),[T,j]=p.useState(Bu()),[w,M]=p.useState(wc()),[_,C]=p.useState(_c()),A=Mt(ie=>ie.currentProvider)==="copilot",B=sr(ie=>ie.activeTabKey),N=sr(ie=>ie.setActiveTabKey),O=Tc(ie=>ie.isAdvanced),R=i.paddingSM,I=(ie,re)=>({key:ie,label:o.jsx(Hd,{type:"secondary",style:{fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em",cursor:"default",userSelect:"none"},children:re}),disabled:!0,children:null}),$=(ie,re)=>o.jsx("span",{"data-testid":`settings-tab-${ie}`,children:re}),U=()=>{localStorage.clear(),m.success(a("settings.notifications.localStorageCleared"))},q=async()=>{u(!0);try{await l(),await Yt.resetSetupStatus(),await Yt.resetBambooConfig(),localStorage.clear(),m.success(a("settings.notifications.resetSuccessReloading")),setTimeout(()=>{window.location.reload()},1500)}catch(ie){console.error("Failed to reset application:",ie),m.error(ie instanceof Error?ie.message:a("settings.notifications.resetFailed")),u(!1)}},K=()=>{mT(g),m.success(a("settings.notifications.promptEnhancementSaved"))},P=ie=>{x(ie),eT(ie)},W=ie=>{j(ie),sT(ie)},se=ie=>{M(ie),iT(ie)},V=ie=>{C(ie),xT(ie),window.dispatchEvent(new Event("lotus-vdi-safe-mode-change")),m.success(ie?a("settings.appTab.vdiSafeModeEnabled","Graphics compatibility mode enabled"):a("settings.appTab.vdiSafeModeDisabled","Graphics compatibility mode disabled"))};return p.useEffect(()=>{b(lx()),x(Nu()),j(Bu()),M(wc()),C(_c())},[]),o.jsxs(be,{vertical:!0,role:"region","aria-label":a("settings.page.title"),style:{height:"100vh",overflow:"hidden",background:i.colorBgContainer},children:[f,o.jsxs(be,{align:"center",justify:"space-between",style:{padding:i.padding,paddingTop:i.padding+R,borderBottom:`1px solid ${i.colorBorderSecondary}`},children:[o.jsxs(be,{align:"center",gap:i.marginSM,children:[o.jsx(ue,{icon:o.jsx(Kw,{}),onClick:r,"aria-label":a("settings.page.back"),children:a("settings.page.back")}),o.jsx(Hd,{strong:!0,"data-testid":"settings-page-title",children:a("settings.page.title")})]}),o.jsxs(Hd,{type:"secondary","data-testid":"settings-page-version",children:[a("settings.appTab.runningVersion","Running version"),": v",Km]})]}),o.jsx(so.Content,{style:{flex:1,minHeight:0,overflow:"auto",padding:i.padding},children:o.jsx(Di,{tabPosition:"left",activeKey:B,onChange:ie=>N(ie),items:[I("group-ai",a("settings.page.groups.ai")),{key:"provider",label:$("provider",a("settings.page.tabs.provider")),children:o.jsx(ZC,{})},{key:"model-limits",label:$("model-limits",a("settings.page.tabs.modelLimits")),children:o.jsx(uM,{})},{key:"prompts",label:$("prompts",a("settings.page.tabs.prompts")),children:o.jsx($T,{promptEnhancement:g,onPromptEnhancementChange:b,mermaidEnhancementEnabled:S,taskEnhancementEnabled:T,showCopilotConclusionWithOptionsEnhancement:A,copilotConclusionWithOptionsEnhancementEnabled:w,onMermaidToggle:P,onTaskToggle:W,onCopilotConclusionWithOptionsToggle:se,onSaveEnhancement:K})},I("group-tools",a("settings.page.groups.toolsAndExtensions")),{key:"skills",label:$("skills",a("settings.page.tabs.skills")),children:o.jsx(nM,{})},{key:"mcp",label:$("mcp",a("settings.page.tabs.mcp")),children:o.jsx(zj,{})},{key:"workflows",label:$("workflows",a("settings.page.tabs.workflows")),children:o.jsx(ZT,{})},{key:"hooks",label:$("hooks",a("settings.page.tabs.hooks")),children:o.jsx(AC,{})},I("group-security",a("settings.page.groups.securityAndPrivacy")),{key:"masking",label:$("masking",a("settings.page.tabs.masking")),children:o.jsx(KT,{})},{key:"env-vars",label:$("env-vars",a("settings.page.tabs.envVars")),children:o.jsx(XT,{})},I("group-monitoring",a("settings.page.groups.monitoring")),{key:"metrics",label:$("metrics",a("settings.page.tabs.metrics")),children:o.jsx(MC,{})},{key:"sessions",label:$("sessions",a("settings.page.tabs.sessions")),children:o.jsx(HC,{})},I("group-system",a("settings.page.groups.system")),{key:"config",label:$("config",a("settings.page.tabs.config")),children:o.jsx(CT,{msgApi:m,locale:n,onLocaleChange:s})},{key:"schedules",label:$("schedules",a("settings.page.tabs.schedules")),children:o.jsx(UC,{})},{key:"app",label:$("app",a("settings.page.tabs.app")),children:o.jsx(qT,{themeMode:e,onThemeModeChange:t,vdiSafeMode:_,onVdiSafeModeToggle:V,onClearLocalStorage:U,onResetApp:q,isResetting:c,darkModeKey:hM})}].filter(ie=>!(!O&&ie.key&&wx.has(ie.key)||!O&&(ie.key==="group-security"||ie.key==="group-monitoring")))})})]})},{Text:Tf,Paragraph:fM}=He;class Bi extends p.Component{constructor(n){super(n);Ct(this,"handleReset",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,s){var a,i;const r=this.props.name??"ErrorBoundary";console.error(`[${r}] Uncaught error:`,n,s),(i=(a=this.props).onError)==null||i.call(a,n,s)}render(){if(!this.state.hasError)return this.props.children;const{fallback:n}=this.props,s=this.state.error;return typeof n=="function"?n(s,this.handleReset):n!==void 0?n:o.jsx(gM,{error:s,onReset:this.handleReset})}}const gM=({error:e,onReset:t})=>{const{token:n}=Ge.useToken(),[s,r]=fn.useState(!1);return o.jsxs("div",{role:"alert",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:n.paddingLG,minHeight:200,textAlign:"center"},children:[o.jsx(gb,{style:{fontSize:36,color:n.colorWarning}}),o.jsx(Tf,{strong:!0,style:{fontSize:16},children:"Something went wrong"}),o.jsx(Tf,{type:"secondary",style:{maxWidth:420},children:"An unexpected error occurred in this section. You can try again or reload the page if the issue persists."}),o.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[o.jsx(ue,{type:"primary",icon:o.jsx(lr,{}),onClick:t,"aria-label":"Retry rendering this section",children:"Try Again"}),o.jsx(ue,{type:"text",size:"small",onClick:()=>r(a=>!a),"aria-expanded":s,"aria-label":"Toggle error details",children:s?"Hide Details":"Show Details"})]}),s&&o.jsxs(fM,{code:!0,copyable:!0,style:{maxWidth:560,maxHeight:200,overflow:"auto",fontSize:12,textAlign:"left",marginTop:8,background:n.colorFillTertiary,padding:n.paddingSM,borderRadius:n.borderRadius},children:[e.message,e.stack?`
|
|
128
|
+
|
|
129
|
+
${e.stack}`:""]})]})},yM=()=>{const{token:e}=Ge.useToken(),t=Uc(),n=p.useRef("");p.useEffect(()=>{const s=bM(e.colorBgContainer),r=`${s}-${t.theme}-${JSON.stringify(t.themeVariables)}`;if(n.current===r)return;n.current=r;let a=t.theme;(t.theme==="default"||t.theme==="neutral")&&(a=s?"dark":t.theme),Dm.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 bM(e){if(e.startsWith("#")){const n=e.slice(1),s=parseInt(n.substr(0,2),16),r=parseInt(n.substr(2,2),16),a=parseInt(n.substr(4,2),16);return(.299*s+.587*r+.114*a)/255<.5}const t=e.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(t){const n=parseInt(t[1]),s=parseInt(t[2]),r=parseInt(t[3]);return(.299*n+.587*s+.114*r)/255<.5}return!1}Dm.initialize({startOnLoad:!1,theme:"dark",securityLevel:"loose",suppressErrorRendering:!0});Dm.parseError=function(e){console.warn("Mermaid parse error (handled gracefully):",e)};const jf=new Map,xM=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,vM=e=>e.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),SM=e=>(xM.test(e)?vM(e):e).replace(/\[([\s\S]*?)\]/g,(n,s)=>{const r=String(s),a=/\r?\n/.test(r),i=/[()]/.test(r),l=/@/.test(r);if(!a&&!i&&!l)return n;const c=r.trim(),u=c.startsWith("(")&&c.endsWith(")")&&c.length>=2;let m=r;return a&&(m=m.replace(/\r?\n/g,"<br/>")),i&&!u&&(m=m.replace(/\(/g,"(").replace(/\)/g,")")),l&&(m=m.replace(/@/g,"@")),m===r?n:`[${m}]`}),wM=200,qs=new Map,ec=new Map;let Kd=null;const _M=e=>{const n=new DOMParser().parseFromString(e,"image/svg+xml");return Array.from(n.querySelectorAll("rect")).reduce((r,a)=>{const i=Number(a.getAttribute("width"));return Number.isFinite(i)&&i<0?r+1:r},0)};async function kM(){Kd||(Kd=Bn(()=>import("./vendor-mermaid-DA4JIJaA.js").then(t=>t.be),__vite__mapDeps([7,1,2,3,6]),import.meta.url));const e=await Kd;return e.default??e}function TM(e,t){if(qs.has(e)&&qs.delete(e),qs.set(e,t),qs.size>wM){const n=qs.keys().next().value;n&&qs.delete(n)}}function tc(e){const t=qs.get(e);return t?(qs.delete(e),qs.set(e,t),t):null}function Cf(){qs.clear(),ec.clear()}function jM(e,t){const n=tc(e);if(n)return Promise.resolve(n);const s=ec.get(e);if(s)return s;const r=(async()=>{var w,M;const a=await kM();await a.parse(t);const i=`mermaid-${e}`,l=document.createElement("div"),c=Math.max(1600,window.innerWidth||0,((w=document.documentElement)==null?void 0:w.clientWidth)||0);l.style.cssText=["position:absolute","left:-9999px","top:-9999px",`width:${c}px`,`min-width:${c}px`,"visibility:hidden","pointer-events:none","overflow:visible"].join(";"),document.body.appendChild(l);let u;try{u=await a.render(i,t,l)}finally{document.body.removeChild(l)}const m=typeof u=="object"&&"svg"in u?u.svg:String(u),f=_M(m);if(f>0)throw new Error(`Mermaid rendered invalid SVG (${f} rect widths < 0)`);const S=new DOMParser().parseFromString(m,"image/svg+xml").querySelector("svg");let x=800,T=300;if(S){const _=S.getAttribute("viewBox");if(_){const C=_.split(/\s+/).map(Number);C.length===4&&(x=C[2]||800,T=C[3]||300)}if(x===800&&T===300){const C=document.createElement("div");C.style.cssText="position:absolute;visibility:hidden;width:800px;",C.innerHTML=m,document.body.appendChild(C);const L=(M=C.querySelector("svg"))==null?void 0:M.getBoundingClientRect();L&&(x=L.width,T=L.height),document.body.removeChild(C)}}const j={svg:m,width:x,height:T};return TM(e,j),j})().finally(()=>{ec.delete(e)});return ec.set(e,r),r}function Il(...e){}const CM=e=>{const t=e;return(t==null?void 0:t.name)==="AbortError"||(t==null?void 0:t.code)===20},Mf=220,Pf=e=>{const t=e.replace(/\s+/g," ").trim();return t.length<=Mf?t:`${t.slice(0,Mf)}...`},MM=e=>e==="pending"||e==="in_progress"||e==="completed"||e==="blocked",PM=new Set(["completed","error","cancelled","failed"]),Ol=e=>{const t=e.trim().toLowerCase();return t==="memory_note"||t==="session_note"};function EM(){const{message:e}=sn.useApp(),t=te(P=>P.addMessage),n=te(P=>P.applyAgentEvent),s=te(P=>P.updateTokenUsage),r=te(P=>P.setTruncationInfo),a=te(P=>P.updateSession),i=te(P=>P.updateMessage),l=te(P=>P.setTaskList),c=te(P=>P.loadTaskList),u=te(P=>P.updateTaskListDelta),m=te(P=>P.setEvaluationState),f=te(P=>P.applyChildProgress),g=te(P=>P.persistSessionTitle),b=te(P=>P.refreshChatsNow),S=te(P=>P.setPendingQuestion),x=te(P=>P.clearPendingQuestion),T=p.useRef(new Jn),j=p.useRef(new Set),w=p.useRef(new Map),M=p.useRef(new Map),_=p.useRef(new Map),C=p.useRef(new Map),L=p.useRef(new Map),A=p.useRef(new Map),B=p.useRef(new Set),N=p.useRef(new Map),O=p.useCallback(P=>{const W=N.current.get(P);W!=null&&W.timer&&clearTimeout(W.timer),N.current.delete(P)},[]),R=p.useCallback(P=>{const W=w.current.get(P);W&&(clearTimeout(W),w.current.delete(P))},[]),I=p.useCallback((P,W)=>{O(P),R(P),B.current.delete(P);const se=M.current.get(P);if(!se)return;M.current.delete(P),se.controller.abort(),It.forceFlush();const V=_.current.get(se.sessionId);V?(W!=null&&W.clearDraft&&(It.clear(V.sessionId,V.messageId),It.clear(V.sessionId,V.reasoningMessageId),It.clear(V.sessionId,V.statusMessageId)),_.current.delete(se.sessionId)):W!=null&&W.clearDraft&&(It.clear(P,`streaming-${P}`),It.clear(P,`streaming-reasoning-${P}`),It.clear(P,`streaming-status-${P}`))},[R,O]),$=p.useCallback(async P=>{const W=P.trim();if(W&&!j.current.has(W)&&!te.getState().taskLists[W]){j.current.add(W);try{await c(W)}catch(se){console.warn(`[useAgentEventSubscription] Failed to recover task list baseline for ${W}:`,se)}finally{j.current.delete(W)}}},[c]),U=p.useCallback(P=>{const W=Sc(P)(te.getState())??0;O(P);const se=new AbortController;M.current.set(P,{sessionId:P,controller:se,generation:W,streamEnded:!1});const V=`streaming-${P}`,ie=`streaming-reasoning-${P}`,re=`streaming-status-${P}`,fe=It.getLatest(V),Se=It.getLatest(ie),ke=It.getLatest(re);_.current.set(P,{sessionId:P,messageId:V,content:fe??"",reasoningMessageId:ie,reasoningContent:Se??"",statusMessageId:re,status:ke??""});const Be=F=>{const ce=_.current.get(P);if(!ce)return;const ge=(F??"").trim();if(!ge){if(!ce.status)return;ce.status="",It.clear(ce.sessionId,ce.statusMessageId);return}ce.status!==ge&&(ce.status=ge,It.publish({sessionId:ce.sessionId,messageId:ce.statusMessageId,content:ce.status}))};fe===null&&It.publish({sessionId:P,messageId:V,content:""});const tt=()=>{const F=N.current.get(P),ce=(F==null?void 0:F.attempt)??0,ge=Math.min(5e3,250*Math.pow(2,ce));I(P,{clearDraft:!1});const De=setTimeout(()=>{var H;if(N.current.delete(P),!qr(P)(te.getState()))return;const Le=te.getState().chats.find(ye=>ye.id===P),me=(H=Le==null?void 0:Le.id)==null?void 0:H.trim();me&&U(me)},ge);N.current.set(P,{attempt:ce+1,timer:De})};let ft=!1;const Ht=250,Oe=()=>{const F=M.current.get(P);!F||F.controller!==se||F.streamEnded||(F.streamEnded=!0,Il("markStreamEnded",P,"generation:",F.generation,"terminal:",ft))},zt=()=>{const F=C.current.get(P);return((F==null?void 0:F.children.size)??0)>0},Ye=()=>ft&&!zt(),we=()=>{const F=M.current.get(P);F&&(It.clear(P,`streaming-${P}`),It.clear(P,`streaming-reasoning-${P}`),It.clear(P,`streaming-status-${P}`),_.current.delete(F.sessionId))},Ke=async()=>{R(P);try{await b()}catch(me){console.warn(`[useAgentEventSubscription] High-priority refresh failed while settling parent ${P}:`,me)}const F=C.current.get(P)??{children:new Set,parentDone:!1};if(!F.parentDone||F.children.size>0)return;const ce=M.current.get(P);if(ce&&(ce.controller!==se||ce.generation!==W))return;const De=te.getState().chats.find(me=>me.id===P);De!=null&&De.isRunning||I(P,{clearDraft:!0})},st=()=>{R(P);const F=setTimeout(()=>{w.current.delete(P),Ke()},Ht);w.current.set(P,F)},Dt=()=>{const F=C.current.get(P)??{children:new Set},ce=new Set(F.children);if(C.current.set(P,{children:ce,parentDone:!0}),ce.size===0){st();return}we()};T.current.subscribeToEvents(P,{onToken:F=>{n(P,{type:"token",content:F},W);const ce=_.current.get(P);ce&&(Be(null),ce.content+=F,It.publish({sessionId:ce.sessionId,messageId:ce.messageId,content:ce.content}))},onReasoningToken:F=>{n(P,{type:"reasoning_token",content:F},W);const ce=_.current.get(P);ce&&(ce.reasoningContent+=F,It.publish({sessionId:ce.sessionId,messageId:ce.reasoningMessageId,content:ce.reasoningContent}))},onToolStart:(F,ce,ge)=>{var Ue,Re;n(P,{type:"tool_start",tool_call_id:F,tool_name:ce},W);const De=_.current.get(P),Le=(De==null?void 0:De.content)||"",me=(De==null?void 0:De.reasoningContent)||"",H=Le.trim().length>0,ye=me.trim().length>0;if(H||ye){const ut=te.getState().chats.find(vt=>vt.id===P),ot=(Ue=ut==null?void 0:ut.messages)==null?void 0:Ue[ut.messages.length-1],gt=typeof((Re=ot==null?void 0:ot.metadata)==null?void 0:Re.reasoning)=="string"?ot.metadata.reasoning:"";(ot==null?void 0:ot.role)==="assistant"&&(ot==null?void 0:ot.type)==="text"&&typeof(ot==null?void 0:ot.content)=="string"&&ot.content===Le&>===me||t(P,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:Le,createdAt:new Date().toISOString(),metadata:{sessionId:P,model:"agent",...ye?{reasoning:me}:{}}}),De&&(De.content="",De.reasoningContent="",De.status&&(De.status="",It.clear(De.sessionId,De.statusMessageId)),It.publish({sessionId:De.sessionId,messageId:De.messageId,content:""}),It.publish({sessionId:De.sessionId,messageId:De.reasoningMessageId,content:""}))}L.current.set(F,ce);const xe=ce.trim().toLowerCase();Ol(ce)?Be("memory_updating"):Be(`tool_running:${xe||"tool"}`);const _e=crypto.randomUUID();A.current.set(F,_e),t(P,{id:_e,role:"assistant",type:"tool_call",toolCalls:[{toolCallId:F,toolName:ce,parameters:ge||{},streamingOutput:""}],metadata:{},createdAt:new Date().toISOString()})},onToolToken:(F,ce)=>{n(P,{type:"tool_token",tool_call_id:F,content:ce},W);const ge=A.current.get(F),De=te.getState().chats.find(ye=>ye.id===P);if(!De)return;const Le=(ge?De==null?void 0:De.messages.find(ye=>ye.id===ge):null)||(De==null?void 0:De.messages[De.messages.length-1]);if(!Le||!("type"in Le)||Le.type!=="tool_call"||!("toolCalls"in Le)||!Array.isArray(Le.toolCalls))return;const me=Le.toolCalls.find(ye=>ye.toolCallId===F);me&&!L.current.has(F)&&(L.current.set(F,me.toolName),A.current.set(F,Le.id));const H=Le.toolCalls.map(ye=>{if(ye.toolCallId!==F)return ye;const xe=(ye.streamingOutput||"")+(ce||"");return{...ye,streamingOutput:xe}});i(P,Le.id,{toolCalls:H})},onToolComplete:(F,ce)=>{n(P,{type:"tool_complete",tool_call_id:F},W);const ge=L.current.get(F)||"unknown";L.current.delete(F),A.current.delete(F);const De=ge.trim().toLowerCase(),Le=_.current.get(P);(Ol(ge)?(Le==null?void 0:Le.status)==="memory_updating":!!(Le!=null&&Le.status&&Le.status.includes(De)))&&Be(null);const H=(ce==null?void 0:ce.display_preference)||"Default";t(P,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:ge,toolCallId:F,result:{tool_name:ge,result:(ce==null?void 0:ce.result)??"",display_preference:H},isError:!(ce!=null&&ce.success),createdAt:new Date().toISOString()})},onToolError:(F,ce)=>{n(P,{type:"tool_error",tool_call_id:F},W),L.current.delete(F),A.current.delete(F),Be(null),t(P,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:"unknown",toolCallId:F,result:{tool_name:"unknown",result:ce,display_preference:"Default"},isError:!0,createdAt:new Date().toISOString()})},onToolLifecycle:(F,ce,ge,De,Le)=>{if(ge==="begin"){const me=(ce||"").trim().toLowerCase();Ol(ce||"")?Be("memory_updating"):Be(`tool_running:${me||"tool"}`)}if(ge==="finished"||ge==="error"||ge==="cancelled"){const me=A.current.get(F);me&&i(P,me,{metadata:{elapsed_ms:De,is_mutating:Le}});const H=(ce||"").trim().toLowerCase(),ye=_.current.get(P);(Ol(ce||"")?(ye==null?void 0:ye.status)==="memory_updating":!!(ye!=null&&ye.status&&ye.status.includes(H)))&&Be(null)}},onContextCompressionStatus:(F,ce)=>{if(ce==="started"){Be("context_compacting");return}if(ce==="degraded_sections"){Be("context_compaction_degraded");return}if(ce==="failed"){Be("context_compaction_failed");return}Be(null)},onTokenBudgetUpdated:F=>{const ce=typeof F.max_context_tokens=="number"&&F.max_context_tokens>0?F.max_context_tokens:void 0,ge={systemTokens:F.system_tokens,summaryTokens:F.summary_tokens,windowTokens:F.window_tokens,totalTokens:F.total_tokens,budgetLimit:F.budget_limit,...ce?{maxContextTokens:ce}:{},...typeof F.prompt_cached_tool_outputs=="number"&&F.prompt_cached_tool_outputs>0?{promptCachedToolOutputs:F.prompt_cached_tool_outputs}:{}};s(P,ge),r(P,F.truncation_occurred,F.segments_removed);const De=te.getState().chats.find(Le=>Le.id===P);De&&a(P,{config:{...De.config,tokenUsage:ge,truncationOccurred:F.truncation_occurred,segmentsRemoved:F.segments_removed}})},onContextSummarized:F=>{Be(null),e.info(`Conversation summarized: ${F.messages_summarized} messages compressed, saved ${F.tokens_saved.toLocaleString()} tokens`,5)},onContextPressureNotification:(F,ce,ge)=>{ce==="critical"?e.error(ge,6):e.warning(ge,5)},onTaskListUpdated:F=>{F.session_id&&l(F.session_id,F)},onTaskListItemProgress:F=>{if(F.session_id){if(!te.getState().taskLists[F.session_id]){$(F.session_id);return}u(F.session_id,F)}},onTaskListCompleted:(F,ce,ge)=>{e.success(`All tasks completed! Total rounds: ${ce}, Tool calls: ${ge}`,3)},onTaskEvaluationStarted:(F,ce)=>{m(F,{isEvaluating:!0,reasoning:null,timestamp:Date.now()}),e.info(`Evaluating ${ce} task(s)...`,2)},onTaskEvaluationCompleted:(F,ce,ge)=>{const De=Pf(ge);m(F,{isEvaluating:!1,reasoning:ce>0?De:null,timestamp:Date.now()}),ce>0?e.success(`Evaluation complete: ${ce} task(s) updated.`,3):e.info("Evaluation complete: No updates needed",2)},onComplete:()=>{ft=!0,n(P,{type:"complete"},W);const F=se,ce=()=>{const ge=M.current.get(P);return ge!=null&&(ge.controller!==F||ge.generation!==W)};(async()=>{var ye,xe,_e;if(Be(null),It.forceFlush(),x(P),ce())return;const ge=_.current.get(P),De=(ge==null?void 0:ge.content)||"",Le=(ge==null?void 0:ge.reasoningContent)||"",me=De.trim().length>0,H=Le.trim().length>0;if(me||H){const Ue=te.getState().chats.find(gt=>gt.id===P),Re=(ye=Ue==null?void 0:Ue.messages)==null?void 0:ye[Ue.messages.length-1],ut=typeof((xe=Re==null?void 0:Re.metadata)==null?void 0:xe.reasoning)=="string"?Re.metadata.reasoning:"";(Re==null?void 0:Re.role)==="assistant"&&(Re==null?void 0:Re.type)==="text"&&typeof(Re==null?void 0:Re.content)=="string"&&Re.content===De&&ut===Le||await t(P,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:De,createdAt:new Date().toISOString(),metadata:{sessionId:P,model:"agent",...H?{reasoning:Le}:{}}})}if(!ce()&&(await te.getState().loadChatHistory(P,{mode:"monotonic",retries:4,retryDelayMs:200,waitForAssistant:!0}),!ce())){if(H){const Ue=te.getState().chats.find(ot=>ot.id===P),Re=[...(Ue==null?void 0:Ue.messages)||[]].reverse().find(ot=>(ot==null?void 0:ot.role)==="assistant"&&(ot==null?void 0:ot.type)==="text"),ut=typeof((_e=Re==null?void 0:Re.metadata)==null?void 0:_e.reasoning)=="string"&&Re.metadata.reasoning.trim().length>0;Re!=null&&Re.id&&!ut&&i(P,Re.id,{metadata:{...Re.metadata||{},reasoning:Le}})}ce()||Dt()}})().catch(ge=>{console.warn(`[useAgentEventSubscription] Completion finalization failed for session ${P}:`,ge),ce()||Dt()})},onError:async F=>{ft=!0,n(P,{type:"error",message:F},W),Be(null);try{const ce=Wu(F)?qu(F):F;await t(P,{id:`error-${Date.now()}`,role:"assistant",type:"text",content:`❌ **Error**: ${ce}`,createdAt:new Date().toISOString(),finishReason:"error"})}catch(ce){console.warn(`[useAgentEventSubscription] Failed to append error message for session ${P}:`,ce)}finally{Dt()}},onSessionTitleUpdated:F=>{Pu(F,te.getState())},onSessionPinnedUpdated:F=>{Pu(F,te.getState())},onSubSessionStarted:(F,ce,ge)=>{const De=C.current.get(F)??{children:new Set,parentDone:!1},Le=new Set(De.children);Le.add(ce),C.current.set(F,{children:Le,parentDone:De.parentDone}),f(F,ce,{title:ge,status:"pending",lastEventAt:new Date().toISOString()}),ge&&ge.trim()&&g(ce,ge).catch(me=>{console.warn(`[useAgentEventSubscription] Failed to persist sub-session title for ${ce}:`,me)}),b()},onSubSessionEvent:(F,ce,ge)=>{var De,Le,me;if(ge.type==="task_list_updated"&&ge.task_list){const H=ge.task_list.session_id||F;l(H,ge.task_list);return}if(ge.type==="task_list_item_progress"){const H=ge.session_id||F;if(typeof ge.item_id=="string"&&MM(ge.status)&&typeof ge.tool_calls_count=="number"&&typeof ge.version=="number"){if(!te.getState().taskLists[H]){$(H);return}u(H,{session_id:H,item_id:ge.item_id,status:ge.status,tool_calls_count:ge.tool_calls_count,version:ge.version})}return}if(ge.type==="task_evaluation_started"){const H=ge.session_id||F;m(H,{isEvaluating:!0,reasoning:null,timestamp:Date.now()});return}if(ge.type==="task_evaluation_completed"){const H=ge.session_id||F,ye=ge.updates_count??0;m(H,{isEvaluating:!1,reasoning:ye>0?Pf(ge.reasoning??""):null,timestamp:Date.now()});return}if(ge.type==="runner_progress"){const H=(De=Fi(F)(te.getState()))==null?void 0:De[ce];if(H!=null&&H.status&&PM.has(H.status))return;f(F,ce,{status:"running",roundCount:typeof ge.round_count=="number"?ge.round_count:H==null?void 0:H.roundCount,lastEventAt:new Date().toISOString()});return}if(ge.type==="token"&&typeof ge.content=="string"){const ye=((((me=(Le=Fi(F)(te.getState()))==null?void 0:Le[ce])==null?void 0:me.outputPreview)||"")+ge.content).slice(-2e3);f(F,ce,{status:"running",outputPreview:ye,lastEventAt:new Date().toISOString()})}else f(F,ce,{status:"running",lastEventAt:new Date().toISOString()})},onSubSessionHeartbeat:(F,ce,ge)=>{f(F,ce,{status:"running",lastHeartbeatAt:ge})},onSubSessionCompleted:(F,ce,ge,De)=>{const Le=C.current.get(F)??{children:new Set,parentDone:!1},me=new Set(Le.children);me.delete(ce),C.current.set(F,{children:me,parentDone:Le.parentDone}),f(F,ce,{status:ge,error:De,lastEventAt:new Date().toISOString()}),Le.parentDone&&me.size===0&&st(),b()},onNeedClarification:F=>{const ce=F.session_id||P;S(ce,{question:F.question||"",options:F.options||[],allowCustom:F.allow_custom??!0,toolCallId:F.tool_call_id??null})},onExecutionStarted:(F,ce)=>{n(P,{type:"execution_started",run_id:F},W)},onRunnerProgress:()=>{}},se).then(()=>{if(Oe(),Il("streamEnded",P,"generation:",W,"aborted:",se.signal.aborted,"terminal:",ft),se.signal.aborted||Ye())return;const F=M.current.get(P);if(F&&(F.controller!==se||F.generation!==W))return;if(!qr(P)(te.getState())){I(P,{clearDraft:!0});return}tt()}).catch(F=>{if(Oe(),se.signal.aborted)return;if(CM(F)){if(Ye())return;if(!qr(P)(te.getState())){I(P,{clearDraft:!0});return}tt();return}if(Ye())return;console.error("[useAgentEventSubscription] Subscription error:",F),I(P,{clearDraft:!0});const ce=Sc(P)(te.getState()),ge=qr(P)(te.getState());ce===W&&ge&&n(P,{type:"error",message:String(F)},W)})},[t,I,R,x,O,$,e,g,b,m,S,n,l,r,i,a,u,s,f]),q=p.useCallback(P=>{const W=P.trim();if(!W)return;B.current.delete(W);const se=M.current.get(W);if((se==null?void 0:se.sessionId)===W&&!se.controller.signal.aborted&&!se.streamEnded){Il("skipExistingSubscription",W,"generation:",se.generation,"streamEnded:",se.streamEnded);return}se&&(Il("restartStaleSubscription",W,"generation:",se.generation,"aborted:",se.controller.signal.aborted,"streamEnded:",se.streamEnded),I(W,{clearDraft:!1})),U(W)},[I,U]),K=te(P=>P.executionBySession);p.useEffect(()=>{const P={executionBySession:K},W=new Set(Object.entries(K).filter(([se])=>qr(se)(P)).map(([se])=>se));W.forEach(se=>q(se));for(const se of Array.from(M.current.keys()))W.has(se)||I(se,{clearDraft:!0});for(const se of Array.from(B.current))W.has(se)||B.current.delete(se)},[K,q,I]),p.useEffect(()=>te.subscribe(P=>P.chats,()=>{if(B.current.size!==0)for(const P of Array.from(B.current)){if(!qr(P)(te.getState())){B.current.delete(P);continue}q(P)}}),[q]),p.useEffect(()=>{const P=M.current;return()=>{const W=Array.from(P.keys());for(const se of W)I(se,{clearDraft:!0})}},[I])}const _x=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_result",RM=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_call",AM=e=>e.role==="assistant"&&"type"in e&&e.type==="workflow_result",IM=e=>e.role==="user"&&"type"in e&&e.type==="file_reference",OM=e=>e.role==="assistant"&&"type"in e&&e.type==="task_list",jc=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/bmp"],Ef=10*1024*1024,$M=2048,DM=2048,LM=.82,FM=512*1024,NM=e=>jc.includes(e.type)?e.size>Ef?{isValid:!1,error:`Image size too large: ${(e.size/1024/1024).toFixed(2)}MB. Maximum size: ${Ef/1024/1024}MB`}:{isValid:!0}:{isValid:!1,error:`Unsupported image type: ${e.type}. Supported types: ${jc.join(", ")}`},zM=e=>new Promise((t,n)=>{const s=new Image;s.onload=()=>t(s),s.onerror=()=>n(new Error("Failed to load image")),s.src=e}),Rf=e=>new Promise((t,n)=>{const s=new FileReader;s.onload=()=>{typeof s.result=="string"?t(s.result):n(new Error("Failed to convert file to base64"))},s.onerror=()=>n(new Error("Failed to read file")),s.readAsDataURL(e)}),BM=e=>URL.createObjectURL(e),WM=(e,t,n,s)=>{let{width:r,height:a}=t;if(r>n||a>s){const l=r/a;r>a?(r=n,a=Math.round(r/l)):(a=s,r=Math.round(a*l))}e.width=r,e.height=a;const i=e.getContext("2d");i&&(i.fillStyle="#ffffff",i.fillRect(0,0,r,a),i.drawImage(t,0,0,r,a))},qM=async(e,t)=>{const n=await zM(e),s=document.createElement("canvas");return WM(s,n,$M,DM),KM(s,t)},UM=async e=>{const t=NM(e);if(!t.isValid)throw new Error(t.error);const n=BM(e);try{let s;if(e.type==="image/gif"||e.size<FM)s=await Rf(e);else try{s=await qM(n,LM)}catch(a){console.warn("[imageUtils] Failed to re-encode image, using original:",a),s=await Rf(e)}const r=`img_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return{file:e,base64:s,preview:n,id:r,name:e.name,size:e.size,type:e.type}}catch(s){throw kx(n),s}},HM=async e=>{const t=Array.from(e),n=[];for(const s of t)try{const r=await UM(s);n.push(r)}catch(r){console.error(`Failed to process image ${s.name}:`,r)}return n},KM=(e,t=.8)=>e.toDataURL("image/jpeg",t),kx=e=>{e.startsWith("blob:")&&URL.revokeObjectURL(e)},Af=e=>{e.forEach(t=>kx(t.preview))},VM=e=>{if(e===0)return"0 Bytes";const t=1024,n=["Bytes","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,s)).toFixed(2))+" "+n[s]},YM=e=>!e.files||e.files.length===0?!1:Array.from(e.files).some(t=>jc.includes(t.type)),XM=e=>e.files?Array.from(e.files).filter(t=>jc.includes(t.type)):[],{Text:GM,Title:JM}=He,QM=({visible:e,images:t,currentIndex:n=0,onClose:s,onDownload:r})=>{const{token:a}=Ge.useToken(),[i,l]=p.useState(n);if(!t||t.length===0)return null;const c=t[i],u=()=>{if(r&&c)r(c);else{const g=document.createElement("a");g.href=c.base64,g.download=c.name,document.body.appendChild(g),g.click(),document.body.removeChild(g)}},m=()=>{l(g=>g>0?g-1:t.length-1)},f=()=>{l(g=>g<t.length-1?g+1:0)};return o.jsxs(Xn,{open:e,onCancel:s,footer:null,width:"90vw",style:{top:20},styles:{body:{padding:0,height:"80vh",display:"flex",flexDirection:"column"}},closeIcon:o.jsx(Ho,{style:{color:a.colorTextLightSolid}}),children:[o.jsx("div",{style:{padding:a.paddingMD,borderBottom:`1px solid ${a.colorBorder}`,background:a.colorBgContainer},children:o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",width:"100%"},children:[o.jsxs("div",{children:[o.jsx(JM,{level:5,style:{margin:0},children:c.name}),o.jsxs(GM,{type:"secondary",style:{fontSize:a.fontSizeSM},children:[VM(c.size)," • ",c.type,t.length>1&&` • ${i+1} of ${t.length}`]})]}),o.jsxs(he,{children:[t.length>1&&o.jsxs(o.Fragment,{children:[o.jsx(ue,{icon:o.jsx(op,{}),onClick:m,disabled:t.length<=1}),o.jsx(ue,{icon:o.jsx(Vs,{}),onClick:f,disabled:t.length<=1})]}),o.jsx(ue,{icon:o.jsx(Wo,{}),onClick:u,children:"Download"})]})]})}),o.jsxs("div",{style:{flex:1,display:"flex",justifyContent:"center",alignItems:"center",background:a.colorBgLayout,position:"relative",overflow:"hidden"},children:[t.length===1?o.jsx("img",{src:c.preview,alt:c.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}}):o.jsx(Vw,{dots:!1,arrows:!0,infinite:!0,afterChange:l,style:{width:"100%",height:"100%"},children:t.map(g=>o.jsx("div",{children:o.jsx("div",{style:{height:"70vh",display:"flex",justifyContent:"center",alignItems:"center"},children:o.jsx("img",{src:g.preview,alt:g.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}})})},g.id))}),t.length>1&&o.jsxs(o.Fragment,{children:[o.jsx(ue,{type:"primary",shape:"circle",icon:o.jsx(op,{}),onClick:m,style:{position:"absolute",left:20,top:"50%",transform:"translateY(-50%)",zIndex:10}}),o.jsx(ue,{type:"primary",shape:"circle",icon:o.jsx(Vs,{}),onClick:f,style:{position:"absolute",right:20,top:"50%",transform:"translateY(-50%)",zIndex:10}})]})]}),t.length>1&&o.jsx("div",{style:{padding:a.paddingSM,borderTop:`1px solid ${a.colorBorder}`,background:a.colorBgContainer,display:"flex",gap:a.marginXS,overflowX:"auto",maxHeight:80},children:t.map((g,b)=>o.jsx("div",{style:{minWidth:60,height:60,border:b===i?`2px solid ${a.colorPrimary}`:`1px solid ${a.colorBorder}`,borderRadius:a.borderRadius,overflow:"hidden",cursor:"pointer",opacity:b===i?1:.7},onClick:()=>l(b),children:o.jsx("img",{src:g.preview,alt:g.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},g.id))})]})},ka=e=>/\s/.test(e),ZM=e=>{if(!e)return[{text:"",type:"text"}];const t=[],n=e.length;let s=0;for(;s<n;){const r=e[s],a=s>0?e[s-1]:"",i=r==="/"&&(s===0||ka(a)),l=r==="@"&&(s===0||ka(a));if(!i&&!l){let m=s;for(;s<n&&!((e[s]==="/"||e[s]==="@")&&(s===0||ka(e[s-1])));)s+=1;t.push({text:e.slice(m,s),type:"text"});continue}let c=s+1;for(;c<n&&!ka(e[c]);)c+=1;const u=e.slice(s,c);i?c===n||ka(e[c])?t.push({text:u,type:"workflow"}):t.push({text:u,type:"text"}):l&&t.push({text:u,type:"file"}),s=c}return t.length>0?t:[{text:"",type:"text"}]},eP=/(\/)([a-zA-Z0-9_-]*)$/,tP=e=>{if(!e)return{command:null,isTriggerActive:!1,searchText:""};const t=e.match(eP);if(!t)return{command:null,isTriggerActive:!1,searchText:""};const n=t[2]||"",s=!n.includes(" ")&&t.index!==void 0;return{command:n||null,isTriggerActive:s,searchText:n}},nP=/@([a-zA-Z0-9._\-\/\\]*)$/,sP=e=>{if(!e)return{isTriggerActive:!1,searchText:"",tokenStart:null};const t=e.match(nP);if(!t||t.index===void 0)return{isTriggerActive:!1,searchText:"",tokenStart:null};const n=t[1]||"",s=t.index;return{isTriggerActive:!n.includes(" "),searchText:n,tokenStart:s}},rP=(e,t=80)=>{const[n,s]=p.useState(e);return p.useEffect(()=>{const r=window.setTimeout(()=>{s(e)},t);return()=>{window.clearTimeout(r)}},[e,t]),n},{Text:oP}=He,aP=({visible:e,token:t})=>e?o.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:t.colorPrimaryBg,borderRadius:t.borderRadius,zIndex:10,pointerEvents:"none"},children:o.jsxs(he,{direction:"vertical",align:"center",children:[o.jsx(Yw,{style:{fontSize:32,color:t.colorPrimary}}),o.jsx(oP,{style:{color:t.colorPrimary,fontWeight:500},children:"Drop images here"})]})}):null,{Text:If}=He,iP=({images:e,token:t,allowImages:n,onPreview:s,onClear:r})=>{const{t:a}=Ie();return!n||e.length===0?null:o.jsx("div",{style:{marginBottom:t.marginSM,padding:`${t.paddingXXS}px ${t.paddingXS}px`,borderRadius:999,border:`1px solid ${t.colorBorderSecondary}`,background:t.colorFillSecondary},children:o.jsxs(be,{align:"center",wrap:"wrap",gap:t.marginXS,children:[o.jsx(If,{type:"secondary",style:{fontSize:t.fontSizeSM,minWidth:"fit-content"},children:e.length>1?a("chat.input.imageCountPlural",{count:e.length}):a("chat.input.imageCountSingular",{count:e.length})}),e.slice(0,3).map(i=>o.jsx("div",{style:{position:"relative",width:32,height:32,borderRadius:999,overflow:"hidden",border:`1px solid ${t.colorBorderSecondary}`,cursor:"pointer"},onClick:()=>s(i),children:o.jsx("img",{src:i.preview,alt:i.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},i.id)),e.length>3&&o.jsx(If,{type:"secondary",style:{fontSize:t.fontSizeSM},children:a("chat.input.moreImages",{count:e.length-3})}),o.jsx(ue,{type:"text",size:"small",icon:o.jsx(Ho,{}),onClick:r,style:{marginLeft:"auto",minWidth:"auto",padding:"0 4px",height:24},title:a("chat.input.clearAllImages")})]})})},{TextArea:lP}=Qe,cP=({value:e,placeholder:t,disabled:n,token:s,highlightSegments:r,textAreaRef:a,highlightOverlayRef:i,onChange:l,onKeyDown:c,onPaste:u,onScrollSync:m})=>{const f=e.length>0&&r.some(x=>x.type!=="text"),g="6px 4px",b=1.65,S=n?s.colorTextDisabled:s.colorText;return o.jsxs("div",{style:{position:"relative",flex:1},children:[f?o.jsxs("div",{ref:i,"aria-hidden":!0,style:{position:"absolute",top:0,left:0,right:0,bottom:0,padding:g,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflow:"hidden",pointerEvents:"none",color:"transparent",fontSize:s.fontSize,lineHeight:b,fontFamily:"inherit",fontWeight:400,letterSpacing:"normal",transform:"translate(0, 0)",zIndex:0},children:[r.map((x,T)=>{let j;return x.type==="workflow"?j={backgroundColor:s.colorPrimaryBg,color:"transparent",WebkitTextFillColor:"transparent",fontWeight:400,textDecoration:"underline",textDecorationStyle:"dotted",textDecorationColor:s.colorPrimary}:x.type==="file"&&(j={backgroundColor:s.colorSuccessBg,color:"transparent",WebkitTextFillColor:"transparent"}),o.jsx("span",{style:j,children:x.text},`segment-${T}`)}),e.endsWith(`
|
|
130
|
+
`)?`
|
|
131
|
+
`:null]}):null,o.jsx(lP,{"data-testid":"chat-input",ref:a,value:e,onChange:x=>l(x.target.value),onKeyDown:c,onPaste:u,placeholder:t,disabled:n,autoSize:{minRows:3,maxRows:8},variant:"borderless",onScroll:m,className:"lotus-message-input-field",style:{resize:"none",flex:1,fontSize:s.fontSize,padding:g,lineHeight:b,border:"none",outline:"none",background:"transparent",color:S,WebkitTextFillColor:S,caretColor:S,position:"relative",zIndex:1,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflowY:"auto"}})]})},dP=({allowImages:e,disabled:t,isStreaming:n,token:s,fileInputRef:r,onFileInputChange:a,onFileReferenceButtonClick:i,extraControl:l})=>{const{t:c}=Ie();return o.jsxs(be,{align:"center",style:{minWidth:0,gap:0},children:[e&&o.jsxs(o.Fragment,{children:[o.jsx("input",{ref:r,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:a}),o.jsx(ue,{type:"text",icon:o.jsx(rr,{}),onClick:()=>{var u;return(u=r.current)==null?void 0:u.click()},disabled:t||n,size:"small",style:{minWidth:36,padding:"0 8px",height:36,borderRadius:18,color:s.colorTextSecondary},title:c("chat.input.addAttachments"),"aria-label":c("chat.input.addAttachments")})]}),i&&o.jsx(ue,{type:"text",icon:o.jsx(qo,{}),onClick:i,disabled:t||n,size:"small",style:{minWidth:36,padding:"0 8px",height:36,borderRadius:18,color:s.colorTextSecondary},title:c("chat.input.referenceWorkspaceFiles"),"aria-label":c("chat.input.referenceWorkspaceFiles")}),l]})},uP=({allowRetry:e,hasMessages:t,isStreaming:n,canCancel:s,disabled:r,onRetry:a,onCancel:i,onSubmit:l,value:c,images:u,isOverCharLimit:m,token:f,statusIndicator:g,submitButtonLabel:b})=>{const{t:S}=Ie(),x=!c.trim()&&u.length===0,T=s??n,j=T||r||!a,w=b??S("chat.actions.sendMessage");return o.jsxs(be,{align:"center",style:{flex:"0 0 auto",gap:f.marginXS},children:[g?o.jsx("span",{style:{flex:"0 0 auto"},children:g}):null,e&&t&&o.jsx(lo,{trigger:["click"],menu:{items:[{key:"regenerate",label:S("chat.actions.regenerate"),icon:o.jsx(lr,{})},{key:"error_retry",label:S("chat.actions.retryFailed"),icon:o.jsx(Em,{})}],onClick:({key:M})=>a==null?void 0:a(M)},disabled:j,children:o.jsx(ue,{"data-testid":"regenerate-button",type:"text",icon:o.jsx(Pm,{spin:n}),disabled:j,title:S("chat.actions.retryOptions"),"aria-label":S("chat.actions.retryOptions"),size:"small",className:"lotus-secondary-button",style:{minWidth:38,padding:"0 8px",height:38,width:38,borderRadius:19,color:f.colorTextSecondary}})}),o.jsx(ue,{"data-testid":T?"cancel-button":"send-button",type:"primary",icon:T?o.jsx(Xw,{}):o.jsx(Gw,{}),onClick:T?i:l,loading:T&&!i,disabled:T?!i||r:x||r||m,size:"small",danger:T,className:T?"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:T?void 0:"linear-gradient(135deg, var(--lotus-primary) 0%, var(--lotus-accent-secondary) 100%)",border:T?void 0:"none",boxShadow:T?void 0:"var(--lotus-send-btn-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",transform:"scale(1)"},title:T?S("chat.actions.cancelRequest"):w,"aria-label":T?S("chat.actions.cancelRequest"):w})]})},{Text:Of}=He,mP=({charCount:e,maxCharCount:t,isOverCharLimit:n,isNearCharLimit:s,isProcessingAttachments:r,token:a})=>{const i=typeof t=="number"&&Number.isFinite(t)&&t>0;return!r&&!s&&!n?null:o.jsxs(o.Fragment,{children:[i&&o.jsx(be,{justify:"flex-end",style:{marginTop:a.marginXXS},children:o.jsxs(Of,{type:n?"danger":s?"warning":"secondary",style:{fontSize:a.fontSizeSM},children:[e.toLocaleString()," / ",t.toLocaleString()]})}),r&&o.jsxs(he,{size:"small",style:{marginTop:a.marginXS},children:[o.jsx(Rs,{size:"small"}),o.jsx(Of,{type:"secondary",children:"Processing files…"})]})]})},hP=({onFiles:e,mode:t="images"})=>{const[n,s]=p.useState(!1),r=p.useCallback(l=>{var u,m;l.preventDefault(),l.stopPropagation(),(t==="images"?YM(l.dataTransfer):((m=(u=l.dataTransfer)==null?void 0:u.files)==null?void 0:m.length)>0)&&s(!0)},[t]),a=p.useCallback(l=>{l.preventDefault(),l.stopPropagation(),s(!1)},[]),i=p.useCallback(l=>{if(l.preventDefault(),l.stopPropagation(),s(!1),t==="images"){const u=XM(l.dataTransfer);u.length>0&&e(u);return}const c=Array.from(l.dataTransfer.files||[]);c.length>0&&e(c)},[t,e]);return{isDragOver:n,handleDragOver:r,handleDragLeave:a,handleDrop:i}},pP=e=>{const{message:t}=sn.useApp(),[n,s]=p.useState([]),[r,a]=p.useState(!1),[i,l]=p.useState(0),c=p.useCallback(async g=>{if(e)try{const b=await HM(g);b.length>0&&(s(S=>[...S,...b]),t.success(`Added ${b.length} image(s)`))}catch(b){t.error(`Failed to process images: ${b}`)}},[e,t]),u=p.useCallback(g=>{const b=n.find(S=>S.id===g);b&&Af([b]),s(S=>S.filter(x=>x.id!==g))},[n]),m=p.useCallback(g=>{const b=n.findIndex(S=>S.id===g.id);l(b>=0?b:0),a(!0)},[n]),f=p.useCallback(()=>{Af(n),s([])},[n]);return{images:n,setImages:s,previewModalVisible:r,setPreviewModalVisible:a,previewImageIndex:i,handleImageFiles:c,handleRemoveImage:u,handleImagePreview:m,clearImages:f}},fP=({onImages:e,onAttachments:t,allowImages:n})=>({handlePaste:p.useCallback(r=>{if(!r.clipboardData)return;const a=Array.from(r.clipboardData.items),i=[],l=[];a.forEach(c=>{if(c.kind==="file"){const u=c.getAsFile();if(!u)return;u.type.startsWith("image/")?i.push(u):l.push(u)}}),i.length>0&&n&&(r.preventDefault(),e(i)),l.length>0&&t&&(r.preventDefault(),t(l))},[n,e,t])}),Tn=[];for(let e=0;e<256;++e)Tn.push((e+256).toString(16).slice(1));function gP(e,t=0){return(Tn[e[t+0]]+Tn[e[t+1]]+Tn[e[t+2]]+Tn[e[t+3]]+"-"+Tn[e[t+4]]+Tn[e[t+5]]+"-"+Tn[e[t+6]]+Tn[e[t+7]]+"-"+Tn[e[t+8]]+Tn[e[t+9]]+"-"+Tn[e[t+10]]+Tn[e[t+11]]+Tn[e[t+12]]+Tn[e[t+13]]+Tn[e[t+14]]+Tn[e[t+15]]).toLowerCase()}const yP=new Uint8Array(16);function bP(){return crypto.getRandomValues(yP)}function $f(e,t,n){return crypto.randomUUID?crypto.randomUUID():xP(e)}function xP(e,t,n){var r;e=e||{};const s=e.random??((r=e.rng)==null?void 0:r.call(e))??bP();if(s.length<16)throw new Error("Random bytes length must be >= 16");return s[6]=s[6]&15|64,s[8]=s[8]&63|128,gP(s)}const vP=["text/","application/json","application/xml"],SP=[".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"],wP=200*1024,Tx=e=>e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`,Df=e=>{const t=e.toLowerCase();return SP.some(n=>t.endsWith(n))},_P=e=>!e.type&&Df(e.name)?!0:vP.some(t=>e.type.startsWith(t))||Df(e.name),kP=e=>new Promise((t,n)=>{const s=new FileReader;s.onerror=()=>n(s.error),s.onload=()=>t(s.result),s.readAsText(e)}),Lf=async(e,t)=>{const n=wP,s=[],r=[];for(const a of e)try{if(_P(a)&&a.size<=n){const i=await kP(a);s.push({id:$f(),file:a,name:a.name,size:a.size,type:a.type||"text/plain",kind:"text",content:i,preview:i.length>400?`${i.slice(0,400)}…`:i,lastModified:a.lastModified})}else s.push({id:$f(),file:a,name:a.name,size:a.size,type:a.type||"application/octet-stream",kind:"binary",preview:`(${Tx(a.size)}) Preview unavailable for this file type.`,lastModified:a.lastModified})}catch(i){console.error("[fileUtils] Failed to process file",a.name,i),r.push(`Failed to process ${a.name}: ${i.message}`)}return{processed:s,errors:r}},TP=e=>{const t=[],n=[];return e.forEach(s=>{s.type.startsWith("image/")?t.push(s):n.push(s)}),{images:t,others:n}},jP=e=>e.length===0?"":e.map(t=>{const n=`### File: ${t.name}`,s=`(_${Tx(t.size)}_, ${t.type||"unknown"})`;return t.kind==="text"&&t.content?`${n}
|
|
132
|
+
${s}
|
|
133
|
+
|
|
134
|
+
\`\`\`
|
|
135
|
+
${t.content}
|
|
136
|
+
\`\`\``:`${n}
|
|
137
|
+
${s}
|
|
138
|
+
|
|
139
|
+
> Preview unavailable for this file type.`}).join(`
|
|
140
|
+
|
|
141
|
+
`),CP=({allowImages:e,onAttachmentsAdded:t,messageApi:n})=>{const[s,r]=p.useState(!1),{images:a,setImages:i,previewModalVisible:l,setPreviewModalVisible:c,previewImageIndex:u,handleImageFiles:m,handleImagePreview:f,clearImages:g}=pP(e),b=p.useCallback(async _=>{if(!_||_.length===0)return;const{images:C,others:L}=TP(_);if(C.length>0&&await m(C),L.length>0&&t){r(!0);const{processed:A,errors:B}=await Lf(L);A.length>0&&(t(A),n.success(`Added ${A.length} file(s)`)),B.forEach(N=>n.error(N)),r(!1)}},[m,n,t]),{isDragOver:S,handleDragOver:x,handleDragLeave:T,handleDrop:j}=hP({onFiles:b,mode:"any"}),{handlePaste:w}=fP({onImages:m,onAttachments:t?async _=>{r(!0);const{processed:C,errors:L}=await Lf(_);C.length>0&&(t(C),n.success(`Attached ${C.length} file(s)`)),L.forEach(A=>n.error(A)),r(!1)}:void 0,allowImages:e}),M=p.useCallback(_=>{const C=_.target.files;C&&C.length>0&&m(C),_.target.value=""},[m]);return{images:a,setImages:i,previewModalVisible:l,setPreviewModalVisible:c,previewImageIndex:u,handleImageFiles:m,handleImagePreview:f,clearImages:g,isProcessingAttachments:s,isDragOver:S,handleDragOver:x,handleDragLeave:T,handleDrop:j,handlePaste:w,handleFileInputChange:M}},MP=({value:e,debouncedValue:t,onWorkflowCommandChange:n,onFileReferenceChange:s,onImagesChange:r,images:a,propImages:i,setImages:l,syncOverlayScroll:c})=>{p.useEffect(()=>{c()},[e,c]),p.useEffect(()=>{n&&n(tP(t))},[t,n]),p.useEffect(()=>{s&&s(sP(t))},[t,s]),p.useEffect(()=>{r&&r(a)},[a,r]),p.useEffect(()=>{i&&l(i)},[i,l])},PP=({value:e,images:t,isStreaming:n,disabled:s,isWorkflowSelectorVisible:r,onChange:a,onSubmit:i,onRetry:l,onHistoryNavigate:c,validateMessage:u,isOverCharLimit:m,maxCharCount:f,messageApi:g,clearImages:b,textAreaRef:S})=>{const x=p.useCallback(()=>{const w=e.trim();if(!(!w&&t.length===0||n||s)){if(m){const M=typeof f=="number"?f.toLocaleString():"configured";g.error(`Message exceeds the maximum length of ${M} characters.`);return}if(u){const M=u(w);if(!M.isValid){g.error(M.errorMessage||"Message format is incorrect");return}}i(w,t.length>0?t:void 0),b()}},[b,s,t,m,n,f,g,i,u,e]),T=p.useCallback(w=>{if(c&&!s&&!n&&!w.shiftKey&&(w.key==="ArrowUp"||w.key==="ArrowDown")){const M=w.key==="ArrowUp"?"previous":"next",_=c(M,e);if(_!=null){w.preventDefault(),a(_),requestAnimationFrame(()=>{var L,A;const C=((A=(L=S.current)==null?void 0:L.resizableTextArea)==null?void 0:A.textArea)||null;if(C){const B=_.length;C.setSelectionRange(B,B)}});return}}w.key==="Enter"&&!w.shiftKey&&!n&&!s&&!r&&(w.preventDefault(),x())},[s,x,n,r,a,c,S,e]),j=p.useCallback((w="regenerate")=>{n||s||!l||l(w)},[s,n,l]);return{handleKeyDown:T,handleSubmit:x,handleRetry:j}},EP=({value:e,onChange:t,onSubmit:n,interaction:s,placeholder:r,disabled:a=!1,images:i,onImagesChange:l,allowImages:c=!0,isWorkflowSelectorVisible:u=!1,textAreaRef:m,statusIndicator:f,validateMessage:g,onAttachmentsAdded:b,onWorkflowCommandChange:S,onFileReferenceChange:x,onFileReferenceButtonClick:T,maxCharCount:j,leftControlsExtra:w,submitButtonLabel:M})=>{const{t:_}=Ie(),{isStreaming:C,canCancel:L,hasMessages:A,allowRetry:B=!0,onRetry:N,onCancel:O,onHistoryNavigate:R}=s,I=p.useRef(null),$=p.useRef(null),U=m||$,q=p.useRef(null),{token:K}=Ge.useToken(),P=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",[W,se]=Cr.useMessage(),V=e.length,ie=typeof j=="number"&&Number.isFinite(j)&&j>0,re=ie?V>j:!1,fe=ie?!re&&V>=j*.9:!1,{images:Se,setImages:ke,previewModalVisible:Be,setPreviewModalVisible:tt,previewImageIndex:ft,handleImagePreview:Ht,clearImages:Oe,isProcessingAttachments:zt,isDragOver:Ye,handleDragOver:we,handleDragLeave:Ke,handleDrop:st,handlePaste:Dt,handleFileInputChange:F}=CP({allowImages:c,onAttachmentsAdded:b,messageApi:W}),ce=rP(e,80),ge=p.useMemo(()=>ZM(e),[e]),De=()=>{var Re,ut;const xe=(ut=(Re=U.current)==null?void 0:Re.resizableTextArea)==null?void 0:ut.textArea;if(!xe||!q.current)return;const _e=xe.scrollTop,Ue=xe.scrollLeft;q.current.style.transform=`translate(${-Ue}px, ${-_e}px)`};MP({value:e,debouncedValue:ce,onWorkflowCommandChange:S,onFileReferenceChange:x,onImagesChange:l,images:Se,propImages:i,setImages:ke,syncOverlayScroll:De});const{handleKeyDown:Le,handleSubmit:me,handleRetry:H}=PP({value:e,images:Se,isStreaming:C,disabled:a,isWorkflowSelectorVisible:u,onChange:t,onSubmit:n,onRetry:N,onHistoryNavigate:R,validateMessage:g,isOverCharLimit:re,maxCharCount:j,messageApi:W,clearImages:Oe,textAreaRef:U}),ye=r??_("chat.input.placeholder");return o.jsxs(o.Fragment,{children:[se,o.jsxs("div",{className:`message-input-container lotus-message-input-shell ${Ye?"is-drag-over":""}`,role:"group","aria-label":_("chat.input.messageComposer","Message composer"),style:{position:"relative",border:`1px solid ${Ye?"var(--lotus-input-border-active)":"var(--lotus-input-border)"}`,borderRadius:26,background:Ye?"var(--lotus-input-bg-active)":"var(--lotus-input-bg)",backdropFilter:P?"none":"blur(18px)",WebkitBackdropFilter:P?"none":"blur(18px)",boxShadow:"var(--lotus-input-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",width:"100%",padding:`${K.paddingSM}px`,overflow:"hidden"},onDragOver:we,onDragLeave:Ke,onDrop:st,children:[o.jsx(iP,{images:Se,token:K,allowImages:c,onPreview:Ht,onClear:Oe}),o.jsx(aP,{visible:Ye,token:K}),o.jsxs(be,{vertical:!0,style:{gap:K.marginXS,minHeight:132,width:"100%"},children:[o.jsx(cP,{value:e,placeholder:ye,disabled:a,token:K,highlightSegments:ge,textAreaRef:U,highlightOverlayRef:q,onChange:t,onKeyDown:Le,onPaste:Dt,onScrollSync:De}),o.jsxs(be,{align:"center",justify:"space-between",gap:K.marginSM,wrap:"wrap",style:{rowGap:K.marginXS},children:[o.jsx(be,{align:"center",gap:K.marginXS,wrap:"wrap",style:{minWidth:0,flex:"1 1 260px"},children:o.jsx(dP,{allowImages:c,disabled:a,isStreaming:C,token:K,fileInputRef:I,onFileInputChange:F,onFileReferenceButtonClick:T,extraControl:w})}),o.jsx(uP,{allowRetry:B,hasMessages:A,isStreaming:C,canCancel:L,disabled:a,onRetry:H,onCancel:O,onSubmit:me,value:e,images:Se,isOverCharLimit:re,token:K,statusIndicator:f,submitButtonLabel:M})]})]})]}),o.jsx(mP,{charCount:V,maxCharCount:j,isOverCharLimit:re,isNearCharLimit:fe,isProcessingAttachments:zt,token:K}),c&&o.jsx(QM,{visible:Be,images:Se,currentIndex:ft,onClose:()=>tt(!1)})]})},{Text:Ff}=He,{useToken:RP}=Ge,AP=({text:e,onClose:t})=>{const{token:n}=RP(),r=(e.length>150?e.substring(0,147)+"...":e).replace(/^> |^>/gm,"");return o.jsx("div",{style:{marginBottom:n.marginSM,background:n.colorFillSecondary,borderRadius:999,border:`1px solid ${n.colorBorderSecondary}`,padding:`${n.paddingXXS}px ${n.paddingSM}px`},children:o.jsxs(he,{style:{width:"100%",justifyContent:"space-between",alignItems:"flex-start"},children:[o.jsxs("div",{style:{flex:1},children:[o.jsx(Ff,{style:{fontSize:n.fontSizeSM,color:n.colorPrimary},children:"Referencing"}),o.jsx(Ff,{style:{fontSize:n.fontSizeSM,color:n.colorTextSecondary,marginLeft:n.marginSM},ellipsis:!0,children:r})]}),o.jsx(ue,{type:"text",size:"small",icon:o.jsx(Ho,{}),onClick:t,style:{marginLeft:n.marginXS,color:n.colorTextSecondary,borderRadius:999}})]})})},IP=e=>{const t=p.useRef(new Map),n=p.useRef(!1),[s,r]=p.useState(null);p.useEffect(()=>{r(null),n.current=!1},[e]);const a=p.useCallback(u=>{if(!e)return;const m=u.trim();if(!m)return;const f=t.current.get(e)??[];if(f[f.length-1]===m)return;const g=[...f,m].slice(-50);t.current.set(e,g),r(null),n.current=!1},[e]),i=p.useCallback((u,m)=>{if(!e)return{value:null,applied:!1};const f=t.current.get(e)??[];if(f.length===0)return{value:null,applied:!1};const g=m.trim();if(u==="previous"){if(g.length>0&&s===null)return{value:null,applied:!1};const S=s??f.length,x=Math.max(0,S-1);return x===s?{value:null,applied:!1}:(r(x),n.current=!0,{value:f[x]??null,applied:!0})}if(s===null)return{value:null,applied:!1};const b=s+1;return b>=f.length?(r(null),n.current=!0,{value:"",applied:!0}):(r(b),n.current=!0,{value:f[b]??null,applied:!0})},[e,s]),l=p.useCallback(()=>{if(n.current){n.current=!1;return}s!==null&&r(null)},[s]),c=p.useCallback(()=>{e&&(t.current.delete(e),r(null),n.current=!1)},[e]);return{recordEntry:a,navigate:i,acknowledgeManualInput:l,clearHistory:c}},to=class to{constructor(){Ct(this,"cache",null);Ct(this,"cacheTime",0);Ct(this,"CACHE_TTL",3e4)}static getInstance(){return to.instance||(to.instance=new to),to.instance}async listCommands(t=!1){const n=Date.now();if(!t&&this.cache&&n-this.cacheTime<this.CACHE_TTL)return this.cache;try{const s=await rt.get("commands");if(!Array.isArray(s.commands))throw new Error("Invalid command list response");return this.cache=s.commands,this.cacheTime=n,Jt("[CommandService]","[CommandService] Loaded commands:",this.cache.length),this.cache}catch(s){throw console.error("[CommandService] Failed to list commands:",s),s}}async getCommand(t,n){try{return await rt.get(`commands/${t}/${n}`)}catch(s){throw console.error(`[CommandService] Failed to get command ${t}/${n}:`,s),s}}clearCache(){this.cache=null,this.cacheTime=0}};Ct(to,"instance");let Ei=to;const Go=e=>{if(typeof e!="string"||!e.startsWith("mcp__"))return null;const t=e.slice(5),n=t.indexOf("__");if(n<=0)return null;const s=t.slice(0,n),r=t.slice(n+2);return!s||!r?null:{serverId:s,toolName:r}},OP=({setContent:e,onWorkflowDraftChange:t,acknowledgeManualInput:n,currentSessionId:s,textAreaRef:r,content:a})=>{const[i,l]=p.useState(!1),[c,u]=p.useState(""),[m,f]=p.useState(null);p.useEffect(()=>{f(null),t==null||t(null)},[s,t]);const g=p.useCallback((C,L)=>{const A=C.trimStart(),B=`/${L}`;if(!A.startsWith(B))return!1;const N=A.charAt(B.length);return!N||/\s/.test(N)},[]),b=p.useCallback(()=>{f(null),t==null||t(null)},[t]),S=p.useCallback((C,L)=>{if(!g(C,L.name))return;const A=`/${L.name}`,N=C.trim().slice(A.length).trim(),O=[L.content,N].filter(Boolean).join(`
|
|
142
|
+
|
|
143
|
+
`);t==null||t({...L,content:O})},[g,t]),x=p.useCallback(C=>{n(),m&&!g(C,m.name)&&b(),m&&g(C,m.name)&&S(C,m),e(C)},[n,b,g,m,S,e]),T=p.useCallback(C=>{l(C.isTriggerActive),u(C.isTriggerActive?C.searchText:"")},[]),j=p.useCallback(async C=>{var q,K,P,W,se,V;l(!1);const A=(ie=>{var Se;if(ie.type!=="mcp")return ie.name;const re=(Se=ie.metadata)==null?void 0:Se.originalName;if(typeof re=="string"&&re.trim())return re.trim();const fe=Go(ie.name);return fe!=null&&fe.toolName?fe.toolName:ie.displayName||ie.name})(C),B=(K=(q=r.current)==null?void 0:q.resizableTextArea)==null?void 0:K.textArea,N=(B==null?void 0:B.selectionStart)??a.length;let O,R;const $=a.substring(0,N).match(/\/([a-zA-Z0-9_-]*)$/);if($){const ie=N-$[0].length,re=a.substring(0,ie),fe=a.substring(N);O=`${re}/${A} ${fe}`,R=`${re}/${A} `.length}else if(a.trim()==="")O=`/${A} `,R=O.length;else{const ie=a.substring(0,N),re=a.substring(N);O=`${ie}/${A} ${re}`,R=`${ie}/${A} `.length}if(e(O),setTimeout(()=>{B&&(B.selectionStart=R,B.selectionEnd=R,B.focus())},0),C.type!=="workflow"){const ie={id:`command-draft-${C.id}`,name:A,content:"",createdAt:new Date().toISOString(),type:C.type,displayName:C.displayName,mcpAlias:C.type==="mcp"?C.name:void 0,mcpServerId:C.type==="mcp"?(P=C.metadata)==null?void 0:P.serverId:void 0,mcpServerName:C.type==="mcp"?(W=C.metadata)==null?void 0:W.serverName:void 0,mcpOriginalName:C.type==="mcp"?(se=C.metadata)==null?void 0:se.originalName:void 0};f(ie),t==null||t(ie);return}const U=Ei.getInstance();try{const ie=C.id.startsWith("workflow-")?C.id.slice(9):C.id,fe=((V=(await U.getCommand(C.type,ie)).content)==null?void 0:V.trim())||"";if(fe){const Se={id:`command-draft-${C.id}`,name:C.name,content:fe,createdAt:new Date().toISOString(),type:C.type,displayName:C.displayName};f(Se),t==null||t(Se)}else b()}catch(ie){console.error(`[InputContainer] Failed to apply command '${C.name}':`,ie),b()}},[b,t,e,a,r]),w=p.useCallback(async C=>{try{const B=(await Ei.getInstance().listCommands()).find(N=>N.id===C.id&&N.type===C.type);if(!B){console.error(`[InputContainer] Command '${C.id}' of type '${C.type}' not found`),e(`/${C.name} `),b();return}await j(B)}catch(L){console.error(`[InputContainer] Failed to select command '${C.name}':`,L),e(`/${C.name} `),b()}},[j,b,e]),M=p.useCallback(()=>{l(!1)},[]),_=p.useCallback(async C=>{l(!1);try{const B=(await Ei.getInstance().listCommands()).find(N=>N.name===C);B?await j(B):(console.error(`[InputContainer] Command '${C}' not found in auto-complete`),e(`/${C} `),b())}catch(L){console.error(`[InputContainer] Failed to load command '${C}' in auto-complete:`,L),e(`/${C} `),b()}},[j,b,e]);return{selectedCommand:m,showCommandSelector:i,commandSearchText:c,clearCommandDraft:b,matchesCommandToken:g,handleInputChange:x,handleCommandChange:T,handleCommandSelect:w,handleCommandSelectorCancel:M,handleAutoComplete:_,setShowCommandSelector:l}};class $P{constructor(t={}){Ct(this,"cache",null);Ct(this,"options");Ct(this,"validateWorkspacePath",this.validatePath.bind(this));Ct(this,"getRecentWorkspaces",this.getRecent.bind(this));Ct(this,"addRecentWorkspace",this.addRecent.bind(this));Ct(this,"removeRecentWorkspace",this.removeRecent.bind(this));Ct(this,"clearRecentWorkspaces",this.clearRecent.bind(this));Ct(this,"getWorkspaceSuggestions",this.getCombinedSuggestions.bind(this));Ct(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 rt.post("workspace/validate",{path:t})}async getRecent(){var t;if(this.isCacheValid())return this.cache.recentWorkspaces;try{const n=await rt.get("workspace/recent",{signal:AbortSignal.timeout(this.options.requestTimeoutMs)});return this.cache={recentWorkspaces:n,timestamp:Date.now()},n}catch(n){if(console.error("Failed to get recent workspaces:",n),(t=this.cache)!=null&&t.recentWorkspaces)return this.cache.recentWorkspaces;throw n}}async addRecent(t,n){await rt.post("workspace/recent",{path:t,metadata:n}),this.invalidateCache()}async removeRecent(t){const s=(await this.getRecent()).filter(r=>r.path!==t);this.cache={recentWorkspaces:s,timestamp:Date.now()}}async clearRecent(){this.cache=null}async getPathSuggestions(){return rt.get("workspace/suggestions")}async browseFolder(t){return rt.post("workspace/browse-folder",{path:t})}async getCombinedSuggestions(){const[t,n]=await Promise.all([this.getPathSuggestions().catch(()=>({suggestions:[]})),this.getRecent().catch(()=>[])]),r=[...t.suggestions.map(i=>({path:i.path,is_valid:!0,workspace_name:i.name})),...n];return this.deduplicateByPath(r).sort((i,l)=>{const c=n.findIndex(m=>m.path===i.path),u=n.findIndex(m=>m.path===l.path);return c!==-1&&u!==-1?c-u:c!==-1?-1:u!==-1?1:(i.workspace_name||"").localeCompare(l.workspace_name||"")})}async healthCheck(){var n,s,r;const t=Date.now();try{await rt.get("workspace/recent",{signal:AbortSignal.timeout(2e3)});const a=((n=this.cache)==null?void 0:n.recentWorkspaces)||await this.getRecent();return{available:!0,cacheValid:this.isCacheValid(),recentCount:a.length,latency:Date.now()-t}}catch(a){return{available:!1,cacheValid:this.isCacheValid(),recentCount:((r=(s=this.cache)==null?void 0:s.recentWorkspaces)==null?void 0:r.length)||0,error:a instanceof Error?a.message:"Unknown error"}}}async listWorkspaceFiles(t,n){return rt.post("workspace/files",{path:t,max_depth:(n==null?void 0:n.max_depth)??3,max_entries:(n==null?void 0:n.max_entries)??500,include_hidden:(n==null?void 0:n.include_hidden)??!1})}isCacheValid(){return this.cache?!(Date.now()-this.cache.timestamp>this.options.cacheTimeoutMs):!1}invalidateCache(){this.cache=null}deduplicateByPath(t){const n=new Set;return t.filter(s=>n.has(s.path)?!1:(n.add(s.path),!0))}}const DP=new $P,LP=({content:e,setContent:t,currentSessionId:n,currentChat:s,updateSession:r,messageApi:a})=>{const[i,l]=p.useState(new Map),[c,u]=p.useState([]),[m,f]=p.useState(!1),[g,b]=p.useState(""),[S,x]=p.useState(!1),[T,j]=p.useState(""),[w,M]=p.useState(!1),[_,C]=p.useState(null),[L,A]=p.useState(!1),B=p.useRef(null);p.useEffect(()=>{S&&j((s==null?void 0:s.config.workspacePath)??"")},[S,s==null?void 0:s.config.workspacePath]),p.useEffect(()=>{f(!1),b(""),u([]),l(new Map),B.current=(s==null?void 0:s.config.workspacePath)??null},[n,s==null?void 0:s.config.workspacePath]);const N=p.useCallback(async(K,P)=>{M(!0),u([]),C(null);try{const W=await DP.listWorkspaceFiles(P);u(W),B.current=P}catch(W){console.error("Failed to load workspace files:",W),C(W instanceof Error?W.message:"Workspace file browsing is unavailable.")}finally{M(!1)}},[]),O=p.useCallback(K=>{if(b(K.searchText),!K.isTriggerActive){f(!1);return}if(!n||!s){f(!1);return}const P=s.config.workspacePath;if(!P){j(""),x(!0),f(!1);return}f(!0),(B.current!==P||c.length===0)&&N(n,P)},[s,n,N,c.length]),R=p.useCallback(K=>{const P=e.lastIndexOf("@");let W;P>=0&&e.substring(P).match(/^@[a-zA-Z0-9._\\-\\/\\\\]*$/)?W=`${e.slice(0,P)}@${K.name} `:W=e.trim()?`${e.trim()} @${K.name} `:`@${K.name} `,t(W),l(se=>{const V=new Map(se);return V.set(K.name,K),V}),f(!1),b("")},[e,t]),I=p.useCallback(()=>{f(!1)},[]),$=p.useCallback(()=>{if(!n||!s)return;const K=s.config.workspacePath;if(!K){j(""),x(!0),f(!1);return}b(""),f(!0),(B.current!==K||c.length===0)&&N(n,K)},[s,n,N,c.length]),U=p.useCallback(()=>{x(!1),j("")},[]),q=p.useCallback(async K=>{if(!s||!n)return;const P=K.trim();if(!P){a.error("Workspace path cannot be empty");return}A(!0);try{r(n,{config:{...s.config,workspacePath:P}}),x(!1),j(""),f(!1),C(null)}catch(W){const se=W instanceof Error?W.message:"Unable to save workspace path";a.error(se)}finally{A(!1)}},[s,n,a,r]);return{fileReferences:i,setFileReferences:l,workspaceFiles:c,showFileSelector:m,setShowFileSelector:f,fileSearchText:g,isWorkspaceLoading:w,workspaceError:_,isWorkspaceModalVisible:S,workspacePathInput:T,isSavingWorkspace:L,setWorkspacePathInput:j,setIsWorkspaceModalVisible:x,handleFileReferenceChange:O,handleFileReferenceSelect:R,handleFileSelectorCancel:I,handleFileReferenceButtonClick:$,handleWorkspaceModalCancel:U,handleWorkspaceModalSubmit:q,fetchWorkspaceFiles:N}},FP=()=>{const[e,t]=p.useState([]),n=p.useCallback(a=>{t(i=>[...i,...a])},[]),s=p.useCallback(a=>{t(i=>i.filter(l=>l.id!==a))},[]),r=p.useCallback(()=>{t([])},[]);return{attachments:e,setAttachments:t,handleAttachmentsAdded:n,handleAttachmentRemove:s,handleClearAttachments:r}},NP=({attachments:e,referenceText:t,selectedWorkflow:n,matchesWorkflowToken:s,fileReferences:r,reasoningEffort:a,sendMessage:i,recordEntry:l,clearWorkflowDraft:c,setContent:u,setReferenceText:m,setAttachments:f,setFileReferences:g})=>({handleSubmit:p.useCallback(async(S,x)=>{const T=S.trim(),j=jP(e),w=(t==null?void 0:t.trim())??"";let M=T,_;if(n!=null&&n.content&&n.type==="workflow"){const L=`/${n.name}`;if(s(T,n.name)){const B=T.slice(L.length).trim();M=[n.content,B].filter(Boolean).join(`
|
|
144
|
+
|
|
145
|
+
`)}}else if((n==null?void 0:n.type)==="skill"){const L=`/${n.name}`;if(s(T,n.name)){const B=T.slice(L.length).trim();M=[`[User explicitly selected skill: ${n.displayName||n.name} (ID: ${n.name})]`,B].filter(Boolean).join(`
|
|
146
|
+
|
|
147
|
+
`),_=[n.name]}}else if((n==null?void 0:n.type)==="mcp"){const L=`/${n.name}`;if(s(T,n.name)){const B=T.slice(L.length).trim();M=[`[User explicitly selected MCP tool: ${n.mcpAlias||n.displayName||n.name}]`,B].filter(Boolean).join(`
|
|
148
|
+
|
|
149
|
+
`)}}if(!M&&!j&&(!x||x.length===0))return;const C=[w,M,j].filter(Boolean).join(`
|
|
150
|
+
|
|
151
|
+
`);if(l(C),u(""),c(),r.size>0){const L=Array.from(C.matchAll(/@([^\\s]+)/g));if(L.length>0){const A=[];for(const B of L){const N=B[1],O=r.get(N);O&&A.push(O)}if(A.length>0){const B=JSON.stringify({type:"file_reference",paths:A.map(N=>N.path),display_text:C});await i(B,x,a,_)}else await i(C,x,a,_)}else await i(C,x,a,_)}else await i(C,x,a,_);m(null),f([]),g(new Map)},[e,c,r,s,l,a,n,i,f,u,g,m,t])}),zP=({currentSessionId:e,currentChat:t,currentMessages:n,reasoningEffort:s,retryLastTurn:r,navigate:a})=>{const i=p.useCallback(async(c="regenerate")=>{if(!e||!t)return;const u=[...n];u.length===0||[...u].reverse().findIndex(f=>f.role==="user")===-1||await r(s,c)},[t,e,n,s,r]),l=p.useCallback((c,u)=>{const m=a(c,u);return m.applied?m.value:null},[a]);return{retryLastMessage:i,handleHistoryNavigate:l}},BP=({referenceText:e,isToolSpecificMode:t,isRestrictConversation:n,allowedTools:s,autoToolPrefix:r,t:a})=>a(e?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows"),Ju="chat-toggle-batch-export-selection",Qu="chat-focus-input",zo="chat-pending-question-resolved",WP=p.lazy(()=>Bn(()=>import("./index-CTVpEC_u.js"),__vite__mapDeps([8,1,2,3]),import.meta.url)),qP=p.lazy(()=>Bn(()=>import("./index-ytQ0KoKe.js"),__vite__mapDeps([9,1,2,3,4,5,6,7,10]),import.meta.url)),UP=p.lazy(()=>Bn(()=>import("./index-CWu7YVPN.js"),__vite__mapDeps([11,1,2,3,4,5,6,7]),import.meta.url)),HP=p.lazy(()=>Bn(()=>import("./index-Byt6VrzO.js"),__vite__mapDeps([12,1,2,3]),import.meta.url)),{useToken:KP}=Ge,Nf="chat-send-message",zf="reference-text",VP="chat-model-options-cache-v1",jx=24*60*60*1e3,YP=["low","medium","high","xhigh","max"],XP=[],Cx=e=>`${VP}:${e}`,GP=e=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(Cx(e));if(!t)return null;const n=JSON.parse(t);return!n||!Array.isArray(n.options)||Date.now()-n.timestamp>jx?null:n.options.filter(s=>s&&typeof s.value=="string"&&s.value.trim().length>0&&typeof s.label=="string").map(s=>({value:s.value,label:s.label}))}catch{return null}},JP=(e,t)=>{if(!(typeof window>"u"))try{const n={timestamp:Date.now(),options:t};localStorage.setItem(Cx(e),JSON.stringify(n))}catch{}},QP=async e=>{const t=Wn.getInstance();try{const n=await t.loadModelOptionsCache(e);if(n)return Date.now()-n.timestamp>jx?null:n.options.filter(s=>s&&typeof s.value=="string"&&s.value.trim().length>0&&typeof s.label=="string")}catch{}return GP(e)},ZP=async(e,t)=>{const n=Wn.getInstance();try{await n.saveModelOptionsCache(e,t,Date.now())}catch{}JP(e,t)},eE=({sessionId:e,onWorkflowDraftChange:t,statusIndicator:n})=>{var Ir,al;const{t:s}=Ie(),r=p.useRef(null),{token:a}=KP(),i=Lm(),l=sr(ve=>ve.open),c=te(ve=>e??ve.currentSessionId),u=te(ve=>ve.currentSessionId),m=te(Er(c)),f=(m==null?void 0:m.messages)||[],g=te(ve=>ve.addMessage),b=te(ve=>ve.updateSession),S=te(Gb(c)),x=te(Jb(c)),T=te(ve=>ve.markRespondStart),j=te(ve=>ve.markSettleTimeout),w=te(Ci(c)),M=te(ve=>ve.clearPendingQuestion),_=Ym(c),C=Xm((Ir=m==null?void 0:m.config)==null?void 0:Ir.model_ref),L=Mt(ve=>ve.isProviderModelRefEnabled),A=te(ve=>c?ve.inputStates[c]:void 0),B=te(ve=>ve.setInputContent),N=te(ve=>ve.setReferenceText),O=te(ve=>ve.setInputReasoningEffort),R=Mt(ve=>ve.currentProvider),I=Mt(ve=>ve.providerConfig),[$,U]=p.useState([]),[q,K]=p.useState(!1),[P,W]=p.useState(null),[se,V]=p.useState(!1),ie=(A==null?void 0:A.content)||"",re=(A==null?void 0:A.referenceText)||null,fe=p.useMemo(()=>{var ve;return(ve=I.providers[R])==null?void 0:ve.reasoning_effort},[I,R]),Se=p.useMemo(()=>c?Um(c):void 0,[c]),ke=((al=m==null?void 0:m.config)==null?void 0:al.reasoningEffort)??(A==null?void 0:A.reasoningEffort)??Se??fe??"medium",Be=p.useCallback(ve=>{c&&B(c,ve)},[c,B]),tt=p.useCallback(ve=>{c&&N(c,ve)},[c,N]),ft=p.useCallback(async ve=>{if(c&&(O(c,ve),!!m))try{await Fo.patchSession(c,{reasoning_effort:ve}),b(c,{config:{...m.config,reasoningEffort:ve}})}catch($t){console.warn("[InputContainer] Failed to persist reasoning effort:",$t)}},[m,c,O,b]),Ht=S,{sendMessage:Oe,retryLastTurn:zt,cancel:Ye}=cx({sessionId:c,addMessage:g,updateSession:b});p.useEffect(()=>{if(typeof window>"u")return;const ve=Gt=>Gt?c===Gt:c!==null&&c===u,$t=Gt=>{const Tt=Gt;if(!Tt.detail||typeof Tt.detail.text!="string")return;const Pt=typeof Tt.detail.sessionId=="string"?Tt.detail.sessionId:null;if(!ve(Pt))return;const dn=Tt.detail.text.trim();dn&&(Tt.detail.handled=!0,tt(dn),requestAnimationFrame(()=>{var an;(an=r.current)==null||an.focus()}))},Lt=Gt=>{var dn;const Tt=Gt,Pt=typeof((dn=Tt.detail)==null?void 0:dn.sessionId)=="string"?Tt.detail.sessionId:null;ve(Pt)&&(Tt.detail&&(Tt.detail.handled=!0),requestAnimationFrame(()=>{var an;(an=r.current)==null||an.focus()}))};return window.addEventListener(zf,$t),window.addEventListener(Qu,Lt),()=>{window.removeEventListener(zf,$t),window.removeEventListener(Qu,Lt)}},[u,c,tt]);const we=Ht,{message:Ke}=sn.useApp(),st=!1,Dt=!1,F=XP,ce=void 0,{recordEntry:ge,navigate:De,acknowledgeManualInput:Le}=IP(c),{attachments:me,setAttachments:H,handleAttachmentsAdded:ye,handleAttachmentRemove:xe,handleClearAttachments:_e}=FP(),Ue=OP({setContent:Be,onWorkflowDraftChange:t,acknowledgeManualInput:Le,currentSessionId:c,textAreaRef:r,content:ie}),Re=LP({content:ie,setContent:Be,currentSessionId:c,currentChat:m,updateSession:b,messageApi:Ke}),{setShowFileSelector:ut}=Re;p.useEffect(()=>{Ue.showCommandSelector&&ut(!1)},[Ue.showCommandSelector,ut]);const{handleSubmit:ot}=NP({attachments:me,referenceText:re,selectedWorkflow:Ue.selectedCommand,matchesWorkflowToken:Ue.matchesCommandToken,fileReferences:Re.fileReferences,reasoningEffort:ke,sendMessage:Oe,recordEntry:ge,clearWorkflowDraft:Ue.clearCommandDraft,setContent:Be,setReferenceText:tt,setAttachments:H,setFileReferences:Re.setFileReferences}),gt=w,_t=!!gt,vt=(gt==null?void 0:gt.options)||[],Bt=(gt==null?void 0:gt.allowCustom)??!0,Kt=p.useCallback(ve=>ve?!!Ci(ve)(te.getState()):!1,[]),qe=p.useCallback(async ve=>{const $t=ve.trim();if(!$t||!c)return;const Gt=Ci(c)(te.getState());if(Gt&&!Gt.allowCustom&&Gt.options.length>0&&!Gt.options.includes($t)){Ke.warning(s("components.questionDialog.selectOptionWarning"));return}T(c,(gt==null?void 0:gt.toolCallId)??null),await new Promise(Tt=>setTimeout(Tt,0));try{const Tt={response:$t,reasoning_effort:ke};L()&&C&&(Tt.model_ref=C,Tt.provider=C.provider);const Pt=await Ze.post(`respond/${c}`,Tt);Ke.success(s("components.questionDialog.responseSubmittedContinue")),Be(""),M(c),typeof window<"u"&&window.dispatchEvent(new CustomEvent(zo,{detail:{sessionId:c}}));const dn=Pt==null?void 0:Pt.auto_resume_status;(!dn||!["started","already_running"].includes(dn))&&j(c)}catch(Tt){console.error("[InputContainer] Failed to submit respond:",Tt),Ke.error(Tt instanceof Error?Tt.message:s("components.questionDialog.submitFailed")),j(c)}},[c,ke,C,L,Ke,Be,M,T,j,gt==null?void 0:gt.toolCallId,s]),rn=p.useCallback(async(ve,$t)=>{if(Kt(c)){await qe(ve);return}await ot(ve,$t)},[c,Kt,qe,ot]),cn=p.useCallback(async(ve,$t)=>{await rn(ve,$t)},[rn]);p.useEffect(()=>{if(typeof window>"u")return;const ve=$t=>{var dn,an,ea;const Lt=$t;if(!Lt.detail)return;const Gt=typeof Lt.detail.sessionId=="string"?Lt.detail.sessionId:null;if(!(Gt?c===Gt:c!==null&&c===u))return;Lt.detail.handled=!0;const Pt=(dn=Lt.detail)==null?void 0:dn.content;if(typeof Pt!="string"||Pt.trim().length===0){(ea=(an=Lt.detail)==null?void 0:an.reject)==null||ea.call(an,new Error("External send message content is empty"));return}rn(Pt,void 0).then(()=>{var ws,_s;(_s=(ws=Lt.detail)==null?void 0:ws.resolve)==null||_s.call(ws)}).catch(ws=>{var _s,go;(go=(_s=Lt.detail)==null?void 0:_s.reject)==null||go.call(_s,ws)})};return window.addEventListener(Nf,ve),()=>{window.removeEventListener(Nf,ve)}},[u,c,rn]);const{retryLastMessage:on,handleHistoryNavigate:ze}=zP({currentSessionId:c,currentChat:m,currentMessages:f,reasoningEffort:ke,retryLastTurn:zt,navigate:De}),Ar=()=>tt(null),as=p.useMemo(()=>I.providers[R],[I,R]),En=p.useMemo(()=>!as||typeof as!="object"?!1:R==="copilot"?Object.keys(as).length>0:"api_key"in as?typeof as.api_key=="string"&&as.api_key.trim().length>0:!1,[R,as]),$s=p.useCallback(()=>En?!1:(l("chat"),Ke.warning("Please configure provider first"),!0),[En,Ke,l]);p.useEffect(()=>{(async()=>{const ve=await QP(R);U(ve??[]),W(null)})()},[R]);const Qn=p.useCallback(ve=>ve instanceof Error&&ve.message.trim()?ve.message:"Unknown error",[]),Ys=p.useMemo(()=>({openai:[...YC],anthropic:[...XC],gemini:[...GC],copilot:[...JC],bodhi:[]})[R]||[],[R]),ur=p.useMemo(()=>{const $t=[...$.length>0?$:Ys];return _&&!$t.some(Lt=>Lt.value===_)&&$t.unshift({value:_,label:_}),$t},[$,Ys,_]),is=p.useCallback(async(ve,$t)=>{if(!(!($t!=null&&$t.force)&&$.length>0))try{K(!0),W(null);const Gt=(ve==="copilot"?await Lb.getModels():Ys).map(Tt=>({value:typeof Tt=="string"?Tt:Tt.value,label:typeof Tt=="string"?Tt:Tt.label}));U(Gt),await ZP(ve,Gt)}catch(Lt){W(Qn(Lt))}finally{K(!1)}},[Ys,Qn,$.length]),Ss=p.useCallback(ve=>{ve&&($s()||q||$.length>0||is(R))},[R,is,q,$.length,$s]),Fe=p.useCallback(async ve=>{var $t,Lt,Gt;if(!(!ve||ve===_)&&!se)try{if($s())return;if(V(!0),!c||!m){c&&b(c,{config:{systemPromptId:(($t=m==null?void 0:m.config)==null?void 0:$t.systemPromptId)||"default",baseSystemPrompt:((Lt=m==null?void 0:m.config)==null?void 0:Lt.baseSystemPrompt)||"",lastUsedEnhancedPrompt:((Gt=m==null?void 0:m.config)==null?void 0:Gt.lastUsedEnhancedPrompt)??null,...(m==null?void 0:m.config)||{},model:ve}});return}await Fo.patchSession(c,{model:ve}),b(c,{config:{...m.config,model:ve}}),Ke.success(s("settings.providerTab.modelUpdated"))}catch(Tt){Ke.error(`${s("settings.providerTab.updateModelErrorPrefix")}: ${Qn(Tt)}`)}finally{V(!1)}},[_,m,Qn,se,Ke,$s,c,s,b]),yt=p.useCallback(async ve=>{if(!c||!(m!=null&&m.config)){Mt.getState().setSelectedModelRef(ve);return}if(!se)try{V(!0),await Fo.patchSession(c,{model:ve.model,model_ref:ve,provider:ve.provider}),Mt.getState().setSelectedModelRef(ve),b(c,{config:{...m.config,model:ve.model,model_ref:ve}}),Ke.success(s("settings.providerTab.modelUpdated"))}catch($t){Ke.error(`${s("settings.providerTab.updateModelErrorPrefix")}: ${Qn($t)}`)}finally{V(!1)}},[m==null?void 0:m.config,Qn,se,Ke,c,s,b]),et=p.useMemo(()=>BP({referenceText:re,isToolSpecificMode:st,isRestrictConversation:Dt,allowedTools:F,autoToolPrefix:ce,t:s}),[re,st,Dt,F,ce,s]),mt=_t&&Bt?s("chat.respond.customAnswerPlaceholder"):_t?s("components.questionDialog.selectOptionWarning"):et,_n=_t?s("chat.respond.submitToolResult","Submit tool result"):void 0,Un=p.useMemo(()=>({low:s("chat.input.reasoning.low"),medium:s("chat.input.reasoning.medium"),high:s("chat.input.reasoning.high"),xhigh:s("chat.input.reasoning.xhigh"),max:s("chat.input.reasoning.max")}),[s]),Hn=p.useMemo(()=>Un[ke]??ke,[ke,Un]),Rn=o.jsx(lo,{trigger:["click"],placement:"topLeft",disabled:!_||S,menu:{selectable:!0,selectedKeys:[ke],items:YP.map(ve=>({key:ve,label:Un[ve]})),onClick:({key:ve})=>{ft(ve)}},children:o.jsx(ue,{type:"text",size:"small",disabled:!_||we,style:{minWidth:i?74:88,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:ke==="medium"?a.colorTextSecondary:a.colorPrimary},title:s("chat.input.reasoningTitle",{label:Hn}),children:o.jsxs(he,{size:6,children:[o.jsx(yb,{}),o.jsx("span",{children:Hn}),o.jsx(Gn,{style:{fontSize:10}})]})})}),ls=_||s(En?"chat.model.selectModel":"chat.model.configureProvider"),yn=p.useMemo(()=>ur.length>0?ur.map(ve=>({key:ve.value,label:ve.label})):[{key:"__no_models__",label:P||s("chat.model.noModelsAvailable"),disabled:!0}],[ur,P,s]),An=o.jsx(ue,{type:"text",size:"small",disabled:we||se,onClick:()=>{En||$s()},style:{minWidth:i?112:146,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:P?a.colorError:a.colorTextSecondary},title:ls,children:o.jsxs(he,{size:6,children:[q?o.jsx(io,{}):o.jsx(Rm,{}),o.jsx("span",{style:{maxWidth:i?84:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ls}),o.jsx(Gn,{style:{fontSize:10}})]})}),Ds=L()?o.jsx(Sx,{value:C,onChange:yt,disabled:we||se}):En?o.jsx(lo,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:_?[_]:[],items:yn,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:ve})=>{ve!=="__no_models__"&&Fe(String(ve))}},onOpenChange:Ss,disabled:S||se,children:An}):An;return o.jsxs("div",{style:{padding:`${a.paddingXXS}px ${a.paddingXS}px`,background:"transparent",borderTop:"none",boxShadow:"none",width:"100%",position:"relative",overflow:"visible"},children:[!_&&o.jsx(Ut,{type:"warning",showIcon:!0,icon:o.jsx(Ki,{}),message:s(En?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:s(En?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:En?void 0:o.jsx(he,{children:o.jsx("a",{onClick:()=>l("chat"),children:s("chat.model.openSettings")})}),style:{marginBottom:a.marginSM}}),st,re&&o.jsx(AP,{text:re,onClose:Ar}),me.length>0&&o.jsx(p.Suspense,{fallback:o.jsx(Rs,{size:"small"}),children:o.jsx(WP,{files:me,onRemove:xe,onClear:_e})}),_t&&vt.length>0&&o.jsx("div",{style:{marginBottom:a.marginSM},children:o.jsx(he,{wrap:!0,size:[8,8],children:vt.map(ve=>o.jsx(ue,{size:"small",onClick:()=>{qe(ve)},disabled:S,children:ve},ve))})}),o.jsx(EP,{value:ie,onChange:Ue.handleInputChange,onSubmit:cn,placeholder:mt,allowImages:!0,disabled:!_||_t&&!Bt&&vt.length>0,statusIndicator:n,submitButtonLabel:_n,isWorkflowSelectorVisible:Ue.showCommandSelector,textAreaRef:r,validateMessage:ve=>({isValid:!0}),onAttachmentsAdded:ye,onWorkflowCommandChange:Ue.handleCommandChange,onFileReferenceChange:Re.handleFileReferenceChange,onFileReferenceButtonClick:Re.handleFileReferenceButtonClick,leftControlsExtra:o.jsxs(he,{size:0,wrap:!0,children:[Ds,Rn]}),interaction:{isStreaming:we,canCancel:x,hasMessages:f.some(ve=>ve.role==="user"),allowRetry:!0,onRetry:on,onCancel:Ye,onHistoryNavigate:ze}}),o.jsx(p.Suspense,{fallback:null,children:o.jsx(qP,{visible:Ue.showCommandSelector,onSelect:Ue.handleCommandSelect,onCancel:Ue.handleCommandSelectorCancel,onAutoComplete:Ue.handleAutoComplete,searchText:Ue.commandSearchText})}),Re.showFileSelector&&o.jsx(p.Suspense,{fallback:o.jsx(Rs,{size:"small"}),children:o.jsx(HP,{visible:Re.showFileSelector,files:Re.workspaceFiles,searchText:Re.fileSearchText,loading:Re.isWorkspaceLoading,error:Re.workspaceError,onSelect:Re.handleFileReferenceSelect,onCancel:Re.handleFileSelectorCancel,onChangeWorkspace:()=>{Re.setWorkspacePathInput((m==null?void 0:m.config.workspacePath)??""),Re.setIsWorkspaceModalVisible(!0)}})}),o.jsx(p.Suspense,{fallback:null,children:o.jsx(UP,{open:Re.isWorkspaceModalVisible,initialPath:Re.workspacePathInput,loading:Re.isSavingWorkspace,onSubmit:Re.handleWorkspaceModalSubmit,onCancel:Re.handleWorkspaceModalCancel})})]})},{Text:Zs}=He,tE=220,nE="chat-session-diff-collapse:",sE=e=>e.split(/[\\/]/).pop()||e,Mx=e=>`${nE}${e??"default"}`,Vd=e=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Mx(e));if(!t)return null;const n=JSON.parse(t);if(!n||typeof n!="object")return null;const s="isExpanded"in n&&typeof n.isExpanded=="boolean"?n.isExpanded:!0,r="expandedFiles"in n&&Array.isArray(n.expandedFiles)?n.expandedFiles.filter(a=>typeof a=="string"):[];return{isExpanded:s,expandedFiles:r}}catch{return null}},rE=async(e,t)=>{if(typeof window>"u")return;await Wn.getInstance().saveDiffCollapse(e??"default",t);try{window.localStorage.setItem(Mx(e),JSON.stringify(t))}catch{}},oE=({sessionDiffSummary:e,sessionId:t})=>{const{token:n}=Ge.useToken(),s=!!(e&&e.files.length>0),[r,a]=p.useState(s),[i,l]=p.useState(s),[c,u]=p.useState(()=>{var S;return((S=Vd(t))==null?void 0:S.isExpanded)??!0}),[m,f]=p.useState(()=>{var S;return new Set(((S=Vd(t))==null?void 0:S.expandedFiles)??[])});p.useEffect(()=>{if(s){a(!0);const x=window.setTimeout(()=>l(!0),0);return()=>window.clearTimeout(x)}l(!1);const S=window.setTimeout(()=>a(!1),tE);return()=>window.clearTimeout(S)},[s]);const g=p.useMemo(()=>e?e.files:[],[e]),b=p.useMemo(()=>{const S=new Map;return e&&e.files.forEach(x=>{S.set(x.filePath,fx(x.unifiedDiff))}),S},[e]);return p.useEffect(()=>{const S=Vd(t);u((S==null?void 0:S.isExpanded)??!0),f(new Set((S==null?void 0:S.expandedFiles)??[])),Wn.getInstance().loadDiffCollapse(t??"default").then(T=>{T&&(u(T.isExpanded),f(new Set(T.expandedFiles)))}).catch(()=>{})},[t]),p.useEffect(()=>{rE(t,{isExpanded:c,expandedFiles:Array.from(m)}).catch(()=>{})},[t,c,m]),p.useEffect(()=>{if(!e||e.files.length===0)return;const S=new Set(e.files.map(x=>x.filePath));f(x=>{const T=new Set;let j=!1;return x.forEach(w=>{S.has(w)?T.add(w):j=!0}),!j&&T.size===x.size?x:T})},[e]),!r||!e?null:o.jsx("div",{className:`active-tool-card-wrapper ${i?"visible":""}`,"aria-hidden":!i,"data-testid":"session-diff-card",children:o.jsx(Ce,{size:"small",style:{width:"100%",borderRadius:n.borderRadiusLG,border:`1px solid ${n.colorBorderSecondary}`,background:n.colorBgContainer,boxShadow:n.boxShadowSecondary},styles:{body:{padding:`${n.paddingXS}px ${n.paddingSM}px`}},children:o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:6,children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:n.marginSM,cursor:"pointer"},onClick:()=>u(S=>!S),"data-testid":"session-diff-toggle",children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:n.marginSM,minWidth:0},children:[o.jsx(bb,{style:{color:n.colorPrimary}}),o.jsx(Zs,{strong:!0,style:{whiteSpace:"nowrap"},children:"Session diffs"}),o.jsxs(Zs,{type:"secondary",style:{fontSize:n.fontSizeSM,whiteSpace:"nowrap"},children:["(",e.files.length," files / ",e.changedTools," tools)"]}),o.jsxs(he,{size:4,style:{marginInlineStart:n.marginXS},children:[o.jsxs(Zs,{style:{color:n.colorSuccess,fontSize:n.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",e.totalAdded]}),o.jsxs(Zs,{style:{color:n.colorError,fontSize:n.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",e.totalRemoved]})]})]}),o.jsx("div",{style:{color:n.colorTextSecondary},children:c?o.jsx(Gn,{}):o.jsx(Vs,{})})]}),c&&o.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr",gap:6,maxHeight:280,overflowY:"auto"},"data-testid":"session-diff-file-list",children:g.map(S=>{const x=m.has(S.filePath),T=b.get(S.filePath)??[];return o.jsxs("div",{style:{border:`1px solid ${n.colorBorderSecondary}`,borderRadius:n.borderRadiusSM,overflow:"hidden",background:n.colorBgContainer},"data-testid":"session-diff-file-item","data-file-path":S.filePath,children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:n.marginSM,padding:"4px 8px",borderRadius:n.borderRadiusSM,background:n.colorFillTertiary,cursor:"pointer"},onClick:()=>{f(j=>{const w=new Set(j);return w.has(S.filePath)?w.delete(S.filePath):w.add(S.filePath),w})},"data-testid":"session-diff-file-header","data-file-path":S.filePath,children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:n.marginXS,minWidth:0,flex:1},children:[o.jsx("span",{style:{color:n.colorTextSecondary},children:x?o.jsx(Gn,{}):o.jsx(Vs,{})}),o.jsx(Zs,{ellipsis:{tooltip:S.filePath},style:{flex:1,minWidth:0,fontSize:n.fontSizeSM},children:sE(S.filePath)})]}),o.jsxs(he,{size:4,children:[o.jsxs(Zs,{style:{color:n.colorSuccess,fontSize:n.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",S.added]}),o.jsxs(Zs,{style:{color:n.colorError,fontSize:n.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",S.removed]})]})]}),x&&o.jsxs("div",{style:{borderTop:`1px solid ${n.colorBorderSecondary}`,maxHeight:220,overflow:"auto",background:n.colorBgContainer},"data-testid":"session-diff-file-panel","data-file-path":S.filePath,children:[T.length>0?T.map((j,w)=>{const M={margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:n.fontSizeSM,lineHeight:1.5,padding:"0 8px",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"};return j.kind==="add"?M.background=n.colorSuccessBg:j.kind==="remove"?M.background=n.colorErrorBg:j.kind==="modified_add"?(M.background=n.colorWarningBg,M.borderLeft=`3px solid ${n.colorSuccess}`):j.kind==="modified_remove"?(M.background=n.colorWarningBg,M.borderLeft=`3px solid ${n.colorError}`):j.kind==="hunk"?(M.background=n.colorFillSecondary,M.color=n.colorTextSecondary):j.kind==="meta"&&(M.background=n.colorFillTertiary,M.color=n.colorTextSecondary),o.jsx("pre",{style:M,"data-testid":"session-diff-line","data-kind":j.kind,children:j.text||" "},`${S.filePath}-${w}`)}):o.jsx(Zs,{type:"secondary",style:{display:"block",padding:"8px",fontSize:n.fontSizeSM},children:"No diff preview available."}),S.truncated&&o.jsx(Zs,{type:"secondary",style:{display:"block",padding:"6px 8px 8px",fontSize:n.fontSizeSM},children:"Diff truncated for display."})]})]},S.filePath)})})]})})})},aE=e=>{if(!e)return;const{activeLeafId:t,setLeafSessionId:n,setActiveLeafId:s}=wt.getState();n(t,e),s(t),te.getState().selectSession(e)},iE=["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(" "),lE=["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(" "),cE=["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(" "),dE=["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(" "),uE=["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(" "),mE=["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(" "),hE=["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(" "),pE=["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(" "),fE=["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(" "),gE=["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(" "),yE=["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(" "),bE=["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(" "),xE=["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(" "),vE=["development","debugging","analysis","documentation","operations"],SE={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"}},wE=(e,t)=>{const n=e.find(r=>r.id===t),s=e.find(r=>r.id==="general_assistant")||e[0];return{systemPromptId:(n==null?void 0:n.id)||(s==null?void 0:s.id)||"",baseSystemPrompt:(n==null?void 0:n.content)||(s==null?void 0:s.content)||""}},Px=({sessionId:e=null,embedded:t=!1,hideHeader:n=!1,layoutMode:s="default"})=>{var R;const{t:r}=Ie(),{token:a}=Ge.useToken(),{message:i}=sn.useApp(),l=te(I=>e??I.currentSessionId),c=te(Er(l)),u=te(I=>I.addChat),m=te(I=>I.lastSelectedPromptId),f=te(I=>I.setInputContent),g=te(I=>I.systemPrompts),b=te(I=>I.chats),[S,x]=p.useState(null),[T,j]=p.useState(""),w=(c==null?void 0:c.config.workspacePath)??((R=b.find(I=>I.config.workspacePath))==null?void 0:R.config.workspacePath),M=p.useMemo(()=>[{id:"blank",icon:o.jsx(rr,{}),title:r("chat.emptyLauncher.actions.blank.title","Blank session"),description:r("chat.emptyLauncher.actions.blank.description","Start from scratch with the default assistant and an empty composer."),sessionTitle:r("chat.emptyLauncher.actions.blank.sessionTitle","New Session"),prefill:r("chat.emptyLauncher.actions.blank.prefill",""),category:"development"},{id:"codeReview",icon:o.jsx(Bc,{}),title:r("chat.emptyLauncher.actions.codeReview.title","Code review"),description:r("chat.emptyLauncher.actions.codeReview.description","Open a review-focused session with an editable review brief."),sessionTitle:r("chat.emptyLauncher.actions.codeReview.sessionTitle","Code Review"),prefill:r("chat.emptyLauncher.actions.codeReview.prefill","Review the relevant code changes in this workspace or repository. Start with the overall scope, then list risks, notable diffs, and the most important fixes."),baseSystemPrompt:iE,category:"development",recommendWorkspace:!0},{id:"implementFeature",icon:o.jsx(Ui,{}),title:r("chat.emptyLauncher.actions.implementFeature.title","Implement feature"),description:r("chat.emptyLauncher.actions.implementFeature.description","Plan and build a feature step by step following existing code conventions."),sessionTitle:r("chat.emptyLauncher.actions.implementFeature.sessionTitle","Implement Feature"),prefill:r("chat.emptyLauncher.actions.implementFeature.prefill","Help me implement a new feature in this workspace. Start by understanding the codebase structure, then propose an implementation plan before writing code."),baseSystemPrompt:cE,category:"development",recommendWorkspace:!0},{id:"refactor",icon:o.jsx(bb,{}),title:r("chat.emptyLauncher.actions.refactor.title","Refactor code"),description:r("chat.emptyLauncher.actions.refactor.description","Get targeted suggestions for improving code quality and maintainability."),sessionTitle:r("chat.emptyLauncher.actions.refactor.sessionTitle","Refactor Suggestion"),prefill:r("chat.emptyLauncher.actions.refactor.prefill","Suggest refactoring improvements for the code in this workspace. Focus on readability, maintainability, and performance. Propose incremental changes with clear rationale."),baseSystemPrompt:hE,category:"development",recommendWorkspace:!0},{id:"bugInvestigation",icon:o.jsx(gb,{}),title:r("chat.emptyLauncher.actions.bugInvestigation.title","Bug investigation"),description:r("chat.emptyLauncher.actions.bugInvestigation.description","Diagnose issues by analyzing code, logs, and runtime behavior."),sessionTitle:r("chat.emptyLauncher.actions.bugInvestigation.sessionTitle","Bug Investigation"),prefill:r("chat.emptyLauncher.actions.bugInvestigation.prefill","Help me investigate a bug. I'll describe the symptoms and share relevant code or logs. Trace the root cause and suggest targeted fixes."),baseSystemPrompt:lE,category:"debugging",recommendWorkspace:!0},{id:"explainError",icon:o.jsx(Cm,{}),title:r("chat.emptyLauncher.actions.explainError.title","Explain error"),description:r("chat.emptyLauncher.actions.explainError.description","Understand what went wrong from an error message or stack trace."),sessionTitle:r("chat.emptyLauncher.actions.explainError.sessionTitle","Explain Error"),prefill:r("chat.emptyLauncher.actions.explainError.prefill","Help me understand the following error. Explain the root cause, suggest fixes, and share prevention tips."),baseSystemPrompt:uE,category:"debugging"},{id:"tokenUsage",icon:o.jsx(Jw,{}),title:r("chat.emptyLauncher.actions.tokenUsage.title","Token usage investigation"),description:r("chat.emptyLauncher.actions.tokenUsage.description","Diagnose context growth, truncation risk, and token budget pressure."),sessionTitle:r("chat.emptyLauncher.actions.tokenUsage.sessionTitle","Token Usage Investigation"),prefill:r("chat.emptyLauncher.actions.tokenUsage.prefill","Help me investigate token usage, context growth, and truncation risk for this session or workflow. Summarize the likely drivers and recommend concrete next fixes."),baseSystemPrompt:xE,category:"debugging"},{id:"architectureReview",icon:o.jsx(Qw,{}),title:r("chat.emptyLauncher.actions.architectureReview.title","Read repo architecture"),description:r("chat.emptyLauncher.actions.architectureReview.description","Analyze repository structure, modules, and architectural patterns."),sessionTitle:r("chat.emptyLauncher.actions.architectureReview.sessionTitle","Architecture Review"),prefill:r("chat.emptyLauncher.actions.architectureReview.prefill","Analyze the architecture of this repository. Map the key modules, data flow, abstractions, and dependency patterns. Identify strengths and potential improvements."),baseSystemPrompt:dE,category:"analysis",recommendWorkspace:!0},{id:"compareFiles",icon:o.jsx(Zw,{}),title:r("chat.emptyLauncher.actions.compareFiles.title","Compare files"),description:r("chat.emptyLauncher.actions.compareFiles.description","Diff and understand differences between files or code sections."),sessionTitle:r("chat.emptyLauncher.actions.compareFiles.sessionTitle","Compare Files"),prefill:r("chat.emptyLauncher.actions.compareFiles.prefill","Compare the following files or code sections. Highlight key differences, their implications, and any potential risks."),baseSystemPrompt:mE,category:"analysis",recommendWorkspace:!0},{id:"releaseNotes",icon:o.jsx(qo,{}),title:r("chat.emptyLauncher.actions.releaseNotes.title","Generate release notes"),description:r("chat.emptyLauncher.actions.releaseNotes.description","Create structured release notes from git history and code changes."),sessionTitle:r("chat.emptyLauncher.actions.releaseNotes.sessionTitle","Release Notes"),prefill:r("chat.emptyLauncher.actions.releaseNotes.prefill","Generate release notes for the latest changes in this workspace. Categorize into features, fixes, improvements, and breaking changes."),baseSystemPrompt:pE,category:"documentation",recommendWorkspace:!0},{id:"summarizeWork",icon:o.jsx(e_,{}),title:r("chat.emptyLauncher.actions.summarizeWork.title","Summarize work"),description:r("chat.emptyLauncher.actions.summarizeWork.description","Create a work summary for standups or weekly status reports."),sessionTitle:r("chat.emptyLauncher.actions.summarizeWork.sessionTitle","Work Summary"),prefill:r("chat.emptyLauncher.actions.summarizeWork.prefill","Help me summarize my recent work for a status update. Pull key accomplishments, blockers, and next steps."),baseSystemPrompt:fE,category:"documentation"},{id:"writeDocs",icon:o.jsx(qo,{}),title:r("chat.emptyLauncher.actions.writeDocs.title","Write documentation"),description:r("chat.emptyLauncher.actions.writeDocs.description","Create or improve technical documentation from code and context."),sessionTitle:r("chat.emptyLauncher.actions.writeDocs.sessionTitle","Write Documentation"),prefill:r("chat.emptyLauncher.actions.writeDocs.prefill","Help me write technical documentation for this project. Analyze the code and produce clear, well-structured Markdown documentation."),baseSystemPrompt:gE,category:"documentation",recommendWorkspace:!0},{id:"createSchedule",icon:o.jsx(As,{}),title:r("chat.emptyLauncher.actions.createSchedule.title","Create scheduled task"),description:r("chat.emptyLauncher.actions.createSchedule.description","Set up a recurring task that runs automatically on a schedule."),sessionTitle:r("chat.emptyLauncher.actions.createSchedule.sessionTitle","Create Schedule"),prefill:r("chat.emptyLauncher.actions.createSchedule.prefill","Help me set up a recurring scheduled task. I'll describe what I want it to do, and you guide me through the configuration."),baseSystemPrompt:yE,category:"operations"},{id:"sessionReview",icon:o.jsx($i,{}),title:r("chat.emptyLauncher.actions.sessionReview.title","Review session history"),description:r("chat.emptyLauncher.actions.sessionReview.description","Inspect and analyze past sessions for patterns and insights."),sessionTitle:r("chat.emptyLauncher.actions.sessionReview.sessionTitle","Session Review"),prefill:r("chat.emptyLauncher.actions.sessionReview.prefill","Help me review my recent session history. Summarize key decisions, outcomes, and areas that need follow-up."),baseSystemPrompt:bE,category:"operations"}],[r]),_=T.trim().toLowerCase(),C=p.useMemo(()=>_?M.filter(I=>I.title.toLowerCase().includes(_)||I.description.toLowerCase().includes(_)):M,[_,M]),L=p.useMemo(()=>{const I={};for(const $ of C)I[$.category]||(I[$.category]=[]),I[$.category].push($);return I},[C]),A=p.useCallback(I=>{typeof window>"u"||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent(Qu,{detail:{sessionId:I}}))},0)},[]),B=p.useCallback(async I=>{if(!S){x(I.id);try{const $=wE(g,m),U=await u({title:I.sessionTitle,createdAt:Date.now(),messages:[],config:{systemPromptId:$.systemPromptId,baseSystemPrompt:I.baseSystemPrompt??$.baseSystemPrompt,lastUsedEnhancedPrompt:null,...w?{workspacePath:w}:{}}});aE(U),I.prefill.trim().length>0&&f(U,I.prefill),A(U)}catch($){console.error("[EmptyTaskLauncher] Failed to create session",$),i.error($ instanceof Error?$.message:r("chat.emptyLauncher.errors.createFailed","Failed to create session"))}finally{x(null)}}},[u,m,i,S,A,f,g,r,w]),N=p.useMemo(()=>({"--lotus-empty-launcher-border":a.colorBorderSecondary,"--lotus-empty-launcher-border-hover":a.colorPrimaryBorder,"--lotus-empty-launcher-bg":a.colorBgElevated,"--lotus-empty-launcher-icon-bg":a.colorPrimaryBg,"--lotus-empty-launcher-icon-color":a.colorPrimary,"--lotus-empty-launcher-text":a.colorText,"--lotus-empty-launcher-text-secondary":a.colorTextSecondary,"--lotus-empty-launcher-shadow":a.boxShadowSecondary,"--lotus-empty-launcher-shadow-hover":a.boxShadow,"--lotus-empty-launcher-category-border":a.colorBorderSecondary,"--lotus-empty-launcher-search-bg":a.colorBgContainer,"--lotus-empty-launcher-badge-bg":a.colorPrimaryBg,"--lotus-empty-launcher-badge-text":a.colorPrimary}),[a]),O=!!w;return o.jsxs("div",{className:`lotus-empty-task-launcher ${t?"is-embedded":""} ${n?"is-headerless":""} ${s==="staggered"?"is-staggered":""}`,style:N,children:[!n&&o.jsxs("div",{className:"lotus-empty-task-launcher__header",children:[o.jsx(He.Title,{level:t?4:3,style:{margin:0},children:r("chat.emptyLauncher.title","Start with a task")}),o.jsx(He.Paragraph,{type:"secondary",className:"lotus-empty-task-launcher__subtitle",children:r("chat.emptyLauncher.subtitle","Create a focused session in this pane and prefill the first message before you send it.")}),o.jsx(He.Text,{type:"secondary",className:"lotus-empty-task-launcher__hint",children:r("chat.emptyLauncher.hint","Nothing is sent automatically — you can edit the prompt first.")})]}),o.jsx("div",{className:"lotus-empty-task-launcher__search",children:o.jsx(Qe,{placeholder:r("chat.emptyLauncher.searchPlaceholder","Search templates..."),prefix:o.jsx($i,{style:{color:a.colorTextQuaternary}}),value:T,onChange:I=>j(I.target.value),allowClear:!0,size:"middle",variant:"filled"})}),o.jsxs("div",{className:"lotus-empty-task-launcher__categories",children:[vE.map(I=>{const $=L[I];if(!$||$.length===0)return null;const U=SE[I];return o.jsxs("div",{className:"lotus-empty-task-launcher__category",children:[o.jsx(He.Text,{type:"secondary",className:"lotus-empty-task-launcher__category-label",children:r(U.titleKey,U.fallback)}),o.jsx("div",{className:"lotus-empty-task-launcher__grid",children:$.map(q=>{const K=S===q.id,P=q.recommendWorkspace&&O;return o.jsxs("button",{type:"button",className:"lotus-empty-task-card",onClick:()=>{B(q)},disabled:S!==null,"aria-busy":K,"aria-label":q.title,children:[o.jsx("div",{className:"lotus-empty-task-card__icon","aria-hidden":!0,children:K?o.jsx(io,{}):q.icon}),o.jsxs("div",{className:"lotus-empty-task-card__body",children:[o.jsxs("div",{className:"lotus-empty-task-card__titleRow",children:[o.jsx("span",{className:"lotus-empty-task-card__title",children:q.title}),o.jsx(t_,{className:"lotus-empty-task-card__arrow","aria-hidden":!0})]}),o.jsx("p",{className:"lotus-empty-task-card__description",children:q.description}),P&&o.jsx("div",{className:"lotus-empty-task-card__badges",children:o.jsxs("span",{className:"lotus-empty-task-card__badge",title:w,children:["📂 ",r("chat.emptyLauncher.badges.workspace","workspace")]})})]})]},q.id)})})]},I)}),C.length===0&&o.jsx("div",{className:"lotus-empty-task-launcher__no-results",children:o.jsx(He.Text,{type:"secondary",children:r("chat.emptyLauncher.noResults","No templates match your search. Try a different keyword or start a blank session.")})})]})]})},_E=({sessionId:e,isCenteredLayout:t,maxWidth:n,onWorkflowDraftChange:s,showMessagesView:r,sessionDiffSummary:a,contextUsageIndicator:i})=>o.jsx(be,{justify:"center",className:`chat-view-input-container-wrapper ${r?"messages-view":"centered-view"}`,children:o.jsxs("div",{style:{width:"100%",maxWidth:r?n:"min(100%, 920px)",margin:r?"0 auto":void 0,position:"relative",paddingBottom:r?12:0,display:"flex",flexDirection:"column",gap:r?0:24},children:[r&&o.jsx(oE,{sessionDiffSummary:a,sessionId:e}),!r&&e&&o.jsx(Px,{sessionId:e}),o.jsx(eE,{sessionId:e,isCenteredLayout:t,onWorkflowDraftChange:s,statusIndicator:i})]})});function To(e,t,n){let s=n.initialDeps??[],r;function a(){var i,l,c,u;let m;n.key&&((i=n.debug)!=null&&i.call(n))&&(m=Date.now());const f=e();if(!(f.length!==s.length||f.some((S,x)=>s[x]!==S)))return r;s=f;let b;if(n.key&&((l=n.debug)!=null&&l.call(n))&&(b=Date.now()),r=t(...f),n.key&&((c=n.debug)!=null&&c.call(n))){const S=Math.round((Date.now()-m)*100)/100,x=Math.round((Date.now()-b)*100)/100,T=x/16,j=(w,M)=>{for(w=String(w);w.length<M;)w=" "+w;return w};console.info(`%c⏱ ${j(x,5)} /${j(S,5)} ms`,`
|
|
152
|
+
font-size: .6rem;
|
|
153
|
+
font-weight: bold;
|
|
154
|
+
color: hsl(${Math.max(0,Math.min(120-120*T,120))}deg 100% 31%);`,n==null?void 0:n.key)}return(u=n==null?void 0:n.onChange)==null||u.call(n,r),r}return a.updateDeps=i=>{s=i},a}function Bf(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const kE=(e,t)=>Math.abs(e-t)<1.01,TE=(e,t,n)=>{let s;return function(...r){e.clearTimeout(s),s=e.setTimeout(()=>t.apply(this,r),n)}},Wf=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},jE=e=>e,CE=e=>{const t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1),s=[];for(let r=t;r<=n;r++)s.push(r);return s},ME=(e,t)=>{const n=e.scrollElement;if(!n)return;const s=e.targetWindow;if(!s)return;const r=i=>{const{width:l,height:c}=i;t({width:Math.round(l),height:Math.round(c)})};if(r(Wf(n)),!s.ResizeObserver)return()=>{};const a=new s.ResizeObserver(i=>{const l=()=>{const c=i[0];if(c!=null&&c.borderBoxSize){const u=c.borderBoxSize[0];if(u){r({width:u.inlineSize,height:u.blockSize});return}}r(Wf(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(n,{box:"border-box"}),()=>{a.unobserve(n)}},qf={passive:!0},Uf=typeof window>"u"?!0:"onscrollend"in window,PE=(e,t)=>{const n=e.scrollElement;if(!n)return;const s=e.targetWindow;if(!s)return;let r=0;const a=e.options.useScrollendEvent&&Uf?()=>{}:TE(s,()=>{t(r,!1)},e.options.isScrollingResetDelay),i=m=>()=>{const{horizontal:f,isRtl:g}=e.options;r=f?n.scrollLeft*(g&&-1||1):n.scrollTop,a(),t(r,m)},l=i(!0),c=i(!1);c(),n.addEventListener("scroll",l,qf);const u=e.options.useScrollendEvent&&Uf;return u&&n.addEventListener("scrollend",c,qf),()=>{n.removeEventListener("scroll",l),u&&n.removeEventListener("scrollend",c)}},EE=(e,t,n)=>{if(t!=null&&t.borderBoxSize){const s=t.borderBoxSize[0];if(s)return Math.round(s[n.options.horizontal?"inlineSize":"blockSize"])}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},RE=(e,{adjustments:t=0,behavior:n},s)=>{var r,a;const i=e+t;(a=(r=s.scrollElement)==null?void 0:r.scrollTo)==null||a.call(r,{[s.options.horizontal?"left":"top"]:i,behavior:n})};class AE{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.measurementsCache=[],this.itemSizeCache=new Map,this.pendingMeasuredCacheIndexes=[],this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.observer=(()=>{let n=null;const s=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(r=>{r.forEach(a=>{const i=()=>{this._measureElement(a.target,a)};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var r;(r=s())==null||r.disconnect(),n=null},observe:r=>{var a;return(a=s())==null?void 0:a.observe(r,{box:"border-box"})},unobserve:r=>{var a;return(a=s())==null?void 0:a.unobserve(r)}}})(),this.range=null,this.setOptions=n=>{Object.entries(n).forEach(([s,r])=>{typeof r>"u"&&delete n[s]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:jE,rangeExtractor:CE,onChange:()=>{},measureElement:EE,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,...n}},this.notify=n=>{var s,r;(r=(s=this.options).onChange)==null||r.call(s,this,n)},this.maybeNotify=To(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const s=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==s){if(this.cleanup(),!s){this.maybeNotify();return}this.scrollElement=s,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(r=>{this.observer.observe(r)}),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0}),this.unsubs.push(this.options.observeElementRect(this,r=>{this.scrollRect=r,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(r,a)=>{this.scrollAdjustments=0,this.scrollDirection=a?this.getScrollOffset()<r?"forward":"backward":null,this.scrollOffset=r,this.isScrolling=a,this.maybeNotify()}))}},this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(n,s)=>{const r=new Map,a=new Map;for(let i=s-1;i>=0;i--){const l=n[i];if(r.has(l.lane))continue;const c=a.get(l.lane);if(c==null||l.end>c.end?a.set(l.lane,l):l.end<c.end&&r.set(l.lane,!0),r.size===this.options.lanes)break}return a.size===this.options.lanes?Array.from(a.values()).sort((i,l)=>i.end===l.end?i.index-l.index:i.end-l.end)[0]:void 0},this.getMeasurementOptions=To(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled],(n,s,r,a,i)=>(this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:s,scrollMargin:r,getItemKey:a,enabled:i}),{key:!1}),this.getMeasurements=To(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:s,scrollMargin:r,getItemKey:a,enabled:i},l)=>{if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),[];this.measurementsCache.length===0&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(m=>{this.itemSizeCache.set(m.key,m.size)}));const c=this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[];const u=this.measurementsCache.slice(0,c);for(let m=c;m<n;m++){const f=a(m),g=this.options.lanes===1?u[m-1]:this.getFurthestMeasurement(u,m),b=g?g.end+this.options.gap:s+r,S=l.get(f),x=typeof S=="number"?S:this.options.estimateSize(m),T=b+x,j=g?g.lane:m%this.options.lanes;u[m]={index:m,start:b,size:x,end:T,key:f,lane:j}}return this.measurementsCache=u,u},{key:!1,debug:()=>this.options.debug}),this.calculateRange=To(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,s,r,a)=>this.range=n.length>0&&s>0?IE({measurements:n,outerSize:s,scrollOffset:r,lanes:a}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=To(()=>{let n=null,s=null;const r=this.calculateRange();return r&&(n=r.startIndex,s=r.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,s]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,s]},(n,s,r,a,i)=>a===null||i===null?[]:n({startIndex:a,endIndex:i,overscan:s,count:r}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const s=this.options.indexAttribute,r=n.getAttribute(s);return r?parseInt(r,10):(console.warn(`Missing attribute name '${s}={index}' on measured element.`),-1)},this._measureElement=(n,s)=>{const r=this.indexFromElement(n),a=this.measurementsCache[r];if(!a)return;const i=a.key,l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),n.isConnected&&this.resizeItem(r,this.options.measureElement(n,s,this))},this.resizeItem=(n,s)=>{const r=this.measurementsCache[n];if(!r)return;const a=this.itemSizeCache.get(r.key)??r.size,i=s-a;i!==0&&((this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(r,i,this):r.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=i,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(r.index),this.itemSizeCache=new Map(this.itemSizeCache.set(r.key,s)),this.notify(!1))},this.measureElement=n=>{if(!n){this.elementsCache.forEach((s,r)=>{s.isConnected||(this.observer.unobserve(s),this.elementsCache.delete(r))});return}this._measureElement(n,void 0)},this.getVirtualItems=To(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,s)=>{const r=[];for(let a=0,i=n.length;a<i;a++){const l=n[a],c=s[l];r.push(c)}return r},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const s=this.getMeasurements();if(s.length!==0)return Bf(s[Ex(0,s.length-1,r=>Bf(s[r]).start,n)])},this.getOffsetForAlignment=(n,s,r=0)=>{const a=this.getSize(),i=this.getScrollOffset();s==="auto"&&(s=n>=i+a?"end":"start"),s==="center"?n+=(r-a)/2:s==="end"&&(n-=a);const l=this.getTotalSize()+this.options.scrollMargin-a;return Math.max(Math.min(l,n),0)},this.getOffsetForIndex=(n,s="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const r=this.measurementsCache[n];if(!r)return;const a=this.getSize(),i=this.getScrollOffset();if(s==="auto")if(r.end>=i+a-this.options.scrollPaddingEnd)s="end";else if(r.start<=i+this.options.scrollPaddingStart)s="start";else return[i,s];const l=s==="end"?r.end+this.options.scrollPaddingEnd:r.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,s,r.size),s]},this.isDynamicMode=()=>this.elementsCache.size>0,this.scrollToOffset=(n,{align:s="start",behavior:r}={})=>{r==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getOffsetForAlignment(n,s),{adjustments:void 0,behavior:r})},this.scrollToIndex=(n,{align:s="auto",behavior:r}={})=>{r==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),n=Math.max(0,Math.min(n,this.options.count-1));let a=0;const i=10,l=u=>{if(!this.targetWindow)return;const m=this.getOffsetForIndex(n,u);if(!m){console.warn("Failed to get offset for index:",n);return}const[f,g]=m;this._scrollToOffset(f,{adjustments:void 0,behavior:r}),this.targetWindow.requestAnimationFrame(()=>{const b=this.getScrollOffset(),S=this.getOffsetForIndex(n,g);if(!S){console.warn("Failed to get offset for index:",n);return}kE(S[0],b)||c(g)})},c=u=>{this.targetWindow&&(a++,a<i?this.targetWindow.requestAnimationFrame(()=>l(u)):console.warn(`Failed to scroll to index ${n} after ${i} attempts.`))};l(s)},this.scrollBy=(n,{behavior:s}={})=>{s==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getScrollOffset()+n,{adjustments:void 0,behavior:s})},this.getTotalSize=()=>{var n;const s=this.getMeasurements();let r;if(s.length===0)r=this.options.paddingStart;else if(this.options.lanes===1)r=((n=s[s.length-1])==null?void 0:n.end)??0;else{const a=Array(this.options.lanes).fill(null);let i=s.length-1;for(;i>=0&&a.some(l=>l===null);){const l=s[i];a[l.lane]===null&&(a[l.lane]=l.end),i--}r=Math.max(...a.filter(l=>l!==null))}return Math.max(r-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(n,{adjustments:s,behavior:r})=>{this.options.scrollToFn(n,{behavior:r,adjustments:s},this)},this.measure=()=>{this.itemSizeCache=new Map,this.notify(!1)},this.setOptions(t)}}const Ex=(e,t,n,s)=>{for(;e<=t;){const r=(e+t)/2|0,a=n(r);if(a<s)e=r+1;else if(a>s)t=r-1;else return r}return e>0?e-1:0};function IE({measurements:e,outerSize:t,scrollOffset:n,lanes:s}){const r=e.length-1,a=c=>e[c].start;if(e.length<=s)return{startIndex:0,endIndex:r};let i=Ex(0,r,a,n),l=i;if(s===1)for(;l<r&&e[l].end<n+t;)l++;else if(s>1){const c=Array(s).fill(0);for(;l<r&&c.some(m=>m<n+t);){const m=e[l];c[m.lane]=m.end,l++}const u=Array(s).fill(n+t);for(;i>=0&&u.some(m=>m>=n);){const m=e[i];u[m.lane]=m.start,i--}i=Math.max(0,i-i%s),l=Math.min(r,l+(s-1-l%s))}return{startIndex:i,endIndex:l}}const Hf=typeof document<"u"?p.useLayoutEffect:p.useEffect;function OE(e){const t=p.useReducer(()=>({}),{})[1],n={...e,onChange:(r,a)=>{var i;a?n_.flushSync(t):t(),(i=e.onChange)==null||i.call(e,r,a)}},[s]=p.useState(()=>new AE(n));return s.setOptions(n),Hf(()=>s._didMount(),[]),Hf(()=>s._willUpdate()),s}function $E(e){return OE({observeElementRect:ME,observeElementOffset:PE,scrollToFn:RE,...e})}const{Text:Kf,Paragraph:DE}=He,LE=({content:e,token:t,headingColor:n})=>o.jsx(Ps,{components:{p:({children:s})=>o.jsx(DE,{style:{marginBottom:t.marginSM},children:s}),ol:({children:s})=>o.jsx("ol",{style:{marginBottom:t.marginSM,paddingLeft:20},children:s}),ul:({children:s})=>o.jsx("ul",{style:{marginBottom:t.marginSM,paddingLeft:20},children:s}),li:({children:s})=>o.jsx("li",{style:{marginBottom:t.marginXS},children:s}),h1:({children:s})=>o.jsx(Kf,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block",color:n},children:s}),h2:({children:s})=>o.jsx(Kf,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block",color:n},children:s})},children:e}),Vf=p.memo(LE),FE=e=>{if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null},NE=e=>e?[["base",e.base_system_prompt],["enhancement",e.enhancement_prompt],["workspace",e.workspace_context],["instruction",e.instruction_context],["env",e.env_context],["skills",e.skill_context],["toolGuide",e.tool_guide_context],["dream",e.dream_notebook],["sessionMemory",e.session_memory_note],["externalMemory",e.external_memory],["taskList",e.task_list],["effective",e.effective_system_prompt]].flatMap(([n,s])=>{const r=FE(s);return r?[{key:n,content:r}]:[]}):[],zE=({currentChat:e,message:t,systemPrompts:n})=>{var O;const[s,r]=p.useState(null),[a,i]=p.useState(null),[l,c]=p.useState(null),[u,m]=p.useState(!1),[f,g]=p.useState(!1),b=p.useMemo(()=>xc.getInstance(),[]),S=p.useMemo(()=>Jn.getInstance(),[]),x=t.role==="system"&&typeof t.content=="string"?t.content:"",T=t.role==="system"&&!t.id.startsWith("system-prompt-")&&x.trim().length>0;p.useEffect(()=>{t.role==="system"&&(i(null),c(null),g(!1))},[t.id,t.role,x]);const j=(e==null?void 0:e.id)??null,w=((O=e==null?void 0:e.config)==null?void 0:O.systemPromptId)??null,M=p.useMemo(()=>w?n.find(R=>R.id===w)??null:null,[w,n]),_=(M==null?void 0:M.content)??(s==null?void 0:s.content)??"",C=(M==null?void 0:M.description)??(s==null?void 0:s.description)??"",L=p.useRef(null);p.useEffect(()=>{r(null),L.current=null},[j,w]),p.useEffect(()=>{if(!w)return;const R=w;if(M!=null&&M.content)return;const I=`${j??"no-chat"}:${R}`;if(L.current===I)return;L.current=I;let $=!1;return(async()=>{try{const q=await b.findPresetById(R);if($)return;const K=q?{content:q.content,description:q.description}:null;r(P=>!P&&!K||P&&K&&P.content===K.content&&P.description===K.description?P:K)}catch(q){console.error("Failed to load preset prompt:",q)}})(),()=>{$=!0}},[j,w,b,M==null?void 0:M.content]);const A=p.useCallback(async()=>{var R;if(!u){m(!0);try{if(j)try{const I=await S.getSessionSystemPrompt(j);c(I);const $=(R=I.effective_system_prompt)==null?void 0:R.trim();if($){i($),g(!0);return}}catch(I){console.warn("Failed to load backend prompt snapshot:",I)}if(T){c(null),i(x),g(!0);return}console.warn("Enhanced prompt snapshot unavailable; keeping base prompt view.")}catch(I){console.error("Failed to load enhanced prompt:",I)}finally{m(!1)}}},[S,j,T,u,x]),B=p.useMemo(()=>f&&a?a:_||C||(t.role==="system"?x:"System prompt is being prepared..."),[f,a,_,C,t.role,x]),N=p.useMemo(()=>NE(l),[l]);return{basePrompt:_,categoryDescription:C,enhancedPrompt:a,loadingEnhanced:u,loadEnhancedPrompt:A,promptSnapshot:l,promptToDisplay:B,showEnhanced:f,setShowEnhanced:g,snapshotSections:N,systemMessageContent:x}},{Text:Yf}=He,{useToken:BE}=Ge,WE=(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],qE=({currentChat:e,message:t})=>{const{token:n}=BE(),{t:s}=Ie(),r=te(S=>S.systemPrompts),{basePrompt:a,loadingEnhanced:i,loadEnhancedPrompt:l,promptSnapshot:c,promptToDisplay:u,showEnhanced:m,setShowEnhanced:f,snapshotSections:g}=zE({currentChat:e,message:t,systemPrompts:r}),b=p.useCallback(async S=>{try{await vs(S)}catch(x){console.error("Failed to copy text:",x)}},[]);return o.jsx(Ce,{style:{width:"100%",maxWidth:"100%",background:n.colorBgContainer,borderRadius:n.borderRadiusLG,boxShadow:"none"},children:o.jsxs(he,{direction:"vertical",size:n.marginSM,style:{width:"100%"},children:[o.jsxs(be,{justify:"space-between",align:"center",children:[o.jsx(be,{align:"center",gap:n.marginXS,children:o.jsx(Yf,{type:"secondary",strong:!0,style:{fontSize:n.fontSizeSM},children:s("chat.prompt.systemCard.title")})}),o.jsxs(he,{children:[a&&!m?o.jsx(ue,{type:"text",size:"small",icon:o.jsx(Fc,{}),onClick:l,loading:i,children:s("chat.prompt.systemCard.viewEnhanced")}):null,a&&m?o.jsx(ue,{type:"text",size:"small",onClick:()=>f(!1),children:s("chat.prompt.systemCard.viewBase")}):null,o.jsx(ue,{type:"text",size:"small",icon:o.jsx(xs,{}),onClick:()=>b(u),children:s("chat.prompt.systemCard.copy")})]})]}),o.jsx(be,{vertical:!0,style:{maxHeight:m?400:300,overflowY:"auto",paddingRight:n.paddingXS},children:o.jsx(Vf,{content:u,token:n,headingColor:n.colorPrimary})}),c&&g.length>0?o.jsxs(o.Fragment,{children:[o.jsx(zn,{style:{margin:`${n.marginXS}px 0`}}),o.jsxs(he,{direction:"vertical",size:n.marginXS,style:{width:"100%"},children:[o.jsx(Yf,{type:"secondary",strong:!0,style:{fontSize:n.fontSizeSM},children:s("chat.prompt.systemCard.snapshotTitle")}),o.jsx(ir,{defaultActiveKey:g.map(S=>S.key),items:g.map(S=>({key:S.key,label:WE(s,S.key),children:o.jsx(Vf,{content:S.content,token:n,headingColor:n.colorPrimary})}))})]})]}):null]})})},Rx=p.memo(qE);Rx.displayName="SystemMessageCard";const Ax=6048e5,UE=864e5,Xf=Symbol.for("constructDateFrom");function Tr(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&Xf in e?e[Xf](t):e instanceof Date?new e.constructor(t):new Date(t)}function Os(e,t){return Tr(t||e,e)}let HE={};function Vc(){return HE}function Wi(e,t){var l,c,u,m;const n=Vc(),s=(t==null?void 0:t.weekStartsOn)??((c=(l=t==null?void 0:t.locale)==null?void 0:l.options)==null?void 0:c.weekStartsOn)??n.weekStartsOn??((m=(u=n.locale)==null?void 0:u.options)==null?void 0:m.weekStartsOn)??0,r=Os(e,t==null?void 0:t.in),a=r.getDay(),i=(a<s?7:0)+a-s;return r.setDate(r.getDate()-i),r.setHours(0,0,0,0),r}function Cc(e,t){return Wi(e,{...t,weekStartsOn:1})}function Ix(e,t){const n=Os(e,t==null?void 0:t.in),s=n.getFullYear(),r=Tr(n,0);r.setFullYear(s+1,0,4),r.setHours(0,0,0,0);const a=Cc(r),i=Tr(n,0);i.setFullYear(s,0,4),i.setHours(0,0,0,0);const l=Cc(i);return n.getTime()>=a.getTime()?s+1:n.getTime()>=l.getTime()?s:s-1}function Gf(e){const t=Os(e),n=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return n.setUTCFullYear(t.getFullYear()),+e-+n}function KE(e,...t){const n=Tr.bind(null,t.find(s=>typeof s=="object"));return t.map(n)}function Jf(e,t){const n=Os(e,t==null?void 0:t.in);return n.setHours(0,0,0,0),n}function VE(e,t,n){const[s,r]=KE(n==null?void 0:n.in,e,t),a=Jf(s),i=Jf(r),l=+a-Gf(a),c=+i-Gf(i);return Math.round((l-c)/UE)}function YE(e,t){const n=Ix(e,t),s=Tr(e,0);return s.setFullYear(n,0,4),s.setHours(0,0,0,0),Cc(s)}function XE(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function GE(e){return!(!XE(e)&&typeof e!="number"||isNaN(+Os(e)))}function JE(e,t){const n=Os(e,t==null?void 0:t.in);return n.setFullYear(n.getFullYear(),0,1),n.setHours(0,0,0,0),n}const QE={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"}},ZE=(e,t,n)=>{let s;const r=QE[e];return typeof r=="string"?s=r:t===1?s=r.one:s=r.other.replace("{{count}}",t.toString()),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"in "+s:s+" ago":s};function Yd(e){return(t={})=>{const n=t.width?String(t.width):e.defaultWidth;return e.formats[n]||e.formats[e.defaultWidth]}}const e1={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},t1={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},n1={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},s1={date:Yd({formats:e1,defaultWidth:"full"}),time:Yd({formats:t1,defaultWidth:"full"}),dateTime:Yd({formats:n1,defaultWidth:"full"})},r1={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},o1=(e,t,n,s)=>r1[e];function Ta(e){return(t,n)=>{const s=n!=null&&n.context?String(n.context):"standalone";let r;if(s==="formatting"&&e.formattingValues){const i=e.defaultFormattingWidth||e.defaultWidth,l=n!=null&&n.width?String(n.width):i;r=e.formattingValues[l]||e.formattingValues[i]}else{const i=e.defaultWidth,l=n!=null&&n.width?String(n.width):e.defaultWidth;r=e.values[l]||e.values[i]}const a=e.argumentCallback?e.argumentCallback(t):t;return r[a]}}const a1={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},i1={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},l1={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"]},c1={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"]},d1={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"}},u1={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"}},m1=(e,t)=>{const n=Number(e),s=n%100;if(s>20||s<10)switch(s%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},h1={ordinalNumber:m1,era:Ta({values:a1,defaultWidth:"wide"}),quarter:Ta({values:i1,defaultWidth:"wide",argumentCallback:e=>e-1}),month:Ta({values:l1,defaultWidth:"wide"}),day:Ta({values:c1,defaultWidth:"wide"}),dayPeriod:Ta({values:d1,defaultWidth:"wide",formattingValues:u1,defaultFormattingWidth:"wide"})};function ja(e){return(t,n={})=>{const s=n.width,r=s&&e.matchPatterns[s]||e.matchPatterns[e.defaultMatchWidth],a=t.match(r);if(!a)return null;const i=a[0],l=s&&e.parsePatterns[s]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(l)?f1(l,f=>f.test(i)):p1(l,f=>f.test(i));let u;u=e.valueCallback?e.valueCallback(c):c,u=n.valueCallback?n.valueCallback(u):u;const m=t.slice(i.length);return{value:u,rest:m}}}function p1(e,t){for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&t(e[n]))return n}function f1(e,t){for(let n=0;n<e.length;n++)if(t(e[n]))return n}function g1(e){return(t,n={})=>{const s=t.match(e.matchPattern);if(!s)return null;const r=s[0],a=t.match(e.parsePattern);if(!a)return null;let i=e.valueCallback?e.valueCallback(a[0]):a[0];i=n.valueCallback?n.valueCallback(i):i;const l=t.slice(r.length);return{value:i,rest:l}}}const y1=/^(\d+)(th|st|nd|rd)?/i,b1=/\d+/i,x1={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},v1={any:[/^b/i,/^(a|c)/i]},S1={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},w1={any:[/1/i,/2/i,/3/i,/4/i]},_1={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},k1={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]},T1={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},j1={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]},C1={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},M1={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}},P1={ordinalNumber:g1({matchPattern:y1,parsePattern:b1,valueCallback:e=>parseInt(e,10)}),era:ja({matchPatterns:x1,defaultMatchWidth:"wide",parsePatterns:v1,defaultParseWidth:"any"}),quarter:ja({matchPatterns:S1,defaultMatchWidth:"wide",parsePatterns:w1,defaultParseWidth:"any",valueCallback:e=>e+1}),month:ja({matchPatterns:_1,defaultMatchWidth:"wide",parsePatterns:k1,defaultParseWidth:"any"}),day:ja({matchPatterns:T1,defaultMatchWidth:"wide",parsePatterns:j1,defaultParseWidth:"any"}),dayPeriod:ja({matchPatterns:C1,defaultMatchWidth:"any",parsePatterns:M1,defaultParseWidth:"any"})},E1={code:"en-US",formatDistance:ZE,formatLong:s1,formatRelative:o1,localize:h1,match:P1,options:{weekStartsOn:0,firstWeekContainsDate:1}};function R1(e,t){const n=Os(e,t==null?void 0:t.in);return VE(n,JE(n))+1}function A1(e,t){const n=Os(e,t==null?void 0:t.in),s=+Cc(n)-+YE(n);return Math.round(s/Ax)+1}function Ox(e,t){var m,f,g,b;const n=Os(e,t==null?void 0:t.in),s=n.getFullYear(),r=Vc(),a=(t==null?void 0:t.firstWeekContainsDate)??((f=(m=t==null?void 0:t.locale)==null?void 0:m.options)==null?void 0:f.firstWeekContainsDate)??r.firstWeekContainsDate??((b=(g=r.locale)==null?void 0:g.options)==null?void 0:b.firstWeekContainsDate)??1,i=Tr((t==null?void 0:t.in)||e,0);i.setFullYear(s+1,0,a),i.setHours(0,0,0,0);const l=Wi(i,t),c=Tr((t==null?void 0:t.in)||e,0);c.setFullYear(s,0,a),c.setHours(0,0,0,0);const u=Wi(c,t);return+n>=+l?s+1:+n>=+u?s:s-1}function I1(e,t){var l,c,u,m;const n=Vc(),s=(t==null?void 0:t.firstWeekContainsDate)??((c=(l=t==null?void 0:t.locale)==null?void 0:l.options)==null?void 0:c.firstWeekContainsDate)??n.firstWeekContainsDate??((m=(u=n.locale)==null?void 0:u.options)==null?void 0:m.firstWeekContainsDate)??1,r=Ox(e,t),a=Tr((t==null?void 0:t.in)||e,0);return a.setFullYear(r,0,s),a.setHours(0,0,0,0),Wi(a,t)}function O1(e,t){const n=Os(e,t==null?void 0:t.in),s=+Wi(n,t)-+I1(n,t);return Math.round(s/Ax)+1}function Ft(e,t){const n=e<0?"-":"",s=Math.abs(e).toString().padStart(t,"0");return n+s}const yr={y(e,t){const n=e.getFullYear(),s=n>0?n:1-n;return Ft(t==="yy"?s%100:s,t.length)},M(e,t){const n=e.getMonth();return t==="M"?String(n+1):Ft(n+1,2)},d(e,t){return Ft(e.getDate(),t.length)},a(e,t){const n=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];case"aaaa":default:return n==="am"?"a.m.":"p.m."}},h(e,t){return Ft(e.getHours()%12||12,t.length)},H(e,t){return Ft(e.getHours(),t.length)},m(e,t){return Ft(e.getMinutes(),t.length)},s(e,t){return Ft(e.getSeconds(),t.length)},S(e,t){const n=t.length,s=e.getMilliseconds(),r=Math.trunc(s*Math.pow(10,n-3));return Ft(r,t.length)}},jo={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Qf={G:function(e,t,n){const s=e.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return n.era(s,{width:"abbreviated"});case"GGGGG":return n.era(s,{width:"narrow"});case"GGGG":default:return n.era(s,{width:"wide"})}},y:function(e,t,n){if(t==="yo"){const s=e.getFullYear(),r=s>0?s:1-s;return n.ordinalNumber(r,{unit:"year"})}return yr.y(e,t)},Y:function(e,t,n,s){const r=Ox(e,s),a=r>0?r:1-r;if(t==="YY"){const i=a%100;return Ft(i,2)}return t==="Yo"?n.ordinalNumber(a,{unit:"year"}):Ft(a,t.length)},R:function(e,t){const n=Ix(e);return Ft(n,t.length)},u:function(e,t){const n=e.getFullYear();return Ft(n,t.length)},Q:function(e,t,n){const s=Math.ceil((e.getMonth()+1)/3);switch(t){case"Q":return String(s);case"QQ":return Ft(s,2);case"Qo":return n.ordinalNumber(s,{unit:"quarter"});case"QQQ":return n.quarter(s,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(s,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(s,{width:"wide",context:"formatting"})}},q:function(e,t,n){const s=Math.ceil((e.getMonth()+1)/3);switch(t){case"q":return String(s);case"qq":return Ft(s,2);case"qo":return n.ordinalNumber(s,{unit:"quarter"});case"qqq":return n.quarter(s,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(s,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(s,{width:"wide",context:"standalone"})}},M:function(e,t,n){const s=e.getMonth();switch(t){case"M":case"MM":return yr.M(e,t);case"Mo":return n.ordinalNumber(s+1,{unit:"month"});case"MMM":return n.month(s,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(s,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(s,{width:"wide",context:"formatting"})}},L:function(e,t,n){const s=e.getMonth();switch(t){case"L":return String(s+1);case"LL":return Ft(s+1,2);case"Lo":return n.ordinalNumber(s+1,{unit:"month"});case"LLL":return n.month(s,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(s,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(s,{width:"wide",context:"standalone"})}},w:function(e,t,n,s){const r=O1(e,s);return t==="wo"?n.ordinalNumber(r,{unit:"week"}):Ft(r,t.length)},I:function(e,t,n){const s=A1(e);return t==="Io"?n.ordinalNumber(s,{unit:"week"}):Ft(s,t.length)},d:function(e,t,n){return t==="do"?n.ordinalNumber(e.getDate(),{unit:"date"}):yr.d(e,t)},D:function(e,t,n){const s=R1(e);return t==="Do"?n.ordinalNumber(s,{unit:"dayOfYear"}):Ft(s,t.length)},E:function(e,t,n){const s=e.getDay();switch(t){case"E":case"EE":case"EEE":return n.day(s,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(s,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(s,{width:"short",context:"formatting"});case"EEEE":default:return n.day(s,{width:"wide",context:"formatting"})}},e:function(e,t,n,s){const r=e.getDay(),a=(r-s.weekStartsOn+8)%7||7;switch(t){case"e":return String(a);case"ee":return Ft(a,2);case"eo":return n.ordinalNumber(a,{unit:"day"});case"eee":return n.day(r,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(r,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(r,{width:"short",context:"formatting"});case"eeee":default:return n.day(r,{width:"wide",context:"formatting"})}},c:function(e,t,n,s){const r=e.getDay(),a=(r-s.weekStartsOn+8)%7||7;switch(t){case"c":return String(a);case"cc":return Ft(a,t.length);case"co":return n.ordinalNumber(a,{unit:"day"});case"ccc":return n.day(r,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(r,{width:"narrow",context:"standalone"});case"cccccc":return n.day(r,{width:"short",context:"standalone"});case"cccc":default:return n.day(r,{width:"wide",context:"standalone"})}},i:function(e,t,n){const s=e.getDay(),r=s===0?7:s;switch(t){case"i":return String(r);case"ii":return Ft(r,t.length);case"io":return n.ordinalNumber(r,{unit:"day"});case"iii":return n.day(s,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(s,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(s,{width:"short",context:"formatting"});case"iiii":default:return n.day(s,{width:"wide",context:"formatting"})}},a:function(e,t,n){const r=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(r,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(r,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(r,{width:"wide",context:"formatting"})}},b:function(e,t,n){const s=e.getHours();let r;switch(s===12?r=jo.noon:s===0?r=jo.midnight:r=s/12>=1?"pm":"am",t){case"b":case"bb":return n.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(r,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(r,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(r,{width:"wide",context:"formatting"})}},B:function(e,t,n){const s=e.getHours();let r;switch(s>=17?r=jo.evening:s>=12?r=jo.afternoon:s>=4?r=jo.morning:r=jo.night,t){case"B":case"BB":case"BBB":return n.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(r,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(r,{width:"wide",context:"formatting"})}},h:function(e,t,n){if(t==="ho"){let s=e.getHours()%12;return s===0&&(s=12),n.ordinalNumber(s,{unit:"hour"})}return yr.h(e,t)},H:function(e,t,n){return t==="Ho"?n.ordinalNumber(e.getHours(),{unit:"hour"}):yr.H(e,t)},K:function(e,t,n){const s=e.getHours()%12;return t==="Ko"?n.ordinalNumber(s,{unit:"hour"}):Ft(s,t.length)},k:function(e,t,n){let s=e.getHours();return s===0&&(s=24),t==="ko"?n.ordinalNumber(s,{unit:"hour"}):Ft(s,t.length)},m:function(e,t,n){return t==="mo"?n.ordinalNumber(e.getMinutes(),{unit:"minute"}):yr.m(e,t)},s:function(e,t,n){return t==="so"?n.ordinalNumber(e.getSeconds(),{unit:"second"}):yr.s(e,t)},S:function(e,t){return yr.S(e,t)},X:function(e,t,n){const s=e.getTimezoneOffset();if(s===0)return"Z";switch(t){case"X":return eg(s);case"XXXX":case"XX":return Ur(s);case"XXXXX":case"XXX":default:return Ur(s,":")}},x:function(e,t,n){const s=e.getTimezoneOffset();switch(t){case"x":return eg(s);case"xxxx":case"xx":return Ur(s);case"xxxxx":case"xxx":default:return Ur(s,":")}},O:function(e,t,n){const s=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+Zf(s,":");case"OOOO":default:return"GMT"+Ur(s,":")}},z:function(e,t,n){const s=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+Zf(s,":");case"zzzz":default:return"GMT"+Ur(s,":")}},t:function(e,t,n){const s=Math.trunc(+e/1e3);return Ft(s,t.length)},T:function(e,t,n){return Ft(+e,t.length)}};function Zf(e,t=""){const n=e>0?"-":"+",s=Math.abs(e),r=Math.trunc(s/60),a=s%60;return a===0?n+String(r):n+String(r)+t+Ft(a,2)}function eg(e,t){return e%60===0?(e>0?"-":"+")+Ft(Math.abs(e)/60,2):Ur(e,t)}function Ur(e,t=""){const n=e>0?"-":"+",s=Math.abs(e),r=Ft(Math.trunc(s/60),2),a=Ft(s%60,2);return n+r+t+a}const tg=(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"})}},$x=(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"})}},$1=(e,t)=>{const n=e.match(/(P+)(p+)?/)||[],s=n[1],r=n[2];if(!r)return tg(e,t);let a;switch(s){case"P":a=t.dateTime({width:"short"});break;case"PP":a=t.dateTime({width:"medium"});break;case"PPP":a=t.dateTime({width:"long"});break;case"PPPP":default:a=t.dateTime({width:"full"});break}return a.replace("{{date}}",tg(s,t)).replace("{{time}}",$x(r,t))},D1={p:$x,P:$1},L1=/^D+$/,F1=/^Y+$/,N1=["D","DD","YY","YYYY"];function z1(e){return L1.test(e)}function B1(e){return F1.test(e)}function W1(e,t,n){const s=q1(e,t,n);if(console.warn(s),N1.includes(e))throw new RangeError(s)}function q1(e,t,n){const s=e[0]==="Y"?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${s} to the input \`${n}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const U1=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,H1=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,K1=/^'([^]*?)'?$/,V1=/''/g,Y1=/[a-zA-Z]/;function X1(e,t,n){var m,f,g,b;const s=Vc(),r=s.locale??E1,a=s.firstWeekContainsDate??((f=(m=s.locale)==null?void 0:m.options)==null?void 0:f.firstWeekContainsDate)??1,i=s.weekStartsOn??((b=(g=s.locale)==null?void 0:g.options)==null?void 0:b.weekStartsOn)??0,l=Os(e,n==null?void 0:n.in);if(!GE(l))throw new RangeError("Invalid time value");let c=t.match(H1).map(S=>{const x=S[0];if(x==="p"||x==="P"){const T=D1[x];return T(S,r.formatLong)}return S}).join("").match(U1).map(S=>{if(S==="''")return{isToken:!1,value:"'"};const x=S[0];if(x==="'")return{isToken:!1,value:G1(S)};if(Qf[x])return{isToken:!0,value:S};if(x.match(Y1))throw new RangeError("Format string contains an unescaped latin alphabet character `"+x+"`");return{isToken:!1,value:S}});r.localize.preprocessor&&(c=r.localize.preprocessor(l,c));const u={firstWeekContainsDate:a,weekStartsOn:i,locale:r};return c.map(S=>{if(!S.isToken)return S.value;const x=S.value;(B1(x)||z1(x))&&W1(x,t,String(e));const T=Qf[x[0]];return T(l,x,r.localize,u)}).join("")}function G1(e){const t=e.match(K1);return t?t[1].replace(V1,"'"):e}const{useToken:J1}=Ge,{Text:$l}=He,Q1=({images:e,className:t,style:n,maxHeight:s={single:400,multiple:200}})=>{const{token:r}=J1(),{t:a}=Ie();return!e||e.length===0?null:o.jsx(Ce,{className:t,style:{marginBottom:r.marginMD,...n},styles:{body:{padding:0}},variant:"borderless",children:o.jsx(be,{wrap:"wrap",gap:r.marginSM,style:{width:"100%"},children:e.map(i=>o.jsxs(Ce,{size:"small",style:{flex:e.length===1?"1 1 100%":"1 1 200px",overflow:"hidden",borderRadius:r.borderRadius,border:`1px solid ${r.colorBorderSecondary}`,backgroundColor:r.colorBgLayout},styles:{body:{padding:0}},children:[o.jsxs("div",{style:{position:"relative"},children:[o.jsx(s_,{src:i.url||i.base64,alt:i.name,style:{width:"100%",height:"auto",maxHeight:e.length===1?s.single:s.multiple,objectFit:"cover"},preview:{mask:o.jsxs(be,{align:"center",justify:"center",gap:r.marginXS,style:{color:r.colorTextLightSolid},children:[o.jsx(Fc,{}),o.jsx($l,{style:{color:r.colorTextLightSolid},children:a("components.imageGrid.preview")})]})}}),o.jsxs(be,{vertical:!0,style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(transparent, rgba(0,0,0,0.7))",color:r.colorTextLightSolid,padding:`${r.paddingXS}px ${r.paddingSM}px`,fontSize:r.fontSizeSM},children:[o.jsx($l,{style:{color:r.colorTextLightSolid},strong:!0,children:i.name}),i.size&&o.jsxs($l,{style:{fontSize:r.fontSizeSM*.85,opacity:.8,color:r.colorTextLightSolid},children:[(i.size/1024).toFixed(1)," KB",i.width&&i.height&&` • ${i.width}×${i.height}`]})]})]}),(i.ocrText||i.ocrError)&&o.jsx("div",{style:{padding:r.paddingSM},children:o.jsx(ir,{ghost:!0,size:"small",items:[{key:"ocr",label:a("components.imageGrid.ocr"),children:o.jsxs(o.Fragment,{children:[i.ocrError&&o.jsx($l,{type:"danger",children:i.ocrError}),i.ocrText&&o.jsx(He.Paragraph,{style:{marginTop:i.ocrError?r.marginXS:0,marginBottom:0,whiteSpace:"pre-wrap"},children:i.ocrText})]})}]})})]},i.id))})})},{useToken:Z1}=Ge,{useBreakpoint:eR}=Nc,tR=({buttons:e,isVisible:t,className:n,style:s,position:r={bottom:"8px",right:"8px"}})=>{const{token:a}=Z1(),i=eR(),l=()=>(i.xs,"small");return o.jsx(be,{justify:"flex-end",gap:a.marginXS,className:n,style:{marginTop:a.marginXS,position:"absolute",bottom:r.bottom,right:r.right,top:r.top,left:r.left,background:"transparent",zIndex:1,opacity:t?1:0,transition:"opacity 0.2s ease",pointerEvents:t?"auto":"none",...s},children:e.map(c=>o.jsx(bt,{title:c.title,children:o.jsx(ue,{"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))})},nR=(e,t)=>({key:"copy","data-testid":"copy-message",icon:o.jsx(xs,{}),title:t||"Copy message",onClick:e}),sR=(e,t)=>({key:"reference",icon:o.jsx(xb,{}),title:t||"Reference message",onClick:e}),{Title:ng,Text:us,Paragraph:sg}=He,{useToken:rR}=Ge,oR=({plan:e,contextId:t,onExecute:n,onRefine:s,timestamp:r})=>{const{t:a}=Ie(),{token:i}=rR(),[l,c]=p.useState(!1),[u,m]=p.useState(""),f=()=>{u.trim()&&(s(u),m(""),c(!1))};return o.jsxs(Ce,{style:{marginBottom:i.marginMD,borderColor:i.colorPrimary,borderWidth:2,backgroundColor:i.colorPrimaryBg},title:o.jsxs(he,{children:[o.jsx(ar,{style:{color:i.colorPrimary}}),o.jsx(us,{strong:!0,style:{color:i.colorPrimary},children:a("components.plan.executionPlan")})]}),extra:r?o.jsx(us,{type:"secondary",style:{fontSize:i.fontSizeSM},children:r}):void 0,children:[o.jsxs(be,{vertical:!0,style:{marginBottom:i.marginLG},children:[o.jsx(ng,{level:5,style:{marginBottom:i.marginXS},children:a("components.plan.goal")}),o.jsx(sg,{style:{fontSize:15,marginBottom:0},children:e.goal})]}),o.jsxs(be,{vertical:!0,style:{marginBottom:i.marginLG},children:[o.jsx(ng,{level:5,style:{marginBottom:i.marginMD},children:a("components.plan.steps")}),o.jsx(vb,{direction:"vertical",current:-1,items:e.steps.map(g=>({title:o.jsxs(us,{strong:!0,children:[a("components.plan.stepTitle",{number:g.step_number}),": ",g.action]}),description:o.jsxs(be,{vertical:!0,children:[o.jsxs(sg,{style:{marginBottom:i.marginXS},children:[o.jsxs(us,{type:"secondary",children:[a("components.plan.reason"),":"]})," ",g.reason]}),o.jsxs(he,{wrap:!0,children:[o.jsxs(us,{type:"secondary",children:[o.jsx(Ui,{})," ",a("components.plan.tools"),":"]}),g.tools_needed.map((b,S)=>o.jsx(Ne,{color:"processing",children:b},S))]}),o.jsx(be,{style:{marginTop:i.marginXS},children:o.jsxs(us,{type:"secondary",children:[o.jsx(As,{})," ",a("components.plan.estimated"),": ",g.estimated_time]})})]}),icon:o.jsx(us,{children:g.step_number})}))})]}),o.jsxs(he,{direction:"vertical",style:{width:"100%",marginBottom:i.marginLG},children:[o.jsxs(be,{align:"center",gap:i.marginXS,wrap:"wrap",children:[o.jsxs(us,{type:"secondary",children:[o.jsx(As,{})," ",a("components.plan.totalEstimatedTime")," "]}),o.jsx(Ne,{color:"processing",children:e.estimated_total_time})]}),e.prerequisites&&e.prerequisites.length>0&&o.jsxs(be,{vertical:!0,children:[o.jsxs(us,{type:"secondary",children:[a("components.plan.prerequisites"),":"]}),o.jsx(Qt,{size:"small",dataSource:e.prerequisites,renderItem:(g,b)=>o.jsx(Qt.Item,{style:{padding:0},children:o.jsx(us,{children:g})},`${g}-${b}`)})]})]}),e.risks&&e.risks.length>0&&o.jsx(ir,{ghost:!0,style:{marginBottom:i.marginLG},items:[{key:"risks",label:o.jsxs(he,{children:[o.jsx(Vi,{style:{color:i.colorWarning}}),o.jsx(us,{strong:!0,children:a("components.plan.potentialRisks",{count:e.risks.length})})]}),children:o.jsx(Qt,{size:"small",dataSource:e.risks,renderItem:(g,b)=>o.jsx(Qt.Item,{style:{padding:0},children:o.jsx(us,{children:g})},`${g}-${b}`)})}]}),o.jsx(he,{style:{width:"100%",justifyContent:"flex-end"},children:l?o.jsxs(o.Fragment,{children:[o.jsx(ue,{onClick:()=>c(!1),children:a("common.cancel")}),o.jsx(ue,{type:"primary",onClick:f,disabled:!u.trim(),children:a("components.plan.sendFeedback")})]}):o.jsxs(o.Fragment,{children:[o.jsx(ue,{onClick:()=>c(!0),children:a("components.plan.refinePlan")}),o.jsx(ue,{type:"primary",icon:o.jsx(Sb,{}),onClick:n,children:a("components.plan.executePlan")})]})}),l&&o.jsx(be,{vertical:!0,style:{marginTop:i.marginMD},children:o.jsx(Qe.TextArea,{value:u,onChange:g=>m(g.target.value),placeholder:a("components.plan.feedbackPlaceholder"),autoSize:{minRows:4,maxRows:10}})})]})},Dx=p.memo(oR);Dx.displayName="PlanMessageCard";const{Title:aR,Text:Co,Paragraph:iR}=He,{useToken:lR}=Ge,cR=({question:e,contextId:t,onAnswer:n,disabled:s=!1,timestamp:r})=>{const{t:a}=Ie(),{token:i}=lR(),[l,c]=p.useState(e.default),[u,m]=p.useState(!1),f=async()=>{if(l){m(!0);try{await n(l)}catch(x){console.error("Failed to submit answer:",x)}finally{m(!1)}}},g=()=>{switch(e.severity){case"critical":return o.jsx(Em,{style:{color:i.colorError}});case"major":return o.jsx(Vi,{style:{color:i.colorWarning}});case"minor":return o.jsx(Kn,{style:{color:i.colorInfo}});default:return o.jsx(Cm,{style:{color:i.colorPrimary}})}},b=()=>{switch(e.severity){case"critical":return i.colorErrorBg;case"major":return i.colorWarningBg;case"minor":return i.colorInfoBg;default:return i.colorPrimaryBg}},S=()=>{switch(e.severity){case"critical":return i.colorError;case"major":return i.colorWarning;case"minor":return i.colorInfo;default:return i.colorPrimary}};return o.jsxs(Ce,{style:{marginBottom:i.marginMD,borderColor:S(),borderWidth:2,backgroundColor:b()},title:o.jsxs(he,{children:[g(),o.jsx(Co,{strong:!0,style:{color:S()},children:a("components.question.agentQuestion")}),o.jsxs(Co,{type:"secondary",style:{fontSize:12},children:["(",e.severity,")"]})]}),extra:r?o.jsx(Co,{type:"secondary",style:{fontSize:i.fontSizeSM},children:r}):void 0,children:[o.jsx(be,{vertical:!0,style:{marginBottom:i.marginLG},children:o.jsx(aR,{level:5,style:{marginBottom:i.marginXS},children:e.question})}),e.context&&o.jsx(Ut,{message:a("components.question.context"),description:e.context,type:"info",showIcon:!0,style:{marginBottom:i.marginLG}}),o.jsxs(be,{vertical:!0,style:{marginBottom:i.marginLG},children:[o.jsx(Co,{strong:!0,style:{display:"block",marginBottom:i.marginSM},children:a("components.question.chooseOption")}),o.jsx(bs.Group,{value:l,onChange:x=>c(x.target.value),disabled:s||u,style:{width:"100%"},children:o.jsx(he,{direction:"vertical",style:{width:"100%"},children:e.options.map(x=>o.jsx(Ce,{size:"small",hoverable:!s&&!u,style:{borderColor:l===x.value?i.colorPrimary:i.colorBorder,backgroundColor:l===x.value?i.colorPrimaryBg:i.colorBgContainer,cursor:s||u?"not-allowed":"pointer"},onClick:()=>!s&&!u&&c(x.value),children:o.jsx(bs,{value:x.value,style:{width:"100%"},children:o.jsxs(be,{vertical:!0,children:[o.jsxs(be,{align:"center",gap:i.marginXS,wrap:"wrap",children:[o.jsx(Co,{strong:!0,children:x.label}),x.value===e.default&&o.jsx(Ne,{color:"processing",style:{marginLeft:i.marginXS},children:a("components.question.recommended")})]}),o.jsx(iR,{type:"secondary",style:{marginTop:i.marginXXS,marginBottom:0},children:x.description})]})})},x.value))})})]}),e.allow_custom&&o.jsxs(be,{vertical:!0,style:{marginBottom:i.marginMD},children:[o.jsx(Co,{type:"secondary",style:{fontSize:12},children:a("components.question.customAnswerHint")}),o.jsx(Qe.TextArea,{value:l&&!e.options.find(x=>x.value===l)?l:"",onChange:x=>c(x.target.value),placeholder:a("components.question.customAnswerPlaceholder"),disabled:s||u,autoSize:{minRows:3,maxRows:8},style:{marginTop:i.marginXS}})]}),o.jsx(be,{justify:"flex-end",children:o.jsx(ue,{type:"primary",icon:o.jsx(ar,{}),onClick:f,loading:u,disabled:s||!l,children:a("components.question.submitAnswer")})})]})},Lx=p.memo(cR);Lx.displayName="QuestionMessageCard";const{Text:rg}=He,dR=({paths:e,displayText:t})=>{const{token:n}=Ge.useToken(),s=t.replace(/@[^\s]+/g,"").trim();return o.jsxs(Ce,{size:"small",styles:{body:{padding:`${n.paddingSM}px ${n.paddingMD}px`}},style:{maxWidth:"100%"},children:[o.jsx(he,{direction:"vertical",size:n.marginXXS,children:e.map((r,a)=>{const i=r.split("/").pop()||r,l=r.substring(0,r.lastIndexOf("/"))||"",c=!i.includes(".");return o.jsxs(be,{vertical:!0,children:[o.jsxs(he,{size:n.marginXS,align:"center",wrap:!0,children:[c?o.jsx(fc,{style:{color:n.colorWarning,fontSize:n.fontSizeLG}}):o.jsx(qo,{style:{color:n.colorPrimary,fontSize:n.fontSizeLG}}),o.jsx(Ne,{color:c?"warning":"processing",style:{margin:0,fontFamily:n.fontFamilyCode,fontSize:n.fontSize},children:i})]}),l&&o.jsx(bt,{title:r,children:o.jsxs(he,{size:4,align:"center",style:{marginTop:4},children:[o.jsx(fc,{style:{color:n.colorTextTertiary,fontSize:n.fontSizeSM}}),o.jsx(rg,{type:"secondary",style:{fontSize:n.fontSizeSM,fontFamily:n.fontFamilyCode,maxWidth:"400px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},copyable:{text:r},children:l})]})})]},a)})}),s&&o.jsx(rg,{style:{fontSize:n.fontSize,color:n.colorText,marginTop:n.marginXS,paddingTop:n.marginXS,borderTop:`1px solid ${n.colorBorderSecondary}`},children:s})]})},Fx=p.memo(dR);Fx.displayName="FileReferenceCard";const uR=({taskList:e})=>{const{token:t}=Ge.useToken(),{Text:n}=He,s=l=>{switch(l){case"pending":return o.jsx(Ne,{icon:o.jsx(As,{}),color:"default",children:"Pending"});case"in_progress":return o.jsx(Ne,{icon:o.jsx(io,{spin:!0}),color:"processing",children:"In Progress"});case"completed":return o.jsx(Ne,{icon:o.jsx(ar,{}),color:"success",children:"Completed"});case"skipped":return o.jsx(Ne,{icon:o.jsx(Cu,{}),color:"default",children:"Skipped"});case"failed":return o.jsx(Ne,{icon:o.jsx(pc,{}),color:"error",children:"Failed"});default:return null}},r=()=>{switch(e.status){case"active":return o.jsx(Ne,{color:"processing",children:"Active"});case"completed":return o.jsx(Ne,{color:"success",children:"Completed"});case"abandoned":return o.jsx(Ne,{color:"error",children:"Abandoned"});default:return null}},a=fn.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=fn.useMemo(()=>e.items.find(l=>l.status==="in_progress"),[e.items]);return o.jsx(Ce,{size:"small",styles:{body:{padding:t.paddingSM}},style:{borderRadius:t.borderRadiusLG},children:o.jsxs(be,{vertical:!0,gap:t.marginSM,children:[o.jsxs(be,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[o.jsxs(he,{direction:"vertical",size:2,children:[o.jsx(n,{strong:!0,children:e.title}),e.description?o.jsx(n,{type:"secondary",children:e.description}):null]}),r()]}),o.jsxs(he,{direction:"vertical",size:4,children:[o.jsx(Am,{percent:a,status:e.status==="completed"?"success":e.status==="abandoned"?"exception":"active",showInfo:!0}),o.jsxs(n,{type:"secondary",children:[a,"% Complete"]})]}),o.jsx(Qt,{size:"small",dataSource:e.items,renderItem:l=>{var u;const c=(i==null?void 0:i.id)===l.id;return o.jsx(Qt.Item,{style:{borderRadius:t.borderRadius,padding:t.paddingXS,background:c?t.colorPrimaryBg:"transparent",border:"1px solid",borderColor:c?t.colorPrimaryBorder:t.colorBorderSecondary},children:o.jsxs(be,{vertical:!0,style:{width:"100%"},gap:4,children:[o.jsxs(be,{align:"center",justify:"space-between",wrap:"wrap",gap:8,children:[o.jsx(n,{children:l.description}),s(l.status)]}),l.status==="failed"&&((u=l.metadata)!=null&&u.error)?o.jsx(n,{type:"danger",style:{fontSize:12},children:l.metadata.error}):null,l.status==="completed"&&l.summary?o.jsx(n,{type:"success",style:{fontSize:12},children:l.summary}):null]})})}}),o.jsxs(be,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[o.jsxs(n,{type:"secondary",style:{fontSize:12},children:[e.items.filter(l=>l.status==="completed").length," /"," ",e.items.length," tasks completed"]}),i?o.jsxs(n,{type:"secondary",style:{fontSize:12},children:["Current: ",i.description]}):null]})]})})},mR=100,Hr=new Set;function hR(e){if(Hr.has(e)&&Hr.delete(e),Hr.add(e),Hr.size>mR){const t=Hr.values().next().value;t&&Hr.delete(t)}}function pR(e){let t=2166136261;for(let n=0;n<e.length;n++)t=(t^e.charCodeAt(n))*16777619;return(t>>>0).toString(36)}const fR=e=>{const{t}=Ie(),n=pR(e.chart),[s,r]=p.useState(()=>Hr.has(n)),a=p.useRef(null);return p.useEffect(()=>{if(s)return;const i=a.current;if(!i)return;const l=new IntersectionObserver(c=>{c.some(u=>u.isIntersecting)&&(hR(n),r(!0),l.disconnect())},{rootMargin:"50px",threshold:.01});return l.observe(i),()=>l.disconnect()},[s,n]),o.jsx("div",{ref:a,style:{minHeight:s?"auto":"200px"},children:s?o.jsx(fn.Suspense,{fallback:o.jsx(Rs,{size:"small",tip:t("components.mermaid.loadingDiagram")}),children:o.jsx(gR,{...e})}):o.jsx("div",{style:{minHeight:"200px"}})})},gR=e=>{const{t}=Ie(),[n,s]=p.useState(null);return p.useEffect(()=>{let r=!1;return Bn(()=>Promise.resolve().then(()=>qA),void 0,import.meta.url).then(a=>{r||s(()=>a.MermaidChart)}),()=>{r=!0}},[]),n?o.jsx(n,{...e}):o.jsx(Rs,{size:"small",tip:t("components.mermaid.loadingDiagram")})},yR=fn.memo(fR),bR=({error:e,className:t,style:n,token:s,onFix:r,isFixing:a,fixError:i})=>{const{t:l}=Ie(),c=e.split(`
|
|
155
|
+
|
|
156
|
+
`);return o.jsxs("div",{className:t,style:{color:s.colorError,padding:`${s.paddingXS}px ${s.paddingSM}px`,fontSize:s.fontSizeSM,background:s.colorErrorBg,borderRadius:s.borderRadiusSM,border:`1px solid ${s.colorErrorBorder}`,margin:`${s.marginXS}px 0`,minHeight:"60px",maxHeight:"120px",display:"flex",flexDirection:"column",alignItems:"flex-start",justifyContent:"flex-start",overflow:"auto",position:"relative",maxWidth:"100%",boxSizing:"border-box",...n},title:`${l("components.mermaid.errorTitlePrefix")}: ${e}
|
|
157
|
+
|
|
158
|
+
${l("components.mermaid.checkConsoleHint")}`,children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:s.marginXXS},children:[o.jsx("span",{style:{marginRight:s.marginXS,fontSize:"14px",flexShrink:0,lineHeight:1},children:o.jsx(Vi,{})}),o.jsx("span",{style:{fontWeight:600,color:s.colorError},children:l("components.mermaid.diagramError")})]}),o.jsx("div",{style:{fontSize:s.fontSizeSM,lineHeight:1.4,wordBreak:"break-word",flex:1,width:"100%"},children:c.map((u,m)=>o.jsx("div",{style:{marginBottom:m<c.length-1?s.marginXS:0,...u.startsWith("💡")?{backgroundColor:s.colorInfoBg,border:`1px solid ${s.colorInfoBorder}`,borderRadius:s.borderRadiusSM,padding:s.paddingXS,marginTop:s.marginXS,color:s.colorInfo,fontWeight:500}:{}},children:u},`${m}-${u.substring(0,12)}`))}),r&&o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.marginXS,marginTop:s.marginXS,width:"100%"},children:[o.jsx(ue,{size:"small",type:"primary",onClick:r,loading:a,children:l("components.mermaid.fixMermaid")}),i&&o.jsx("span",{style:{color:s.colorError,fontSize:s.fontSizeSM,wordBreak:"break-word",flex:1},children:i})]}),o.jsxs("div",{style:{fontSize:s.fontSizeSM,color:s.colorTextSecondary,marginTop:s.marginXS,fontStyle:"italic"},children:[o.jsx(hb,{style:{marginRight:4}})," ",l("components.mermaid.checkConsoleHint")]})]})};var gs=function(e,t){return Number(e.toFixed(t))},xR=function(e,t){return typeof e=="number"?e:t},Vt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},vR=function(e){return-Math.cos(e*Math.PI)/2+.5},SR=function(e){return e},wR=function(e){return e*e},_R=function(e){return e*(2-e)},kR=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},TR=function(e){return e*e*e},jR=function(e){return--e*e*e+1},CR=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},MR=function(e){return e*e*e*e},PR=function(e){return 1- --e*e*e*e},ER=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},RR=function(e){return e*e*e*e*e},AR=function(e){return 1+--e*e*e*e*e},IR=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},Nx={easeOut:vR,linear:SR,easeInQuad:wR,easeOutQuad:_R,easeInOutQuad:kR,easeInCubic:TR,easeOutCubic:jR,easeInOutCubic:CR,easeInQuart:MR,easeOutQuart:PR,easeInOutQuart:ER,easeInQuint:RR,easeOutQuint:AR,easeInOutQuint:IR},zx=function(e){typeof e=="number"&&cancelAnimationFrame(e)},Cs=function(e){e.mounted&&(zx(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function Bx(e,t,n,s){if(e.mounted){var r=new Date().getTime(),a=1;Cs(e),e.animation=function(){if(!e.mounted)return zx(e.animation);var i=new Date().getTime()-r,l=i/n,c=Nx[t],u=c(l);i>=n?(s(a),e.animation=null):e.animation&&(s(u),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function OR(e){var t=e.scale,n=e.positionX,s=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(s))}function Rr(e,t,n,s){var r=OR(t);if(!(!e.mounted||!r)){var a=e.setTransformState,i=e.transformState,l=i.scale,c=i.positionX,u=i.positionY,m=t.scale-l,f=t.positionX-c,g=t.positionY-u;n===0?a(t.scale,t.positionX,t.positionY):Bx(e,s,n,function(b){var S=l+m*b,x=c+f*b,T=u+g*b;a(S,x,T)})}}function $R(e,t,n){var s=e.offsetWidth,r=e.offsetHeight,a=t.offsetWidth,i=t.offsetHeight,l=a*n,c=i*n,u=s-l,m=r-c;return{wrapperWidth:s,wrapperHeight:r,newContentWidth:l,newDiffWidth:u,newContentHeight:c,newDiffHeight:m}}var DR=function(e,t,n,s,r,a,i){var l=e>t?n*(i?1:.5):0,c=s>r?a*(i?1:.5):0,u=e-t-l,m=l,f=s-r-c,g=c;return{minPositionX:u,maxPositionX:m,minPositionY:f,maxPositionY:g}},th=function(e,t){var n=e.wrapperComponent,s=e.contentComponent,r=e.setup.centerZoomedOut;if(!n||!s)throw new Error("Components are not mounted");var a=$R(n,s,t),i=a.wrapperWidth,l=a.wrapperHeight,c=a.newContentWidth,u=a.newDiffWidth,m=a.newContentHeight,f=a.newDiffHeight,g=DR(i,c,u,l,m,f,!!r);return g},Zu=function(e,t,n,s){return s?e<t?gs(t,2):e>n?gs(n,2):gs(e,2):gs(e,2)},ao=function(e,t){var n=th(e,t);return e.bounds=n,n};function el(e,t,n,s,r,a,i){var l=n.minPositionX,c=n.minPositionY,u=n.maxPositionX,m=n.maxPositionY,f=0,g=0;i&&(f=r,g=a);var b=Zu(e,l-f,u+f,s),S=Zu(t,c-g,m+g,s);return{x:b,y:S}}function Yc(e,t,n,s,r,a){var i=e.transformState,l=i.scale,c=i.positionX,u=i.positionY,m=s-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:c,y:u};var f=c-t*m,g=u-n*m,b=el(f,g,r,a,0,0,null);return b}function tl(e,t,n,s,r){var a=r?s:0,i=t-a;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=i?i:e}var og=function(e,t){var n=e.setup.panning.excluded,s=e.isInitialized,r=e.wrapperComponent,a=t.target,i="shadowRoot"in a&&"composedPath"in t,l=i?t.composedPath().some(function(m){return m instanceof Element?r==null?void 0:r.contains(m):!1}):r==null?void 0:r.contains(a),c=s&&a&&l;if(!c)return!1;var u=Xc(a,n);return!u},ag=function(e){var t=e.isInitialized,n=e.isPanning,s=e.setup,r=s.panning.disabled,a=t&&n&&!r;return!!a},LR=function(e,t){var n=e.transformState,s=n.positionX,r=n.positionY;e.isPanning=!0;var a=t.clientX,i=t.clientY;e.startCoords={x:a-s,y:i-r}},FR=function(e,t){var n=t.touches,s=e.transformState,r=s.positionX,a=s.positionY;e.isPanning=!0;var i=n.length===1;if(i){var l=n[0].clientX,c=n[0].clientY;e.startCoords={x:l-r,y:c-a}}};function NR(e){var t=e.transformState,n=t.positionX,s=t.positionY,r=t.scale,a=e.setup,i=a.disabled,l=a.limitToBounds,c=a.centerZoomedOut,u=e.wrapperComponent;if(!(i||!u||!e.bounds)){var m=e.bounds,f=m.maxPositionX,g=m.minPositionX,b=m.maxPositionY,S=m.minPositionY,x=n>f||n<g,T=s>b||s<S,j=n>f?u.offsetWidth:e.setup.minPositionX||0,w=s>b?u.offsetHeight:e.setup.minPositionY||0,M=Yc(e,j,w,r,e.bounds,l||c),_=M.x,C=M.y;return{scale:r,positionX:x?_:n,positionY:T?C:s}}}function Wx(e,t,n,s,r){var a=e.setup.limitToBounds,i=e.wrapperComponent,l=e.bounds,c=e.transformState,u=c.scale,m=c.positionX,f=c.positionY;if(!(i===null||l===null||t===m&&n===f)){var g=el(t,n,l,a,s,r,i),b=g.x,S=g.y;e.setTransformState(u,b,S)}}var zR=function(e,t,n){var s=e.startCoords,r=e.transformState,a=e.setup.panning,i=a.lockAxisX,l=a.lockAxisY,c=r.positionX,u=r.positionY;if(!s)return{x:c,y:u};var m=t-s.x,f=n-s.y,g=i?c:m,b=l?u:f;return{x:g,y:b}},jr=function(e,t){var n=e.setup,s=e.transformState,r=s.scale,a=n.minScale,i=n.disablePadding;return t>0&&r>=a&&!i?t:0},BR=function(e){var t=e.mounted,n=e.setup,s=n.disabled,r=n.velocityAnimation,a=e.transformState.scale,i=r.disabled,l=!i||a>1||!s||t;return!!l},WR=function(e){var t=e.mounted,n=e.velocity,s=e.bounds,r=e.setup,a=r.disabled,i=r.velocityAnimation,l=e.transformState.scale,c=i.disabled,u=!c||l>1||!a||t;return!(!u||!n||!s)};function qR(e,t){var n=e.setup.velocityAnimation,s=n.equalToMove,r=n.animationTime,a=n.sensitivity;return s?r*t*a:r}function ig(e,t,n,s,r,a,i,l,c,u){if(r){if(t>i&&n>i){var m=i+(e-i)*u;return m>c?c:m<i?i:m}if(t<a&&n<a){var m=a+(e-a)*u;return m<l?l:m>a?a:m}}return s?t:Zu(e,a,i,r)}function UR(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function HR(e,t){var n=BR(e);if(n){var s=e.lastMousePosition,r=e.velocityTime,a=e.setup,i=e.wrapperComponent,l=a.velocityAnimation.equalToMove,c=Date.now();if(s&&r&&i){var u=UR(i,l),m=t.x-s.x,f=t.y-s.y,g=m/u,b=f/u,S=c-r,x=m*m+f*f,T=Math.sqrt(x)/S;e.velocity={velocityX:g,velocityY:b,total:T}}e.lastMousePosition=t,e.velocityTime=c}}function KR(e){var t=e.velocity,n=e.bounds,s=e.setup,r=e.wrapperComponent,a=WR(e);if(!(!a||!t||!n||!r)){var i=t.velocityX,l=t.velocityY,c=t.total,u=n.maxPositionX,m=n.minPositionX,f=n.maxPositionY,g=n.minPositionY,b=s.limitToBounds,S=s.alignmentAnimation,x=s.zoomAnimation,T=s.panning,j=T.lockAxisY,w=T.lockAxisX,M=x.animationType,_=S.sizeX,C=S.sizeY,L=S.velocityAlignmentTime,A=L,B=qR(e,c),N=Math.max(B,A),O=jr(e,_),R=jr(e,C),I=O*r.offsetWidth/100,$=R*r.offsetHeight/100,U=u+I,q=m-I,K=f+$,P=g-$,W=e.transformState,se=new Date().getTime();Bx(e,M,N,function(V){var ie=e.transformState,re=ie.scale,fe=ie.positionX,Se=ie.positionY,ke=new Date().getTime()-se,Be=ke/A,tt=Nx[S.animationType],ft=1-tt(Math.min(1,Be)),Ht=1-V,Oe=fe+i*Ht,zt=Se+l*Ht,Ye=ig(Oe,W.positionX,fe,w,b,m,u,q,U,ft),we=ig(zt,W.positionY,Se,j,b,g,f,P,K,ft);(fe!==Oe||Se!==zt)&&e.setTransformState(re,Ye,we)})}}function lg(e,t){var n=e.transformState.scale;Cs(e),ao(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?FR(e,t):LR(e,t)}function nh(e,t){var n=e.transformState.scale,s=e.setup,r=s.minScale,a=s.alignmentAnimation,i=a.disabled,l=a.sizeX,c=a.sizeY,u=a.animationTime,m=a.animationType,f=i||n<r||!l&&!c;if(!f){var g=NR(e);g&&Rr(e,g,t??u,m)}}function cg(e,t,n){var s=e.startCoords,r=e.setup,a=r.alignmentAnimation,i=a.sizeX,l=a.sizeY;if(s){var c=zR(e,t,n),u=c.x,m=c.y,f=jr(e,i),g=jr(e,l);HR(e,{x:u,y:m}),Wx(e,u,m,f,g)}}function VR(e){if(e.isPanning){var t=e.setup.panning.velocityDisabled,n=e.velocity,s=e.wrapperComponent,r=e.contentComponent;e.isPanning=!1,e.animate=!1,e.animation=null;var a=s==null?void 0:s.getBoundingClientRect(),i=r==null?void 0:r.getBoundingClientRect(),l=(a==null?void 0:a.width)||0,c=(a==null?void 0:a.height)||0,u=(i==null?void 0:i.width)||0,m=(i==null?void 0:i.height)||0,f=l<u||c<m,g=!t&&n&&(n==null?void 0:n.total)>.1&&f;g?KR(e):nh(e)}}function sh(e,t,n,s){var r=e.setup,a=r.minScale,i=r.maxScale,l=r.limitToBounds,c=tl(gs(t,2),a,i,0,!1),u=ao(e,c),m=Yc(e,n,s,c,u,l),f=m.x,g=m.y;return{scale:c,positionX:f,positionY:g}}function qx(e,t,n){var s=e.transformState.scale,r=e.wrapperComponent,a=e.setup,i=a.minScale,l=a.limitToBounds,c=a.zoomAnimation,u=c.disabled,m=c.animationTime,f=c.animationType,g=u||s>=i;if((s>=1||l)&&nh(e),!(g||!r||!e.mounted)){var b=t||r.offsetWidth/2,S=n||r.offsetHeight/2,x=sh(e,i,b,S);x&&Rr(e,x,m,f)}}var kr=function(){return kr=Object.assign||function(t){for(var n,s=1,r=arguments.length;s<r;s++){n=arguments[s];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},kr.apply(this,arguments)};function dg(e,t,n){for(var s=0,r=t.length,a;s<r;s++)(a||!(s in t))&&(a||(a=Array.prototype.slice.call(t,0,s)),a[s]=t[s]);return e.concat(a||Array.prototype.slice.call(t))}var Dl={scale:1,positionX:0,positionY:0},Ca={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}},em={wrapperClass:"react-transform-wrapper",contentClass:"react-transform-component"},Ux=function(e){var t,n,s,r;return{previousScale:(t=e.initialScale)!==null&&t!==void 0?t:Dl.scale,scale:(n=e.initialScale)!==null&&n!==void 0?n:Dl.scale,positionX:(s=e.initialPositionX)!==null&&s!==void 0?s:Dl.positionX,positionY:(r=e.initialPositionY)!==null&&r!==void 0?r:Dl.positionY}},ug=function(e){var t=kr({},Ca);return Object.keys(e).forEach(function(n){var s=typeof e[n]<"u",r=typeof Ca[n]<"u";if(r&&s){var a=Object.prototype.toString.call(Ca[n]),i=a==="[object Object]",l=a==="[object Array]";i?t[n]=kr(kr({},Ca[n]),e[n]):l?t[n]=dg(dg([],Ca[n],!0),e[n]):t[n]=e[n]}}),t},Hx=function(e,t,n){var s=e.transformState.scale,r=e.wrapperComponent,a=e.setup,i=a.maxScale,l=a.minScale,c=a.zoomAnimation,u=a.smooth,m=c.size;if(!r)throw new Error("Wrapper is not mounted");var f=u?s*Math.exp(t*n):s+t*n,g=tl(gs(f,3),l,i,m,!1);return g};function Kx(e,t,n,s,r){var a=e.wrapperComponent,i=e.transformState,l=i.scale,c=i.positionX,u=i.positionY;if(!a)return console.error("No WrapperComponent found");var m=a.offsetWidth,f=a.offsetHeight,g=(m/2-c)/l,b=(f/2-u)/l,S=Hx(e,t,n),x=sh(e,S,g,b);if(!x)return console.error("Error during zoom event. New transformation state was not calculated.");Rr(e,x,s,r)}function Vx(e,t,n,s){var r=e.setup,a=e.wrapperComponent,i=r.limitToBounds,l=Ux(e.props),c=e.transformState,u=c.scale,m=c.positionX,f=c.positionY;if(a){var g=th(e,l.scale),b=el(l.positionX,l.positionY,g,i,0,0,a),S={scale:l.scale,positionX:b.x,positionY:b.y};u===l.scale&&m===l.positionX&&f===l.positionY||(s==null||s(),Rr(e,S,t,n))}}function YR(e,t,n,s){var r=e.getBoundingClientRect(),a=t.getBoundingClientRect(),i=n.getBoundingClientRect(),l=a.x*s.scale,c=a.y*s.scale;return{x:(r.x-i.x+l)/s.scale,y:(r.y-i.y+c)/s.scale}}function XR(e,t,n){var s=e.wrapperComponent,r=e.contentComponent,a=e.transformState,i=e.setup,l=i.limitToBounds,c=i.minScale,u=i.maxScale;if(!s||!r)return a;var m=s.getBoundingClientRect(),f=t.getBoundingClientRect(),g=YR(t,s,r,a),b=g.x,S=g.y,x=f.width/a.scale,T=f.height/a.scale,j=s.offsetWidth/x,w=s.offsetHeight/T,M=tl(n||Math.min(j,w),c,u,0,!1),_=(m.width-x*M)/2,C=(m.height-T*M)/2,L=(m.left-b)*M+_,A=(m.top-S)*M+C,B=th(e,M),N=el(L,A,B,l,0,0,s),O=N.x,R=N.y;return{positionX:O,positionY:R,scale:M}}var GR=function(e){return function(t,n,s){t===void 0&&(t=.5),n===void 0&&(n=300),s===void 0&&(s="easeOut"),Kx(e,1,t,n,s)}},JR=function(e){return function(t,n,s){t===void 0&&(t=.5),n===void 0&&(n=300),s===void 0&&(s="easeOut"),Kx(e,-1,t,n,s)}},QR=function(e){return function(t,n,s,r,a){r===void 0&&(r=300),a===void 0&&(a="easeOut");var i=e.transformState,l=i.positionX,c=i.positionY,u=i.scale,m=e.wrapperComponent,f=e.contentComponent,g=e.setup.disabled;if(!(g||!m||!f)){var b={positionX:Number.isNaN(t)?l:t,positionY:Number.isNaN(n)?c:n,scale:Number.isNaN(s)?u:s};Rr(e,b,r,a)}}},ZR=function(e){return function(t,n){t===void 0&&(t=200),n===void 0&&(n="easeOut"),Vx(e,t,n)}},eA=function(e){return function(t,n,s){n===void 0&&(n=200),s===void 0&&(s="easeOut");var r=e.transformState,a=e.wrapperComponent,i=e.contentComponent;if(a&&i){var l=Yx(t||r.scale,a,i);Rr(e,l,n,s)}}},tA=function(e){return function(t,n,s,r){s===void 0&&(s=600),r===void 0&&(r="easeOut"),Cs(e);var a=e.wrapperComponent,i=typeof t=="string"?document.getElementById(t):t;if(a&&i&&a.contains(i)){var l=XR(e,i,n);Rr(e,l,s,r)}}},tm=function(e){return{instance:e,zoomIn:GR(e),zoomOut:JR(e),setTransform:QR(e),resetTransform:ZR(e),centerView:eA(e),zoomToElement:tA(e)}},nA=function(e){return{instance:e,state:e.transformState}},qt=function(e){var t={};return Object.assign(t,nA(e)),Object.assign(t,tm(e)),t},Xd=!1;function Gd(){try{var e={get passive(){return Xd=!0,!1}};return e}catch{return Xd=!1,Xd}}var Ll=".".concat(em.wrapperClass),Xc=function(e,t){return t.some(function(n){return e.matches("".concat(Ll," ").concat(n,", ").concat(Ll," .").concat(n,", ").concat(Ll," ").concat(n," *, ").concat(Ll," .").concat(n," *"))})},nm=function(e){e&&clearTimeout(e)},sA=function(e,t,n){return"translate(".concat(e,"px, ").concat(t,"px) scale(").concat(n,")")},Yx=function(e,t,n){var s=n.offsetWidth*e,r=n.offsetHeight*e,a=(t.offsetWidth-s)/2,i=(t.offsetHeight-r)/2;return{scale:e,positionX:a,positionY:i}};function rA(e){return function(t){e.forEach(function(n){typeof n=="function"?n(t):n!=null&&(n.current=t)})}}var oA=function(e,t){var n=e.setup.wheel,s=n.disabled,r=n.wheelDisabled,a=n.touchPadDisabled,i=n.excluded,l=e.isInitialized,c=e.isPanning,u=t.target,m=l&&!c&&!s&&u;if(!m||r&&!t.ctrlKey||a&&t.ctrlKey)return!1;var f=Xc(u,i);return!f},aA=function(e){return e?e.deltaY<0?1:-1:0};function iA(e,t){var n=aA(e),s=xR(t,n);return s}function Xx(e,t,n){var s=t.getBoundingClientRect(),r=0,a=0;if("clientX"in e)r=(e.clientX-s.left)/n,a=(e.clientY-s.top)/n;else{var i=e.touches[0];r=(i.clientX-s.left)/n,a=(i.clientY-s.top)/n}return(Number.isNaN(r)||Number.isNaN(a))&&console.error("No mouse or touch offset found"),{x:r,y:a}}var lA=function(e,t,n,s,r){var a=e.transformState.scale,i=e.wrapperComponent,l=e.setup,c=l.maxScale,u=l.minScale,m=l.zoomAnimation,f=l.disablePadding,g=m.size,b=m.disabled;if(!i)throw new Error("Wrapper is not mounted");var S=a+t*n,x=s?!1:!b,T=tl(gs(S,3),u,c,g,x&&!f);return T},cA=function(e,t){var n=e.previousWheelEvent,s=e.transformState.scale,r=e.setup,a=r.maxScale,i=r.minScale;return n?s<a||s>i||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaY<t.deltaY||n.deltaY<0&&n.deltaY>t.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},dA=function(e,t){var n=e.setup.pinch,s=n.disabled,r=n.excluded,a=e.isInitialized,i=t.target,l=a&&!s&&i;if(!l)return!1;var c=Xc(i,r);return!c},uA=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,s=e.pinchStartDistance,r=n&&!t&&s;return!!r},mA=function(e,t,n){var s=n.getBoundingClientRect(),r=e.touches,a=gs(r[0].clientX-s.left,5),i=gs(r[0].clientY-s.top,5),l=gs(r[1].clientX-s.left,5),c=gs(r[1].clientY-s.top,5);return{x:(a+l)/2/t,y:(i+c)/2/t}},Gx=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))},hA=function(e,t){var n=e.pinchStartScale,s=e.pinchStartDistance,r=e.setup,a=r.maxScale,i=r.minScale,l=r.zoomAnimation,c=r.disablePadding,u=l.size,m=l.disabled;if(!n||s===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var f=t/s,g=f*n;return tl(gs(g,2),i,a,u,!m&&!c)},pA=160,fA=100,gA=function(e,t){var n=e.props,s=n.onWheelStart,r=n.onZoomStart;e.wheelStopEventTimer||(Cs(e),Vt(qt(e),t,s),Vt(qt(e),t,r))},yA=function(e,t){var n=e.props,s=n.onWheel,r=n.onZoom,a=e.contentComponent,i=e.setup,l=e.transformState,c=l.scale,u=i.limitToBounds,m=i.centerZoomedOut,f=i.zoomAnimation,g=i.wheel,b=i.disablePadding,S=i.smooth,x=f.size,T=f.disabled,j=g.step,w=g.smoothStep;if(!a)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var M=iA(t,null),_=S?w*Math.abs(t.deltaY):j,C=lA(e,M,_,!t.ctrlKey);if(c!==C){var L=ao(e,C),A=Xx(t,a,c),B=T||x===0||m||b,N=u&&B,O=Yc(e,A.x,A.y,C,L,N),R=O.x,I=O.y;e.previousWheelEvent=t,e.setTransformState(C,R,I),Vt(qt(e),t,s),Vt(qt(e),t,r)}},bA=function(e,t){var n=e.props,s=n.onWheelStop,r=n.onZoomStop;nm(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(qx(e,t.x,t.y),e.wheelAnimationTimer=null)},fA);var a=cA(e,t);a&&(nm(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Vt(qt(e),t,s),Vt(qt(e),t,r))},pA))},Jx=function(e){for(var t=0,n=0,s=0;s<2;s+=1)t+=e.touches[s].clientX,n+=e.touches[s].clientY;var r=t/2,a=n/2;return{x:r,y:a}},xA=function(e,t){var n=Gx(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1;var s=Jx(t);e.pinchLastCenterX=s.x,e.pinchLastCenterY=s.y,Cs(e)},vA=function(e,t){var n=e.contentComponent,s=e.pinchStartDistance,r=e.wrapperComponent,a=e.transformState.scale,i=e.setup,l=i.limitToBounds,c=i.centerZoomedOut,u=i.zoomAnimation,m=i.alignmentAnimation,f=u.disabled,g=u.size;if(!(s===null||!n)){var b=mA(t,a,n);if(!(!Number.isFinite(b.x)||!Number.isFinite(b.y))){var S=Gx(t),x=hA(e,S),T=Jx(t),j=T.x-(e.pinchLastCenterX||0),w=T.y-(e.pinchLastCenterY||0);if(!(x===a&&j===0&&w===0)){e.pinchLastCenterX=T.x,e.pinchLastCenterY=T.y;var M=ao(e,x),_=f||g===0||c,C=l&&_,L=Yc(e,b.x,b.y,x,M,C),A=L.x,B=L.y;e.pinchMidpoint=b,e.lastDistance=S;var N=m.sizeX,O=m.sizeY,R=jr(e,N),I=jr(e,O),$=A+j,U=B+w,q=el($,U,M,l,R,I,r),K=q.x,P=q.y;e.setTransformState(x,K,P)}}}},SA=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,qx(e,t==null?void 0:t.x,t==null?void 0:t.y)},Qx=function(e,t){var n=e.props.onZoomStop,s=e.setup.doubleClick.animationTime;nm(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Vt(qt(e),t,n)},s)},wA=function(e,t){var n=e.props,s=n.onZoomStart,r=n.onZoom,a=e.setup.doubleClick,i=a.animationTime,l=a.animationType;Vt(qt(e),t,s),Vx(e,i,l,function(){return Vt(qt(e),t,r)}),Qx(e,t)};function _A(e,t){return e==="toggle"?t===1?1:-1:e==="zoomOut"?-1:1}function kA(e,t){var n=e.setup,s=e.doubleClickStopEventTimer,r=e.transformState,a=e.contentComponent,i=r.scale,l=e.props,c=l.onZoomStart,u=l.onZoom,m=n.doubleClick,f=m.disabled,g=m.mode,b=m.step,S=m.animationTime,x=m.animationType;if(!f&&!s){if(g==="reset")return wA(e,t);if(!a)return console.error("No ContentComponent found");var T=_A(g,e.transformState.scale),j=Hx(e,T,b);if(i!==j){Vt(qt(e),t,c);var w=Xx(t,a,i),M=sh(e,j,w.x,w.y);if(!M)return console.error("Error during zoom event. New transformation state was not calculated.");Vt(qt(e),t,u),Rr(e,M,S,x),Qx(e,t)}}}var TA=function(e,t){var n=e.isInitialized,s=e.setup,r=e.wrapperComponent,a=s.doubleClick,i=a.disabled,l=a.excluded,c=t.target,u=r==null?void 0:r.contains(c),m=n&&c&&u&&!i;if(!m)return!1;var f=Xc(c,l);return!f},jA=function(){function e(t){var n=this;this.mounted=!0,this.pinchLastCenterX=null,this.pinchLastCenterY=null,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.isWheelPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(s){n.props=s,ao(n,n.transformState.scale),n.setup=ug(s)},this.initializeWindowEvents=function(){var s,r,a=Gd(),i=(s=n.wrapperComponent)===null||s===void 0?void 0:s.ownerDocument,l=i==null?void 0:i.defaultView;(r=n.wrapperComponent)===null||r===void 0||r.addEventListener("wheel",n.onWheelPanning,a),l==null||l.addEventListener("mousedown",n.onPanningStart,a),l==null||l.addEventListener("mousemove",n.onPanning,a),l==null||l.addEventListener("mouseup",n.onPanningStop,a),i==null||i.addEventListener("mouseleave",n.clearPanning,a),l==null||l.addEventListener("keyup",n.setKeyUnPressed,a),l==null||l.addEventListener("keydown",n.setKeyPressed,a)},this.cleanupWindowEvents=function(){var s,r,a=Gd(),i=(s=n.wrapperComponent)===null||s===void 0?void 0:s.ownerDocument,l=i==null?void 0:i.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,a),l==null||l.removeEventListener("mousemove",n.onPanning,a),l==null||l.removeEventListener("mouseup",n.onPanningStop,a),i==null||i.removeEventListener("mouseleave",n.clearPanning,a),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,a),l==null||l.removeEventListener("keydown",n.setKeyPressed,a),document.removeEventListener("mouseleave",n.clearPanning,a),Cs(n),(r=n.observer)===null||r===void 0||r.disconnect()},this.handleInitializeWrapperEvents=function(s){var r=Gd();s.addEventListener("wheel",n.onWheelZoom,r),s.addEventListener("dblclick",n.onDoubleClick,r),s.addEventListener("touchstart",n.onTouchPanningStart,r),s.addEventListener("touchmove",n.onTouchPanning,r),s.addEventListener("touchend",n.onTouchPanningStop,r)},this.handleInitialize=function(s,r){var a=!1,i=n.setup.centerOnInit,l=function(c,u){for(var m=0,f=c;m<f.length;m++){var g=f[m];if(g.target===u)return!0}return!1};n.applyTransformation(),n.onInitCallbacks.forEach(function(c){c(qt(n))}),n.observer=new ResizeObserver(function(c){if(l(c,s)||l(c,r))if(i&&!a){var u=r.offsetWidth,m=r.offsetHeight;(u>0||m>0)&&(a=!0,n.setCenter())}else Cs(n),ao(n,n.transformState.scale),nh(n,0)}),n.observer.observe(s),n.observer.observe(r)},this.onWheelZoom=function(s){var r=n.setup.disabled;if(!r){var a=oA(n,s);if(a){var i=n.isPressingKeys(n.setup.wheel.activationKeys);i&&(gA(n,s),yA(n,s),bA(n,s))}}},this.onWheelPanning=function(s){var r=n.setup,a=r.disabled,i=r.wheel,l=r.panning;if(!(!n.wrapperComponent||!n.contentComponent||a||!i.wheelDisabled||l.disabled||!l.wheelPanning||s.ctrlKey)){s.preventDefault(),s.stopPropagation();var c=n.transformState,u=c.positionX,m=c.positionY,f=u-s.deltaX,g=m-s.deltaY,b=l.lockAxisX?u:f,S=l.lockAxisY?m:g,x=n.setup.alignmentAnimation,T=x.sizeX,j=x.sizeY,w=jr(n,T),M=jr(n,j);b===u&&S===m||Wx(n,b,S,w,M)}},this.onPanningStart=function(s){var r=n.setup.disabled,a=n.props.onPanningStart;if(!r){var i=og(n,s);if(i){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(s.button===0&&!n.setup.panning.allowLeftClickPan||s.button===1&&!n.setup.panning.allowMiddleClickPan||s.button===2&&!n.setup.panning.allowRightClickPan||(s.preventDefault(),s.stopPropagation(),Cs(n),lg(n,s),Vt(qt(n),s,a)))}}},this.onPanning=function(s){var r=n.setup.disabled,a=n.props.onPanning;if(!r){var i=ag(n);if(i){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(s.preventDefault(),s.stopPropagation(),cg(n,s.clientX,s.clientY),Vt(qt(n),s,a))}}},this.onPanningStop=function(s){var r=n.props.onPanningStop;n.isPanning&&(VR(n),Vt(qt(n),s,r))},this.onPinchStart=function(s){var r=n.setup.disabled,a=n.props,i=a.onPinchingStart,l=a.onZoomStart;if(!r){var c=dA(n,s);c&&(xA(n,s),Cs(n),Vt(qt(n),s,i),Vt(qt(n),s,l))}},this.onPinch=function(s){var r=n.setup.disabled,a=n.props,i=a.onPinching,l=a.onZoom;if(!r){var c=uA(n);c&&(s.preventDefault(),s.stopPropagation(),vA(n,s),Vt(qt(n),s,i),Vt(qt(n),s,l))}},this.onPinchStop=function(s){var r=n.props,a=r.onPinchingStop,i=r.onZoomStop;n.pinchStartScale&&(SA(n),Vt(qt(n),s,a),Vt(qt(n),s,i))},this.onTouchPanningStart=function(s){var r=n.setup.disabled,a=n.props.onPanningStart;if(!r){var i=og(n,s);if(i){var l=n.lastTouch&&+new Date-n.lastTouch<200&&s.touches.length===1;if(!l){n.lastTouch=+new Date,Cs(n);var c=s.touches,u=c.length===1,m=c.length===2;u&&(Cs(n),lg(n,s),Vt(qt(n),s,a)),m&&n.onPinchStart(s)}}}},this.onTouchPanning=function(s){var r=n.setup.disabled,a=n.props.onPanning;if(n.isPanning&&s.touches.length===1){if(r)return;var i=ag(n);if(!i)return;s.preventDefault(),s.stopPropagation();var l=s.touches[0];cg(n,l.clientX,l.clientY),Vt(qt(n),s,a)}else s.touches.length>1&&n.onPinch(s)},this.onTouchPanningStop=function(s){n.onPanningStop(s),n.onPinchStop(s)},this.onDoubleClick=function(s){var r=n.setup.disabled;if(!r){var a=TA(n,s);a&&kA(n,s)}},this.clearPanning=function(s){n.isPanning&&n.onPanningStop(s)},this.setKeyPressed=function(s){n.pressedKeys[s.key]=!0},this.setKeyUnPressed=function(s){n.pressedKeys[s.key]=!1},this.isPressingKeys=function(s){return s.length?!!s.find(function(r){return n.pressedKeys[r]}):!0},this.setTransformState=function(s,r,a){var i=n.props.onTransformed;if(!Number.isNaN(s)&&!Number.isNaN(r)&&!Number.isNaN(a)){s!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=s),n.transformState.positionX=r,n.transformState.positionY=a,n.applyTransformation();var l=qt(n);n.onChangeCallbacks.forEach(function(c){return c(l)}),Vt(l,{scale:s,positionX:r,positionY:a},i)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var s=Yx(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(s.scale,s.positionX,s.positionY)}},this.handleTransformStyles=function(s,r,a){return n.props.customTransform?n.props.customTransform(s,r,a):sA(s,r,a)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var s=n.transformState,r=s.scale,a=s.positionX,i=s.positionY,l=n.handleTransformStyles(a,i,r);n.contentComponent.style.transform=l}},this.getContext=function(){return qt(n)},this.onChange=function(s){return n.onChangeCallbacks.has(s)||n.onChangeCallbacks.add(s),function(){n.onChangeCallbacks.delete(s)}},this.onInit=function(s){return n.onInitCallbacks.has(s)||n.onInitCallbacks.add(s),function(){n.onInitCallbacks.delete(s)}},this.init=function(s,r){n.cleanupWindowEvents(),n.wrapperComponent=s,n.contentComponent=r,ao(n,n.transformState.scale),n.handleInitializeWrapperEvents(s),n.handleInitialize(s,r),n.initializeWindowEvents(),n.isInitialized=!0;var a=qt(n);Vt(a,void 0,n.props.onInit)},this.props=t,this.setup=ug(this.props),this.transformState=Ux(this.props)}return e}(),rh=fn.createContext(null),CA=function(e,t){return typeof e=="function"?e(t):e},MA=fn.forwardRef(function(e,t){var n=p.useRef(new jA(e)).current,s=CA(e.children,tm(n));return p.useImperativeHandle(t,function(){return tm(n)},[n]),p.useEffect(function(){n.update(e)},[n,e]),fn.createElement(rh.Provider,{value:n},s)});fn.forwardRef(function(e,t){var n=p.useRef(null),s=p.useContext(rh);return p.useEffect(function(){return s.onChange(function(r){if(n.current){var a=0,i=0;n.current.style.transform=s.handleTransformStyles(a,i,1/r.instance.transformState.scale)}})},[s]),fn.createElement("div",kr({},e,{ref:rA([n,t])}))});function PA(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(typeof document>"u")){var s=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",n==="top"&&s.firstChild?s.insertBefore(r,s.firstChild):s.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}var EA=`.transform-component-module_wrapper__SPB86 {
|
|
159
|
+
position: relative;
|
|
160
|
+
width: -moz-fit-content;
|
|
161
|
+
width: fit-content;
|
|
162
|
+
height: -moz-fit-content;
|
|
163
|
+
height: fit-content;
|
|
164
|
+
overflow: hidden;
|
|
165
|
+
-webkit-touch-callout: none; /* iOS Safari */
|
|
166
|
+
-webkit-user-select: none; /* Safari */
|
|
167
|
+
-khtml-user-select: none; /* Konqueror HTML */
|
|
168
|
+
-moz-user-select: none; /* Firefox */
|
|
169
|
+
-ms-user-select: none; /* Internet Explorer/Edge */
|
|
170
|
+
user-select: none;
|
|
171
|
+
margin: 0;
|
|
172
|
+
padding: 0;
|
|
173
|
+
transform: translate3d(0, 0, 0);
|
|
174
|
+
}
|
|
175
|
+
.transform-component-module_content__FBWxo {
|
|
176
|
+
display: flex;
|
|
177
|
+
flex-wrap: wrap;
|
|
178
|
+
width: -moz-fit-content;
|
|
179
|
+
width: fit-content;
|
|
180
|
+
height: -moz-fit-content;
|
|
181
|
+
height: fit-content;
|
|
182
|
+
margin: 0;
|
|
183
|
+
padding: 0;
|
|
184
|
+
transform-origin: 0% 0%;
|
|
185
|
+
}
|
|
186
|
+
.transform-component-module_content__FBWxo img {
|
|
187
|
+
pointer-events: none;
|
|
188
|
+
}
|
|
189
|
+
`,mg={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};PA(EA);var RA=function(e){var t=e.children,n=e.wrapperClass,s=n===void 0?"":n,r=e.contentClass,a=r===void 0?"":r,i=e.wrapperStyle,l=e.contentStyle,c=e.wrapperProps,u=c===void 0?{}:c,m=e.contentProps,f=m===void 0?{}:m,g=p.useContext(rh),b=g.init,S=g.cleanupWindowEvents,x=p.useRef(null),T=p.useRef(null);return p.useEffect(function(){var j=x.current,w=T.current;return j!==null&&w!==null&&b&&(b==null||b(j,w)),function(){S==null||S()}},[]),fn.createElement("div",kr({},u,{ref:x,className:"".concat(em.wrapperClass," ").concat(mg.wrapper," ").concat(s),style:i}),fn.createElement("div",kr({},f,{ref:T,className:"".concat(em.contentClass," ").concat(mg.content," ").concat(a),style:l}),t))};const Zx=()=>typeof window<"u"&&!!window.__TAURI_INTERNALS__;class AA{async saveFile(t){const{content:n,filters:s,defaultPath:r}=t,{save:a}=await Bn(async()=>{const{save:u}=await import("./index-BmjFP0ha.js");return{save:u}},__vite__mapDeps([13,14]),import.meta.url),{writeFile:i,writeTextFile:l}=await Bn(async()=>{const{writeFile:u,writeTextFile:m}=await import("./index-_XI0Qq6F.js");return{writeFile:u,writeTextFile:m}},__vite__mapDeps([15,14]),import.meta.url),c=await a({filters:s.map(u=>({name:u.name,extensions:[...u.extensions]})),defaultPath:r});if(!c)throw new Error("User cancelled save operation");return typeof n=="string"?await l(c,n):await i(c,n),{filename:ev(c,r),success:!0}}}class IA{async saveFile(t){const{content:n,filters:s,defaultPath:r}=t,a=ev(r,r);if(typeof window>"u"||typeof document>"u")throw new Error("File save is unavailable in this environment");const i=DA(s,n),l=typeof n=="string"?new Blob([n],{type:`${i};charset=utf-8`}):new Blob([n],{type:i}),c=URL.createObjectURL(l);try{const u=document.createElement("a");u.href=c,u.download=a,u.style.display="none",document.body.appendChild(u),u.click(),document.body.removeChild(u)}finally{URL.revokeObjectURL(c)}return{filename:a,success:!0}}}const OA=new AA,$A=new IA,ev=(e,t)=>e.split(/[/\\]/).pop()||t,DA=(e,t)=>{var s,r,a;switch(((a=(r=(s=e[0])==null?void 0:s.extensions)==null?void 0:r[0])==null?void 0:a.toLowerCase())||""){case"md":return"text/markdown";case"txt":return"text/plain";case"json":return"application/json";case"pdf":return"application/pdf";case"svg":return"image/svg+xml";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";default:return typeof t=="string"?"text/plain":"application/octet-stream"}},LA=()=>Zx()?OA:$A;class Us{static async saveFile(t){try{return await LA().saveFile(t)}catch(n){return{filename:"",success:!1,error:n instanceof Error?n.message:"Unknown error occurred"}}}static async saveTextFile(t,n,s){return this.saveFile({content:t,filters:n,defaultPath:s})}static async saveBinaryFile(t,n,s){return this.saveFile({content:t,filters:n,defaultPath:s})}static generateTimestampedFilename(t,n){const s=new Date().toISOString().slice(0,19).replace(/:/g,"-");return`${t}-${s}.${n}`}}Ct(Us,"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 FA=e=>{const s=new DOMParser().parseFromString(e,"image/svg+xml").querySelector("svg");return s?(s.getAttribute("xmlns")||s.setAttribute("xmlns","http://www.w3.org/2000/svg"),s.getAttribute("xmlns:xlink")||s.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink"),`<?xml version="1.0" encoding="UTF-8"?>
|
|
190
|
+
${new XMLSerializer().serializeToString(s)}`):e},NA=({svg:e,height:t,isLoading:n,initialScale:s,chartKey:r,className:a,style:i,token:l,containerRef:c})=>{const{t:u}=Ie(),{message:m}=sn.useApp(),[f,g]=p.useState(!1),b=p.useCallback(async()=>{var x;if(!(!e||f)){g(!0);try{const T=FA(e),j=new TextEncoder().encode(T),w=r?`mermaid-${r.slice(0,8)}`:"mermaid-graph",M=Us.generateTimestampedFilename(w,"svg"),_=await Us.saveBinaryFile(j,Us.FILTERS.SVG,M);if(_.success){m.success(u("chat.messageActions.savedFile",{filename:_.filename}));return}if((x=_.error)!=null&&x.toLowerCase().includes("cancel"))return;m.error(_.error||u("chat.messageActions.exportFailed"))}catch(T){const j=T instanceof Error?T.message:u("components.mermaid.exportFailed");m.error(j)}finally{g(!1)}}},[m,r,f,e,u]),S=n||!e||f;return o.jsxs("div",{ref:c,"data-mermaid-loading":n?"true":"false",className:a,style:{textAlign:"center",margin:`${l.marginXS}px 0`,padding:l.padding,background:l.colorBgContainer,borderRadius:l.borderRadiusSM,border:`1px solid ${l.colorBorder}`,overflow:"hidden",height:`${Math.min(t,800)}px`,minHeight:"300px",maxHeight:"80vh",display:"flex",alignItems:"center",justifyContent:"center",position:"relative",willChange:"auto",contain:"layout style paint",...i},children:[n&&o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:l.colorTextSecondary,fontSize:l.fontSizeSM,zIndex:2},children:u("components.mermaid.renderingDiagram")}),o.jsx("div",{style:{width:"100%",height:"100%",opacity:n?0:1,position:"relative"},children:o.jsx(MA,{initialScale:s,minScale:.1,maxScale:10,centerOnInit:!0,limitToBounds:!1,wheel:{step:.1},panning:{disabled:!1},pinch:{disabled:!1},doubleClick:{disabled:!1,mode:"zoomIn",step:.5},children:({zoomIn:x,zoomOut:T,resetTransform:j})=>o.jsxs(o.Fragment,{children:[o.jsxs("div",{"data-mermaid-controls":"true",style:{position:"absolute",top:8,right:8,zIndex:10,display:"flex",flexDirection:"column",gap:4,background:l.colorBgContainer,borderRadius:l.borderRadiusSM,border:`1px solid ${l.colorBorder}`,padding:4,boxShadow:l.boxShadowSecondary},children:[o.jsx(ue,{size:"small",type:"text",onClick:()=>x(),style:{fontSize:12,padding:"2px 6px"},children:"+"}),o.jsx(ue,{size:"small",type:"text",onClick:()=>T(),style:{fontSize:12,padding:"2px 6px"},children:"-"}),o.jsx(ue,{size:"small",type:"text",onClick:()=>j(),style:{fontSize:10,padding:"2px 6px"},children:"⌂"}),o.jsx(bt,{title:u("components.mermaid.exportSvg"),children:o.jsx(ue,{size:"small",type:"text",icon:o.jsx(Wo,{}),"aria-label":"Download chart",disabled:S,loading:f,onClick:()=>{b()},style:{fontSize:11,padding:"2px 6px"}})})]}),o.jsx(RA,{wrapperStyle:{width:"100%",height:"100%"},contentStyle:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%"},children:o.jsx("div",{style:{display:"inline-block",lineHeight:0},dangerouslySetInnerHTML:{__html:e.replace(/<svg([^>]*)>/,'<svg$1 style="display: block; max-width: 100%; max-height: 100%;">')}})})]})})})]})};function zA(e){let t=2166136261;for(let n=0;n<e.length;n++)t=(t^e.charCodeAt(n))*16777619;return(t>>>0).toString(36)}const BA=(e,t)=>{const n=p.useMemo(()=>SM(e),[e]),s=p.useMemo(()=>zA(n),[n]),[r,a]=p.useState(()=>{const i=tc(s);return i?{svg:i.svg,height:i.height+80,svgWidth:i.width,svgHeight:i.height,error:"",isLoading:!1}:{svg:"",height:200,svgWidth:800,svgHeight:200,error:"",isLoading:t}});return p.useEffect(()=>{const i=tc(s);a(i?{svg:i.svg,height:i.height+80,svgWidth:i.width,svgHeight:i.height,error:"",isLoading:!1}:{svg:"",height:200,svgWidth:800,svgHeight:200,error:"",isLoading:!1})},[s]),p.useEffect(()=>{if(tc(s))return;let l=!1;return a(c=>({...c,isLoading:!0})),jM(s,n).then(c=>{l||a({svg:c.svg,height:c.height+80,svgWidth:c.width,svgHeight:c.height,error:"",isLoading:!1})}).catch(c=>{if(!l){console.error("[MermaidState] Render error:",c);const u=c instanceof Error?c.message:String(c);a(m=>({...m,error:u||"Failed to render Mermaid diagram",isLoading:!1}))}}),()=>{l=!0}},[s,n,t]),{renderState:r,chartKey:s}},{useToken:WA}=Ge,Mc=fn.memo(({chart:e,id:t,className:n,style:s,onFix:r})=>{const{token:a}=WA(),i=Uc(),[l,c]=p.useState(!1),[u,m]=p.useState(""),f=p.useRef(null),{renderState:g,chartKey:b}=BA(e,!0),{svg:S,height:x,svgWidth:T,error:j,isLoading:w}=g,_=(()=>{const L=i.defaultScale;return T>1200?L*.8:T>800?L*1:L*1.2})(),C=async()=>{if(!(!r||l)){c(!0),m("");try{await r(e,j)}catch(L){const A=L instanceof Error?L.message:String(L);m(A||"Failed to fix Mermaid diagram")}finally{c(!1)}}};return j?o.jsx(bR,{error:j,className:n,style:s,token:a,onFix:r?C:void 0,isFixing:l,fixError:u}):o.jsx(NA,{svg:S,height:x,isLoading:w,initialScale:_,chartKey:b,className:n,style:s,token:a,containerRef:f})});Mc.displayName="MermaidChart";const qA=Object.freeze(Object.defineProperty({__proto__:null,MermaidChart:Mc,default:Mc},Symbol.toStringTag,{value:"Module"}));gn.registerLanguage("javascript",ab);gn.registerLanguage("js",ab);gn.registerLanguage("typescript",ib);gn.registerLanguage("ts",ib);gn.registerLanguage("python",lb);gn.registerLanguage("py",lb);gn.registerLanguage("json",Cw);gn.registerLanguage("bash",_m);gn.registerLanguage("shell",_m);gn.registerLanguage("sh",_m);gn.registerLanguage("css",Mw);gn.registerLanguage("html",cb);gn.registerLanguage("xml",cb);gn.registerLanguage("sql",Pw);gn.registerLanguage("yaml",db);gn.registerLanguage("yml",db);gn.registerLanguage("markdown",ub);gn.registerLanguage("md",ub);const UA=()=>mo,HA=["javascript","js","typescript","ts","python","py","json","bash","shell","sh","css","html","xml","sql","yaml","yml","markdown","md"],KA=({language:e,codeString:t,token:n})=>{const{t:s}=Ie(),{message:r}=sn.useApp(),[a,i]=p.useState(!1),l=async()=>{try{await vs(t),r.success(s("components.markdown.codeCopiedSuccess"))}catch(m){console.error("Copy failed:",m),r.error(s("components.markdown.copyFailed"))}},c=e.toLowerCase(),u=HA.includes(c);return o.jsxs(Ce,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto"},onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:[o.jsx(gn,{style:UA(),language:u?c:"text",PreTag:"div",customStyle:{margin:`${n.marginXS}px 0`,borderRadius:n.borderRadiusSM,fontSize:n.fontSizeSM,maxWidth:"100%",paddingRight:"50px"},showLineNumbers:t.split(`
|
|
191
|
+
`).length>10,wrapLines:!0,wrapLongLines:!0,children:t}),a&&o.jsx(ue,{type:"text",size:"small",icon:o.jsx(xs,{}),onClick:l,"aria-label":"Copy code",style:{position:"absolute",top:n.paddingSM,right:n.paddingSM,backgroundColor:"var(--lotus-code-copy-btn-bg, rgba(0, 0, 0, 0.6))",color:"var(--lotus-code-copy-btn-color, white)",border:"none",borderRadius:n.borderRadiusSM,opacity:.8,transition:"opacity 0.2s",zIndex:10},onMouseEnter:m=>{const f=m.currentTarget;f.style.opacity="1"},onMouseLeave:m=>{const f=m.currentTarget;f.style.opacity="0.8"}})]})},VA=({codeString:e,token:t})=>{const{t:n}=Ie(),{message:s}=sn.useApp();return o.jsxs(Ce,{size:"small",styles:{body:{padding:0}},style:{position:"relative",margin:`${t.marginXS}px 0`},onMouseEnter:r=>{const a=r.currentTarget.querySelector(".fallback-copy-btn");a&&(a.style.display="block")},onMouseLeave:r=>{const a=r.currentTarget.querySelector(".fallback-copy-btn");a&&(a.style.display="none")},children:[o.jsx("pre",{style:{backgroundColor:t.colorBgContainer,border:`1px solid ${t.colorBorder}`,padding:t.padding,borderRadius:t.borderRadiusSM,overflow:"auto",fontSize:t.fontSizeSM,paddingRight:"50px",margin:0},children:o.jsx("code",{style:{color:t.colorText},children:e})}),o.jsx(ue,{type:"text",size:"small",icon:o.jsx(xs,{}),"aria-label":"Copy code",className:"fallback-copy-btn",onClick:async()=>{try{await vs(e),s.success(n("components.markdown.codeCopiedSuccess"))}catch(r){console.error("Copy failed:",r),s.error(n("components.markdown.copyFailed"))}},style:{position:"absolute",top:t.paddingSM,right:t.paddingSM,backgroundColor:"var(--lotus-code-copy-btn-bg, rgba(0, 0, 0, 0.6))",color:"var(--lotus-code-copy-btn-color, white)",border:"none",borderRadius:t.borderRadiusSM,display:"none",zIndex:10}})]})},YA={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"},tv=/^(\s*%%\{[\s\S]*?\}%%\s*)+/,XA=/^(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,GA=e=>e.replace(tv,"").trimStart(),JA=(e,t)=>{const n=e.match(tv);if(!n)return`${t}
|
|
192
|
+
${e}`.trim();const s=n[0].trimEnd(),r=e.slice(n[0].length).trimStart();return r?`${s}
|
|
193
|
+
${t}
|
|
194
|
+
${r}`:`${s}
|
|
195
|
+
${t}`},QA=(e,t)=>{const n=YA[e];if(!n)return null;const s=t.trim();if(!s)return"";if(e==="mermaid")return s;const r=GA(s);return XA.test(r)?s:JA(s,n)},nv=(e,t,n,s,r="lazy")=>{try{if(!t||typeof t!="string")return console.warn("Invalid codeString provided to renderCodeBlock:",t),null;const a=e.toLowerCase().trim(),i=QA(a,t);if(i!==null){const l=i.trim();return l?r==="eager"?o.jsx(Mc,{chart:l,onFix:s}):o.jsx(yR,{chart:l,onFix:s}):(console.warn("Empty Mermaid chart content"),null)}return o.jsx(KA,{language:a,codeString:t,token:n})}catch(a){return console.warn("Syntax highlighting failed:",a),o.jsx(VA,{codeString:t,token:n})}},hg=(e,t)=>{if(typeof window>"u")return;const n=window.open(e,"_blank","noopener,noreferrer");if(n){n.opener=null;return}((t==null?void 0:t.allowLocationFallback)??!0)&&window.location.assign(e)},sv=async e=>{const t=e.trim();if(!t)return;if(Zx()){const s=window.__TAURI_INTERNALS__,r=s==null?void 0:s.invoke;if(typeof r=="function")try{await r("plugin:shell|open",{path:t});return}catch(a){console.warn("[openExternalLink] Failed to open via Tauri shell plugin, falling back to browser open.",a)}hg(t,{allowLocationFallback:!1});return}hg(t)},{Text:pg}=He,rv=(e,t)=>({p:({children:n})=>o.jsx(pg,{style:{marginBottom:e.marginSM,display:"block"},children:n}),ol:({children:n})=>o.jsx("ol",{style:{marginBottom:e.marginSM,paddingLeft:20},children:n}),ul:({children:n})=>o.jsx("ul",{style:{marginBottom:e.marginSM,paddingLeft:20},children:n}),li:({children:n})=>o.jsx("li",{style:{marginBottom:e.marginXS},children:n}),code({className:n,children:s,inline:r,...a}){const i=/language-([^\s]+)/i.exec(n||""),l=i?i[1]:"",c=r??(!i&&!n),u=s?String(s).replace(/\n$/,""):"";return c?o.jsx(pg,{code:!0,className:n,...a,children:s}):u.trim()?nv(l,u,e,t==null?void 0:t.onFixMermaid,t==null?void 0:t.mermaidRenderMode):null},blockquote:({children:n})=>o.jsx(Ce,{size:"small",styles:{body:{padding:`${e.paddingXS}px ${e.padding}px`}},style:{borderLeft:`3px solid ${e.colorPrimary}`,background:e.colorPrimaryBg,margin:`${e.marginXS}px 0`,color:e.colorTextSecondary,fontStyle:"italic"},children:n}),a:({children:n,href:s})=>{const r=typeof s=="string"?s.trim():"";return r?o.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",onClick:a=>{a.preventDefault(),a.stopPropagation(),sv(r)},style:{color:e.colorLink,textDecoration:"underline",overflowWrap:"anywhere"},children:n}):o.jsx(o.Fragment,{children:n})},table:({children:n})=>o.jsx(Ce,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${e.marginSM}px 0`},children:o.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${e.colorBorder}`},children:n})}),thead:({children:n})=>o.jsx("thead",{style:{backgroundColor:e.colorFillTertiary,color:e.colorText},children:n}),tbody:({children:n})=>o.jsx("tbody",{children:n}),tr:({children:n})=>o.jsx("tr",{style:{borderBottom:`1px solid ${e.colorBorder}`},children:n}),th:({children:n})=>o.jsx("th",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,textAlign:"left",fontWeight:"bold",borderRight:`1px solid ${e.colorBorder}`},children:n}),td:({children:n})=>o.jsx("td",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,borderRight:`1px solid ${e.colorBorder}`},children:n}),input:({type:n,checked:s,disabled:r})=>n==="checkbox"?o.jsx("input",{type:"checkbox",checked:s,disabled:r,style:{marginRight:e.marginXS,accentColor:e.colorPrimary},readOnly:!0}):o.jsx("input",{type:n,checked:s,disabled:r})}),{Text:At}=He,fg=e=>{if(!e)return;const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},ZA=({content:e,toolName:t,status:n="success",timestamp:s,defaultCollapsed:r=!0,isLoading:a,errorMessage:i})=>{var j;const{t:l}=Ie(),{token:c}=Ge.useToken(),u=p.useMemo(()=>Yu(e),[e]),m=p.useMemo(()=>typeof a=="boolean"?a:u.formattedText.trim().length===0,[u.formattedText,a]),f=p.useMemo(()=>Pj(u.formattedText),[u.formattedText]),g=p.useMemo(()=>Kc(e),[e]),b=p.useMemo(()=>px(e),[e]),S=p.useMemo(()=>g?fx(g.diff.unified):[],[g]),x=async()=>{try{const w=u.isJson?Uo(u.parsedJson):u.formattedText;await vs(w)}catch(w){console.error("[ToolResultCard] Failed to copy result:",w)}},T=p.useMemo(()=>{const w=e?e.slice(0,50).replace(/[^a-zA-Z0-9]/g,""):"empty";return`tool-result-${t}-${w}`},[t,e]);return o.jsx(ir,{defaultActiveKey:r?[]:[T],style:{backgroundColor:c.colorBgContainer,borderColor:c.colorBorderSecondary,borderWidth:1,borderStyle:"solid",borderRadius:c.borderRadiusLG},items:[{key:T,label:o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:c.marginSM,width:"100%"},children:[o.jsx(Rm,{style:{color:c.colorPrimary,flexShrink:0}}),o.jsx(At,{strong:!0,style:{color:c.colorText,flexShrink:0},children:t}),o.jsx(At,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:c.fontSizeSM},children:m?l("components.toolResult.waiting"):f}),o.jsx(Ne,{color:yx(n),style:{flexShrink:0,margin:0},children:n})]}),children:o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:c.marginSM,children:[s&&o.jsx(At,{type:"secondary",style:{fontSize:c.fontSizeSM},children:new Date(s).toLocaleString()}),i&&o.jsx(Ut,{type:"error",message:l("components.toolResult.executionFailed"),description:i,showIcon:!0}),o.jsxs("div",{style:{position:"relative"},children:[o.jsx(bt,{title:l("components.toolResult.copyResult"),children:o.jsx(ue,{type:"text",size:"small",icon:o.jsx(xs,{}),"aria-label":l("components.toolResult.copyResult"),onClick:w=>{w.stopPropagation(),x()},style:{position:"absolute",top:8,right:8,zIndex:1}})}),m?o.jsx(At,{type:"secondary",children:l("components.toolResult.waitingForResult")}):b?o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:10,children:[o.jsxs(he,{wrap:!0,children:[o.jsx(Ne,{color:b.action==="rebuild"?"gold":"blue",children:l(`components.toolResult.memory.action.${b.action}`)}),o.jsx(Ne,{children:b.data.scope}),b.data.project_key?o.jsx(Ne,{children:b.data.project_key}):null,o.jsx(Ne,{color:"green",children:l("components.toolResult.memory.totalMemories",{count:b.data.total_memories})}),o.jsx(Ne,{color:b.data.stale_candidate_count>0?"orange":"default",children:l("components.toolResult.memory.staleCandidates",{count:b.data.stale_candidate_count})})]}),o.jsxs("div",{children:[o.jsx(At,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.coverage")}),o.jsxs("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:[Object.entries(b.data.by_type).map(([w,M])=>o.jsx(Ne,{children:`${w}: ${M}`},`type-${w}`)),Object.entries(b.data.by_status).map(([w,M])=>o.jsx(Ne,{color:"processing",children:`${w}: ${M}`},`status-${w}`))]})]}),o.jsx(zn,{style:{margin:`${c.marginXS}px 0`}}),o.jsxs("div",{style:{display:"grid",gap:c.marginXS},children:[o.jsxs(At,{style:{fontSize:c.fontSizeSM},children:[o.jsx(At,{strong:!0,children:l("components.toolResult.memory.viewsLabel")})," ",b.data.view_files.length]}),o.jsxs(At,{style:{fontSize:c.fontSizeSM},children:[o.jsx(At,{strong:!0,children:l("components.toolResult.memory.indexesLabel")})," ",b.data.index_files.length]}),o.jsxs(At,{style:{fontSize:c.fontSizeSM},children:[o.jsx(At,{strong:!0,children:l("components.toolResult.memory.stateFilesLabel")})," ",b.data.state_files.length]}),b.data.last_reindex_at?o.jsxs(At,{style:{fontSize:c.fontSizeSM},children:[o.jsx(At,{strong:!0,children:l("components.toolResult.memory.lastReindexLabel")})," ",fg(b.data.last_reindex_at)]}):null,b.data.last_dream_at?o.jsxs(At,{style:{fontSize:c.fontSizeSM},children:[o.jsx(At,{strong:!0,children:l("components.toolResult.memory.lastDreamLabel")})," ",fg(b.data.last_dream_at)]}):null]}),b.data.view_files.length>0?o.jsxs("div",{children:[o.jsx(At,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.viewFiles")}),o.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:b.data.view_files.map(w=>o.jsx(Ne,{children:w},`view-${w}`))})]}):null,b.data.index_files.length>0?o.jsxs("div",{children:[o.jsx(At,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.indexFiles")}),o.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:b.data.index_files.map(w=>o.jsx(Ne,{children:w},`index-${w}`))})]}):null,b.data.state_files.length>0?o.jsxs("div",{children:[o.jsx(At,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.stateFiles")}),o.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:b.data.state_files.map(w=>o.jsx(Ne,{children:w},`state-${w}`))})]}):null,b.data.topic_paths.length>0?o.jsxs("div",{children:[o.jsx(At,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.topicPaths")}),o.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:b.data.topic_paths.map(w=>o.jsx(Ne,{children:w},`topic-${w}`))})]}):null,b.data.recent_ids.length>0?o.jsxs("div",{children:[o.jsx(At,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.recentMemories")}),o.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:b.data.recent_ids.map(w=>o.jsx(Ne,{color:"default",children:w},`recent-${w}`))})]}):null]}):g?o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:8,children:[g.message&&o.jsx(At,{style:{fontSize:c.fontSizeSM},children:g.message}),o.jsxs(At,{style:{fontSize:c.fontSizeSM},children:[o.jsxs(At,{strong:!0,children:[l("common.file"),":"]})," ",o.jsx(At,{code:!0,children:g.file_path})]}),g.workspace&&o.jsxs(At,{style:{fontSize:c.fontSizeSM},children:[o.jsxs(At,{strong:!0,children:[l("common.workspace"),":"]})," ",o.jsx(At,{code:!0,children:g.workspace})]}),(j=g.checkpoint)!=null&&j.created?o.jsxs(At,{style:{fontSize:c.fontSizeSM},children:[o.jsxs(At,{strong:!0,children:[l("components.toolResult.checkpoint"),":"]})," ",o.jsx(At,{code:!0,children:g.checkpoint.path})]}):o.jsx(At,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("components.toolResult.checkpointNone")}),o.jsx("div",{style:{border:`1px solid ${c.colorBorderSecondary}`,borderRadius:c.borderRadiusSM,maxHeight:400,overflow:"auto",background:c.colorBgContainer},children:S.map((w,M)=>{const _={margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:c.fontSizeSM,lineHeight:1.5,padding:"0 8px",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"};return w.kind==="add"?_.background=c.colorSuccessBg:w.kind==="remove"?_.background=c.colorErrorBg:w.kind==="modified_add"?(_.background=c.colorWarningBg,_.borderLeft=`3px solid ${c.colorSuccess}`):w.kind==="modified_remove"?(_.background=c.colorWarningBg,_.borderLeft=`3px solid ${c.colorError}`):w.kind==="hunk"?(_.background=c.colorFillSecondary,_.color=c.colorTextSecondary):w.kind==="meta"&&(_.background=c.colorFillTertiary,_.color=c.colorTextSecondary),o.jsx("pre",{style:_,children:w.text||" "},`${M}-${w.kind}`)})}),g.diff.truncated&&o.jsx(At,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("components.toolResult.diffTruncated")})]}):u.isJson?o.jsx(Bo,{language:"json",style:mo,wrapLongLines:!0,customStyle:{margin:0,borderRadius:c.borderRadiusSM,backgroundColor:c.colorBgContainer,fontSize:c.fontSizeSM,maxHeight:400,overflow:"auto"},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:u.formattedText}):o.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:c.fontSizeSM,backgroundColor:c.colorBgContainer,padding:c.paddingSM,borderRadius:c.borderRadiusSM,margin:0,maxHeight:400,overflow:"auto"},children:u.formattedText})]})]})}]})},ov=p.memo(ZA);ov.displayName="ToolResultCard";function av(e,t){const n=Go(e);if(n)return`MCP ${n.serverId}: ${n.toolName}`;const s=(i,l)=>{const c=typeof i=="string"?i:String(i??"");return!c||c.length<=l?c:c.substring(0,l).trimEnd()+"…"},r={file_read:i=>`Reading: ${s(i.path||i.file_path||"file",40)}`,file_write:i=>`Writing to: ${s(i.path||i.file_path||"file",35)}`,file_edit:i=>`Editing: ${s(i.path||i.file_path||"file",40)}`,bash:i=>`Executing: ${s(i.command,40)}`,grep:i=>`Searching: "${s(i.pattern,30)}"`,glob:i=>`Finding files: "${i.pattern}"`,conclusion:i=>`Presenting conclusion: "${s(i.conclusion||i.title||"",30)}"`,read:i=>`Reading: ${i.file_path||"file"}`,write:i=>`Writing: ${i.file_path||"file"}`,edit:i=>`Editing: ${i.file_path||"file"}`,search:i=>`Searching: "${s(i.query||i.pattern,30)}"`,default:()=>`Calling ${e}`};return(r[e]||r.default)(t)}const{Text:Ns}=He,eI=e=>e==null?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`,tI=({open:e,onClose:t,call:n,metadata:s,initialTab:r="preview",result:a})=>{var w,M;const{t:i}=Ie(),{token:l}=Ge.useToken(),c=p.useMemo(()=>Go(n.toolName),[n.toolName]),u=p.useMemo(()=>av(n.toolName,n.parameters),[n.toolName,n.parameters]),m=p.useMemo(()=>Uo(n.parameters,2),[n.parameters]),f=async()=>{try{await vs(m)}catch(_){console.error("[ToolStepDetailDrawer] Failed to copy parameters:",_)}},g=p.useMemo(()=>{const _=["path","file_path","command","pattern","query","limit"];return Object.entries(n.parameters).sort((A,B)=>{const N=_.indexOf(A[0]),O=_.indexOf(B[0]);return N!==-1&&O!==-1?N-O:N!==-1?-1:O!==-1?1:0}).slice(0,3)},[n.parameters]),b=!!((w=n.streamingOutput)!=null&&w.trim()),S=p.useMemo(()=>a?a.isError?o.jsx(Ne,{color:"error",children:"error"}):o.jsx(Ne,{color:"success",children:"finish"}):b?o.jsx(Ne,{color:"processing",children:"process"}):o.jsx(Ne,{color:"default",children:"wait"}),[a,b]),x=(s==null?void 0:s.elapsed_ms)!=null?o.jsx(Ne,{color:s.is_mutating?"orange":"green",children:eI(s.elapsed_ms)}):null,T=o.jsxs(he,{size:"small",children:[c?o.jsxs(o.Fragment,{children:[o.jsx(Ne,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:8,fontWeight:700},children:"MCP"}),o.jsx(Ns,{strong:!0,children:c.toolName}),o.jsx(Ns,{type:"secondary",style:{fontSize:l.fontSizeSM},children:o.jsx(Ns,{code:!0,style:{fontSize:l.fontSizeSM},children:c.serverId})})]}):o.jsx(Ns,{strong:!0,children:n.toolName}),S,x]}),j=[{key:"preview",label:i("components.toolSteps.preview"),children:o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:l.marginSM,children:[o.jsxs("div",{children:[o.jsx(Ns,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolSteps.intent")}),o.jsx("div",{style:{marginTop:l.marginXS},children:o.jsx(Ns,{style:{fontSize:l.fontSizeSM},children:u})})]}),g.length>0&&o.jsxs("div",{children:[o.jsx(Ns,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolSteps.keyParameters")}),o.jsx("ul",{style:{margin:`${l.marginXS}px 0 0`,paddingLeft:l.paddingLG,fontSize:l.fontSizeSM},children:g.map(([_,C])=>o.jsxs("li",{children:[o.jsx(Ns,{code:!0,style:{fontSize:l.fontSizeSM},children:_}),o.jsxs(Ns,{style:{fontSize:l.fontSizeSM},children:[": ",typeof C=="string"?C:JSON.stringify(C)]})]},_))})]}),(M=n.streamingOutput)!=null&&M.trim()?o.jsxs("div",{children:[o.jsx(Ns,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolCall.liveOutput")}),o.jsx("div",{className:"lotus-code-surface",style:{marginTop:l.marginXS,borderRadius:l.borderRadiusSM,backgroundColor:l.colorBgContainer,maxHeight:360,overflow:"auto"},children:o.jsx(Bo,{language:"text",style:mo,wrapLongLines:!0,customStyle:{margin:0,backgroundColor:"transparent",fontSize:l.fontSizeSM},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:n.streamingOutput})})]}):null]})},{key:"parameters",label:i("components.toolSteps.parameters"),children:o.jsxs("div",{style:{position:"relative"},children:[o.jsx(bt,{title:i("components.toolCall.copyParameters"),children:o.jsx(ue,{type:"text",size:"small",icon:o.jsx(xs,{}),"aria-label":i("components.toolCall.copyParameters"),onClick:f,style:{position:"absolute",top:0,right:0,zIndex:1}})}),o.jsx(Bo,{language:"json",style:mo,wrapLongLines:!0,customStyle:{margin:0,borderRadius:l.borderRadiusSM,backgroundColor:l.colorBgContainer,fontSize:l.fontSizeSM,maxHeight:400,overflow:"auto"},className:"lotus-code-surface",codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:m})]})},{key:"result",label:i("components.toolSteps.result"),children:a?o.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:l.fontSizeSM,backgroundColor:l.colorBgContainer,padding:l.paddingSM,borderRadius:l.borderRadiusSM,margin:0,maxHeight:400,overflow:"auto"},children:a.result.result}):o.jsx(Mn,{description:i("components.toolSteps.noResult")})}];return o.jsx(wb,{placement:"right",width:480,open:e,onClose:t,title:T,destroyOnClose:!0,children:o.jsx(Di,{defaultActiveKey:r,items:j})})},{Text:Ma}=He;function nI(e){var n;return!((n=e.streamingOutput)!=null&&n.trim())?{status:"wait",icon:o.jsx(As,{})}:{status:"process",icon:o.jsx(io,{spin:!0})}}function sI(e){var s;const t=e.call.toolCalls[0];return e.result?e.result.isError?{status:"error",icon:o.jsx(pc,{})}:{status:"finish",icon:o.jsx(ar,{})}:!((s=t==null?void 0:t.streamingOutput)!=null&&s.trim())?{status:"wait",icon:o.jsx(As,{})}:{status:"process",icon:o.jsx(io,{spin:!0})}}const gg=e=>e==null?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`,rI=({toolCalls:e,metadata:t,tools:n,defaultExpanded:s=!1,hideHeader:r=!1})=>{const{t:a}=Ie(),{token:i}=Ge.useToken(),[l,c]=p.useState(s),u=p.useMemo(()=>n&&n.length>0?n.map(O=>{const R=O.call.toolCalls[0];return{key:(R==null?void 0:R.toolCallId)||"unknown",toolName:(R==null?void 0:R.toolName)||"tool",parameters:(R==null?void 0:R.parameters)||{},streamingOutput:R==null?void 0:R.streamingOutput,info:sI(O),result:O.result,metadata:t}}):(e||[]).map(O=>({key:O.toolCallId,toolName:O.toolName,parameters:O.parameters,streamingOutput:O.streamingOutput,info:nI(O),result:void 0,metadata:t})),[n,e,t]),[m,f]=p.useState(!1),[g,b]=p.useState(null),[S,x]=p.useState("preview"),T=(O,R)=>{b(O),x(R??"preview"),f(!0)},j=()=>{f(!1)},w=p.useMemo(()=>{const O=u.findIndex(R=>R.info.status!=="finish");return O===-1?u.length-1:O},[u]),M=u.some(O=>O.info.status==="error"),_=u.filter(O=>O.info.status==="finish").length,C=u.length,L=gg(t==null?void 0:t.elapsed_ms),A=p.useMemo(()=>{const O=[a("components.toolSteps.title"),`${_}/${C}`];return L&&O.push(L),O.join(" · ")},[a,_,C,L]),B=p.useMemo(()=>u.map(O=>{var P,W,se;const R=Go(O.toolName),I=av(O.toolName,O.parameters),$=I.length>60?I.substring(0,60).trimEnd()+"…":I;let U=null,q=null;if(O.info.status==="process"&&((P=O.streamingOutput)!=null&&P.trim()))U=O.streamingOutput.split(`
|
|
196
|
+
`).slice(-3).join(`
|
|
197
|
+
`),q="live";else if((O.info.status==="finish"||O.info.status==="error")&&((se=(W=O.result)==null?void 0:W.result)!=null&&se.result)){const V=String(O.result.result.result).trimEnd();V.length>0&&(U=V.split(`
|
|
198
|
+
`).slice(0,3).join(`
|
|
199
|
+
`),q="result")}const K=O.info.status==="process"?a("components.toolSteps.running"):(t==null?void 0:t.elapsed_ms)!=null?gg(t.elapsed_ms):void 0;return{key:O.key,title:o.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:i.marginXS},children:R?o.jsxs(o.Fragment,{children:[o.jsx(Ne,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:6,fontWeight:700,fontSize:i.fontSizeSM-1,lineHeight:"18px"},children:"MCP"}),o.jsx(Ma,{strong:!0,style:{fontSize:i.fontSizeSM},children:R.toolName})]}):o.jsx(Ma,{strong:!0,style:{fontSize:i.fontSizeSM},children:O.toolName})}),subTitle:K?o.jsx(Ma,{type:"secondary",style:{fontSize:i.fontSizeSM-1},children:K}):void 0,description:o.jsxs("div",{style:{minWidth:0},children:[o.jsx(Ma,{ellipsis:!0,style:{fontSize:i.fontSizeSM,display:"block",maxWidth:"100%"},children:$}),o.jsx("div",{style:{marginTop:i.marginXXS,display:"flex",gap:i.marginXS,alignItems:"center"},children:o.jsx(ue,{type:"link",size:"small",icon:o.jsx(Fc,{}),style:{padding:0,height:"auto",fontSize:i.fontSizeSM},"data-testid":`tool-step-details-${O.key}`,onClick:()=>T(O,"preview"),children:a("components.toolSteps.details")})}),U&&o.jsxs("div",{style:{marginTop:i.marginXS},children:[o.jsx("pre",{className:"lotus-tool-step-preview",style:{margin:0,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:i.fontSizeSM,color:i.colorTextSecondary,background:"transparent",border:"none",padding:0,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:72,overflow:"hidden"},children:U}),o.jsx(ue,{type:"link",size:"small",style:{padding:0,height:"auto",fontSize:i.fontSizeSM-1},onClick:()=>T(O,q==="result"?"result":"preview"),children:q==="result"?a("components.toolSteps.viewFullResult",{defaultValue:"View full result"}):a("components.toolSteps.viewFullOutput")})]})]}),status:O.info.status,icon:O.info.icon}}),[u,i,t,a]),N=r?{background:"transparent"}:{background:"var(--lotus-tool-card-bg)",borderColor:"var(--lotus-tool-card-border)",borderWidth:1,borderStyle:"solid",borderRadius:i.borderRadiusLG,overflow:"hidden"};return o.jsxs("div",{className:"lotus-tool-steps",style:N,children:[!r&&o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:i.marginSM,padding:`${i.paddingSM}px ${i.paddingSM}px`,cursor:"pointer",userSelect:"none"},onClick:()=>c(O=>!O),"data-testid":"tool-steps-header",children:[o.jsx("span",{style:{flexShrink:0},children:l?o.jsx(Gn,{style:{color:i.colorTextSecondary,fontSize:i.fontSizeSM}}):o.jsx(Vs,{style:{color:i.colorTextSecondary,fontSize:i.fontSizeSM}})}),o.jsxs(Ma,{strong:!0,style:{fontSize:i.fontSizeSM},children:["🛠 ",A]})]}),(r||l)&&o.jsx("div",{style:{padding:r?`${i.paddingXS}px 0 0 0`:`${i.paddingXS}px ${i.paddingSM}px ${i.paddingSM}px`},children:o.jsx(vb,{direction:"vertical",size:"small",current:w,status:M?"error":"process",items:B})}),g&&o.jsx(tI,{open:m,onClose:j,call:{toolCallId:g.key,toolName:g.toolName,parameters:g.parameters,streamingOutput:g.streamingOutput},metadata:g.metadata,initialTab:S,result:g.result})]})},oh=p.memo(rI);oh.displayName="ToolStepsCard";const{Text:Jd}=He,oI=({content:e,workflowName:t,parameters:n,status:s="success",timestamp:r,onRetry:a,isLoading:i,errorMessage:l})=>{const{t:c}=Ie(),{token:u}=Ge.useToken(),[m,f]=p.useState(!1),g=p.useMemo(()=>Yu(e),[e]),b=p.useMemo(()=>typeof i=="boolean"?i:g.formattedText.trim().length===0,[g.formattedText,i]),S=p.useMemo(()=>Cj(g.formattedText),[g.formattedText]),x=g.isJson||S,T=!x||m,j=p.useMemo(()=>Mj(g.formattedText),[g.formattedText]),w=p.useMemo(()=>{if(n==null)return null;if(typeof n=="string")return Yu(n);try{return{isJson:!0,formattedText:JSON.stringify(n,null,2),parsedJson:n}}catch(C){return console.error("[WorkflowResultCard] Failed to stringify parameters:",C),{isJson:!1,formattedText:String(n)}}},[n]),M=async()=>{try{const C=g.isJson?Uo(g.parsedJson):g.formattedText;await vs(C)}catch(C){console.error("[WorkflowResultCard] Failed to copy content:",C)}},_=async()=>{if(w)try{const C=w.isJson?Uo(w.parsedJson):w.formattedText;await vs(C)}catch(C){console.error("[WorkflowResultCard] Failed to copy parameters:",C)}};return o.jsx(Ce,{size:"small",variant:"outlined",style:{borderRadius:u.borderRadiusLG,borderColor:u.colorBorderSecondary,backgroundColor:u.colorBgContainer},styles:{body:{padding:u.paddingMD}},children:o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:u.marginSM,children:[o.jsxs(be,{align:"center",justify:"space-between",children:[o.jsxs(he,{size:u.marginXS,align:"center",children:[o.jsx(r_,{style:{color:u.colorWarning}}),o.jsx(Jd,{strong:!0,children:c("components.workflowResult.userWorkflow")}),o.jsx(Ne,{color:u.colorWarning,children:t}),o.jsx(Ne,{color:yx(s),children:s})]}),o.jsxs(he,{size:"small",children:[o.jsx(bt,{title:c(m?"components.workflowResult.collapseResult":"components.workflowResult.expandResult"),children:x&&o.jsx(ue,{type:"text",size:"small",icon:m?o.jsx(o_,{}):o.jsx(a_,{}),onClick:()=>f(C=>!C)})}),o.jsx(bt,{title:c("components.workflowResult.copyResult"),children:o.jsx(ue,{type:"text",size:"small",icon:o.jsx(xs,{}),onClick:M,"aria-label":c("components.workflowResult.copyContent")})}),a&&o.jsx(bt,{title:c("components.workflowResult.retryWorkflow"),children:o.jsx(ue,{type:"text",size:"small",icon:o.jsx(lr,{}),onClick:a,"aria-label":c("components.workflowResult.retryWorkflow")})})]})]}),r&&o.jsx(Jd,{type:"secondary",style:{fontSize:u.fontSizeSM},children:new Date(r).toLocaleString()}),o.jsx(zn,{style:{margin:`${u.marginXS}px 0`}}),l&&o.jsx(Ut,{type:"error",message:c("components.workflowResult.executionFailed"),description:l,showIcon:!0,style:{marginBottom:u.marginXS}}),o.jsx(be,{vertical:!0,style:{width:"100%"},children:b?o.jsx(Rs,{tip:c("components.workflowResult.waitingForResult")}):g.isJson?o.jsx(Bo,{language:"json",style:mo,wrapLongLines:!0,customStyle:{margin:0,borderRadius:u.borderRadiusSM,backgroundColor:u.colorBgContainer,fontSize:u.fontSizeSM,maxHeight:T?"none":280,overflow:T?"auto":"hidden"},children:g.formattedText}):o.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:u.fontSizeSM,maxHeight:T?"none":280,overflow:T?"visible":"hidden",marginBottom:0},children:[T?g.formattedText:j.preview,!T&&j.isTruncated&&`
|
|
200
|
+
…`]})}),w&&o.jsxs(be,{vertical:!0,style:{width:"100%"},children:[o.jsx(zn,{style:{margin:`${u.marginXS}px 0`},children:o.jsxs(he,{size:"small",children:[o.jsx(Jd,{strong:!0,children:c("common.parameters")}),o.jsx(bt,{title:c("components.workflowResult.copyParameters"),children:o.jsx(ue,{type:"text",size:"small",icon:o.jsx(xs,{}),onClick:_,"aria-label":c("components.workflowResult.copyParameters")})})]})}),w.isJson?o.jsx(Bo,{language:"json",style:mo,wrapLongLines:!0,customStyle:{margin:0,borderRadius:u.borderRadiusSM,backgroundColor:u.colorBgContainer,fontSize:u.fontSizeSM,maxHeight:220,overflow:"auto"},children:w.formattedText}):o.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:u.fontSizeSM,marginBottom:0},children:w.formattedText})]})]})})},iv=p.memo(oI);iv.displayName="WorkflowResultCard";const aI=e=>Array.isArray(e)?e.map(t=>String(t??"")):[],nc=({sessionId:e,question:t,options:n,allowCustom:s,toolCallId:r})=>JSON.stringify({sessionId:e??null,question:t??"",options:aI(n),allowCustom:s??!0,toolCallId:r??null}),{Text:Qd}=He,iI=({sessionId:e,question:t,options:n,allowCustom:s,toolCallId:r,conclusionMarkdown:a,markdownComponents:i,markdownPlugins:l,rehypePlugins:c})=>{const{t:u}=Ie(),[m,f]=p.useState(null),g=p.useMemo(()=>nc({sessionId:e,question:t,options:n,allowCustom:s,toolCallId:r}),[e,t,n,s,r]),b=m===g;return p.useEffect(()=>{if(typeof window>"u")return;const S=x=>{var w;const j=((w=x.detail)==null?void 0:w.sessionId)??null;!e||j!==e||f(g)};return window.addEventListener(zo,S),()=>{window.removeEventListener(zo,S)}},[e,g]),o.jsxs(he,{direction:"vertical",size:"middle",style:{width:"100%"},children:[a?o.jsx(Ps,{remarkPlugins:l,rehypePlugins:c,components:i,children:a}):null,o.jsxs("div",{children:[o.jsx(Qd,{strong:!0,children:u("components.questionDialog.questionLabel","Question")}),o.jsx("div",{style:{marginTop:8},children:o.jsx(Ps,{remarkPlugins:l,rehypePlugins:c,components:i,children:t})})]}),b?o.jsx(Qd,{type:"secondary",children:u("components.questionDialog.responseSubmittedContinue","Response submitted. Continuing...")}):o.jsx(Qd,{type:"secondary",children:s?u("components.questionDialog.responseInInputHint","Use the options or input box below to respond."):u("components.questionDialog.responseByOptionHint","Please respond using the options below the input box.")})]})},{Text:Ts}=He,lI=e=>{var a;if(!e)return{cleanText:e,hints:[]};const t=e.split(`
|
|
201
|
+
`),n=[],s=[];for(const i of t){const l=i.trim(),c=l.match(/^\[User explicitly selected MCP tool:\s*(.+?)\s*\]$/);if(c){const m=c[1]??"",f=Go(m);n.push({type:"mcp",label:m,serverId:f==null?void 0:f.serverId,toolName:f==null?void 0:f.toolName});continue}const u=l.match(/^\[User explicitly selected skill:\s*(.+?)\s*\]$/);if(u){const m=u[1]??"",f=m.match(/\(ID:\s*([^)]+)\)\s*$/i),g=(a=f==null?void 0:f[1])==null?void 0:a.trim(),b=f?m.replace(/\(ID:\s*([^)]+)\)\s*$/i,"").trim():m;n.push({type:"skill",label:b||m,skillId:g});continue}s.push(i)}return{cleanText:s.join(`
|
|
202
|
+
`).trimStart(),hints:n}},cI=({sessionId:e,message:t,messageText:n,isUserToolCall:s,formatUserToolCall:r,markdownComponents:a,markdownPlugins:i,rehypePlugins:l})=>{var S;const{t:c}=Ie(),u=x=>(x??"").trim().toLowerCase()==="conclusion";if(_x(t)){const x=t.result.result??"",T=t.isError?x||c("components.toolResult.executionFailed"):void 0,j=!T&&x.trim().length===0;if(t.result.display_preference==="Hidden")return null;const w=(t.toolName??"").trim().toLowerCase(),M=w==="conclusion",_=kj(x),C=(w==="conclusion_with_options"||w==="exitplanmode"||w==="request_permissions")&&!t.isError&&_,L=w==="conclusion"?hx(x):null;return C&&_?o.jsx(iI,{sessionId:e,question:_.question,options:_.options,allowCustom:_.allow_custom,toolCallId:t.toolCallId,conclusionMarkdown:Tj(_.conclusion),markdownComponents:a,markdownPlugins:i,rehypePlugins:l}):L?o.jsx(he,{direction:"vertical",style:{width:"100%"},size:"small",children:o.jsx(Ps,{remarkPlugins:i,rehypePlugins:l,components:a,children:L})}):o.jsx(ov,{content:x,toolName:t.toolName,status:t.isError?"error":j?"warning":"success",timestamp:t.createdAt,defaultCollapsed:!M,isLoading:j,errorMessage:T})}if(AM(t)){const x=t.content??"",T=t.status==="error"?x||c("components.workflowResult.executionFailed"):void 0,j=!T&&x.trim().length===0;return o.jsx(iv,{content:x,workflowName:t.workflowName,parameters:t.parameters,status:j?"warning":t.status??"success",timestamp:t.createdAt,isLoading:j,errorMessage:T})}if(RM(t)){const x=t.toolCalls.filter(T=>!u(T.toolName));return x.length===0?null:o.jsx(oh,{toolCalls:x,metadata:t.metadata,defaultExpanded:!1})}if(t.isAuthError)return o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:"middle",children:[o.jsx(Ut,{message:c("chat.messageCard.authRequired"),description:o.jsx(Ps,{remarkPlugins:i,rehypePlugins:l,components:a,children:n}),type:"error",showIcon:!0}),o.jsx(ue,{type:"primary",icon:o.jsx(Ki,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:m,hints:f}=t.role==="user"?lI(n):{cleanText:n,hints:[]},g=t.role==="assistant"&&"type"in t&&t.type==="text"&&"metadata"in t&&typeof((S=t.metadata)==null?void 0:S.reasoning)=="string"?t.metadata.reasoning:"",b=g.trim().length>0;return t.role==="assistant"&&!n&&!b?o.jsx(Ts,{italic:!0,children:c("chat.messageCard.assistantThinking")}):o.jsxs(he,{direction:"vertical",style:{width:"100%"},size:"small",children:[b?o.jsx(ir,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:o.jsx(Ts,{strong:!0,children:c("chat.messageCard.reasoning")}),children:o.jsx(Ps,{remarkPlugins:i,rehypePlugins:l,components:a,children:g})}]}):null,f.map((x,T)=>x.type==="mcp"?o.jsx(Ut,{type:"info",showIcon:!1,message:o.jsxs(he,{wrap:!0,size:"small",children:[o.jsx(Ne,{color:"purple",children:"MCP"}),o.jsx(Ts,{strong:!0,children:c("chat.messageCard.selectedTool")}),x.serverId&&o.jsx(Ts,{type:"secondary",children:o.jsx(Ts,{code:!0,children:x.serverId})}),x.toolName&&o.jsx(Ts,{type:"secondary",children:o.jsx(Ts,{code:!0,children:x.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${T}`):o.jsx(Ut,{type:"success",showIcon:!1,message:o.jsxs(he,{wrap:!0,size:"small",children:[o.jsx(Ne,{color:"success",children:"Skill"}),o.jsx(Ts,{strong:!0,children:c("chat.messageCard.selected")}),x.label&&o.jsx(Ts,{children:x.label}),x.skillId&&o.jsx(Ts,{type:"secondary",children:o.jsx(Ts,{code:!0,children:x.skillId})})]}),style:{marginBottom:0}},`hint-skill-${T}`)),m?o.jsx(Ps,{remarkPlugins:i,rehypePlugins:l,components:a,children:s?r(m):m}):null]})},dI=p.memo(cI),{Text:Zd}=He,uI=({role:e,formattedTimestamp:t,token:n})=>{const s=e==="user",r=e==="assistant",a=s?"You":r?"Bodhi":e,i=s?"Y":r?"B":e.slice(0,1).toUpperCase();return o.jsxs(be,{align:"center",justify:"space-between",gap:n.marginXS,style:{marginBottom:n.marginXS},children:[o.jsxs(be,{align:"center",gap:10,children:[o.jsx("div",{style:{width:30,height:30,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:700,letterSpacing:"0.3px",background:s?"var(--lotus-avatar-user-bg)":r?"var(--lotus-avatar-assistant-bg)":"var(--lotus-avatar-system-bg)",color:"white",boxShadow:s?"var(--lotus-avatar-user-shadow)":r?"var(--lotus-avatar-assistant-shadow)":"var(--lotus-avatar-system-shadow)",border:"var(--lotus-avatar-border)"},children:i}),o.jsxs(be,{vertical:!0,gap:0,children:[o.jsx(Zd,{strong:!0,style:{fontSize:13,color:s?"var(--lotus-primary)":n.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:a}),o.jsx(Zd,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:s?"Prompt":r?"Assistant":"System"})]})]}),t&&o.jsx(Zd,{type:"secondary",style:{fontSize:11,whiteSpace:"nowrap",opacity:.92,padding:"4px 8px",borderRadius:999,background:"var(--lotus-timestamp-bg)",border:"1px solid var(--lotus-timestamp-border)"},children:t})]})},ah=e=>{if(e.includes("```json")){const t=e.indexOf("```json")+7,n=e.indexOf("```",t);if(n>t)return e.substring(t,n).trim()}else if(e.includes("{")){const t=e.indexOf("{"),n=e.lastIndexOf("}");if(n>t)return e.substring(t,n+1).trim()}return null},mI=e=>e==="text"||e==="plan"||e==="question"||e==="tool_call"||e==="tool_result",hI=(e,t)=>{if(t)return t;if("message_type"in e&&e.message_type){const n=e.message_type;if(mI(n))return n}if(e.role==="assistant"&&e.type==="text"){const n=typeof e.content=="string"?e.content:"";try{const s=ah(n);if(s){const r=JSON.parse(s);if(r.goal&&r.steps&&Array.isArray(r.steps))return"plan";if(r.type==="question"&&r.question)return"question"}}catch{return"text"}}return"text"},pI=(e,t)=>{if(t!=="plan"||e.role!=="assistant"||e.type!=="text")return null;const n=e.content??"";try{const s=ah(n);if(s){const r=JSON.parse(s);if(r.goal&&r.steps)return{goal:r.goal,steps:r.steps.map(a=>({step_number:a.step_number||a.stepNumber||0,action:a.action||"",reason:a.reason||a.rationale||"",tools_needed:a.tools_needed||a.tools||[],estimated_time:a.estimated_time||a.estimatedTime||""})),estimated_total_time:r.estimated_total_time||r.estimatedTotalTime||"",risks:r.risks||[],prerequisites:r.prerequisites||[]}}}catch(s){console.error("Failed to parse plan:",s)}return null},fI=(e,t)=>{if(t!=="question"||e.role!=="assistant"||e.type!=="text")return null;const n=e.content??"";try{const s=ah(n);if(s){const r=JSON.parse(s);if(r.type==="question"&&r.question)return{type:"question",question:r.question,context:r.context||"",severity:r.severity||"minor",options:r.options||[],default:r.default,allow_custom:r.allow_custom||!1}}}catch(s){console.error("Failed to parse question:",s)}return null},lv=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"?hx(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""},gI=e=>{if(!e.startsWith("/"))return e;const t=e.split(" "),n=t[0].substring(1),s=t.slice(1).join(" ");if(n.startsWith("mcp__")){const a=n.slice(5),i=a.indexOf("__");if(i>0){const l=a.slice(0,i),c=a.slice(i+2);if(l&&c)return`🔌 MCP ${l}/${c}: ${s}`}}return`🔧 ${n.replace(/_/g," ").replace(/\b\w/g,a=>a.toUpperCase())}: ${s}`},yg=e=>e.map(t=>({name:t.name,extensions:[...t.extensions]})),bg=e=>e.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",yI={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"},bI='[data-mermaid-loading="true"]';class cv{static async exportMessageText(t){const{format:n,content:s,sessionId:r=null,messageId:a=null,filenamePrefix:i}=t,l=i||["chat-message",r?bg(r.slice(0,8)):null,a?bg(a.slice(0,8)):null].filter(Boolean).join("-"),c=n==="markdown"?Us.generateTimestampedFilename(l,"md"):Us.generateTimestampedFilename(l,"pdf");if(n==="markdown"){const u=await Us.saveTextFile(s,yg(Us.FILTERS.MARKDOWN),c);return u.success?{success:!0,filename:u.filename}:{success:!1,error:u.error}}try{const u=await this.generatePdfFromText(s),m=await Us.saveBinaryFile(u,yg(Us.FILTERS.PDF),c);return m.success?{success:!0,filename:m.filename}:{success:!1,error:m.error}}catch(u){return{success:!1,error:u instanceof Error?u.message:Es.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(t){if(typeof document>"u")throw new Error(Es.t("chat.messageActions.pdfUnavailable"));const n=(await Bn(async()=>{const{default:b}=await import("./vendor-pdf-xt0MLWhy.js").then(S=>S.h);return{default:b}},__vite__mapDeps([16,1,2,3]),import.meta.url)).default,{jsPDF:s}=await Bn(async()=>{const{jsPDF:b}=await import("./vendor-pdf-xt0MLWhy.js").then(S=>S.j);return{jsPDF:b}},__vite__mapDeps([16,1,2,3]),import.meta.url),{createRoot:r}=await Bn(async()=>{const{createRoot:b}=await import("./main-NZYpmPsh.js").then(S=>S.c);return{createRoot:b}},__vite__mapDeps([4,1,2,3,5]),import.meta.url),{flushSync:a}=await Bn(async()=>{const{flushSync:b}=await import("./vendor-antd-BpW-8RO2.js").then(S=>S.R);return{flushSync:b}},__vite__mapDeps([3,2]),import.meta.url),i=rv(yI,{mermaidRenderMode:"eager"}),l=document.createElement("div");l.style.position="fixed",l.style.left="0",l.style.top="0",l.style.right="0",l.style.bottom="0",l.style.zIndex="2147483647",l.style.background="rgba(0,0,0,0.15)",l.style.display="flex",l.style.alignItems="center",l.style.justifyContent="center",l.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",l.style.fontSize="14px",l.style.color="#111";const c=document.createElement("div");c.style.background="#fff",c.style.border="1px solid rgba(0,0,0,0.12)",c.style.borderRadius="10px",c.style.padding="12px 14px",c.style.boxShadow="0 8px 24px rgba(0,0,0,0.12)",c.textContent=Es.t("chat.messageActions.exportingPdf"),l.appendChild(c);const u=document.createElement("div");u.style.position="fixed",u.style.left="0",u.style.top="0",u.style.zIndex="2147483646",u.style.pointerEvents="none",u.style.width="794px",u.style.background="#fff",u.style.color="#111",u.style.padding="24px",u.style.boxSizing="border-box",u.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",u.style.fontSize="14px",u.style.lineHeight="1.35";const m=document.createElement("style");m.textContent=`
|
|
203
|
+
.md-export { color: #111; }
|
|
204
|
+
.md-export h1 { font-size: 24px; margin: 0 0 16px; }
|
|
205
|
+
.md-export h2 { font-size: 18px; margin: 18px 0 12px; }
|
|
206
|
+
.md-export h3 { font-size: 16px; margin: 14px 0 10px; }
|
|
207
|
+
.md-export [data-mermaid-controls="true"] { display: none !important; }
|
|
208
|
+
`,u.appendChild(m);const f=document.createElement("div");f.className="md-export",u.appendChild(f),document.body.appendChild(u),document.body.appendChild(l);const g=r(f);a(()=>{g.render(fn.createElement(Ps,{remarkPlugins:[Lc,Tm],rehypePlugins:[km],components:i},t||""))});try{await this.waitForExportRenderReady(u);const b=await this.renderCanvasWithFallback(n,u),S=new s({unit:"pt",format:"a4",orientation:"portrait"}),x=S.internal.pageSize.getWidth(),T=S.internal.pageSize.getHeight(),j=24,w=x-j*2,M=T-j*2,_=b.width/w,C=Math.max(1,Math.floor(M*_));let L=0,A=0;for(;L<b.height;){const N=this.computeSmartSliceHeight(b,L,C),O=Math.max(1,Math.min(N,b.height-L)),R=document.createElement("canvas");R.width=b.width,R.height=O;const I=R.getContext("2d");if(!I)throw new Error("PDF render failed (no canvas context)");I.fillStyle="#ffffff",I.fillRect(0,0,R.width,R.height),I.drawImage(b,0,L,b.width,O,0,0,b.width,O);const $=R.toDataURL("image/jpeg",.92),U=O/_;A>0&&S.addPage(),S.addImage($,"JPEG",j,j,w,U),L+=O,A+=1}const B=S.output("arraybuffer");return new Uint8Array(B)}finally{g.unmount(),l.remove(),u.remove()}}static async waitForExportRenderReady(t){var r,a,i;await new Promise(l=>requestAnimationFrame(()=>requestAnimationFrame(()=>l()))),await((i=(a=(r=document.fonts)==null?void 0:r.ready)==null?void 0:a.catch)==null?void 0:i.call(a,()=>{}));const n=Date.now(),s=6e3;for(;Date.now()-n<s;){if(!t.querySelector(bI)){await new Promise(c=>requestAnimationFrame(()=>c()));return}await new Promise(c=>setTimeout(c,50))}}static async renderCanvasWithFallback(t,n){const s={backgroundColor:"#ffffff",scale:2,useCORS:!0,allowTaint:!0};try{const a=await t(n,{...s,foreignObjectRendering:!0});if(a.width&&a.height)return a}catch(a){console.warn("PDF capture with foreignObjectRendering=true failed:",a)}const r=await t(n,{...s,foreignObjectRendering:!1});if(!r.width||!r.height)throw new Error("PDF render failed (empty canvas)");return r}static computeSmartSliceHeight(t,n,s){const r=t.height-n;if(r<=s)return r;const a=n+s,i=Math.max(1,Math.floor(s*.72)),l=Math.max(8,Math.floor(s*.12)),c=Math.max(n+i,a-l),u=Math.min(t.height-1,a+l),m=this.findWhitespaceBreakY(t,a,c,u);return m===null||m<=n?s:m-n}static findWhitespaceBreakY(t,n,s,r){if(s>r||t.width<=0)return null;try{const a=t.getContext("2d",{willReadFrequently:!0});if(!a||typeof a.getImageData!="function")return null;const i=r-s+1,l=a.getImageData(0,s,t.width,i).data,c=t.width*4,u=Math.max(1,Math.floor(t.width/320)),m=245,f=16,g=.03;let b=null,S=Number.POSITIVE_INFINITY,x=Number.POSITIVE_INFINITY;for(let T=0;T<i;T+=1){let j=0,w=0;const M=T*c;for(let B=0;B<t.width;B+=u){const N=M+B*4,O=l[N+3];if(w+=1,O<=f)continue;const R=l[N],I=l[N+1],$=l[N+2];(R<m||I<m||$<m)&&(j+=1)}if(w===0)continue;const _=j/w,C=s+T,L=Math.abs(C-n);(_<S||_===S&&L<x)&&(S=_,x=L,b=C)}return b===null||S>g?null:b}catch{return null}}}const xI=({messageText:e,messageId:t,currentSessionId:n,onDelete:s,onRestoreChat:r,onRestoreFilesAndChat:a,cardRef:i})=>{const{message:l}=sn.useApp(),{t:c}=Ie(),[u,m]=p.useState(""),f=p.useCallback(async j=>{try{await vs(j)}catch(w){console.error("Failed to copy text:",w)}},[]),g=p.useCallback(j=>`> ${j.replace(/\n/g,`
|
|
209
|
+
> `)}`,[]),b=p.useCallback(()=>{if(!n)return;const j=g(u||e),w=new CustomEvent("reference-text",{detail:{text:j,sessionId:n}});window.dispatchEvent(w)},[g,n,e,u]),S=p.useCallback(async j=>{var _;const w=u||e;if(!w){l.warning(c("chat.messageActions.nothingToExport"));return}const M=await cv.exportMessageText({format:j,content:w,sessionId:n??null,messageId:t??null});if(M.success)l.success(c("chat.messageActions.savedFile",{filename:M.filename}));else{if((_=M.error)!=null&&_.toLowerCase().includes("cancel"))return;l.error(M.error||c("chat.messageActions.exportFailed"))}},[l,n,t,e,u,c]),x=p.useCallback(j=>{j.preventDefault(),j.stopPropagation();const w=window.getSelection(),M=w?w.toString():"";M&&i.current&&w&&i.current.contains(w.anchorNode)?m(M):m("")},[i]);return{contextMenuItems:p.useMemo(()=>{const j=[...r&&a&&n&&t?[{key:"restore-chat",label:c("chat.messageActions.restoreChat"),icon:o.jsx(i_,{}),onClick:()=>{r()}},{key:"restore-chat-files",label:c("chat.messageActions.restoreFilesAndChat"),icon:o.jsx(fb,{}),onClick:()=>{a()}},{type:"divider"}]:[],{key:"copy",label:c("chat.messageActions.copy"),icon:o.jsx(xs,{}),onClick:()=>{f(u||e)}},{key:"reference",label:c("chat.actions.referenceMessage"),icon:o.jsx(xb,{}),onClick:b},{type:"divider"},{key:"export-md",label:c("chat.messageActions.exportMarkdown"),icon:o.jsx(Wo,{}),onClick:()=>S("markdown")},{key:"export-pdf",label:c("chat.messageActions.exportPdf"),icon:o.jsx(Wo,{}),onClick:()=>S("pdf")}];return s&&t&&j.push({key:"delete",label:c("chat.messageActions.deleteMessage"),icon:o.jsx(Mr,{}),onClick:()=>s(t),danger:!0}),j},[f,S,t,e,s,r,a,b,u,n,c]),handleMouseUp:x,copyToClipboard:f,referenceMessage:b}},vI=({currentSessionId:e,updateSession:t,sendMessage:n})=>{const s=p.useCallback(async()=>{if(!e)return;const l=te.getState().chats.find(c=>c.id===e);if(l)try{t(e,{config:{...l.config,agentRole:"actor"}})}catch(c){console.error("Failed to switch to Actor role:",c)}},[e,t]),r=p.useCallback(async i=>{if(i.trim())try{await n(i.trim())}catch(l){console.error("Failed to send plan refinement:",l)}},[n]),a=p.useCallback(async i=>{if(i)try{await n(i)}catch(l){throw console.error("Failed to send answer:",l),l}},[n]);return{handleExecutePlan:s,handleRefinePlan:r,handleQuestionAnswer:a}};function at(e,t,n,s,r){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}function le(e,t,n,s){if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?s:n==="a"?s.call(e):s?s.value:t.get(e)}let dv=function(){const{crypto:e}=globalThis;if(e!=null&&e.randomUUID)return dv=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^n()&15>>+s/4).toString(16))};function sm(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const rm=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 it extends Error{}class Pn extends it{constructor(t,n,s,r){super(`${Pn.makeMessage(t,n,s)}`),this.status=t,this.headers=r,this.requestID=r==null?void 0:r.get("x-request-id"),this.error=n;const a=n;this.code=a==null?void 0:a.code,this.param=a==null?void 0:a.param,this.type=a==null?void 0:a.type}static makeMessage(t,n,s){const r=n!=null&&n.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):s;return t&&r?`${t} ${r}`:t?`${t} status code (no body)`:r||"(no status code or body)"}static generate(t,n,s,r){if(!t||!r)return new Gc({message:s,cause:rm(n)});const a=n==null?void 0:n.error;return t===400?new uv(t,a,s,r):t===401?new mv(t,a,s,r):t===403?new hv(t,a,s,r):t===404?new pv(t,a,s,r):t===409?new fv(t,a,s,r):t===422?new gv(t,a,s,r):t===429?new yv(t,a,s,r):t>=500?new bv(t,a,s,r):new Pn(t,a,s,r)}}class ys extends Pn{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class Gc extends Pn{constructor({message:t,cause:n}){super(void 0,void 0,t||"Connection error.",void 0),n&&(this.cause=n)}}class ih extends Gc{constructor({message:t}={}){super({message:t??"Request timed out."})}}class uv extends Pn{}class mv extends Pn{}class hv extends Pn{}class pv extends Pn{}class fv extends Pn{}class gv extends Pn{}class yv extends Pn{}class bv extends Pn{}class xv extends it{constructor(){super("Could not parse response content as the length limit was reached")}}class vv extends it{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class bi extends Error{constructor(t){super(t)}}const SI=/^[a-z][a-z0-9+.-]*:/i,wI=e=>SI.test(e);let Yn=e=>(Yn=Array.isArray,Yn(e)),xg=Yn;function _I(e){return typeof e!="object"?{}:e??{}}function kI(e){if(!e)return!0;for(const t in e)return!1;return!0}function TI(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function eu(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}const jI=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new it(`${e} must be an integer`);if(t<0)throw new it(`${e} must be a positive integer`);return t},CI=e=>{try{return JSON.parse(e)}catch{return}},nl=e=>new Promise(t=>setTimeout(t,e)),Ao="5.10.2",MI=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function PI(){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 EI=()=>{var n;const e=PI();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ao,"X-Stainless-OS":Sg(Deno.build.os),"X-Stainless-Arch":vg(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((n=Deno.version)==null?void 0:n.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ao,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ao,"X-Stainless-OS":Sg(globalThis.process.platform??"unknown"),"X-Stainless-Arch":vg(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=RI();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ao,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ao,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function RI(){if(typeof navigator>"u"||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:n}of e){const s=n.exec(navigator.userAgent);if(s){const r=s[1]||0,a=s[2]||0,i=s[3]||0;return{browser:t,version:`${r}.${a}.${i}`}}}return null}const vg=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",Sg=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 wg;const AI=()=>wg??(wg=EI());function II(){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 Sv(...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 wv(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Sv({start(){},async pull(n){const{done:s,value:r}=await t.next();s?n.close():n.enqueue(r)},async cancel(){var n;await((n=t.return)==null?void 0:n.call(t))}})}function _v(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const n=await t.read();return n!=null&&n.done&&t.releaseLock(),n}catch(n){throw t.releaseLock(),n}},async return(){const n=t.cancel();return t.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function OI(e){var s,r;if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await((r=(s=e[Symbol.asyncIterator]()).return)==null?void 0:r.call(s));return}const t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const $I=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),kv="RFC3986",Tv=e=>String(e),_g={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:Tv},DI="RFC1738";let om=(e,t)=>(om=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),om(e,t));const zs=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),tu=1024,LI=(e,t,n,s,r)=>{if(e.length===0)return e;let a=e;if(typeof e=="symbol"?a=Symbol.prototype.toString.call(e):typeof e!="string"&&(a=String(e)),n==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<a.length;l+=tu){const c=a.length>=tu?a.slice(l,l+tu):a,u=[];for(let m=0;m<c.length;++m){let f=c.charCodeAt(m);if(f===45||f===46||f===95||f===126||f>=48&&f<=57||f>=65&&f<=90||f>=97&&f<=122||r===DI&&(f===40||f===41)){u[u.length]=c.charAt(m);continue}if(f<128){u[u.length]=zs[f];continue}if(f<2048){u[u.length]=zs[192|f>>6]+zs[128|f&63];continue}if(f<55296||f>=57344){u[u.length]=zs[224|f>>12]+zs[128|f>>6&63]+zs[128|f&63];continue}m+=1,f=65536+((f&1023)<<10|c.charCodeAt(m)&1023),u[u.length]=zs[240|f>>18]+zs[128|f>>12&63]+zs[128|f>>6&63]+zs[128|f&63]}i+=u.join("")}return i};function FI(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function kg(e,t){if(Yn(e)){const n=[];for(let s=0;s<e.length;s+=1)n.push(t(e[s]));return n}return t(e)}const jv={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},Cv=function(e,t){Array.prototype.push.apply(e,Yn(t)?t:[t])};let Tg;const hn={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:LI,encodeValuesOnly:!1,format:kv,formatter:Tv,indices:!1,serializeDate(e){return(Tg??(Tg=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function NI(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}const nu={};function Mv(e,t,n,s,r,a,i,l,c,u,m,f,g,b,S,x,T,j){let w=e,M=j,_=0,C=!1;for(;(M=M.get(nu))!==void 0&&!C;){const O=M.get(e);if(_+=1,typeof O<"u"){if(O===_)throw new RangeError("Cyclic object value");C=!0}typeof M.get(nu)>"u"&&(_=0)}if(typeof u=="function"?w=u(t,w):w instanceof Date?w=g==null?void 0:g(w):n==="comma"&&Yn(w)&&(w=kg(w,function(O){return O instanceof Date?g==null?void 0:g(O):O})),w===null){if(a)return c&&!x?c(t,hn.encoder,T,"key",b):t;w=""}if(NI(w)||FI(w)){if(c){const O=x?t:c(t,hn.encoder,T,"key",b);return[(S==null?void 0:S(O))+"="+(S==null?void 0:S(c(w,hn.encoder,T,"value",b)))]}return[(S==null?void 0:S(t))+"="+(S==null?void 0:S(String(w)))]}const L=[];if(typeof w>"u")return L;let A;if(n==="comma"&&Yn(w))x&&c&&(w=kg(w,c)),A=[{value:w.length>0?w.join(",")||null:void 0}];else if(Yn(u))A=u;else{const O=Object.keys(w);A=m?O.sort(m):O}const B=l?String(t).replace(/\./g,"%2E"):String(t),N=s&&Yn(w)&&w.length===1?B+"[]":B;if(r&&Yn(w)&&w.length===0)return N+"[]";for(let O=0;O<A.length;++O){const R=A[O],I=typeof R=="object"&&typeof R.value<"u"?R.value:w[R];if(i&&I===null)continue;const $=f&&l?R.replace(/\./g,"%2E"):R,U=Yn(w)?typeof n=="function"?n(N,$):N:N+(f?"."+$:"["+$+"]");j.set(e,_);const q=new WeakMap;q.set(nu,j),Cv(L,Mv(I,U,n,s,r,a,i,l,n==="comma"&&x&&Yn(w)?null:c,u,m,f,g,b,S,x,T,q))}return L}function zI(e=hn){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||hn.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=kv;if(typeof e.format<"u"){if(!om(_g,e.format))throw new TypeError("Unknown format option provided.");n=e.format}const s=_g[n];let r=hn.filter;(typeof e.filter=="function"||Yn(e.filter))&&(r=e.filter);let a;if(e.arrayFormat&&e.arrayFormat in jv?a=e.arrayFormat:"indices"in e?a=e.indices?"indices":"repeat":a=hn.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:hn.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:hn.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:hn.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:hn.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?hn.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:hn.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:hn.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:hn.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:hn.encodeValuesOnly,filter:r,format:n,formatter:s,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:hn.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:hn.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:hn.strictNullHandling}}function BI(e,t={}){let n=e;const s=zI(t);let r,a;typeof s.filter=="function"?(a=s.filter,n=a("",n)):Yn(s.filter)&&(a=s.filter,r=a);const i=[];if(typeof n!="object"||n===null)return"";const l=jv[s.arrayFormat],c=l==="comma"&&s.commaRoundTrip;r||(r=Object.keys(n)),s.sort&&r.sort(s.sort);const u=new WeakMap;for(let g=0;g<r.length;++g){const b=r[g];s.skipNulls&&n[b]===null||Cv(i,Mv(n[b],b,l,c,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,u))}const m=i.join(s.delimiter);let f=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?f+="utf8=%26%2310003%3B&":f+="utf8=%E2%9C%93&"),m.length>0?f+m:""}function WI(e){let t=0;for(const r of e)t+=r.length;const n=new Uint8Array(t);let s=0;for(const r of e)n.set(r,s),s+=r.length;return n}let jg;function lh(e){let t;return(jg??(t=new globalThis.TextEncoder,jg=t.encode.bind(t)))(e)}let Cg;function Mg(e){let t;return(Cg??(t=new globalThis.TextDecoder,Cg=t.decode.bind(t)))(e)}var ts,ns;class Jc{constructor(){ts.set(this,void 0),ns.set(this,void 0),at(this,ts,new Uint8Array),at(this,ns,null)}decode(t){if(t==null)return[];const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?lh(t):t;at(this,ts,WI([le(this,ts,"f"),n]));const s=[];let r;for(;(r=qI(le(this,ts,"f"),le(this,ns,"f")))!=null;){if(r.carriage&&le(this,ns,"f")==null){at(this,ns,r.index);continue}if(le(this,ns,"f")!=null&&(r.index!==le(this,ns,"f")+1||r.carriage)){s.push(Mg(le(this,ts,"f").subarray(0,le(this,ns,"f")-1))),at(this,ts,le(this,ts,"f").subarray(le(this,ns,"f"))),at(this,ns,null);continue}const a=le(this,ns,"f")!==null?r.preceding-1:r.preceding,i=Mg(le(this,ts,"f").subarray(0,a));s.push(i),at(this,ts,le(this,ts,"f").subarray(r.index)),at(this,ns,null)}return s}flush(){return le(this,ts,"f").length?this.decode(`
|
|
210
|
+
`):[]}}ts=new WeakMap,ns=new WeakMap;Jc.NEWLINE_CHARS=new Set([`
|
|
211
|
+
`,"\r"]);Jc.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function qI(e,t){for(let r=t??0;r<e.length;r++){if(e[r]===10)return{preceding:r,index:r+1,carriage:!1};if(e[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function UI(e){for(let s=0;s<e.length-1;s++){if(e[s]===10&&e[s+1]===10||e[s]===13&&e[s+1]===13)return s+2;if(e[s]===13&&e[s+1]===10&&s+3<e.length&&e[s+2]===13&&e[s+3]===10)return s+4}return-1}const Pc={off:0,error:200,warn:300,info:400,debug:500},Pg=(e,t,n)=>{if(e){if(TI(Pc,e))return e;jn(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Pc))}`)}};function xi(){}function Fl(e,t,n){return!t||Pc[e]>Pc[n]?xi:t[e].bind(t)}const HI={error:xi,warn:xi,info:xi,debug:xi};let Eg=new WeakMap;function jn(e){const t=e.logger,n=e.logLevel??"off";if(!t)return HI;const s=Eg.get(t);if(s&&s[0]===n)return s[1];const r={error:Fl("error",t,n),warn:Fl("warn",t,n),info:Fl("info",t,n),debug:Fl("debug",t,n)};return Eg.set(t,[n,r]),r}const Kr=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,n])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var Pa;class Ks{constructor(t,n,s){this.iterator=t,Pa.set(this,void 0),this.controller=n,at(this,Pa,s)}static fromSSEResponse(t,n,s){let r=!1;const a=s?jn(s):console;async function*i(){if(r)throw new it("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let l=!1;try{for await(const c of KI(t,n))if(!l){if(c.data.startsWith("[DONE]")){l=!0;continue}if(c.event===null||c.event.startsWith("response.")||c.event.startsWith("image_edit.")||c.event.startsWith("image_generation.")||c.event.startsWith("transcript.")){let u;try{u=JSON.parse(c.data)}catch(m){throw a.error("Could not parse message into JSON:",c.data),a.error("From chunk:",c.raw),m}if(u&&u.error)throw new Pn(void 0,u.error,void 0,t.headers);yield u}else{let u;try{u=JSON.parse(c.data)}catch(m){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),m}if(c.event=="error")throw new Pn(void 0,u.error,u.message,void 0);yield{event:c.event,data:u}}}l=!0}catch(c){if(sm(c))return;throw c}finally{l||n.abort()}}return new Ks(i,n,s)}static fromReadableStream(t,n,s){let r=!1;async function*a(){const l=new Jc,c=_v(t);for await(const u of c)for(const m of l.decode(u))yield m;for(const u of l.flush())yield u}async function*i(){if(r)throw new it("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let l=!1;try{for await(const c of a())l||c&&(yield JSON.parse(c));l=!0}catch(c){if(sm(c))return;throw c}finally{l||n.abort()}}return new Ks(i,n,s)}[(Pa=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const t=[],n=[],s=this.iterator(),r=a=>({next:()=>{if(a.length===0){const i=s.next();t.push(i),n.push(i)}return a.shift()}});return[new Ks(()=>r(t),this.controller,le(this,Pa,"f")),new Ks(()=>r(n),this.controller,le(this,Pa,"f"))]}toReadableStream(){const t=this;let n;return Sv({async start(){n=t[Symbol.asyncIterator]()},async pull(s){try{const{value:r,done:a}=await n.next();if(a)return s.close();const i=lh(JSON.stringify(r)+`
|
|
212
|
+
`);s.enqueue(i)}catch(r){s.error(r)}},async cancel(){var s;await((s=n.return)==null?void 0:s.call(n))}})}}async function*KI(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new it("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 it("Attempted to iterate over a response with no body");const n=new YI,s=new Jc,r=_v(e.body);for await(const a of VI(r))for(const i of s.decode(a)){const l=n.decode(i);l&&(yield l)}for(const a of s.flush()){const i=n.decode(a);i&&(yield i)}}async function*VI(e){let t=new Uint8Array;for await(const n of e){if(n==null)continue;const s=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?lh(n):n;let r=new Uint8Array(t.length+s.length);r.set(t),r.set(s,t.length),t=r;let a;for(;(a=UI(t))!==-1;)yield t.slice(0,a),t=t.slice(a)}t.length>0&&(yield t)}class YI{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(`
|
|
213
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(t),t.startsWith(":"))return null;let[n,s,r]=XI(t,":");return r.startsWith(" ")&&(r=r.substring(1)),n==="event"?this.event=r:n==="data"&&this.data.push(r),null}}function XI(e,t){const n=e.indexOf(t);return n!==-1?[e.substring(0,n),t,e.substring(n+t.length)]:[e,"",""]}async function Pv(e,t){const{response:n,requestLogID:s,retryOfRequestLogID:r,startTime:a}=t,i=await(async()=>{var f;if(t.options.stream)return jn(e).debug("response",n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e):Ks.fromSSEResponse(n,t.controller,e);if(n.status===204)return null;if(t.options.__binaryResponse)return n;const l=n.headers.get("content-type"),c=(f=l==null?void 0:l.split(";")[0])==null?void 0:f.trim();if((c==null?void 0:c.includes("application/json"))||(c==null?void 0:c.endsWith("+json"))){const g=await n.json();return Ev(g,n)}return await n.text()})();return jn(e).debug(`[${s}] response parsed`,Kr({retryOfRequestLogID:r,url:n.url,status:n.status,body:i,durationMs:Date.now()-a})),i}function Ev(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 vi;class Qc extends Promise{constructor(t,n,s=Pv){super(r=>{r(null)}),this.responsePromise=n,this.parseResponse=s,vi.set(this,void 0),at(this,vi,t)}_thenUnwrap(t){return new Qc(le(this,vi,"f"),this.responsePromise,async(n,s)=>Ev(t(await this.parseResponse(n,s),s),s.response))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){const[t,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:n,request_id:n.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(le(this,vi,"f"),t))),this.parsedPromise}then(t,n){return this.parse().then(t,n)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}}vi=new WeakMap;var Nl;class Rv{constructor(t,n,s,r){Nl.set(this,void 0),at(this,Nl,t),this.options=r,this.response=n,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const t=this.nextPageRequestOptions();if(!t)throw new it("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await le(this,Nl,"f").requestAPIList(this.constructor,t)}async*iterPages(){let t=this;for(yield t;t.hasNextPage();)t=await t.getNextPage(),yield t}async*[(Nl=new WeakMap,Symbol.asyncIterator)](){for await(const t of this.iterPages())for(const n of t.getPaginatedItems())yield n}}class GI extends Qc{constructor(t,n,s){super(t,n,async(r,a)=>new s(r,a.response,await Pv(r,a),a.options))}async*[Symbol.asyncIterator](){const t=await this;for await(const n of t)yield n}}class Zc extends Rv{constructor(t,n,s,r){super(t,n,s,r),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class ln extends Rv{constructor(t,n,s,r){super(t,n,s,r),this.data=s.data||[],this.has_more=s.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var s;const t=this.getPaginatedItems(),n=(s=t[t.length-1])==null?void 0:s.id;return n?{...this.options,query:{..._I(this.options.query),after:n}}:null}}const Av=()=>{var e;if(typeof File>"u"){const{process:t}=globalThis,n=typeof((e=t==null?void 0:t.versions)==null?void 0:e.node)=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Ri(e,t,n){return Av(),new File(e,t??"unknown_file",n)}function sc(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 Iv=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",po=async(e,t)=>({...e,body:await QI(e.body,t)}),Rg=new WeakMap;function JI(e){const t=typeof e=="function"?e:e.fetch,n=Rg.get(t);if(n)return n;const s=(async()=>{try{const r="Response"in t?t.Response:(await t("data:,")).constructor,a=new FormData;return a.toString()!==await new r(a).text()}catch{return!0}})();return Rg.set(t,s),s}const QI=async(e,t)=>{if(!await JI(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const n=new FormData;return await Promise.all(Object.entries(e||{}).map(([s,r])=>am(n,s,r))),n},ZI=e=>e instanceof Blob&&"name"in e,am=async(e,t,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")e.append(t,String(n));else if(n instanceof Response)e.append(t,Ri([await n.blob()],sc(n)));else if(Iv(n))e.append(t,Ri([await new Response(wv(n)).blob()],sc(n)));else if(ZI(n))e.append(t,n,sc(n));else if(Array.isArray(n))await Promise.all(n.map(s=>am(e,t+"[]",s)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([s,r])=>am(e,`${t}[${s}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},Ov=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",eO=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&Ov(e),tO=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function nO(e,t,n){if(Av(),e=await e,eO(e))return e instanceof File?e:Ri([await e.arrayBuffer()],e.name);if(tO(e)){const r=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Ri(await im(r),t,n)}const s=await im(e);if(t||(t=sc(e)),!(n!=null&&n.type)){const r=s.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof r=="string"&&(n={...n,type:r})}return Ri(s,t,n)}async function im(e){var n;let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Ov(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Iv(e))for await(const s of e)t.push(...await im(s));else{const s=(n=e==null?void 0:e.constructor)==null?void 0:n.name;throw new Error(`Unexpected data type: ${typeof e}${s?`; constructor: ${s}`:""}${sO(e)}`)}return t}function sO(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(n=>`"${n}"`).join(", ")}]`}class dt{constructor(t){this._client=t}}function $v(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Ag=Object.freeze(Object.create(null)),rO=(e=$v)=>function(n,...s){if(n.length===1)return n[0];let r=!1;const a=[],i=n.reduce((m,f,g)=>{var x;/[?#]/.test(f)&&(r=!0);const b=s[g];let S=(r?encodeURIComponent:e)(""+b);return g!==s.length&&(b==null||typeof b=="object"&&b.toString===((x=Object.getPrototypeOf(Object.getPrototypeOf(b.hasOwnProperty??Ag)??Ag))==null?void 0:x.toString))&&(S=b+"",a.push({start:m.length+f.length,length:S.length,error:`Value of type ${Object.prototype.toString.call(b).slice(8,-1)} is not a valid path parameter`})),m+f+(g===s.length?"":S)},""),l=i.split(/[?#]/,1)[0],c=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let u;for(;(u=c.exec(l))!==null;)a.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(a.sort((m,f)=>m.start-f.start),a.length>0){let m=0;const f=a.reduce((g,b)=>{const S=" ".repeat(b.start-m),x="^".repeat(b.length);return m=b.start+b.length,g+S+x},"");throw new it(`Path parameters result in path with invalid segments:
|
|
214
|
+
${a.map(g=>g.error).join(`
|
|
215
|
+
`)}
|
|
216
|
+
${i}
|
|
217
|
+
${f}`)}return i},We=rO($v);let Dv=class extends dt{list(t,n={},s){return this._client.getAPIList(We`/chat/completions/${t}/messages`,ln,{query:n,...s})}};function oO(e){return typeof e.parse=="function"}const Ec=e=>(e==null?void 0:e.role)==="assistant",Lv=e=>(e==null?void 0:e.role)==="tool";var lm,rc,oc,Si,wi,ac,_i,tr,ki,Rc,Ac,Io,Fv;class ch{constructor(){lm.add(this),this.controller=new AbortController,rc.set(this,void 0),oc.set(this,()=>{}),Si.set(this,()=>{}),wi.set(this,void 0),ac.set(this,()=>{}),_i.set(this,()=>{}),tr.set(this,{}),ki.set(this,!1),Rc.set(this,!1),Ac.set(this,!1),Io.set(this,!1),at(this,rc,new Promise((t,n)=>{at(this,oc,t,"f"),at(this,Si,n,"f")})),at(this,wi,new Promise((t,n)=>{at(this,ac,t,"f"),at(this,_i,n,"f")})),le(this,rc,"f").catch(()=>{}),le(this,wi,"f").catch(()=>{})}_run(t){setTimeout(()=>{t().then(()=>{this._emitFinal(),this._emit("end")},le(this,lm,"m",Fv).bind(this))},0)}_connected(){this.ended||(le(this,oc,"f").call(this),this._emit("connect"))}get ended(){return le(this,ki,"f")}get errored(){return le(this,Rc,"f")}get aborted(){return le(this,Ac,"f")}abort(){this.controller.abort()}on(t,n){return(le(this,tr,"f")[t]||(le(this,tr,"f")[t]=[])).push({listener:n}),this}off(t,n){const s=le(this,tr,"f")[t];if(!s)return this;const r=s.findIndex(a=>a.listener===n);return r>=0&&s.splice(r,1),this}once(t,n){return(le(this,tr,"f")[t]||(le(this,tr,"f")[t]=[])).push({listener:n,once:!0}),this}emitted(t){return new Promise((n,s)=>{at(this,Io,!0),t!=="error"&&this.once("error",s),this.once(t,n)})}async done(){at(this,Io,!0),await le(this,wi,"f")}_emit(t,...n){if(le(this,ki,"f"))return;t==="end"&&(at(this,ki,!0),le(this,ac,"f").call(this));const s=le(this,tr,"f")[t];if(s&&(le(this,tr,"f")[t]=s.filter(r=>!r.once),s.forEach(({listener:r})=>r(...n))),t==="abort"){const r=n[0];!le(this,Io,"f")&&!(s!=null&&s.length)&&Promise.reject(r),le(this,Si,"f").call(this,r),le(this,_i,"f").call(this,r),this._emit("end");return}if(t==="error"){const r=n[0];!le(this,Io,"f")&&!(s!=null&&s.length)&&Promise.reject(r),le(this,Si,"f").call(this,r),le(this,_i,"f").call(this,r),this._emit("end")}}_emitFinal(){}}rc=new WeakMap,oc=new WeakMap,Si=new WeakMap,wi=new WeakMap,ac=new WeakMap,_i=new WeakMap,tr=new WeakMap,ki=new WeakMap,Rc=new WeakMap,Ac=new WeakMap,Io=new WeakMap,lm=new WeakSet,Fv=function(t){if(at(this,Rc,!0),t instanceof Error&&t.name==="AbortError"&&(t=new ys),t instanceof ys)return at(this,Ac,!0),this._emit("abort",t);if(t instanceof it)return this._emit("error",t);if(t instanceof Error){const n=new it(t.message);return n.cause=t,this._emit("error",n)}return this._emit("error",new it(String(t)))};function dh(e){return(e==null?void 0:e.$brand)==="auto-parseable-response-format"}function sl(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function aO(e,t){return!t||!Nv(t)?{...e,choices:e.choices.map(n=>({...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:uh(e,t)}function uh(e,t){const n=e.choices.map(s=>{var r;if(s.finish_reason==="length")throw new xv;if(s.finish_reason==="content_filter")throw new vv;return{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:((r=s.message.tool_calls)==null?void 0:r.map(a=>lO(t,a)))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?iO(t,s.message.content):null}}});return{...e,choices:n}}function iO(e,t){var n,s;return((n=e.response_format)==null?void 0:n.type)!=="json_schema"?null:((s=e.response_format)==null?void 0:s.type)==="json_schema"?"$parseRaw"in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function lO(e,t){var s;const n=(s=e.tools)==null?void 0:s.find(r=>{var a;return((a=r.function)==null?void 0:a.name)===t.function.name});return{...t,function:{...t.function,parsed_arguments:sl(n)?n.$parseRaw(t.function.arguments):n!=null&&n.function.strict?JSON.parse(t.function.arguments):null}}}function cO(e,t){var s;if(!e)return!1;const n=(s=e.tools)==null?void 0:s.find(r=>{var a;return((a=r.function)==null?void 0:a.name)===t.function.name});return sl(n)||(n==null?void 0:n.function.strict)||!1}function Nv(e){var t;return dh(e.response_format)?!0:((t=e.tools)==null?void 0:t.some(n=>sl(n)||n.type==="function"&&n.function.strict===!0))??!1}function dO(e){for(const t of e??[]){if(t.type!=="function")throw new it(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new it(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Nn,cm,Ic,dm,um,mm,zv,Bv;const uO=10;class Wv extends ch{constructor(){super(...arguments),Nn.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(t){var s;this._chatCompletions.push(t),this._emit("chatCompletion",t);const n=(s=t.choices[0])==null?void 0:s.message;return n&&this._addMessage(n),t}_addMessage(t,n=!0){if("content"in t||(t.content=null),this.messages.push(t),n){if(this._emit("message",t),Lv(t)&&t.content)this._emit("functionToolCallResult",t.content);else if(Ec(t)&&t.tool_calls)for(const s of t.tool_calls)s.type==="function"&&this._emit("functionToolCall",s.function)}}async finalChatCompletion(){await this.done();const t=this._chatCompletions[this._chatCompletions.length-1];if(!t)throw new it("stream ended without producing a ChatCompletion");return t}async finalContent(){return await this.done(),le(this,Nn,"m",cm).call(this)}async finalMessage(){return await this.done(),le(this,Nn,"m",Ic).call(this)}async finalFunctionToolCall(){return await this.done(),le(this,Nn,"m",dm).call(this)}async finalFunctionToolCallResult(){return await this.done(),le(this,Nn,"m",um).call(this)}async totalUsage(){return await this.done(),le(this,Nn,"m",mm).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const t=this._chatCompletions[this._chatCompletions.length-1];t&&this._emit("finalChatCompletion",t);const n=le(this,Nn,"m",Ic).call(this);n&&this._emit("finalMessage",n);const s=le(this,Nn,"m",cm).call(this);s&&this._emit("finalContent",s);const r=le(this,Nn,"m",dm).call(this);r&&this._emit("finalFunctionToolCall",r);const a=le(this,Nn,"m",um).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",le(this,Nn,"m",mm).call(this))}async _createChatCompletion(t,n,s){const r=s==null?void 0:s.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),le(this,Nn,"m",zv).call(this,n);const a=await t.chat.completions.create({...n,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(uh(a,n))}async _runChatCompletion(t,n,s){for(const r of n.messages)this._addMessage(r,!1);return await this._createChatCompletion(t,n,s)}async _runTools(t,n,s){var b,S,x;const r="tool",{tool_choice:a="auto",stream:i,...l}=n,c=typeof a!="string"&&((b=a==null?void 0:a.function)==null?void 0:b.name),{maxChatCompletions:u=uO}=s||{},m=n.tools.map(T=>{if(sl(T)){if(!T.$callback)throw new it("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:T.$callback,name:T.function.name,description:T.function.description||"",parameters:T.function.parameters,parse:T.$parseRaw,strict:!0}}}return T}),f={};for(const T of m)T.type==="function"&&(f[T.function.name||T.function.function.name]=T.function);const g="tools"in n?m.map(T=>T.type==="function"?{type:"function",function:{name:T.function.name||T.function.function.name,parameters:T.function.parameters,description:T.function.description,strict:T.function.strict}}:T):void 0;for(const T of n.messages)this._addMessage(T,!1);for(let T=0;T<u;++T){const w=(S=(await this._createChatCompletion(t,{...l,tool_choice:a,tools:g,messages:[...this.messages]},s)).choices[0])==null?void 0:S.message;if(!w)throw new it("missing message in ChatCompletion response");if(!((x=w.tool_calls)!=null&&x.length))return;for(const M of w.tool_calls){if(M.type!=="function")continue;const _=M.id,{name:C,arguments:L}=M.function,A=f[C];if(A){if(c&&c!==C){const R=`Invalid tool_call: ${JSON.stringify(C)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:r,tool_call_id:_,content:R});continue}}else{const R=`Invalid tool_call: ${JSON.stringify(C)}. Available options are: ${Object.keys(f).map(I=>JSON.stringify(I)).join(", ")}. Please try again`;this._addMessage({role:r,tool_call_id:_,content:R});continue}let B;try{B=oO(A)?await A.parse(L):L}catch(R){const I=R instanceof Error?R.message:String(R);this._addMessage({role:r,tool_call_id:_,content:I});continue}const N=await A.function(B,this),O=le(this,Nn,"m",Bv).call(this,N);if(this._addMessage({role:r,tool_call_id:_,content:O}),c)return}}}}Nn=new WeakSet,cm=function(){return le(this,Nn,"m",Ic).call(this).content??null},Ic=function(){let t=this.messages.length;for(;t-- >0;){const n=this.messages[t];if(Ec(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new it("stream ended without producing a ChatCompletionMessage with role=assistant")},dm=function(){var t,n;for(let s=this.messages.length-1;s>=0;s--){const r=this.messages[s];if(Ec(r)&&((t=r==null?void 0:r.tool_calls)!=null&&t.length))return(n=r.tool_calls.at(-1))==null?void 0:n.function}},um=function(){for(let t=this.messages.length-1;t>=0;t--){const n=this.messages[t];if(Lv(n)&&n.content!=null&&typeof n.content=="string"&&this.messages.some(s=>{var r;return s.role==="assistant"&&((r=s.tool_calls)==null?void 0:r.some(a=>a.type==="function"&&a.id===n.tool_call_id))}))return n.content}},mm=function(){const t={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:n}of this._chatCompletions)n&&(t.completion_tokens+=n.completion_tokens,t.prompt_tokens+=n.prompt_tokens,t.total_tokens+=n.total_tokens);return t},zv=function(t){if(t.n!=null&&t.n>1)throw new it("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Bv=function(t){return typeof t=="string"?t:t===void 0?"undefined":JSON.stringify(t)};class mh extends Wv{static runTools(t,n,s){const r=new mh,a={...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(t,n,a)),r}_addMessage(t,n=!0){super._addMessage(t,n),Ec(t)&&t.content&&this._emit("content",t.content)}}const qv=1,Uv=2,Hv=4,Kv=8,Vv=16,Yv=32,Xv=64,Gv=128,Jv=256,Qv=Gv|Jv,Zv=Vv|Yv|Qv|Xv,eS=qv|Uv|Zv,tS=Hv|Kv,mO=eS|tS,Sn={STR:qv,NUM:Uv,ARR:Hv,OBJ:Kv,NULL:Vv,BOOL:Yv,NAN:Xv,INFINITY:Gv,MINUS_INFINITY:Jv,INF:Qv,SPECIAL:Zv,ATOM:eS,COLLECTION:tS,ALL:mO};class hO extends Error{}class pO extends Error{}function fO(e,t=Sn.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return gO(e.trim(),t)}const gO=(e,t)=>{const n=e.length;let s=0;const r=g=>{throw new hO(`${g} at position ${s}`)},a=g=>{throw new pO(`${g} at position ${s}`)},i=()=>(f(),s>=n&&r("Unexpected end of input"),e[s]==='"'?l():e[s]==="{"?c():e[s]==="["?u():e.substring(s,s+4)==="null"||Sn.NULL&t&&n-s<4&&"null".startsWith(e.substring(s))?(s+=4,null):e.substring(s,s+4)==="true"||Sn.BOOL&t&&n-s<4&&"true".startsWith(e.substring(s))?(s+=4,!0):e.substring(s,s+5)==="false"||Sn.BOOL&t&&n-s<5&&"false".startsWith(e.substring(s))?(s+=5,!1):e.substring(s,s+8)==="Infinity"||Sn.INFINITY&t&&n-s<8&&"Infinity".startsWith(e.substring(s))?(s+=8,1/0):e.substring(s,s+9)==="-Infinity"||Sn.MINUS_INFINITY&t&&1<n-s&&n-s<9&&"-Infinity".startsWith(e.substring(s))?(s+=9,-1/0):e.substring(s,s+3)==="NaN"||Sn.NAN&t&&n-s<3&&"NaN".startsWith(e.substring(s))?(s+=3,NaN):m()),l=()=>{const g=s;let b=!1;for(s++;s<n&&(e[s]!=='"'||b&&e[s-1]==="\\");)b=e[s]==="\\"?!b:!1,s++;if(e.charAt(s)=='"')try{return JSON.parse(e.substring(g,++s-Number(b)))}catch(S){a(String(S))}else if(Sn.STR&t)try{return JSON.parse(e.substring(g,s-Number(b))+'"')}catch{return JSON.parse(e.substring(g,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},c=()=>{s++,f();const g={};try{for(;e[s]!=="}";){if(f(),s>=n&&Sn.OBJ&t)return g;const b=l();f(),s++;try{const S=i();Object.defineProperty(g,b,{value:S,writable:!0,enumerable:!0,configurable:!0})}catch(S){if(Sn.OBJ&t)return g;throw S}f(),e[s]===","&&s++}}catch{if(Sn.OBJ&t)return g;r("Expected '}' at end of object")}return s++,g},u=()=>{s++;const g=[];try{for(;e[s]!=="]";)g.push(i()),f(),e[s]===","&&s++}catch{if(Sn.ARR&t)return g;r("Expected ']' at end of array")}return s++,g},m=()=>{if(s===0){e==="-"&&Sn.NUM&t&&r("Not sure what '-' is");try{return JSON.parse(e)}catch(b){if(Sn.NUM&t)try{return e[e.length-1]==="."?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(b))}}const g=s;for(e[s]==="-"&&s++;e[s]&&!",]}".includes(e[s]);)s++;s==n&&!(Sn.NUM&t)&&r("Unterminated number literal");try{return JSON.parse(e.substring(g,s))}catch{e.substring(g,s)==="-"&&Sn.NUM&t&&r("Not sure what '-' is");try{return JSON.parse(e.substring(g,e.lastIndexOf("e")))}catch(S){a(String(S))}}},f=()=>{for(;s<n&&`
|
|
218
|
+
\r `.includes(e[s]);)s++};return i()},Ig=e=>fO(e,Sn.ALL^Sn.NUM);var mn,er,Mo,br,su,zl,ru,ou,au,Bl,iu,Og;class qi extends Wv{constructor(t){super(),mn.add(this),er.set(this,void 0),Mo.set(this,void 0),br.set(this,void 0),at(this,er,t),at(this,Mo,[])}get currentChatCompletionSnapshot(){return le(this,br,"f")}static fromReadableStream(t){const n=new qi(null);return n._run(()=>n._fromReadableStream(t)),n}static createChatCompletion(t,n,s){const r=new qi(n);return r._run(()=>r._runChatCompletion(t,{...n,stream:!0},{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(t,n,s){var i;super._createChatCompletion;const r=s==null?void 0:s.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),le(this,mn,"m",su).call(this);const a=await t.chat.completions.create({...n,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(const l of a)le(this,mn,"m",ru).call(this,l);if((i=a.controller.signal)!=null&&i.aborted)throw new ys;return this._addChatCompletion(le(this,mn,"m",Bl).call(this))}async _fromReadableStream(t,n){var i;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),le(this,mn,"m",su).call(this),this._connected();const r=Ks.fromReadableStream(t,this.controller);let a;for await(const l of r)a&&a!==l.id&&this._addChatCompletion(le(this,mn,"m",Bl).call(this)),le(this,mn,"m",ru).call(this,l),a=l.id;if((i=r.controller.signal)!=null&&i.aborted)throw new ys;return this._addChatCompletion(le(this,mn,"m",Bl).call(this))}[(er=new WeakMap,Mo=new WeakMap,br=new WeakMap,mn=new WeakSet,su=function(){this.ended||at(this,br,void 0)},zl=function(n){let s=le(this,Mo,"f")[n.index];return s||(s={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},le(this,Mo,"f")[n.index]=s,s)},ru=function(n){var r,a,i,l,c,u,m,f,g,b,S,x,T,j,w;if(this.ended)return;const s=le(this,mn,"m",Og).call(this,n);this._emit("chunk",n,s);for(const M of n.choices){const _=s.choices[M.index];M.delta.content!=null&&((r=_.message)==null?void 0:r.role)==="assistant"&&((a=_.message)!=null&&a.content)&&(this._emit("content",M.delta.content,_.message.content),this._emit("content.delta",{delta:M.delta.content,snapshot:_.message.content,parsed:_.message.parsed})),M.delta.refusal!=null&&((i=_.message)==null?void 0:i.role)==="assistant"&&((l=_.message)!=null&&l.refusal)&&this._emit("refusal.delta",{delta:M.delta.refusal,snapshot:_.message.refusal}),((c=M.logprobs)==null?void 0:c.content)!=null&&((u=_.message)==null?void 0:u.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(m=M.logprobs)==null?void 0:m.content,snapshot:((f=_.logprobs)==null?void 0:f.content)??[]}),((g=M.logprobs)==null?void 0:g.refusal)!=null&&((b=_.message)==null?void 0:b.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(S=M.logprobs)==null?void 0:S.refusal,snapshot:((x=_.logprobs)==null?void 0:x.refusal)??[]});const C=le(this,mn,"m",zl).call(this,_);_.finish_reason&&(le(this,mn,"m",au).call(this,_),C.current_tool_call_index!=null&&le(this,mn,"m",ou).call(this,_,C.current_tool_call_index));for(const L of M.delta.tool_calls??[])C.current_tool_call_index!==L.index&&(le(this,mn,"m",au).call(this,_),C.current_tool_call_index!=null&&le(this,mn,"m",ou).call(this,_,C.current_tool_call_index)),C.current_tool_call_index=L.index;for(const L of M.delta.tool_calls??[]){const A=(T=_.message.tool_calls)==null?void 0:T[L.index];A!=null&&A.type&&((A==null?void 0:A.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(j=A.function)==null?void 0:j.name,index:L.index,arguments:A.function.arguments,parsed_arguments:A.function.parsed_arguments,arguments_delta:((w=L.function)==null?void 0:w.arguments)??""}):(A==null||A.type,void 0))}}},ou=function(n,s){var i,l,c;if(le(this,mn,"m",zl).call(this,n).done_tool_calls.has(s))return;const a=(i=n.message.tool_calls)==null?void 0:i[s];if(!a)throw new Error("no tool call snapshot");if(!a.type)throw new Error("tool call snapshot missing `type`");if(a.type==="function"){const u=(c=(l=le(this,er,"f"))==null?void 0:l.tools)==null?void 0:c.find(m=>m.type==="function"&&m.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:s,arguments:a.function.arguments,parsed_arguments:sl(u)?u.$parseRaw(a.function.arguments):u!=null&&u.function.strict?JSON.parse(a.function.arguments):null})}else a.type},au=function(n){var r,a;const s=le(this,mn,"m",zl).call(this,n);if(n.message.content&&!s.content_done){s.content_done=!0;const i=le(this,mn,"m",iu).call(this);this._emit("content.done",{content:n.message.content,parsed:i?i.$parseRaw(n.message.content):null})}n.message.refusal&&!s.refusal_done&&(s.refusal_done=!0,this._emit("refusal.done",{refusal:n.message.refusal})),(r=n.logprobs)!=null&&r.content&&!s.logprobs_content_done&&(s.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:n.logprobs.content})),(a=n.logprobs)!=null&&a.refusal&&!s.logprobs_refusal_done&&(s.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:n.logprobs.refusal}))},Bl=function(){if(this.ended)throw new it("stream has ended, this shouldn't happen");const n=le(this,br,"f");if(!n)throw new it("request ended without sending any chunks");return at(this,br,void 0),at(this,Mo,[]),yO(n,le(this,er,"f"))},iu=function(){var s;const n=(s=le(this,er,"f"))==null?void 0:s.response_format;return dh(n)?n:null},Og=function(n){var s,r,a,i;let l=le(this,br,"f");const{choices:c,...u}=n;l?Object.assign(l,u):l=at(this,br,{...u,choices:[]});for(const{delta:m,finish_reason:f,index:g,logprobs:b=null,...S}of n.choices){let x=l.choices[g];if(x||(x=l.choices[g]={finish_reason:f,index:g,message:{},logprobs:b,...S}),b)if(!x.logprobs)x.logprobs=Object.assign({},b);else{const{content:L,refusal:A,...B}=b;Object.assign(x.logprobs,B),L&&((s=x.logprobs).content??(s.content=[]),x.logprobs.content.push(...L)),A&&((r=x.logprobs).refusal??(r.refusal=[]),x.logprobs.refusal.push(...A))}if(f&&(x.finish_reason=f,le(this,er,"f")&&Nv(le(this,er,"f")))){if(f==="length")throw new xv;if(f==="content_filter")throw new vv}if(Object.assign(x,S),!m)continue;const{content:T,refusal:j,function_call:w,role:M,tool_calls:_,...C}=m;if(Object.assign(x.message,C),j&&(x.message.refusal=(x.message.refusal||"")+j),M&&(x.message.role=M),w&&(x.message.function_call?(w.name&&(x.message.function_call.name=w.name),w.arguments&&((a=x.message.function_call).arguments??(a.arguments=""),x.message.function_call.arguments+=w.arguments)):x.message.function_call=w),T&&(x.message.content=(x.message.content||"")+T,!x.message.refusal&&le(this,mn,"m",iu).call(this)&&(x.message.parsed=Ig(x.message.content))),_){x.message.tool_calls||(x.message.tool_calls=[]);for(const{index:L,id:A,type:B,function:N,...O}of _){const R=(i=x.message.tool_calls)[L]??(i[L]={});Object.assign(R,O),A&&(R.id=A),B&&(R.type=B),N&&(R.function??(R.function={name:N.name??"",arguments:""})),N!=null&&N.name&&(R.function.name=N.name),N!=null&&N.arguments&&(R.function.arguments+=N.arguments,cO(le(this,er,"f"),R)&&(R.function.parsed_arguments=Ig(R.function.arguments)))}}}return l},Symbol.asyncIterator)](){const t=[],n=[];let s=!1;return this.on("chunk",r=>{const a=n.shift();a?a.resolve(r):t.push(r)}),this.on("end",()=>{s=!0;for(const r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),this.on("error",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((a,i)=>n.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Ks(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function yO(e,t){const{id:n,choices:s,created:r,model:a,system_fingerprint:i,...l}=e,c={...l,id:n,choices:s.map(({message:u,finish_reason:m,index:f,logprobs:g,...b})=>{if(!m)throw new it(`missing finish_reason for choice ${f}`);const{content:S=null,function_call:x,tool_calls:T,...j}=u,w=u.role;if(!w)throw new it(`missing role for choice ${f}`);if(x){const{arguments:M,name:_}=x;if(M==null)throw new it(`missing function_call.arguments for choice ${f}`);if(!_)throw new it(`missing function_call.name for choice ${f}`);return{...b,message:{content:S,function_call:{arguments:M,name:_},role:w,refusal:u.refusal??null},finish_reason:m,index:f,logprobs:g}}return T?{...b,index:f,finish_reason:m,logprobs:g,message:{...j,role:w,content:S,refusal:u.refusal??null,tool_calls:T.map((M,_)=>{const{function:C,type:L,id:A,...B}=M,{arguments:N,name:O,...R}=C||{};if(A==null)throw new it(`missing choices[${f}].tool_calls[${_}].id
|
|
219
|
+
${Wl(e)}`);if(L==null)throw new it(`missing choices[${f}].tool_calls[${_}].type
|
|
220
|
+
${Wl(e)}`);if(O==null)throw new it(`missing choices[${f}].tool_calls[${_}].function.name
|
|
221
|
+
${Wl(e)}`);if(N==null)throw new it(`missing choices[${f}].tool_calls[${_}].function.arguments
|
|
222
|
+
${Wl(e)}`);return{...B,id:A,type:L,function:{...R,name:O,arguments:N}}})}}:{...b,message:{...j,content:S,role:w,refusal:u.refusal??null},finish_reason:m,index:f,logprobs:g}}),created:r,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return aO(c,t)}function Wl(e){return JSON.stringify(e)}class Oc extends qi{static fromReadableStream(t){const n=new Oc(null);return n._run(()=>n._fromReadableStream(t)),n}static runTools(t,n,s){const r=new Oc(n),a={...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(t,n,a)),r}}let hh=class extends dt{constructor(){super(...arguments),this.messages=new Dv(this._client)}create(t,n){return this._client.post("/chat/completions",{body:t,...n,stream:t.stream??!1})}retrieve(t,n){return this._client.get(We`/chat/completions/${t}`,n)}update(t,n,s){return this._client.post(We`/chat/completions/${t}`,{body:n,...s})}list(t={},n){return this._client.getAPIList("/chat/completions",ln,{query:t,...n})}delete(t,n){return this._client.delete(We`/chat/completions/${t}`,n)}parse(t,n){return dO(t.tools),this._client.chat.completions.create(t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(s=>uh(s,t))}runTools(t,n){return t.stream?Oc.runTools(this._client,t,n):mh.runTools(this._client,t,n)}stream(t,n){return qi.createChatCompletion(this._client,t,n)}};hh.Messages=Dv;class ph extends dt{constructor(){super(...arguments),this.completions=new hh(this._client)}}ph.Completions=hh;const nS=Symbol("brand.privateNullableHeaders");function*bO(e){if(!e)return;if(nS in e){const{values:s,nulls:r}=e;yield*s.entries();for(const a of r)yield[a,null];return}let t=!1,n;e instanceof Headers?n=e.entries():xg(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let s of n){const r=s[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const a=xg(s[1])?s[1]:[s[1]];let i=!1;for(const l of a)l!==void 0&&(t&&!i&&(i=!0,yield[r,null]),yield[r,l])}}const nt=e=>{const t=new Headers,n=new Set;for(const s of e){const r=new Set;for(const[a,i]of bO(s)){const l=a.toLowerCase();r.has(l)||(t.delete(a),r.add(l)),i===null?(t.delete(a),n.add(l)):(t.append(a,i),n.delete(l))}}return{[nS]:!0,values:t,nulls:n}};class sS extends dt{create(t,n){return this._client.post("/audio/speech",{body:t,...n,headers:nt([{Accept:"application/octet-stream"},n==null?void 0:n.headers]),__binaryResponse:!0})}}class rS extends dt{create(t,n){return this._client.post("/audio/transcriptions",po({body:t,...n,stream:t.stream??!1,__metadata:{model:t.model}},this._client))}}class oS extends dt{create(t,n){return this._client.post("/audio/translations",po({body:t,...n,__metadata:{model:t.model}},this._client))}}class rl extends dt{constructor(){super(...arguments),this.transcriptions=new rS(this._client),this.translations=new oS(this._client),this.speech=new sS(this._client)}}rl.Transcriptions=rS;rl.Translations=oS;rl.Speech=sS;class aS extends dt{create(t,n){return this._client.post("/batches",{body:t,...n})}retrieve(t,n){return this._client.get(We`/batches/${t}`,n)}list(t={},n){return this._client.getAPIList("/batches",ln,{query:t,...n})}cancel(t,n){return this._client.post(We`/batches/${t}/cancel`,n)}}class iS extends dt{create(t,n){return this._client.post("/assistants",{body:t,...n,headers:nt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(We`/assistants/${t}`,{...n,headers:nt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,n,s){return this._client.post(We`/assistants/${t}`,{body:n,...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}list(t={},n){return this._client.getAPIList("/assistants",ln,{query:t,...n,headers:nt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,n){return this._client.delete(We`/assistants/${t}`,{...n,headers:nt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class lS extends dt{create(t,n){return this._client.post("/realtime/sessions",{body:t,...n,headers:nt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class cS extends dt{create(t,n){return this._client.post("/realtime/transcription_sessions",{body:t,...n,headers:nt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class ed extends dt{constructor(){super(...arguments),this.sessions=new lS(this._client),this.transcriptionSessions=new cS(this._client)}}ed.Sessions=lS;ed.TranscriptionSessions=cS;class dS extends dt{create(t,n,s){return this._client.post(We`/threads/${t}/messages`,{body:n,...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,n,s){const{thread_id:r}=n;return this._client.get(We`/threads/${r}/messages/${t}`,{...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,n,s){const{thread_id:r,...a}=n;return this._client.post(We`/threads/${r}/messages/${t}`,{body:a,...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}list(t,n={},s){return this._client.getAPIList(We`/threads/${t}/messages`,ln,{query:n,...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}delete(t,n,s){const{thread_id:r}=n;return this._client.delete(We`/threads/${r}/messages/${t}`,{...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class uS extends dt{retrieve(t,n,s){const{thread_id:r,run_id:a,...i}=n;return this._client.get(We`/threads/${r}/runs/${a}/steps/${t}`,{query:i,...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}list(t,n,s){const{thread_id:r,...a}=n;return this._client.getAPIList(We`/threads/${r}/runs/${t}/steps`,ln,{query:a,...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}const xO=e=>{if(typeof Buffer<"u"){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{const t=atob(e),n=t.length,s=new Uint8Array(n);for(let r=0;r<n;r++)s[r]=t.charCodeAt(r);return Array.from(new Float32Array(s.buffer))}};var lu={};const Po=e=>{var t,n,s,r;if(typeof globalThis.process<"u")return((t=lu==null?void 0:lu[e])==null?void 0:t.trim())??void 0;if(typeof globalThis.Deno<"u")return(r=(s=(n=globalThis.Deno.env)==null?void 0:n.get)==null?void 0:s.call(n,e))==null?void 0:r.trim()};var Cn,ro,hm,Ws,ic,js,oo,Do,Xr,$c,ss,lc,cc,Ai,Ti,ji,$g,Dg,Lg,Fg,Ng,zg,Bg;class Ii extends ch{constructor(){super(...arguments),Cn.add(this),hm.set(this,[]),Ws.set(this,{}),ic.set(this,{}),js.set(this,void 0),oo.set(this,void 0),Do.set(this,void 0),Xr.set(this,void 0),$c.set(this,void 0),ss.set(this,void 0),lc.set(this,void 0),cc.set(this,void 0),Ai.set(this,void 0)}[(hm=new WeakMap,Ws=new WeakMap,ic=new WeakMap,js=new WeakMap,oo=new WeakMap,Do=new WeakMap,Xr=new WeakMap,$c=new WeakMap,ss=new WeakMap,lc=new WeakMap,cc=new WeakMap,Ai=new WeakMap,Cn=new WeakSet,Symbol.asyncIterator)](){const t=[],n=[];let s=!1;return this.on("event",r=>{const a=n.shift();a?a.resolve(r):t.push(r)}),this.on("end",()=>{s=!0;for(const r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),this.on("error",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((a,i)=>n.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(t){const n=new ro;return n._run(()=>n._fromReadableStream(t)),n}async _fromReadableStream(t,n){var a;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),this._connected();const r=Ks.fromReadableStream(t,this.controller);for await(const i of r)le(this,Cn,"m",Ti).call(this,i);if((a=r.controller.signal)!=null&&a.aborted)throw new ys;return this._addRun(le(this,Cn,"m",ji).call(this))}toReadableStream(){return new Ks(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,n,s,r){const a=new ro;return a._run(()=>a._runToolAssistantStream(t,n,s,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(t,n,s,r){var c;const a=r==null?void 0:r.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...s,stream:!0},l=await t.submitToolOutputs(n,i,{...r,signal:this.controller.signal});this._connected();for await(const u of l)le(this,Cn,"m",Ti).call(this,u);if((c=l.controller.signal)!=null&&c.aborted)throw new ys;return this._addRun(le(this,Cn,"m",ji).call(this))}static createThreadAssistantStream(t,n,s){const r=new ro;return r._run(()=>r._threadAssistantStream(t,n,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),r}static createAssistantStream(t,n,s,r){const a=new ro;return a._run(()=>a._runAssistantStream(t,n,s,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return le(this,lc,"f")}currentRun(){return le(this,cc,"f")}currentMessageSnapshot(){return le(this,js,"f")}currentRunStepSnapshot(){return le(this,Ai,"f")}async finalRunSteps(){return await this.done(),Object.values(le(this,Ws,"f"))}async finalMessages(){return await this.done(),Object.values(le(this,ic,"f"))}async finalRun(){if(await this.done(),!le(this,oo,"f"))throw Error("Final run was not received.");return le(this,oo,"f")}async _createThreadAssistantStream(t,n,s){var l;const r=s==null?void 0:s.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const a={...n,stream:!0},i=await t.createAndRun(a,{...s,signal:this.controller.signal});this._connected();for await(const c of i)le(this,Cn,"m",Ti).call(this,c);if((l=i.controller.signal)!=null&&l.aborted)throw new ys;return this._addRun(le(this,Cn,"m",ji).call(this))}async _createAssistantStream(t,n,s,r){var c;const a=r==null?void 0:r.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...s,stream:!0},l=await t.create(n,i,{...r,signal:this.controller.signal});this._connected();for await(const u of l)le(this,Cn,"m",Ti).call(this,u);if((c=l.controller.signal)!=null&&c.aborted)throw new ys;return this._addRun(le(this,Cn,"m",ji).call(this))}static accumulateDelta(t,n){for(const[s,r]of Object.entries(n)){if(!t.hasOwnProperty(s)){t[s]=r;continue}let a=t[s];if(a==null){t[s]=r;continue}if(s==="index"||s==="type"){t[s]=r;continue}if(typeof a=="string"&&typeof r=="string")a+=r;else if(typeof a=="number"&&typeof r=="number")a+=r;else if(eu(a)&&eu(r))a=this.accumulateDelta(a,r);else if(Array.isArray(a)&&Array.isArray(r)){if(a.every(i=>typeof i=="string"||typeof i=="number")){a.push(...r);continue}for(const i of r){if(!eu(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const l=i.index;if(l==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);const c=a[l];c==null?a.push(i):a[l]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${s}, deltaValue: ${r}, accValue: ${a}`);t[s]=a}return t}_addRun(t){return t}async _threadAssistantStream(t,n,s){return await this._createThreadAssistantStream(n,t,s)}async _runAssistantStream(t,n,s,r){return await this._createAssistantStream(n,t,s,r)}async _runToolAssistantStream(t,n,s,r){return await this._createToolAssistantStream(n,t,s,r)}}ro=Ii,Ti=function(t){if(!this.ended)switch(at(this,lc,t),le(this,Cn,"m",Lg).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":le(this,Cn,"m",Bg).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":le(this,Cn,"m",Dg).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":le(this,Cn,"m",$g).call(this,t);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},ji=function(){if(this.ended)throw new it("stream has ended, this shouldn't happen");if(!le(this,oo,"f"))throw Error("Final run has not been received");return le(this,oo,"f")},$g=function(t){const[n,s]=le(this,Cn,"m",Ng).call(this,t,le(this,js,"f"));at(this,js,n),le(this,ic,"f")[n.id]=n;for(const r of s){const a=n.content[r.index];(a==null?void 0:a.type)=="text"&&this._emit("textCreated",a.text)}switch(t.event){case"thread.message.created":this._emit("messageCreated",t.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",t.data.delta,n),t.data.delta.content)for(const r of t.data.delta.content){if(r.type=="text"&&r.text){let a=r.text,i=n.content[r.index];if(i&&i.type=="text")this._emit("textDelta",a,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(r.index!=le(this,Do,"f")){if(le(this,Xr,"f"))switch(le(this,Xr,"f").type){case"text":this._emit("textDone",le(this,Xr,"f").text,le(this,js,"f"));break;case"image_file":this._emit("imageFileDone",le(this,Xr,"f").image_file,le(this,js,"f"));break}at(this,Do,r.index)}at(this,Xr,n.content[r.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(le(this,Do,"f")!==void 0){const r=t.data.content[le(this,Do,"f")];if(r)switch(r.type){case"image_file":this._emit("imageFileDone",r.image_file,le(this,js,"f"));break;case"text":this._emit("textDone",r.text,le(this,js,"f"));break}}le(this,js,"f")&&this._emit("messageDone",t.data),at(this,js,void 0)}},Dg=function(t){const n=le(this,Cn,"m",Fg).call(this,t);switch(at(this,Ai,n),t.event){case"thread.run.step.created":this._emit("runStepCreated",t.data);break;case"thread.run.step.delta":const s=t.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&n.step_details.type=="tool_calls")for(const a of s.step_details.tool_calls)a.index==le(this,$c,"f")?this._emit("toolCallDelta",a,n.step_details.tool_calls[a.index]):(le(this,ss,"f")&&this._emit("toolCallDone",le(this,ss,"f")),at(this,$c,a.index),at(this,ss,n.step_details.tool_calls[a.index]),le(this,ss,"f")&&this._emit("toolCallCreated",le(this,ss,"f")));this._emit("runStepDelta",t.data.delta,n);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":at(this,Ai,void 0),t.data.step_details.type=="tool_calls"&&le(this,ss,"f")&&(this._emit("toolCallDone",le(this,ss,"f")),at(this,ss,void 0)),this._emit("runStepDone",t.data,n);break}},Lg=function(t){le(this,hm,"f").push(t),this._emit("event",t)},Fg=function(t){switch(t.event){case"thread.run.step.created":return le(this,Ws,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let n=le(this,Ws,"f")[t.data.id];if(!n)throw Error("Received a RunStepDelta before creation of a snapshot");let s=t.data;if(s.delta){const r=ro.accumulateDelta(n,s.delta);le(this,Ws,"f")[t.data.id]=r}return le(this,Ws,"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":le(this,Ws,"f")[t.data.id]=t.data;break}if(le(this,Ws,"f")[t.data.id])return le(this,Ws,"f")[t.data.id];throw new Error("No snapshot available")},Ng=function(t,n){let s=[];switch(t.event){case"thread.message.created":return[t.data,s];case"thread.message.delta":if(!n)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let r=t.data;if(r.delta.content)for(const a of r.delta.content)if(a.index in n.content){let i=n.content[a.index];n.content[a.index]=le(this,Cn,"m",zg).call(this,a,i)}else n.content[a.index]=a,s.push(a);return[n,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(n)return[n,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},zg=function(t,n){return ro.accumulateDelta(n,t)},Bg=function(t){switch(at(this,cc,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":at(this,oo,t.data),le(this,ss,"f")&&(this._emit("toolCallDone",le(this,ss,"f")),at(this,ss,void 0));break}};let fh=class extends dt{constructor(){super(...arguments),this.steps=new uS(this._client)}create(t,n,s){const{include:r,...a}=n;return this._client.post(We`/threads/${t}/runs`,{query:{include:r},body:a,...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers]),stream:n.stream??!1})}retrieve(t,n,s){const{thread_id:r}=n;return this._client.get(We`/threads/${r}/runs/${t}`,{...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,n,s){const{thread_id:r,...a}=n;return this._client.post(We`/threads/${r}/runs/${t}`,{body:a,...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}list(t,n={},s){return this._client.getAPIList(We`/threads/${t}/runs`,ln,{query:n,...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}cancel(t,n,s){const{thread_id:r}=n;return this._client.post(We`/threads/${r}/runs/${t}/cancel`,{...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}async createAndPoll(t,n,s){const r=await this.create(t,n,s);return await this.poll(r.id,{thread_id:t},s)}createAndStream(t,n,s){return Ii.createAssistantStream(t,this._client.beta.threads.runs,n,s)}async poll(t,n,s){var a;const r=nt([s==null?void 0:s.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=s==null?void 0:s.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const{data:i,response:l}=await this.retrieve(t,n,{...s,headers:{...s==null?void 0:s.headers,...r}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let c=5e3;if(s!=null&&s.pollIntervalMs)c=s.pollIntervalMs;else{const u=l.headers.get("openai-poll-after-ms");if(u){const m=parseInt(u);isNaN(m)||(c=m)}}await nl(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(t,n,s){return Ii.createAssistantStream(t,this._client.beta.threads.runs,n,s)}submitToolOutputs(t,n,s){const{thread_id:r,...a}=n;return this._client.post(We`/threads/${r}/runs/${t}/submit_tool_outputs`,{body:a,...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers]),stream:n.stream??!1})}async submitToolOutputsAndPoll(t,n,s){const r=await this.submitToolOutputs(t,n,s);return await this.poll(r.id,n,s)}submitToolOutputsStream(t,n,s){return Ii.createToolAssistantStream(t,this._client.beta.threads.runs,n,s)}};fh.Steps=uS;class td extends dt{constructor(){super(...arguments),this.runs=new fh(this._client),this.messages=new dS(this._client)}create(t={},n){return this._client.post("/threads",{body:t,...n,headers:nt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(We`/threads/${t}`,{...n,headers:nt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,n,s){return this._client.post(We`/threads/${t}`,{body:n,...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}delete(t,n){return this._client.delete(We`/threads/${t}`,{...n,headers:nt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}createAndRun(t,n){return this._client.post("/threads/runs",{body:t,...n,headers:nt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:t.stream??!1})}async createAndRunPoll(t,n){const s=await this.createAndRun(t,n);return await this.runs.poll(s.id,{thread_id:s.thread_id},n)}createAndRunStream(t,n){return Ii.createThreadAssistantStream(t,this._client.beta.threads,n)}}td.Runs=fh;td.Messages=dS;class ol extends dt{constructor(){super(...arguments),this.realtime=new ed(this._client),this.assistants=new iS(this._client),this.threads=new td(this._client)}}ol.Realtime=ed;ol.Assistants=iS;ol.Threads=td;class mS extends dt{create(t,n){return this._client.post("/completions",{body:t,...n,stream:t.stream??!1})}}let hS=class extends dt{retrieve(t,n,s){const{container_id:r}=n;return this._client.get(We`/containers/${r}/files/${t}/content`,{...s,headers:nt([{Accept:"application/binary"},s==null?void 0:s.headers]),__binaryResponse:!0})}},gh=class extends dt{constructor(){super(...arguments),this.content=new hS(this._client)}create(t,n,s){return this._client.post(We`/containers/${t}/files`,po({body:n,...s},this._client))}retrieve(t,n,s){const{container_id:r}=n;return this._client.get(We`/containers/${r}/files/${t}`,s)}list(t,n={},s){return this._client.getAPIList(We`/containers/${t}/files`,ln,{query:n,...s})}delete(t,n,s){const{container_id:r}=n;return this._client.delete(We`/containers/${r}/files/${t}`,{...s,headers:nt([{Accept:"*/*"},s==null?void 0:s.headers])})}};gh.Content=hS;class yh extends dt{constructor(){super(...arguments),this.files=new gh(this._client)}create(t,n){return this._client.post("/containers",{body:t,...n})}retrieve(t,n){return this._client.get(We`/containers/${t}`,n)}list(t={},n){return this._client.getAPIList("/containers",ln,{query:t,...n})}delete(t,n){return this._client.delete(We`/containers/${t}`,{...n,headers:nt([{Accept:"*/*"},n==null?void 0:n.headers])})}}yh.Files=gh;class pS extends dt{create(t,n){const s=!!t.encoding_format;let r=s?t.encoding_format:"base64";s&&jn(this._client).debug("embeddings/user defined encoding_format:",t.encoding_format);const a=this._client.post("/embeddings",{body:{...t,encoding_format:r},...n});return s?a:(jn(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(i=>(i&&i.data&&i.data.forEach(l=>{const c=l.embedding;l.embedding=xO(c)}),i)))}}class fS extends dt{retrieve(t,n,s){const{eval_id:r,run_id:a}=n;return this._client.get(We`/evals/${r}/runs/${a}/output_items/${t}`,s)}list(t,n,s){const{eval_id:r,...a}=n;return this._client.getAPIList(We`/evals/${r}/runs/${t}/output_items`,ln,{query:a,...s})}}class bh extends dt{constructor(){super(...arguments),this.outputItems=new fS(this._client)}create(t,n,s){return this._client.post(We`/evals/${t}/runs`,{body:n,...s})}retrieve(t,n,s){const{eval_id:r}=n;return this._client.get(We`/evals/${r}/runs/${t}`,s)}list(t,n={},s){return this._client.getAPIList(We`/evals/${t}/runs`,ln,{query:n,...s})}delete(t,n,s){const{eval_id:r}=n;return this._client.delete(We`/evals/${r}/runs/${t}`,s)}cancel(t,n,s){const{eval_id:r}=n;return this._client.post(We`/evals/${r}/runs/${t}`,s)}}bh.OutputItems=fS;class xh extends dt{constructor(){super(...arguments),this.runs=new bh(this._client)}create(t,n){return this._client.post("/evals",{body:t,...n})}retrieve(t,n){return this._client.get(We`/evals/${t}`,n)}update(t,n,s){return this._client.post(We`/evals/${t}`,{body:n,...s})}list(t={},n){return this._client.getAPIList("/evals",ln,{query:t,...n})}delete(t,n){return this._client.delete(We`/evals/${t}`,n)}}xh.Runs=bh;let gS=class extends dt{create(t,n){return this._client.post("/files",po({body:t,...n},this._client))}retrieve(t,n){return this._client.get(We`/files/${t}`,n)}list(t={},n){return this._client.getAPIList("/files",ln,{query:t,...n})}delete(t,n){return this._client.delete(We`/files/${t}`,n)}content(t,n){return this._client.get(We`/files/${t}/content`,{...n,headers:nt([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}async waitForProcessing(t,{pollInterval:n=5e3,maxWait:s=30*60*1e3}={}){const r=new Set(["processed","error","deleted"]),a=Date.now();let i=await this.retrieve(t);for(;!i.status||!r.has(i.status);)if(await nl(n),i=await this.retrieve(t),Date.now()-a>s)throw new ih({message:`Giving up on waiting for file ${t} to finish processing after ${s} milliseconds.`});return i}};class yS extends dt{}let bS=class extends dt{run(t,n){return this._client.post("/fine_tuning/alpha/graders/run",{body:t,...n})}validate(t,n){return this._client.post("/fine_tuning/alpha/graders/validate",{body:t,...n})}};class vh extends dt{constructor(){super(...arguments),this.graders=new bS(this._client)}}vh.Graders=bS;class xS extends dt{create(t,n,s){return this._client.getAPIList(We`/fine_tuning/checkpoints/${t}/permissions`,Zc,{body:n,method:"post",...s})}retrieve(t,n={},s){return this._client.get(We`/fine_tuning/checkpoints/${t}/permissions`,{query:n,...s})}delete(t,n,s){const{fine_tuned_model_checkpoint:r}=n;return this._client.delete(We`/fine_tuning/checkpoints/${r}/permissions/${t}`,s)}}let Sh=class extends dt{constructor(){super(...arguments),this.permissions=new xS(this._client)}};Sh.Permissions=xS;class vS extends dt{list(t,n={},s){return this._client.getAPIList(We`/fine_tuning/jobs/${t}/checkpoints`,ln,{query:n,...s})}}class wh extends dt{constructor(){super(...arguments),this.checkpoints=new vS(this._client)}create(t,n){return this._client.post("/fine_tuning/jobs",{body:t,...n})}retrieve(t,n){return this._client.get(We`/fine_tuning/jobs/${t}`,n)}list(t={},n){return this._client.getAPIList("/fine_tuning/jobs",ln,{query:t,...n})}cancel(t,n){return this._client.post(We`/fine_tuning/jobs/${t}/cancel`,n)}listEvents(t,n={},s){return this._client.getAPIList(We`/fine_tuning/jobs/${t}/events`,ln,{query:n,...s})}pause(t,n){return this._client.post(We`/fine_tuning/jobs/${t}/pause`,n)}resume(t,n){return this._client.post(We`/fine_tuning/jobs/${t}/resume`,n)}}wh.Checkpoints=vS;class Jo extends dt{constructor(){super(...arguments),this.methods=new yS(this._client),this.jobs=new wh(this._client),this.checkpoints=new Sh(this._client),this.alpha=new vh(this._client)}}Jo.Methods=yS;Jo.Jobs=wh;Jo.Checkpoints=Sh;Jo.Alpha=vh;class SS extends dt{}class _h extends dt{constructor(){super(...arguments),this.graderModels=new SS(this._client)}}_h.GraderModels=SS;class wS extends dt{createVariation(t,n){return this._client.post("/images/variations",po({body:t,...n},this._client))}edit(t,n){return this._client.post("/images/edits",po({body:t,...n,stream:t.stream??!1},this._client))}generate(t,n){return this._client.post("/images/generations",{body:t,...n,stream:t.stream??!1})}}class _S extends dt{retrieve(t,n){return this._client.get(We`/models/${t}`,n)}list(t){return this._client.getAPIList("/models",Zc,t)}delete(t,n){return this._client.delete(We`/models/${t}`,n)}}class kS extends dt{create(t,n){return this._client.post("/moderations",{body:t,...n})}}function vO(e,t){return!t||!wO(t)?{...e,output_parsed:null,output:e.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(s=>({...s,parsed:null}))}:n)}:TS(e,t)}function TS(e,t){const n=e.output.map(r=>{if(r.type==="function_call")return{...r,parsed_arguments:TO(t,r)};if(r.type==="message"){const a=r.content.map(i=>i.type==="output_text"?{...i,parsed:SO(t,i.text)}:i);return{...r,content:a}}return r}),s=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,"output_text")||pm(s),Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(const r of s.output)if(r.type==="message"){for(const a of r.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),s}function SO(e,t){var n,s,r,a;return((s=(n=e.text)==null?void 0:n.format)==null?void 0:s.type)!=="json_schema"?null:"$parseRaw"in((r=e.text)==null?void 0:r.format)?((a=e.text)==null?void 0:a.format).$parseRaw(t):JSON.parse(t)}function wO(e){var t;return!!dh((t=e.text)==null?void 0:t.format)}function _O(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function kO(e,t){return e.find(n=>n.type==="function"&&n.name===t)}function TO(e,t){const n=kO(e.tools??[],t.name);return{...t,...t,parsed_arguments:_O(n)?n.$parseRaw(t.arguments):n!=null&&n.strict?JSON.parse(t.arguments):null}}function pm(e){const t=[];for(const n of e.output)if(n.type==="message")for(const s of n.content)s.type==="output_text"&&t.push(s.text);e.output_text=t.join("")}var Eo,ql,xr,Ul,Wg,qg,Ug,Hg;class kh extends ch{constructor(t){super(),Eo.add(this),ql.set(this,void 0),xr.set(this,void 0),Ul.set(this,void 0),at(this,ql,t)}static createResponse(t,n,s){const r=new kh(n);return r._run(()=>r._createOrRetrieveResponse(t,n,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createOrRetrieveResponse(t,n,s){var l;const r=s==null?void 0:s.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),le(this,Eo,"m",Wg).call(this);let a,i=null;"response_id"in n?(a=await t.responses.retrieve(n.response_id,{stream:!0},{...s,signal:this.controller.signal,stream:!0}),i=n.starting_after??null):a=await t.responses.create({...n,stream:!0},{...s,signal:this.controller.signal}),this._connected();for await(const c of a)le(this,Eo,"m",qg).call(this,c,i);if((l=a.controller.signal)!=null&&l.aborted)throw new ys;return le(this,Eo,"m",Ug).call(this)}[(ql=new WeakMap,xr=new WeakMap,Ul=new WeakMap,Eo=new WeakSet,Wg=function(){this.ended||at(this,xr,void 0)},qg=function(n,s){if(this.ended)return;const r=(i,l)=>{(s==null||l.sequence_number>s)&&this._emit(i,l)},a=le(this,Eo,"m",Hg).call(this,n);switch(r("event",n),n.type){case"response.output_text.delta":{const i=a.output[n.output_index];if(!i)throw new it(`missing output at index ${n.output_index}`);if(i.type==="message"){const l=i.content[n.content_index];if(!l)throw new it(`missing content at index ${n.content_index}`);if(l.type!=="output_text")throw new it(`expected content to be 'output_text', got ${l.type}`);r("response.output_text.delta",{...n,snapshot:l.text})}break}case"response.function_call_arguments.delta":{const i=a.output[n.output_index];if(!i)throw new it(`missing output at index ${n.output_index}`);i.type==="function_call"&&r("response.function_call_arguments.delta",{...n,snapshot:i.arguments});break}default:r(n.type,n);break}},Ug=function(){if(this.ended)throw new it("stream has ended, this shouldn't happen");const n=le(this,xr,"f");if(!n)throw new it("request ended without sending any events");at(this,xr,void 0);const s=jO(n,le(this,ql,"f"));return at(this,Ul,s),s},Hg=function(n){let s=le(this,xr,"f");if(!s){if(n.type!=="response.created")throw new it(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return s=at(this,xr,n.response),s}switch(n.type){case"response.output_item.added":{s.output.push(n.item);break}case"response.content_part.added":{const r=s.output[n.output_index];if(!r)throw new it(`missing output at index ${n.output_index}`);r.type==="message"&&r.content.push(n.part);break}case"response.output_text.delta":{const r=s.output[n.output_index];if(!r)throw new it(`missing output at index ${n.output_index}`);if(r.type==="message"){const a=r.content[n.content_index];if(!a)throw new it(`missing content at index ${n.content_index}`);if(a.type!=="output_text")throw new it(`expected content to be 'output_text', got ${a.type}`);a.text+=n.delta}break}case"response.function_call_arguments.delta":{const r=s.output[n.output_index];if(!r)throw new it(`missing output at index ${n.output_index}`);r.type==="function_call"&&(r.arguments+=n.delta);break}case"response.completed":{at(this,xr,n.response);break}}return s},Symbol.asyncIterator)](){const t=[],n=[];let s=!1;return this.on("event",r=>{const a=n.shift();a?a.resolve(r):t.push(r)}),this.on("end",()=>{s=!0;for(const r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),this.on("error",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((a,i)=>n.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const t=le(this,Ul,"f");if(!t)throw new it("stream ended without producing a ChatCompletion");return t}}function jO(e,t){return vO(e,t)}class jS extends dt{list(t,n={},s){return this._client.getAPIList(We`/responses/${t}/input_items`,ln,{query:n,...s})}}class Th extends dt{constructor(){super(...arguments),this.inputItems=new jS(this._client)}create(t,n){return this._client.post("/responses",{body:t,...n,stream:t.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&pm(s),s))}retrieve(t,n={},s){return this._client.get(We`/responses/${t}`,{query:n,...s,stream:(n==null?void 0:n.stream)??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&pm(r),r))}delete(t,n){return this._client.delete(We`/responses/${t}`,{...n,headers:nt([{Accept:"*/*"},n==null?void 0:n.headers])})}parse(t,n){return this._client.responses.create(t,n)._thenUnwrap(s=>TS(s,t))}stream(t,n){return kh.createResponse(this._client,t,n)}cancel(t,n){return this._client.post(We`/responses/${t}/cancel`,n)}}Th.InputItems=jS;class CS extends dt{create(t,n,s){return this._client.post(We`/uploads/${t}/parts`,po({body:n,...s},this._client))}}class jh extends dt{constructor(){super(...arguments),this.parts=new CS(this._client)}create(t,n){return this._client.post("/uploads",{body:t,...n})}cancel(t,n){return this._client.post(We`/uploads/${t}/cancel`,n)}complete(t,n,s){return this._client.post(We`/uploads/${t}/complete`,{body:n,...s})}}jh.Parts=CS;const CO=async e=>{const t=await Promise.allSettled(e),n=t.filter(r=>r.status==="rejected");if(n.length){for(const r of n)console.error(r.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const s=[];for(const r of t)r.status==="fulfilled"&&s.push(r.value);return s};class MS extends dt{create(t,n,s){return this._client.post(We`/vector_stores/${t}/file_batches`,{body:n,...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,n,s){const{vector_store_id:r}=n;return this._client.get(We`/vector_stores/${r}/file_batches/${t}`,{...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}cancel(t,n,s){const{vector_store_id:r}=n;return this._client.post(We`/vector_stores/${r}/file_batches/${t}/cancel`,{...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}async createAndPoll(t,n,s){const r=await this.create(t,n);return await this.poll(t,r.id,s)}listFiles(t,n,s){const{vector_store_id:r,...a}=n;return this._client.getAPIList(We`/vector_stores/${r}/file_batches/${t}/files`,ln,{query:a,...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}async poll(t,n,s){var a;const r=nt([s==null?void 0:s.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=s==null?void 0:s.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const{data:i,response:l}=await this.retrieve(n,{vector_store_id:t},{...s,headers:r}).withResponse();switch(i.status){case"in_progress":let c=5e3;if(s!=null&&s.pollIntervalMs)c=s.pollIntervalMs;else{const u=l.headers.get("openai-poll-after-ms");if(u){const m=parseInt(u);isNaN(m)||(c=m)}}await nl(c);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(t,{files:n,fileIds:s=[]},r){if(n==null||n.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const a=(r==null?void 0:r.maxConcurrency)??5,i=Math.min(a,n.length),l=this._client,c=n.values(),u=[...s];async function m(g){for(let b of g){const S=await l.files.create({file:b,purpose:"assistants"},r);u.push(S.id)}}const f=Array(i).fill(c).map(m);return await CO(f),await this.createAndPoll(t,{file_ids:u})}}class PS extends dt{create(t,n,s){return this._client.post(We`/vector_stores/${t}/files`,{body:n,...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,n,s){const{vector_store_id:r}=n;return this._client.get(We`/vector_stores/${r}/files/${t}`,{...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,n,s){const{vector_store_id:r,...a}=n;return this._client.post(We`/vector_stores/${r}/files/${t}`,{body:a,...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}list(t,n={},s){return this._client.getAPIList(We`/vector_stores/${t}/files`,ln,{query:n,...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}delete(t,n,s){const{vector_store_id:r}=n;return this._client.delete(We`/vector_stores/${r}/files/${t}`,{...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}async createAndPoll(t,n,s){const r=await this.create(t,n,s);return await this.poll(t,r.id,s)}async poll(t,n,s){var a;const r=nt([s==null?void 0:s.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=s==null?void 0:s.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const i=await this.retrieve(n,{vector_store_id:t},{...s,headers:r}).withResponse(),l=i.data;switch(l.status){case"in_progress":let c=5e3;if(s!=null&&s.pollIntervalMs)c=s.pollIntervalMs;else{const u=i.response.headers.get("openai-poll-after-ms");if(u){const m=parseInt(u);isNaN(m)||(c=m)}}await nl(c);break;case"failed":case"completed":return l}}}async upload(t,n,s){const r=await this._client.files.create({file:n,purpose:"assistants"},s);return this.create(t,{file_id:r.id},s)}async uploadAndPoll(t,n,s){const r=await this.upload(t,n,s);return await this.poll(t,r.id,s)}content(t,n,s){const{vector_store_id:r}=n;return this._client.getAPIList(We`/vector_stores/${r}/files/${t}/content`,Zc,{...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class nd extends dt{constructor(){super(...arguments),this.files=new PS(this._client),this.fileBatches=new MS(this._client)}create(t,n){return this._client.post("/vector_stores",{body:t,...n,headers:nt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(We`/vector_stores/${t}`,{...n,headers:nt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,n,s){return this._client.post(We`/vector_stores/${t}`,{body:n,...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}list(t={},n){return this._client.getAPIList("/vector_stores",ln,{query:t,...n,headers:nt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,n){return this._client.delete(We`/vector_stores/${t}`,{...n,headers:nt([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}search(t,n,s){return this._client.getAPIList(We`/vector_stores/${t}/search`,Zc,{body:n,method:"post",...s,headers:nt([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}nd.Files=PS;nd.FileBatches=MS;var Oo,ES,dc;class RS extends dt{constructor(){super(...arguments),Oo.add(this)}async unwrap(t,n,s=this._client.webhookSecret,r=300){return await this.verifySignature(t,n,s,r),JSON.parse(t)}async verifySignature(t,n,s=this._client.webhookSecret,r=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");le(this,Oo,"m",ES).call(this,s);const a=nt([n]).values,i=le(this,Oo,"m",dc).call(this,a,"webhook-signature"),l=le(this,Oo,"m",dc).call(this,a,"webhook-timestamp"),c=le(this,Oo,"m",dc).call(this,a,"webhook-id"),u=parseInt(l,10);if(isNaN(u))throw new bi("Invalid webhook timestamp format");const m=Math.floor(Date.now()/1e3);if(m-u>r)throw new bi("Webhook timestamp is too old");if(u>m+r)throw new bi("Webhook timestamp is too new");const f=i.split(" ").map(x=>x.startsWith("v1,")?x.substring(3):x),g=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),b=c?`${c}.${l}.${t}`:`${l}.${t}`,S=await crypto.subtle.importKey("raw",g,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const x of f)try{const T=Buffer.from(x,"base64");if(await crypto.subtle.verify("HMAC",S,T,new TextEncoder().encode(b)))return}catch{continue}throw new bi("The given webhook signature does not match the expected signature")}}Oo=new WeakSet,ES=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")},dc=function(t,n){if(!t)throw new Error("Headers are required");const s=t.get(n);if(s==null)throw new Error(`Missing required header: ${n}`);return s};var fm,Ch,uc,AS;class xt{constructor({baseURL:t=Po("OPENAI_BASE_URL"),apiKey:n=Po("OPENAI_API_KEY"),organization:s=Po("OPENAI_ORG_ID")??null,project:r=Po("OPENAI_PROJECT_ID")??null,webhookSecret:a=Po("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(fm.add(this),uc.set(this,void 0),this.completions=new mS(this),this.chat=new ph(this),this.embeddings=new pS(this),this.files=new gS(this),this.images=new wS(this),this.audio=new rl(this),this.moderations=new kS(this),this.models=new _S(this),this.fineTuning=new Jo(this),this.graders=new _h(this),this.vectorStores=new nd(this),this.webhooks=new RS(this),this.beta=new ol(this),this.batches=new aS(this),this.uploads=new jh(this),this.responses=new Th(this),this.evals=new xh(this),this.containers=new yh(this),n===void 0)throw new it("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const l={apiKey:n,organization:s,project:r,webhookSecret:a,...i,baseURL:t||"https://api.openai.com/v1"};if(!l.dangerouslyAllowBrowser&&MI())throw new it(`It looks like you're running in a browser-like environment.
|
|
223
|
+
|
|
224
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
225
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
226
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
227
|
+
|
|
228
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
229
|
+
|
|
230
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
231
|
+
`);this.baseURL=l.baseURL,this.timeout=l.timeout??Ch.DEFAULT_TIMEOUT,this.logger=l.logger??console;const c="warn";this.logLevel=c,this.logLevel=Pg(l.logLevel,"ClientOptions.logLevel",this)??Pg(Po("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??II(),at(this,uc,$I),this._options=l,this.apiKey=n,this.organization=s,this.project=r,this.webhookSecret=a}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...t})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:n}){}async authHeaders(t){return nt([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return BI(t,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Ao}`}defaultIdempotencyKey(){return`stainless-node-retry-${dv()}`}makeStatusError(t,n,s,r){return Pn.generate(t,n,s,r)}buildURL(t,n,s){const r=!le(this,fm,"m",AS).call(this)&&s||this.baseURL,a=wI(t)?new URL(t):new URL(r+(r.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),i=this.defaultQuery();return kI(i)||(n={...i,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(a.search=this.stringifyQuery(n)),a.toString()}async prepareOptions(t){}async prepareRequest(t,{url:n,options:s}){}get(t,n){return this.methodRequest("get",t,n)}post(t,n){return this.methodRequest("post",t,n)}patch(t,n){return this.methodRequest("patch",t,n)}put(t,n){return this.methodRequest("put",t,n)}delete(t,n){return this.methodRequest("delete",t,n)}methodRequest(t,n,s){return this.request(Promise.resolve(s).then(r=>({method:t,path:n,...r})))}request(t,n=null){return new Qc(this,this.makeRequest(t,n,void 0))}async makeRequest(t,n,s){var j,w;const r=await t,a=r.maxRetries??this.maxRetries;n==null&&(n=a),await this.prepareOptions(r);const{req:i,url:l,timeout:c}=await this.buildRequest(r,{retryCount:a-n});await this.prepareRequest(i,{url:l,options:r});const u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=s===void 0?"":`, retryOf: ${s}`,f=Date.now();if(jn(this).debug(`[${u}] sending request`,Kr({retryOfRequestLogID:s,method:r.method,url:l,options:r,headers:i.headers})),(j=r.signal)!=null&&j.aborted)throw new ys;const g=new AbortController,b=await this.fetchWithTimeout(l,i,c,g).catch(rm),S=Date.now();if(b instanceof Error){const M=`retrying, ${n} attempts remaining`;if((w=r.signal)!=null&&w.aborted)throw new ys;const _=sm(b)||/timed? ?out/i.test(String(b)+("cause"in b?String(b.cause):""));if(n)return jn(this).info(`[${u}] connection ${_?"timed out":"failed"} - ${M}`),jn(this).debug(`[${u}] connection ${_?"timed out":"failed"} (${M})`,Kr({retryOfRequestLogID:s,url:l,durationMs:S-f,message:b.message})),this.retryRequest(r,n,s??u);throw jn(this).info(`[${u}] connection ${_?"timed out":"failed"} - error; no more retries left`),jn(this).debug(`[${u}] connection ${_?"timed out":"failed"} (error; no more retries left)`,Kr({retryOfRequestLogID:s,url:l,durationMs:S-f,message:b.message})),_?new ih:new Gc({cause:b})}const x=[...b.headers.entries()].filter(([M])=>M==="x-request-id").map(([M,_])=>", "+M+": "+JSON.stringify(_)).join(""),T=`[${u}${m}${x}] ${i.method} ${l} ${b.ok?"succeeded":"failed"} with status ${b.status} in ${S-f}ms`;if(!b.ok){const M=await this.shouldRetry(b);if(n&&M){const N=`retrying, ${n} attempts remaining`;return await OI(b.body),jn(this).info(`${T} - ${N}`),jn(this).debug(`[${u}] response error (${N})`,Kr({retryOfRequestLogID:s,url:b.url,status:b.status,headers:b.headers,durationMs:S-f})),this.retryRequest(r,n,s??u,b.headers)}const _=M?"error; no more retries left":"error; not retryable";jn(this).info(`${T} - ${_}`);const C=await b.text().catch(N=>rm(N).message),L=CI(C),A=L?void 0:C;throw jn(this).debug(`[${u}] response error (${_})`,Kr({retryOfRequestLogID:s,url:b.url,status:b.status,headers:b.headers,message:A,durationMs:Date.now()-f})),this.makeStatusError(b.status,L,A,b.headers)}return jn(this).info(T),jn(this).debug(`[${u}] response start`,Kr({retryOfRequestLogID:s,url:b.url,status:b.status,headers:b.headers,durationMs:S-f})),{response:b,options:r,controller:g,requestLogID:u,retryOfRequestLogID:s,startTime:f}}getAPIList(t,n,s){return this.requestAPIList(n,{method:"get",path:t,...s})}requestAPIList(t,n){const s=this.makeRequest(n,null,void 0);return new GI(this,s,t)}async fetchWithTimeout(t,n,s,r){const{signal:a,method:i,...l}=n||{};a&&a.addEventListener("abort",()=>r.abort());const c=setTimeout(()=>r.abort(),s),u=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,m={signal:r.signal,...u?{duplex:"half"}:{},method:"GET",...l};i&&(m.method=i.toUpperCase());try{return await this.fetch.call(void 0,t,m)}finally{clearTimeout(c)}}async shouldRetry(t){const n=t.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,n,s,r){let a;const i=r==null?void 0:r.get("retry-after-ms");if(i){const c=parseFloat(i);Number.isNaN(c)||(a=c)}const l=r==null?void 0:r.get("retry-after");if(l&&!a){const c=parseFloat(l);Number.isNaN(c)?a=Date.parse(l)-Date.now():a=c*1e3}if(!(a&&0<=a&&a<60*1e3)){const c=t.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(n,c)}return await nl(a),this.makeRequest(t,n-1,s)}calculateDefaultRetryTimeoutMillis(t,n){const a=n-t,i=Math.min(.5*Math.pow(2,a),8),l=1-Math.random()*.25;return i*l*1e3}async buildRequest(t,{retryCount:n=0}={}){const s={...t},{method:r,path:a,query:i,defaultBaseURL:l}=s,c=this.buildURL(a,i,l);"timeout"in s&&jI("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:u,body:m}=this.buildBody({options:s}),f=await this.buildHeaders({options:t,method:r,bodyHeaders:u,retryCount:n});return{req:{method:r,headers:f,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"},...m&&{body:m},...this.fetchOptions??{},...s.fetchOptions??{}},url:c,timeout:s.timeout}}async buildHeaders({options:t,method:n,bodyHeaders:s,retryCount:r}){let a={};this.idempotencyHeader&&n!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=t.idempotencyKey);const i=nt([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...AI(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(t),this._options.defaultHeaders,s,t.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:t,headers:n}}){if(!t)return{bodyHeaders:void 0,body:void 0};const s=nt([n]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&s.values.has("content-type")||t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:wv(t)}:le(this,uc,"f").call(this,{body:t,headers:s})}}Ch=xt,uc=new WeakMap,fm=new WeakSet,AS=function(){return this.baseURL!=="https://api.openai.com/v1"};xt.OpenAI=Ch;xt.DEFAULT_TIMEOUT=6e5;xt.OpenAIError=it;xt.APIError=Pn;xt.APIConnectionError=Gc;xt.APIConnectionTimeoutError=ih;xt.APIUserAbortError=ys;xt.NotFoundError=pv;xt.ConflictError=fv;xt.RateLimitError=yv;xt.BadRequestError=uv;xt.AuthenticationError=mv;xt.InternalServerError=bv;xt.PermissionDeniedError=hv;xt.UnprocessableEntityError=gv;xt.InvalidWebhookSignatureError=bi;xt.toFile=nO;xt.Completions=mS;xt.Chat=ph;xt.Embeddings=pS;xt.Files=gS;xt.Images=wS;xt.Audio=rl;xt.Moderations=kS;xt.Models=_S;xt.FineTuning=Jo;xt.Graders=_h;xt.VectorStores=nd;xt.Webhooks=RS;xt.Beta=ol;xt.Batches=aS;xt.Uploads=jh;xt.Responses=Th;xt.Evals=xh;xt.Containers=yh;let Hl=null,cu=null;const MO=()=>{const e=Yo().trim().replace(/\/+$/,"");if(e.endsWith("/openai/v1"))return e;const t="/v1";return`${e.endsWith(t)?e.slice(0,-t.length):e}/openai/v1`},PO=()=>{const e=MO();return Hl?cu!==e&&(Hl=new xt({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),cu=e):(Hl=new xt({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),cu=e),Hl},IS=e=>{const t=e.match(/```mermaid\s*([\s\S]*?)```/i);return t?t[1].trim():e.trim()},EO=(e,t,n)=>{const s=t.trim(),r=IS(n),a=/```mermaid\s*([\s\S]*?)```/gi;let i=!1;const l=e.replace(a,(u,m)=>i||m.trim()!==s?u:(i=!0,`\`\`\`mermaid
|
|
232
|
+
${r}
|
|
233
|
+
\`\`\``));return i?l:e.match(a)?e.replace(a,u=>i?u:(i=!0,`\`\`\`mermaid
|
|
234
|
+
${r}
|
|
235
|
+
\`\`\``)):null},Kg="_text",Dc=e=>!!(e&&e.role==="assistant"&&"type"in e&&e.type==="text"),Vg=(e,t,n)=>{var r;const s=typeof((r=t.metadata)==null?void 0:r.backendMessageId)=="string"?t.metadata.backendMessageId.trim():"";if(s)return s;if(e.endsWith(Kg)){const a=e.slice(0,-Kg.length);if(a&&n.some(i=>i.id===a))return a}return e},RO=(e,t)=>{const n=t.trim();if(!n)return!1;const s=e.matchAll(/```mermaid\s*([\s\S]*?)```/gi);for(const r of s)if((r[1]||"").trim()===n)return!0;return!1},AO=e=>(e instanceof Error?e.message:String(e)).toLowerCase().includes("message not found"),IO=(e,t,n,s)=>{const r=e.find(a=>a.id===t);return Dc(r)?r:e.find(a=>Dc(a)&&(a.content===n||RO(a.content,s)))},OO=(e,t)=>{const n=(t??"").trim(),s=["Original Mermaid code:","```mermaid",e.trim(),"```"];return n&&s.push("","Mermaid parser/render error:",n),s.push("","Please fix the Mermaid syntax while preserving the original meaning and labels."),s.join(`
|
|
236
|
+
`)},$O=async(e,t,n)=>{var l,c,u;const s=t==null?void 0:t.trim();if(!s)throw new Error("No model configured. Please select a default model in Provider Settings.");const i=((u=(c=(l=(await PO().chat.completions.create({model:s,messages:[{role:"system",content:"You fix Mermaid diagrams using the parser/render error context. Return only corrected Mermaid code without markdown fences or extra text."},{role:"user",content:OO(e,n)}],temperature:0})).choices)==null?void 0:l[0])==null?void 0:c.message)==null?void 0:u.content)??"";return IS(i)},DO=(e,t)=>{const n=fT(),s=gT(),r=(s==null?void 0:s.model)??n;return p.useCallback(async(a,i)=>{const l=te.getState(),c=t??l.currentSessionId,u=l.chats.find(w=>w.id===c);if(!c||!u)throw new Error("No active chat available");const m=u.messages.find(w=>w.id===e);if(!Dc(m))throw new Error("Mermaid fix is only available for assistant text messages");const f=await $O(a,r,i);if(!f)throw new Error("AI did not return a Mermaid fix");const g=EO(m.content,a,f);if(!g)throw new Error("Unable to locate Mermaid block to update");let b=Vg(e,m,u.messages);try{await Fo.patchSessionMessage(c,b,{content:g})}catch(w){if(!AO(w))throw w;await l.loadChatHistory(c,{mode:"replace",retries:2,retryDelayMs:150,waitForAssistant:!0});const _=te.getState().chats.find(L=>L.id===c);if(!_)throw w;const C=IO(_.messages,e,m.content,a);if(!C)throw w;b=Vg(C.id,C,_.messages),await Fo.patchSessionMessage(c,b,{content:g})}const S=te.getState(),x=S.chats.find(w=>w.id===c);if(!x)throw new Error("No active chat available");const T=new Set([e,b]),j=x.messages.map(w=>!T.has(w.id)||!Dc(w)?w:{...w,content:g});S.updateSession(c,{messages:j})},[e,t,r])},LO=e=>e.xs?"100%":e.sm?"95%":"800px",FO=[{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:"}],NO=({messageId:e,isVisible:t,onRetryWithVariation:n})=>{const{t:s}=Ie(),[r,a]=p.useState(null),[i,l]=p.useState(!1),c=p.useCallback(()=>{a(b=>b==="like"?null:"like"),l(!1)},[]),u=p.useCallback(()=>{a(b=>{const S=b==="dislike"?null:"dislike";return l(S==="dislike"),S})},[]),m=p.useCallback(b=>{n&&n(b.prefix)},[n]),g=["lotus-msg-feedback",t?"is-visible":"",r!==null?"has-rating":""].filter(Boolean).join(" ");return o.jsxs("div",{className:g,"data-message-id":e,children:[o.jsx(bt,{title:s("feedback.helpful","Helpful"),children:o.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${r==="like"?"is-liked":""}`,onClick:c,"aria-label":s("feedback.helpful","Helpful"),children:r==="like"?o.jsx(l_,{}):o.jsx(c_,{})})}),o.jsx(bt,{title:s("feedback.notHelpful","Not helpful"),children:o.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${r==="dislike"?"is-disliked":""}`,onClick:u,"aria-label":s("feedback.notHelpful","Not helpful"),children:r==="dislike"?o.jsx(d_,{}):o.jsx(u_,{})})}),i&&n&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"lotus-msg-feedback-sep"}),o.jsx("span",{className:"lotus-msg-feedback-retry",children:FO.map(b=>o.jsx(Ne,{color:b.color,bordered:!1,className:"lotus-msg-feedback-retry-tag",onClick:()=>m(b),children:s(b.labelKey,b.fallbackLabel)},b.key))})]})]})},{useToken:zO}=Ge,{useBreakpoint:BO}=Nc,WO="chat-send-message",qO=({sessionId:e,message:t,onDelete:n,messageType:s})=>{const{role:r,id:a}=t,{token:i}=zO(),l=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:c}=Ie(),{message:u}=sn.useApp(),m=BO(),f=te(Se=>Se.updateSession),g=te(Se=>Se.loadChatHistory),b=te(Se=>Se.refreshChats),S=p.useRef(null),[x,T]=p.useState(!1),j=te(dr(e)),w=p.useCallback(Se=>typeof window>"u"?Promise.reject(new Error("window is unavailable")):new Promise((ke,Be)=>{const tt={content:Se,sessionId:e,handled:!1,resolve:ke,reject:Be};window.dispatchEvent(new CustomEvent(WO,{detail:tt})),tt.handled||Be(new Error("No chat message dispatcher available"))}),[e]),M=p.useMemo(()=>{if(!t.createdAt)return null;const Se=new Date(t.createdAt);if(Number.isNaN(Se.getTime()))return null;try{return X1(Se,"MMM d, yyyy HH:mm")}catch{return Se.toLocaleString()}},[t.createdAt]),_=p.useMemo(()=>hI(t,s),[t,s]),C=p.useMemo(()=>pI(t,_),[t,_]),L=p.useMemo(()=>fI(t,_),[t,_]),A=p.useMemo(()=>lv(t),[t]),B=DO(a,e),N=p.useCallback(async Se=>{var ke;if(!e||!a){u.warning(c("chat.messageActions.cannotRestore"));return}try{const Be=await Fo.restoreSessionState(e,{target_message_id:a,restore_files:Se});await g(e,{mode:"replace"}),await b();const tt=((ke=Be.file_errors)==null?void 0:ke.length)??0;if(tt>0){u.warning(c("chat.messageActions.restorePartial",{count:tt}));return}Se?u.success(c("chat.messageActions.restoreFilesSuccess",{count:Be.messages_removed})):u.success(c("chat.messageActions.restoreSuccess",{count:Be.messages_removed}))}catch(Be){const tt=Be instanceof Error?Be.message:c("chat.messageActions.restoreFailed");u.error(tt)}},[u,e,g,a,b,c]),O=p.useCallback(()=>{N(!1)},[N]),R=p.useCallback(()=>{N(!0)},[N]),{contextMenuItems:I,handleMouseUp:$,copyToClipboard:U,referenceMessage:q}=xI({messageText:A,messageId:a,currentSessionId:e,onDelete:n,onRestoreChat:O,onRestoreFilesAndChat:R,cardRef:S}),K=p.useMemo(()=>r==="user"&&A.startsWith("/"),[r,A]),P=p.useMemo(()=>rv(i,{onFixMermaid:B}),[i,B]),W=p.useMemo(()=>[Lc,Tm],[]),se=p.useMemo(()=>[km],[]),V=p.useMemo(()=>[nR(()=>U(A),c("chat.actions.copyMessage")),sR(q,c("chat.actions.referenceMessage"))],[A,U,q,c]),{handleExecutePlan:ie,handleRefinePlan:re,handleQuestionAnswer:fe}=vI({currentSessionId:e,updateSession:f,sendMessage:w});return _==="plan"&&C&&r==="assistant"?o.jsx(Dx,{plan:C,contextId:e||"",onExecute:ie,onRefine:re,timestamp:M??void 0}):_==="question"&&L&&r==="assistant"?o.jsx(Lx,{question:L,contextId:e||"",onAnswer:fe,disabled:j||!1,timestamp:M??void 0}):OM(t)?o.jsx(uR,{taskList:t.taskList}):IM(t)?(Jt("[MessageCard]","[MessageCard] Rendering FileReferenceCard for message:",t.id,"paths:",t.paths),o.jsx(be,{justify:"flex-end",style:{width:"100%"},children:o.jsx(Fx,{paths:t.paths,displayText:t.displayText,timestamp:M??void 0})})):o.jsxs(be,{vertical:!0,onContextMenu:Se=>$(Se),style:{width:"100%"},children:[o.jsx(lo,{menu:{items:I},trigger:["contextMenu"],children:o.jsx(Ce,{"data-testid":r==="assistant"?"assistant-message":"user-message",id:a?`message-${a}`:void 0,ref:S,style:{width:"100%",minWidth:"100%",maxWidth:LO(m),margin:"0 auto",background:r==="user"?"var(--lotus-message-user-bg)":r==="assistant"?"var(--lotus-message-assistant-bg)":i.colorBgContainer,backdropFilter:l?"none":"blur(14px)",WebkitBackdropFilter:l?"none":"blur(14px)",border:r==="user"?"1px solid var(--lotus-message-user-border)":"1px solid var(--lotus-glass-border-subtle)",borderRadius:i.borderRadiusLG,boxShadow:x?"var(--lotus-card-hover-shadow)":"var(--lotus-shadow-soft)",position:"relative",wordWrap:"break-word",overflowWrap:"break-word",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",transform:x?"translateY(-2px) scale(1.002)":"none",overflow:"hidden"},styles:{body:{padding:i.paddingMD}},onMouseEnter:()=>T(!0),onMouseLeave:()=>T(!1),children:o.jsxs(he,{direction:"vertical",size:i.marginXS,style:{width:"100%",maxWidth:"100%"},children:[o.jsx(uI,{role:r,formattedTimestamp:M,token:i}),t.role==="user"&&t.images&&o.jsx(Q1,{images:t.images}),o.jsx(be,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:o.jsx(dI,{sessionId:e,message:t,messageText:A,isUserToolCall:K,formatUserToolCall:gI,markdownComponents:P,markdownPlugins:W,rehypePlugins:se})}),o.jsx(tR,{isVisible:x,position:{bottom:i.paddingXS,right:i.paddingXS},buttons:V})]})})}),r==="assistant"&&_==="text"&&a&&o.jsx(NO,{messageId:a,isVisible:x})]})},OS=p.memo(qO,(e,t)=>e.message===t.message&&e.messageType===t.messageType&&e.onDelete===t.onDelete);OS.displayName="MessageCard";const{Text:Oi}=He,{useToken:UO}=Ge,HO=e=>({p:({children:t})=>o.jsx(Oi,{style:{marginBottom:e.marginSM,display:"block"},children:t}),ol:({children:t})=>o.jsx("ol",{style:{marginBottom:e.marginSM,paddingLeft:20},children:t}),ul:({children:t})=>o.jsx("ul",{style:{marginBottom:e.marginSM,paddingLeft:20},children:t}),li:({children:t})=>o.jsx("li",{style:{marginBottom:e.marginXS},children:t}),code({className:t,children:n,inline:s,...r}){const a=/language-([^\s]+)/i.exec(t||""),i=a?a[1]:"",l=s??(!a&&!t),c=n?String(n).replace(/\n$/,""):"";return l?o.jsx(Oi,{code:!0,className:t,...r,children:n}):c.trim()?i.toLowerCase()==="mermaid"?o.jsx(Ce,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto",marginBottom:e.marginSM},children:o.jsx("pre",{style:{margin:0,padding:e.paddingSM,background:e.colorBgContainer,borderRadius:e.borderRadiusSM,fontSize:"13px"},children:o.jsx("code",{children:c})})}):nv(i,c,e,void 0):null},blockquote:({children:t})=>o.jsx(Ce,{size:"small",styles:{body:{padding:`${e.paddingXS}px ${e.padding}px`}},style:{borderLeft:`3px solid ${e.colorPrimary}`,background:e.colorPrimaryBg,margin:`${e.marginXS}px 0`,color:e.colorTextSecondary,fontStyle:"italic"},children:t}),a:({children:t,href:n})=>{const s=typeof n=="string"?n.trim():"";return s?o.jsx("a",{href:s,target:"_blank",rel:"noopener noreferrer",onClick:r=>{r.preventDefault(),sv(s)},style:{color:e.colorLink,textDecoration:"underline",overflowWrap:"anywhere"},children:t}):o.jsx(o.Fragment,{children:t})},table:({children:t})=>o.jsx(Ce,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${e.marginSM}px 0`},children:o.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${e.colorBorder}`},children:t})}),thead:({children:t})=>o.jsx("thead",{style:{backgroundColor:e.colorBgContainer},children:t}),tbody:({children:t})=>o.jsx("tbody",{children:t}),tr:({children:t})=>o.jsx("tr",{style:{borderBottom:`1px solid ${e.colorBorder}`},children:t}),th:({children:t})=>o.jsx("th",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,textAlign:"left",fontWeight:"bold",borderRight:`1px solid ${e.colorBorder}`},children:t}),td:({children:t})=>o.jsx("td",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,borderRight:`1px solid ${e.colorBorder}`},children:t}),input:({type:t,checked:n,disabled:s})=>t==="checkbox"?o.jsx("input",{type:"checkbox",checked:n,disabled:s,style:{marginRight:e.marginXS,accentColor:e.colorPrimary},readOnly:!0}):o.jsx("input",{type:t,checked:n,disabled:s})}),$S=p.memo(({sessionId:e})=>{const{token:t}=UO(),n=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:s}=Ie(),r=`streaming-${e}`,a=`streaming-reasoning-${e}`,i=`streaming-status-${e}`,[l,c]=p.useState(()=>It.getLatest(r)??""),[u,m]=p.useState(()=>It.getLatest(a)??""),[f,g]=p.useState(()=>It.getLatest(i)??"");p.useEffect(()=>It.subscribeMessage(r,j=>{c(j??"")}),[r]),p.useEffect(()=>It.subscribeMessage(a,j=>{m(j??"")}),[a]),p.useEffect(()=>It.subscribeMessage(i,j=>{g(j??"")}),[i]);const b=p.useMemo(()=>{const j=f.trim().toLowerCase();if(!j)return s("chat.messageCard.assistantThinking");if(j==="context_compacting")return s("chat.messageCard.assistantCompactingContext");if(j==="context_compaction_degraded")return s("chat.messageCard.assistantCompactingContextDegraded");if(j==="context_compaction_failed")return s("chat.messageCard.assistantCompactingContextFailed");if(j==="memory_updating")return s("chat.messageCard.assistantUpdatingMemory");if(j.startsWith("tool_running:")){const M=(j.slice(13).trim()||"tool").replace(/[_-]+/g," ");return s("chat.messageCard.assistantRunningTool",{tool:M})}return s("chat.messageCard.assistantThinking")},[f,s]),S=p.useMemo(()=>[Lc,Tm],[]),x=p.useMemo(()=>[km],[]),T=p.useMemo(()=>HO(t),[t]);return o.jsx(Ce,{"data-testid":"streaming-indicator",role:"status","aria-live":"polite","aria-busy":!0,"aria-label":"AI is responding",style:{width:"100%",minWidth:"100%",maxWidth:"800px",margin:"0 auto",background:"var(--lotus-message-streaming-bg)",backdropFilter:n?"none":"blur(14px)",WebkitBackdropFilter:n?"none":"blur(14px)",borderRadius:t.borderRadiusLG,boxShadow:"none",position:"relative",wordWrap:"break-word",overflowWrap:"break-word"},children:o.jsxs(he,{direction:"vertical",size:t.marginXS,style:{width:"100%",maxWidth:"100%"},children:[o.jsx(be,{align:"baseline",justify:"space-between",gap:t.marginXS,children:o.jsx(Oi,{type:"secondary",strong:!0,style:{fontSize:t.fontSizeSM},children:s("chat.streaming.assistant")})}),o.jsxs(be,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:[u?o.jsx(ir,{size:"small",defaultActiveKey:["reasoning"],style:{marginBottom:t.marginSM,background:t.colorBgContainer,borderColor:t.colorBorderSecondary},items:[{key:"reasoning",label:o.jsx(Oi,{strong:!0,children:s("chat.messageCard.reasoning")}),children:o.jsx(Ps,{remarkPlugins:S,rehypePlugins:x,components:T,children:u})}]}):null,!l||f?o.jsx(Oi,{italic:!0,className:"thinking-shimmer",children:b}):null,l?o.jsx(Ps,{remarkPlugins:S,rehypePlugins:x,components:T,children:l}):null,o.jsx("span",{className:"blinking-cursor",style:{display:"inline-block",marginLeft:"0.2em",color:t.colorText}})]})]})})});$S.displayName="StreamingMessageCard";const{Text:Kl}=He,KO="chat-session-tool-collapse:",DS=(e,t)=>`${KO}${e}:${t}`,Yg=(e,t)=>{if(typeof window>"u")return null;try{const n=window.localStorage.getItem(DS(e,t));if(!n)return null;const s=JSON.parse(n);return!s||typeof s!="object"?null:{isExpanded:"isExpanded"in s&&typeof s.isExpanded=="boolean"?s.isExpanded:!0,expandedTools:[]}}catch{return null}},VO=async(e,t,n)=>{if(typeof window>"u")return;await Wn.getInstance().saveToolSessionCollapse(e,t,n);try{window.localStorage.setItem(DS(e,t),JSON.stringify(n))}catch{}},YO="synthetic-tool-call:",XO=e=>{var n,s,r,a;const t=new Set;return(n=e.callMessageId)!=null&&n.trim()?t.add(e.callMessageId.trim()):e.call.id&&!e.call.id.includes(":")&&!e.call.id.startsWith(YO)&&t.add(e.call.id),(s=e.resultMessageId)!=null&&s.trim()?t.add(e.resultMessageId.trim()):(a=(r=e.result)==null?void 0:r.id)!=null&&a.trim()&&t.add(e.result.id.trim()),Array.from(t)},GO=e=>{const t=new Set;return e.forEach(n=>{XO(n).forEach(s=>t.add(s))}),Array.from(t)},JO=({tools:e,sessionId:t,defaultExpanded:n=!1,autoCollapseWhenStale:s=!1,onDeleteMessageIds:r})=>{const{t:a}=Ie(),{token:i}=Ge.useToken(),l=p.useMemo(()=>{var A,B,N,O;const _=e[0],C=(B=(A=_==null?void 0:_.call)==null?void 0:A.toolCalls)==null?void 0:B[0];return`${(_==null?void 0:_.callMessageId)||((N=_==null?void 0:_.call)==null?void 0:N.id)||(_==null?void 0:_.resultMessageId)||((O=_==null?void 0:_.result)==null?void 0:O.id)||"tool-message-missing"}:${(C==null?void 0:C.toolCallId)||"tool-call-missing"}`},[e]),[c,u]=p.useState(()=>{const _=Yg(t,l);return _?_.isExpanded:n});p.useEffect(()=>{const _=Yg(t,l);u(_?_.isExpanded:n),Wn.getInstance().loadToolSessionCollapse(t,l).then(L=>{L&&u(L.isExpanded)}).catch(()=>{})},[n,t,l]),p.useEffect(()=>{VO(t,l,{isExpanded:c,expandedTools:[]}).catch(()=>{})},[t,l,c]);const m=p.useRef(s);p.useEffect(()=>{!m.current&&s&&u(!1),m.current=s},[s]);const{completedCount:f,pendingCount:g,hasErrors:b}=p.useMemo(()=>{let _=0,C=0,L=!1;return e.forEach(A=>{A.result?(_++,A.result.isError&&(L=!0)):C++}),{completedCount:_,pendingCount:C,hasErrors:L}},[e]),S=p.useMemo(()=>g>0?{color:"processing",text:a("components.toolSession.completedProgress",{completed:f,total:e.length})}:b?{color:"warning",text:a("components.toolSession.completedWithErrors",{completed:f})}:{color:"success",text:a("components.toolSession.completedOnly",{completed:f})},[f,g,b,e.length,a]),x=p.useMemo(()=>{let _=0,C=0,L=0;return e.forEach(A=>{var O,R;const B=(R=(O=A.result)==null?void 0:O.result)==null?void 0:R.result;if(!B)return;const N=gx(B);N&&(_+=N.added,C+=N.removed,L+=1)}),{added:_,removed:C,changedTools:L}},[e]),T=p.useMemo(()=>{const _=e.map(A=>{var O,R;const B=(R=(O=A.call)==null?void 0:O.toolCalls)==null?void 0:R[0];if(!B)return null;const N=Go(B.toolName);return N?N.toolName:B.toolName||null}).filter(A=>!!A);if(_.length===0)return a("components.toolSession.title");if(_.length===1)return _[0];const C=_.filter((A,B)=>B===0||A!==_[B-1]),L=3;return C.length<=L?C.join(" → "):`${C.slice(0,L).join(" → ")} +${C.length-L}`},[e,a]),j=p.useMemo(()=>GO(e),[e]),w=o.jsx(oh,{tools:e,defaultExpanded:!0,hideHeader:!0}),M={background:"transparent"};return o.jsxs("div",{style:M,children:[o.jsxs("div",{style:{padding:`${i.paddingXS}px 0`,backgroundColor:"transparent",borderBottom:"none",cursor:"pointer",display:"flex",alignItems:"center",gap:i.marginSM,transition:"border-color 240ms ease, background-color 240ms ease"},onClick:()=>u(!c),"data-testid":"tool-session-card-header",children:[o.jsx(Ui,{style:{color:i.colorPrimary}}),o.jsx(Kl,{strong:!0,style:{flex:1},children:T}),o.jsx(Mm,{count:e.length,style:{backgroundColor:i.colorPrimary}}),x.changedTools>0&&o.jsxs(he,{size:4,style:{marginInlineStart:i.marginXS},children:[o.jsxs(Kl,{style:{color:i.colorSuccess,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",x.added]}),o.jsxs(Kl,{style:{color:i.colorError,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",x.removed]})]}),o.jsx(Kl,{type:"secondary",style:{fontSize:i.fontSizeSM},children:S.text}),r&&o.jsx(bt,{title:j.length>0?a("components.toolSession.deleteMessage"):a("components.toolSession.noPersistedMessage"),children:o.jsx(ue,{type:"text",size:"small",danger:!0,icon:o.jsx(Mr,{}),"aria-label":a("components.toolSession.deleteMessage"),"data-testid":"delete-tool-session",disabled:j.length===0,onClick:_=>{_.preventDefault(),_.stopPropagation(),j.length!==0&&r(j)}})}),o.jsx("div",{style:{marginLeft:i.marginXS},children:c?o.jsx(Gn,{style:{color:i.colorTextSecondary}}):o.jsx(Vs,{style:{color:i.colorTextSecondary}})})]}),c&&w]})},LS=p.memo(JO);LS.displayName="ToolSessionCard";const{Content:QO}=so,{Text:Xg}=He,ZO=24,e$=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};function du(e){return"type"in e&&(e.type==="tool_session"||e.type==="compression_divider")?e.id:e.message.id}const t$=({currentChat:e,currentSessionId:t,convertRenderableEntry:n,handleDeleteMessage:s,handleDeleteToolMessages:r,handleMessagesScroll:a,hasSystemPrompt:i,messagesListRef:l,renderableMessages:c,rowGap:u,showMessagesView:m,screens:f,workflowDraftId:g,isThinking:b,padding:S,selectionMode:x,selectedMessageIds:T,selectableMessageIds:j,onToggleMessageSelection:w})=>{const{t:M}=Ie(),_=p.useRef(c);_.current=c;const C=p.useCallback(I=>{const $=_.current[I];return $?du($):String(I)},[]),L=$E({count:c.length,getScrollElement:()=>l.current,estimateSize:()=>120,overscan:5,gap:u,getItemKey:C}),A=(I,$)=>{if(!x)return null;const U=j.has(I);return o.jsx(m_,{checked:T.has(I),disabled:!U,onChange:()=>{U&&w(I)},style:{marginTop:8,marginLeft:$==="flex-end"?8:0,marginRight:$==="flex-start"?8:0}})},B=(I,$)=>{const U=n(I),q=$===void 0||$===c.length-1;if(U.type==="compression_divider"){const K=e$(U.createdAt);return o.jsx("div",{role:"note","aria-label":M("chat.compression.timelineAria",{detail:U.label,time:K,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:f.xs?"8px 10px":"10px 12px"},children:o.jsxs(be,{align:"center",justify:"space-between",gap:8,wrap:!0,children:[o.jsxs(be,{align:"center",gap:8,wrap:!0,children:[o.jsx(Ne,{color:"gold",icon:o.jsx(_b,{}),children:M("chat.compression.tag","Context compressed")}),o.jsx(Xg,{strong:!0,style:{fontSize:12},children:U.label})]}),o.jsx(Xg,{type:"secondary",style:{fontSize:11},children:K})]})})}return U.type==="tool_session"?o.jsx(be,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:o.jsx("div",{id:`message-${U.id}`,style:{width:"100%",maxWidth:f.xs?"100%":"90%"},children:o.jsx(LS,{tools:U.tools,sessionId:U.sessionId,createdAt:U.createdAt,defaultExpanded:q,autoCollapseWhenStale:!q,onDeleteMessageIds:t?r:void 0})})}):U.message.role==="system"?o.jsxs(be,{align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[A(U.message.id,"flex-start"),o.jsx("div",{style:{flex:1,minWidth:0},children:o.jsx(Rx,{currentChat:e,message:U.message})})]}):o.jsxs(be,{justify:U.align,align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[U.align==="flex-start"&&A(U.message.id,U.align),o.jsx("div",{style:{width:U.message.role==="user"?"85%":"100%",maxWidth:f.xs?"100%":"90%"},children:o.jsx(OS,{sessionId:t,message:U.message,messageType:U.messageType,onDelete:U.message.id===g?void 0:s})}),U.align==="flex-end"&&A(U.message.id,U.align)]})},N=(m||i)&&c.length>0,O=L.getVirtualItems(),R=c.length>ZO;return o.jsxs(QO,{role:"log","aria-live":"polite","aria-label":"Chat messages",className:`chat-view-messages-list ${m?"visible":"hidden"}`,style:{flex:1,minHeight:0,padding:S,overflowY:"auto",opacity:m?1:0,scrollbarWidth:"none",msOverflowStyle:"none"},ref:l,onScroll:a,children:[N&&(R?o.jsx("div",{style:{position:"relative",width:"100%",height:L.getTotalSize()},children:O.map(I=>{const $=c[I.index];if(!$)return null;const U=du($);return o.jsx("div",{"data-chat-entry-id":U,"data-index":I.index,ref:L.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${I.start}px)`},children:o.jsx("div",{className:"messageEnter",children:B($,I.index)})},I.key)})}):o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:u,width:"100%"},children:c.map((I,$)=>{const U=du(I);return o.jsx("div",{"data-chat-entry-id":U,className:"messageEnter",children:B(I,$)},U)})})),b&&t&&o.jsx("div",{className:"streaming-card-enter",style:{paddingTop:u},children:o.jsx(be,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:o.jsx("div",{style:{width:"100%",maxWidth:f.xs?"100%":"90%"},children:o.jsx($S,{sessionId:t})})})})]})},{Text:Ro}=He,n$=e=>({pending:{icon:o.jsx(As,{}),color:e.colorTextTertiary,textKey:"components.todoList.status.pending",tagColor:"default"},in_progress:{icon:o.jsx(Pm,{spin:!0}),color:e.colorPrimary,textKey:"components.todoList.status.inProgress",tagColor:"processing"},completed:{icon:o.jsx(ar,{}),color:e.colorSuccess,textKey:"components.todoList.status.completed",tagColor:"success"},blocked:{icon:o.jsx(Em,{}),color:e.colorError,textKey:"components.todoList.status.blocked",tagColor:"error"}}),s$=({sessionId:e,initialCollapsed:t=!0})=>{const{t:n}=Ie(),{token:s}=Ge.useToken(),r=fn.useMemo(()=>n$(s),[s]),a=te(A=>A.chats.find(B=>B.id===e)),i=(a==null?void 0:a.kind)==="child"&&(a.parentSessionId||a.rootSessionId)||e,l=te(A=>A.taskLists[i]),c=te(A=>A.activeItems[i]),u=te(A=>A.evaluationStates[i]),[m,f]=p.useState(t),[g,b]=p.useState(!1),S=(u==null?void 0:u.isEvaluating)||!1,x=(u==null?void 0:u.reasoning)||null,T=l?{session_id:l.session_id,title:l.title,items:l.items,progress:{completed:l.items.filter(A=>A.status==="completed").length,total:l.items.length,percentage:l.items.length>0?Math.round(l.items.filter(A=>A.status==="completed").length/l.items.length*100):0}}:null;if(!T)return null;const j=()=>{g||f(!m)},w=A=>{A.stopPropagation(),b(!g),g||f(!1)},{title:M,items:_,progress:C}=T,L=C.percentage===100;return o.jsx(Ce,{size:"small",style:{marginBottom:16,borderRadius:8,boxShadow:S?`0 0 0 2px ${s.colorPrimaryBorder}`:"0 2px 8px rgba(0, 0, 0, 0.06)",opacity:m&&!g?.9:1},styles:{body:{padding:m?"12px 16px":16}},title:o.jsxs(he,{onClick:j,style:{cursor:"pointer",width:"100%"},children:[o.jsx(p_,{style:{color:s.colorPrimary}}),o.jsx(Ro,{strong:!0,style:{fontSize:15},children:M||n("components.todoList.title")}),S&&o.jsx(Ne,{icon:o.jsx(Pm,{spin:!0}),color:"processing",children:n("components.todoList.evaluating")}),!m&&C.total>0&&o.jsx(Mm,{count:`${C.completed}/${C.total}`,style:{backgroundColor:L?s.colorSuccess:s.colorPrimary}})]}),extra:o.jsxs(he,{children:[C.total>0&&m&&o.jsxs(Ro,{type:"secondary",style:{fontSize:13},children:[C.completed,"/",C.total,L&&o.jsx(ar,{style:{color:s.colorSuccess,marginLeft:4}})]}),o.jsx(bt,{title:n(g?"components.todoList.unpin":"components.todoList.pin"),children:o.jsx("span",{onClick:w,style:{cursor:"pointer",color:g?s.colorPrimary:s.colorTextSecondary,fontSize:16},children:g?o.jsx(ju,{}):o.jsx(jm,{})})}),!g&&o.jsx("span",{onClick:j,style:{cursor:"pointer",color:s.colorTextSecondary,fontSize:12,transform:m?"rotate(-90deg)":void 0,transition:"transform 0.2s"},children:m?o.jsx(Vs,{}):o.jsx(Gn,{})})]}),children:!m&&o.jsxs(o.Fragment,{children:[x&&o.jsx(Ut,{icon:o.jsx(Rm,{}),message:n("components.todoList.llmEvaluation"),description:x,type:"info",showIcon:!0,style:{marginBottom:16}}),C.total>0&&o.jsx("div",{style:{marginBottom:16},children:o.jsx(Am,{percent:C.percentage,size:"small",status:L?"success":"active",format:A=>o.jsxs(Ro,{type:"secondary",children:[A,"%"]})})}),o.jsx(Qt,{size:"small",dataSource:_,renderItem:A=>{const B=r[A.status],N=c===A.id,O=n(B.textKey);return o.jsx(Qt.Item,{style:{padding:"12px 0",borderLeft:N?`3px solid ${s.colorPrimary}`:"3px solid transparent",paddingLeft:N?12:15,backgroundColor:N?s.colorPrimaryBg:"transparent",borderRadius:4,marginBottom:4},children:o.jsx("div",{style:{width:"100%"},children:o.jsxs(he,{align:"start",style:{width:"100%"},children:[o.jsx(bt,{title:O,children:o.jsx("span",{style:{color:B.color,fontSize:16},children:B.icon})}),o.jsxs("div",{style:{flex:1,minWidth:0},children:[o.jsx(Ro,{style:{textDecoration:A.status==="completed"?"line-through":"none",color:A.status==="completed"?s.colorTextSecondary:s.colorText,fontWeight:N?500:400},children:A.description}),o.jsx("div",{style:{marginTop:4},children:o.jsxs(he,{size:8,wrap:!0,children:[o.jsx(Ne,{color:B.tagColor,children:O}),A.tool_calls_count!==void 0&&A.tool_calls_count>0&&o.jsxs(Ne,{icon:o.jsx(Ui,{}),color:"processing",children:[A.tool_calls_count," ",n("components.todoList.tools")]}),A.depends_on.length>0&&o.jsx(bt,{title:n("components.todoList.dependsOn",{deps:A.depends_on.join(", ")}),children:o.jsxs(Ne,{icon:o.jsx(h_,{}),children:[A.depends_on.length," ",n("components.todoList.dependencies")]})})]})}),A.status==="completed"&&A.summary&&o.jsx(Ro,{type:"secondary",style:{display:"block",marginTop:6,fontSize:12,padding:"4px 8px",backgroundColor:s.colorSuccessBg,borderRadius:4,color:s.colorSuccess},children:A.summary}),A.notes&&o.jsx(Ro,{type:"secondary",style:{display:"block",marginTop:6,fontSize:12,padding:"4px 8px",backgroundColor:s.colorFillQuaternary,borderRadius:4},children:A.notes})]})]})})})}})]})})},r$="_questionCard_15meh_1",o$="_questionHeader_15meh_8",a$="_headerLeft_15meh_27",i$="_questionIcon_15meh_35",l$="_questionText_15meh_40",c$="_collapseBtn_15meh_52",d$="_questionBody_15meh_57",u$="_optionsGroup_15meh_61",m$="_optionItem_15meh_65",h$="_customHint_15meh_81",p$="_questionFooter_15meh_93",ms={questionCard:r$,questionHeader:o$,headerLeft:a$,questionIcon:i$,questionText:l$,collapseBtn:c$,questionBody:d$,optionsGroup:u$,optionItem:m$,customHint:h$,questionFooter:p$},{Text:Vl}=He,{useToken:f$}=Ge,g$=e=>{const t=(e||"").replace(/\\r\\n/g,`
|
|
237
|
+
`).replace(/\\n/g,`
|
|
238
|
+
`).replace(/\r\n?/g,`
|
|
239
|
+
`).trim();return t?t.includes(`
|
|
240
|
+
`)?t:t.replace(/\s+(?=\d+[).]\s)/g,`
|
|
241
|
+
`).replace(/\s+(?=[一二三四五六七八九十]+[、.]\s)/g,`
|
|
242
|
+
`).replace(/\s+(?=[-*•]\s)/g,`
|
|
243
|
+
`):""},y$=({sessionId:e,onResponseSubmitted:t,onQuestionAppeared:n})=>{var zt,Ye;const{t:s}=Ie(),{token:r}=f$(),{message:a}=sn.useApp(),[i,l]=p.useState(null),[c,u]=p.useState(null),[m,f]=p.useState(!1),[g,b]=p.useState(!0),[S,x]=p.useState(!1),T=p.useRef(0),j=p.useRef(0),w=p.useRef(null),M=p.useRef(n);M.current=n;const[_,C]=p.useState(()=>typeof document>"u"?!0:!document.hidden),L=te(we=>we.markRespondStart),A=te(we=>we.markSettleTimeout),B=te(we=>we.setPendingQuestion),N=te(we=>we.clearPendingQuestion),O=te(we=>we.chats.find(Ke=>Ke.id===e)||null),R=te(we=>{if(!e)return null;const Ke=Xb(e)(we);return(Ke==null?void 0:Ke.interaction.pendingQuestion)??null}),I=p.useMemo(()=>R?{has_pending_question:!0,question:R.question,options:R.options,allow_custom:R.allowCustom,tool_call_id:R.toolCallId??void 0}:i,[R,i]),$=Xm((zt=O==null?void 0:O.config)==null?void 0:zt.model_ref),U=te(we=>{var Ke;return e?(Ke=we.inputStates)==null?void 0:Ke[e]:void 0}),q=Mt(we=>we.currentProvider),K=Mt(we=>we.providerConfig),P=p.useMemo(()=>{var we;return(we=K.providers[q])==null?void 0:we.reasoning_effort},[K,q]),W=p.useMemo(()=>e?Um(e):void 0,[e]),se=((Ye=O==null?void 0:O.config)==null?void 0:Ye.reasoningEffort)??(U==null?void 0:U.reasoningEffort)??W??P??"medium",V=te(dr(e)),re=te(we=>we.currentSessionId)===e,fe=p.useCallback(async()=>{try{const we=await Ze.get(`respond/${e}/pending`);we.has_pending_question?(l(Ke=>{const st=nc({sessionId:e,question:we.question,options:we.options,allowCustom:we.allow_custom,toolCallId:we.tool_call_id});return(Ke!=null&&Ke.has_pending_question?nc({sessionId:e,question:Ke.question,options:Ke.options,allowCustom:Ke.allow_custom,toolCallId:Ke.tool_call_id}):null)===st?Ke??we:we}),T.current=0,j.current=0):(l(null),w.current=null,T.current+=1,T.current>=6?j.current=2:T.current>=2&&(j.current=1))}catch(we){if(we instanceof Error&&we.message.includes("404")){l(null),w.current=null,T.current+=1;return}l(null),w.current=null,T.current+=1,T.current>=6?j.current=2:T.current>=2&&(j.current=1),console.error("Failed to fetch pending question:",we)}finally{b(!1)}},[e]);p.useEffect(()=>{T.current=0,j.current=0,w.current=null,b(!0),u(null),x(!1)},[e]),p.useEffect(()=>{if(typeof document>"u")return;const we=()=>{C(!document.hidden)};return document.addEventListener("visibilitychange",we),()=>document.removeEventListener("visibilitychange",we)},[]),p.useEffect(()=>{var we;if(I!=null&&I.has_pending_question){const Ke=nc({sessionId:e,question:I==null?void 0:I.question,options:I==null?void 0:I.options,allowCustom:I==null?void 0:I.allow_custom,toolCallId:I==null?void 0:I.tool_call_id}),st=w.current===Ke;B(e,{question:(I==null?void 0:I.question)||"",options:(I==null?void 0:I.options)||[],allowCustom:(I==null?void 0:I.allow_custom)??!0,toolCallId:(I==null?void 0:I.tool_call_id)??null}),st||(u(null),x(!1),(we=M.current)==null||we.call(M)),w.current=Ke}else w.current=null,N(e)},[I==null?void 0:I.allow_custom,I==null?void 0:I.has_pending_question,I==null?void 0:I.options,I==null?void 0:I.question,I==null?void 0:I.tool_call_id,e,B,N]);const Se=p.useCallback(()=>{if(R)return null;if(I!=null&&I.has_pending_question)return _?5e3:15e3;if(V)return re?_?5e3:15e3:null;if(!re||!_)return null;const we=j.current;return we===0?3e4:we===1?6e4:12e4},[R,I==null?void 0:I.has_pending_question,V,re,_]);p.useEffect(()=>{if(R){b(!1);return}let we=!1,Ke=null;const st=async()=>{if(we||m||(await fe(),we))return;const Dt=Se();Dt!==null&&(Ke=setTimeout(st,Dt))};return st(),()=>{we=!0,Ke&&clearTimeout(Ke)}},[R,fe,Se,m]),p.useEffect(()=>{if(typeof window>"u")return;const we=Ke=>{var F;const Dt=((F=Ke.detail)==null?void 0:F.sessionId)??null;!Dt||Dt!==e||(l(null),u(null),T.current=0)};return window.addEventListener(zo,we),()=>{window.removeEventListener(zo,we)}},[e]);const ke=p.useCallback(we=>{u(we)},[]),Be=async()=>{if(!c||c==="custom"){a.warning(s("components.questionDialog.selectOptionWarning"));return}f(!0),L(e,(I==null?void 0:I.tool_call_id)??null),await new Promise(we=>setTimeout(we,0));try{const we={};Mt.getState().isProviderModelRefEnabled()&&$&&(we.model_ref=$,we.provider=$.provider);const Ke=await Ze.post(`respond/${e}`,{response:c,reasoning_effort:se,...we});a.success(s("components.questionDialog.responseSubmitted")),l(null),u(null),T.current=0,N(e),typeof window<"u"&&window.dispatchEvent(new CustomEvent(zo,{detail:{sessionId:e}}));const st=Ke==null?void 0:Ke.auto_resume_status;st==="error"?(console.error("[QuestionDialog] Failed to auto-resume agent execution"),A(e)):(!st||!["started","already_running"].includes(st))&&A(e),t==null||t()}catch(we){console.error("Failed to submit response:",we),a.error(we instanceof Error?we.message:s("components.questionDialog.submitFailed")),A(e)}finally{f(!1)}};if(g||!(I!=null&&I.has_pending_question))return null;const{question:tt,options:ft,allow_custom:Ht}=I,Oe=g$(tt);return o.jsxs("div",{className:ms.questionCard,style:{background:r.colorBgContainer,borderColor:r.colorBorderSecondary,border:`1px solid ${r.colorBorderSecondary}`},children:[o.jsxs("div",{className:ms.questionHeader,"data-collapsed":S?"true":"false",onClick:()=>x(we=>!we),role:"button",tabIndex:0,onKeyDown:we=>{(we.key==="Enter"||we.key===" ")&&x(Ke=>!Ke)},children:[o.jsxs("span",{className:ms.headerLeft,children:[o.jsx("span",{className:ms.questionIcon,children:"🤔"}),o.jsx(Vl,{strong:!0,className:ms.questionText,style:{color:r.colorPrimary,whiteSpace:"pre-wrap"},title:S?Oe:void 0,children:Oe})]}),o.jsx(ue,{type:"text",size:"small",icon:S?o.jsx(Gn,{}):o.jsx(Im,{}),className:ms.collapseBtn,tabIndex:-1})]}),!S&&o.jsxs("div",{className:ms.questionBody,children:[o.jsx(bs.Group,{className:ms.optionsGroup,value:c,onChange:we=>ke(we.target.value),children:o.jsxs(he,{direction:"vertical",size:4,style:{width:"100%"},children:[ft==null?void 0:ft.map((we,Ke)=>o.jsx(bs,{value:we,className:ms.optionItem,children:o.jsx(Vl,{style:{color:r.colorText},children:we})},Ke)),Ht&&o.jsx(bs,{value:"custom",className:ms.optionItem,children:o.jsxs(he,{size:4,children:[o.jsx(Hi,{}),o.jsx(Vl,{style:{color:r.colorText},children:s("components.questionDialog.otherTypeBelow")})]})})]})}),c==="custom"&&o.jsx("div",{className:ms.customHint,children:o.jsx(Vl,{type:"secondary",style:{fontSize:12},children:s("components.questionDialog.customAnswerTip")})}),c&&c!=="custom"&&o.jsx("div",{className:ms.questionFooter,children:o.jsx(ue,{type:"primary",size:"small",onClick:Be,loading:m,children:s("components.questionDialog.confirm")})})]})]})};function FS(e){return typeof e.maxContextTokens=="number"&&e.maxContextTokens>0?e.maxContextTokens:e.budgetLimit>0?e.budgetLimit:0}function NS(e){const t=FS(e);return t===0?0:e.totalTokens/t*100}function b$(e){const t=NS(e);return t>=90?"error":t>=70?"warning":t>=50?"success":"default"}function Ea(e){return e.toLocaleString()}const x$=({usage:e,showDetails:t=!0,size:n="small",className:s=""})=>{const{t:r}=Ie(),a=FS(e),i=NS(e),l=f=>{const g=Math.round(f*10)/10;return Number.isInteger(g)?g.toFixed(0):g.toFixed(1)},c=b$(e),u=()=>i>=90?"var(--lotus-chart-danger)":i>=70?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",m=o.jsxs("div",{style:{minWidth:180,color:"var(--lotus-metric-text-strong)"},children:[o.jsx("div",{style:{marginBottom:4,fontWeight:"bold"},children:r("components.tokenUsage.title")}),o.jsxs("div",{style:{fontSize:12},children:[r("components.tokenUsage.contextWindow"),":"," ",Ea(e.totalTokens)," / ",Ea(a)," ",r("components.tokenUsage.tokens")]}),o.jsx("div",{style:{fontSize:12,color:"var(--lotus-metric-text-muted)"},children:r("components.tokenUsage.usedPercent",{value:i.toFixed(1)})}),t&&o.jsxs("div",{style:{marginTop:6,borderTop:"1px solid var(--lotus-metric-tooltip-border)",paddingTop:6,fontSize:11},children:[o.jsxs("div",{children:[r("components.tokenUsage.system"),": ",Ea(e.systemTokens)]}),e.summaryTokens>0&&o.jsxs("div",{children:[r("components.tokenUsage.summary"),": ",Ea(e.summaryTokens)]}),o.jsxs("div",{children:[r("components.tokenUsage.messages"),": ",Ea(e.windowTokens)]}),typeof e.promptCachedToolOutputs=="number"&&e.promptCachedToolOutputs>0&&o.jsx("div",{style:{color:"var(--lotus-metric-text-muted)"},children:r("components.tokenUsage.cachedToolOutputs",{count:e.promptCachedToolOutputs,defaultValue:"Prompt cache: {{count}} tool outputs summarized"})})]})]});return o.jsx(bt,{title:m,placement:"top",arrow:!0,children:o.jsxs(he,{className:`token-usage-display ${s}`,size:4,align:"center",style:{lineHeight:1},children:[o.jsx(Am,{type:"line",percent:Math.min(i,100),size:{height:n==="small"?6:8,width:80},strokeColor:u(),showInfo:!1,style:{margin:0,lineHeight:1}}),o.jsxs("span",{style:{fontSize:n==="small"?11:12,color:c==="error"?"var(--lotus-chart-danger)":c==="warning"?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",whiteSpace:"nowrap",fontWeight:600},children:[l(i),"%"]})]})})},no=class no{static getInstance(){return no.instance||(no.instance=new no),no.instance}parseUserCommand(t){Jt("[ToolService]",`[ToolService] parseUserCommand: Parsing content: "${t}"`);const n=t.trim();if(!n.startsWith("/"))return Jt("[ToolService]",'[ToolService] parseUserCommand: Content does not start with "/", not a tool command.'),null;const s=n.indexOf(" ");let r,a;if(s===-1?(r=n.substring(1),a=""):(r=n.substring(1,s),a=n.substring(s+1).trim()),r){const i={tool_name:r,user_description:a};return Jt("[ToolService]","[ToolService] parseUserCommand: Successfully parsed command:",i),i}return Jt("[ToolService]","[ToolService] parseUserCommand: Failed to parse tool name from content."),null}parseAIResponseToToolCall(t){return this.parseUserCommand(t)}async executeTool(t){Jt("[ToolService]","[ToolService] executeTool: Attempting to execute tool via HTTP with request:",t);try{const n=await rt.post("tools/execute",t),s=JSON.parse(n.result);return Jt("[ToolService]","[ToolService] executeTool: Parsed structured result:",s),s}catch(n){throw console.error("[ToolService] executeTool: HTTP tool execution failed:",n),n instanceof uo?new Error(`Workflow execution failed: ${n.message}`):n}}};Ct(no,"instance");let gm=no;const uu=new gm;class v${async listProfiles(){return rt.get("subagent_profiles")}}const S$=new v$,w$=[];function _$(e={}){const{enabled:t=!0,refreshKey:n}=e,[s,r]=p.useState(null),[a,i]=p.useState(!1),[l,c]=p.useState(null),u=p.useCallback(async()=>{i(!0);try{const f=await S$.listProfiles();r(f),c(null)}catch(f){c(f instanceof Error?f:new Error(String(f)))}finally{i(!1)}},[]);p.useEffect(()=>{t&&u()},[t,u,n]);const m=p.useMemo(()=>{const f=new Map;if(s!=null&&s.profiles)for(const g of s.profiles)f.set(g.id,g);return f},[s]);return{profiles:(s==null?void 0:s.profiles)??w$,fallbackId:(s==null?void 0:s.fallback_id)??null,loading:a,error:l,refresh:u,byId:m}}const k$=(e,t)=>{var l,c,u,m,f;const n=e==null?void 0:e.trim();if(!n)return null;const s=t.get(n),r=((l=s==null?void 0:s.display_name)==null?void 0:l.trim())||n,a=(u=(c=s==null?void 0:s.ui)==null?void 0:c.icon)==null?void 0:u.trim(),i=((f=(m=s==null?void 0:s.ui)==null?void 0:m.color)==null?void 0:f.trim())||void 0;return o.jsx(Ne,{color:i,style:{marginInlineEnd:0,flex:"0 0 auto"},"data-testid":`sub-session-role-tag-${n}`,children:a?`${a} ${r}`:r})},{Text:Sr}=He,{useToken:zS}=Ge,T$="chat-session-sub-sessions-collapsed:",j$=3,C$=600,mc=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"},M$=(e,t)=>{if(t&&t.trim())return t;if(e.isRunning)return"running";if(e.lastRunStatus&&e.lastRunStatus.trim())return e.lastRunStatus;const n=e.messageCount??0;return n>2?"completed":(n>0,"pending")},BS=e=>`${T$}${e}`,mu=e=>{if(typeof window>"u")return!1;try{const t=window.localStorage.getItem(BS(e));return t==="1"?!0:t==="0"?!1:null}catch{return null}},P$=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(BS(e),t?"1":"0")}catch{}},E$=({parentSessionId:e})=>{const{t}=Ie(),{token:n}=zS(),[s,r]=p.useState(()=>mu(e)??!1),[a,i]=p.useState(null),[l,c]=p.useState(null),[u,m]=p.useState(null),f=te(q=>Fi(e)(q)),g=te(q=>q.chats),b=te(q=>q.loadChatHistory),S=te(q=>q.refreshChats),x=te(q=>q.markOptimisticStart),T=te(q=>q.markRetryStart),j=te(q=>q.markSettleTimeout),w=te(q=>q.pinSession),M=te(q=>q.unpinSession),_=te(q=>q.applyChildProgress),C=te(q=>q.clearChildProgress),{byId:L}=_$(),A=p.useMemo(()=>Object.entries(f).map(([q,K])=>({childSessionId:q,...K})),[f]),B=p.useMemo(()=>g.filter(q=>q.kind==="child"&&q.parentSessionId===e).sort((q,K)=>{const P=Date.parse(q.updatedAt||"")||0;return(Date.parse(K.updatedAt||"")||0)-P}),[g,e]),N=p.useMemo(()=>{const q=new Map(A.map(P=>[P.childSessionId,P])),K=[];for(const P of B){const W=q.get(P.id);K.push({childSessionId:P.id,title:P.title||(W==null?void 0:W.title),status:mc(M$(P,W==null?void 0:W.status)),error:(W==null?void 0:W.error)||P.lastRunError,lastHeartbeatAt:W==null?void 0:W.lastHeartbeatAt,lastEventAt:W==null?void 0:W.lastEventAt,outputPreview:W==null?void 0:W.outputPreview,roundCount:W==null?void 0:W.roundCount,pinned:P.pinned,updatedAt:P.updatedAt,isRunning:P.isRunning,messageCount:P.messageCount,lastRunStatus:P.lastRunStatus,lastRunError:P.lastRunError,subagentType:P.subagentType??null}),q.delete(P.id)}for(const P of q.values())K.push({childSessionId:P.childSessionId,title:P.title,status:mc(P.status),error:P.error,lastHeartbeatAt:P.lastHeartbeatAt,lastEventAt:P.lastEventAt,outputPreview:P.outputPreview,roundCount:P.roundCount});return K},[B,A]);p.useEffect(()=>{r(mu(e)??!1)},[e]),p.useEffect(()=>{mu(e)===null&&r(N.length>j$)},[e,N.length]);const O=p.useCallback(()=>{r(q=>{const K=!q;return P$(e,K),K})},[e]),R=p.useCallback(q=>q instanceof Error&&q.message.trim()?q.message:"Failed to run child session",[]),I=p.useCallback(async(q,K="regenerate")=>{i(q),_(e,q,{status:"running",error:void 0,lastEventAt:new Date().toISOString()}),T(q);try{const P=await uu.executeTool({tool_name:"SubSession",session_id:e,parameters:[{name:"action",value:"run"},{name:"child_session_id",value:q},{name:"reset_to_last_user",value:K==="error_retry"?"false":"true"}]});if(!P.success)throw new Error(P.result||"Failed to run child session");_(e,q,{status:"running",error:void 0,lastEventAt:new Date().toISOString()}),await b(q,{mode:"replace"}),await S()}catch(P){j(q),_(e,q,{status:"error",error:R(P),lastEventAt:new Date().toISOString()})}finally{i(P=>P===q?null:P)}},[b,e,S,T,j,R,_]),$=p.useCallback(async q=>{const K=typeof window<"u"?window.prompt.bind(window):null;if(!K)return;const P=K("Send a follow-up message to this child session:","Continue from where you left off.");if(P===null)return;const W=P.trim();if(!W){_(e,q,{status:"error",error:"Follow-up message cannot be empty.",lastEventAt:new Date().toISOString()});return}c(q),_(e,q,{status:"running",error:void 0,lastEventAt:new Date().toISOString()}),x(q);try{const se=await uu.executeTool({tool_name:"SubSession",session_id:e,parameters:[{name:"action",value:"send_message"},{name:"child_session_id",value:q},{name:"message",value:W},{name:"auto_run",value:"true"}]});if(!se.success)throw new Error(se.result||"Follow-up failed");let V="running";try{JSON.parse(se.result).status==="pending"&&(V="pending")}catch{V="running"}_(e,q,{status:V,error:void 0,lastEventAt:new Date().toISOString()}),await S()}catch(se){j(q),_(e,q,{status:"error",error:se instanceof Error&&se.message.trim()?se.message:"Failed to continue child session",lastEventAt:new Date().toISOString()})}finally{c(se=>se===q?null:se)}},[e,S,x,j,_]),U=p.useCallback(async q=>{m(q);try{const K=await uu.executeTool({tool_name:"SubSession",session_id:e,parameters:[{name:"action",value:"delete"},{name:"child_session_id",value:q}]});if(!K.success)throw new Error(K.result||"Failed to delete child session");C(e,q),await S()}finally{m(K=>K===q?null:K)}},[C,e,S]);return N.length===0?null:o.jsxs(Ce,{size:"small",className:"lotus-settings-card",style:{marginBottom:n.marginMD},"data-testid":"sub-sessions-panel",title:o.jsxs(Sr,{strong:!0,children:[t("chat.subSessions.title")," ",o.jsxs(Sr,{type:"secondary",children:["(",N.length,")"]})]}),extra:o.jsx(ue,{type:"text",size:"small",icon:s?o.jsx(Gn,{}):o.jsx(Im,{}),onClick:O,"data-testid":"sub-sessions-toggle",children:t(s?"chat.subSessions.expand":"chat.subSessions.collapse")}),children:[s?o.jsx(Sr,{type:"secondary","data-testid":"sub-sessions-collapsed-hint",children:t("chat.subSessions.hiddenHint",{count:N.length})}):o.jsx(be,{vertical:!0,gap:n.marginSM,"data-testid":"sub-sessions-list",style:{maxHeight:`${C$}px`,overflowY:"auto",paddingRight:n.paddingXS},children:N.map(q=>{const K=mc(q.status),P=K==="running",W=a===q.childSessionId,se=l===q.childSessionId,V=u===q.childSessionId,ie=W||se||V;return o.jsxs(be,{align:"flex-start",justify:"space-between",gap:n.marginSM,className:"lotus-settings-list-item",style:{padding:n.paddingSM,borderRadius:n.borderRadiusSM},children:[o.jsxs(be,{vertical:!0,style:{flex:1,minWidth:0},children:[o.jsxs(be,{align:"center",gap:n.marginXS,style:{minWidth:0},children:[o.jsx(Sr,{strong:!0,ellipsis:!0,style:{minWidth:0},children:q.title||"Child Session"}),o.jsx(Ne,{color:K==="running"?"processing":K==="completed"?"success":K==="error"||K==="failed"?"error":K==="cancelled"?"warning":"default",style:{marginInlineEnd:0,flex:"0 0 auto"},children:K}),q.pinned?o.jsx(Ne,{color:"warning",style:{marginInlineEnd:0,flex:"0 0 auto"},children:"Pinned"}):null,k$(q.subagentType,L)]}),o.jsxs(Sr,{type:"secondary",style:{fontSize:12,marginTop:2},children:[q.childSessionId.slice(0,8),q.updatedAt?` • ${q.updatedAt}`:"",q.lastHeartbeatAt?` • heartbeat: ${q.lastHeartbeatAt}`:"",typeof q.roundCount=="number"?` • round ${q.roundCount+1}`:""]}),q.outputPreview?o.jsx(Sr,{type:"secondary",style:{marginTop:n.marginXS,fontSize:13},ellipsis:!0,children:q.outputPreview}):null,q.error?o.jsx(Sr,{type:"danger",style:{marginTop:n.marginXS},children:q.error}):null]}),o.jsxs(be,{gap:8,children:[o.jsx(ue,{size:"small",disabled:ie,onClick:()=>{qc(q.childSessionId),b(q.childSessionId)},children:t("chat.subSessions.open")}),o.jsx(ue,{size:"small",loading:se,disabled:V||W||P,"data-testid":`sub-session-continue-${q.childSessionId}`,onClick:()=>{$(q.childSessionId)},children:t("chat.subSessions.continue")}),o.jsx(lo,{trigger:["click"],menu:{items:[{key:"regenerate",label:t("chat.actions.regenerate")},{key:"error_retry",label:t("chat.actions.retryFailed")}],onClick:({key:re})=>{I(q.childSessionId,re)}},disabled:V||P||se,children:o.jsx(ue,{size:"small",loading:W,disabled:V||P||se,"data-testid":`sub-session-retry-${q.childSessionId}`,children:t("chat.subSessions.retry")})}),typeof q.pinned=="boolean"?o.jsx(ue,{size:"small",disabled:ie,onClick:()=>{q.pinned?M(q.childSessionId):w(q.childSessionId)},children:q.pinned?t("chat.actions.unpin"):t("chat.actions.pin")}):null,o.jsx(ue,{danger:!0,size:"small",loading:V,disabled:W,"data-testid":`sub-session-delete-${q.childSessionId}`,onClick:()=>{U(q.childSessionId)},children:t("common.delete")})]})]},q.childSessionId)})}),!s&&N.length>1&&o.jsx(R$,{items:N})]})},R$=({items:e})=>{const{token:t}=zS(),n=e.reduce((r,a)=>{const i=mc(a.status);return i==="completed"?r.completed++:i==="running"?r.running++:i==="error"||i==="failed"?r.error++:r.pending++,r},{completed:0,running:0,error:0,pending:0}),s=[];return n.completed>0&&s.push(`${n.completed} completed`),n.running>0&&s.push(`${n.running} running`),n.pending>0&&s.push(`${n.pending} pending`),n.error>0&&s.push(`${n.error} failed`),s.length===0?null:o.jsx(Sr,{type:"secondary",style:{fontSize:11,marginTop:t.marginXS,display:"block"},children:s.join(" · ")})},{useToken:A$}=Ge,I$=e=>{const t=e.replace(/\/$/,"").split("/").filter(Boolean);return t.length<=2?e:`~/${t.slice(-2).join("/")}`},O$=({sessionId:e})=>{const{t}=Ie(),{token:n}=A$(),s=te(Er(e)),r=te(m=>m.systemPrompts),a=s==null?void 0:s.config.workspacePath,i=s==null?void 0:s.config.systemPromptId,l=p.useMemo(()=>{if(!i)return null;const m=r.find(f=>f.id===i);return(m==null?void 0:m.name)||i},[i,r]),c=p.useMemo(()=>s!=null&&s.messages?s.messages.filter(m=>m.role==="user"&&"type"in m&&m.type==="file_reference").length:0,[s==null?void 0:s.messages]);return!s||!(a||l||c>0)?null:o.jsx("div",{className:"lotus-context-bar",style:{borderBottomColor:n.colorBorderSecondary,backgroundColor:n.colorBgContainer},children:o.jsxs(be,{align:"center",gap:6,wrap:"wrap",className:"lotus-context-bar__content",children:[a&&o.jsx(bt,{title:a,children:o.jsx(Ne,{className:"lotus-context-bar__tag",icon:o.jsx(fc,{}),bordered:!1,children:I$(a)})}),c>0&&o.jsx(bt,{title:t("chat.contextBar.fileRefsTooltip",{count:c,defaultValue:"{{count}} file reference(s) in this session"}),children:o.jsxs(Ne,{className:"lotus-context-bar__tag",icon:o.jsx(f_,{}),bordered:!1,children:[c," ",t("chat.contextBar.files","files")]})}),l&&o.jsx(bt,{title:t("chat.contextBar.promptTooltip",{name:l,defaultValue:"System prompt: {{name}}"}),children:o.jsx(Ne,{className:"lotus-context-bar__tag",icon:o.jsx(Bc,{}),bordered:!1,children:l})})]})})},$$=new Set(["Write","Edit","apply_patch","NotebookEdit"]),D$=e=>{const t=e.match(/(?:file_path|Wrote file|Edited file)[:\s]*["']?([^\s"',]+)/i);if(t){const n=t[1];return n.split("/").pop()||n}return null},L$=(e,t)=>{const n=t-e;if(n<0)return"";const s=Math.floor(n/1e3);if(s<60)return`${s}s`;const r=Math.floor(s/60);return r<60?`${r}m ${s%60}s`:`${Math.floor(r/60)}h ${r%60}m`},F$=e=>{var f,g;let t=0,n=0,s=0,r=0,a=!1,i=0,l="";const c=new Set;let u=0,m=0;for(const b of e){const S=b.createdAt?new Date(b.createdAt).getTime():0;if(S>0&&(u===0||S<u)&&(u=S),S>m&&(m=S),b.isCompressed){a=!0,i++;continue}if(b.role==="user"&&!("type"in b&&b.type==="file_reference")&&t++,b.role==="assistant"){if("type"in b&&b.type==="tool_call"&&(s+=((f=b.toolCalls)==null?void 0:f.length)??0),"type"in b&&b.type==="tool_result"){const x=b;if(x.isError&&r++,$$.has(x.toolName)){const T=D$(((g=x.result)==null?void 0:g.result)??"");T&&c.add(T)}}if("type"in b&&b.type==="text"){n++;const x=b.content||"";x.length>0&&x.length>30&&(l=x.slice(0,300))}}}return{messageCount:e.length,userMessageCount:t,assistantMessageCount:n,toolCallCount:s,toolErrorCount:r,fileChanges:Array.from(c).slice(0,10),lastAssistantExcerpt:l,hasCompression:a,compressionCount:i,duration:u>0&&m>u?L$(u,m):""}},N$=({sessionId:e})=>{const{t}=Ie(),{token:n}=Ge.useToken(),[s,r]=p.useState(!1),a=te(Er(e)),i=a==null?void 0:a.messages,l=p.useMemo(()=>!i||i.length===0?null:F$(i),[i]);if(!l||l.messageCount<3)return null;const c=l.fileChanges.length>0,u=l.lastAssistantExcerpt.length>0;return o.jsxs("div",{className:"lotus-session-summary",style:{borderColor:n.colorBorderSecondary,background:`${n.colorBgElevated}`},children:[o.jsxs("div",{className:"lotus-session-summary-header",onClick:()=>r(m=>!m),role:"button",tabIndex:0,onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),r(f=>!f))},"aria-expanded":s,children:[o.jsx("span",{className:"lotus-session-summary-header-icon",style:{color:n.colorPrimary},children:o.jsx(g_,{})}),o.jsx("span",{className:"lotus-session-summary-header-title",style:{color:n.colorText},children:t("sessionSummary.title","Session Summary")}),!s&&o.jsxs("span",{className:"lotus-session-summary-stats",children:[o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:n.colorTextSecondary},children:[o.jsx(gc,{className:"lotus-session-summary-stat-icon"}),o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.messageCount})]}),l.toolCallCount>0&&o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:n.colorTextSecondary},children:[o.jsx(ap,{className:"lotus-session-summary-stat-icon"}),o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolCallCount})]}),c&&o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:n.colorTextSecondary},children:[o.jsx(qo,{className:"lotus-session-summary-stat-icon"}),o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.fileChanges.length})]})]}),o.jsx("span",{className:`lotus-session-summary-toggle ${s?"is-expanded":""}`,style:{color:n.colorTextTertiary},children:o.jsx(Gn,{})})]}),s&&o.jsxs("div",{className:"lotus-session-summary-body",children:[o.jsxs("div",{className:"lotus-session-summary-stats",children:[o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:n.colorTextSecondary},children:[o.jsx(gc,{className:"lotus-session-summary-stat-icon"}),o.jsxs("span",{children:[o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.messageCount})," ",t("sessionSummary.messages","messages")]})]}),o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:n.colorTextSecondary},children:[o.jsx("span",{className:"lotus-session-summary-stat-icon",children:"👤"}),o.jsxs("span",{children:[o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.userMessageCount})," ",t("sessionSummary.userTurns","user")]})]}),o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:n.colorTextSecondary},children:[o.jsx("span",{className:"lotus-session-summary-stat-icon",children:"🤖"}),o.jsxs("span",{children:[o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.assistantMessageCount})," ",t("sessionSummary.assistantTurns","assistant")]})]}),l.toolCallCount>0&&o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:n.colorTextSecondary},children:[o.jsx(ap,{className:"lotus-session-summary-stat-icon"}),o.jsxs("span",{children:[o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolCallCount})," ",t("sessionSummary.toolCalls","tool calls")]})]}),l.toolErrorCount>0&&o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:"#ff4d4f"},children:[o.jsx(Vi,{className:"lotus-session-summary-stat-icon"}),o.jsxs("span",{children:[o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolErrorCount})," ",t("sessionSummary.errors","errors")]})]}),l.duration&&o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:n.colorTextSecondary},children:[o.jsx(As,{className:"lotus-session-summary-stat-icon"}),o.jsx("span",{children:l.duration})]}),l.hasCompression&&o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:n.colorTextSecondary},children:[o.jsx(Bc,{className:"lotus-session-summary-stat-icon"}),o.jsxs("span",{children:[o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.compressionCount})," ",t("sessionSummary.compressions","compressions")]})]})]}),c&&o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:11,fontWeight:600,color:n.colorTextSecondary,marginBottom:4,textTransform:"uppercase",letterSpacing:.3},children:t("sessionSummary.filesChanged","Files Changed")}),o.jsx("div",{className:"lotus-session-summary-files",children:l.fileChanges.map(m=>o.jsx(bt,{title:m,children:o.jsxs(Ne,{bordered:!1,className:"lotus-session-summary-file-tag",children:[o.jsx(qo,{style:{marginRight:4}}),m]})},m))})]}),u&&o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:11,fontWeight:600,color:n.colorTextSecondary,marginBottom:4,textTransform:"uppercase",letterSpacing:.3},children:t("sessionSummary.lastResponse","Latest Response")}),o.jsx("div",{className:"lotus-session-summary-conclusion",style:{color:n.colorTextSecondary},children:l.lastAssistantExcerpt})]})]})]})},ym="chat_scroll_anchors_v1",WS="chat_scroll_anchor_v2:";function qS(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 z$(){try{const e=localStorage.getItem(ym);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const n={};for(const[s,r]of Object.entries(t))qS(r)&&(n[s]=r);return n}catch{return{}}}function B$(e){const t=z$(),n=t[e];if(!n)return null;Wn.getInstance().saveScrollAnchor(e,n).catch(()=>{}),delete t[e];const r=Object.keys(t).length;try{r===0?localStorage.removeItem(ym):localStorage.setItem(ym,JSON.stringify(t))}catch{}return n}async function W$(e){if(typeof window>"u")return null;try{const n=await Wn.getInstance().loadScrollAnchor(e);if(n)return n}catch{}try{const t=localStorage.getItem(`${WS}${e}`);if(t){const n=JSON.parse(t);if(qS(n))return Wn.getInstance().saveScrollAnchor(e,n).catch(()=>{}),n}}catch{}return B$(e)}async function q$(e,t){if(!(typeof window>"u")){try{await Wn.getInstance().saveScrollAnchor(e,t)}catch(n){console.warn("[ScrollAnchor] IndexedDB save failed:",n)}try{localStorage.setItem(`${WS}${e}`,JSON.stringify(t))}catch{}}}const hu=1,U$=3,H$=2e3;function K$(e,t){const n=Math.max(0,e.scrollHeight-e.clientHeight);return Math.min(Math.max(0,t),n)}function V$(e){const{scrollEl:t,getAnchorElement:n,offsetPx:s,isCancelled:r}=e;return new Promise(a=>{const i=performance.now();let l=0,c=-1,u=Number.NaN;const m=()=>{if(r()){a();return}const f=n();if(!f){requestAnimationFrame(m);return}const g=t.getBoundingClientRect(),S=f.getBoundingClientRect().top-g.top,x=K$(t,t.scrollTop+(S-s));if(Math.abs(t.scrollTop-x)>hu)t.scrollTop=x,l=0;else{const j=Number.isFinite(u)?Math.abs(x-u)<=hu:!1,w=Math.abs(t.scrollTop-c)<=hu;l=j&&w?l+1:0}u=x,c=t.scrollTop;const T=performance.now()-i>H$;if(l>=U$||T){a();return}requestAnimationFrame(m)};requestAnimationFrame(m)})}const Y$=300,X$=.5;function G$(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 US(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 Gg(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function J$(e,t){const n=Gg(e.createdAt);if(n!=null){let s=null,r=Number.POSITIVE_INFINITY;for(let a=0;a<t.length;a++){const i=Gg(US(t[a]));if(i==null)continue;const l=Math.abs(i-n);l<r&&(r=l,s=a)}if(s!=null)return s}if(typeof e.indexHint=="number"){const s=Math.max(0,Math.min(t.length-1,e.indexHint));return Number.isFinite(s)?s:null}return null}function Mh(e){return Array.from(e.querySelectorAll("[data-chat-entry-id]"))}function Q$(e,t){const n=Mh(e);for(const s of n)if(s.dataset.chatEntryId===t)return s;return null}function Z$(e,t){const n=Mh(e);if(n.length===0)return null;const s=Math.max(0,Math.min(n.length-1,t));return n[s]??null}function eD(e){const t=Mh(e);if(t.length===0)return null;const n=e.getBoundingClientRect().top;for(const s of t)if(s.getBoundingClientRect().bottom>n)return s;return t[t.length-1]??null}function tD(e){const{currentSessionId:t,messagesListRef:n,renderableMessages:s}=e,r=p.useRef(new Set),a=p.useRef(!1),i=p.useRef(0),l=p.useRef(null),c=p.useRef(null),u=p.useRef(!1);p.useEffect(()=>{const S=n.current;if(!S)return;const x=()=>{u.current=!0};return S.addEventListener("wheel",x,{passive:!0}),S.addEventListener("touchmove",x,{passive:!0}),S.addEventListener("pointerdown",x),()=>{S.removeEventListener("wheel",x),S.removeEventListener("touchmove",x),S.removeEventListener("pointerdown",x)}},[n]);const m=p.useMemo(()=>{const S=new Map;for(let x=0;x<s.length;x++){const T=G$(s[x]);T&&S.set(T,x)}return S},[s]),f=p.useCallback(()=>{const S=n.current;if(!S||s.length===0)return null;const x=eD(S);if(!x)return null;const T=x.dataset.chatEntryId;if(!T)return null;const j=S.getBoundingClientRect(),w=x.getBoundingClientRect(),M=m.get(T),_=typeof M=="number"?s[M]:void 0;return{v:1,anchorId:T,offsetPx:w.top-j.top,ts:Date.now(),indexHint:M,createdAt:_?US(_):void 0}},[m,n,s]),g=p.useCallback(async S=>{if(a.current)return;const x=f();if(!x)return;const T=c.current;T&&T.anchorId===x.anchorId&&Math.abs(T.offsetPx-x.offsetPx)<=X$||(await q$(S,x),c.current=x)},[f]),b=p.useCallback(S=>{if(!t||a.current)return;l.current&&clearTimeout(l.current);const x=t;l.current=setTimeout(()=>{g(x).catch(()=>{})},Y$)},[t,g]);return p.useEffect(()=>{const S=t;return()=>{S&&(l.current&&(clearTimeout(l.current),l.current=null),g(S).catch(()=>{}))}},[t,g]),p.useLayoutEffect(()=>{if(!t)return;const S=n.current;if(!S||s.length===0||r.current.has(t))return;let x=!1;return W$(t).then(T=>{if(x||!T){x||r.current.add(t);return}const j=m.get(T.anchorId),w=typeof j=="number"?j:J$(T,s);if(w==null){r.current.add(t);return}l.current&&(clearTimeout(l.current),l.current=null);const M=++i.current;a.current=!0,u.current=!1,S.style.overflowAnchor="none";const _=()=>i.current!==M||u.current;V$({scrollEl:S,getAnchorElement:()=>Q$(S,T.anchorId)??Z$(S,w),offsetPx:T.offsetPx,isCancelled:_}).finally(()=>{i.current===M&&(a.current=!1,r.current.add(t),S.style.overflowAnchor="",g(t).catch(()=>{}))})}),()=>{x=!0}},[t,m,s,s.length,n,g]),{handleScroll:b}}const Jg=2,Qg=6,nD=({currentSessionId:e,isThinking:t,messagesListRef:n,renderableMessages:s})=>{const[r,a]=p.useState(!1),[i,l]=p.useState(!1),c=p.useRef(!1),u=p.useRef(!0),{handleScroll:m}=tD({currentSessionId:e,messagesListRef:n,renderableMessages:s}),f=p.useCallback(T=>{const j=n.current;if(!j)return;if(s.length===0){a(!1),l(!1);return}const w=j.scrollHeight-j.scrollTop-j.clientHeight,M=j.scrollTop,_=150,C=150,L=w<_,A=M<C;a(!L),l(!A&&s.length>3),w>_*2?c.current=!0:L&&(c.current=!1),m(T)},[n,s.length,m]),g=p.useCallback(()=>{if(!n.current||s.length===0)return;let j=0,w=-1;const M=()=>{const _=n.current;if(!_)return;const C=Math.max(0,_.scrollHeight-_.clientHeight),L=Math.max(0,_.scrollHeight-_.scrollTop-_.clientHeight),A=_.scrollHeight!==w,B=L>Jg||A||j===0;B&&_.scrollTo({top:C,behavior:j===0?"smooth":"auto"}),w=_.scrollHeight,j+=1,j<Qg&&B&&requestAnimationFrame(M)};requestAnimationFrame(M)},[n,s.length]),b=p.useCallback(()=>{if(!n.current)return;let j=0;const w=()=>{const M=n.current;if(!M)return;const _=M.scrollTop>Jg||j===0;_&&M.scrollTo({top:0,behavior:"auto"}),j+=1,j<Qg&&_&&requestAnimationFrame(w)};requestAnimationFrame(w)},[n]),S=p.useCallback(()=>{c.current=!1},[]);p.useEffect(()=>{const T=j=>{var O,R;const M=(O=j.detail)==null?void 0:O.messageId;if(!M){console.error("No messageId provided for navigation");return}const _=s.findIndex(I=>"message"in I&&I.message?I.message.id===M:"id"in I?I.id===M:!1);if(_===-1){console.warn("Message not found for navigation:",M);return}const C=s[_],L=C&&"message"in C?C.message.id:C&&"id"in C?C.id:M,A=document.getElementById(`message-${L}`),B=Array.from(((R=n.current)==null?void 0:R.querySelectorAll("[data-chat-entry-id]"))||[]),N=A||B.find(I=>I.dataset.chatEntryId===L);if(!N){console.warn("Message element not found for navigation:",M);return}N.scrollIntoView({behavior:"smooth",block:"center"}),N.classList.add("highlight-message"),setTimeout(()=>{N.classList.remove("highlight-message")},2e3)};return window.addEventListener("navigate-to-message",T),()=>{window.removeEventListener("navigate-to-message",T)}},[n,s]);const x=p.useRef(t);return p.useEffect(()=>{!x.current&&t&&(S(),g()),x.current=t},[t,S,g]),p.useEffect(()=>It.subscribe(T=>{T.sessionId===e&&(c.current||T.content&&g())}),[e,g]),p.useEffect(()=>{!c.current&&s.length>0&&!u.current&&g(),u.current=!1},[s.length,g]),p.useEffect(()=>{if(!n.current){a(!1),l(!1);return}if(s.length===0){a(!1),l(!1);return}const j=()=>{const M=n.current;if(!M)return;const _=M.scrollHeight-M.scrollTop-M.clientHeight,C=M.scrollTop,L=150,A=150,B=_<L,N=C<A;a(!B),l(!N&&s.length>3)};j();let w=requestAnimationFrame(()=>{j(),w=requestAnimationFrame(j)});return()=>cancelAnimationFrame(w)},[n,s.length,e]),p.useEffect(()=>{u.current=!0,c.current=!1},[e]),{handleMessagesScroll:f,resetUserScroll:S,scrollToBottom:g,scrollToTop:b,showScrollToBottom:r,showScrollToTop:i}};function sD(e){return"type"in e&&e.type==="tool_session"}function rD(e){return"type"in e&&e.type==="compression_divider"}const Zg=e=>{const t=Date.parse(e||"");return Number.isFinite(t)?t:Number.MAX_SAFE_INTEGER},oD=e=>"type"in e?e.createdAt:e.message.createdAt,aD=e=>!("type"in e)&&e.message.role==="system";function iD(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_call"}function lD(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_result"}const ey=e=>(e??"").trim().toLowerCase()==="conclusion",cD=e=>{const t=(e??"").trim().toLowerCase();return t==="conclusion_with_options"||t==="exitplanmode"||t==="request_permissions"},dD=e=>{var t,n,s;return((n=(t=e.call.toolCalls)==null?void 0:t[0])==null?void 0:n.toolCallId)||((s=e.result)==null?void 0:s.toolCallId)||"tool-call-missing"},uD=(e,t)=>{var n;return e.call.id||e.callMessageId||e.resultMessageId||((n=e.result)==null?void 0:n.id)||`tool-message-missing-${t}`},mD=(e,t)=>`tool-session-${uD(e,t)}:${dD(e)}`;function hD(e){const t=[],n=new Map,s=new Set,r=(i,l)=>{const c=n.get(i)||[];c.push(l),n.set(i,c)},a=i=>{const l=n.get(i);if(!l||l.length===0)return;let c;for(;l.length>0&&!c;){const u=l.shift();u&&!u.result&&(c=u)}return l.length===0?n.delete(i):n.set(i,l),c};for(const i of e){if(iD(i)){const l=i.toolCalls||[];if(l.length===0){t.push(i);continue}l.forEach((c,u)=>{const m=c.toolCallId||`${i.id}-${u}`;if(ey(c.toolName)){s.add(m);return}if(cD(c.toolName)){s.add(m);const S={...i,id:`${i.id}:tool-call:${u}:${m}`,toolCalls:[{...c,toolCallId:m}]};t.push(S);return}const g={call:{...i,id:`${i.id}:tool-call:${u}:${m}`,toolCalls:[{...c,toolCallId:m}]},callMessageId:i.id};r(m,g);const b=t[t.length-1];Array.isArray(b)?b.push(g):t.push([g])});continue}if(lD(i)){const l=i.toolCallId;if(l&&s.has(l)){s.delete(l),t.push(i);continue}if(ey(i.toolName)){t.push(i);continue}const c=l?a(l):void 0;if(c)c.result=i,c.resultMessageId=i.id;else{const u=l||`orphan-tool-call:${i.id}`,f={call:{role:"assistant",type:"tool_call",id:`synthetic-tool-call:${i.id}`,createdAt:i.createdAt,toolCalls:[{toolCallId:u,toolName:(i.toolName||"").trim()||"tool",parameters:{},streamingOutput:""}],isCompressed:i.isCompressed,compressedEventId:i.compressedEventId},result:i,resultMessageId:i.id},g=t[t.length-1];Array.isArray(g)?g.push(f):t.push([f])}continue}t.push(i)}return t}const pD=(e,t)=>{var l;const{t:n}=Ie(),s=p.useMemo(()=>{var u;const c=t.find(m=>m.role==="system");return c||((u=e==null?void 0:e.config)!=null&&u.baseSystemPrompt?{id:`system-prompt-${e.id}`,role:"system",content:e.config.baseSystemPrompt,createdAt:new Date(e.createdAt).toISOString()}:null)},[e,t]),r=p.useCallback(c=>!1,[]),a=p.useCallback(c=>{if(rD(c))return{type:"compression_divider",id:c.id,createdAt:c.createdAt,label:c.label};if(sD(c))return{type:"tool_session",id:c.id,sessionId:c.sessionId,tools:c.tools,createdAt:c.createdAt};const u=c.message.role==="user"?"flex-end":"flex-start";let m=c.messageType;if(!m&&c.message.role==="assistant"&&"type"in c.message){const f="type"in c.message?c.message.type:void 0;(f==="text"||f==="plan"||f==="question"||f==="tool_call"||f==="tool_result")&&(m=f)}return{type:"message",message:c.message,align:u,messageType:m}},[]),i=p.useMemo(()=>{var x;const c=t.filter(T=>{const j=T.role;return!(j!=="user"&&j!=="assistant"&&j!=="system"&&j!=="tool"||r(T))}),u=hD(c),m=[];u.forEach((T,j)=>{var _,C;if(Array.isArray(T)){const L=T[0];m.push({type:"tool_session",id:L?mD(L,j):`tool-session-unknown-${j}`,sessionId:(e==null?void 0:e.id)||"default",tools:T,createdAt:((_=L==null?void 0:L.call)==null?void 0:_.createdAt)||((C=L==null?void 0:L.result)==null?void 0:C.createdAt)||new Date().toISOString()});return}const w=T;let M;if(w.role==="assistant"&&"type"in w){const L="type"in w?w.type:void 0;(L==="text"||L==="plan"||L==="question"||L==="tool_call"||L==="tool_result")&&(M=L)}m.push({message:w,messageType:M})}),!c.some(T=>T.role==="system")&&s&&m.unshift({message:s});const g=((x=e==null?void 0:e.config)==null?void 0:x.compressionEvents)||[],b=m.findIndex(T=>!aD(T)),S=b===-1?m.length:b;for(const T of g){const j={type:"compression_divider",id:`compression-divider-${T.id}`,createdAt:T.createdAt,label:n("chat.compression.timelineDetail",{count:T.messagesCompressed,defaultValue:"{{count}} messages archived"})},w=Zg(T.createdAt),M=m.findIndex((_,C)=>C>=S&&Zg(oD(_))>w);M===-1?m.push(j):m.splice(M,0,j)}return m},[(l=e==null?void 0:e.config)==null?void 0:l.compressionEvents,e==null?void 0:e.id,t,r,s,n]);return{systemPromptMessage:s,renderableMessages:i,convertRenderableEntry:a}},{useToken:fD}=Ge,{useBreakpoint:gD}=Nc,{Text:yD}=He,bD=e=>e.role==="user"?"You":e.role==="assistant"?"Assistant":e.role==="system"?"System":"Message",HS=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},xD=e=>e.map(({message:t,text:n},s)=>{const r=bD(t),a=HS(t.createdAt);return[`## ${s+1}. ${r} · ${a}`,"",n].join(`
|
|
244
|
+
`)}).join(`
|
|
245
|
+
|
|
246
|
+
---
|
|
247
|
+
|
|
248
|
+
`),vD=({sessionId:e,embedded:t=!1})=>{var Qn,Ys,ur,is,Ss;const{message:n}=sn.useApp(),{t:s}=Ie(),r=Tc(Fe=>Fe.isAdvanced),a=te(Fe=>e??Fe.currentSessionId),i=te(Er(a)),l=te(Fe=>Fe.deleteMessage),c=te(Fe=>Fe.loadChatHistory),u=te(Fe=>Fe.loadTaskList),m=te(Fe=>Fe.tokenUsages),f=te(Fe=>Fe.truncationOccurred),g=te(Fe=>Fe.segmentsRemoved),b=p.useMemo(()=>(i==null?void 0:i.messages)||[],[i]),S=p.useMemo(()=>!a||!i?a:i.kind==="child"&&(i.parentSessionId||i.rootSessionId)||a,[i,a]),x=te(Fe=>S?!!Fe.taskLists[S]:!1),T=te(dr(a)),j=p.useMemo(()=>!a||!i?!1:!!(x||i.kind==="child"||T),[i,x,a,T]),w=te(Fe=>{if(!a)return!1;const yt=Fi(a)(Fe);return Object.keys(yt).length>0?!0:Fe.chats.some(et=>et.kind==="child"&&et.parentSessionId===a)});p.useEffect(()=>{if(!a)return;const Fe=te.getState().chats.find(yt=>yt.id===a);Fe&&Array.isArray(Fe.messages)&&Fe.messages.length>0||c(a)},[a,c]);const M=(i==null?void 0:i.messageCount)??0,_=((Qn=i==null?void 0:i.messages)==null?void 0:Qn.length)??0;p.useEffect(()=>{if(!a)return;M-_>0&&c(a,{mode:"monotonic"})},[a,M,_,c]),p.useEffect(()=>{!S||x||j&&u(S).catch(Fe=>{console.warn(`[ChatView] Failed to load task list for ${S}:`,Fe)})},[S,x,j,u]);const C=T,L=p.useMemo(()=>{var Un;if(!b||b.length===0)return null;const Fe=new Map;let yt=0,et=0,mt=0;for(const Hn of b){if(!_x(Hn))continue;const Rn=((Un=Hn.result)==null?void 0:Un.result)??"",ls=Kc(Rn),yn=gx(Rn);if(!ls||!yn)continue;mt+=1,yt+=yn.added,et+=yn.removed;const An=Fe.get(ls.file_path);An?(An.added+=yn.added,An.removed+=yn.removed,An.diffChunks.push(ls.diff.unified),An.truncated=An.truncated||!!ls.diff.truncated):Fe.set(ls.file_path,{added:yn.added,removed:yn.removed,diffChunks:[ls.diff.unified],truncated:!!ls.diff.truncated})}if(Fe.size===0)return null;const _n=Array.from(Fe.entries()).map(([Hn,Rn])=>({filePath:Hn,added:Rn.added,removed:Rn.removed,unifiedDiff:Rn.diffChunks.join(`
|
|
249
|
+
|
|
250
|
+
`),truncated:Rn.truncated})).sort((Hn,Rn)=>Hn.filePath.localeCompare(Rn.filePath));return{totalAdded:yt,totalRemoved:et,files:_n,changedTools:mt}},[b]),A=C,B=p.useCallback(Fe=>{if(Fe.success)return null;switch(Fe.reason){case"session_not_found":case"message_not_found":case"backend_not_found":return s("chat.messageActions.deleteNotFound");case"session_running":return s("chat.messageActions.deleteConflict");default:return Fe.errorMessage||s("chat.messageActions.deleteFailed")}},[s]),N=p.useCallback(async(Fe,yt)=>{if(!a){const mt={success:!1,sessionId:"",messageId:Fe,reason:"session_not_found"};return(yt==null?void 0:yt.notify)!==!1&&n.error(B(mt)),mt}const et=await l(a,Fe);return!et.success&&(yt==null?void 0:yt.notify)!==!1&&n.error(B(et)),et},[a,l,n,B]),O=p.useCallback(async Fe=>{const yt=Array.from(new Set(Fe.map(_n=>_n.trim()).filter(Boolean)));if(yt.length===0)return;const mt=(await Promise.all(yt.map(_n=>N(_n,{notify:!1})))).filter(_n=>!_n.success);if(mt.length!==0){if(mt.length===1){n.error(B(mt[0]));return}n.error(s("chat.messageActions.deleteBatchFailed",{failed:mt.length,total:yt.length}))}},[N,n,B,s]),R=p.useRef(null),{token:I}=fD(),$=gD(),U=Lm(),[q,K]=p.useState(null),[P,W]=p.useState(!1),[se,V]=p.useState(new Set),ie=wt(Fe=>Fe.sidebar.collapsed),re=()=>t||$.xs||$.sm?"100%":$.md?"90%":$.lg?"85%":"1024px",fe=()=>{let Fe;return t?Fe=I.paddingSM:$.xs?Fe=I.paddingXS:$.sm?Fe=I.paddingSM:Fe=I.padding,!t&&ie&&!U?Fe+18:Fe};p.useEffect(()=>{K(null),W(!1),V(new Set)},[a]);const{systemPromptMessage:Se,renderableMessages:ke,convertRenderableEntry:Be}=pD(i,b),tt=b.length>0,ft=!!(q!=null&&q.content),Ht=!!Se,Oe=!!a&&(tt||ft),zt=t&&!$.xs?190:0,Ye=p.useMemo(()=>{if(!(q!=null&&q.content))return ke;const Fe={message:{id:q.id,role:"user",content:q.content,createdAt:q.createdAt},messageType:"text"};return[...ke,Fe]},[ke,q]),we=p.useMemo(()=>{const Fe=[];for(const yt of Ye){if(!("message"in yt))continue;const et=lv(yt.message).trim();et&&Fe.push({id:yt.message.id,message:yt.message,text:et})}return Fe},[Ye]),Ke=p.useMemo(()=>new Set(we.map(Fe=>Fe.id)),[we]);p.useEffect(()=>{V(Fe=>{let yt=!1;const et=new Set;for(const mt of Fe)Ke.has(mt)?et.add(mt):yt=!0;return yt?et:Fe})},[Ke]);const st=p.useMemo(()=>we.filter(Fe=>se.has(Fe.id)),[we,se]),Dt=we.length>0,F=p.useCallback(Fe=>{V(yt=>{const et=new Set(yt);return et.has(Fe)?et.delete(Fe):et.add(Fe),et})},[]),ce=p.useCallback(()=>{if(!Dt){n.warning("No exportable messages");return}W(!0)},[n,Dt]),ge=p.useCallback(()=>{W(!1),V(new Set)},[]),De=p.useCallback(()=>{if(P){ge();return}ce()},[ce,ge,P]),Le=p.useCallback(()=>{V(new Set(we.map(Fe=>Fe.id)))},[we]),me=p.useCallback(()=>{V(new Set)},[]),H=p.useCallback(async Fe=>{var mt;if(!a){n.warning("No active chat");return}if(st.length===0){n.warning("Please select at least one message");return}const yt=xD(st),et=await cv.exportMessageText({format:Fe,content:yt,sessionId:a,filenamePrefix:`chat-messages-${st.length}`});if(et.success){n.success(`Saved: ${et.filename}`);return}(mt=et.error)!=null&&mt.toLowerCase().includes("cancel")||n.error(et.error||"Export failed")},[n,a,st]);p.useEffect(()=>{if(typeof window>"u")return;const Fe=yt=>{var _n;const mt=((_n=yt.detail)==null?void 0:_n.sessionId)??null;!a||mt!==a||De()};return window.addEventListener(Ju,Fe),()=>{window.removeEventListener(Ju,Fe)}},[a,De]);const ye=a?m[a]:null,xe=(Ys=i==null?void 0:i.config)==null?void 0:Ys.tokenUsage,_e=ye||xe||null,Ue=a?f[a]:!1,Re=(ur=i==null?void 0:i.config)==null?void 0:ur.truncationOccurred,ut=Ue||Re||!1,ot=a?g[a]:0,gt=(is=i==null?void 0:i.config)==null?void 0:is.segmentsRemoved,_t=ot||gt||0,vt=p.useMemo(()=>{var yt;const Fe=(yt=i==null?void 0:i.config)==null?void 0:yt.compressionEvents;return!Fe||Fe.length===0?null:Fe.reduce((et,mt)=>{const _n=Date.parse(et.createdAt),Un=Date.parse(mt.createdAt);return Number.isFinite(_n)?Number.isFinite(Un)&&Un>_n?mt:et:mt})},[(Ss=i==null?void 0:i.config)==null?void 0:Ss.compressionEvents]),Bt=I.marginMD,{handleMessagesScroll:Kt,resetUserScroll:qe,scrollToBottom:rn,scrollToTop:cn,showScrollToBottom:on,showScrollToTop:ze}=nD({currentSessionId:a,isThinking:A,messagesListRef:R,renderableMessages:Ye}),Ar=()=>$.xs?16:32,as=!!Oe&&Dt&&(!t||P),En=vt?o.jsx(bt,{title:s("chat.compression.tooltip",{count:vt.messagesCompressed,time:HS(vt.createdAt),defaultValue:"Latest compression at {{time}}: {{count}} messages archived"}),children:o.jsx(Ne,{color:"gold",icon:o.jsx(_b,{}),style:{marginInlineEnd:0,whiteSpace:"nowrap"},children:s("chat.compression.archivedShort",{count:vt.messagesCompressed,defaultValue:"{{count}} archived"})})}):null,$s=_e&&_e.budgetLimit>0?o.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:I.marginXS},children:[o.jsx(x$,{usage:_e,showDetails:!0,size:"small"}),ut&&o.jsxs("span",{style:{fontSize:11,color:I.colorTextSecondary,whiteSpace:"nowrap"},children:["(",_t," truncated)"]}),En]}):En?o.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:I.marginXS},children:En}):null;return o.jsx(so,{role:"region","aria-label":s("chat.view.chatRegion","Chat conversation"),style:{flex:1,minHeight:0,height:"100%",background:I.colorBgContainer,position:"relative",overflow:"hidden"},children:o.jsxs(be,{vertical:!0,style:{flex:1,minHeight:0,height:"100%"},children:[a&&o.jsx(O$,{sessionId:a}),r&&a&&Oe&&o.jsx("div",{style:{paddingTop:I.paddingXS,paddingRight:fe(),paddingBottom:0,paddingLeft:fe(),maxWidth:re(),margin:"0 auto",width:"100%"},children:o.jsx(N$,{sessionId:a})}),a&&j&&o.jsx("div",{style:{paddingTop:fe(),paddingRight:fe(),paddingBottom:0,paddingLeft:fe(),maxWidth:re(),margin:"0 auto",width:"100%"},children:o.jsx(s$,{sessionId:a,initialCollapsed:!0})}),a&&w&&o.jsx("div",{style:{paddingTop:I.paddingXS,paddingRight:fe(),paddingBottom:0,paddingLeft:fe(),maxWidth:re(),margin:"0 auto",width:"100%"},children:o.jsx(E$,{parentSessionId:a})}),as&&o.jsx("div",{style:{paddingTop:I.paddingXS,paddingRight:fe()+zt,paddingBottom:0,paddingLeft:fe(),maxWidth:re(),margin:"0 auto",width:"100%"},children:P?o.jsxs(be,{align:"center",justify:"space-between",wrap:"wrap",gap:I.marginXS,children:[o.jsx(yD,{type:"secondary",children:s("chat.selectionToolbar.selectedCount",{selected:st.length,total:we.length})}),o.jsxs(he,{size:I.marginXS,wrap:!0,children:[o.jsx(ue,{size:"small",onClick:Le,children:s("chat.selectionToolbar.selectAll")}),o.jsx(ue,{size:"small",onClick:me,children:s("chat.selectionToolbar.clear")}),o.jsx(ue,{size:"small",icon:o.jsx(Wo,{}),onClick:()=>{H("markdown")},disabled:st.length===0,children:s("chat.selectionToolbar.exportMarkdown")}),o.jsx(ue,{size:"small",type:"primary",icon:o.jsx(Wo,{}),onClick:()=>{H("pdf")},disabled:st.length===0,children:s("chat.selectionToolbar.exportPdf")}),o.jsx(ue,{size:"small",icon:o.jsx(Ho,{}),onClick:De,children:s("chat.selectionToolbar.done")})]})]}):o.jsx(be,{justify:"flex-end",children:o.jsx(bt,{title:s("chat.selectionToolbar.selectMessages"),children:o.jsx(ue,{"aria-label":s("chat.selectionToolbar.selectMessages"),icon:o.jsx(kb,{}),size:"small",onClick:De})})})}),o.jsx(t$,{currentChat:i,currentSessionId:a,convertRenderableEntry:Be,handleDeleteMessage:N,handleDeleteToolMessages:O,handleMessagesScroll:Kt,hasSystemPrompt:Ht,messagesListRef:R,renderableMessages:Ye,rowGap:Bt,showMessagesView:!!Oe,screens:$,workflowDraftId:q==null?void 0:q.id,isThinking:A,padding:fe(),selectionMode:P,selectedMessageIds:se,selectableMessageIds:Ke,onToggleMessageSelection:F}),(ze||on)&&o.jsxs("div",{style:{position:"absolute",right:Ar(),bottom:$.xs?160:180,display:"flex",flexDirection:"column",gap:I.marginXS,zIndex:1e3},children:[ze&&o.jsx(ip,{type:"default",icon:o.jsx(Im,{}),style:{position:"relative",inset:"unset"},onClick:()=>{cn()}}),on&&o.jsx(ip,{type:"primary",icon:o.jsx(Gn,{}),style:{position:"relative",inset:"unset"},onClick:()=>{qe(),rn()}})]}),a&&o.jsx("div",{style:{paddingTop:I.paddingXS,paddingRight:fe(),paddingBottom:0,paddingLeft:fe(),maxWidth:re(),margin:"0 auto",width:"100%"},children:o.jsx(y$,{sessionId:a})}),o.jsx(_E,{sessionId:a,isCenteredLayout:!Oe,maxWidth:Oe?re():"100%",onWorkflowDraftChange:K,showMessagesView:!!Oe,sessionDiffSummary:L,contextUsageIndicator:$s})]})})},SD=5,wD=5,_D=5,kD=e=>{if(!e)return"";try{const t=Date.now()-new Date(e).getTime();if(t<0)return"";const n=Math.floor(t/1e3);if(n<60)return"just now";const s=Math.floor(n/60);if(s<60)return`${s}m ago`;const r=Math.floor(s/60);if(r<24)return`${r}h ago`;const a=Math.floor(r/24);return a<30?`${a}d ago`:new Date(e).toLocaleDateString()}catch{return""}},TD=(e,t)=>t?"is-running":e.lastRunStatus==="error"?"is-error":e.pinned?"is-pinned":"is-idle",pu=({chat:e,onOpen:t,textSecondary:n})=>{const s=te(dr(e.id)),r=e.config.workspacePath?e.config.workspacePath.split("/").pop()||e.config.workspacePath:null;return o.jsxs("button",{type:"button",className:"lotus-home-session-item",onClick:()=>t(e.id),children:[o.jsx("span",{className:`lotus-home-session-status ${TD(e,s)}`}),o.jsxs("span",{className:"lotus-home-session-content",children:[o.jsx("span",{className:"lotus-home-session-title",children:e.title}),o.jsxs("span",{className:"lotus-home-session-meta",style:{color:n},children:[o.jsx("span",{children:kD(e.updatedAt)}),r?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"lotus-home-session-meta-sep"}),o.jsxs("span",{children:[o.jsx(fc,{style:{marginRight:3}}),r]})]}):null,e.messageCount!=null?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"lotus-home-session-meta-sep"}),o.jsxs("span",{children:[o.jsx(gc,{style:{marginRight:3}}),e.messageCount]})]}):null]})]}),s?o.jsx(Ne,{color:"green",bordered:!1,style:{margin:0,fontSize:11},children:"Running"}):null,o.jsx(Vs,{className:"lotus-home-session-arrow"})]})},jD=({onOpenSession:e})=>{const{t}=Ie(),{token:n}=Ge.useToken(),s=te(u=>u.chats),r=p.useCallback(u=>dr(u)(te.getState()),[]),a=p.useMemo(()=>s.filter(u=>r(u.id)).slice(0,wD),[s,r]),i=p.useMemo(()=>s.filter(u=>u.pinned&&!r(u.id)).slice(0,_D),[s,r]),l=p.useMemo(()=>{const u=new Set(a.map(f=>f.id)),m=new Set(i.map(f=>f.id));return s.filter(f=>f.kind!=="child"&&!u.has(f.id)&&!m.has(f.id)).sort((f,g)=>{const b=f.updatedAt?new Date(f.updatedAt).getTime():f.createdAt;return(g.updatedAt?new Date(g.updatedAt).getTime():g.createdAt)-b}).slice(0,SD)},[s,a,i]),c=p.useCallback(u=>{e(u)},[e]);return o.jsx("div",{className:"lotus-home-dashboard",children:o.jsxs("div",{className:"lotus-home-dashboard-inner",children:[o.jsxs("div",{className:"lotus-home-header",children:[o.jsx("span",{className:"lotus-home-header-icon",style:{background:`${n.colorPrimary}15`,color:n.colorPrimary},children:o.jsx(y_,{})}),o.jsxs("div",{className:"lotus-home-header-text",children:[o.jsx("h2",{style:{color:n.colorText},children:t("home.title","Welcome to Bodhi")}),o.jsx("p",{style:{color:n.colorTextSecondary},children:t("home.subtitle","Here's an overview of your workspace.")})]})]}),o.jsx("div",{className:"lotus-home-launcher-shell","data-tour-id":"task-templates",children:o.jsx(Px,{embedded:!0,layoutMode:"staggered"})}),o.jsxs("div",{className:"lotus-home-secondary-sections",children:[a.length>0?o.jsxs("div",{className:"lotus-home-section",children:[o.jsxs("div",{className:"lotus-home-section-title",style:{color:n.colorTextSecondary},children:[o.jsx(Sb,{className:"lotus-home-section-icon",style:{color:"#52c41a"}}),o.jsx("span",{children:t("home.sections.running","Running Now")})]}),o.jsx("div",{className:"lotus-home-session-list",children:a.map(u=>o.jsx(pu,{chat:u,onOpen:c,textSecondary:n.colorTextTertiary},u.id))})]}):null,i.length>0?o.jsxs("div",{className:"lotus-home-section",children:[o.jsxs("div",{className:"lotus-home-section-title",style:{color:n.colorTextSecondary},children:[o.jsx(jm,{className:"lotus-home-section-icon",style:{color:"#faad14"}}),o.jsx("span",{children:t("home.sections.pinned","Pinned")})]}),o.jsx("div",{className:"lotus-home-session-list",children:i.map(u=>o.jsx(pu,{chat:u,onOpen:c,textSecondary:n.colorTextTertiary},u.id))})]}):null,l.length>0?o.jsxs("div",{className:"lotus-home-section",children:[o.jsxs("div",{className:"lotus-home-section-title",style:{color:n.colorTextSecondary},children:[o.jsx(As,{className:"lotus-home-section-icon"}),o.jsx("span",{children:t("home.sections.recent","Recent Sessions")})]}),o.jsx("div",{className:"lotus-home-session-list",children:l.map(u=>o.jsx(pu,{chat:u,onOpen:c,textSecondary:n.colorTextTertiary},u.id))})]}):null,s.length===0?o.jsx("div",{className:"lotus-home-empty-hint",style:{color:n.colorTextTertiary},children:t("home.empty","No sessions yet. Create one to get started!")}):null]})]})})},vr=(e,t,n)=>Math.max(t,Math.min(n,e)),Yl=(e,t)=>t==="horizontal"?e.clientWidth:e.clientHeight,Xl=(e,t,n)=>{const s=Math.max(0,Math.round(e)),r=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(n));return r+a>s?{minFirst:0,maxFirst:s,appliedMinFirst:0,appliedMinSecond:0}:{minFirst:r,maxFirst:s-a,appliedMinFirst:r,appliedMinSecond:a}},KS=({layout:e,first:t,second:n,sizesPx:s,defaultSplitRatio:r=.5,minFirstPx:a=0,minSecondPx:i=0,handleSizePx:l=6,disabled:c=!1,onResizeEnd:u,style:m,className:f})=>{const g=p.useRef(null),b=p.useRef(null),[S,x]=p.useState(null),[T,j]=p.useState(0),[w,M]=p.useState(null),_=p.useMemo(()=>{if(!s)return null;const V=Number(s[0]);return Number.isFinite(V)?V:null},[s]),C=p.useMemo(()=>{if(!s)return null;const V=Number(s[0]),ie=Number(s[1]);if(!Number.isFinite(V)||!Number.isFinite(ie))return null;const re=V+ie;return re<=0||ie<=0?null:vr(V/re,0,1)},[s]);p.useLayoutEffect(()=>{const V=g.current;V&&j(Yl(V,e))},[e]),p.useEffect(()=>{const V=g.current;if(!V)return;const ie=()=>{const re=Yl(V,e);j(fe=>fe===re?fe:re)};if(ie(),typeof ResizeObserver<"u"){const re=new ResizeObserver(ie);return re.observe(V),()=>re.disconnect()}return window.addEventListener("resize",ie),()=>window.removeEventListener("resize",ie)},[e]),p.useEffect(()=>{if(C!==null){M(C);return}M(V=>V??vr(r,.1,.9))},[r,C]);const L=p.useMemo(()=>Xl(T,a,i),[T,a,i]),A=vr(r,.1,.9),B=w??A,N=T>0?Math.round(T*B):null,O=S??(C!==null?N:null)??_??N??0,R=T>0?vr(O,L.minFirst,L.maxFirst):Math.max(0,Math.round(O)),I=p.useCallback(V=>{if(c)return;const ie=g.current;if(!ie)return;V.preventDefault(),V.stopPropagation();const re=e==="horizontal"?V.clientX:V.clientY,fe=Yl(ie,e),Se=Xl(fe,a,i),ke=vr(R||Math.round(fe*A),Se.minFirst,Se.maxFirst);b.current={pointerId:V.pointerId,startPos:re,startFirstPx:ke,containerSize:fe};try{V.currentTarget.setPointerCapture(V.pointerId)}catch{}},[c,R,A,e,a,i]),$=p.useCallback(V=>{const ie=b.current;if(!ie||V.pointerId!==ie.pointerId)return;V.preventDefault(),V.stopPropagation();const fe=(e==="horizontal"?V.clientX:V.clientY)-ie.startPos,Se=ie.containerSize,ke=Xl(Se,a,i),Be=vr(Math.round(ie.startFirstPx+fe),ke.minFirst,ke.maxFirst);x(Be)},[e,a,i]),U=p.useCallback(V=>{const ie=b.current;if(!ie||ie.pointerId!==V)return;const re=g.current,fe=re?Yl(re,e):ie.containerSize,Se=S??ie.startFirstPx,ke=Xl(fe,a,i),Be=vr(Se,ke.minFirst,ke.maxFirst),tt=Math.max(0,fe-Be);x(null),fe>0&&M(vr(Be/fe,0,1)),b.current=null,u==null||u([Be,tt])},[e,S,a,i,u]),q=p.useCallback(V=>{V.preventDefault(),V.stopPropagation(),U(V.pointerId)},[U]),K=p.useCallback(V=>{V.preventDefault(),V.stopPropagation(),U(V.pointerId)},[U]),P=e==="horizontal",W=c?"default":P?"col-resize":"row-resize",se=Math.max(0,Math.round(l));return o.jsxs("div",{ref:g,className:f,style:{display:"flex",flexDirection:P?"row":"column",height:"100%",minHeight:0,minWidth:0,width:"100%",position:"relative",...m},children:[o.jsx("div",{style:{flex:`0 0 ${R}px`,minWidth:P?L.appliedMinFirst:0,minHeight:P?0:L.appliedMinFirst,overflow:"hidden",display:"flex"},children:o.jsx("div",{style:{flex:1,minHeight:0,minWidth:0},children:t})}),o.jsx("div",{style:{flex:"1 1 auto",minWidth:P?L.appliedMinSecond:0,minHeight:P?0:L.appliedMinSecond,overflow:"hidden",display:"flex"},children:o.jsx("div",{style:{flex:1,minHeight:0,minWidth:0},children:n})}),se>0?o.jsx("div",{role:"separator","aria-orientation":P?"vertical":"horizontal",onPointerDown:I,onPointerMove:$,onPointerUp:q,onPointerCancel:K,style:{position:"absolute",top:P?0:`${R-se/2}px`,left:P?`${R-se/2}px`:0,width:P?`${se}px`:"100%",height:P?"100%":`${se}px`,cursor:W,touchAction:"none",background:"transparent",zIndex:5}}):null]})},{useToken:CD}=Ge,MD=4,PD=({leafId:e})=>{const{token:t}=CD(),{t:n}=Ie(),s=wt(N=>N.tree),r=wt(N=>N.leafSessionIds),a=wt(N=>N.activeLeafId),i=wt(N=>N.setActiveLeafId),l=wt(N=>N.splitLeaf),c=wt(N=>N.closeLeaf),u=wt(N=>N.setLeafSessionId),m=te(N=>N.selectSession),f=te(N=>N.addChat),g=te(N=>N.systemPrompts),b=te(N=>N.lastSelectedPromptId),S=r[e]??null,x=p.useMemo(()=>os(s).length,[s]),T=x<MD,j=Cb("(max-width: 768px)"),w=x>1,_=w||!!S,C=x>1,L=a===e,A=p.useCallback(N=>{u(e,N),i(e),m(N)},[e,m,i,u]),B=p.useCallback(async()=>{var I,$;const N=g.find(U=>U.id===b),O=(N==null?void 0:N.id)||(g.length>0?((I=g.find(U=>U.id==="general_assistant"))==null?void 0:I.id)||g[0].id:""),R=await f({title:n("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:O,baseSystemPrompt:(N==null?void 0:N.content)||(g.length>0?(($=g.find(U=>U.id==="general_assistant"))==null?void 0:$.content)||g[0].content:""),lastUsedEnhancedPrompt:null}});u(e,R),i(e)},[f,b,g,n,e,u,i]);return o.jsxs("div",{className:"chat-pane-shell",onMouseDownCapture:()=>{fs("pane focus (mouse)",{leafId:e,sessionId:S,prevActiveLeafId:a}),i(e),S&&m(S)},onFocusCapture:()=>{fs("pane focus (focus)",{leafId:e,sessionId:S,prevActiveLeafId:a}),i(e)},style:{height:"100%",minHeight:0,border:C?`1px solid ${L?t.colorPrimaryBorder:t.colorBorderSecondary}`:"none",borderRadius:C?t.borderRadiusLG:0,overflow:"hidden",background:t.colorBgContainer,position:"relative"},children:[!j&&o.jsx("div",{className:"chat-pane-actions",style:{background:t.colorBgElevated,border:`1px solid ${t.colorBorderSecondary}`,borderRadius:10,padding:"2px 4px"},children:o.jsxs(be,{gap:t.marginXS,children:[o.jsx(ue,{size:"small",type:"text",icon:o.jsx(b_,{}),disabled:!T,title:n("chat.multiPane.splitHorizontal"),"aria-label":n("chat.multiPane.splitHorizontal"),onClick:N=>{N.preventDefault(),N.stopPropagation(),fs("pane split request",{leafId:e,layout:"horizontal"}),l(e,"horizontal");const O=wt.getState(),R=O.leafSessionIds[O.activeLeafId]??null;R&&m(R)}}),o.jsx(ue,{size:"small",type:"text",icon:o.jsx(x_,{}),disabled:!T,title:n("chat.multiPane.splitVertical"),"aria-label":n("chat.multiPane.splitVertical"),onClick:N=>{N.preventDefault(),N.stopPropagation(),fs("pane split request",{leafId:e,layout:"vertical"}),l(e,"vertical");const O=wt.getState(),R=O.leafSessionIds[O.activeLeafId]??null;R&&m(R)}}),o.jsx(ue,{size:"small",type:"text",icon:o.jsx(kb,{}),disabled:!S,title:n("chat.multiPane.selectMessagesToExport"),"aria-label":n("chat.multiPane.selectMessagesToExport"),onClick:N=>{N.preventDefault(),N.stopPropagation(),S&&window.dispatchEvent(new CustomEvent(Ju,{detail:{sessionId:S}}))}}),o.jsx(ue,{size:"small",type:"text",danger:!0,icon:o.jsx(Ho,{}),disabled:!_,title:n("chat.multiPane.closePane"),"aria-label":n("chat.multiPane.closePane"),onClick:N=>{N.preventDefault(),N.stopPropagation(),fs("pane close request",{leafId:e}),w?c(e):u(e,null);const O=wt.getState(),R=O.leafSessionIds[O.activeLeafId]??null;m(R)}})]})}),S?o.jsx(Bi,{name:"ChatView",children:o.jsx(vD,{sessionId:S,embedded:!0})}):o.jsx(Bi,{name:"HomeDashboard",children:o.jsx(jD,{onOpenSession:A,onCreateSession:B})})]})},ED=({node:e})=>{const t=wt(s=>s.splitSizesPx[e.id]??null),n=wt(s=>s.setSplitSizesPx);return o.jsx(KS,{layout:e.layout,sizesPx:t,defaultSplitRatio:.5,minFirstPx:240,minSecondPx:240,style:{height:"100%",minHeight:0},onResizeEnd:s=>{n(e.id,s)},first:o.jsx(bm,{node:e.children[0]}),second:o.jsx(bm,{node:e.children[1]})})},bm=({node:e})=>e.type==="leaf"?o.jsx(PD,{leafId:e.id}):o.jsx(ED,{node:e}),ty=()=>{const e=wt(f=>f.tree),t=wt(f=>f.leafSessionIds),n=wt(f=>f.activeLeafId),s=wt(f=>f.setActiveLeafId),r=wt(f=>f.setLeafSessionId),a=wt(f=>f.clearSessionFromAllLeaves),i=te(f=>f.chats),l=te(f=>f.currentSessionId),c=p.useRef(!1),u=p.useMemo(()=>os(e),[e]),m=p.useMemo(()=>new Set(i.map(f=>f.id)),[i]);return p.useEffect(()=>{u.length!==0&&(u.includes(n)||s(u[0]))},[n,u,s]),p.useEffect(()=>{for(const[f,g]of Object.entries(t))g&&!m.has(g)&&r(f,null)},[m,t,r]),p.useEffect(()=>{if(!l||c.current)return;if(!Object.values(t).some(Boolean)){r(n,l),c.current=!0;return}c.current=!0},[n,l,t,r]),p.useEffect(()=>{const f=new Set(Object.values(t).filter(Boolean));for(const g of f)m.has(g)||a(g)},[m,a,t]),o.jsx("div",{style:{height:"100%",minHeight:0,padding:0},children:o.jsx(bm,{node:e})})},RD=[{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"]}],AD=(e,t)=>{const n=[e.title,e.id,e.kind||"root"];return e.pinned&&n.push("pinned","pin"),t&&n.push("running","processing"),e.config.workspacePath&&n.push(e.config.workspacePath),e.updatedAt&&n.push(e.updatedAt),n.filter(Boolean)},ID=(e,t,n)=>{const s=[];if(e.kind==="child"?s.push(t):s.push(n),e.config.workspacePath&&s.push(e.config.workspacePath),e.updatedAt)try{s.push(new Date(e.updatedAt).toLocaleString())}catch{s.push(e.updatedAt)}return s.join(" • ")},OD=(e,t)=>{const n=t.trim().toLowerCase();return n?e.filter(s=>[s.title,s.subtitle||"",...s.keywords].join(" ").toLowerCase().includes(n)):e},$D=e=>{if(!(e instanceof HTMLElement))return!1;const t=e.tagName.toLowerCase();return e.isContentEditable?!0:t==="input"||t==="textarea"||t==="select"},DD=()=>{const{t:e}=Ie(),{token:t}=Ge.useToken(),n=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{message:s}=sn.useApp(),r=te($=>$.chats),a=te($=>$.addChat),i=te($=>$.lastSelectedPromptId),l=te($=>$.systemPrompts),c=te($=>$.executionBySession),[u,m]=p.useState(!1),[f,g]=p.useState(""),[b,S]=p.useState(0),x=p.useRef(null),T=p.useRef(null),j=sr($=>$.open),w=ho($=>$.toggleTheme),M=ho($=>$.themeMode),_=wt($=>$.sidebar.collapsed),C=wt($=>$.setSidebarCollapsed),L=Tc($=>$.mode),A=Tc($=>$.toggleMode),B=p.useCallback(async()=>{var se,V;const $=l.find(ie=>ie.id===i),U=($==null?void 0:$.id)||(l.length>0?((se=l.find(ie=>ie.id==="general_assistant"))==null?void 0:se.id)||l[0].id:""),q=await a({title:e("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:U,baseSystemPrompt:($==null?void 0:$.content)||(l.length>0?((V=l.find(ie=>ie.id==="general_assistant"))==null?void 0:V.content)||l[0].content:""),lastUsedEnhancedPrompt:null}}),{activeLeafId:K,setLeafSessionId:P,setActiveLeafId:W}=wt.getState();P(K,q),W(K)},[a,i,l,e]),N=p.useMemo(()=>{const $=RD.filter(U=>!(L==="simple"&&wx.has(U.tabKey))).map(U=>({id:U.id,kind:"action",title:e(U.titleKey,U.fallbackTitle),subtitle:e(U.subtitleKey||"commandPalette.groups.settings",U.fallbackSubtitle||"System settings"),keywords:[U.tabKey,U.badge||"","settings","config",...U.keywords||[]],icon:o.jsx(Ki,{}),badge:U.badge,onSelect:()=>{j("chat",U.tabKey)}}));return[{id:"new-session",kind:"action",title:e("commandPalette.actions.newSession","Create New Session"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["new","create","session","chat","conversation"],icon:o.jsx(rr,{}),badge:e("commandPalette.badges.quickAction","Action"),onSelect:async()=>{await B()}},{id:"toggle-theme",kind:"action",title:M==="dark"?e("commandPalette.actions.switchToLight","Switch to Light Mode"):e("commandPalette.actions.switchToDark","Switch to Dark Mode"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["theme","dark","light","mode","appearance","toggle","color"],icon:o.jsx(v_,{}),badge:M==="dark"?"☀️":"🌙",onSelect:()=>{w()}},{id:"toggle-sidebar",kind:"action",title:_?e("commandPalette.actions.showSidebar","Show Sidebar"):e("commandPalette.actions.hideSidebar","Hide Sidebar"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["sidebar","toggle","hide","show","panel","menu"],icon:_?o.jsx(Tb,{}):o.jsx(pb,{}),badge:"Layout",onSelect:()=>{C(!_)}},{id:"split-pane",kind:"action",title:e("commandPalette.actions.splitPane","Split Pane"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["split","pane","multi","dual","side","layout"],icon:o.jsx(S_,{}),badge:"Layout",onSelect:()=>{const{tree:U,activeLeafId:q,splitLeaf:K}=wt.getState();os(U).length<4&&K(q,"vertical")}},...$,{id:"toggle-experience-mode",kind:"action",title:L==="simple"?e("commandPalette.actions.switchToAdvanced","Switch to Advanced Mode"):e("commandPalette.actions.switchToSimple","Switch to Simple Mode"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["mode","simple","advanced","beginner","expert","experience","complexity"],icon:o.jsx(yb,{}),badge:L==="simple"?"Simple":"Advanced",onSelect:()=>{A()}}]},[B,j,w,M,_,C,L,A,e]),O=p.useMemo(()=>r.map($=>{const U=dr($.id)({executionBySession:c});return{id:`session-${$.id}`,kind:"session",title:$.title,subtitle:ID($,e("commandPalette.badges.childSession","Child session"),e("commandPalette.badges.rootSession","Session")),keywords:AD($,U),icon:o.jsx(gc,{}),badge:$.pinned?e("commandPalette.badges.pinned","Pinned"):U?e("commandPalette.badges.running","Running"):$.kind==="child"?e("commandPalette.badges.child","Child"):void 0,onSelect:()=>{qc($.id)}}}),[r,c,e]),R=p.useMemo(()=>[...N,...O],[N,O]),I=p.useMemo(()=>OD(R,f).slice(0,40),[R,f]);return p.useEffect(()=>{S($=>I.length===0?0:Math.min($,I.length-1))},[I.length]),p.useEffect(()=>{if(!u)return;const $=window.setTimeout(()=>{var U,q;(U=x.current)==null||U.focus(),(q=x.current)==null||q.select()},0);return()=>window.clearTimeout($)},[u]),p.useEffect(()=>{if(typeof window>"u")return;const $=U=>{if((U.metaKey||U.ctrlKey)&&U.key.toLowerCase()==="k"){U.preventDefault(),m(K=>!K);return}if(u){if(U.key==="Escape"){U.preventDefault(),m(!1);return}if(!($D(U.target)&&U.key!=="ArrowUp"&&U.key!=="ArrowDown"&&U.key!=="Enter")){if(U.key==="ArrowDown"){U.preventDefault(),S(K=>I.length===0?0:(K+1)%I.length);return}if(U.key==="ArrowUp"){U.preventDefault(),S(K=>I.length===0?0:K===0?I.length-1:K-1);return}if(U.key==="Enter"){const K=I[b];if(!K)return;U.preventDefault(),(async()=>{try{await K.onSelect(),m(!1),g("")}catch(P){console.error("[CommandPalette] action failed",P),s.error(P instanceof Error?P.message:e("commandPalette.errors.actionFailed","Command failed"))}})()}}}};return window.addEventListener("keydown",$),()=>window.removeEventListener("keydown",$)},[I,s,u,b,e]),p.useEffect(()=>{u||(g(""),S(0))},[u]),p.useEffect(()=>{const $=T.current;if(!$)return;const U=$.querySelector(`[data-command-index="${b}"]`);U==null||U.scrollIntoView({block:"nearest"})},[b]),o.jsx(Xn,{open:u,onCancel:()=>m(!1),footer:null,centered:!0,width:680,destroyOnClose:!0,className:"lotus-command-palette-modal",title:null,closable:!1,styles:{content:{padding:12,borderRadius:t.borderRadiusLG,overflow:"hidden",background:t.colorBgElevated,backdropFilter:n?"none":"blur(18px)",WebkitBackdropFilter:n?"none":"blur(18px)"},body:{padding:0},mask:{backdropFilter:n?"none":"blur(6px)",WebkitBackdropFilter:n?"none":"blur(6px)"}},children:o.jsxs("div",{className:"lotus-command-palette-shell",children:[o.jsxs("div",{className:"lotus-command-palette-search",children:[o.jsx($i,{style:{color:t.colorTextTertiary,fontSize:16}}),o.jsx(Qe,{ref:x,value:f,onChange:$=>g($.target.value),variant:"borderless",placeholder:e("commandPalette.searchPlaceholder","Search sessions, settings, and actions"),"aria-label":e("commandPalette.searchPlaceholder","Search sessions, settings, and actions"),suffix:o.jsx(He.Text,{type:"secondary",style:{fontSize:12},children:"⌘K"})})]}),o.jsxs("div",{className:"lotus-command-palette-hint",children:[o.jsx(As,{}),o.jsx("span",{children:e("commandPalette.navigationHint","Use ↑↓ to navigate, Enter to open, and Esc to close.")})]}),o.jsx("div",{ref:T,className:"lotus-command-palette-list",role:"listbox",children:I.length===0?o.jsxs("div",{className:"lotus-command-palette-empty",children:[o.jsx(w_,{}),o.jsx("span",{children:e("commandPalette.empty","No matching commands")})]}):I.map(($,U)=>{const q=U===b;return o.jsxs("button",{type:"button",className:`lotus-command-palette-item ${q?"is-selected":""}`,"data-command-index":U,onMouseEnter:()=>S(U),onClick:()=>{(async()=>{try{await $.onSelect(),m(!1),g("")}catch(K){console.error("[CommandPalette] action failed",K),s.error(K instanceof Error?K.message:e("commandPalette.errors.actionFailed","Command failed"))}})()},children:[o.jsx("span",{className:"lotus-command-palette-item-icon",children:$.icon}),o.jsxs("span",{className:"lotus-command-palette-item-content",children:[o.jsxs("span",{className:"lotus-command-palette-item-title-row",children:[o.jsx("span",{className:"lotus-command-palette-item-title",children:$.title}),$.badge?o.jsx(Ne,{bordered:!1,children:$.badge}):null]}),$.subtitle?o.jsx("span",{className:"lotus-command-palette-item-subtitle",children:$.subtitle}):null]})]},$.id)})})]})})},ny="bodhi_open_provider_on_entry",LD=({themeMode:e,onThemeModeChange:t,locale:n,onLocaleChange:s})=>{const r=sr(R=>R.isOpen),a=sr(R=>R.close),{t:i}=Ie(),{token:l}=Ge.useToken(),c=Uc(),u=p.useMemo(()=>ox()==="macos",[]),m=Mt(R=>R.loadProviderConfig);p.useEffect(()=>{m()},[m]),p.useEffect(()=>{localStorage.getItem(ny)==="true"&&(localStorage.removeItem(ny),sr.getState().open("chat","provider"))},[]),EM(),yM(),p.useEffect(()=>{jf.clear(),Cf()},[e]),p.useEffect(()=>{jf.clear(),Cf()},[c]);const f=wt(R=>R.sidebar.collapsed),g=wt(R=>R.sidebar.widthPx),b=wt(R=>R.sidebar.minWidthPx),S=wt(R=>R.sidebar.maxWidthPx),x=wt(R=>R.setSidebarCollapsed),T=wt(R=>R.setSidebarWidthPx),j=18,w=0,_=!r&&f&&u?44:w,C=0,L=88,A=10,B="none",N=Lm();return o.jsxs(o.Fragment,{children:[o.jsx("a",{href:"#lotus-main-content",className:"lotus-skip-link",style:{position:"absolute",top:-9999,left:-9999,zIndex:1e4,padding:"8px 16px",background:"var(--lotus-main-surface, #fff)",color:"var(--ant-color-primary, #0d9488)",borderRadius:8,fontWeight:600,textDecoration:"none"},onFocus:R=>{R.currentTarget.style.top="8px",R.currentTarget.style.left="8px"},onBlur:R=>{R.currentTarget.style.top="-9999px",R.currentTarget.style.left="-9999px"},children:i("app.skipToContent","Skip to main content")}),o.jsx(DD,{}),o.jsx(BT,{disabled:r}),o.jsx(so,{style:{minHeight:"100vh",height:"100vh",overflow:"hidden",background:"transparent",display:"flex",flexDirection:"row",position:"relative"},children:o.jsxs("div",{style:{display:"flex",flex:1,minHeight:0,height:"100%",width:"100%",boxSizing:"border-box",paddingTop:_,paddingLeft:w,paddingRight:w,paddingBottom:w,background:"transparent"},children:[r?o.jsx(so,{className:"lotus-shell-panel lotus-settings-panel lotus-page-enter",style:{flex:1,display:"flex",flexDirection:"column",background:"var(--lotus-main-surface)",minHeight:0,borderRadius:`${j}px 0 0 ${j}px`,border:B,overflow:"hidden"},children:o.jsx(Bi,{name:"SystemSettings",children:o.jsx(pM,{themeMode:e,onThemeModeChange:t,locale:n,onLocaleChange:s,onBack:a})})}):o.jsx(o.Fragment,{children:N?o.jsxs(o.Fragment,{children:[o.jsx(wb,{placement:"left",closable:!1,onClose:()=>x(!0),open:!f,width:"min(86vw, 360px)",styles:{body:{padding:0,background:"var(--lotus-sidebar-bg)"}},children:o.jsx($p,{})}),o.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{flex:1,height:"100%",minHeight:0,borderRadius:`${j}px`,border:B,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:o.jsx(so,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:o.jsx(ty,{})})})]}):o.jsx(KS,{layout:"horizontal",style:{flex:1,minHeight:0,height:"100%",background:"transparent"},sizesPx:[f?C:g,0],minFirstPx:f?C:b,minSecondPx:320,disabled:f,handleSizePx:f?0:2,onResizeEnd:([R])=>{if(f)return;const I=Math.max(b,Math.min(S,R));T(I)},first:o.jsx("div",{className:"lotus-shell-panel lotus-shell-sidebar",style:{height:"100%",minHeight:0,borderRadius:`${j}px 0 0 ${j}px`,border:B,overflow:"hidden",background:"var(--lotus-sidebar-bg)"},children:o.jsx($p,{})}),second:o.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{height:"100%",minHeight:0,borderRadius:`0 ${j}px ${j}px 0`,border:B,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:o.jsx(so,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:o.jsx(ty,{})})})})}),!r&&f?o.jsx(ue,{"data-testid":"show-sidebar",type:"text",size:"small",icon:o.jsx(Tb,{}),onClick:()=>x(!1),title:i("layout.showSidebar"),"aria-label":i("layout.showSidebar"),className:"lotus-toolbar-icon lotus-floating-sidebar-toggle",style:{position:"absolute",top:N?8:A,left:N?8:L,zIndex:40,width:36,height:36,borderRadius:12,border:`1px solid ${l.colorBorderSecondary}`,background:l.colorBgElevated,boxShadow:l.boxShadowSecondary}}):null]})})]})},FD="bodhi_open_provider_on_entry",{Title:sy,Paragraph:ry}=He,ND=()=>{const{t:e}=Ie(),[t,n]=p.useState(!1),[s,r]=p.useState(null),[a,i]=p.useState(!1),l=async c=>{try{r(null),i(!0),await Is.getInstance().markSetupComplete(),c&&localStorage.setItem(FD,"true"),n(!0)}catch(u){console.error("Failed to complete setup:",u),r(e("setup.error.completeFailed"))}finally{i(!1)}};return t?o.jsxs("div",{"data-testid":"setup-complete",className:"setup-complete",children:[o.jsx(sy,{level:2,children:e("setup.complete.title")}),o.jsx(ry,{children:e("setup.complete.restartMessage")}),o.jsx(ue,{"data-testid":"setup-restart",onClick:()=>window.location.reload(),children:e("setup.complete.restartMessage")})]}):o.jsx("div",{className:"setup-page",children:o.jsxs(Ce,{className:"setup-page__card",children:[o.jsxs("div",{className:"setup-page__hero",children:[o.jsx("div",{className:"setup-page__hero-icon",children:o.jsx(lp,{})}),o.jsx(sy,{level:2,style:{marginTop:0},children:e("setup.welcome.heading")}),o.jsx(ry,{type:"secondary",children:e("setup.welcome.description")})]}),o.jsx(Ut,{message:e("setup.welcome.providerHint"),type:"info",showIcon:!0,style:{marginBottom:16}}),o.jsx(Ut,{message:e("setup.welcome.proxyHint"),type:"info",showIcon:!0,style:{marginBottom:24}}),s?o.jsx(Ut,{message:s,type:"error",showIcon:!0,style:{marginBottom:16}}):null,o.jsxs("div",{className:"setup-page__actions",children:[o.jsx(ue,{"data-testid":"setup-configure-provider",icon:o.jsx(Ki,{}),onClick:()=>void l(!0),loading:a,children:e("setup.button.configureProvider")}),o.jsx(ue,{"data-testid":"setup-get-started",type:"primary",icon:o.jsx(lp,{}),onClick:()=>void l(!1),loading:a,children:e("setup.button.getStarted")})]})]})})},{Title:zD,Text:oy}=He,BD=({onVerified:e,verifyPassword:t})=>{const{t:n}=Ie(),[s,r]=p.useState(""),[a,i]=p.useState(null),[l,c]=p.useState(!1),u=async()=>{const m=s.trim();if(!m){i(n("app.passwordGate.validation.required","请输入访问密码"));return}c(!0),i(null);try{await t(m),await e(),r("")}catch(f){const g=f instanceof Error?f.message:n("app.passwordGate.validation.verifyFailed","密码验证失败");i(g)}finally{c(!1)}};return o.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:o.jsx(Ce,{style:{width:"100%",maxWidth:480},children:o.jsxs(he,{direction:"vertical",size:20,style:{width:"100%"},children:[o.jsxs("div",{children:[o.jsx(zD,{level:3,style:{marginBottom:8},children:n("app.passwordGate.title","请输入访问密码")}),o.jsx(oy,{type:"secondary",children:n("app.passwordGate.description","当前访问需要先通过密码验证,验证成功后才会进入应用。")})]}),a?o.jsx(Ut,{type:"error",showIcon:!0,message:a}):null,o.jsxs(he,{direction:"vertical",size:8,style:{width:"100%"},children:[o.jsx(oy,{strong:!0,children:n("app.passwordGate.passwordLabel","访问密码")}),o.jsx(Qe.Password,{value:s,autoFocus:!0,autoComplete:"current-password",onChange:m=>r(m.target.value),onPressEnter:()=>void u(),placeholder:n("app.passwordGate.passwordPlaceholder","请输入访问密码")})]}),o.jsx(ue,{type:"primary",block:!0,loading:l,onClick:()=>void u(),children:n("app.passwordGate.submit","验证并进入")})]})})})};var Ra={},fu={exports:{}},ay;function Xt(){return ay||(ay=1,function(e){function t(n){return n&&n.__esModule?n:{default:n}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}(fu)),fu.exports}var Aa={},iy;function WD(){if(iy)return Aa;iy=1,Object.defineProperty(Aa,"__esModule",{value:!0}),Aa.default=void 0;var e={items_per_page:"/ page",jump_to:"Go to",jump_to_confirm:"confirm",page:"Page",prev_page:"Previous Page",next_page:"Next Page",prev_5:"Previous 5 Pages",next_5:"Next 5 Pages",prev_3:"Previous 3 Pages",next_3:"Next 3 Pages",page_size:"Page Size"};return Aa.default=e,Aa}var Ia={},Oa={},$a={},gu={exports:{}},yu={exports:{}},bu={exports:{}},xu={exports:{}},ly;function qD(){return ly||(ly=1,function(e){var t=mb().default;function n(s,r){if(t(s)!="object"||!s)return s;var a=s[Symbol.toPrimitive];if(a!==void 0){var i=a.call(s,r||"default");if(t(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(s)}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports}(xu)),xu.exports}var cy;function UD(){return cy||(cy=1,function(e){var t=mb().default,n=qD();function s(r){var a=n(r,"string");return t(a)=="symbol"?a:a+""}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}(bu)),bu.exports}var dy;function HD(){return dy||(dy=1,function(e){var t=UD();function n(s,r,a){return(r=t(r))in s?Object.defineProperty(s,r,{value:a,enumerable:!0,configurable:!0,writable:!0}):s[r]=a,s}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports}(yu)),yu.exports}var uy;function Qo(){return uy||(uy=1,function(e){var t=HD();function n(r,a){var i=Object.keys(r);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(r);a&&(l=l.filter(function(c){return Object.getOwnPropertyDescriptor(r,c).enumerable})),i.push.apply(i,l)}return i}function s(r){for(var a=1;a<arguments.length;a++){var i=arguments[a]!=null?arguments[a]:{};a%2?n(Object(i),!0).forEach(function(l){t(r,l,i[l])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(i)):n(Object(i)).forEach(function(l){Object.defineProperty(r,l,Object.getOwnPropertyDescriptor(i,l))})}return r}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}(gu)),gu.exports}var Da={},my;function Zo(){return my||(my=1,Object.defineProperty(Da,"__esModule",{value:!0}),Da.commonLocale=void 0,Da.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0}),Da}var hy;function KD(){if(hy)return $a;hy=1;var e=Xt().default;Object.defineProperty($a,"__esModule",{value:!0}),$a.default=void 0;var t=e(Qo()),n=Zo(),s=(0,t.default)((0,t.default)({},n.commonLocale),{},{locale:"en_US",today:"Today",now:"Now",backToToday:"Back to today",ok:"OK",clear:"Clear",week:"Week",month:"Month",year:"Year",timeSelect:"select time",dateSelect:"select date",weekSelect:"Choose a week",monthSelect:"Choose a month",yearSelect:"Choose a year",decadeSelect:"Choose a decade",dateFormat:"M/D/YYYY",dateTimeFormat:"M/D/YYYY HH:mm:ss",previousMonth:"Previous month (PageUp)",nextMonth:"Next month (PageDown)",previousYear:"Last year (Control + left)",nextYear:"Next year (Control + right)",previousDecade:"Last decade",nextDecade:"Next decade",previousCentury:"Last century",nextCentury:"Next century"});return $a.default=s,$a}var La={},py;function VS(){if(py)return La;py=1,Object.defineProperty(La,"__esModule",{value:!0}),La.default=void 0;const e={placeholder:"Select time",rangePlaceholder:["Start time","End time"]};return La.default=e,La}var fy;function YS(){if(fy)return Oa;fy=1;var e=Xt().default;Object.defineProperty(Oa,"__esModule",{value:!0}),Oa.default=void 0;var t=e(KD()),n=e(VS());const s={lang:Object.assign({placeholder:"Select date",yearPlaceholder:"Select year",quarterPlaceholder:"Select quarter",monthPlaceholder:"Select month",weekPlaceholder:"Select week",rangePlaceholder:["Start date","End date"],rangeYearPlaceholder:["Start year","End year"],rangeQuarterPlaceholder:["Start quarter","End quarter"],rangeMonthPlaceholder:["Start month","End month"],rangeWeekPlaceholder:["Start week","End week"]},t.default),timePickerLocale:Object.assign({},n.default)};return Oa.default=s,Oa}var gy;function VD(){if(gy)return Ia;gy=1;var e=Xt().default;Object.defineProperty(Ia,"__esModule",{value:!0}),Ia.default=void 0;var t=e(YS());return Ia.default=t.default,Ia}var yy;function YD(){if(yy)return Ra;yy=1;var e=Xt().default;Object.defineProperty(Ra,"__esModule",{value:!0}),Ra.default=void 0;var t=e(WD()),n=e(VD()),s=e(YS()),r=e(VS());const a="${label} is not a valid ${type}",i={locale:"en",Pagination:t.default,DatePicker:s.default,TimePicker:r.default,Calendar:n.default,global:{placeholder:"Please select"},Table:{filterTitle:"Filter menu",filterConfirm:"OK",filterReset:"Reset",filterEmptyText:"No filters",filterCheckAll:"Select all items",filterSearchPlaceholder:"Search in filters",emptyText:"No data",selectAll:"Select current page",selectInvert:"Invert current page",selectNone:"Clear all data",selectionAll:"Select all data",sortTitle:"Sort",expand:"Expand row",collapse:"Collapse row",triggerDesc:"Click to sort descending",triggerAsc:"Click to sort ascending",cancelSort:"Click to cancel sorting"},Tour:{Next:"Next",Previous:"Previous",Finish:"Finish"},Modal:{okText:"OK",cancelText:"Cancel",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Cancel"},Transfer:{titles:["",""],searchPlaceholder:"Search here",itemUnit:"item",itemsUnit:"items",remove:"Remove",selectCurrent:"Select current page",removeCurrent:"Remove current page",selectAll:"Select all data",deselectAll:"Deselect all data",removeAll:"Remove all data",selectInvert:"Invert current page"},Upload:{uploading:"Uploading...",removeFile:"Remove file",uploadError:"Upload error",previewFile:"Preview file",downloadFile:"Download file"},Empty:{description:"No data"},Icon:{icon:"icon"},Text:{edit:"Edit",copy:"Copy",copied:"Copied",expand:"Expand",collapse:"Collapse"},Form:{optional:"(optional)",defaultValidateMessages:{default:"Field validation error for ${label}",required:"Please enter ${label}",enum:"${label} must be one of [${enum}]",whitespace:"${label} cannot be a blank character",date:{format:"${label} date format is invalid",parse:"${label} cannot be converted to a date",invalid:"${label} is an invalid date"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"${label} must be ${len} characters",min:"${label} must be at least ${min} characters",max:"${label} must be up to ${max} characters",range:"${label} must be between ${min}-${max} characters"},number:{len:"${label} must be equal to ${len}",min:"${label} must be minimum ${min}",max:"${label} must be maximum ${max}",range:"${label} must be between ${min}-${max}"},array:{len:"Must be ${len} ${label}",min:"At least ${min} ${label}",max:"At most ${max} ${label}",range:"The amount of ${label} must be between ${min}-${max}"},pattern:{mismatch:"${label} does not match the pattern ${pattern}"}}},Image:{preview:"Preview"},QRCode:{expired:"QR code expired",refresh:"Refresh",scanned:"Scanned"},ColorPicker:{presetEmpty:"Empty",transparent:"Transparent",singleColor:"Single",gradientColor:"Gradient"}};return Ra.default=i,Ra}var vu,by;function XD(){return by||(by=1,vu=YD()),vu}var GD=XD();const JD=fo(GD);var Fa={},Na={},xy;function QD(){if(xy)return Na;xy=1,Object.defineProperty(Na,"__esModule",{value:!0}),Na.default=void 0;var e={items_per_page:"/ page",jump_to:"Aller à",jump_to_confirm:"confirmer",page:"Page",prev_page:"Page précédente",next_page:"Page suivante",prev_5:"5 Pages précédentes",next_5:"5 Pages suivantes",prev_3:"3 Pages précédentes",next_3:"3 Pages suivantes",page_size:"taille de la page"};return Na.default=e,Na}var za={},Ba={},Wa={},vy;function ZD(){if(vy)return Wa;vy=1;var e=Xt().default;Object.defineProperty(Wa,"__esModule",{value:!0}),Wa.default=void 0;var t=e(Qo()),n=Zo(),s=(0,t.default)((0,t.default)({},n.commonLocale),{},{locale:"fr_FR",today:"Aujourd'hui",now:"Maintenant",backToToday:"Aujourd'hui",ok:"OK",clear:"Rétablir",week:"Semaine",month:"Mois",year:"Année",timeSelect:"Sélectionner l'heure",dateSelect:"Sélectionner la date",monthSelect:"Choisissez un mois",yearSelect:"Choisissez une année",decadeSelect:"Choisissez une décennie",dateFormat:"DD/MM/YYYY",dayFormat:"DD",dateTimeFormat:"DD/MM/YYYY HH:mm:ss",previousMonth:"Mois précédent (PageUp)",nextMonth:"Mois suivant (PageDown)",previousYear:"Année précédente (Ctrl + gauche)",nextYear:"Année prochaine (Ctrl + droite)",previousDecade:"Décennie précédente",nextDecade:"Décennie suivante",previousCentury:"Siècle précédent",nextCentury:"Siècle suivant"});return Wa.default=s,Wa}var qa={},Sy;function XS(){if(Sy)return qa;Sy=1,Object.defineProperty(qa,"__esModule",{value:!0}),qa.default=void 0;const e={placeholder:"Sélectionner l'heure",rangePlaceholder:["Heure de début","Heure de fin"]};return qa.default=e,qa}var wy;function GS(){if(wy)return Ba;wy=1;var e=Xt().default;Object.defineProperty(Ba,"__esModule",{value:!0}),Ba.default=void 0;var t=e(ZD()),n=e(XS());const s={lang:Object.assign({placeholder:"Sélectionner une date",yearPlaceholder:"Sélectionner une année",quarterPlaceholder:"Sélectionner un trimestre",monthPlaceholder:"Sélectionner un mois",weekPlaceholder:"Sélectionner une semaine",rangePlaceholder:["Date de début","Date de fin"],rangeYearPlaceholder:["Année de début","Année de fin"],rangeMonthPlaceholder:["Mois de début","Mois de fin"],rangeWeekPlaceholder:["Semaine de début","Semaine de fin"]},t.default),timePickerLocale:Object.assign({},n.default)};return Ba.default=s,Ba}var _y;function eL(){if(_y)return za;_y=1;var e=Xt().default;Object.defineProperty(za,"__esModule",{value:!0}),za.default=void 0;var t=e(GS());return za.default=t.default,za}var ky;function tL(){if(ky)return Fa;ky=1;var e=Xt().default;Object.defineProperty(Fa,"__esModule",{value:!0}),Fa.default=void 0;var t=e(QD()),n=e(eL()),s=e(GS()),r=e(XS());const a="La valeur du champ ${label} n'est pas valide pour le type ${type}",i={locale:"fr",Pagination:t.default,DatePicker:s.default,TimePicker:r.default,Calendar:n.default,Table:{filterTitle:"Filtrer",filterConfirm:"OK",filterReset:"Réinitialiser",filterEmptyText:"Aucun filtre",filterCheckAll:"Tout sélectionner",filterSearchPlaceholder:"Chercher dans les filtres",emptyText:"Aucune donnée",selectAll:"Sélectionner la page actuelle",selectInvert:"Inverser la sélection de la page actuelle",selectNone:"Désélectionner toutes les données",selectionAll:"Sélectionner toutes les données",sortTitle:"Trier",expand:"Développer la ligne",collapse:"Réduire la ligne",triggerDesc:"Trier par ordre décroissant",triggerAsc:"Trier par ordre croissant",cancelSort:"Annuler le tri"},Tour:{Next:"Étape suivante",Previous:"Étape précédente",Finish:"Fin de la visite guidée"},Modal:{okText:"OK",cancelText:"Annuler",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Annuler"},Transfer:{titles:["",""],searchPlaceholder:"Rechercher",itemUnit:"élément",itemsUnit:"éléments",remove:"Désélectionner",selectCurrent:"Sélectionner la page actuelle",removeCurrent:"Désélectionner la page actuelle",selectAll:"Sélectionner toutes les données",removeAll:"Désélectionner toutes les données",selectInvert:"Inverser la sélection de la page actuelle"},Upload:{uploading:"Téléchargement...",removeFile:"Effacer le fichier",uploadError:"Erreur de téléchargement",previewFile:"Fichier de prévisualisation",downloadFile:"Télécharger un fichier"},Empty:{description:"Aucune donnée"},Icon:{icon:"icône"},Text:{edit:"Éditer",copy:"Copier",copied:"Copie effectuée",expand:"Développer"},Form:{optional:"(optionnel)",defaultValidateMessages:{default:"Erreur de validation pour le champ ${label}",required:"Le champ ${label} est obligatoire",enum:"La valeur du champ ${label} doit être parmi [${enum}]",whitespace:"La valeur du champ ${label} ne peut pas être vide",date:{format:"La valeur du champ ${label} n'est pas au format date",parse:"La valeur du champ ${label} ne peut pas être convertie vers une date",invalid:"La valeur du champ ${label} n'est pas une date valide"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"La taille du champ ${label} doit être de ${len} caractères",min:"La taille du champ ${label} doit être au minimum de ${min} caractères",max:"La taille du champ ${label} doit être au maximum de ${max} caractères",range:"La taille du champ ${label} doit être entre ${min} et ${max} caractères"},number:{len:"La valeur du champ ${label} doit être égale à ${len}",min:"La valeur du champ ${label} doit être plus grande que ${min}",max:"La valeur du champ ${label} doit être plus petit que ${max}",range:"La valeur du champ ${label} doit être entre ${min} et ${max}"},array:{len:"La taille du tableau ${label} doit être de ${len}",min:"La taille du tableau ${label} doit être au minimum de ${min}",max:"La taille du tableau ${label} doit être au maximum de ${max}",range:"La taille du tableau ${label} doit être entre ${min}-${max}"},pattern:{mismatch:"La valeur du champ ${label} ne correspond pas au modèle ${pattern}"}}},Image:{preview:"Aperçu"}};return Fa.default=i,Fa}var Su,Ty;function nL(){return Ty||(Ty=1,Su=tL()),Su}var sL=nL();const rL=fo(sL);var Ua={},Ha={},jy;function oL(){if(jy)return Ha;jy=1,Object.defineProperty(Ha,"__esModule",{value:!0}),Ha.default=void 0;var e={items_per_page:"/ पृष्ठ",jump_to:"इस पर चलें",jump_to_confirm:"पुष्टि करें",page:"",prev_page:"पिछला पृष्ठ",next_page:"अगला पृष्ठ",prev_5:"पिछले 5 पृष्ठ",next_5:"अगले 5 पृष्ठ",prev_3:"पिछले 3 पृष्ठ",next_3:"अगले 3 पेज",page_size:"Page Size"};return Ha.default=e,Ha}var Ka={},Va={},Ya={},Cy;function aL(){if(Cy)return Ya;Cy=1;var e=Xt().default;Object.defineProperty(Ya,"__esModule",{value:!0}),Ya.default=void 0;var t=e(Qo()),n=Zo(),s=(0,t.default)((0,t.default)({},n.commonLocale),{},{locale:"hi_IN",today:"आज",now:"अभी",backToToday:"आज तक",ok:"ठीक",clear:"स्पष्ट",week:"सप्ताह",month:"महीना",year:"साल",timeSelect:"समय का चयन करें",dateSelect:"तारीख़ चुनें",weekSelect:"एक सप्ताह चुनें",monthSelect:"एक महीना चुनें",yearSelect:"एक वर्ष चुनें",decadeSelect:"एक दशक चुनें",dateFormat:"M/D/YYYY",dateTimeFormat:"M/D/YYYY HH:mm:ss",previousMonth:"पिछला महीना (पेजअप)",nextMonth:"अगले महीने (पेजडाउन)",previousYear:"पिछले साल (Ctrl + बाएं)",nextYear:"अगले साल (Ctrl + दाहिना)",previousDecade:"पिछला दशक",nextDecade:"अगले दशक",previousCentury:"पीछ्ली शताब्दी",nextCentury:"अगली सदी"});return Ya.default=s,Ya}var Xa={},My;function JS(){if(My)return Xa;My=1,Object.defineProperty(Xa,"__esModule",{value:!0}),Xa.default=void 0;const e={placeholder:"समय का चयन करें",rangePlaceholder:["आरंभिक समय","अंत समय"]};return Xa.default=e,Xa}var Py;function QS(){if(Py)return Va;Py=1;var e=Xt().default;Object.defineProperty(Va,"__esModule",{value:!0}),Va.default=void 0;var t=e(aL()),n=e(JS());const s={lang:Object.assign({placeholder:"तारीख़ चुनें",yearPlaceholder:"वर्ष चुनें",quarterPlaceholder:"तिमाही चुनें",monthPlaceholder:"महीना चुनिए",weekPlaceholder:"सप्ताह चुनें",rangePlaceholder:["प्रारंभ तिथि","समाप्ति तिथि"],rangeYearPlaceholder:["आरंभिक वर्ष","अंत वर्ष"],rangeMonthPlaceholder:["आरंभिक महीना","अंत महीना"],rangeWeekPlaceholder:["आरंभिक सप्ताह","अंत सप्ताह"]},t.default),timePickerLocale:Object.assign({},n.default)};return Va.default=s,Va}var Ey;function iL(){if(Ey)return Ka;Ey=1;var e=Xt().default;Object.defineProperty(Ka,"__esModule",{value:!0}),Ka.default=void 0;var t=e(QS());return Ka.default=t.default,Ka}var Ry;function lL(){if(Ry)return Ua;Ry=1;var e=Xt().default;Object.defineProperty(Ua,"__esModule",{value:!0}),Ua.default=void 0;var t=e(oL()),n=e(iL()),s=e(QS()),r=e(JS());const a="${label} मान्य ${type} नहीं है",i={locale:"hi",Pagination:t.default,DatePicker:s.default,TimePicker:r.default,Calendar:n.default,global:{placeholder:"कृपया चुनें"},Table:{filterTitle:"सूची बंद करें",filterConfirm:"अच्छी तरह से",filterReset:"रीसेट",filterEmptyText:"कोई फ़िल्टर नहीं",emptyText:"कोई जानकारी नहीं",selectAll:"वर्तमान पृष्ठ का चयन करें",selectInvert:"वर्तमान पृष्ठ घुमाएं",selectNone:"सभी डेटा साफ़ करें",selectionAll:"सभी डेटा का चयन करें",sortTitle:"द्वारा क्रमबद्ध करें",expand:"पंक्ति का विस्तार करें",collapse:"पंक्ति संक्षिप्त करें",triggerDesc:"अवरोही क्रमित करने के लिए क्लिक करें",triggerAsc:"आरोही क्रमित करने के लिए क्लिक करें",cancelSort:"छँटाई रद्द करने के लिए क्लिक करें"},Modal:{okText:"अच्छी तरह से",cancelText:"रद्द करना",justOkText:"अच्छी तरह से"},Popconfirm:{okText:"अच्छी तरह से",cancelText:"रद्द करना"},Transfer:{titles:["",""],searchPlaceholder:"यहां खोजें",itemUnit:"तत्त्व",itemsUnit:"विषय-वस्तु",remove:"हटाए",selectCurrent:"वर्तमान पृष्ठ का चयन करें",removeCurrent:"वर्तमान पृष्ठ हटाएं",selectAll:"सभी डेटा का चयन करें",removeAll:"सभी डेटा हटाएं",selectInvert:"वर्तमान पृष्ठ को उल्टा करें"},Upload:{uploading:"अपलोड हो रहा...",removeFile:"फ़ाइल निकालें",uploadError:"अपलोड में त्रुटि",previewFile:"फ़ाइल पूर्वावलोकन",downloadFile:"फ़ाइल डाउनलोड करें"},Empty:{description:"कोई आकड़ा उपलब्ध नहीं है"},Icon:{icon:"आइकन"},Text:{edit:"संपादित करें",copy:"प्रतिलिपि",copied:"कॉपी किया गया",expand:"विस्तार"},Form:{optional:"(ऐच्छिक)",defaultValidateMessages:{default:"${label} के लिए फील्ड सत्यापन त्रुटि",required:"कृपया ${label} दर्ज करें",enum:"${label} [${enum}] में से एक होना चाहिए",whitespace:"${label} एक खाली अक्षर नहीं हो सकता",date:{format:"${label} तिथि प्रारूप अमान्य है",parse:"${label} को तारीख में नहीं बदला जा सकता",invalid:"${label} एक अमान्य तिथि है"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"${label} ${len} अक्षर का होना चाहिए",min:"${label} कम से कम ${min} वर्णों का होना चाहिए",max:"${label} अधिकतम ${max} वर्णों का होना चाहिए",range:"${label} ${min}-${max} वर्णों के बीच होना चाहिए"},number:{len:"${label} ${len} के बराबर होना चाहिए",min:"${label} कम से कम ${min} होना चाहिए",max:"${label} अधिकतम ${max} होना चाहिए",range:"${label} ${min}-${max} के बीच होना चाहिए"},array:{len:"${len} ${label} होना चाहिए",min:"कम से कम ${min} ${label}",max:"ज्यादा से ज्यादा ${max} ${label}",range:"${label} की राशि ${min}-${max} के बीच होनी चाहिए"},pattern:{mismatch:"${label} ${pattern} पैटर्न से मेल नहीं खाता"}}},Image:{preview:"पूर्वावलोकन"}};return Ua.default=i,Ua}var wu,Ay;function cL(){return Ay||(Ay=1,wu=lL()),wu}var dL=cL();const uL=fo(dL);var Ga={},Ja={},Iy;function mL(){if(Iy)return Ja;Iy=1,Object.defineProperty(Ja,"__esModule",{value:!0}),Ja.default=void 0;var e={items_per_page:"件 / ページ",jump_to:"移動",jump_to_confirm:"確認する",page:"ページ",prev_page:"前のページ",next_page:"次のページ",prev_5:"前 5ページ",next_5:"次 5ページ",prev_3:"前 3ページ",next_3:"次 3ページ",page_size:"ページサイズ"};return Ja.default=e,Ja}var Qa={},Za={},ei={},Oy;function hL(){if(Oy)return ei;Oy=1;var e=Xt().default;Object.defineProperty(ei,"__esModule",{value:!0}),ei.default=void 0;var t=e(Qo()),n=Zo(),s=(0,t.default)((0,t.default)({},n.commonLocale),{},{locale:"ja_JP",today:"今日",now:"現在時刻",backToToday:"今日に戻る",ok:"確定",timeSelect:"時間を選択",dateSelect:"日時を選択",weekSelect:"週を選択",clear:"クリア",week:"週",month:"月",year:"年",previousMonth:"前月 (ページアップキー)",nextMonth:"翌月 (ページダウンキー)",monthSelect:"月を選択",yearSelect:"年を選択",decadeSelect:"年代を選択",yearFormat:"YYYY年",dateFormat:"YYYY年M月D日",dateTimeFormat:"YYYY年M月D日 HH時mm分ss秒",previousYear:"前年 (Controlを押しながら左キー)",nextYear:"翌年 (Controlを押しながら右キー)",previousDecade:"前の年代",nextDecade:"次の年代",previousCentury:"前の世紀",nextCentury:"次の世紀",monthBeforeYear:!1});return ei.default=s,ei}var ti={},$y;function ZS(){if($y)return ti;$y=1,Object.defineProperty(ti,"__esModule",{value:!0}),ti.default=void 0;const e={placeholder:"時間を選択",rangePlaceholder:["開始時間","終了時間"]};return ti.default=e,ti}var Dy;function ew(){if(Dy)return Za;Dy=1;var e=Xt().default;Object.defineProperty(Za,"__esModule",{value:!0}),Za.default=void 0;var t=e(hL()),n=e(ZS());const s={lang:Object.assign({placeholder:"日付を選択",yearPlaceholder:"年を選択",quarterPlaceholder:"四半期を選択",monthPlaceholder:"月を選択",weekPlaceholder:"週を選択",rangePlaceholder:["開始日付","終了日付"],rangeYearPlaceholder:["開始年","終了年"],rangeMonthPlaceholder:["開始月","終了月"],rangeQuarterPlaceholder:["開始四半期","終了四半期"],rangeWeekPlaceholder:["開始週","終了週"],shortWeekDays:["日","月","火","水","木","金","土"],shortMonths:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"]},t.default),timePickerLocale:Object.assign({},n.default)};return Za.default=s,Za}var Ly;function pL(){if(Ly)return Qa;Ly=1;var e=Xt().default;Object.defineProperty(Qa,"__esModule",{value:!0}),Qa.default=void 0;var t=e(ew());return Qa.default=t.default,Qa}var Fy;function fL(){if(Fy)return Ga;Fy=1;var e=Xt().default;Object.defineProperty(Ga,"__esModule",{value:!0}),Ga.default=void 0;var t=e(mL()),n=e(pL()),s=e(ew()),r=e(ZS());const a="${label}は有効な${type}ではありません",i={locale:"ja",Pagination:t.default,DatePicker:s.default,TimePicker:r.default,Calendar:n.default,global:{placeholder:"選んでください"},Table:{filterTitle:"フィルター",filterConfirm:"OK",filterReset:"リセット",filterEmptyText:"フィルターなし",filterCheckAll:"すべてを選択",filterSearchPlaceholder:"フィルターで検索",emptyText:"データなし",selectAll:"ページ単位で選択",selectInvert:"ページ単位で反転",selectNone:"クリア",selectionAll:"すべてを選択",sortTitle:"ソート",expand:"展開する",collapse:"折り畳む",triggerDesc:"クリックで降順にソート",triggerAsc:"クリックで昇順にソート",cancelSort:"ソートをキャンセル"},Tour:{Next:"次",Previous:"前の",Finish:"仕上げる"},Modal:{okText:"OK",cancelText:"キャンセル",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"キャンセル"},Transfer:{titles:["",""],searchPlaceholder:"ここを検索",itemUnit:"アイテム",itemsUnit:"アイテム",remove:"削除",selectCurrent:"現在のページを選択",removeCurrent:"現在のページを削除",selectAll:"ページ単位で選択",deselectAll:"すべてのデータの選択を解除する",removeAll:"ページ単位で削除",selectInvert:"ページ単位で反転"},Upload:{uploading:"アップロード中...",removeFile:"ファイルを削除",uploadError:"アップロードエラー",previewFile:"ファイルをプレビュー",downloadFile:"ダウンロードファイル"},Empty:{description:"データがありません"},Icon:{icon:"アイコン"},Text:{edit:"編集",copy:"コピー",copied:"コピーされました",expand:"拡大する",collapse:"崩壊"},Form:{optional:"(オプション)",defaultValidateMessages:{default:"${label}のフィールド検証エラー",required:"${label}を入力してください",enum:"${label}は[${enum}]のいずれかである必要があります",whitespace:"${label}は空白文字にすることはできません",date:{format:"${label}の日付形式は不正です",parse:"${label}は日付に変換できません",invalid:"${label}は不正な日付です"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"${label}は${len}文字である必要があります",min:"${label}は${min}文字以上である必要があります",max:"${label}は${max}文字以下である必要があります",range:"${label}は${min}-${max}文字の範囲である必要があります"},number:{len:"${label}は${len}と等しい必要があります",min:"${label}の最小値は${min}です",max:"${label}の最大値は${max}です",range:"${label}は${min}-${max}の範囲である必要があります"},array:{len:"${label}は${len}である必要があります",min:"${label}の最小は${min}です",max:"${label}の最大は${max}です",range:"${label}の合計は${min}-${max}の範囲である必要があります"},pattern:{mismatch:"${label}はパターン${pattern}と一致しません"}}},Image:{preview:"プレビュー"},QRCode:{expired:"QRコードの有効期限が切れました",refresh:"リフレッシュ",scanned:"スキャン済み"},ColorPicker:{presetEmpty:"空の",transparent:"透明",singleColor:"単色",gradientColor:"グラデーション"}};return Ga.default=i,Ga}var _u,Ny;function gL(){return Ny||(Ny=1,_u=fL()),_u}var yL=gL();const bL=fo(yL);var ni={},si={},zy;function xL(){if(zy)return si;zy=1,Object.defineProperty(si,"__esModule",{value:!0}),si.default=void 0;var e={items_per_page:"条/页",jump_to:"跳至",jump_to_confirm:"确定",page:"页",prev_page:"上一页",next_page:"下一页",prev_5:"向前 5 页",next_5:"向后 5 页",prev_3:"向前 3 页",next_3:"向后 3 页",page_size:"页码"};return si.default=e,si}var ri={},oi={},ai={},By;function vL(){if(By)return ai;By=1;var e=Xt().default;Object.defineProperty(ai,"__esModule",{value:!0}),ai.default=void 0;var t=e(Qo()),n=Zo(),s=(0,t.default)((0,t.default)({},n.commonLocale),{},{locale:"zh_CN",today:"今天",now:"此刻",backToToday:"返回今天",ok:"确定",timeSelect:"选择时间",dateSelect:"选择日期",weekSelect:"选择周",clear:"清除",week:"周",month:"月",year:"年",previousMonth:"上个月 (翻页上键)",nextMonth:"下个月 (翻页下键)",monthSelect:"选择月份",yearSelect:"选择年份",decadeSelect:"选择年代",previousYear:"上一年 (Control键加左方向键)",nextYear:"下一年 (Control键加右方向键)",previousDecade:"上一年代",nextDecade:"下一年代",previousCentury:"上一世纪",nextCentury:"下一世纪",yearFormat:"YYYY年",cellDateFormat:"D",monthBeforeYear:!1});return ai.default=s,ai}var ii={},Wy;function tw(){if(Wy)return ii;Wy=1,Object.defineProperty(ii,"__esModule",{value:!0}),ii.default=void 0;const e={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return ii.default=e,ii}var qy;function nw(){if(qy)return oi;qy=1;var e=Xt().default;Object.defineProperty(oi,"__esModule",{value:!0}),oi.default=void 0;var t=e(vL()),n=e(tw());const s={lang:Object.assign({placeholder:"请选择日期",yearPlaceholder:"请选择年份",quarterPlaceholder:"请选择季度",monthPlaceholder:"请选择月份",weekPlaceholder:"请选择周",rangePlaceholder:["开始日期","结束日期"],rangeYearPlaceholder:["开始年份","结束年份"],rangeMonthPlaceholder:["开始月份","结束月份"],rangeQuarterPlaceholder:["开始季度","结束季度"],rangeWeekPlaceholder:["开始周","结束周"]},t.default),timePickerLocale:Object.assign({},n.default)};return s.lang.ok="确定",oi.default=s,oi}var Uy;function SL(){if(Uy)return ri;Uy=1;var e=Xt().default;Object.defineProperty(ri,"__esModule",{value:!0}),ri.default=void 0;var t=e(nw());return ri.default=t.default,ri}var Hy;function wL(){if(Hy)return ni;Hy=1;var e=Xt().default;Object.defineProperty(ni,"__esModule",{value:!0}),ni.default=void 0;var t=e(xL()),n=e(SL()),s=e(nw()),r=e(tw());const a="${label}不是一个有效的${type}",i={locale:"zh-cn",Pagination:t.default,DatePicker:s.default,TimePicker:r.default,Calendar:n.default,global:{placeholder:"请选择"},Table:{filterTitle:"筛选",filterConfirm:"确定",filterReset:"重置",filterEmptyText:"无筛选项",filterCheckAll:"全选",filterSearchPlaceholder:"在筛选项中搜索",emptyText:"暂无数据",selectAll:"全选当页",selectInvert:"反选当页",selectNone:"清空所有",selectionAll:"全选所有",sortTitle:"排序",expand:"展开行",collapse:"关闭行",triggerDesc:"点击降序",triggerAsc:"点击升序",cancelSort:"取消排序"},Modal:{okText:"确定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"结束导览"},Popconfirm:{cancelText:"取消",okText:"确定"},Transfer:{titles:["",""],searchPlaceholder:"请输入搜索内容",itemUnit:"项",itemsUnit:"项",remove:"删除",selectCurrent:"全选当页",removeCurrent:"删除当页",selectAll:"全选所有",deselectAll:"取消全选",removeAll:"删除全部",selectInvert:"反选当页"},Upload:{uploading:"文件上传中",removeFile:"删除文件",uploadError:"上传错误",previewFile:"预览文件",downloadFile:"下载文件"},Empty:{description:"暂无数据"},Icon:{icon:"图标"},Text:{edit:"编辑",copy:"复制",copied:"复制成功",expand:"展开",collapse:"收起"},Form:{optional:"(可选)",defaultValidateMessages:{default:"字段验证错误${label}",required:"请输入${label}",enum:"${label}必须是其中一个[${enum}]",whitespace:"${label}不能为空字符",date:{format:"${label}日期格式无效",parse:"${label}不能转换为日期",invalid:"${label}是一个无效日期"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"${label}须为${len}个字符",min:"${label}最少${min}个字符",max:"${label}最多${max}个字符",range:"${label}须在${min}-${max}字符之间"},number:{len:"${label}必须等于${len}",min:"${label}最小值为${min}",max:"${label}最大值为${max}",range:"${label}须在${min}-${max}之间"},array:{len:"须为${len}个${label}",min:"最少${min}个${label}",max:"最多${max}个${label}",range:"${label}数量须在${min}-${max}之间"},pattern:{mismatch:"${label}与模式不匹配${pattern}"}}},Image:{preview:"预览"},QRCode:{expired:"二维码过期",refresh:"点击刷新",scanned:"已扫描"},ColorPicker:{presetEmpty:"暂无",transparent:"无色",singleColor:"单色",gradientColor:"渐变色"}};return ni.default=i,ni}var ku,Ky;function _L(){return Ky||(Ky=1,ku=wL()),ku}var kL=_L();const TL=fo(kL);var li={},ci={},Vy;function jL(){if(Vy)return ci;Vy=1,Object.defineProperty(ci,"__esModule",{value:!0}),ci.default=void 0;var e={items_per_page:"條/頁",jump_to:"跳至",jump_to_confirm:"確定",page:"頁",prev_page:"上一頁",next_page:"下一頁",prev_5:"向前 5 頁",next_5:"向後 5 頁",prev_3:"向前 3 頁",next_3:"向後 3 頁",page_size:"頁碼"};return ci.default=e,ci}var di={},ui={},mi={},Yy;function CL(){if(Yy)return mi;Yy=1;var e=Xt().default;Object.defineProperty(mi,"__esModule",{value:!0}),mi.default=void 0;var t=e(Qo()),n=Zo(),s=(0,t.default)((0,t.default)({},n.commonLocale),{},{locale:"zh_TW",today:"今天",now:"此刻",backToToday:"返回今天",ok:"確定",timeSelect:"選擇時間",dateSelect:"選擇日期",weekSelect:"選擇周",clear:"清除",week:"週",month:"月",year:"年",previousMonth:"上個月 (翻頁上鍵)",nextMonth:"下個月 (翻頁下鍵)",monthSelect:"選擇月份",yearSelect:"選擇年份",decadeSelect:"選擇年代",yearFormat:"YYYY年",dateFormat:"YYYY年M月D日",dateTimeFormat:"YYYY年M月D日 HH時mm分ss秒",previousYear:"上一年 (Control鍵加左方向鍵)",nextYear:"下一年 (Control鍵加右方向鍵)",previousDecade:"上一年代",nextDecade:"下一年代",previousCentury:"上一世紀",nextCentury:"下一世紀",cellDateFormat:"D",monthBeforeYear:!1});return mi.default=s,mi}var hi={},Xy;function sw(){if(Xy)return hi;Xy=1,Object.defineProperty(hi,"__esModule",{value:!0}),hi.default=void 0;const e={placeholder:"請選擇時間"};return hi.default=e,hi}var Gy;function rw(){if(Gy)return ui;Gy=1;var e=Xt().default;Object.defineProperty(ui,"__esModule",{value:!0}),ui.default=void 0;var t=e(CL()),n=e(sw());const s={lang:Object.assign({placeholder:"請選擇日期",yearPlaceholder:"請選擇年份",quarterPlaceholder:"請選擇季度",monthPlaceholder:"請選擇月份",weekPlaceholder:"請選擇周",rangePlaceholder:["開始日期","結束日期"],rangeYearPlaceholder:["開始年份","結束年份"],rangeMonthPlaceholder:["開始月份","結束月份"],rangeQuarterPlaceholder:["開始季度","結束季度"],rangeWeekPlaceholder:["開始周","結束周"]},t.default),timePickerLocale:Object.assign({},n.default)};return s.lang.ok="確 定",ui.default=s,ui}var Jy;function ML(){if(Jy)return di;Jy=1;var e=Xt().default;Object.defineProperty(di,"__esModule",{value:!0}),di.default=void 0;var t=e(rw());return di.default=t.default,di}var Qy;function PL(){if(Qy)return li;Qy=1;var e=Xt().default;Object.defineProperty(li,"__esModule",{value:!0}),li.default=void 0;var t=e(jL()),n=e(ML()),s=e(rw()),r=e(sw());const a="${label}不是一個有效的${type}",i={locale:"zh-tw",Pagination:t.default,DatePicker:s.default,TimePicker:r.default,Calendar:n.default,global:{placeholder:"請選擇"},Table:{filterTitle:"篩選器",filterConfirm:"確定",filterReset:"重置",filterEmptyText:"無篩選項",filterCheckAll:"全選",filterSearchPlaceholder:"在篩選項中搜尋",emptyText:"暫無數據",selectAll:"全部選取",selectInvert:"反向選取",selectNone:"清空所有",selectionAll:"全選所有",sortTitle:"排序",expand:"展開行",collapse:"關閉行",triggerDesc:"點擊降序",triggerAsc:"點擊升序",cancelSort:"取消排序"},Modal:{okText:"確定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"結束導覽"},Popconfirm:{okText:"確定",cancelText:"取消"},Transfer:{titles:["",""],searchPlaceholder:"搜尋資料",itemUnit:"項目",itemsUnit:"項目",remove:"删除",selectCurrent:"全選當頁",removeCurrent:"删除當頁",selectAll:"全選所有",removeAll:"删除全部",selectInvert:"反選當頁"},Upload:{uploading:"正在上傳...",removeFile:"刪除檔案",uploadError:"上傳失敗",previewFile:"檔案預覽",downloadFile:"下载文件"},Empty:{description:"無此資料"},Icon:{icon:"圖標"},Text:{edit:"編輯",copy:"複製",copied:"複製成功",expand:"展開",collapse:"收起"},Form:{optional:"(可選)",defaultValidateMessages:{default:"字段驗證錯誤${label}",required:"請輸入${label}",enum:"${label}必須是其中一個[${enum}]",whitespace:"${label}不能為空字符",date:{format:"${label}日期格式無效",parse:"${label}不能轉換為日期",invalid:"${label}是一個無效日期"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"${label}須為${len}個字符",min:"${label}最少${min}個字符",max:"${label}最多${max}個字符",range:"${label}須在${min}-${max}字符之間"},number:{len:"${label}必須等於${len}",min:"${label}最小值為${min}",max:"${label}最大值為${max}",range:"${label}須在${min}-${max}之間"},array:{len:"須為${len}個${label}",min:"最少${min}個${label}",max:"最多${max}個${label}",range:"${label}數量須在${min}-${max}之間"},pattern:{mismatch:"${label}與模式不匹配${pattern}"}}},Image:{preview:"預覽"},QRCode:{expired:"二維碼過期",refresh:"點擊刷新",scanned:"已掃描"},ColorPicker:{presetEmpty:"暫無",transparent:"透明",singleColor:"單色",gradientColor:"漸變色"}};return li.default=i,li}var Tu,Zy;function EL(){return Zy||(Zy=1,Tu=PL()),Tu}var RL=EL();const AL=fo(RL),eb=e=>{switch(e){case"zh-CN":return TL;case"zh-TW":return AL;case"fr-FR":return rL;case"ja-JP":return bL;case"hi-IN":return uL;default:return JD}};async function IL(){const e=Wn.getInstance();for(const t of Object.keys(localStorage))if(t.startsWith("chat-model-options-cache-v1:")){const n=t.split(":")[1];try{const s=localStorage.getItem(t);if(s){const r=JSON.parse(s);r&&Array.isArray(r.options)&&(await e.saveModelOptionsCache(n,r.options,r.timestamp),localStorage.removeItem(t))}}catch{localStorage.removeItem(t)}}for(const t of Object.keys(localStorage))if(t.startsWith("chat-session-diff-collapse:")){const n=t.split(":")[1];try{const s=localStorage.getItem(t);if(s){const r=JSON.parse(s);r&&typeof r.isExpanded=="boolean"&&(await e.saveDiffCollapse(n,{isExpanded:r.isExpanded,expandedFiles:r.expandedFiles||[]}),localStorage.removeItem(t))}}catch{localStorage.removeItem(t)}}for(const t of Object.keys(localStorage))if(t.startsWith("chat-session-tool-collapse:")){const n=t.split(":");if(n.length>=3){const s=n[1],r=n.slice(2).join(":");try{const a=localStorage.getItem(t);if(a){const i=JSON.parse(a);i&&typeof i.isExpanded=="boolean"&&(await e.saveToolSessionCollapse(s,r,{isExpanded:i.isExpanded,expandedTools:i.expandedTools||[]}),localStorage.removeItem(t))}}catch{localStorage.removeItem(t)}}}try{const t=localStorage.getItem("chat_input_reasoning_by_session_v1");if(t){const n=JSON.parse(t);for(const[s,r]of Object.entries(n))typeof r=="string"&&await e.saveInputReasoning(s,r);localStorage.removeItem("chat_input_reasoning_by_session_v1")}}catch{localStorage.removeItem("chat_input_reasoning_by_session_v1")}try{const t=localStorage.getItem("chat_input_reasoning_last_used_v1");t&&typeof t=="string"&&(await e.saveLastUsedReasoningEffort(t),localStorage.removeItem("chat_input_reasoning_last_used_v1"))}catch{localStorage.removeItem("chat_input_reasoning_last_used_v1")}for(const t of Object.keys(localStorage))if(t.startsWith("chat_scroll_anchor_v2:")){const n=t.split(":")[1];try{const s=localStorage.getItem(t);if(s){const r=JSON.parse(s);r&&r.v===1&&typeof r.anchorId=="string"&&(await e.saveScrollAnchor(n,r),localStorage.removeItem(t))}}catch{localStorage.removeItem(t)}}localStorage.removeItem("chat_scroll_anchors_v1")}const OL="copilot_ui_theme_v1",xm={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)"},vm={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)"},Sm={Tag:{defaultBg:"rgba(13, 148, 136, 0.1)",defaultColor:"#0f766e"},Table:{bodySortBg:"rgba(13, 148, 136, 0.08)"}},wm={Tag:{defaultBg:"rgba(45, 212, 191, 0.18)",defaultColor:"#ccfbf1"},Table:{bodySortBg:"rgba(45, 212, 191, 0.14)"}},tb={...xm,colorBgElevated:"#ffffff",colorBgSpotlight:"#0f172a",colorFillTertiary:"#f3f7f6"},nb={...vm,colorBgElevated:"#0f1b18",colorBgSpotlight:"#22332f",colorFillTertiary:"#162622"},sb={...Sm,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"}},rb={...wm,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 $L(){const{t:e}=Ie(),t=ho(_=>_.themeMode),n=ho(_=>_.setThemeMode),[s,r]=p.useState(()=>Rw()),[a,i]=p.useState(()=>_c()),[l,c]=p.useState(null),[u,m]=p.useState(null),[f,g]=p.useState(0),[b,S]=p.useState(null),[x,T]=p.useState(!1);if(p.useEffect(()=>{localStorage.setItem(OL,t)},[t]),p.useEffect(()=>{localStorage.setItem(Aw,s),Es.changeLanguage(s)},[s]),p.useEffect(()=>{let _=!1;const C=Date.now(),L=async()=>{try{const A=Is.getInstance(),B=await A.getAccessStatus();if(_)return;if(m(null),S(B),B.requires_password&&!x){c(!1);return}const N=await A.getSetupStatus();if(_)return;c(N.is_complete)}catch(A){if(_)return;const B=Date.now()-C;if(B>=2e4){const R=Yo(),I=A instanceof Error&&A.message.trim()?A.message:"Unknown error";m(e("app.backendNotReachable",{baseUrl:R,message:I}));return}const O=Math.min(500+Math.floor(B/2),2e3);setTimeout(()=>{_||L()},O)}};return L(),()=>{_=!0}},[x,f,e]),p.useEffect(()=>{document.body.setAttribute("data-theme",t)},[t]),p.useEffect(()=>{const _=()=>{const C=_c();i(C),document.body.setAttribute("data-vdi-safe",C?"true":"false");const L=document.getElementById("root");L&&L.setAttribute("data-vdi-safe",C?"true":"false")};return _(),window.addEventListener("storage",_),window.addEventListener("lotus-vdi-safe-mode-change",_),()=>{window.removeEventListener("storage",_),window.removeEventListener("lotus-vdi-safe-mode-change",_)}},[]),p.useEffect(()=>{var C;const _=(C=window.__TAURI_INTERNALS__)==null?void 0:C.invoke;typeof _=="function"&&_("set_window_theme",{theme:t}).catch(L=>{console.warn("[App] Failed to sync native window theme:",L)})},[t]),p.useEffect(()=>{l&&Zb()},[l]),p.useEffect(()=>{const _=Wn.getInstance();_.cleanupStaleData(30).catch(L=>{console.warn("[App] Failed to cleanup stale storage data:",L)});const C=setInterval(()=>{_.cleanupStaleData(30).catch(()=>{})},24*60*60*1e3);return()=>clearInterval(C)},[]),p.useEffect(()=>{const _=setTimeout(()=>{IL().catch(C=>{console.warn("[App] Storage migration failed:",C)})},5e3);return()=>clearTimeout(_)},[]),b!=null&&b.requires_password&&!x)return o.jsx(cp,{locale:eb(s),theme:{token:t==="dark"?a?nb:vm:a?tb:xm,algorithm:t==="dark"?Ge.darkAlgorithm:Ge.defaultAlgorithm,components:t==="dark"?a?rb:wm:a?sb:Sm},children:o.jsx(sn,{children:o.jsx(Bi,{name:"PasswordGatePage",children:o.jsx(BD,{verifyPassword:async _=>{await Is.getInstance().verifyAccessPassword(_)},onVerified:async()=>{T(!0),m(null),g(_=>_+1)}})})})});if(l===null)return u?o.jsxs("div",{style:{padding:40,textAlign:"center"},children:[o.jsx("div",{style:{marginBottom:12},children:u}),o.jsx(ue,{type:"primary",onClick:()=>{m(null),S(null),c(null),g(_=>_+1)},children:e("app.retry")})]}):o.jsx("div",{style:{padding:40,textAlign:"center"},children:e("app.loading")});const j=l?o.jsx(LD,{themeMode:t,onThemeModeChange:n,locale:s,onLocaleChange:r}):o.jsx(ND,{}),w=t==="dark"?a?nb:vm:a?tb:xm,M=t==="dark"?a?rb:wm:a?sb:Sm;return o.jsx(cp,{locale:eb(s),theme:{token:w,algorithm:t==="dark"?Ge.darkAlgorithm:Ge.defaultAlgorithm,components:M},children:o.jsx(sn,{children:o.jsx(Bi,{name:"App",children:o.jsx("div",{style:{position:"relative"},children:j})})})})}const lF=Object.freeze(Object.defineProperty({__proto__:null,default:$L},Symbol.toStringTag,{value:"Module"}));export{lF as A,Ei as C,rt as a,Jt as d,Go as p,te as u,DP as w};
|