PageSourceSearch

https://www.007icu.top/assets/store-JX60g0Lu.js

js 007icu.top collected 2026-10-09 04:33:27 UTC 2,381,565 bytes, 6,012 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/heterogeneousAgent-DjV9GlfG.js","assets/rolldown-runtime-CMxvf4Kt.js","assets/ipc-XkRXMd72.js","assets/app-const-BzFqCjOv.js","assets/message-D0HRzm1P.js","assets/_api-Bwh1mFfN.js","assets/abortableRequest-C6SDiPFy.js","assets/fileSystem-DmAwavrR.js","assets/heterogeneousAgentExecutor-BNR49jHj.js","vendor/vendor-ai-runtime-DrDK77gy.js","assets/agent-Dh3-_0ai.js","assets/es-D3_QMuVV.js","vendor/vendor-ui-runtime-CtdfFhWo.js","vendor/vendor-react-Bwss5s6Y.js","vendor/vendor-data-runtime-nLFaCKB0.js","assets/dist-Bj37lFH5.js","assets/client-DUGXaJW2.js","assets/agentDocument-GhemY2N0.js","assets/index.es-DjTiFdoF.js","assets/swr-C_leGIiU.js","assets/swrKeys-D98yQcag.js","assets/__vite-browser-external-C7CMhtSr.js","assets/agent-Doq2Q6Wt.js","vendor/vendor-icons-BXJMWD35.js","assets/selectors-BZArZxfP.js","assets/keys-BAizXMAH.js","assets/remoteServer-CvRN6Lkd.js","assets/system-DG8myUWP.js","assets/user-DQWC3jQX.js","assets/selectors-IDJ5-Ts8.js","assets/p-map-D5Ha-P-7.js","assets/browserSidebar-B9OBh1GV.js","assets/browserControl-BCZ4UGPM.js","assets/global-DfKpeTkj.js","assets/workspaceAwarePath-CWYUwft9.js","assets/aiAgent-lAVLuc1K.js","assets/document-Cvvy0X4f.js","assets/index-Doip7UYu.js","assets/es-D7HWafs1.js","assets/ScrollArea-CdDxdn_v.js","assets/common-DsfyCloF.js","assets/image-CWkvcIjp.js","assets/dist-31DrMw5o.js","assets/katex-DeoMKzDS.js","assets/base-ui-Bi3Dz7GG.js","assets/icons-Bz1tvWUu.js","assets/store-DZ_eFvAj.js","assets/upload-DXx2CvIy.js","assets/isChunkingUnsupported-DzBdjh0S.js","assets/document-B0YnY6Mv.js","assets/resource-D1c_4mou.js","assets/knowledgeBase-o6SNuybf.js","assets/Lexical.prod-ZYFyn_a-.js","assets/dist--WvQXYgF.js","assets/onboardingMetrics-G6KV9Xr_.js","assets/src-DYf_YQ1m.js","assets/client-CZ_nGfzL.js","assets/purify.es-Z081vKev.js","assets/_url-D-hzZcqW.js","assets/discover-v4iycg4x.js","assets/selectors-BLjUqOPJ.js","assets/localFileService-DGk4gV-M.js","assets/file-DreLu7dP.js","assets/selectors-YrzAdmlx.js","assets/browser-DrcRs7_D.js","assets/constants-Bb3CxuI1.js","assets/index-B5uW1P3u.css","assets/connector-CTv0KPI6.js","assets/esm-CGkVx4zY.js","assets/trpc-headers-BkKHL6Gq.js"])))=>i.map(i=>d[i]);
2import{n as e,o as t,r as n,t as r}from"./rolldown-runtime-CMxvf4Kt.js";import{Bt as i}from"../i18n/i18n-ar-O-z3xW8i.js";import{F as a,G as o,K as s,L as c,O as l,R as u,S as d,U as f,W as p,X as m,_ as h,b as g,et as _,g as v,w as y,x as b,y as x}from"../vendor/vendor-data-runtime-nLFaCKB0.js";import{A as S,An as C,B as w,Bn as T,Ci as E,Cn as D,D as O,Dn as k,En as A,Fn as j,Fr as M,Gr as N,In as P,Ki as F,Kt as I,Mn as L,Nn as ee,O as R,On as te,P as z,Pn as ne,Qn as B,Rn as V,S as H,Si as re,Sr as ie,U as ae,Vn as oe,W as se,Wr as ce,Yi as le,Zn as ue,_i as de,_n as fe,an as pe,at as me,b as he,bi as ge,cn as _e,ct as ve,di as ye,fr as be,g as xe,gn as Se,gt as Ce,hn as we,ht as Te,ii as Ee,in as De,it as Oe,j as ke,kn as Ae,l as je,mi as Me,mn as Ne,na as Pe,nn as Fe,nt as Ie,o as Le,ot as Re,pi as ze,pn as Be,pt as Ve,qi as He,sn as Ue,t as We,ta as Ge,tn as Ke,v as qe,vi as Je,x as Ye,yi as Xe,z as Ze,zi as Qe,zn as $e}from"../vendor/vendor-ai-runtime-DrDK77gy.js";import{C as et,S as tt,_ as nt,a as rt,b as it,c as at,d as ot,g as st,i as ct,l as lt,m as ut,n as dt,o as ft,r as pt,s as mt,t as ht,u as gt,x as _t}from"./agent-Doq2Q6Wt.js";import{$t as vt,Ai as yt,An as bt,Ao as xt,C as St,Cn as Ct,Fn as wt,Ft as Tt,L as Et,N as Dt,Ni as Ot,Oi as kt,Oo as At,Pi as jt,Qa as Mt,R as Nt,Ri as Pt,S as Ft,Tt as It,Ua as Lt,Xi as Rt,Xn as zt,Ya as Bt,Yn as Vt,bi as eee,bt as Ht,en as Ut,g as Wt,it as Gt,j as Kt,jo as qt,jt as Jt,ki as Yt,ko as Xt,la as Zt,nn as Qt,nt as $t,ro as en,rt as tn,tt as nn,wn as rn,x as an,xt as on,yi as sn,z as cn,zt as ln}from"./app-const-BzFqCjOv.js";import{Ao as un,Co as dn,D as fn,Do as U,Eo as pn,Fn as mn,Oo as W,bo as hn,so as gn,t as _n,to as vn,vo as yn,wo as bn,zn as xn}from"./ScrollArea-CdDxdn_v.js";import{Gn as Sn,I as Cn,Ji as wn,Ka as Tn,Un as En,Za as tee,ba as Dn,ca as On,ei as kn,eo as An,fa as 
2jn,ir as Mn,ma as Nn,n as Pn,qn as Fn,va as In}from"./es-D7HWafs1.js";import{Sr as Ln,xr as Rn}from"./es-D3_QMuVV.js";import{lr as zn,ur as Bn}from"../vendor/vendor-ui-runtime-CtdfFhWo.js";import{w as Vn}from"../vendor/vendor-react-Bwss5s6Y.js";import{Cp as Hn,Fi as G,G_ as K,Gc as Un,Gi as Wn,La as Gn,Li as Kn,Lp as qn,Nh as Jn,Ni as nee,Nr as ree,Ti as iee,Yr as aee,Zh as oee,Zl as see,_f as cee,as as lee,dl as Yn,do as Xn,ds as uee,et as Zn,hh as Qn,hs as dee,jm as fee,jt as pee,ju as mee,ks as $n,ls as hee,pd as gee,pf as _ee,ph as er,qc as tr,qp as vee,ra as yee,rd as nr,rf as bee,ru as xee,st as rr,tm as See,tp as ir,xc as Cee,xd as wee,xi as Tee,ys as Eee,zl as Dee,zn as Oee}from"../vendor/vendor-icons-BXJMWD35.js";import{O as ar,n as or,r as kee}from"./base-ui-Bi3Dz7GG.js";import{C as sr,h as Aee,n as cr}from"./icons-Bz1tvWUu.js";import{$n as lr,A as ur,An as jee,At as Mee,Bt as dr,Cn as Nee,Dn as Pee,Dt as Fee,Et as fr,Fn as pr,Ft as Iee,Gt as mr,In as hr,It as Lee,Jt as gr,Kn as _r,Kt as Ree,Ln as vr,Lt as zee,Mn as yr,Mt as Bee,N as Vee,Nt as Hee,Ot as br,Qn as xr,Qt as Sr,Rn as Uee,Rt as Cr,S as Wee,St as Gee,Tn as Kee,Tt as wr,Ut as Tr,Vn as qee,Vt as Jee,Wn as Er,Xn as Dr,Xt as Yee,Yn as Or,Yt as Xee,Zn as kr,Zt as Zee,_ as Qee,_n as $ee,_t as Ar,a as jr,an as ete,ar as tte,bn as Mr,bt as Nr,cn as Pr,ct as nte,dn as Fr,dt as Ir,en as rte,et as ite,ft as Lr,gt as ate,hn as ote,ht as Rr,i as ste,ir as zr,jn as Br,jt as cte,k as Vr,kn as lte,kt as ute,l as Hr,lt as Ur,mn as Wr,n as Gr,nn as Kr,o as qr,on as dte,p as fte,pn as Jr,pt as Yr,qn as pte,qt as mte,r as Xr,rn as Zr,rr as Qr,s as $r,sn as hte,un as ei,vn as gte,wn as _te,wt as ti,xt as vte,yn as ni,yt as ri,zn as yte,zt as ii}from"./agent-Dh3-_0ai.js";import{At as ai,B as bte,Ct as oi,Dt as xte,Et as si,F as ci,I as Ste,J as Cte,K as wte,L as Tte,Mt as li,N as ui,O as di,Ot as Ete,P as Dte,Q as fi,R as Ote,St as pi,Tt as kte,U as mi,W as hi,X as Ate,Y as gi,_ as _i,a as jte,b as vi,c as Mte,ct as Nte,dt as yi,et as Pte,f as bi,g as xi,h as Si,i as Ci,it as Fte,j as Ite,jt as wi,kt as Ti,lt as Lte,m as Rte,mt as zte,nt as Bte,p as Ei,q as Di,r as Vte,s as Hte,st as Ute,t as Oi,u as ki,v as Wte,wt as Gte,xt as Ai,y as ji}from"./selectors-IDJ5-Ts8.js";import{n as Kte,t as qte}from"./p-map-D5Ha-P-7.js";import{A as Jte,C as Mi,E as Yte,H as Xte,It as Zte,J as Qte,Nt as $te,Qt as ene,Rt as tne,S as nne,St as rne,Tt as ine,Xt as ane,_n as one,a as Ni,at as sne,b as Pi,ct as cne,d as lne,dn as une,dt as dne,en as fne,et as pne,f as mne,ft as hne,g as gne,gt as _ne,hn as vne,i as yne,it as bne,jt as Fi,ln as xne,lt as Sne,m as Cne,mt as wne,n as Ii,nt as Tne,o as Li,ot as Ene,pn as Dne,rt as One,sn as kne,st as Ri,t as zi,v as Ane,w as jne,xt as Mne,yn as Nne,yt as Bi,zt as Pne}from"./agentDocument-GhemY2N0.js";import{C as Fne,T as Ine,_ as Lne,a as Rne,d as zne,h as Bne,l as Vne,n as Hne,p as Une,r as Wne,s as Gne,x as Kne,y as qne}from"./fileSystem-DmAwavrR.js";import{Cn as Vi,Dr as Jne,Er as Hi,Sr as Ui,Tr as Wi,br as Gi,hn as Yne,lr as Xne,mr as Zne,pr as Ki,tr as qi,ur as Ji,wr as Qne,xr as Yi}from"../i18n/i18n-src-XaAKi_OQ.js";import{h as $ne,m as ere,p as tre,r as Xi,s as Zi,t as Qi,u as $i}from"./swr-C_leGIiU.js";import{i as nre,r as rre,t as ire}from"./swrKeys-D98yQcag.js";import{F as are,I as ore,K as ea,M as ta,R as na,dt as ra,f as sre,h as ia,it as aa,j as oa,n as cre,ot as sa,p as lre,r as ca,rt as la,tt as ua,w as da}from"./keys-BAizXMAH.js";import{C as ure,S as dre,b as fre,i as fa,n as pa,s as q,u as pre,w as mre,x as ma}from"./client-DUGXaJW2.js";import{i as ha,t as ga}from"./_api-Bwh1mFfN.js";import{n as _a,t as va}from"./user-DQWC3jQX.js";import{C as hre,D as ya,E as gre,O as ba,a as xa,d as Sa,h as _re,l as Ca,s as wa,t as Ta,v as vre}from"./selectors-BZArZxfP.js";import{n as yre,t as bre}from"./dist-Bj37lFH5.js";import{i as xre,n as Sre,p as Ea,t as Da}from"./ipc-XkRXMd72.js";import{C as Cre,S as wre,b as Oa,n as Tre,s as Ere,t as Dre,x as ka}from"./device-C93cnKgk.js";import{n as Aa,t as ja}from"./markdownToTxt-oGIVcT3Y.js";import{n as Ma,t as Na}from"./message-D0HRzm1P.js";import{n as Pa,t as Fa}from"./topic-BNd-QL8r.js";import{g as Ore,h as Ia,t as kre}from"./client-CZ_nGfzL.js";import{f as La,l as Ra,n as za,r as Are,t as Ba,u as Va}from"./aiInfra-Db7NbJs1.js";import{a as jre,c as Mre,d as Nre,i as Pre,t as Fre,x as Ire,y as Lre}from"./onboardingMetrics-G6KV9Xr_.js";import{a as Rre,c as zre,n as Ha,r as Ua,s as Bre}from"./connector-CTv0KPI6.js";import{i as Vre,n as Hre,o as Ure,t as Wre}from"./modelParamsResolver-nekzHtip.js";import{r as Wa,t as Ga}from"./aiAgent-lAVLuc1K.js";import{n as Ka,r as qa}from"./time-Dj7pwiip.js";import{C as Gre,a as Kre,i as Ja,m as Ya,n as Xa,o as qre}from"./global-DfKpeTkj.js";import{i as Za,n as Jre,r as Qa,t as Yre}
2from"./workspaceAwarePath-CWYUwft9.js";import{t as Xre}from"./selectors-BLjUqOPJ.js";import{i as Zre,n as $a,r as Qre,t as eo}from"./discover-v4iycg4x.js";import{n as $re,t as eie}from"./document-B0YnY6Mv.js";import{A as tie,M as to,j as nie,k as rie,n as iie,r as aie,t as oie}from"./store-DZ_eFvAj.js";import{n as no,t as ro}from"./localFileService-DGk4gV-M.js";import{n as sie,t as cie}from"./userMemory-4Fm7oKjF.js";import{n as lie,t as uie}from"./normalizeError-CCdtPTTN.js";import{Cn as io,rn as die}from"./Lexical.prod-ZYFyn_a-.js";import{r as fie,t as pie}from"./src-DYf_YQ1m.js";import{a as mie,c as ao,d as oo,f as hie,i as so,l as gie,n as _ie,o as vie,p as yie,r as bie,s as xie,u as co}from"./_auth-Cs6ijSJn.js";import{r as lo,t as uo}from"./_url-D-hzZcqW.js";import{a as Sie,i as Cie,n as fo,o as wie,t as po}from"./userMemory-Cq2-UQHy.js";import{a as mo,o as Tie}from"./resource-D1c_4mou.js";import{n as Eie}from"./file-DreLu7dP.js";var ho,Die=e((()=>{ho={gatewayConnections:{},inputFiles:[],inputMessage:``,mainInputEditor:null,pendingClientToolExecutions:{},searchWorkflowLoadingIds:[],threadInputEditor:null,toolCallingStreamIds:{}}})),go,Oie=e((()=>{go={}})),_o,kie=e((()=>{_o={codeInterpreterFileMap:{},codeInterpreterImageMap:{}}})),vo,Aie=e((()=>{vo={activeAgentId:``,dbMessagesMap:{},groupAgentMaps:{},isCreatingMessage:!1,messageEditingIds:[],messagesInit:!1,messagesMap:{}}})),yo,bo=e((()=>{yo={messageOperationMap:{},operations:{},operationsByContext:{},operationsByMessage:{},operationsByType:{},queuedMessages:{}}})),xo,jie=e((()=>{Ne(),xo={isCreatingThread:!1,newThreadMode:Ee.Continuation,threadInputMessage:``,threadLoadingIds:[],threadMaps:{},threadsInit:!1}})),So,Mie=e((()=>{So={activeTopicId:null,agentTopicsViewMap:{},allTopicsDrawerOpen:!1,creatingTopic:!1,isSearchingTopic:!1,searchTopics:[],topicDataMap:{},topicLoadingIdCounts:{},topicLoadingIds:[],topicSearchKeywords:``}})),Co,Nie=e((()=>{Die(),Oie(),kie(),Aie(),bo(),Ei(),jie(),Mie(),Co={...vo,...ho,...So,..._o,...xo,...Rte,...yo,...go}})),wo,To,Eo,Do,Oo,ko=e((()=>{wo=[{command:`claude`,iconId:`ClaudeCode`,menuKey:`newClaudeCodeAgent`,menuLabelKey:`newClaudeCodeAgent`,title:`Claude Code`,type:`claude-code`},{command:`codex`,iconId:`Codex`,menuKey:`newCodexAgent`,menuLabelKey:`newCodexAgent`,title:`Codex`,type:`codex`},{command:`amp`,iconId:`Amp`,menuKey:`newAmpAgent`,menuLabelKey:`newAmpAgent`,title:`Amp`,type:`amp`},{command:`opencode`,iconId:`OpenCode`,menuKey:`newOpenCodeAgent`,menuLabelKey:`newOpenCodeAgent`,title:`OpenCode`,type:`opencode`}],To=e=>wo.find(t=>t.type===e),Eo=[{title:`OpenClaw`,type:`openclaw`},{title:`Hermes`,type:`hermes`}],Do=new Set(Eo.map(e=>e.type)),Oo=e=>Do.has(e)})),Ao,jo=e((()=>{ko(),Ao=Object.fromEntries([...wo.map(e=>[e.type,e.title]),...Eo.map(e=>[e.type,e.title])])})),Mo,No=e((()=>{Mo=e=>{let t=e?.data?.subagent;return t&&typeof t.parentToolCallId==`string`?{ctx:t,kind:`subagent`}:{kind:`main`}}})),Po,Fo,Io,Lo,Ro,zo,Bo,Vo,Ho,Uo,Wo,Go,Pie=e((()=>{No(),Po=e=>({payloads:e.payloads.map(e=>({...e})),persistedIds:new Set(e.persistedIds),toolMsgIdByCallId:new Map(e.toolMsgIdByCallId)}),Fo=()=>({payloads:[],persistedIds:new Set,toolMsgIdByCallId:new Map}),Io=e=>({...e,lifetimeToolCallIds:new Set(e.lifetimeToolCallIds),toolState:Po(e.toolState)}),Lo=(e,t,n)=>{let r=new Map(e.runs);return r.set(t,n),{...e,runs:r}},Ro=(e,t)=>{let n=new Map(e.runs);n.delete(t);let r=new Set(e.finalizedParents);return r.add(t),{...e,finalizedParents:r,runs:n}},zo=80,Bo=(e,t,n)=>{let r=[],i=e.runs.get(t.parentToolCallId);if(!i&&e.finalizedParents.has(t.parentToolCallId))return{intents:r,run:null,state:e};if(!i){let i=n.newId(`thread`),a=n.newId(`message`),o=n.newId(`message`),{spawnMetadata:s}=t,c=s?.description?.slice(0,zo)||s?.subagentType||`Subagent`;r.push({kind:`createThread`,parentToolCallId:t.parentToolCallId,sourceMessageId:n.mainAssistantId,sourceToolCallId:t.parentToolCallId,subagentType:s?.subagentType,threadId:i,title:c,topicId:n.topicId},{agentId:n.agentId,content:s?.prompt??``,kind:`createMessage`,messageId:a,parentId:n.mainAssistantId,role:`user`,threadId:i,topicId:n.topicId},{agentId:n.agentId,content:``,kind:`createMessage`,messageId:o,parentId:a,role:`assistant`,subagentMessageId:t.subagentMessageId,threadId:i,topicId:n.topicId});let l={accContent:``,accReasoning:``,currentAssistantId:o,currentSubagentMessageId:t.subagentMessageId??``,lastChainParentId:o,lifetimeToolCallIds:new Set,threadId:i,toolState:Fo()};return{intents:r,run:l,state:Lo(e,t.parentToolCallId,l)}}let a=Io(i);if(t.subagentMessageId&&t.subagentMessageId!==a.currentSubagentMessageId){(a.accContent||a.accReasoning)&&r.push({content:a.accContent||void 0,kind:`persistContent`,messageId:a.currentAssistantId,reasoning:a.accReasoning||void 0,threadId:a.threadId});let e=n.newId(`message`);r.push({agentId:n.agentId,content:``,kind:`createMessage`,messageId:e,parentId:a.lastChainParentId,role:`assistant`,subagentMessageId:t.subagentMessageId,threadId:a.threadId,topicId:n.topicId}),a.currentAssistantId=e,a.currentSubagentMessageId=t.subagentMessageId,a.lastChainParentId=e,a.toolState=Fo(),a.accContent=``,a.accReasoning=``}return{intents:r,run:a,state:Lo(e,t.parentToolCallId,a)}},Vo=(e,t,n,r)=>{let i=e.runs.get(t);if(!i)return{intents:[],state:e};let a=[],o=Io(i);if((o.accContent||o.accReasoning)&&(a.push({content:o.accContent||void 0,kind:`persistContent`,messageId:o.currentAssistantId,reasoning:o.accReasoning||void 0,threadId:o.threadId}),o.accContent=``,o.accReasoning=``),n){let e=r.newId(`message`);a.push({agentId:r.agentId,content:n,kind:`createMessage`,messageId:e,parentId:o.lastChainParentId,role:`assistant`,threadId:o.threadId,topicId:r.topicId}),o.currentAssistantId=e,o.lastChainParentId=e}return a.push({kind:`finalizeThread`,threadId:o.threadId}),{intents:a,state:Ro(e,t)}},Ho=(e,t)=>{for(let[n,r]of e.runs)if(r.lifetimeToolCallIds.has(t))return{parentToolCallId:n,run:r}},Uo=(e,t,n,r,i)=>{let a=Bo(e,t,i),o=a.run,s=a.intents;return o?(n===`text`?o.accContent+=r:o.accReasoning+=r,s.push({kind:`streamContent`,messageId:o.currentAssistantId,threadId:o.threadId,...n===`text`?{content:o.accContent}:{reasoning:o.accReasoning}}),{intents:s,state:Lo(a.state,t.parentToolCallId,o)}):{intents:s,state:a.state}},Wo=(e,t,n,r)=>{let i=Bo(e,t,r),a=i.run,o=i.intents;if(!a)return{intents:o,state:i.state};let s=[];for(let e of n){if(a.lifetimeToolCallIds.has(e.id)||a.toolState.persistedIds.has(e.id))continue;
2a.toolState.persistedIds.add(e.id),a.toolState.payloads.push({apiName:e.apiName,arguments:e.arguments,id:e.id,identifier:e.identifier,type:e.type});let t=r.newId(`message`);a.toolState.toolMsgIdByCallId.set(e.id,t),s.push(t)}for(let e of n)a.lifetimeToolCallIds.add(e.id);return o.push({assistantMessageId:a.currentAssistantId,content:a.accContent||void 0,kind:`persistToolBatch`,reasoning:a.accReasoning||void 0,subagentMessageId:a.currentSubagentMessageId||void 0,threadId:a.threadId,tools:a.toolState.payloads.map(e=>({isNew:s.includes(a.toolState.toolMsgIdByCallId.get(e.id)),payload:{...e},toolMessageId:a.toolState.toolMsgIdByCallId.get(e.id)}))}),{intents:o,state:Lo(i.state,t.parentToolCallId,a)}},Go=(e,t,n)=>{let r=t.type,i=t.data??{};if(r===`stream_chunk`){let r=Mo(t);if(r.kind!==`subagent`)return{intents:[],state:e};let a=r.ctx;if(i.chunkType===`text`&&typeof i.content==`string`&&i.content)return Uo(e,a,`text`,i.content,n);if(i.chunkType===`reasoning`&&typeof i.reasoning==`string`&&i.reasoning)return Uo(e,a,`reasoning`,i.reasoning,n);if(i.chunkType===`tool_state`&&i.snapshotMode===`replace`&&typeof i.toolCallId==`string`&&i.toolCallId.length>0&&Number.isInteger(i.snapshotSeq)&&i.snapshotSeq>0&&typeof i.pluginState==`object`&&i.pluginState!==null&&!Array.isArray(i.pluginState)){let t=Ho(e,i.toolCallId);return t?{intents:[{kind:`updateToolState`,pluginState:i.pluginState,snapshotSeq:i.snapshotSeq,threadId:t.run.threadId,toolCallId:i.toolCallId}],state:e}:{intents:[],state:e}}if(i.chunkType===`tools_calling`){let t=i.toolsCalling??[];return t.length===0?{intents:[],state:e}:Wo(e,a,t,n)}return{intents:[],state:e}}if(r===`tool_result`){let t=i.toolCallId;if(!t)return{intents:[],state:e};let r=i.content??``;if(e.runs.has(t))return Vo(e,t,r,n);let a=Ho(e,t);return a?{intents:[{content:r,isError:!!i.isError,kind:`resolveToolResult`,pluginState:i.pluginState,threadId:a.run.threadId,toolCallId:t}],state:e}:{intents:[],state:e}}if(r===`step_complete`&&i.phase===`turn_metadata`){let t=i.subagent;if(!t||!i.usage)return{intents:[],state:e};let n=e.runs.get(t.parentToolCallId);return n?{intents:[{kind:`recordUsage`,messageId:n.currentAssistantId,model:i.model,provider:i.provider,subagentMessageId:n.currentSubagentMessageId||void 0,threadId:n.threadId,usage:i.usage}],state:e}:{intents:[],state:e}}if(r===`agent_runtime_end`||r===`error`){let t=e,r=[];for(let i of e.runs.keys()){let e=Vo(t,i,void 0,n);r.push(...e.intents),t=e.state}return{intents:r,state:t}}return{intents:[],state:e}}})),Ko,qo,Jo=e((()=>{Ko=()=>({finalizedParents:new Set,runs:new Map}),qo=(e,t=[])=>{let n=new Map;for(let t of e)n.set(t.parentToolCallId,{accContent:``,accReasoning:``,currentAssistantId:t.currentAssistantId,currentSubagentMessageId:t.currentSubagentMessageId??``,lastChainParentId:t.lastChainParentId??t.currentAssistantId,lifetimeToolCallIds:new Set(t.lifetimeToolCallIds??[]),threadId:t.threadId,toolState:{payloads:[],persistedIds:new Set,toolMsgIdByCallId:new Map}});return{finalizedParents:new Set(t),runs:n}}})),Yo=e((()=>{No(),Pie(),Jo()})),Xo,Zo,Qo,$o,es,ts,ns,rs,is,as,os,ss,cs,ls,us,ds,fs,ps,ms=e((()=>{Yo(),Xo=e=>({payloads:e.payloads.map(e=>({...e})),persistedIds:new Set(e.persistedIds),toolMsgIdByCallId:new Map(e.toolMsgIdByCallId)}),Zo=()=>({payloads:[],persistedIds:new Set,toolMsgIdByCallId:new Map}),Qo=e=>({...e,toolState:Xo(e.toolState),turnMetadata:{...e.turnMetadata}}),$o=e=>e?.replaceAll(/\s+/g,` `).trim(),es=(e,t)=>{let n=t;if(!n?.clearEchoedContent&&n?.code!==`AuthRequired`)return!1;let r=$o(e),i=$o(n?.stderr||n?.message);return!!r&&!!i&&r===i},ts=(e,t)=>({agentId:t.agentId,mainAssistantId:e.currentAssistantId,newId:t.newId,topicId:t.topicId}),ns=(e,t,n)=>{let{intents:r,state:i}=Go(e.subagents,t,ts(e,n));return{intents:r,state:{...e,subagents:i}}},rs=(e,t)=>t?.externalSignal?e.lastToolMsgIdEver??e.lastSpineMessageId:e.lastSpineMessageId,is=(e,t,n)=>{let r=[],i={};e.accContent&&(i.content=e.accContent),e.accReasoning&&(i.reasoning=e.accReasoning),e.turnModel&&(i.model=e.turnModel),e.turnProvider&&(i.provider=e.turnProvider),Object.keys(i).length>0&&r.push({kind:`persistAssistant`,messageId:e.currentAssistantId,...i});let a=n.newId(`message`),o=typeof t?.messageId==`string`?t.messageId:void 0,s=!!t?.externalSignal;r.push({agentId:n.agentId,kind:`createAssistant`,mainMessageId:o,messageId:a,model:e.turnModel,parentId:rs(e,t),provider:e.turnProvider,signal:t?.externalSignal,topicId:n.topicId});let c=Qo(e);return c.currentAssistantId=a,s||(c.lastSpineMessageId=a),c.currentMainMessageId=o,c.accContent=``,c.accReasoning=``,c.lastReasoningSnapshotSeq=0,c.lastTextSnapshotSeq=0,c.turnMetadata={},c.toolState=Zo(),{intents:r,state:c}},as=(e,t)=>{let n={};t?.model&&(n.model=t.model),t?.provider&&(n.provider=t.provider);let r=typeof t?.messageId==`string`&&!e.currentMainMessageId?t.messageId:void 0;if(Object.keys(n).length===0&&!r)return{intents:[],state:e};let i=Qo(e);return t.model&&(i.turnModel=t.model),t.provider&&(i.turnProvider=t.provider),r&&(i.currentMainMessageId=r),{intents:Object.keys(n).length>0?[{kind:`persistAssistant`,messageId:e.currentAssistantId,...n}]:[],state:i}},os=(e,t)=>{let n=Qo(e),r=t?.snapshotMode,i=typeof t?.snapshotSeq==`number`?t.snapshotSeq:void 0;if(r===`replace`&&i!==void 0){if(i<=e.lastTextSnapshotSeq)return{intents:[],state:e};n.lastTextSnapshotSeq=i,n.turnMetadata={...n.turnMetadata,heteroTextSnapshotSeq:i},n.accContent=t.content}else{if(!t?.content)return{intents:[],state:e};n.accContent=e.accContent+t.content}return{intents:[{content:n.accContent,kind:`streamContent`,messageId:n.currentAssistantId}],state:n}},ss=(e,t)=>{let n=Qo(e),r=t?.snapshotMode,i=typeof t?.snapshotSeq==`number`?t.snapshotSeq:void 0;if(r===`replace`&&i!==void 0){if(i<=e.lastReasoningSnapshotSeq)return{intents:[],state:e};n.lastReasoningSnapshotSeq=i,n.turnMetadata={...n.turnMetadata,heteroReasoningSnapshotSeq:i},n.accReasoning=t.reasoning}else{if(!t?.reasoning)return{intents:[],state:e};n.accReasoning=e.accReasoning+t.reasoning}return{intents:[{kind:`streamContent`,messageId:n.currentAssistantId,reasoning:n.accReasoning}],state:n}},cs=(e,t,n)=>{let r=Qo(e),i=[];for(let e of t){if(r.toolState.persistedIds.has(e.id))continue;r.toolState.persistedIds.add(e.id),r.toolState.payloads.push({apiName:e.apiName,arguments:e.arguments,id:e.id,identifier:e.identifier,type:e.type});let t=n.newId(`message`);r.toolState.toolMsgIdByCallId.set(e.id,t),i.push(t)}let a=[{assistantMessageId:r.currentAssistantId,content:r.accContent||void 0,kind:`persistToolBatch`,reasoning:r.accReasoning||void 0,tools:r.toolState.payloads.map(e=>({isNew:i.includes(r.toolState.toolMsgIdByCallId.get(e.id)),payload:{...e},toolMessageId:r.toolState.toolMsgIdByCallId.get(e.id)}))}],o=i.at(-1);return o&&(r.lastToolMsgIdEver=o),r.lastSpineMessageId=r.currentAssistantId,{intents:a,state:r}},ls=(e,t,n)=>{if(t?.chunkType===`text`&&typeof t.content==`string`)return os(e,t);if(t?.chunkType===`reasoning`&&typeof t.reasoning==`string`)return ss(e,t);if(t?.chunkType===`tool_state`&&t.snapshotMode===`replace`&&typeof t.toolCallId==`string`&&t.toolCallId.length>0&&Number.isInteger(t.snapshotSeq)&&t.snapshotSeq>0&&typeof t.pluginState==`object`&&t.pluginState!==null&&!Array.isArray(t.pluginState))return{intents:[{kind:`updateToolState`,pluginState:t.pluginState,snapshotSeq:t.snapshotSeq,toolCallId:t.toolCallId}],state:e};if(t?.chunkType===`tools_calling`){let r=t.toolsCalling??[];return r.length===0?{intents:[],state:e}:cs(e,r,n)}return{intents:[],state:e}},us=(e,t,n)=>{let r=t.data??{},i=r.toolCallId;if(!i)return{intents:[],state:e};let a={content:r.content??``,isError:!!r.isError,kind:`resolveToolResult`,pluginState:r.pluginState,toolCallId:i},o=ns(e,t,n);return{intents:[a,...o.intents],state:o.state}},ds=(e,t)=>{let n=Qo(e);t?.model&&(n.turnModel=t.model),t?.provider&&(n.turnProvider=t.provider);let r=t?.usage;return r&&(n.turnMetadata={...n.turnMetadata,usage:r}),!t?.model&&!t?.provider&&!r?{intents:[],state:n}:{intents:[{kind:`recordUsage`,messageId:e.currentAssistantId,model:t?.model,provider:t?.provider,usage:r}],state:n}},fs=(e,t,n)=>{let r=t.type===`error`,i=r?es(e.accContent,t.data):!1,a=[],o={};i?o.content=``:e.accContent&&(o.content=e.accContent),e.accReasoning&&(o.reasoning=e.accReasoning),e.turnModel&&(o.model=e.turnModel),e.turnProvider&&(o.provider=e.turnProvider),Object.keys(o).length>0&&a.push({kind:`persistAssistant`,messageId:e.currentAssistantId,...o}),r&&a.push({clearContent:i,errorData:t.data,kind:`setError`,messageId:e.currentAssistantId});let s=Qo(e);s.accContent=``,s.accReasoning=``,s.ended=!0;let c=ns(s,t,n);return{intents:[...a,...c.intents],state:c.state}},ps=(e,t,n)=>{if(Mo(t).kind===`subagent`)return ns(e,t,n);let r=t.data??{};switch(t.type){case`stream_start`:return r?.newStep?typeof r.messageId==`string`&&r.messageId===e.currentMainMessageId?{intents:[],state:e}:is(e,r,n):as(e,r);case`stream_chunk`:return ls(e,r,n);
2case`tool_result`:return us(e,t,n);case`step_complete`:return r?.phase===`turn_metadata`?ds(e,r):{intents:[],state:e};case`agent_runtime_end`:case`error`:return fs(e,t,n);default:return{intents:[],state:e}}}})),hs,gs=e((()=>{Yo(),hs=e=>({accContent:``,accReasoning:``,currentAssistantId:e,currentMainMessageId:void 0,ended:!1,lastSpineMessageId:e,lastReasoningSnapshotSeq:0,lastTextSnapshotSeq:0,lastToolMsgIdEver:void 0,subagents:Ko(),toolState:{payloads:[],persistedIds:new Set,toolMsgIdByCallId:new Map},turnMetadata:{},turnModel:void 0,turnProvider:void 0})})),Fie=e((()=>{ms(),gs()})),_s=e((()=>{ko(),jo(),Fie(),Yo()})),vs,ys=e((()=>{Wt(),_s(),Ur(),vs=(e,{isDesktop:t=!1}={})=>e.parentRuntime?e.parentRuntime:e.heterogeneousProvider&&Oo(e.heterogeneousProvider.type)?`gateway`:e.heterogeneousProvider?Ir({boundDeviceId:e.boundDeviceId,executionTarget:e.executionTarget,heterogeneousProvider:e.heterogeneousProvider},{isHetero:!0,clientExecutionAvailable:t,workspaceScoped:e.isWorkspaceAgent})===`local`?`hetero`:`gateway`:e.isGatewayMode?`gateway`:`client`})),bs,xs,Ss=e((()=>{pa(),bs=class{listReceipts=async e=>q.agentSignal.listReceipts.query(e);rollbackReceipt=async e=>q.agentSignal.rollbackReceipt.mutate(e);emitSourceEvent=async e=>q.agentSignal.emitSourceEvent.mutate(e);emitClientGatewaySourceEvent=async e=>this.emitSourceEvent({...e,timestamp:e.timestamp??Date.now()})},xs=new bs})),Cs,ws,Ts,Es=e((()=>{Ss(),Cs=(e,t)=>`${e}:${t}:${Math.random().toString(36).slice(2,10)}`,ws=()=>{let e=(typeof window>`u`?void 0:window.global_serverConfigStore)?.getState();return!(e?.serverConfigInit&&e.featureFlags.enableAgentSelfIteration!==!0)},Ts=async e=>{if(!ws())return;let t=e.timestamp??Date.now();try{return await xs.emitClientGatewaySourceEvent({payload:e.payload,scopeKey:e.scopeKey,sourceId:e.sourceId??Cs(e.sourceType,t),sourceType:e.sourceType,timestamp:t})}catch(e){console.error(`[AgentSignal] Failed to emit client source event:`,e);return}}})),Ds,Os,ks,As,js,Ms,Ns=e((()=>{Wt(),Ne(),vr(),Gr(),qr(),Vr(),Ds=e=>!!e.deviceId||!1,Os=e=>{let t=Xr(),n=Yr.getAgencyConfigById(e)(t),r=ur().gatewayDeviceInfo?.deviceId,i=qee(n,r);return{deviceId:i,isLocalDevice:!1,targetDeviceId:i}},ks=e=>{let t=e?.workingDirectoryConfig,n=t?.git,r=n?.branch,i=ce(t)??e?.workingDirectory,a=t?.repoType??(n?.github?`github`:void 0)??`github`;if(!(!i||!r||n?.detached||a!==`github`))return{branch:r,currentConfig:t,path:i,pullRequestNumber:n?.github?.pullRequest?.number}},As=e=>!!e&&!e.ghMissing&&(e.pullRequestStatus??`ok`)===`ok`,js=e=>{if(e)return{...e.extraCount===void 0?{}:{extraPullRequestCount:e.extraCount},pullRequest:e.pullRequest??null,pullRequestStatus:e.pullRequestStatus??(e.ghMissing?`gh-missing`:`ok`)}},Ms=({branch:e,currentConfig:t,github:n,path:r,upstream:i})=>{let a=t?.path??r,o=a!==r,s={...t?.git,branch:e,github:n,isWorktree:o};return delete s.detached,o?s.activeWorktree=r:delete s.activeWorktree,i&&(s.upstream=i),{...t,git:s,path:a,repoType:`github`}}})),Ps,Fs,Is,Iie=e((()=>{Ne(),Ps=t(le()),Cre(),ka(),Ns(),Dre(),ji(),Fs=async e=>{let{isLocalDevice:t,path:n,targetDeviceId:r}=e,i=Ere.getDeviceWorkingDirs(r)(Tre()).find(e=>e.path===n||ce(e)===n)?.repoType;if(i)return i;if(t)return wre.detectRepoType(n)},Is=async(e,{agentId:t,topicId:n})=>{let r=vi.getTopicById(n)(e());if(!r)return;let i=r.metadata?.workingDirectoryConfig,a=ce(i)??r.metadata?.workingDirectory;if(!a)return;let{deviceId:o,isLocalDevice:s,targetDeviceId:c}=Os(t);if(!Ds({deviceId:o})||(i?.repoType??await Fs({isLocalDevice:s,path:a,targetDeviceId:c}))!==`github`)return;let l=await Oa.getGitBranch({deviceId:o,path:a}),u=l?.branch,d=l?.detached;if(!u||d)return;let f=await Oa.getLinkedPullRequest({branch:u,deviceId:o,path:a}),p=js(f);if(!p)return;let m=Ms({branch:u,currentConfig:i,github:p,path:a,upstream:f?.upstream??l?.upstream});(0,Ps.default)(i,m)||await e().updateTopicMetadata(n,{workingDirectoryConfig:m})}})),Ls,Rs,zs=e((()=>{Wt(),f(),Gr(),qr(),ja(),Ti(),Pe(),Ls=async(e,t)=>{},Rs=async(e,{context:t,content:n,badge:r})=>{}})),Bs,Vs,Hs,Us,Ws,Gs,Ks,qs=e((()=>{Wt(),Bs=t(F()),Es(),Iie(),zs(),wi(),Dte(),si(),ji(),Vs=(0,Bs.default)(`lobe-store:run-lifecycle`),Hs=(e,t)=>{if(t===`cancelled`)return`cancelled`;if(t===`failed`)return`failed`;if(t===`completed`||e===`done`)return`completed`;if(e===`error`||e===`interrupted`)return`failed`},Us=e=>{let{runtimeStatus:t,status:n}=e;if(t===`done`)return`success`;if(t===`error`)return`failed`;if(t===`interrupted`)return`cancelled`;if(n===`completed`)return`success`;if(n===`failed`)return`failed`;if(n===`cancelled`)return`cancelled`},Ws=(e,t,n)=>{let r=new Map(e.map(e=>[e.id,e])),i=r.get(t),a=e=>{let n=e.parentId,i=new Set;for(;n&&!i.has(n);){if(n===t)return!0;
2i.add(n),n=r.get(n)?.parentId}return!1};return e.findLast(e=>e.role===`assistant`&&a(e))?.id??(n===`assistant`&&i?.role===`assistant`?i.id:void 0)},Gs=async()=>{},Ks=(e,t)=>{let{context:n,parentMessageId:r,parentMessageType:i}=t,{agentId:a,topicId:o,threadId:s,groupId:c,workspaceSlug:l}=n,u=li(n),d=u,f=(n,c)=>{if(t.runtimeType!==`client`)return;let l=Ws(e().messagesMap[u]||[],r,i)??Ws(e().dbMessagesMap[u]||[],r,i),d=e().operations[n]?.status;Ts({payload:{agentId:a,...l?{anchorMessageId:l}:{},assistantMessageId:l,operationId:n,status:Hs(c,d),threadId:s??void 0,topicId:o??void 0,...i===`user`?{triggerMessageId:r}:{}},sourceId:`${n}:client:complete`,sourceType:`client.runtime.complete`})};return{afterUserMessagePersisted:async n=>{if(t.runScope!==`top_level`)return;let{isCreateNewTopic:r,topicId:i,assistantMessageId:o}=n;if(!i)return;Is(e,{agentId:a,topicId:i}).catch(()=>{});let s=async(t,n)=>{await e().summaryTopicTitle(t,n)},c=()=>ui.getDisplayMessagesByKey(li(n.context))(e());if(r){vi.getTopicById(i)(e())||await e().refreshTopic().catch(()=>{}),await s(i,n.messages??c());return}let l=vi.getTopicById(i)(e());l&&!l.title&&await s(i,c().filter(e=>e.id!==o))},afterRunComplete:async e=>{t.runScope},beforeRunComplete:Gs,completeRun:async r=>{let{operationId:i,runtimeStatus:s}=r,l=Us(r),u=()=>{e().completeOperation(i);let t=e().operations[i];t?.context.agentId&&e().markTopicUnread({agentId:t.context.agentId,groupId:t.context.groupId,topicId:t.context.topicId})},p=()=>{t.runtimeType===`client`&&t.runScope!==`sub_agent`&&o&&(e().activeTopicId!==o&&l===`success`||e().updateTopicStatus?.({agentId:a,groupId:c,...n.scope===`group`||n.scope===`group_agent`?{scope:n.scope}:{},status:`active`,topicId:o}))},m=e().operations[i]?.metadata?.runtimeHooks?.afterCompletionCallbacks;if(m&&m.length>0)for(let e of m)try{await e()}catch(e){console.error(`[executeClientAgent] afterCompletion callback error:`,e)}if(l===`success`&&t.runScope!==`sub_agent`){let t=e().drainQueuedMessages(d);if(t.length>0){let r=xte(t);u(),f(i,s);let a={...n},o=r.content,c=r.filesPreview.length>0?Ete(r.filesPreview):r.files.length>0?r.files.map(e=>({id:e})):void 0;return setTimeout(()=>{e().sendMessage({context:a,editorData:r.editorData,files:c,...r.forceRuntime?{forceRuntime:r.forceRuntime}:{},message:o,metadata:r.metadata}).catch(e=>{console.error(`[executeClientAgent] sendMessage for queued content failed:`,e)})},100),{requeued:!0}}}switch(l){case`success`:u();break;case`failed`:e().failOperation(i,{type:`runtime_error`,message:`Agent runtime execution failed`});break;case`cancelled`:t.runtimeType!==`client`&&e().completeOperation(i);break}return p(),f(i,s),{requeued:!1}},onRunError:Gs,onRunParked:async({operationId:t,reason:n})=>{n===`waiting_for_human`&&e().completeOperation(t)},onRunResumed:async({operationId:e,resumedOperationId:n,runId:r})=>{t.runScope!==`sub_agent`&&Vs(`run resumed (parkedOp=%s → resumeOp=%s, runId=%s)`,e,n,r)},onRunStarted:Gs,onTerminalPersisted:Gs}}})),Js,Lie=e((()=>{Wt(),pa(),Gr(),qr(),Oi(),ys(),di(),Ai(),si(),wi(),qs(),Pe(),Js=class{#e;constructor(e,t,n){this.#e=t}#t=e=>{let t=e.agentId?Rr.getAgentConfigById(e.agentId)(Xr()):void 0;return vs({boundDeviceId:t?.agencyConfig?.boundDeviceId,executionTarget:t?.agencyConfig?.executionTarget,heterogeneousProvider:t?.agencyConfig?.heterogeneousProvider,isGatewayMode:this.#e().isGatewayModeEnabled(e.agentId)})===`gateway`};#n=e=>{let{agentId:t,groupId:n,scope:r,subAgentId:i,topicId:a,threadId:o}=e;return t?pi.getOperationsByContext({agentId:t,groupId:n,scope:r,subAgentId:i,threadId:o??null,topicId:a??null})(this.#e()).filter(e=>e.type===`execServerAgentRuntime`&&e.status===`running`&&!e.metadata?.isAborting):[]};#r=e=>{let t=this.#e().operations,n=new Set,r=e,i;for(;r&&!n.has(r);){n.add(r);let e=t[r];if(i={operation:e,operationId:r},!e)break;if(e.type===`execHeterogeneousAgent`||e.type===`execServerAgentRuntime`)return{operation:e,operationId:r};r=e.parentOperationId}return i??{operationId:e}};#i=(e,t=[])=>{let n=new Map,r=e=>{for(let t of e)n.has(t.id)||n.set(t.id,t)};for(let e of Object.values(this.#e().dbMessagesMap))r(e);r(t);let i=new Set,a=e;for(;a&&!i.has(a);){i.add(a);let e=n.get(a);if(!e)return;let t=e.metadata?.trigger;if(t)return{trigger:t};a=e.parentId}};#a=e=>{let{completeOperation:t}=this.#e();for(let n of e)t(n)};#o=(e,t)=>{if(!e.topicId)return;let n=e.scope===`group`||e.scope===`group_agent`?e.scope:void 0;(this.#e().updateTopicStatus?.({agentId:e.agentId,groupId:e.groupId,...n?{scope:n}:{},status:t,topicId:e.topicId}))?.catch(e=>{console.error(`[conversationControl] updateTopicStatus failed:`,e)})};stopGenerateMessage=()=>{let{activeAgentId:e,activeTopicId:t,cancelOperations:n}=this.#e();n({type:oi,status:`running`,agentId:e,topicId:t},nn)};cancelSendMessageInServer=e=>
2{let{activeAgentId:t,activeGroupId:n,activeThreadId:r,activeTopicId:i}=this.#e(),a=li({agentId:t,groupId:n,threadId:r,topicId:e??i}),o=this.#e().operationsByContext[a]||[];if(o.forEach(e=>{let t=this.#e().operations[e];t&&t.type===`sendMessage`&&t.status===`running`&&this.#e().cancelOperation(e,`User cancelled`)}),a===li({agentId:t,groupId:n,threadId:r,topicId:i}))for(let e of[...o].reverse()){let t=this.#e().operations[e];if(t&&t.type===`sendMessage`&&t.metadata.inputEditorTempState){this.#e().mainInputEditor?.setJSONState(t.metadata.inputEditorTempState);break}}};clearSendMessageError=()=>{let{activeAgentId:e,activeGroupId:t,activeThreadId:n,activeTopicId:r}=this.#e(),i=li({agentId:e,groupId:t,threadId:n,topicId:r});(this.#e().operationsByContext[i]||[]).forEach(e=>{let t=this.#e().operations[e];t&&t.type===`sendMessage`&&t.metadata.inputSendErrorMsg&&this.#e().updateOperationMetadata(e,{inputSendErrorMsg:void 0})})};switchMessageBranch=async(e,t,n)=>{await this.#e().optimisticUpdateMessageMetadata(e,{activeBranchIndex:t},n)};#s=(e,t)=>{let{operationId:n,parentMessageId:r,runtimeType:i}=t,a=e.scope===`sub_agent`?`sub_agent`:`top_level`;Ks(this.#e,{context:e,parentMessageId:r,parentMessageType:`tool`,runId:n,runScope:a,runtimeType:i}).onRunResumed({context:e,operationId:n,resumedOperationId:n,runId:n,runScope:a,runtimeType:i})};#c=e=>{let t=this.#e().operations[e];return!!t&&t.status!==`running`};approveToolCalling=async(e,t,n)=>{let{executeClientAgent:r,startOperation:i,completeOperation:a}=this.#e(),o=n??{agentId:this.#e().activeAgentId,topicId:this.#e().activeTopicId,threadId:this.#e().activeThreadId},{agentId:s,topicId:c,threadId:l,scope:u}=o,d=ci.getDbMessageById(e)(this.#e());if(!d)return;let{operationId:f}=i({type:`approveToolCalling`,context:{...o,messageId:e}}),p={operationId:f},m=this.#t(o);m||this.#o(o,`active`),this.#s(o,{operationId:f,parentMessageId:e,runtimeType:m?`gateway`:`client`}),await this.#e().optimisticUpdateMessagePlugin(e,{intervention:{status:`approved`}},p);let h=this.#i(e);if(m){let t=d.tool_call_id;if(!t){console.warn(`[approveToolCalling][server] tool message missing tool_call_id; skipping resume`),a(f);return}let n=this.#n(o).map(e=>e.id);try{await this.#e().executeGatewayAgent({context:o,message:``,metadata:h,parentMessageId:e,resumeApproval:{decision:`approved`,parentMessageId:e,toolCallId:t}}),this.#o(o,`active`),this.#a(n),a(f)}catch(e){let t=e;console.error(`[approveToolCalling][server] Gateway resume failed:`,t),this.#e().failOperation(f,{type:`approveToolCalling`,message:t.message||`Unknown error`})}return}let g=li({agentId:s,topicId:c,threadId:l,scope:u}),_=ui.getDisplayMessagesByKey(g)(this.#e()),v=this.#i(e,_),{state:y,context:b}=this.#e().internal_createAgentState({messages:_,parentMessageId:e,agentId:s,topicId:c,threadId:l??void 0,operationId:f}),x={...b,phase:`human_approved_tool`,payload:{approvedToolCall:d.plugin,parentMessageId:e,skipCreateToolMessage:!0}};try{await r({context:o,messages:_,parentMessageId:e,parentMessageType:`tool`,initialState:y,initialContext:x,metadata:v,parentOperationId:f}),a(f)}catch(e){let t=e;console.error(`[approveToolCalling] Error executing agent runtime:`,t),this.#e().failOperation(f,{type:`approveToolCalling`,message:t.message||`Unknown error`})}};submitToolInteraction=async(e,t,n,r)=>{let{executeClientAgent:i,startOperation:a,completeOperation:o}=this.#e(),s=n??{agentId:this.#e().activeAgentId,topicId:this.#e().activeTopicId,threadId:this.#e().activeThreadId},{agentId:c,topicId:l,threadId:u,scope:d}=s,f=ci.getDbMessageById(e)(this.#e());if(!f)return;let{operationId:p}=a({type:`submitToolInteraction`,context:{...s,messageId:e}}),m={operationId:p},h=r?.createUserMessage!==!1,g=this.#t(s);g||this.#o(s,`active`),this.#s(s,{operationId:p,parentMessageId:e,runtimeType:g?`gateway`:`client`}),await this.#e().optimisticUpdateMessagePlugin(e,{intervention:{status:`approved`}},m);let _=r?.toolResultContent??`User submitted: ${JSON.stringify(t)}`;if(await this.#e().optimisticUpdateMessageContent(e,_,void 0,m),r?.pluginState&&await this.#e().optimisticUpdatePluginState(e,r.pluginState,m),g){let t=f.tool_call_id;if(!t){console.warn(`[submitToolInteraction][server] tool message missing tool_call_id; skipping resume`),o(p);return}let n=this.#i(e),i=this.#n(s).map(e=>e.id);try{await this.#e().executeGatewayAgent({context:s,message:``,metadata:n,parentMessageId:e,resumeToolResult:{content:_,parentMessageId:e,toolCallId:t,...r?.pluginState?{pluginState:r.pluginState}:{}}}),this.#o(s,`active`),this.#a(i),o(p)}catch(e){let t=e;console.error(`[submitToolInteraction][server] Gateway resume failed:`,t),this.#e().failOperation(p,{type:`submitToolInteraction`,message:t.message||`Unknown error`})}return}let v=li({agentId:c,topicId:l,threadId:u,scope:d});if(!h){let t=ui.getDisplayMessagesByKey(v)(this.#e()),n=this.#i(e,t),{state:r,context:a}=this.#e().internal_createAgentState({messages:t,parentMessageId:e,agentId:c,topicId:l,threadId:u??void 0,operationId:p}),d={...a,phase:`tool_result`,payload:{parentMessageId:e}};try{await i({context:s,messages:t,parentMessageId:e,parentMessageType:`tool`,initialState:r,initialContext:d,metadata:n,parentOperationId:p}
2),o(p)}catch(e){let t=e;console.error(`[submitToolInteraction] Error executing agent runtime:`,t),this.#e().failOperation(p,{type:`submitToolInteraction`,message:t.message||`Unknown error`})}return}let y=this.#i(e),b=Object.values(t).join(`, `),x=f.groupId,S=await this.#e().optimisticCreateMessage({agentId:c,content:b,groupId:x??void 0,...y&&{metadata:y},role:`user`,threadId:u??void 0,topicId:l??void 0},m);if(!S){this.#e().failOperation(p,{type:`submitToolInteraction`,message:`Failed to create user message`});return}if(this.#c(p))return;let C=ui.getDisplayMessagesByKey(v)(this.#e()),{state:w,context:T}=this.#e().internal_createAgentState({messages:C,parentMessageId:S.id,agentId:c,topicId:l,threadId:u??void 0,operationId:p});try{await i({context:s,messages:C,parentMessageId:S.id,parentMessageType:`user`,initialState:w,initialContext:T,metadata:y,parentOperationId:p}),o(p)}catch(e){let t=e;console.error(`[submitToolInteraction] Error executing agent runtime:`,t),this.#e().failOperation(p,{type:`submitToolInteraction`,message:t.message||`Unknown error`})}};skipToolInteraction=async(e,t,n)=>{let{executeClientAgent:r,startOperation:i,completeOperation:a}=this.#e(),o=n??{agentId:this.#e().activeAgentId,topicId:this.#e().activeTopicId,threadId:this.#e().activeThreadId},{agentId:s,topicId:c,threadId:l,scope:u}=o,d=ci.getDbMessageById(e)(this.#e());if(!d)return;let{operationId:f}=i({type:`skipToolInteraction`,context:{...o,messageId:e}}),p={operationId:f};this.#o(o,`active`),this.#s(o,{operationId:f,parentMessageId:e,runtimeType:`client`}),await this.#e().optimisticUpdateMessagePlugin(e,{intervention:{rejectedReason:t,status:`rejected`}},p);let m=t?`User skipped: ${t}`:`User skipped this question.`;if(await this.#e().optimisticUpdateMessageContent(e,m,void 0,p),this.#c(f))return;let h=li({agentId:s,topicId:c,threadId:l,scope:u}),g=this.#i(e),_=t?`I'll skip this. ${t}`:`I'll skip this.`,v=d.groupId,y=await this.#e().optimisticCreateMessage({agentId:s,content:_,groupId:v??void 0,...g&&{metadata:g},role:`user`,threadId:l??void 0,topicId:c??void 0},p);if(!y){this.#e().failOperation(f,{type:`skipToolInteraction`,message:`Failed to create user message`});return}if(this.#c(f))return;let b=ui.getDisplayMessagesByKey(h)(this.#e()),{state:x,context:S}=this.#e().internal_createAgentState({messages:b,parentMessageId:y.id,agentId:s,topicId:c,threadId:l??void 0,operationId:f});try{await r({context:o,messages:b,parentMessageId:y.id,parentMessageType:`user`,initialState:x,initialContext:S,metadata:g,parentOperationId:f}),a(f)}catch(e){let t=e;console.error(`[skipToolInteraction] Error executing agent runtime:`,t),this.#e().failOperation(f,{type:`skipToolInteraction`,message:t.message||`Unknown error`})}};cancelToolInteraction=async(e,t)=>{let{startOperation:n,completeOperation:r}=this.#e(),i=t??{agentId:this.#e().activeAgentId,topicId:this.#e().activeTopicId,threadId:this.#e().activeThreadId},{agentId:a,topicId:o,threadId:s,scope:c}=i;if(!ci.getDbMessageById(e)(this.#e()))return;let{operationId:l}=n({type:`cancelToolInteraction`,context:{agentId:a,topicId:o??void 0,threadId:s??void 0,scope:c,messageId:e}}),u={operationId:l};this.#o(i,`active`),await this.#e().optimisticUpdateMessagePlugin(e,{intervention:{rejectedReason:`User cancelled interaction`,status:`rejected`}},u),await this.#e().optimisticUpdateMessageContent(e,`User cancelled this interaction.`,void 0,u),r(l)};submitHeteroIntervention=async(e,t,n,r)=>{let i=ci.getDbMessageById(e)(this.#e());if(!i)return;let a=i.tool_call_id;if(!a){console.warn(`[submitHeteroIntervention] tool message has no tool_call_id`,e);return}let{messageOperationMap:o}=this.#e(),s=(i.parentId&&o?.[i.parentId])??o?.[e];if(!s){console.warn(`[submitHeteroIntervention] no operationId for`,e);return}let{operation:c,operationId:l}=this.#r(s),u=r??{agentId:this.#e().activeAgentId,topicId:this.#e().activeTopicId,threadId:this.#e().activeThreadId},d=!!c;d||console.warn(`[submitHeteroIntervention] operation already gone, using global-state fallback for optimistic write:`,l);let f=d?{operationId:l}:{};if(t===`submit`){await this.#e().optimisticUpdateMessagePlugin(e,{intervention:{status:`approved`}},f),await this.setInterventionAnswers(e,n??{},f);let t=`User submitted: ${JSON.stringify(n??{})}`;await this.#e().optimisticUpdateMessageContent(e,t,void 0,f)}else{let n=t===`skip`?`User skipped`:`User cancelled`;await this.#e().optimisticUpdateMessagePlugin(e,{intervention:{rejectedReason:n,status:`rejected`}},f),await this.#e().optimisticUpdateMessageContent(e,`${n} this interaction.`,void 0,f)}let p=c?.type===`execHeterogeneousAgent`;try{if(p){let{heterogeneousAgentService:e}=await Ge(async()=>{let{heterogeneousAgentService:e}=await import(`./heterogeneousAgent-DjV9GlfG.js`).then(e=>(e.r(),e.n));return{heterogeneousAgentService:e}},__vite__mapDeps([0,1,2,3]));await e.submitIntervention(t===`submit`?{operationId:l,result:n??{},toolCallId:a}:{cancelReason:`user_cancelled`,cancelled:!0,operationId:l,toolCallId:a})}else await q.aiAgent.submitHeteroIntervention.mutate(t===`submit`?{operationId:l,result:n??{},toolCallId:a}:{cancelReason:`user_cancelled`,cancelled:!0,operationId:l,toolCallId:a})}catch(e){console.error(`[submitHeteroIntervention] submitIntervention failed:`,e)}u.topicId&&this.#e().updateTopicStatus?.({agentId:u.agentId,groupId:u.groupId,status:`running`,topicId:u.topicId})};setInterventionDraft=(e,t)=>{this.#e().internal_dispatchMessage({id:e,key:`askUserDraft`,type:`updatePluginState`,value:t})};setInterventionAnswers=async(e,t,n)=>{this.#e().internal_dispatchMessage({id:e,key:`askUserAnswers`,type:`updatePluginState`,value:t},n);try{let{messageService:r}=await Ge(async()=>{let{messageService:e}=await import(`./message-D0HRzm1P.js`).then(e=>(e.t(),e.r));return{messageService:e}},__vite__mapDeps([4,1,5,6])),i=this.#e().internal_getConversationContext(n);await r.updateMessagePluginState(e,{askUserAnswers:t},i)}catch(e){console.warn(`[setInterventionAnswers] persist failed:`,e)}};rejectToolCalling=async(e,t,n)=>{let{startOperation:r,completeOperation:i}=this.#e(),a=n??{agentId:this.#e().activeAgentId,topicId:this.#e().activeTopicId,threadId:this.#e().activeThreadI
2d},{agentId:o,topicId:s,threadId:c,scope:l}=a,u=ci.getDbMessageById(e)(this.#e());if(!u)return;let{operationId:d}=r({type:`rejectToolCalling`,context:{agentId:o,topicId:s??void 0,threadId:c??void 0,scope:l,messageId:e}}),f={operationId:d},p=this.#t(a);p||this.#o(a,`active`);let m={rejectedReason:t,status:`rejected`};await this.#e().optimisticUpdateMessagePlugin(u.id,{intervention:m},f);let h=t?`User reject this tool calling with reason: ${t}`:`User reject this tool calling without reason`;await this.#e().optimisticUpdateMessageContent(e,h,void 0,f);let g=this.#i(e);if(p){let n=u.tool_call_id;if(!n){console.warn(`[rejectToolCalling][server] tool message missing tool_call_id; skipping resume`),i(d);return}let r=this.#n(a).map(e=>e.id);this.#s(a,{operationId:d,parentMessageId:e,runtimeType:`gateway`});try{await this.#e().executeGatewayAgent({context:a,message:``,metadata:g,parentMessageId:e,resumeApproval:{decision:`rejected_continue`,parentMessageId:e,rejectionReason:t,toolCallId:n}}),this.#o(a,`active`),this.#a(r)}catch(e){console.error(`[rejectToolCalling][server] Gateway resume failed:`,e)}}i(d)};rejectAndContinueToolCalling=async(e,t,n)=>{let r=ci.getDbMessageById(e)(this.#e());if(!r)return;let{executeClientAgent:i,startOperation:a,completeOperation:o}=this.#e(),s=n??{agentId:this.#e().activeAgentId,topicId:this.#e().activeTopicId,threadId:this.#e().activeThreadId},{agentId:c,topicId:l,threadId:u,scope:d}=s;if(this.#t(s)){let n=this.#i(e),i=r.tool_call_id;if(!i){console.warn(`[rejectAndContinueToolCalling][server] tool message missing tool_call_id; skipping resume`);return}let f=this.#n(s).map(e=>e.id),{operationId:p}=a({type:`rejectToolCalling`,context:{agentId:c,topicId:l??void 0,threadId:u??void 0,scope:d,messageId:e}}),m={operationId:p};this.#s(s,{operationId:p,parentMessageId:e,runtimeType:`gateway`}),await this.#e().optimisticUpdateMessagePlugin(e,{intervention:{rejectedReason:t,status:`rejected`}},m);let h=t?`User reject this tool calling with reason: ${t}`:`User reject this tool calling without reason`;await this.#e().optimisticUpdateMessageContent(e,h,void 0,m);try{await this.#e().executeGatewayAgent({context:s,message:``,metadata:n,parentMessageId:e,resumeApproval:{decision:`rejected_continue`,parentMessageId:e,rejectionReason:t,toolCallId:i}}),this.#o(s,`active`),this.#a(f),o(p)}catch(e){let t=e;console.error(`[rejectAndContinueToolCalling][server] Gateway resume failed:`,t),this.#e().failOperation(p,{type:`rejectToolCalling`,message:t.message||`Unknown error`})}return}await this.#e().rejectToolCalling(e,t,n);let{operationId:f}=a({type:`rejectToolCalling`,context:{agentId:c,topicId:l??void 0,threadId:u??void 0,scope:d,messageId:e}});this.#s(s,{operationId:f,parentMessageId:e,runtimeType:`client`});let p=li({agentId:c,topicId:l,threadId:u,scope:d}),m=ui.getDisplayMessagesByKey(p)(this.#e()),h=this.#i(e,m),{state:g,context:_}=this.#e().internal_createAgentState({messages:m,parentMessageId:e,agentId:c,topicId:l,threadId:u??void 0,operationId:f}),v={..._,phase:`user_input`};try{await i({context:s,messages:m,parentMessageId:e,parentMessageType:`tool`,initialState:g,initialContext:v,metadata:h,parentOperationId:f}),o(f)}catch(e){let t=e;console.error(`[rejectAndContinueToolCalling] Error executing agent runtime:`,t),this.#e().failOperation(f,{type:`rejectToolCalling`,message:t.message||`Unknown error`})}}}})),Ys,Xs=e((()=>{Ys=`You have Agent Management tools to create, configure, and orchestrate AI agents. Your primary responsibility is to help users build and manage their agent ecosystem effectively.
3
4<core_capabilities>
5## Tool Overview
6
7**Agent CRUD:**
8- **createAgent**: Create a new agent with custom configuration (title, description, systemRole, model, provider, plugins, avatar, etc.)
9- **updateAgent**: Modify an existing agent's settings
10- **deleteAgent**: Remove an agent from the workspace
11- **getAgentDetail**: Retrieve the full configuration and metadata of an agent
12- **duplicateAgent**: Create a copy of an existing agent
13
14**Discovery:**
15- **searchAgent**: Find agents in user's workspace or marketplace
16
17**Prompt:**
18- **updatePrompt**: Update an agent's system prompt directly (preferred over updateAgent when only changing the prompt)
19
20**Plugin Management:**
21- **installPlugin**: Install a plugin/tool for an agent (builtin, Composio, LobehubSkill, or MCP marketplace)
22
23**Execution:**
24- **callAgent**: Invoke an agent to handle a task (synchronously or as async background task)
25</core_capabilities>
26
27<context_injection>
28## Available Resources
29
30When this tool is enabled, you will receive contextual information about:
31- **Current Agent**: Your own agent ID (in the \`<current_agent>\` tag). Use this ID to manage yourself when the user asks to modify your settings.
32- **Available Models**: List of AI models and providers you can use when creating/updating agents
33- **Available Agents**: The user's existing agents (most recently updated). You can call them directly via callAgent without first running searchAgent when one of them clearly matches the user's request.
34- **Available Plugins**: List of plugins (builtin tools, Composio integrations, LobehubSkill providers) you can enable for agents
35
36This information is automatically injected into the conversation context. Use the exact IDs from the context when specifying model/provider/plugins/agentId parameters. If none of the agents in the \`available_agents\` section match the user's intent, fall back to searchAgent (which can also search the marketplace).
37</context_injection>
38
39<self_management>
40## Self-Management
41
42You can manage yourself using the same Agent Management tools. Your own agent ID is provided in the \`<current_agent>\` tag in the injected context.
43
44**When the user asks to modify YOUR settings** (e.g., "change your model", "add search plugin to you", "update your system prompt"), use your own agent ID with:
45- **getAgentDetail**: Check your current configuration
46- **updatePrompt**: Update your system prompt (preferred for prompt-only changes)
47- **updateAgent**: Change your model, provider, or other config/meta fields
48- **installPlugin**: Add new plugins/tools to yourself
49- **duplicateAgent**: Create a copy of yourself
50
51**Tool selection for prompt changes**: When only the system prompt needs updating, always use \`updatePrompt\` instead of \`updateAgent\`. It takes a flat \`prompt\` string parameter (no nested config object), which is simpler and avoids serialization issues.
52
53**Priority rule**: When the user wants to modify the current agent, always use the Agent Management tools first. Only fall back to other tools (e.g., Agent Builder) if the Agent Management tools cannot fulfill the request.
54
55**IMPORTANT**: Never use callAgent with your own agent ID — this would create an infinite loop.
56</self_management>
57
58<agent_creation_guide>
59## Creating Effective Agents
60
61When creating an agent using createAgent, you can specify:
62
63### 1. Basic Information (Required)
64- **title** (required): Clear, concise name that reflects the agent's purpose
65- **description** (optional): Brief summary of capabilities and use cases
66
67### 2. System Prompt (systemRole)
68The system prompt is the most important element. A good system prompt should:
69- Define the agent's role and expertise
70- Specify the communication style and tone
71- Include constraints and guidelines
72- Provide examples when helpful
73
74**Example structure:**
75\`\`\`
76You are a [role] specialized in [domain].
77
78## Core Responsibilities
79- [Responsibility 1]
80- [Responsibility 2]
81
82## Guidelines
83- [Guideline 1]
84- [Guideline 2]
85
86## Response Format
87[How to structure responses]
88\`\`\`
89
90### 3. Model & Provider Selection
91
92**CRITICAL: You MUST select from the available models and providers listed in the injected context above. Do NOT use models that are not explicitly listed.**
93
94When selecting a model, follow this priority order:
95
961. **First Priority - LobeHub Provider Models**:
97   - If available, prioritize models from the "lobehub" provider
98   - These are optimized for the LobeHub ecosystem
99
1002. **Second Priority - Premium Frontier Models**:
101   - **Anthropic**: Claude Sonnet 4.5, Claude Opus 4.5, or newer Opus/Sonnet series
102   - **OpenAI**: GPT-5 or higher (exclude mini variants)
103   - **Google**: Gemini 2.5 Pro or newer versions
104
1053. **Third Priority - Standard Models**:
106   - If none of the above are available, choose from other enabled models based on task requirements
107   - Consider model capabilities (reasoning, vision, function calling) from the injected context
108
109**Task-Based Recommendations**:
110- **Complex reasoning, analysis**: Choose models with strong reasoning capabilities
111- **Fast, simple tasks**: Choose lighter models for cost-effectiveness
112- **Multimodal tasks**: Ensure the model supports vision/video if needed
113- **Tool use**: Verify function calling support for agents using plugins
114
115**IMPORTANT:** Always specify both \`model\` and \`provider\` parameters together using the exact IDs from the injected context.
116
117### 4. Plugins (Optional)
118You can specify plugins during agent creation using the \`plugins\` parameter:
119- **plugins**: Array of plugin identifiers (e.g., ["lobe-image-designer", "search-engine"])
120
121**Plugin types available:**
122- **Builtin tools**: Core system tools (e.g., web search, image generation)
123- **Composio integrations**: Third-party service integrations requiring OAuth
124- **LobehubSkill providers**: Advanced skill providers
125
126Refer to the injected context for available plugin IDs and descriptions.
127
128### 5. Visual Customization (Optional)
129- **avatar**: Emoji or image URL (e.g., "🤖")
130- **backgroundColor**: Hex color code (e.g., "#3B82F6")
131- **tags**: Array of tags for categorization (e.g., ["coding", "assistant"])
132
133### 6. User Experience (Optional)
134- **openingMessage**: Welcome message displayed when starting a new conversation
135- **openingQuestions**: Array of suggested questions to help users start (e.g., ["What can you help me with?"])
136</agent_creation_guide>
137
138<agent_detail_guide>
139## Getting Agent Details
140
141Use getAgentDetail to inspect an agent's full configuration before making decisions:
142
143**When to use:**
144- Before calling an agent, to understand its capabilities
145- Before updating an agent, to see current settings
146- To check what model, plugins, or system prompt an agent uses
147
148\`\`\`
149getAgentDetail(agentId)
150\`\`\`
151
152Returns the agent's complete configuration including system prompt, model, provider, plugins, and metadata.
153</agent_detail_guide>
154
155<duplicate_guide>
156## Duplicating Agents
157
158Use duplicateAgent to create a copy of an existing agent:
159
160**When to use:**
161- Creating a variant of an existing agent with slight modifications
162- Backing up an agent before making major changes
163- Using an existing agent as a template
164
165\`\`\`
166duplicateAgent(agentId, newTitle?)
167\`\`\`
168
169The duplicated agent inherits all configuration from the original. After duplication, use updateAgent to customize the copy.
170</duplicate_guide>
171
172<install_plugin_guide>
173## Installing Plugins
174
175Use installPlugin to add tools/plugins to an agent:
176
177**Plugin Sources:**
178- **official**: Builtin tools (e.g., web search, code sandbox), Composio integrations (e.g., Gmail, Google Calendar), and LobehubSkill providers
179- **market**: MCP marketplace plugins
180
181\`\`\`
182installPlugin(agentId, identifier, source)
183\`\`\`
184
185**Notes:**
186- Some official plugins (Composio, LobehubSkill) may require OAuth authorization
187- Use the available plugins from the injected context to find valid plugin identifiers
188- After installation, the plugin is automatically enabled for the specified agent
189</install_plugin_guide>
190
191<search_guide>
192## Finding the Right Agent
193
194Use searchAgent to discover agents:
195
196**User Agents** (source: 'user'):
197- Your personally created agents
198- Previously used marketplace agents
199
200**Marketplace Agents** (source: 'market'):
201- Community-created agents
202- Professional templates
203- Specialized tools
204
205**Search Tips:**
206- Use specific keywords related to the task
207- Filter by category when browsing marketplace
208- Check agent descriptions for capability details
209</search_guide>
210
211<execution_guide>
212## Calling Agents
213
214### Synchronous Call (default)
215For quick responses in the conversation context:
216\`\`\`
217callAgent(agentId, instruction)
218\`\`\`
219The agent will respond directly in the current conversation.
220
221### Asynchronous Task
222For longer operations that benefit from focused execution:
223\`\`\`
224callAgent(agentId, instruction, runAsTask: true, taskTitle: "Brief description")
225\`\`\`
226The agent will work in the background and return results upon completion.
227
228**When to use runAsTask:**
229- Complex multi-step operations
230- Tasks requiring extended processing time
231- Work that shouldn't block the conversation flow
232- Operations that benefit from isolated execution context
233</execution_guide>
234
235<workflow_patterns>
236## Common Workflows
237
238### Pattern 1: Create with Full Configuration
2391. Review available models and plugins from injected context
2402. Create agent with complete configuration (title, systemRole, model, provider, plugins)
2413. Test the agent with sample tasks
242
243### Pattern 2: Create and Refine
2441. Create agent with basic configuration (title, systemRole, model, provider)
2452. Test with sample tasks
2463. Update configuration based on results (add plugins, adjust settings)
247
248### Pattern 3: Find and Use
2491. Search for existing agents (workspace or marketplace)
2502. Select the best match for the task
2513. Call agent with specific instruction
252
253### Pattern 4: Create, Call, and Iterate
2541. Create a specialized agent for a specific task
2552. Immediately call the agent to execute the task
2563. Refine agent configuration based on results
257
258### Pattern 5: Inspect and Decide
2591. Use getAgentDetail to inspect an agent's current configuration
2602. Decide whether to call it, update it, or duplicate it based on the details
261
262### Pattern 6: Duplicate and Customize
2631. Find an existing agent that's close to what's needed
2642. Use duplicateAgent to create a copy
2653. Use updateAgent to customize the copy for the new use case
266
267### Pattern 7: Equip with Plugins
2681. Create or select an agent
2692. Use installPlugin to add necessary tools/integrations
2703. Call the agent with instructions that leverage the installed plugins
271</workflow_patterns>
272
273<agent_card_rendering>
274## Rendering Agent Cards
275
276After successfully creating, duplicating, or finding an agent, render a clickable agent card by outputting a \`<lobeAgents>\` tag. This card appears inline in the conversation and lets the user navigate directly to the agent.
277
278**Format:**
279\`\`\`
280<lobeAgents identifier="{agentId}" title="{title}" description="{description}" avatar="{avatar}" backgroundColor="{backgroundColor}" />
281\`\`\`
282
283**Attribute rules:**
284- **identifier** (required): Use \`agentId\` from the tool result
285- **title** (required): The agent's display name
286- **description** (optional): Brief description of the agent
287- **avatar** (optional): Emoji or image URL used for the agent
288- **backgroundColor** (optional): The agent's background color
289
290**When to render:**
291- After **createAgent** succeeds → render a card for the newly created agent
292- After **duplicateAgent** succeeds → render a card for the duplicated agent
293- After **searchAgent** returns results → render a card for each relevant agent found (up to 5)
294
295**Example — after createAgent:**
296\`\`\`
297I've created your coding assistant agent.
298
299<lobeAgents identifier="session-abc123" title="Coding Assistant" description="Expert in TypeScript and React" avatar="💻" backgroundColor="#3B82F6" />
300\`\`\`
301
302Do NOT render a card when calling \`getAgentDetail\`, \`updateAgent\`, \`updatePrompt\`, \`deleteAgent\`, or \`installPlugin\`.
303</agent_card_rendering>
304
305<best_practices>
306## Best Practices
307
3081. **Use Context Information**: Always refer to the injected context for accurate model IDs, provider IDs, and plugin IDs
3092. **Specify Model AND Provider**: When setting a model, always specify both \`model\` and \`provider\` together
3103. **Start with Essential Config**: Begin with title, systemRole, model, and provider. Add plugins and other settings as needed
3114. **Clear Instructions**: When calling agents, be specific about expected outcomes and deliverables
3125. **Right Tool for the Job**: Match agent capabilities (model, plugins) to task requirements
3136. **Meaningful Metadata**: Use descriptive titles, tags, and descriptions for easy discovery
3147. **Test and Iterate**: Test agents with sample tasks and refine configuration based on actual usage
3158. **Plugin Selection**: Only enable plugins that are relevant to the agent's purpose to avoid unnecessary overhead
316</best_practices>`})),Zs,Qs,$s=e((()=>{Zs=`lobe-agent-management`,Qs={callAgent:`callAgent`,createAgent:`createAgent`,deleteAgent:`deleteAgent`,duplicateAgent:`duplicateAgent`,getAgentDetail:`getAgentDetail`,installPlugin:`installPlugin`,searchAgent:`searchAgent`,updateAgent:`updateAgent`,updatePrompt:`updatePrompt`}})),ec,tc=e((()=>{Xs(),$s(),ec={api:[{description:`Create a new AI agent with custom configuration. The agent will be added to your workspace and can be used for c
316onversations or tasks.`,name:Qs.createAgent,parameters:{properties:{title:{description:`The display name for the agent (required)`,type:`string`},description:{description:`A brief description of what the agent does`,type:`string`},systemRole:{description:`The system prompt that defines the agent's personality, expertise, and behavior. This is the core instruction for the agent.`,type:`string`},avatar:{description:`Agent avatar (emoji like "🤖" or image URL)`,type:`string`},backgroundColor:{description:`Background color for the agent card (hex color code)`,type:`string`},model:{description:`The AI model to use (e.g., "gpt-4o", "gpt-4o-mini", "claude-3-5-sonnet-20241022")`,type:`string`},provider:{description:`The AI provider (e.g., "openai", "anthropic", "google")`,type:`string`},plugins:{description:`Array of plugin identifiers to enable for this agent`,items:{type:`string`},type:`array`},openingMessage:{description:`Welcome message displayed when starting a new conversation`,type:`string`},openingQuestions:{description:`Suggested questions to help users start the conversation`,items:{type:`string`},type:`array`},tags:{description:`Tags for categorizing the agent`,items:{type:`string`},type:`array`}},required:[`title`],type:`object`}},{description:`Update an existing agent configuration. Only include fields you want to change.`,name:Qs.updateAgent,parameters:{properties:{agentId:{description:`The ID of the agent to update`,type:`string`},config:{description:`Partial agent configuration to update`,properties:{model:{description:`The AI model to use`,type:`string`},provider:{description:`The AI provider`,type:`string`},systemRole:{description:`The system prompt`,type:`string`},plugins:{description:`Array of enabled plugin identifiers`,items:{type:`string`},type:`array`},openingMessage:{description:`Opening message for new conversations`,type:`string`},openingQuestions:{description:`Suggested opening questions`,items:{type:`string`},type:`array`}},type:`object`},meta:{description:`Partial metadata to update`,properties:{title:{description:`Agent display name`,type:`string`},description:{description:`Agent description`,type:`string`},avatar:{description:`Agent avatar`,type:`string`},backgroundColor:{description:`Background color`,type:`string`},tags:{description:`Tags for categorization`,items:{type:`string`},type:`array`}},type:`object`}},required:[`agentId`],type:`object`}},{description:`Delete an agent from your workspace. This action cannot be undone. The agent and its associated session will be removed.`,humanIntervention:`required`,name:Qs.deleteAgent,parameters:{properties:{agentId:{description:`The ID of the agent to delete`,type:`string`}},required:[`agentId`],type:`object`}},{description:`Get the detailed configuration and metadata of an agent, including its system prompt, model, provider, plugins, and other settings. For heterogeneous agents (external CLI/runtime such as Claude Code or Codex) the result also describes the external runtime and its capabilities (filesystem/shell access, where it runs) — use this to judge whether the agent can carry out coding/software-engineering tasks.`,name:Qs.getAgentDetail,parameters:{properties:{agentId:{description:`The ID of the agent to get details for`,type:`string`}},required:[`agentId`],type:`object`}},{description:`Duplicate an existing agent to create a copy with the same configuration. Optionally provide a new title for the duplicated agent.`,name:Qs.duplicateAgent,parameters:{properties:{agentId:{description:`The ID of the agent to duplicate`,type:`string`},newTitle:{description:`Optional new title for the duplicated agent. If not provided, the original title with a "Copy" suffix will be used.`,type:`string`}},required:[`agentId`],type:`object`}},{description:`Install a plugin/tool for an agent. Use 'official' source for builtin tools, Composio integrations, and LobehubSkill providers. Use 'market' source for MCP marketplace plugins.`,name:Qs.installPlugin,parameters:{properties:{agentId:{description:`The ID of the agent to install the plugin for`,type:`string`},identifier:{description:`The plugin identifier to install`,type:`string`},source:{description:`Plugin source: 'official' (builtin tools, Composio, LobehubSkill) or 'market' (MCP marketplace)`,enum:[`official`,`market`],type:`string`}},required:[`agentId`,`identifier`,`source`],type:`object`}},{description:`Update an agent's system prompt. Use this instead of updateAgent when you only need to change the system prompt — it's simpler, avoids nested config objects, and clears stale editor data automatically.`,name:Qs.updatePrompt,parameters:{properties:{agentId:{description:`The ID of the agent to update the prompt for`,type:`string`},prompt:{description:`The new system prompt content`,type:`string`}},required:[`agentId`,`prompt`],type:`object`}},{description:"Search for agents in your workspace or the marketplace. Use 'user' source to find your own agents, 'market' for marketplace agents, or 'all' for both. Results are paginated: the response reports the real total, and you can page through workspace agents with 'offset'. Each result carries an `origin` (workspace/market) and, for heterogeneous agents, a `heteroType` (e.g. claude-code, codex) — those are backed by an external CLI/device runtime and can execute coding/agentic tasks directly, so you can hand a task to them without further setup.",name:Qs.searchAgent,parameters:{properties:{keyword:{description:`Search keywords to find agents by name or description`,type:`string`},source:{description:`Where to search: 'user' (your agents), 'market' (marketplace), 'all' (both). Default: 'all'`,enum:[`user`,`market`,`all`],type:`string`},category:{description:`Category filter for marketplace search (e.g., "programming", "writing", "translation")`,type:`string`},limit:{default:10,description:`Maximum number of results to return (default: 10, max: 20)`,type:`number`},offset:{default:0,description:`Number of workspace agents to skip, for pagination (e.g. offset=20 with limit=20 returns agents 21-40). Not applied to marketplace results.`,type:`number`}},required:[],type:`object`}},{description:`Call an agent to handle a specific task or respond to an instruction. Can run synchronously (immediate response) or as a background task for longer operations.`,name:Qs.callAgent,parameters:{properties:{agentId:{description:`The ID of the agent to call`,type:`string`},instruction:{description:`The instruction or task for the agent to execute. Be specific about expected deliverables.`,type:`string`},runAsTask:{default:!1,description:`If true, run as a background task for longer operations. The agent will work asynchronously and return results upon completion.`,type:`boolean`},taskTitle:{description:`Brief title for the task (shown in UI). Required when runAsTask is true.`,type:`string`},timeout:{default:18e5,description:`Maximum time in milliseconds to wait for task completion (default: 1800000 = 30 minutes). Only applies when runAsTask is true.`,type:`number`},skipCallSupervisor:{default:!1,description:`If true (and in a group context), the orchestration will end after this agent responds, without calling the supervisor again. Only relevant when used within agent groups.`,type:`boolean`}},required:[`agentId`,`instruction`],type:`object`}}],identifier:Zs,meta:{avatar:`🤖`,description:`Create, manage, and orchestrate AI agents`,title:`Agent Management`},systemRole:Ys,type:`builtin`}})),nc,rc,Rie=e((()=>{tc(),$s(),nc=`You have a callAgent tool to delegate tasks to other AI agents.
317
318<execution_guide>
319### Synchronous Call (default)
320callAgent(agentId, instruction) — agent responds directly in conversation.
321
322### Asynchronous Task
323callAgent(agentId, instruction, runAsTask: true, taskTitle: "...") — agent works in background.
324Use runAsTask for complex/long operations that shouldn't block conversation.
325</execution_guide>`,rc=()=>{let e=ec.api.find(e=>e.name===Qs.callAgent);if(!e)throw Error(`callAgent API not found in AgentManagementManifest`);return{api:[{description:e.description,name:e.name,parameters:e.parameters}],identifier:Zs,meta:{description:`Delegate tasks to other agents`,title:`Agent Management`},systemRole:nc,type:`builtin`}}}
325)),ic=e((()=>{Rie(),tc(),Xs(),$s()})),ac,oc,sc=e((()=>{Na(),Fa(),ha(),ac=class{sendMessageInServer=async(e,t)=>{let{agentId:n,newUserMessage:r,newAssistantMessage:i,newTopic:a,topicId:o,threadId:s}=e,c=n,l=o,u=!1;if(!l){let e=a?.title||(typeof r.content==`string`?r.content.slice(0,30):`新话题`);l=await Pa.createTopic({sessionId:c,title:e,favorite:!1}),u=!0}let d=typeof r.content==`string`?r.content:JSON.stringify(r.content),f=await Ma.createMessage({sessionId:c,topicId:l,role:`user`,content:d,...s?{threadId:s}:{}}),p=await Ma.createMessage({sessionId:c,topicId:l,role:`assistant`,content:``,model:i?.model,...s?{threadId:s}:{}}),m=await Pa.getTopics({agentId:c,pageSize:50});return{topicId:l,isCreateNewTopic:u,topics:m,userMessageId:f.id,assistantMessageId:p.id,messages:[f,p]}};generateJSON=async(e,t)=>ga(`/ai/v1/chat/completions`,{method:`POST`,body:JSON.stringify({...e,stream:!1}),signal:t?.signal});recordTracingFeedback=async e=>{}},oc=new ac})),cc,lc=e((()=>{v(),cc=async e=>{let t;try{let n=await e.json();t={body:n.body,message:h(`response.${n.errorType}`,{ns:`error`}),type:n.errorType}}catch{t={message:h(`response.${e.status}`,{ns:`error`}),type:e.status}}return t}})),uc,dc,fc,pc,zie=e((()=>{Wt(),We(),Ne(),Ore(),S(),lc(),uc=10,dc=e=>{let{startSpeed:t=uc}=e,n=``,r=[],i=!1,a=null,o=0,s=0,c=t,l=0;return{flushQueue:()=>{if(r.length===0)return;let t=r.splice(0).join(``);n+=t,e.onTextUpdate(t,n)},isAnimationActive:i,isTokenRemain:()=>r.length>0,pushToQueue:e=>{r.push(...e.split(``))},startAnimation:(u=t)=>new Promise(t=>{if(i){t();return}i=!0,o=performance.now(),s=0,c=u,l=0;let d=f=>{if(!i){a!==null&&cancelAnimationFrame(a),t();return}let p=f-o;o=f,s+=p;let m=0;if(r.length>0){let e=Math.max(u,r.length),t=Math.abs(r.length-l)*8e-4+.005;c+=(e-c)*t,m=Math.floor(s*c/1e3)}if(m>0){s-=m*1e3/c;let t=Math.min(m,r.length),i=r.splice(0,t).join(``);n+=i,e.onTextUpdate(i,n)}l=r.length,r.length>0&&i?a=requestAnimationFrame(d):(i=!1,a=null,t())};a=requestAnimationFrame(d)}),stopAnimation:()=>{i=!1,a!==null&&(cancelAnimationFrame(a),a=null)}}},fc=e=>typeof e==`object`?e:{text:e},pc=async(e,t={})=>{let n,r=!1,i=`done`,a,o=Date.now(),{text:s,speed:c}=fc(t.responseAnimation??{}),l=s===`none`,u=s===`smooth`,d=``,f=null,p=()=>{d&&=(t.onMessageHandle?.({text:d,type:`text`}),``)},m=``,h=dc({onTextUpdate:(e,n)=>{m=n,t.onMessageHandle?.({text:e,type:`text`})},startSpeed:c}),g=``,_,v=dc({onTextUpdate:(e,n)=>{g=n,t.onMessageHandle?.({text:e,type:`reasoning`})},startSpeed:c}),y=``,b=null,x=()=>{y&&=(t.onMessageHandle?.({text:y,type:`reasoning`}),``)},S,C,w=[],T;if(await Ia(e,{body:t.body,fetch:t?.fetcher,headers:t.headers,method:t.method,onerror:e=>{if(e===`canceled`||e.name===`AbortError`)i=`abort`,t?.onAbort?.(m),h.stopAnimation();else{i=`error`;let n=Date.now()-o,r=typeof navigator<`u`?navigator.onLine:void 0,a={...t.requestContext,elapsedMs:n,networkStatus:r};t.onErrorHandle?.(e.type?e:{body:{message:e.message,name:e.name,...a},message:e.message,type:be.UnknownChatFetchError});return}},onmessage:e=>{if(r=!0,typeof e.data==`string`&&e.data.trim()===`[DONE]`){i=`stop`;return}let a;try{a=JSON.parse(e.data)}catch(n){console.warn(`parse error:`,n),t.onErrorHandle?.({body:{context:{chunk:e.data,error:{message:n.message,name:n.name}},message:`chat response streaming chunk parse error, please contact your API Provider to fix it.`},message:`parse error`,type:`StreamChunkError`});return}let o=e=>{e&&(l?(m+=e,t.onMessageHandle?.({text:e,type:`text`})):u?(h.pushToQueue(e),h.isAnimationActive||h.startAnimation()):(m+=e,d+=e,f||=setTimeout(()=>{p(),f=null},300)))},s=e=>{u?(v.pushToQueue(e),v.isAnimationActive||v.startAnimation()):(g+=e,y+=e,b||=setTimeout(()=>{x(),b=null},300))};switch(e.event){case`error`:i=`error`,t.onErrorHandle?.(a);break;case`base64_image`:{let e=`tmp_img_`+ke(),n={data:a,id:e,isBase64:!0};w.push(n),t.onMessageHandle?.({id:e,image:n,images:w,type:`base64_image`});break}case`text`:o(a);break;case`usage`:C=a,t.onMessageHandle?.({type:`usage`,usage:a});break;case`speed`:T=a,t.onMessageHandle?.({speed:a,type:`speed`});break;case`grounding`:S=a,t.onMessageHandle?.({grounding:a,type:`grounding`});break;case`reasoning_signature`:_=a;break;case`stop`:t.onMessageHandle?.({reason:a,type:`stop`});break;case`reasoning`:s(a);break;
325case`reasoning_part`:a.partType===`text`&&a.content&&(g+=a.content),t.onMessageHandle?.({content:a.content,mimeType:a.mimeType,partType:a.partType,thoughtSignature:a.thoughtSignature,type:e.event});break;case`content_part`:a.partType===`text`&&a.content&&(m+=a.content),t.onMessageHandle?.({content:a.content,mimeType:a.mimeType,partType:a.partType,thoughtSignature:a.thoughtSignature,type:e.event});break;case`tool_calls`:n||=[],n=je(n,a),t.onMessageHandle?.({tool_calls:n,type:`tool_calls`});break;default:{if(!a||typeof a!=`object`)break;let e=a,r=e.choices?.[0],c=r?.delta;r?.finish_reason===`stop`&&(i=`stop`),c?.reasoning_content&&s(c.reasoning_content),c?.content&&o(c.content),c?.tool_calls&&(n||=[],n=je(n,c.tool_calls),t.onMessageHandle?.({tool_calls:n,type:`tool_calls`})),e.usage&&(C=e.usage,t.onMessageHandle?.({type:`usage`,usage:e.usage}));break}}},onopen:async e=>{if(a=e.clone(),!a.ok)throw await cc(e)},signal:t.signal}),a&&(h.stopAnimation(),v.stopAnimation(),f&&(clearTimeout(f),p()),b&&(clearTimeout(b),x()),a.ok)){r||(m=await a.clone().text(),t.onMessageHandle?.({text:m,type:`text`}));let e=a.headers.get(St),o=a.headers.get(an);h.flushQueue(),v.flushQueue(),await t?.onFinish?.(m,{grounding:S,images:w.length>0?w:void 0,observationId:o,reasoning:g?{content:g,signature:_}:void 0,speed:T,toolCalls:n,traceId:e,type:i,usage:C})}return a}})),Bie=e((()=>{})),Vie=e((()=>{})),mc=e((()=>{zie(),Bie(),lc(),Vie()})),hc,gc=e((()=>{Gr(),qr(),Ba(),Ra(),hc=(e,t,n)=>{let r=Xr(),i=n||r.activeAgentId||``,a=Hr.getChatConfigById(i)(r),o=za(),s=a.searchMode!==`off`,c=Va.isProviderHasBuiltinSearch(t)(o),l=La.isModelHasBuiltinSearch(e,t)(o),u=La.isModelBuiltinSearchInternal(e,t)(o),d=(c||l)&&a.useModelBuiltinSearch||u||!1;return{enabledSearch:s,isModelHasBuiltinSearch:l,isProviderHasBuiltinSearch:c,useApplicationBuiltinSearchTool:s&&!d,useModelSearch:d}}})),_c,vc=e((()=>{Ba(),_c=(e,t)=>{let n=za();return Va.isInitAiProviderRuntimeState(n)?La.isModelSupportToolUse(e,t)(n)||!1:!0}})),yc=n({getChatStoreState:()=>Q9,useChatStore:()=>Z9}),bc=e((()=>{$9()})),xc,Sc,Cc,wc,Tc,Ec,Dc,Oc,kc=e((()=>{xc=(e,t)=>e?.find(e=>e.identifier===t),Sc=e=>e?.title,Cc=e=>e?.description,wc=e=>e?.tags,Tc=e=>e?.avatar||`🧩`,Ec=(e,t)=>t.some(t=>t.identifier===e&&t.type===`customPlugin`),Dc=e=>e?.properties&&Object.keys(e.properties).length>0,Oc={getPluginAvatar:Tc,getPluginDesc:Cc,getPluginFormList:xc,getPluginTags:wc,getPluginTitle:Sc,isCustomPlugin:Ec,isSettingSchemaNonEmpty:Dc}})),Hie,Uie=e((()=>{Hie={agentDocumentSkills:[],agentDocumentSkillsAgentId:void 0}})),Wie,Gie=e((()=>{Wie={agentSkillDetailMap:{},agentSkills:[],agentSkillsLoading:!1}})),Kie,qie=e((()=>{Kie=`<agent_browser_guides>
326# agent-browser
327
328\`agent-browser\` is a fast browser automation CLI for AI agents — drives Chrome/Chromium via CDP and serves accessibility-tree snapshots with compact \`@eN\` element refs (so you act on the page in a few hundred tokens, not raw HTML).
329
330\`agent-browser\` and Chrome are pre-installed — no setup needed.
331
332## The core loop
333
334\`\`\`bash
335agent-browser open example.com
336agent-browser snapshot -i                 # accessibility tree with interactive refs (@e1, @e2, …)
337agent-browser click @e2                   # click by ref
338agent-browser fill @e3 "[email protected]" # clear and fill by ref
339agent-browser get text @e1                # get text by ref
340agent-browser screenshot page.png
341agent-browser close
342\`\`\`
343
344Refs become **stale on every page change** (click that navigates, form submit, dynamic re-render, dialog open). Always re-snapshot before the next ref interaction.
345
346If a page opens to an empty body or a verification/challenge screen, treat it as a block, not a slow load — go straight to the real-Chrome step below.
347
348If a page requires signing in (a login form, an account/password wall, or an OTP/verification step you have no credentials for), don't guess credentials or engineer a way around the gate. Open it in a visible browser — the real-Chrome CDP window below is one — ask the user to sign in themselves in that window, and continue once they confirm.
349
350When the task is done — every time, as the final step and without waiting to be asked — run \`agent-browser close\` and quit any Chrome you lau
350nched for CDP. A browser you opened for the task otherwise keeps running on the user's machine. See the teardown rule below for how to quit the CDP Chrome without touching the user's own browser.
351
352## Blocked pages — escalate to real Chrome
353
354Empty body, verification screen, or obfuscated JS means the page is **blocked, not loading**. This is a binary decision: got real text → proceed; no text → switch to real Chrome immediately.
355
3561. **Verify once** — \`agent-browser open <url>\`, then \`agent-browser wait --fn "document.body.innerText.length > 100" --timeout 3000\`. If it succeeds, page is usable — continue.
3572. **Timed out → launch real Chrome over CDP.** Its human fingerprint bypasses JS challenges:
358   \`\`\`bash
359   # macOS (Linux: use \`google-chrome\`)
360   "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" \\
361     --remote-debugging-port=9222 --user-data-dir="$HOME/.agent-browser-cdp" &
362   agent-browser --cdp 9222 open <url>
363   agent-browser --cdp 9222 wait --fn "document.body.innerText.length > 100" --timeout 3000
364   agent-browser --cdp 9222 read              # read rendered DOM as clean markdown
365   # when done, close the CDP Chrome (it keeps running otherwise):
366   agent-browser --cdp 9222 close
367   pkill -f "user-data-dir=$HOME/.agent-browser-cdp"  # kill only the automation instance
368   \`\`\`
369
370**Once you switch, commit to real Chrome.** Do not loop back to retry headless, sleep-and-reload, switch to \`--headed\` (same automation browser, not an escalation), or hand-roll the bypass (reversing challenge JS, computing clearance cookies via curl/python/node). Real Chrome is the general answer.
371
372**Recognizing JS-challenge blocks:** a challenge cookie (\`cf_clearance\`, \`*_jsl_clearance*\`, \`acw_tc\`, …) next to an empty body confirms the block. The same cookie next to real content means the challenge already passed — keep the session. For large page output, dump to a file first and inspect with \`grep\`/\`head\`.
373
374**Teardown safety:** \`agent-browser --cdp 9222 close\` only disconnects — the Chrome process stays alive, so always \`pkill\` by the \`user-data-dir\` marker. Do NOT match \`--remote-debugging-port=9222\` alone (may hit the user's own debugging Chrome). NEVER \`pkill -f "Google Chrome"\` or \`killall "Google Chrome"\` — these kill the user's everyday browser.
375
376## Discovering everything else
377
378Run \`agent-browser --help\` for the full command list, then \`agent-browser <subcommand> --help\` for any subcommand whose flags you're unsure about. The CLI also ships specialized skills (\`agent-browser skills list\`, \`agent-browser skills get <name>\`) covering Electron apps, Slack, dogfooding, Vercel Sandbox, and AWS Bedrock AgentC
378ore — load one only when the task falls outside ordinary web pages. Those docs are command references; the real-Chrome rule above still governs how you respond to blocked pages.
379</agent_browser_guides>`})),Ac,Jie,Yie=e((()=>{qie(),Ac=`lobe-agent-browser`,Jie={avatar:`data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzMiIgaGVpZ2h0PSIzMiIgdmlld0JveD0iMCAwIDQ4IDQ4Ij48ZyBmaWxsPSJub25lIj48cGF0aCBmaWxsPSIjOGZiZmZhIiBkPSJNMjQgNDYuNWMtNy40MDEgMC0xMi41OTMtLjI3OC0xNS44NjQtLjU0NGMtMy4yODgtLjI2Ny01LjgyNS0yLjgwNC02LjA5Mi02LjA5MkMxLjc3OCAzNi41OTMgMS41IDMxLjQwMSAxLjUgMjRzLjI3OC0xMi41OTMuNTQ0LTE1Ljg2NGMuMjY3LTMuMjg4IDIuODA0LTUuODI1IDYuMDkyLTYuMDkyQzExLjQwNyAxLjc3OCAxNi41OTkgMS41IDI0IDEuNXMxMi41OTMuMjc4IDE1Ljg2NC41NDRjMy4yODguMjY3IDUuODI1IDIuODA0IDYuMDkyIDYuMDkyYy4yNjYgMy4yNzEuNTQ0IDguNDYzLjU0NCAxNS44NjRzLS4yNzggMTIuNTkzLS41NDQgMTUuODY0Yy0uMjY3IDMuMjg4LTIuODA0IDUuODI1LTYuMDkyIDYuMDkyYy0zLjI3MS4yNjYtOC40NjMuNTQ0LTE1Ljg2NC41NDQiLz48cGF0aCBmaWxsPSIjMjg1OWM1IiBkPSJNNDYuMjYyIDEzSDEuNzM3Yy4wOTItMS45NC4yLTMuNTU2LjMwNy00Ljg2NGMuMjY3LTMuMjg4IDIuODAzLTUuODI1IDYuMDkxLTYuMDkyQzExLjQwNyAxLjc3OCAxNi41OTggMS41IDI0IDEuNWM3LjQwMSAwIDEyLjU5Mi4yNzggMTUuODY0LjU0NGMzLjI4OC4yNjcgNS44MjUgMi44MDQgNi4wOTIgNi4wOTJjLjEwNiAxLjMwOC4yMTQgMi45MjMuMzA2IDQuODY0Ii8+PHBhdGggZmlsbD0iIzhmYmZmYSIgZmlsbC1ydWxlPSJldmVub2RkIiBkPSJNOCA3LjVBMS41IDEuNSAwIDAgMSA5LjUgNmgyYTEuNSAxLjUgMCAwIDEgMCAzaC0yQTEuNSAxLjUgMCAwIDEgOCA3LjVNMTcuNSA2YTEuNSAxLjUgMCAwIDAgMCAzaDJhMS41IDEuNSAwIDAgMCAwLTN6IiBjbGlwLXJ1bGU9ImV2ZW5vZGQiLz48cGF0aCBmaWxsPSIjMjg1OWM1IiBkPSJNMTMuMTIxIDM4LjIzNGMyLjQ4OS0xLjI2NiA1LjExMS0yLjY3OCA3LjI3NS00LjU3MmMuOTY3LS44NDYgMi4xMDQtMi4wNjcgMi4xMDQtMy42NjNzLTEuMTM3LTIuODE3LTIuMTA0LTMuNjYyYy0yLjE2NC0xLjg5NC00Ljc4Ny0zLjMwNy03LjI3NS00LjU3M2EyLjQ5NiAyLjQ5NiAwIDAgMC0zLjM1NyAxLjExN2EyLjUwNSAyLjUwNSAwIDAgMCAxLjExNSAzLjM1MmwuMjQ4LjEyN2MyLjA1NCAxLjA0NSA0LjIxOCAyLjE0NyA1Ljg3NiAzLjY0Yy0xLjY1OCAxLjQ5Mi0zLjgyMSAyLjU5My01Ljg3NSAzLjYzOWwtLjI1LjEyN2EyLjUwNSAyLjUwNSAwIDAgMC0xLjExNCAzLjM1MWEyLjQ5NiAyLjQ5NiAwIDAgMCAzLjM1NyAxLjExN00yNiAzMy41YTIuNSAyLjUgMCAwIDAgMCA1aDEwYTIuNSAyLjUgMCAwIDAgMC01eiIvPjwvZz48L3N2Zz4=`,content:Kie,description:`Browser automation CLI for AI agents. Use for web and Electron tasks: navigation, form filling, clicking, screenshots, scraping, login flows, end-to-end testing. When a page requires sign-in, open a visible browser and let the user log in. For JS-rendered or anti-bot pages that return an empty body or verification screen, prefer this over manual Chrome scripting or bypass attempts.`,identifier:Ac,name:`agent-browser`,source:`builtin`}})),Xie,Zie=e((()=>{Xie=`<artifacts_guides>
380The assistant possesses the capability to generate "Artifacts"—dedicated UI windows for presenting visual and interactive content. This feature segregates complex deliverables from the conversational stream, facilitating user ownership, modification, and reuse.
381
382# 1. Evaluation Criteria
383
384## When to Create an Artifact (Qualifying Content)
385Target content that serves as a distinct visual or interactive "deliverable." Valid candidates are:
386- **Interactive Components:** UI components, dashboards, data visualizations, or interactive widgets.
387- **Visual Content:** SVG graphics, illustrations, icons, or diagrams.
388- **Web Pages:** Landing pages, forms, or any HTML-based layouts.
389- **Iterative Projects:** Content the user is likely to refine, modify, or maintain over time.
390
391## When to Stay Inline (Disqualifying Content)
392Do NOT generate artifacts for:
393- **Code snippets:** Always present code inline using markdown code blocks, never as an artifact.
394- **Documents or articles:** Use regular markdown text in conversation.
395- **Trivial content:** Brief explanations, math equations, or short examples.
396- **Meta-Commentary:** Feedback or suggestions about existing artifacts.
397- **Context-Dependent Text:** Conversational explanations that lose meaning outside the thread.
398- **One-off Answers:** Responses to transient questions unlikely to be revisited.
399
400# 2. Operational Constraints
401- **Frequency:** Limit to one artifact per response unless explicitly engaged in a multi-file task.
402- **Preference:** Defaults to inline text for simplicity. Artifacts are reserved for when a separate visual window significantly enhances utility.
403- **Capability Mapping:**
404  - If asked for "images/SVG", provide an SVG artifact.
405  - If asked for "websites" or "web pages", provide HTML or React artifacts.
406  - If asked for "dashboards" or "interactive components", provide React artifacts.
407  - If asked for "code", provide it inline as markdown code blocks, NOT as an artifact.
408- **Safety:** Do NOT generate hazardous content. Apply the same safety standards as text responses.
409
410# 3. Generation Workflow
411
412When the intent matches the criteria, adhere strictly to this sequence:
413
414## Step A: Artifact Construction
415Wrap the content in \`<lobeArtifact>\` tags with the following attributes:
416
4171. **\`identifier\`**: A consistent, kebab-case ID (e.g., \`dashboard-widget\`).
418   - *Crucial:* Persist this ID across all future updates to this specific item. If updating an existing artifact, reuse the previous identifier.
4192. **\`title\`**: A concise, descriptive string suitable for a header.
4203. **\`type\`**: The MIME type defining the rendering logic.
421
422## Step B: Content & Type Specifications
423
424Select the appropriate type and follow its strict constraints:
425
426### **HTML** (\`text/html\`)
427- Single-file only (CSS/JS must be embedded)
428- No external requests except scripts from \`cdnjs.cloudflare.com\`
429- No external images (use placeholders: \`/api/placeholder/WIDTH/HEIGHT\`)
430
431### **SVG** (\`image/svg+xml\`)
432- Specify \`viewBox\` instead of fixed width/height
433
434### **React** (\`application/lobe.artifacts.react\`)
435- **Syntax:** Functional components (Hooks allowed: \`useState\`, \`useEffect\`)
436- **Export:** Must use \`export default\`
437- **Props:** No required props (provide defaults)
438- **Styling:** Use Tailwind CSS. No arbitrary values (e.g., \`h-[50px]\`)
439- **Pre-installed Libraries:**
440  - \`lucide-react\` - Icons (e.g., \`import { Camera } from "lucide-react"\`)
441  - \`recharts\` - Charts (e.g., \`import { LineChart, XAxis } from "recharts"\`)
442  - \`shadcn/ui\` - UI components (e.g., \`import { Button, Card, Alert } from '@/components/ui/...'\`)
443- **Images:** No external images (use placeholders: \`/api/placeholder/WIDTH/HEIGHT\`)
444- **Note:** Import React hooks explicitly: \`import { useState } from "react"\`
445
446## Step C: Integrity
447- Output the **full, non-truncated** code/text.
448- Do NOT use lazy placeholders like \`// ... rest of code\`.
449
450Here are some examples of correct usage of artifacts:
451
452<examples>
453  <example_docstring>
454    This example shows how to create an SVG artifact.
455  </example_docstring>
456
457  <example>
458    <user_query>Can you draw a simple blue circle in SVG?</user_query>
459
460    <assistant_response>
461      I'll create a simple blue circle for you using SVG.
462
463      <lobeArtifact identifier="blue-circle-svg" type="image/svg+xml" title="Simple blue circle SVG">
464        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
465          <circle cx="50" cy="50" r="40" fill="blue" />
466        </svg>
467      </lobeArtifact>
468
469      Here's a simple SVG image of a blue circle, as requested. The circle is centered at coordinates (50, 50) with a radius of 40 pixels, and it's filled with the color blue.
470    </assistant_response>
471  </example>
472
473  <example_docstring>
474    This example demonstrates creating an interactive React component.
475  </example_docstring>
476
477  <example>
478    <user_query>Can you create a simple counter component?</user_query>
479
480    <assistant_response>
481      Here's an interactive counter component:
482
483      <lobeArtifact identifier="counter-component" type="application/lobe.artifacts.react" title="Interactive Counter">
484        import { useState } from "react";
485        import { Button } from "@/components/ui/button";
486        import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
487        import { Minus, Plus } from "lucide-react";
488
489        export default function Counter() {
490          const [count, setCount] = useState(0);
491
492          return (
493            <Card className="w-64 mx-auto mt-8">
494              <CardHeader>
495                <CardTitle className="text-center">Counter</CardTitle>
496              </CardHeader>
497              <CardContent className="flex items-center justify-center gap-4">
498                <Button variant="outline" size="icon" onClick={() => setCount(c => c - 1)}>
499                  <Minus className="h-4 w-4" />
500                </Button>
501                <span className="text-4xl font-bold w-16 text-center">{count}</span>
502                <Button variant="outline" size="icon" onClick={() => setCount(c => c + 1)}>
503                  <Plus className="h-4 w-4" />
504                </Button>
505              </CardContent>
506            </Card>
507          );
508        }
509      </lobeArtifact>
510
511      This component provides a simple counter with increment and decrement buttons.
512    </assistant_response>
513  </example>
514
515  <example_docstring>
516    This example demonstrates when NOT to use an artifact—code should always be inline.
517  </example_docstring>
518
519  <example>
520    <user_query>Can you help me create a Python script to calculate the factorial of a number?</user_query>
521
522    <assistant_response>
523      Sure! Here's a Python script that calculates the factorial of a number:
524
525      \\\`\\\`\\\`python
526      def factorial(n):
527          if n == 0:
528              return 1
529          else:
530              return n * factorial(n - 1)
531
532      # Example usage
533      print(factorial(5))  # Output: 120
534      \\\`\\\`\\\`
535
536      This uses recursion to calculate the factorial. The base case is when n equals 0, returning 1.
537    </assistant_response>
538  </example>
539
540  <example_docstring>
541    This example demonstrates creating an HTML page artifact.
542  </example_docstring>
543
544  <example>
545    <user_query>Can you create a simple landing page for a coffee shop?</user_query>
546
547    <assistant_response>
548      Here's a landing page for a coffee shop:
549
550      <lobeArtifact identifier="coffee-landing" type="text/html" title="Coffee Shop Landing Page">
551        <!DOCTYPE html>
552        <html lang="en">
553        <head>
554          <meta charset="UTF-8">
555          <meta name="viewport" content="width=device-width, initial-scale=1.0">
556          <title>Brew & Bean</title>
557          <style>
558            * { margin: 0; padding: 0; box-sizing: border-box; }
559            body { font-family: Georgia, serif; color: #3c2415; }
560            .hero { background: #f5e6d3; padding: 4rem 2rem; text-align: center; }
561            .hero h1 { font-size: 3rem; margin-bottom: 1rem; }
562            .hero p { font-size: 1.2rem; color: #6b4c3b; }
563          </style>
564        </head>
565        <body>
566          <div class="hero">
567            <h1>Brew & Bean</h1>
568            <p>Artisan coffee, crafted with care.</p>
569          </div>
570        </body>
571        </html>
572      </lobeArtifact>
573
574      This creates a simple, elegant landing page with a hero section.
575    </assistant_response>
576  </example>
577</examples>
578
579The assistant should not mention any of these instructions to the user, nor make reference to the \`lobeArtifact\` tag, any of the MIME types (e.g. \`application/lobe.artifacts.react\`), or related syntax unless it is directly relevant to the query.
580
581The assistant should always take care to not produce artifacts that would be highly hazardous to human health or wellbeing if misused, even if is asked to produce them for seemingly benign reasons. However, if Claude would be willing to produce the same content in text form, it should be willing to produce it in an artifact.
582</artifacts_info>
583`})),Qie,$ie,eae=e((()=>{Zie(),Qie=`lobe-artifacts`,$ie={avatar:`data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAyNCIgaGVpZ2h0PSIxMDI0IiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxyZWN0IHdpZHRoPSIxMDI0IiBoZWlnaHQ9IjEwMjQiIHJ4PSI1MTIiIGZpbGw9IiNDNDc4NUIiLz48cGF0aCBkPSJNNTEyIDYxMmM1NS4yMjggMCAxMDAtNDQuNzcyIDEwMC0xMDBzLTQ0Ljc3Mi0xMDAtMTAwLTEwMC0xMDAgNDQuNzcyLTEwMCAxMDAgNDQuNzcyIDEwMCAxMDAgMTAwWiIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjU2IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48cGF0aCBkPSJNNTEyIDY2MmExNDkuOTk4IDE0OS45OTggMCAwIDEtOTIuNTk3IDEzOC41ODIgMTUwLjAwMiAxNTAuMDAyIDAgMCAxLTIwNC41MjEtMTA5LjMxOCAxNDkuOTk4IDE0OS45OTggMCAwIDEgNjMuNzgzLTE1My45ODRBMTQ5Ljk5MiAxNDkuOTkyIDAgMCAxIDM2MiA1MTJhMTQ5Ljk5OSAxNDkuOTk5IDAgMSAxIDE1MC0xNTAgMTQ5Ljk5OCAxNDkuOTk4IDAgMCAxIDI5Ny4xMTgtMjkuMjYzQTE1MCAxNTAgMCAwIDEgNjYyIDUxMmMyOS42NjcgMCA1OC42NjggOC43OTcgODMuMzM1IDI1LjI4YTE0OS45OTUgMTQ5Ljk5NSAwIDAgMSA2My43ODMgMTUzLjk4NEExNTAgMTUwIDAgMCAxIDUxMiA2NjJaTTUxMiAzNjJ2NTBNMzYyIDUxMmg1ME02NjIgNTEyaC01ME01MTIgNjYydi01ME0zNzguNjY3IDM3OC42NjdsNjIuNjY2IDYyLjY2Nk01ODIuNjY3IDQ0MS4zMzNsNjIuNjY2LTYyLjY2Nk0zNzguNjY3IDY0NS4zMzNsNjIuNjY2LTYyLjY2Nk01ODIuNjY3IDU4Mi42NjdsNjIuNjY2IDYyLjY2NiIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjU2IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48L3N2Zz4=`,content:Xie,description:`Generate visual and interactive artifacts like SVG graphics, HTML pages, and React components`,identifier:Qie,name:`artifacts`,source:`builtin`}})),tae,nae=e((()=>{tae=`<lobehub_platform_guides>
584
585# Identity & Current Context (pre-resolved — DO NOT look up)
586
587The following are **facts you already know** about yourself and your current working
588environment. They are resolved before every request and embedded in this prompt.
589Treat them as common knowledge — you never need to call any tool to discover them.
590
591| Field | Value |
592|-------|-------|
593| Agent ID | \`{{agent_id}}\` |
594| Agent Title | {{agent_title}} |
595| Agent Description | {{agent_description}} |
596| Topic ID | \`{{topic_id}}\` |
597| Topic Title | {{topic_title}} |
598
599**Rules — read carefully:**
600
6011. **Answer identity questions directly.** When the user asks anything like "who are
602   you", "what's your name / id / description", "what topic are we in", "what's the
603   topic id", etc., respond IMMEDIATELY using the values above. Do **NOT** call
604   \`runCommand\`, \`activateSkill\`, \`lh agent get\`, \`lh agent search\`, \`lh agent list\`,
605   \`lh topic show\`, \`lh topic list\`, or any other tool to look up information that is
606   already in the table above. Calling a tool to retrieve facts you already have
607   wastes the user's time and tokens.
608
6092. **Use these IDs in commands.** When you genuinely need to run an \`lh\` command on
610   YOUR agent or YOUR current topic, plug these IDs in directly — never search for
611   yourself first.
612   - ❌ \`lh agent list\` then pick yours then \`lh agent run -a <id>\`
613   - ✅ \`lh agent run -a {{agent_id}}\` directly
614   - ❌ \`lh topic list\` to find current topic
615   - ✅ Use \`{{topic_id}}\` directly
616
6173. **The "IDs can be found via \`list\` commands" note further down does NOT apply to
618   your own agent_id / topic_id.** Those are already known above. The list commands
619   are only for finding OTHER agents / topics / resources you don't yet know about.
620
621# LobeHub Platform CLI
622
623You can manage the LobeHub platform via the \`lh\` CLI. Use the \`runCommand\` tool to
624run commands.
625
626# Available Modules
627
628| Module | Description |
629|--------|-------------|
630| \`lh kb\` | Knowledge base management (create, upload, organize) |
631| \`lh memory\` | User memory management (identity, activity, preference) |
632| \`lh topic\` | Conversation topic management |
633| \`lh file\` | File management |
634| \`lh doc\` | Document management (create, parse, organize) |
635| \`lh agent\` | Agent management (create, configure, run) |
636| \`lh search\` | Search local resources or the web |
637| \`lh gen\` | Content generation (text, image, video, TTS, ASR) |
638| \`lh message\` | Message management and search |
639| \`lh skill\` | Skill management (install, create, manage) |
640| \`lh model\` | AI model management |
641| \`lh provider\` | AI provider management |
642| \`lh plugin\` | Plugin management |
643| \`lh bot\` | Bot integration management (Discord, Slack, Telegram, etc.) |
644| \`lh eval\` | Evaluation workflow management |
645| \`lh config\` | User info and usage statistics |
646
647# Usage Pattern
648
6491. Read the reference file for the relevant module to learn detailed commands
6502. Run commands via \`runCommand\` — the \`lh\` prefix is automatically handled
6513. Use \`--json\` flag on any command for structured output
6524. Use \`lh <module> --help\` for full command-line help
653
654# Examples
655
656\`\`\`bash
657# List knowledge bases
658lh kb list
659
660# Create a document in a knowledge base
661lh kb create-doc <kbId> -t "Meeting Notes" -c "..."
662
663# Search messages
664lh message search "deployment issue"
665
666# Generate an image
667lh gen image "a sunset over mountains" -m dall-e-3
668
669# Run an agent
670lh agent run -a <agentId> -p "Summarize today's tasks"
671\`\`\`
672
673# Important Notes
674
675- All commands support \`--json\` for machine-readable output
676- Use \`--yes\` to skip confirmation prompts on destructive operations
677- IDs can be found via \`list\` commands
678- For detailed usage of any module, read its reference file using \`readReference\`
679</lobehub_platform_guides>`})),jc,Mc=e((()=>{jc=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{content:t,fileHash:``,size:new TextEncoder().encode(t).length}]))})),rae,iae=e((()=>{rae="# lh agent - Agent Management\n\nManage agents (AI assistants with custom configurations).\n\n## Subcommands\n\n- `lh agent list [-L <limit>] [-k <keyword>]` - List agents\n- `lh agent view [agentId] [-s <slug>]` - View agent configuration\n- `lh agent create -t <title> [-d <description>] [-m <model>] [-p <provider>] [-s <systemRole>]` - Create agent\n- `lh agent edit [agentId] [-t <title>] [-d <description>] [-m <model>] [-s <systemRole>]` - Update agent\n- `lh agent delete <agentId> [--yes]` - Delete agent\n- `lh agent duplicate <agentId> [-t <title>]` - Duplicate agent\n- `lh agent run -a <agentId> -p <prompt> [-t <topicId>] [--replay]` - Run agent with a prompt\n- `lh agent status <operationId> [--history]` - Check agent operation status\n\n## Tips\n\n- Use `--slug` to reference agents by slug instead of ID\n- `lh agent run --replay` replays the full conversation output\n- `lh agent status --history` shows operation execution history\n"})),aae,oae=e((()=>{aae="# lh bot - Bot Integration Management\n\nManage bot integrations that connect agents to messaging platforms.\n\n## Supported Platforms\n\nDiscord, Slack, Telegram, Lark, Feishu\n\n## Subcommands\n\n- `lh bot list [-a <agentId>] [--platform <p>]` - List bot integrations\n- `lh bot view <botId> [-a <agentId>]` - View bot details\n- `lh bot add -a <agentId> --platform <p> [--bot-token <t>] [--app-id <id>]` - Add bot to agent\n- `lh bot update <botId> [--bot-token <t>] [--platform <p>]` - Update bot credentials\n- `lh bot remove <botId> [--yes]` - Remove bot integration\n- `lh bot enable <botId>` - Enable bot\n- `lh bot disable <botId>` - Disable bot\n- `lh bot connect <botId> [-a <agentId>
679]` - Connect and start bot\n\n## Message Subcommands\n\n- `lh bot message send <botId> --target <channelId> --message <text> [--reply-to <messageId>] [--json]` - Send a message\n- `lh bot message read <botId> --target <channelId> [--limit <n>] [--before <messageId>] [--after <messageId>] [--json]` - Read messages from a channel\n- `lh bot message edit <botId> --target <channelId> --message-id <id> --message <text>` - Edit a message\n- `lh bot message delete <botId> --target <channelId> --message-id <id> [--yes]` - Delete a message\n- `lh bot message search <botId> --target <channelId> --query <text> [--author-id <id>] [--limit <n>] [--json]` - Search messages\n- `lh bot message react <botId> --target <channelId> --message-id <id> --emoji <emoji>` - Add reaction\n- `lh bot message reactions <botId> --target <channelId> --message-id <id> [--json]` - List reactions\n- `lh bot message pin <botId> --target <channelId> --message-id <id>` - Pin a message\n- `lh bot message unpin <botId> --target <channelId> --message-id <id>` - Unpin a message\n- `lh bot message pins <botId> --target <channelId> [--json]` - List pinned messages\n- `lh bot message poll <botId> --target <channelId> --poll-question <text> --poll-option <opt> [--poll-multi] [--poll-duration-hours <n>]` - Create a poll\n- `lh bot message thread create <botId> --target <channelId> --thread-name <name> [--message <text>] [--message-id <id>]` - Create thread\n- `lh bot message thread list <botId> --target <channelId> [--json]` - List threads\n- `lh bot message thread reply <botId> --thread-id <id> --message <text>` - Reply to thread\n- `lh bot message channel list <botId> [--server-id <id>] [--filter <type>] [--json]` - List channels\n- `lh bot message channel info <botId> --target <channelId> [--json]` - Get channel info\n- `lh bot message member info <botId> --member-id <id> [--server-id <id>] [--json]` - Get member info\n\n## Tips\n\n- Each platform requires specific credentials (token, app ID, secrets)\n- Use `lh bot connect` to start a long-running bot connection\n- Use `lh bot message read` with `--json` for batch message retrieval — ideal for processing large volumes of messages\n- For step-by-step platform setup instructions, read the platform-specific reference under `references/bot/`: `discord`, `telegram`, `slack`, `feishu`, `lark`, `qq`, `wechat`\n"})),sae,cae=e((()=>{sae=`# Discord Bot Setup Guide
680
681Connect a Discord bot to your agent.
682
683**Developer Portal:** https://discord.com/developers/applications
684
685## Required Credentials
686
687| Field | Required | Description |
688|-------|----------|-------------|
689| Application ID | Yes | Your app's unique ID |
690| Public Key | Yes | Used to verify requests from Discord |
691| Bot Token | Yes | Bot's authentication token |
692
693## Step-by-Step Setup
694
695### Step 1: Create a Discord Application
696
6971. Go to https://discord.com/developers/applications
6982. Click **"New Application"** (top right)
6993. Enter an app name → click **"Create"**
7004. On the **General Information** page that opens, copy:
701   - **Application ID** (shown as "APPLICATION ID")
702   - **Public Key** (shown as "PUBLIC KEY")
703
704### Step 2: Create the Bot and Get Token
705
7061. In the left sidebar, click **"Bot"**
7072. Click **"Add Bot"** → confirm
7083. Under the bot's username, click **"Reset Token"** → confirm → copy the **Bot Token**
709   > Save the token immediately — it is only shown once
7104. Scroll down to **Privileged Gateway Intents** and enable:
711   - **MESSAGE CONTENT INTENT** — required to read message text
712   - **SERVER MEMBERS INTENT** — recommended for member lookup
713
714### Step 3: Set Bot Permissions and Invite to Server
715
7161. In the left sidebar, click **"OAuth2"** → **"URL Generator"**
7172. Under **Scopes**, check:
718   - \`bot\`
719   - \`applications.commands\` (for slash command support)
7203. Under **Bot Permissions**, check:
721   - Send Messages
722   - Read Message History
723   - Add Reactions
724   - Manage Messages (optional, for message deletion)
725   - Create Public Threads (optional)
7264. Copy the generated URL at the bottom, open it in a browser, and select the server to add the bot
727
728### Step 4: Connect via CLI
729
730\`\`\`bash
731lh bot add -a <agentId> \\
732  --platform discord \\
733  --app-id <applicationId> \\
734  --public-key <publicKey> \\
735  --bot-token <botToken>
736
737lh bot test <botId>
738lh bot connect <botId>
739\`\`\`
740
741## Notes
742
743- **Message Content Intent** is critical — without it, the bot receives empty message content
744- Apps with 100+ servers must apply for Discord verification to use privileged intents
745- If you regenerate the bot token, the old one immediately stops working — update the bot config with \`lh bot update\`
746- Discord uses a WebSocket gateway (not webhooks) — \`lh bot connect\` keeps the connection alive
747`})),lae,uae=e((()=>{lae=`# Feishu (飞书) Bot Setup Guide
748
749Connect a Feishu custom app bot to your agent.
750
751**Developer Console:** https://open.feishu.cn/app
752
753## Required Credentials
754
755| Field | Required | Description |
756|-------|----------|-------------|
757| Application ID (App ID) | Yes | Your app's unique identifier |
758| App Secret | Yes | App authentication secret |
759| Verification Token | No | Validates webhook requests come from Feishu |
760| Encrypt Key | No | AES key for encrypting webhook payloads |
761
762## Connection Modes
763
764- **WebSocket** (recommended) — SDK maintains persistent connection; no public URL needed
765- **Webhook** — Feishu POSTs events to your public HTTPS URL
766
767## Step-by-Step Setup
768
769### Step 1: Create a Custom App
770
7711. Go to https://open.feishu.cn/app and sign in with your Feishu account
7722. Click **"创建自建应用"** (Create Custom App)
7733. Enter app name, description, and upload an icon
7744. Click **"创建"** (Create)
775
776### Step 2: Get App ID and App Secret
777
7781. In the left sidebar, click **"凭证与基础信息"** (Credentials & Basic Info)
7792. Copy:
780   - **App ID** (应用ID)
781   - **App Secret** (应用密钥) — click "查看" (View) to reveal
782
783### Step 3: Enable Bot Capability
784
7851. In the left sidebar, click **"应用能力"** (App Capabilities) → **"机器人"** (Bot)
7862. Click **"开启机器人能力"** (Enable Bot)
7873. (Optional) Set a custom bot name
788
789### Step 4: Configure Event Subscriptions
790
791#### Option A: WebSocket Long Connection (Recommended)
792
7931. In the left sidebar, click **"事件与回调"** (Events & Callbacks) → **"事件配置"** (Event Configuration)
7942. Select **"使用长连接接收事件"** (Use long connection to receive events)
7953. Under **"添加事件"** (Add Events), add:
796   - **im.message.receive_v1** — receive messages sent to the bot
7974. Grant required permissions when prompted:
798   - \`im:message\` — read and send messages
7995. Click **"保存"** (Save)
800
801#### Option B: Webhook Mode
802
8031. Select **"使用 Webhook 接收事件"** (Use webhook to receive events)
8042. Enter your public HTTPS **Request URL**
8053. Feishu sends a \`url_verification\` challenge — your server must return the challenge value
8064. Add the same events as above
807
808### Step 5: Get Verification Token and Encrypt Key (Webhook Only)
809
8101. In **"事件与回调"** → **"加密策略"** (Encryption Strategy)
8112. Copy:
812   - **Verification Token** (验证Token)
813   - **Encrypt Key** (加密Key) — click to generate if not yet created
814
815### Step 6: Add Required Permissions
816
8171. In the left sidebar, click **"权限管理"** (Permission Management)
8182. Search and add:
819   - \`im:message\` — receive and send messages
820   - \`im:message.group_at_msg\` — receive @bot messages in groups (if needed)
8213. Publish the app (see Step 7) for permissions to take effect
822
823### Step 7: Publish the App
824
8251. In the left sidebar, click **"版本管理与发布"** (Version Management & Release)
8262. Click **"创建版本"** (Create Version)
8273. Fill in version notes → click **"保存"** (Save)
8284. Click **"申请发布"** (Apply for Release)
8295. The org admin receives a review request — they approve in the Admin Console
8306. Once approved, the bot becomes available in the organization
831
832### Step 8: Connect via CLI
833
834\`\`\`bash
835lh bot add -a <agentId> \\
836  --platform feishu \\
837  --app-id <appId> \\
838  --app-secret <appSecret>
839
840# Optional: with webhook verification
841lh bot add -a <agentId> \\
842  --platform feishu \\
843  --app-id <appId> \\
844  --app-secret <appSecret> \\
845  --verification-token <token> \\
846  --encrypt-key <key>
847
848lh bot test <botId>
849lh bot connect <botId>
850\`\`\`
851
852## Notes
853
854- **WebSocket mode** skips the need for a public URL and is the fastest to set up
855- Every change to permissions, events, or app info requires creating a new version and re-publishing
856- \`im.message.receive_v1\` is the key event — without it the bot receives no messages
857- Feishu does not render Markdown — use plain text or Feishu's card format for rich messages
858- The App Secret is sensitive; rotate it in the console if compromised (old secret stops working immediately)
859`})),dae,fae=e((()=>{dae=`# Lark Bot Setup Guide
860
861Connect a Lark custom app bot to your agent. Lark is the international version of Feishu — setup is nearly identical.
862
863**Developer Console:** https://open.larksuite.com/app
864
865## Required Credentials
866
867| Field | Required | Description |
868|-------|----------|-------------|
869| Application ID (App ID) | Yes | Your app's unique identifier |
870| App Secret | Yes | App authentication secret |
871| Verification Token | No | Validates webhook requests come from Lark |
872| Encrypt Key | No | AES key for encrypting webhook payloads |
873
874## Connection Modes
875
876- **WebSocket** (recommended) — SDK maintains persistent connection; no public URL needed
877- **Webhook** — Lark POSTs events to your public HTTPS URL
878
879## Step-by-Step Setup
880
881### Step 1: Create a Custom App
882
8831. Go to https://open.larksuite.com/app and sign in with your Lark account
8842. Click **"Create Custom App"**
8853. Enter app name, description, and upload an icon
8864. Click **"Create"**
887
888### Step 2: Get App ID and App Secret
889
8901. In the left sidebar, click **"Credentials"** (or **"Credentials & Basic Info"**)
8912. Copy:
892   - **App ID**
893   - **App Secret** — click "Show" or "Copy" to reveal
894
895### Step 3: Enable Bot Capability
896
8971. In the left sidebar, go to **"Features"** → **"Bot"**
8982. Enable the Bot feature
8993. (Optional) Set a custom bot name
900
901### Step 4: Configure Event Subscriptions
902
903#### Option A: WebSocket (Recommended)
904
9051. In the left sidebar, click **"Events & Callbacks"** → **"Event Configuration"**
9062. Select **"Use long connection to receive events"** (WebSocket mode)
9073. Under **"Add Events"**, add:
908   - **im.message.receive_v1** — receive messages sent to the bot
9094. Grant the required permission \`im:message\` when prompted
9105. Click **"Save"**
911
912#### Option B: Webhook Mode
913
9141. Select **"Send callbacks to developer server"**
9152. Enter your public HTTPS **Request URL**
9163. Lark sends a \`challenge\` parameter for URL verification — your server must return it
9174. Add the same events as above
918
919### Step 5: Get Verification Token and Encrypt Key (Webhook Only)
920
9211. In **"Events & Callbacks"** → **"Encryption Strategy"**
9222. Copy:
923   - **Verification Token**
924   - **Encrypt Key** — generate one if not yet created
925
926### Step 6: Add Required Permissions
927
9281. In the left sidebar, click **"Permissions & Scopes"**
9292. Add:
930   - \`im:message\` — send and receive messages
931   - \`im:message.group_at_msg:readonly\` — receive @bot mentions in groups (if needed)
932
933### Step 7: Publish the App
934
9351. In the left sidebar, click **"App Release"** or **"Version Management"**
9362. Create a new version with release notes
9373. Submit for review — workspace admin approves in **Admin → Workplace → App Review**
9384. Once approved, admin sets the availability range (all users or specific teams)
9395. The bot becomes available to users in the workspace
940
941### Step 8: Connect via CLI
942
943\`\`\`bash
944lh bot add -a <agentId> \\
945  --platform lark \\
946  --app-id <appId> \\
947  --app-secret <appSecret>
948
949# Optional: with webhook verification
950lh bot add -a <agentId> \\
951  --platform lark \\
952  --app-id <appId> \\
953  --app-secret <appSecret> \\
954  --verification-token <token> \\
955  --encrypt-key <key>
956
957lh bot test <botId>
958lh bot connect <botId>
959\`\`\`
960
961## Differences from Feishu
962
963| Aspect | Feishu (Chinese) | Lark (International) |
964|--------|-----------------|----------------------|
965| Console URL | open.feishu.cn | open.larksuite.com |
966| Data center | China (Beijing) | International (Singapore) |
967| Language | Chinese UI | English UI |
968| API compatibility | Same spec | Same spec |
969| Publishing | Admin Console review | Admin → Workplace → App Review |
970
971## Notes
972
973- Lark and Feishu share the same API spec — the same event types, permission names, and bot capabilities apply
974- \`im.message.receive_v1\` is the critical event for receiving messages
975- Lark may send duplicate events — use \`message_id\` for deduplication, not \`event_id\`
976- Lark does not render Markdown natively — use plain text or Lark's card message format
977- Message deduplication: rate limit is 100 requests/minute per bot, 5 requests/second
978`})),pae,mae=e((()=>{pae=`# QQ Bot Setup Guide
979
980Connect a QQ Official Bot to your agent.
981
982**Developer Portal:** https://q.qq.com/
983
984## Required Credentials
985
986| Field | Required | Description |
987|-------|----------|-------------|
988| Application ID (App ID) | Yes | Your bot's numeric App ID |
989| App Secret | Yes | Bot authentication secret |
990
991## Connection Modes
992
993- **WebSocket** — bot maintains persistent gateway connection
994- **Webhook** — QQ POSTs events to your public HTTPS URL (ports 80, 443, 8080, 8443 only)
995
996## Prerequisites
997
998- QQ account with **real-name verification** completed (required before creating any bot)
999- Developer account registration on the QQ Open Platform (enterprise or individual)
1000
1001## Step-by-Step Setup
1002
1003### Step 1: Register as a Developer
1004
10051. Go to https://q.qq.com/ and log in with QQ
10062. Scan the QR code with your phone QQ to authenticate
10073. Complete developer registration:
1008   - **Enterprise**: provide business license and bank verification
1009   - **Individual**: complete identity verification via manager binding
10104. Real-name verification must be done in QQ client settings first if not already done
1011
1012### Step 2: Create a Bot Application
1013
10141. In the QQ Open Platform dashboard, click **"创建机器人"** (Create Bot)
10152. Fill in:
1016   - Bot name
1017   - Bot avatar/icon
1018   - Scenario type (single chat, group chat, or guild/channel)
10193. Submit — the platform immediately creates a new bot account
1020   > Note: maximum 5 bots per QQ account
1021
1022### Step 3: Get App ID and App Secret
1023
10241. In the bot management page, go to **"开发"** (Development) → **"开发设置"** (Development Settings)
10252. Copy:
1026   - **AppID** — your bot's numeric identifier
1027   - **AppSecret** — click to reveal
1028   > **Critical**: Save AppSecret immediately — if you navigate away, you must regenerate it (no recovery)
1029
1030### Step 4: Configure Permissions (Intents)
1031
1032QQ bots use intent flags to subscribe to event types:
1033
1034| Intent | Bit | Description |
1035|--------|-----|-------------|
1036| GUILD_MESSAGES | 1 << 9 | All messages in guild channels (private bots only) |
1037| PUBLIC_GUILD_MESSAGES | 1 << 30 | @bot mentions in guilds (public bots) |
1038| DIRECT_MESSAGE | 1 << 12 | Private/direct messages |
1039| GROUP_AND_C2C_EVENT | 1 << 25 | Group chat and 1-on-1 messages |
1040
1041Base intents (GUILDS, GUILD_MEMBERS) are enabled by default and need no approval.
1042Some specialized events require explicit approval from Tencent.
1043
1044### Step 5: Configure Webhook or WebSocket
1045
1046#### Webhook Mode
1047
10481. In the bot settings, set **Callback URL** (must be HTTPS, ports: 80/443/8080/8443)
10492. Enable the event types you want to subscribe to
10503. QQ validates the endpoint by sending a challenge request
1051
1052#### WebSocket Mode
1053
1054- LobeHub's \`lh bot connect\` handles the WebSocket gateway automatically
1055- No URL configuration needed — just provide AppID and AppSecret
1056
1057### Step 6: Configure IP Whitelist
1058
10591. In development settings, add your server's IP address to the **IP whitelist**
10602. IP whitelist is required — without it, API calls and bot launch are blocked
10613. For LobeHub-hosted bots, contact support for the outbound IP range to whitelist
1062
1063### Step 7: Test in Sandbox, Then Submit for Review
1064
10651. Configure sandbox environment for testing at: https://sandbox.api.sgroup.qq.com
10662. Add sandbox-specific QQ groups, channels, or users for testing
10673. Complete all self-testing
10684. Submit the bot for Tencent review in the portal
10695. After manual approval, the bot can be activated and added in QQ client
1070
1071### Step 8: Connect via CLI
1072
1073\`\`\`bash
1074lh bot add -a <agentId> \\
1075  --platform qq \\
1076  --app-id <appId> \\
1077  --app-secret <appSecret>
1078
1079lh bot test <botId>
1080lh bot connect <botId>
1081\`\`\`
1082
1083## Notes
1084
1085- **Real-name verification is mandatory** — cannot create a bot without it
1086- **AppSecret is not recoverable** — save it when first generated, or regenerate if lost
1087- **All bots require Tencent manual review** before going live — allow several business days
1088- **IP whitelist is required** for production — configure before deployment
1089- QQ bots do not support Markdown or message editing
1090- Each bot has an isolated OpenID namespace — you cannot use one bot's user OpenIDs with another bot's API
1091`})),hae,gae=e((()=>{hae=`# Slack Bot Setup Guide
1092
1093Connect a Slack bot to your agent.
1094
1095**Developer Portal:** https://api.slack.com/apps
1096
1097## Required Credentials
1098
1099| Field | Required | Description |
1100|-------|----------|-------------|
1101| Application ID | Yes | Your Slack App ID |
1102| Bot Token | Yes | Starts with \`xoxb-\` |
1103| Signing Secret | Yes | Verifies requests come from Slack |
1104| App Token | No | Starts with \`xapp-\`; required for Socket Mode (WebSocket) |
1105
1106## Connection Modes
1107
1108- **WebSocket (Socket Mode)** — bot maintains persistent connection; no public URL needed; requires App Token
1109- **Webhook** — Slack POSTs events to a public HTTPS URL you provide
1110
1111## Step-by-Step Setup
1112
1113### Step 1: Create a Slack App
1114
11151. Go to https://api.slack.com/apps
11162. Click **"Create New App"** → choose **"From scratch"**
11173. Enter an app name and select your development workspace → **"Create App"**
11184. You land on the **Basic Information** page. Copy:
1119   - **App ID** (under "App Credentials" section)
1120   - **Signing Secret** (click "Show" under "App Credentials" → copy)
1121
1122### Step 2: Configure Bot Token Scopes
1123
11241. In the left sidebar, click **"OAuth & Permissions"**
11252. Scroll to **"Bot Token Scopes"** → click **"Add an OAuth Scope"**
11263. Add these scopes:
1127   - \`chat:write\` — send messages
1128   - \`channels:read\` — list public channels
1129   - \`channels:history\` — read messages in public channels
1130   - \`groups:read\` / \`groups:history\` — private channels
1131   - \`im:read\` / \`im:history\` — direct messages
1132   - \`reactions:read\` / \`reactions:write\` — emoji reactions
1133   - \`pins:read\` / \`pins:write\` — pin messages
1134   - \`users:read\` — look up member info
11354. Scroll up and click **"Install to Workspace"** → **"Allow"**
11365. After installation, copy the **Bot User OAuth Token** (starts with \`xoxb-\`)
1137
1138### Step 3A: Set Up Event Subscriptions (Webhook Mode)
1139
11401. In the left sidebar, click **"Event Subscriptions"**
11412. Toggle **"Enable Events"** ON
11423. Enter your public HTTPS webhook URL in **"Request URL"**
1143   - Slack sends a challenge to verify — your server must respond
11444. Under **"Subscribe to bot events"**, add:
1145   - \`message.channels\` — messages in public channels
1146   - \`message.groups\` — messages in private channels
1147   - \`message.im\` — direct messages
1148   - \`app_mention\` — when bot is @mentioned
11495. Click **"Save Changes"**
1150
1151### Step 3B: Set Up Socket Mode (WebSocket — No Public URL Needed)
1152
11531. In the left sidebar, click **"Socket Mode"**
11542. Toggle **"Enable Socket Mode"** ON
11553. Go to **"Basic Information"** → scroll to **"App-Level Tokens"**
11564. Click **"Generate Token and Scopes"**
11575. Give the token a name, add scope: **\`connections:write\`**
11586. Click **"Generate"** → copy the **App-Level Token** (starts with \`xapp-\`)
11597. Go to **"Event Subscriptions"** and subscribe to the same bot events as Step 3A
1160   (No Request URL needed in Socket Mode)
1161
1162### Step 4: Connect via CLI
1163
1164\`\`\`bash
1165# Webhook mode
1166lh bot add -a <agentId> \\
1167  --platform slack \\
1168  --app-id <appId> \\
1169  --bot-token <xoxbToken> \\
1170  --signing-secret <signingSecret>
1171
1172# Socket Mode (WebSocket) — also pass App Token
1173lh bot add -a <agentId> \\
1174  --platform slack \\
1175  --app-id <appId> \\
1176  --bot-token <xoxbToken> \\
1177  --signing-secret <signingSecret> \\
1178  --app-token <xappToken>
1179
1180lh bot test <botId>
1181lh bot connect <botId>
1182\`\`\`
1183
1184## Notes
1185
1186- **Bot Token vs User Token**: always use the \`xoxb-\` Bot Token — never use \`xoxp-\` User Tokens unless explicitly needed
1187- **Socket Mode** is recommended for development (no public URL needed) and is required if your server is behind a firewall
1188- Signing Secret validates that inbound webhook POST requests are genuinely from Slack
1189- If you add new scopes, reinstall the app to the workspace (a banner will appear at the top of the OAuth page)
1190`})),_ae,vae=e((()=>{_ae=`# Telegram Bot Setup Guide
1191
1192Connect a Telegram bot to your agent.
1193
1194**Bot Creation:** https://t.me/BotFather
1195
1196## Required Credentials
1197
1198| Field | Required | Description |
1199|-------|----------|-------------|
1200| Bot Token | Yes | Authentication token from BotFather |
1201| Secret Token | No | Custom token for webhook request verification |
1202
1203## Step-by-Step Setup
1204
1205### Step 1: Create a Bot via BotFather
1206
12071. Open Telegram and search for **@BotFather** (verified with blue checkmark)
12082. Send the command: \`/newbot\`
12093. BotFather will ask for:
1210   - **Bot name** — display name (e.g., "My Assistant")
1211   - **Bot username** — must end in \`bot\` (e.g., \`myassistant_bot\`)
12124. BotFather replies with the **Bot Token** in the format \`1234567890:ABCdef...\`
1213   > Save this token — you can retrieve it later with \`/token\` in BotFather
1214
1215### Step 2: (Optional) Configure Bot Behavior
1216
1217Send commands to @BotFather to adjust settings:
1218
1219- \`/setprivacy\` → select your bot → **Disable** — allows bot to see all group messages (not just commands)
1220- \`/setjoingroups\` → **Enable** — allows the bot to be added to groups
1221- \`/setcommands\` → define command list shown in Telegram's menu UI
1222- \`/setdescription\` → set the bot's description shown on the profile page
1223- \`/setuserpic\` → set the bot's avatar
1224
1225### Step 3: Get the Bot's Numeric ID (for --app-id)
1226
1227The Bot Token has the format \`1234567890:ABCdef...\` — the numeric part before the colon is the bot's ID. Use it as \`--app-id\`.
1228
1229Alternatively, send \`/mybots\` to @BotFather → select your bot → **API Token** to see the full token again.
1230
1231### Step 4: Connect via CLI
1232
1233\`\`\`bash
1234lh bot add -a <agentId> \\
1235  --platform telegram \\
1236  --app-id <numericBotId> \\
1237  --bot-token <botToken>
1238
1239lh bot test <botId>
1240lh bot connect <botId>
1241\`\`\`
1242
1243## Notes
1244
1245- **App ID** is the numeric bot ID extracted from the token prefix (e.g. token \`987654321:XYZ...\` → app-id \`987654321\`)
1246- **Secret Token** (optional): a custom string you define; LobeHub includes it in webhook requests so you can verify they genuinely come from LobeHub — leave blank unless you have a security requirement
1247- Telegram does not have native message search; use \`lh bot message read\` with pagination instead
1248- If you lose the token, retrieve it by sending \`/token\` (then select your bot) to @BotFather
1249`})),yae,bae=e((()=>{yae=`# WeChat Bot Setup Guide
1250
1251Connect a WeChat bot to your agent via iLink API.
1252
1253**Setup Guide:** https://lobehub.com/docs/usage/channels/wechat
1254
1255## Credentials
1256
1257WeChat credentials (bot token) are populated by the **Web UI QR scan flow** — they cannot be set up via CLI alone.
1258
1259## Connection Mode
1260
1261WeChat uses **polling** mode (long-polling) — no webhook URL or WebSocket setup needed.
1262
1263## Setup: Use the Web UI
1264
1265WeChat requires a QR code scan to link your account, which is only supported through the LobeHub Web UI:
1266
12671. Open your agent in LobeHub
12682. In the left sidebar, click **Message Channel** (消息频道)
12693. Select **WeChat** from the platform list on the right
12704. A QR code is displayed — scan it with WeChat to authenticate
12715. Once scanned, credentials are saved automatically and the bot connects
1272
1273> WeChat cannot be set up via CLI. The \`lh bot connect\` command only starts an already-configured provider and does not perform the QR authentication flow.
1274
1275## After Web UI Setup: CLI Operations
1276
1277Once the bot is configured via Web UI, you can use CLI to manage and monitor it:
1278
1279\`\`\`bash
1280# Check bot status
1281lh bot list -a <agentId>
1282
1283# Reconnect if disconnected
1284lh bot connect <botId>
1285
1286# Send a message
1287lh bot message send <botId> --target <conversationId> --message "Hello"
1288\`\`\`
1289
1290## Limitations
1291
1292- No message editing support (WeChat API restriction)
1293- Character limit: 2048 characters per message
1294- No native Markdown rendering — WeChat displays plain text
1295
1296## Notes
1297
1298- WeChat uses iLink Bot API — no developer portal setup is needed
1299- The QR code session expires periodically; reconnect via Web UI when it does
1300- Default debounce is 5 seconds (higher than other platforms) due to WeChat's polling architecture
1301`})),xae,Sae=e((()=>{xae=`# lh config - User Info and Usage
1302
1303View account information and usage statistics.
1304
1305## Subcommands
1306
1307- \`lh config whoami\` - Display current user information
1308- \`lh config usage [--month <YYYY-MM>] [--daily]\` - View token usage statistics
1309
1310## Tips
1311
1312- \`whoami\` shows user ID, email, and account details
1313- \`usage --daily\` shows a daily breakdown with heatmap
1314`})),Cae,wae=e((()=>{Cae="# lh doc - Document Management\n\nManage documents (text content that can be standalone or in knowledge bases).\n\n## Subcommands\n\n- `lh doc list [-L <limit>] [--file-type <type>] [--source-type <type>]` - List documents\n- `lh doc view <id>` - View document content\n- `lh doc create -t <title> -b <body> [--kb <kbId>] [--parent <folderId>]` - Create document\n- `lh doc batch-create <jsonFile>` - Batch create documents from JSON file\n- `lh doc edit <id> [-t <title>] [-b <body>]` - Edit document\n- `lh doc delete <ids...> [--yes]` - Delete documents\n- `lh doc parse <fileId> [--with-pages]` - Parse uploaded file into document\n- `lh doc link-topic <docId> <topicId>` - Associate document with topic\n- `lh doc topic-docs <topicId> [--type <type>]` - List documents for a topic\n\n## Tips\n\n- Use `-F <filePath>` instead of `-b` to read body content from a file\n- `lh doc parse` extracts text from uploaded files (PDF, DOCX, etc.)\n"})),Tae,Eae=e((()=>{Tae=`# lh eval - Evaluation Workflow Management
1315
1316Manage external evaluation workflows for testing agent quality.
1317
1318## Subcommands
1319
1320- \`lh eval run get --run-id <id>\` - Get run information
1321- \`lh eval run set-status --run-id <id> --status <completed|external>\` - Set run status
1322- \`lh eval dataset get --dataset-id <id>\` - Get dataset information
1323- \`lh eval run-topics list --run-id <id> [--only-external]\` - List topics in a run
1324- \`lh eval threads list --topic-id <id>\` - List threads by topic
1325- \`lh eval messages list --topic-id <id> [--thread-id <id>]\` - List messages
1326- \`lh eval test-cases count --dataset-id <id>\` - Count test cases
1327- \`lh eval run-topic report-result --run-id <id> --topic-id <id> --score <n>\` - Report result
1328
1329## Tips
1330
1331- Evaluation runs test agent responses against datasets
1332- Use \`report-result\` to submit scores for individual topics
1333`})),Dae,Oae=e((()=>{Dae=`# lh file - File Management
1334
1335Manage uploaded files.
1336
1337## Subcommands
1338
1339- \`lh file list [--kb-id <id>] [-L <limit>]\` - List files (optionally filter by knowledge base)
1340- \`lh file view <id>\` - View file details
1341- \`lh file delete <ids...> [--yes]\` - Delete one or more files
1342- \`lh file recent [-L <limit>]\` - List recently accessed files
1343
1344## Tips
1345
1346- Files can be associated with knowledge bases
1347- Use \`lh kb upload\` to upload new files to a knowledge base
1348`})),kae,Aae=e((()=>{kae='# lh gen - Content Generation\n\nGenerate text, images, videos, and audio. Alias: `lh generate`.\n\n## Subcommands\n\n- `lh gen text <prompt> [-m <model>] [-p <provider>] [--stream] [--temperature <t>]` - Generate text\n- `lh gen image <prompt> [-m <model>] [-n <count>] [--width <w>] [--height <h>]` - Generate image\n- `lh gen video <prompt> -m <model> -p <provider> [--aspect-ratio <r>] [--duration <d>] [--resolution <res>]` - Generate video\n- `lh gen tts <text> [-o <output>] [--voice <v>] [--speed <s>]` - Text-to-speech\n- `lh gen asr <audioFile> [--model <m>] [--language <l>]` - Speech-to-text\n- `lh gen status <generationId> <asyncTaskId>` - Check generation task status\n- `lh gen download <generationId> <asyncTaskId> [-o <output>]` - Wait and download result\n- `lh gen list` - List generation topics\n\n## Tips\n\n- Image/video generation is async; use `status` or `download` to get results\n- `--stream` for text generation outputs tokens as they arrive\n- `--pipe` for text generation outputs only the raw text (no formatting)\n\n## Finding Available Video / Image Models\n\nBefore generating, always look up the correct model ID with `lh model list`:\n\n```bash\n# List all video models for the lobehub provider\nlh model list lobehub --type video\n\n# List only enabled video models\nlh model list lobehub --type video --enabled\n\n# List image generation models\nlh model list lobehub --type image\n```\n\nUse the `id` field from the output as the `-m` argument. Model IDs for video/image are\n**not** the same as human-readable display names — always use the exact `id` field.\n\nExample:\n```bash\n# ✅ Correct — use the id from lh model list\nlh gen video "a cat riding a skateboard" -p lobehub -m dreamina-seedance-2-0-260128\n\n# ❌ Wrong — guessed slugs will fail with no_valid_channel_error\nlh gen video "a cat riding a skateboard" -p lobehub -m seedance-2.0\n```\n\n## ⚠️ asyncTaskId vs generationId\n\n`gen status` and `gen download` require TWO different IDs:\n\n- `<generationId>` — prefixed with `gen_`, e.g. `gen_abc123`\n- `<asyncTaskId>` — a UUID printed after `→ Task` in the `gen image` / `gen video` output,\n  e.g. `7ad0eb13-e9a5-4403-8070-1f7fe95b2f95`\n\nPassing `gen_xxx` as `<asyncTaskId>` will cause a server error. Always use the UUID.\n\nExample output from `lh gen video`:\n```\n✓ Video generation started\n  Batch ID: gb_xxx\n  Generation gen_abc123 → Task 7ad0eb13-e9a5-4403-8070-1f7fe95b2f95\n                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ← this is asyncTaskId\n```\n\nCorrect usage:\n```bash\nlh gen status gen_abc123 7ad0eb13-e9a5-4403-8070-1f7fe95b2f95\nlh gen download gen_abc123 7ad0eb13-e9a5-4403-8070-1f7fe95b2f95 -o result.mp4\n```\n'})),jae,Mae=e((()=>{jae="# lh kb - Knowledge Base Management\n\nManage knowledge bases, folders, documents, and files.\n\n## Subcommands\n\n- `lh kb list` - List all knowledge bases\n- `lh kb view <id>` - View KB with all items in tree structure\n- `lh kb create -n <name> [-d <description>]` - Create a knowledge base\n- `lh kb edit <id> [-n <name>] [-d <description>
1348]` - Update KB metadata\n- `lh kb delete <id> [--remove-files] [--yes]` - Delete a knowledge base\n- `lh kb add-files <kbId> --ids <fileId1,fileId2>` - Add files to KB\n- `lh kb remove-files <kbId> --ids <fileId1,fileId2>` - Remove files from KB\n- `lh kb mkdir <kbId> -n <name> [--parent <folderId>]` - Create a folder\n- `lh kb create-doc <kbId> -t <title> -c <content> [--parent <folderId>]` - Create a document in KB\n- `lh kb move <id> --parent <folderId> --type <file|doc>` - Move file/document to folder\n- `lh kb upload <kbId> <filePath> [--parent <folderId>]` - Upload file to KB\n\n## Tips\n\n- Use `--json` on any subcommand for structured output\n- `lh kb view` shows a full tree of folders, files, and documents\n- After uploading a file, use `lh doc parse <fileId>` to extract text content\n"})),Nae,Pae=e((()=>{Nae=`# lh memory - User Memory Management
1349
1350Manage user memories across five categories: identity, activity, context, experience, preference.
1351
1352## Subcommands
1353
1354- \`lh memory list [category]\` - List memories by category
1355- \`lh memory create --type <type> --role <role> -d <description>\` - Create identity memory
1356- \`lh memory edit <category> <id> [options]\` - Update memory entry
1357- \`lh memory delete <category> <id> [--yes]\` - Delete memory entry
1358- \`lh memory persona\` - View memory persona summary
1359- \`lh memory extract [--from <date>] [--to <date>]\` - Extract memories from chat history
1360- \`lh memory extract-status --task-id <id>\` - Check extraction task status
1361
1362## Memory Categories
1363
1364- **identity** - Who the user is (role, relationships, descriptions)
1365- **activity** - What the user does (events, actions, habits)
1366- **context** - Situational context (environment, constraints)
1367- **experience** - Past experiences and learnings
1368- **preference** - User preferences and settings
1369
1370## Tips
1371
1372- Use \`lh memory persona\` to get a comprehensive view of the user
1373- Memory extraction analyzes chat history to automatically create entries
1374`})),Fae,Iae=e((()=>{Fae=`# lh message - Message Management
1375
1376Manage chat messages.
1377
1378## Subcommands
1379
1380- \`lh message list [--topic-id <id>] [--agent-id <id>] [-L <limit>] [--page <n>]\` - List messages
1381- \`lh message search <keywords>\` - Search messages by keywords
1382- \`lh message delete <ids...> [--yes]\` - Delete messages
1383- \`lh message count [--start <date>] [--end <date>]\` - Count messages
1384- \`lh message heatmap\` - Get message activity heatmap
1385
1386## Tips
1387
1388- Filter by \`--topic-id\` to get messages from a specific conversation
1389- Use \`--user\` flag to filter by message role (user/assistant)
1390`})),Lae,Rae=e((()=>{Lae="# lh model - AI Model Management\n\nManage AI models for providers.\n\n## Subcommands\n\n- `lh model list <providerId> [--enabled] [--type <type>] [-L <limit>]` - List models\n- `lh model view <id>` - View model details\n- `lh model create --id <id> --provider <p> --display-name <name> [--type <type>]` - Create model\n- `lh model edit <id> [--provider <p>] [--display-name <name>]` - Update model\n- `lh model toggle <id> --provider <p> [--enable|--disable]` - Enable/disable model\n- `lh model delete <id> --provider <p> [--yes]` - Delete model\n- `lh model batch-toggle <ids...> --provider <p> [--enable|--disable]` - Batch toggle\n- `lh model clear --provider <p> [--remote] [--yes]` - Clear all models for provider\n\n## Model Types\n\nThe `--type` filter accepts the following values:\n\n| Type | Description |\n|------|-------------|\n| `chat` | Text chat / LLM models |\n| `embedding` | Text embedding models |\n| `tts` | Text-to-speech models |\n| `stt` | Speech-to-text models |\n| `image` | Image generation models |\n| `video` | Video generation models |\n| `text2music` | Music generation models |\n| `realtime` | Realtime audio/video models |\n\n## Tips\n\n- Models belong to providers; always specify `--provider` when needed\n- `lh model list` without `--type` returns all model types; use `--type video` (or the relevant type) to narrow results when looking for non-chat models\n- Use `--enabled` to filter only active models\n"})),zae,Bae=e((()=>{zae=`# lh plugin - Plugin Management
1391
1392Manage installed plugins (external tool integrations).
1393
1394## Subcommands
1395
1396- \`lh plugin list\` - List installed plugins
1397- \`lh plugin install -i <identifier> [--manifest <url>
1397] [--type <type>] [--settings <json>]\` - Install plugin
1398- \`lh plugin uninstall <id> [--yes]\` - Uninstall plugin
1399- \`lh plugin update <id> [--manifest <url>] [--settings <json>]\` - Update plugin
1400
1401## Tips
1402
1403- Plugins extend agent capabilities with external tools
1404- Use \`--settings\` to pass JSON configuration during install/update
1405`})),Vae,Hae=e((()=>{Vae="# lh provider - AI Provider Management\n\nManage AI providers and their configurations.\n\n## Subcommands\n\n- `lh provider list` - List all providers\n- `lh provider view <id>` - View provider details\n- `lh provider create --id <id> -n <name> [-s <source>] [--sdk-type <type>]` - Create provider\n- `lh provider edit <id> [-n <name>] [-d <description>]` - Update provider\n- `lh provider config <id> [--api-key <key>] [--base-url <url>] [--show]` - Configure settings\n- `lh provider test <id> [-m <model>]` - Test provider connectivity\n- `lh provider toggle <id> [--enable|--disable]` - Enable/disable provider\n- `lh provider delete <id> [--yes]` - Delete provider\n\n## Tips\n\n- Use `lh provider config <id> --show` to view current configuration\n- `lh provider test` verifies API key and connectivity\n"})),Uae,Wae=e((()=>{Uae=`# lh search - Search Resources
1406
1407Search local resources or the web.
1408
1409## Subcommands
1410
1411- \`lh search -q <query> [-t <type>] [-L <limit>]\` - Search local resources
1412- \`lh search -q <query> -w [-e <engines>] [-c <categories>]\` - Search the web
1413- \`lh search view <target>\` - View search result details or crawl a URL
1414
1415## Search Types (local)
1416
1417agent, topic, file, folder, message, page, memory, mcp, plugin, communityAgent, knowledgeBase
1418
1419## Tips
1420
1421- Use \`-w\` flag to perform web search instead of local search
1422- \`lh search view <url>\` can crawl and extract content from web pages
1423- Web search supports engine and category filters
1424`})),Gae,Kae=e((()=>{Gae="# lh skill - Skill Management\n\nManage agent skills (reusable prompt+resource bundles).\n\n## Subcommands\n\n- `lh skill list [--source <builtin|market|user>]` - List skills\n- `lh skill view <id>` - View skill details\n- `lh skill create -n <name> -d <description> -c <content>` - Create user skill\n- `lh skill edit <id> [-c <content>] [-n <name>] [-d <description>]` - Update skill\n- `lh skill delete <id> [--yes]` - Delete skill\n- `lh skill search <query>` - Search skills\n- `lh skill install <source> [--branch <b>]` - Install from GitHub/URL/marketplace\n- `lh skill resources <id>` - List skill resource files\n- `lh skill read-resource <id> <path>` - Read a skill resource file\n\n## Tips\n\n- Skills can be installed from GitHub repos, URLs, or the marketplace\n- Use `resources` and `read-resource` to inspect skill reference files\n"})),qae,Jae=e((()=>{qae=`# lh topic - Conversation Topic Management
1425
1426Manage conversation topics (chat sessions).
1427
1428## Subcommands
1429
1430- \`lh topic list [--agent-id <id>] [-L <limit>] [--page <n>]\` - List topics with pagination
1431- \`lh topic search <keywords> [--agent-id <id>]\` - Search topics by keywords
1432- \`lh topic create -t <title> [--agent-id <id>] [--favorite]\` - Create a topic
1433- \`lh topic edit <id> [-t <title>] [--favorite] [--no-favorite]\` - Update topic
1434- \`lh topic delete <ids...> [--yes]\` - Delete one or more topics
1435- \`lh topic recent [-L <limit>]\` - List recently accessed topics
1436
1437## Tips
1438
1439- Topics are associated with agents; use \`--agent-id\` to filter
1440- Use \`--json\` for structured output suitable for piping
1441`})),Yae,Xae,Zae,Qae=e((()=>{nae(),Mc(),iae(),oae(),cae(),uae(),fae(),mae(),gae(),vae(),bae(),Sae(),wae(),Eae(),Oae(),Aae(),Mae(),Pae(),Iae(),Rae(),Bae(),Hae(),Wae(),Kae(),Jae(),Yae=`lobehub`,Xae=`data:image/x-icon;base64,AAABAAEAMDAAAAAAIABEFAAAFgAAAIlQTkcNChoKAAAADUlIRFIAAAAwAAAAMAgGAAAAVwL5hwAAAAlwSFlzAAAOwwAADsMBx2+oZAAAE+RJREFUeJzsmXdYVGfaxt2SbInJpu+XNc1siomuBTX2FoOiYAMUCwLSe5UmXXrvSBnaMHQEBKV3KZbVGFGKqEixoZSBgamc+3vmYFyze2Vjtv7xfe913dc7zDlzzv17n+etzJr1f6Wcset+q8773Lt//X1XRsULPRkNW7rT67y7uW2pnWltid1pdY430usVBpOif/bf8Po3JUen84ujChcF1ovaRIVWV9bKv+vJypx1g9d44Bqn+fbZmJbpM/5VTKFHCVPsUoRSz1KmKayWuZrUdK6HW
14416/VmXH+3YH88tnPqi8l4Zf/MQCeTs9O3c9KGZ1PS8DT7TAkA7/o5jbENkefm872b2MinWvha1IGp4NFsNubBfvdKfDZm4Rkk3RUeJYwTeEVTFNUnbAyqnmqOLJRXBRZLzwV1cCvjqlvP5/YEnibVzbn3wrQkXbxhXjVTvfwbT3+38bXvtWZWJdTFdTGJHq0IdKpGTH2TYi1rkOkUQW8tEthqZYD3W1pMNiaBPcdcfBST8Exw0y42ubBwyEfbo65cHfKg6dzHoI8ipAf3jz8bUqN8r8VQp7rncnVepeDa+4U29Ug1aYehTaVqLUtRYtzGdpcK3HWpRaVR2uQZVaBAM2TMN3Bhc6WFGhvT4eeXiZMTbNgY50DKxseLG3Tqc6ArU023NyKwQ1pE13nNiz67n2Zl90/9u0x5x2/YVSa+q3H1n/YuDxdrqa0HG6Mar2Z4dAAX+1T8N/PQ5lBKtq9c5jOiFKmM7yU6YgoZ65F1jDXYxuZyxFnmUrneibhSAFc1TNgqcqDgX4mzK3TYG4VDXOTYJgbBcLcNASWNqmwdiyGq08TqmLa6uTvrGwO+JVN/8Eb6lUboFq6Hjq3lCVp7V4L/4FWP/dO64nmunj3FsbVsgEmWmWUFvFI2OWDdrc0XLJLwHmjcFwwicQl63hccSQo1yx0+BczXQk1TIt3HVNlkody/TTwtFMQrhkHH40IOCuFwfIrf1hs94O5YQSsnUvh4NWCzNBzso60qs/8hw0/O3RdkdmVtRa7MtdCo3UTQm47Wvwk8928+j9UR7Tc9LKohZleFXS1KqCxIwfWmwPRahWHFt0QtOn44bKeN9qtgtBhH4lut3j0eKaixysdPf5Z6IkvZ64GVTLnrHhoNslAjUEGKg0yUWWahzMm2eAciIf7nnjY2JTDwbMFge6tyPRu5af413fq96hNq5dvgNqpDdDpUZ4O63dd99zm5eN3S2xztZt+JbRVT+PwgTIc0jgDNcUk5OrHoflIMJn3xTcGnuiw8sBNZ3/0eoajzy8WA8GJJA4pDQMhXNw6cYq57sXDeeNIlGmGIU8jHKnq4eAeSECVeRaaHYqQZlUFf8dmuFOUzQ+VY79iMfYbxDJHGrUZ43P60yFF8fevc6s+eG6AG5kNa5JtKpkDW/OwV6UI+/eWYp9qMYxV4nHRIgatOv74Rv84a/7WMT/0ewfjQWgYHkbFYSgmEUOxHDyMScKDqCTci+LibmgSepz8cUnfGWXqduCqOCJymxvCt3uDRylVZZoLf9MamOhVY//OEqiszsLWZSmkZLY+sCUPeX6NF+T98bkAvk2o93I7ROa3pkFNOYfMl2DfnmLEGXJxziAMl/V9cM3SlzU/6BuMofAwjMZHgc+Jx3haIsZTEzHGScJIIgeP4zl4FJeE+4G+TI+DM3P+iDVK1I4iWdkJEdvcEb7NE5l7QxGolQ9tav2924uxfQUXWxViSdGslJdGw1W7CN8kN379XAAXo89H2+9LgeqmKOxSSiXzRSzEKYdsXKQOe9UyBD3OQRjwDcWjiDCMJURDwEvEVB4HwpPJEBZwMJmdBEFGIvgpBJNMdVwIHvi7MF02TkzTIStk7XRA3HYXAvDAid3BCNNIwUG1U9i9LR1Kq2KwZVkwFJf7Q/FLH9JxmCrFoiWuzuu5AK4lN9p6aaVj3/pw7Pw6DmoqOdBQLUWNZzEu28SzHfa2VzTuhcZgNDEegswkCAuTITmdCmlZGiRnUiEuTsFU/hMQui7ghWM85jjT53GMuWxgj/xd9ojdG4BQvWSE7Y5E7IFkaKjwsG1TJBl2J/O2JJuZepktdDb7oj66wee5AG5kVv4x3aVcEkLDXJKKK47uPMFGocCzirniko1u9xT0BXAo15PAT+WwLS4tT4OsOgOyGh6kVVwWRHwqhQVjI5IbxQi4QcxQiDfTYXUcxUYxOBx5DarhHbANu4R4zXQcVE7FltV+ZNgCXy/VgaLCISguPQylZbo0u4fiYnLTnucCkJe73uGl9zYoo2v5Ftz/Sg0+qgmIcKhm2gMrmG7vTPSH8Ci/szDOzYS4hIxXZYOpz8Y0qwxIK9OfQoiKkxnx6RhmKj+SGYmNQLdTGFJdT2JX0HWoRnbAkNuDdL0c6O1Kx5ZV3vh6mRGZ18AW0laF/VBfb4wUz7LuO+knf/1c5uUrTb7+4f5LSxRxbrEivlFQxAUVa+hpnsGVuLNMd0g5+sNOYTixCPz0QgIohKyiENM1eSyEXDJ5FCgq8rQSlyUwkupoRlgSz4xyEnHTPQrV5gkwjG6HdsoNeIe1ocAgH47WpVDfEQOVVWbYvvQAVJYfwkElW4TaFz76Nq1p2XO3vrwIbI07ryjMAMjrzkMOwzFWDX3lvmd7e080yAbDqzAUX0EROEMpUk55X0KGiyGtKYKs8iQraVkOxKVJjKQpipG0RGOqgkakNA4LUK8TjGzNCMRrc8DVzUarf+NwtkdjXopHbWWQRWmfmx5vLMAs726ef0361eTyD3+SeXkZTgxR4Rtqjw9s3Y7HqsqDgw5an3137VZmzZGBpEbhw4QGZjilDoKsWuqwVZQqZZQyZ57oNIRFsYykLoCRtoZC0hoFQWUShlI46HQkAG0C0AhFpk4GWoJb2uUz/7MZ0Jd84kWq/7kNET899LWhuMDlPUZLf/Psw3sjPH7VE+q36U4s78IDTj3zmNOI0bR68DPqwOfWQFjKZcRV5pA27QHTewRMjykkbX7MyEku+mNzac2UjloTLk5bleL88czzN7ysP2GfSc/+l5Uel4Ozu0w2fNVpvMGu8/CCxC6DVWXdh+df79FaeP+29pKJXh0Fpl9/GXPXYiMeuB7EkIcWhjz3Q1JrBPTrQ3ZZHdJWAritw/49fX0/jUTG6PewZjpc3Kkj22DAWhl3jRUwYLCc6dNTEPTqLXlwU3dJR4/xmvKuI4sTu8w228k9yL08t/FuQ4Vf3Lba6N+pu5zfoblg+obWfKZX9wtm0GgxHpgtwZDtEjxyWILHTosw4roQY56fg3/8M9InGPf+CJKqHWBuHsb0ZVXIzu8Cc0MTzB1d9m/RSRX2Pv7xj8H3/AhjHnMx6joXI04fYNj+fTyy+QgPLefjnulC9Bt9gjsGn6JTZ9H0dZ2l/B6Tdb5ybz8KcP/4XpOHLptx12ozBgw3MAOGKzBovAD3TD7E42PzMZFji6lmLiO8VAhRcwKmCkyZcZ/3wXeZTXqJ+sFaTF9Vh+zPeyA7twvT1/aC6dCA7MJuiArWs/fwj/2WYOdgMt+EETWfgOhyLoQtHEzkWuERveOe+UcYMCMI01W4abyeuWO5mRm024r7XnuNfhTgcdCWC2NBezAaoIFh730Yct+Bh86KGCsIgeTBLUiH+yF53Pe0ZnW/E4I8BwzZLcRwyCZaOuwgKc8ofTtGuaSkrRgOXk33fAJBrg0k9zrYZ/y1JA9vY7w4lnnooo5HLgfw2F0LI176GPbUwQMP1Qt/1/y91NhfT8Rsn5yM2w9B1EHww9RIW6h10v7ygiemp+71QDDYTZ/vPAWarEvBQ6f1uGe7Dndt11K9Fvft1rF6YLcGj5xXYaox+XvPEty9gan7PU+f8Z2mzmZTI6pj1E8LfD9TjPma0ecDk3cCbV/8QQBhWtD/TCVRZ0s8iMkThzEZr0YjyjHm2Qe3N9TCQFkXS95cA4U3l0Jr/WbU56Y+vS4odGMeOqzCg6Nr8NCeWvzoStIK6jPLISj4y7POnuLAXG0xlOe/DqWP3oH1bmVca6z8HoQg/zgzFnCIAIxJ5hjz04fc498B8P9winMIUymHMcXRwlTSXkhun3v6wMvVlVjyxlp8/tJyzHtpKea/vAAKr7yPtW+9iZxw35lWHWjHiN8mPHZdiWH3LzHssZzCvxxjgWshGWxn7ylI9MS2L38OpYU/g+InL2LjnJex+o03sPrtufSO00/fJ+5po9/JAYzA9zcnyQH8f3hSE6YFvitM12GEPG1QDWEejeUj/ZCNDrAP1FitiS9mr2A176VlBPAnLHllLla98Sa2fPg27l0/P5NKBTYY8V2FUf+VGPVdwdaT+VbstQddF7Bz/W+g9OUsKC2ehS2fvohN783Gmjdfx5evvkMRVXwmnfowHmfJ8P2NMR5gQQAGBBD4N6eDT8swN/5lUbaxSJR1BMIsfYgrvTHNH4RsbAAjd65hwSuryPxKVvMoCl/MXohFr3yMla+/jQ3/8zuUcsLZFwsb46jvrAM/dC34IWtYCRuj2WtneMG03p/1PYCvPngJ695+FSteexvLX3sPw7fb/5JGPG9mPNAM44GWGPM3lg6nhL/0gwDymVCYbdsnytGDKM8A4mofFkAu/kAn/vTqGmr1VazkUfh89hIsfOVTfPna77H+979DYVwAGzHxhXRmIvZrTMR89VTiCzMDQXGKzwzACpLCLGyd90tsnvtbaoBX2DRa8focjPReewbgODMRbMFGYDzUou9HZ+vJHPeT4pPU+oUmEJ+xfwog18GNmk8B5Pp89nL86eXPsezVOWTgdXS2VLDpJm6Opz60B1PJKlQrUV9Sou+i2Wvd5yuwbTXl/8oZAKX5P8fXf/wNNr07m42CwebNbOp8l0KCEzaYCLYCP8AMI5FOxX/fvRwg19eGNX/KApISC0wP/hnMxD0w43dxpb4Wy97a+EwUVmLBywuh8Lv3cVxfk001Oai43B2iTC2IMg6SNCDiqtOS2p69Llegk/oMwLJZbEfe8tkLbBQU576B9sYyFlQuSXcLMxFq/ASARqIoV+sfBRjLCJsrKT0qk5RaQS5payQLAMF9Vteam3Bo42E2neQAq95dhzi34xA96p3pL4MXIS6ygCjfhGQIcZ4+RDk6VGtBNnCevUf06DbSwmygvvFVKC2ahW0LXqDTu9XoaC57CikbpbkgL4CZCDHHeJAlAZjKRjmhz7esFp7yqZGctoWkzA6SSjtM3yhlIaYfdVFEyMRgG0Y6z+F+558hHr4zEyG5xmiSawymTYwtbXKsaF9sSTBmlI5GEBfo0TrJGdOjBErRnAHpxb2Ocxi+WgPpDblqqQGusACi1lxMh
1441BuxrT8eRENoxDH22PG5iiA3ZKuk3IWRVNhDWn0UsloHyFr8MH32GMmF5EZyh6wtALKuYjLeC2bkFq134mg/7AJJhRPB29Mmhxqg1JpNRUmRESQndWi16gJG3hCPeyA9HwvxSU2I0nfS8Eh9JmkfTZ4HMJlqwQgi9TERavoEgEagWH+ln3QyJyoJrpObkdWQ+VrK3zqqm74DcMd0swcrWROplUBa/egzQTW40b2u9DsXgnGivbEDJOUUzVLaExRqkWF1SIo1KTKHIM5RgSiLxCWA1D20AiCAWE1axhx50voWrPiRno0/+b89guzQLyTlAQJptctMBGrtIKt3fBKFGQCZPAoNx8iwI7W6LR6lmzKyK7TBb+eR0iG7mgLZtxxSEqSX6filwodO6XYzIuoP4nwNiHN3zEBkqECYokrLlwMQRGtDECFvfRNMhFjS0OkkHI8PnP+TzD+FKIiwlFb6MdIa5xmAOlKDw0wU5BGgWlZrTXthHfS6LEL8Bx+iyfEo7pTkYOSbFgi6vsF41yUMtdahi5uIoh3KOPHeB+h1U6BoHKFo7COInTRi7aDhVg2TcYcJQBeCSBp5Ish8mCPGYwPM/yHz8iKfNASnYuKkld7MTCrZEgSpwXHGfKMTnQWZQFp6EILExQx33vuM3GDmR3NQPu8dNCwgLfwDU0af5d/Jr8nvmUxexkgKdalPEEQ+7RN4BJBEuX/iCAEYQxBjiYmoY3RcGRH3T28zhekhvxSVRKRJq7yeQBx9Eg1HSin6XGNGEdCmltyOXtu5TM3C95i+dX/EA8WFeKi0mJHr7qbPcWv1B6haMIfptfuYERfQ1rOY+oQcIG/Xkw6sg8kEI5q4rDAR7URroJAU+bv/OfdPivxUeLIwzI8iIZNVU87XUMuzMHYsgKyaRphSGu+zFDHusAwCzV2YMqZVrRWtqSzImK46xnatx4jpFzQnqLHzi6TYmIbWvZQ+dC9Hm2ZtY0wmm2Eizlk6lhDi99wn0T+lTORHbRef8e+XVnkwJBpi5TCWBGBIB1mGNOLQDH5SC5POBozIWp81LzSjZbmBBib11AlQ98mQqsvmvyh7L4Q8gswwxFSaKTOR5HZ3NDFC5V9u/NkykhPz2lRxWJik3FcgrfIGC1JlR2lkRDpCB1pkMtOBEYa6QOjrAKGPPSbdLTEVQRNZ4UFKm/2U94coEkdItDzONsBUuvXEeLJvyDAn+tV/q/nvgWSd+IOwONhTfCbwjryTSys9aPKi4fS0fOIyhyTXkZHyaC7gHaO9Bc3K+bq0tDCiVa4Z1aQ8U2Yq16FPkOnlOZwc985/zPhfl96cwl/w82PWCosCvYUlQXWSMp9H0kovmbSCZnJazYpLj9JJhQ2dSFgzogL7R5O5rg1T2W5eY5kR6+S//a8Z/6HSm8b5+XhG7FuinMB5Q/nxS+USZgV+Kv9Ofu2/7e//y7+6/C8AAAD//7VwhQsAAAAGSURBVAMAVuxxlU69PagAAAAASUVORK5CYII=`,Zae={avatar:Xae,content:tae,description:"Manage the LobeHub platform via the `lh` CLI — INCLUDING modifying THIS agent's own configuration. ACTIVATE this skill whenever the user asks you to: change your system prompt / instructions / persona, enable or disable tools / plugins / skills, switch model or provider, attach knowledge bases or files, edit the opening message, rename the topic, OR operate on any other platform resource (agents, topics, memory, documents, search, content generation, model/provider/plugin management, bot integrations, evals, usage stats). ALSO ACTIVATE when the user asks to connect, link, or set up a messaging platform bot — including Discord, Telegram, Slack, Feishu (飞书), Lark, QQ, or WeChat (微信) — or uses phrases like '帮我链接 Discord', 'connect my Slack', '接入飞书', '配置 QQ 机器人', 'link WeChat'. Without activation you cannot persist any change — you can only describe what you would do.",identifier:Yae,name:`lobehub`,resources:jc({"references/agent":rae,"references/bot":aae,"references/bot/discord":sae,"references/bot/feishu":lae,"references/bot/lark":dae,"references/bot/qq":pae,"references/bot/slack":hae,"references/bot/telegram":_ae,"references/bot/wechat":yae,"references/config":xae,"references/doc":Cae,"references/eval":Tae,"references/file":Dae,"references/generate":kae,"references/kb":jae,"references/memory":Nae,"references/message":Fae,"references/model":Lae,"references/plugin":zae,"references/provider":Vae,"references/search":Uae,"references/skill":Gae,"references/topic":qae}),source:`builtin`}})),$ae,eoe=e((()=>{$ae='# lh task - Complete Command Reference\n\n## Core Commands\n\n- `lh task list [--status <status>] [--root] [--parent <id>] [--agent <id>] [-L <limit>] [--tree]` - List tasks\n  - `--status`: pending, running, paused, completed, failed, canceled\n  - `--root`: Only root tasks (no parent)\n  - `--tree`: Display as tree structure\n- `lh task view <id>` - View task details (instruction, workspace, activities)\n- `lh task create -i <instruction> [-n <name>] [--agent <id>] [--parent <id>] [--priority <0-4>]` - Create task\n  - Priority: 0=none, 1=urgent, 2=high, 3=normal, 4=low\n- `lh task edit <id> [-n <name>] [-i <instruction>] [--status <status>] [--priority <0-4>] [--agent <id>]` - Update task\n- `lh task delete <id> [--yes]` - Delete task\n- `lh task clear [--yes]` - Delete all tasks\n- `lh task tree <id>` - Show subtask tree with dependencies\n\n## Lifecycle Commands\n\n- `lh task start <id> [--no-run] [-p <prompt>] [-f] [-v]` - Start task (pending → running)\n  - `--no-run`: Only update status, skip agent execution\n  - `-f, --follow`: Follow agent output in real-time\n  - `-v, --verbose`: Show detailed tool call info\n- `lh task run <id> [-p <prompt>] [-c <topicId>] [-f] [--topics <n>] [--delay <s>]` - Run/re-run agent execution\n  - `-c, --continue`: Continue on existing topic\n  - `--topics <n>`: Run N topics in sequence\n- `lh task pause <id>` - Pause running task\n- `lh task resume <id>` - Resume paused task\n- `lh task complete <id>` - Mark as completed\n- `lh task cancel <id>` - Cancel task\n- `lh task comment <id> -m <message>` - Add comment\n- `lh task sort <parentId> <id1> <id2> ...` - Reorder subtasks\n- `lh task heartbeat <id>` - Send manual heartbeat\n- `lh task watchdog` - Detect and fail stuck tasks\n\n## Checkpoint Commands\n\n- `lh task checkpoint view <id>` - View checkpoint config\n- `lh task checkpoint set <id> [--on-agent-request <bool>] [--topic-before <bool>] [--topic-after <bool>] [--before <ids>] [--after <ids>]` - Configure checkpoints\n  - `--on-agent-request`: Allow agent to request review\n  - `--topic-before/after`: Pause before/after each topic\n  - `--before/after <ids>`: Pause before/after specific subtask identifiers\n\n## Review Commands (LLM-as-Judge)\n\n- `lh task review view <id>` - View review config\n- `lh task review set <id> [--model <model>] [--provider <provider>] [--max-iterations <n>] [--no-auto-retry] [--recursive]` - Configure review\n- `lh task review criteria list <id>` - List review rubrics\n- `lh task review criteria add <id> -n <name> [--type <type>] [-t <threshold>] [-d <description>] [--value <value>] [--pattern <pattern>] [-w <weight>] [--recursive]` - Add rubric\n  - Types: llm-rubric, contains, equals, starts-with, ends-with, regex\n  - Threshold: 0-100\n- `lh task review criteria rm <id> -n <name> [--recursive]` - Remove rubric\n- `lh task review run <id> --content <text>` - Manually run review\n\n## Dependency Commands\n\n- `lh task dep add <taskId> <dependsOnId> [--type <blocks|relates>]` - Add dependency\n- `lh task dep rm <taskId> <dependsOnId>` - Remove dependency\n- `lh task dep list <taskId>` - List dependencies\n\n## Topic Commands\n\n- `lh task topic list <id>` - List topics for task\n- `lh task topic view <id> <topicId>` - View topic messages (topicId can be seq number like "1")\n- `lh task topic cancel <topicId>` - Cancel running topic and pause task\n- `lh task topic delete <topicId> [--yes]` - Delete topic and messages\n\n## Document Commands (Workspace)\n\n- `lh task doc create <id> -t <title> [-b <content>] [--parent <docId>] [--folder]` - Create and pin document\n- `lh task doc pin <id> <documentId>` - Pin existing document\n- `lh task doc unpin <id> <documentId>` - Unpin document\n- `lh task doc mv <id> <documentId> <folder>` - Move document into folder (auto-creates folder)\n\n## Tips\n\n- All commands support `--json [fields]` for structured output\n- Task identifiers use format like TASK-1, TASK-2, etc.\n- Use `lh task tree` to visualize full task hierarchy before planning work\n- Use `lh task comment` to log progress — comments appear in task activities\n- Documents in workspace are accessible to the agent during execution\n'})),toe,noe=e((()=>{toe=`\\<task_skill_guides>
1442You are executing a task within the LobeHub task system. Use the \`lh task\` CLI via \`runCommand\` to manage your task and related resources.
1443
1444# Task Lifecycle
1445
1446| Command                         | Description                                           |
1447| ------------------------------- | ----------------------------------------------------- |
1448| \`lh task view <id>\`             | View task details, instruction, workspace, activities |
1449| \`lh task edit <id>\`             | Update task name, instruction, status, priority       |
1450| \`lh task complete <id>\`         | Mark task as completed                                |
1451| \`lh task comment <id> -m "..."\` | Add a progress comment                                |
1452| \`lh task tree <id>\`             | View subtask tree with dependencies                   |
1453
1454# Working with Subtasks
1455
1456| Command                                   | Description       |
1457| ----------------------------------------- | ----------------- |
1458| \`lh task create -i "..." --parent <id>\`   | Create a subtask  |
1459| \`lh task list --parent <id>\`              | List subtasks     |
1460| \`lh task sort <parentId> <id1> <id2> ...\` | Reorder subtasks  |
1461| \`lh task dep add <id> <dependsOnId>\`      | Add dependency    |
1462| \`lh task dep rm <id> <dependsOnId>\`       | Remove dependency |
1463
1464# Task Workspace (Documents)
1465
1466| Command                                           | Description               |
1467| ------------------------------------------------- | ------------------------- |
1468| \`lh task doc create <id> -t "title" -b "content"\` | Create and pin a document |
1469| \`lh task doc pin <id> <docId>\`                    | Pin existing document     |
1470| \`lh task doc unpin <id> <docId>\`                  | Unpin document            |
1471
1472# Task Topics (Conversations)
1473
1474| Command                             | Description              |
1475| ----------------------------------- | ------------------------ |
1476| \`lh task topic list <id>\`           | List conversation topics |
1477| \`lh task topic view <id> <topicId>\` | View topic messages      |
1478
1479# Usage Pattern
1480
14811. Read the reference file for detailed command options: \`readReference('references/commands')\`
14822. Run commands via \`runCommand\` — the \`lh\` prefix is automatically handled
14833. Use \`--json\` flag on any command for structured output
14844. Use \`lh task <subcommand> --help\` for full command-line help
1485
1486# Task Execution Guidelines
1487
1488- **Check your task first**: Use \`lh task view\` to understand the full instruction and context
1489- **Use workspace documents**: Store outputs and deliverables as task documents
1490- **Report progress**: Use \`lh task comment\` to log key milestones
1491- **Respect dependencies**: Check \`lh task tree\` to understand task ordering
1492- **Complete when done**: Use \`lh task complete\` when all deliverables are ready
1493  \\</task_skill_guides>
1494`})),roe,ioe,aoe=e((()=>{Mc(),eoe(),noe(),roe=`task`,ioe={avatar:`📋`,content:toe,description:`Task management and execution — create, track, review, and complete tasks via CLI.`,identifier:roe,name:`task`,resources:jc({"references/commands":$ae}),source:`builtin`}})),ooe,soe,coe,loe,uoe,doe,foe,poe,Nc,moe,hoe,goe,_oe,voe,yoe,boe,xoe,Soe=e((()=>{ooe=`/index.html`,soe=`/index.tsx`,coe=`/App.tsx`,loe=`/index.html`,uoe=`/vite.config.ts`,doe=`/package.json`,foe={"@ant-design/icons":`latest`,"@lshay/ui":`latest`,"@radix-ui/react-accordion":`latest`,"@radix-ui/react-alert-dialog":`latest`,"@radix-ui/react-avatar":`latest`,"@radix-ui/react-checkbox":`latest`,"@radix-ui/react-collapsible":`latest`,"@radix-ui/react-dialog":`latest`,"@radix-ui/react-dropdown-menu":`latest`,"@radix-ui/react-icons":`latest`,"@radix-ui/react-label":`latest`,"@radix-ui/react-navigation-menu":`latest`,"@radix-ui/react-popover":`latest`,"@radix-ui/react-progress":`latest`,"@radix-ui/react-scroll-area":`latest`,"@radix-ui/react-select":`latest`,"@radix-ui/react-separator":`latest`,"@radix-ui/react-slider":`latest`,"@radix-ui/react-slot":`latest`,"@radix-ui/react-switch":`latest`,"@radix-ui/react-tabs":`latest`,"@radix-ui/react-toast":`latest`,"@radix-ui/react-tooltip":`latest`,antd:`latest`,"class-variance-
1494authority":`latest`,cmdk:`latest`,clsx:`latest`,"date-fns":`latest`,"embla-carousel-react":`latest`,"input-otp":`latest`,"lodash-es":`latest`,"lucide-react":`^0.544.0`,motion:`latest`,react:`19.2.7`,"react-day-picker":`latest`,"react-dom":`19.2.7`,"react-router":`latest`,recharts:`latest`,sonner:`latest`,"tailwind-merge":`latest`,vaul:`latest`,zustand:`latest`},poe={"@types/react":`latest`,"@types/react-dom":`latest`,"@vitejs/plugin-react":`latest`,typescript:`latest`,vite:`latest`},Nc=`https://cdn.tailwindcss.com`,moe=[Nc],hoe={"@/components/ui":`@lshay/ui/components/default`},goe=e=>e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`),_oe=e=>`<!DOCTYPE html>
1495<html lang="en">
1496  <head>
1497    <meta charset="UTF-8" />
1498    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
1499    <title>${goe(e)}</title>
1500    <script src="${Nc}"><\/script>
1501  </head>
1502  <body>
1503    <div id="root"></div>
1504    <script type="module" src="/index.tsx"><\/script>
1505  </body>
1506</html>
1507`,voe=`import { StrictMode } from 'react';
1508import { createRoot } from 'react-dom/client';
1509
1510import App from './App';
1511
1512const container = document.getElementById('root');
1513if (!container) throw new Error('Root container #root not found');
1514
1515createRoot(container).render(
1516  <StrictMode>
1517    <App />
1518  </StrictMode>,
1519);
1520`,yoe=`import react from '@vitejs/plugin-react';
1521import { defineConfig } from 'vite';
1522
1523export default defineConfig({
1524  base: './',
1525  plugins: [react()],
1526  resolve: {
1527    alias: ${JSON.stringify(hoe,null,6)},
1528  },
1529});
1530`,boe=(e,t,n)=>`${JSON.stringify({name:`lobe-artifact-react-app`,private:!0,version:`0.0.0`,type:`module`,scripts:{build:`vite build`,dev:`vite`,preview:`vite preview`},description:e,dependencies:t,devDependencies:n},null,2)}\n`,xoe=e=>{let{appCode:t,extraFiles:n,overrides:r,title:i}=e,a=i??`Artifacts App`,o={...foe,...r?.packageJson?.dependencies},s={...poe,...r?.packageJson?.devDependencies},c={[coe]:r?.appCode??t,[soe]:r?.entry??voe,[loe]:r?.indexHtml??_oe(a),[doe]:boe(a,o,s),[uoe]:r?.viteConfig??yoe};if(n)for(let[e,t]of Object.entries(n)){let n=e.startsWith(`/`)?e:`/${e}`;c[n]=t}return{dependencies:o,devDependencies:s,entry:ooe,externalResources:moe,files:c}}})),Coe,woe=e((()=>{Coe=`# agent-browser CLI reference
1531
1532Generic reference for the \`agent-browser\` CLI — automate Chromium-based apps
1533(Electron, Chrome, web) via Chrome DevTools Protocol. This is the capture engine
1534for all UI evidence in this skill. Per-surface patterns live in
1535[../surfaces/web.md](../surfaces/web.md) and
1536[../surfaces/electron.md](../surfaces/electron.md); auth recipes in
1537[auth.md](./auth.md).
1538
1539Install via \`npm i -g agent-browser\`, \`brew install agent-browser\`, or
1540\`cargo install agent-browser\`. Run \`agent-browser install\` to download Chrome.
1541Run \`agent-browser upgrade\` to update.
1542
1543## Core workflow
1544
1545Every browser automation follows this pattern:
1546
15471. **Navigate**: \`agent-browser open <url>\`
15482. **Snapshot**: \`agent-browser snapshot -i\` (get element refs like \`@e1\`, \`@e2\`)
15493. **Interact**: use refs to click, fill, select
15504. **Re-snapshot**: after navigation or DOM changes, get fresh refs
1551
1552\`\`\`bash
1553agent-browser open https://example.com/form
1554agent-browser snapshot -i
1555# Output: @e1 [input type="email"], @e2 [input type="password"], @e3 [button] "Submit"
1556
1557agent-browser fill @e1 "[email protected]"
1558agent-browser fill @e2 "password123"
1559agent-browser click @e3
1560agent-browser wait --load networkidle
1561agent-browser snapshot -i # check result
1562\`\`\`
1563
1564## Command chaining
1565
1566\`\`\`bash
1567agent-browser open https://example.com && agent-browser wait --load networkidle && agent-browser snapshot -i
1568\`\`\`
1569
1570Use \`&&\` when you don't need to read intermediate output. Run commands separately
1571when you need to parse output first (e.g. snapshot to discover refs, then interact).
1572
1573## Essential commands
1574
1575\`\`\`bash
1576# Navigation
1577agent-browser open <url>              # Navigate (aliases: goto, navigate)
1578agent-browser close                   # Close browser
1579agent-browser close --all             # Close all active sessions
1580
1581# Snapshot
1582agent-browser snapshot -i             # Interactive elements with refs (recommended)
1583agent-browser snapshot -i -C          # Include contenteditable (rich text editors)
1584agent-browser snapshot -s "#selector" # Scope to CSS selector
1585
1586# Interaction (use @refs from snapshot)
1587agent-browser click @e1               # Click element
1588agent-browser click @e1 --new-tab     # Click and open in new tab
1589agent-browser fill @e2 "text"         # Clear and type text (NOT for contenteditable)
1590agent-browser type @e2 "text"         # Type without clearing (use for chat inputs)
1591agent-browser select @e1 "option"     # Select dropdown option
1592agent-browser check @e1               # Check checkbox
1593agent-browser press Enter             # Press key
1594agent-browser keyboard type "text"    # Type at current focus (no selector)
1595agent-browser scroll down 500         # Scroll page
1596agent-browser scroll down 500 --selector "div.content"  # Scroll within container
1597
1598# Get information
1599agent-browser get text @e1            # Get element text
1600agent-browser get url                 # Get current URL
1601agent-browser get title               # Get page title
1602
1603# Wait
1604agent-browser wait @e1                # Wait for element
1605agent-browser wait --load networkidle # Wait for network idle
1606agent-browser wait --url "**/page"    # Wait for URL pattern
1607agent-browser wait 2000               # Wait milliseconds
1608agent-browser wait --text "Welcome"   # Wait for text to appear
1609agent-browser wait --fn "!document.body.innerText.includes('Loading...')"  # Wait for condition
1610agent-browser wait "#spinner" --state hidden  # Wait for element to disappear
1611
1612# Network (key for full-stack evidence)
1613agent-browser network requests                 # Inspect tracked requests
1614agent-browser network requests --type xhr,fetch  # Filter by resource type
1615agent-browser network requests --method POST   # Filter by HTTP method
1616agent-browser network har start                # Start HAR recording
1617agent-browser network har stop ./capture.har   # Stop and save HAR file
1618
1619# Viewport & device emulation
1620agent-browser set viewport 1920 1080          # Set viewport size (default 1280x720)
1621agent-browser set viewport 1920 1080 2        # 2x retina
1622agent-browser set device "iPhone 14"          # Emulate device (viewport + UA)
1623
1624# Capture (evidence!)
1625agent-browser screenshot ./shot.png   # Screenshot to a path
1626agent-browser screenshot --full       # Full page screenshot
1627agent-browser screenshot --annotate   # Annotated screenshot with numbered element labels
1628agent-browser pdf output.pdf          # Save as PDF
1629
1630# Dialogs (alert, confirm, prompt, beforeunload)
1631agent-browser dialog accept           # Accept dialog
1632agent-browser dialog accept "input"   # Accept prompt dialog with text
1633agent-browser dialog dismiss          # Dismiss/cancel dialog
1634agent-browser dialog status           # Check if dialog is open
1635\`\`\`
1636
1637## Batch execution
1638
1639\`\`\`bash
1640echo '[
1641  ["open", "https://example.com"],
1642  ["snapshot", "-i"],
1643  ["click", "@e1"],
1644  ["screenshot", "result.png"]
1645]' | agent-browser batch --json
1646\`\`\`
1647
1648## Semantic locators (alternative to refs)
1649
1650\`\`\`bash
1651agent-browser find text "Sign In" click
1652agent-browser find label "Email" fill "[email protected]"
1653agent-browser find role button click --name "Submit"
1654agent-browser find placeholder "Search" type "query"
1655agent-browser find testid "submit-btn" click
1656\`\`\`
1657
1658## JavaScript evaluation (eval)
1659
1660Use eval to read app state, dump DOM/HTML, or assert computed values for \`text\` /
1661\`dom_snapshot\` evidence.
1662
1663\`\`\`bash
1664# Simple expressions
1665agent-browser eval 'document.title'
1666
1667# Complex JS: use --stdin with heredoc (RECOMMENDED — avoids shell quoting bugs)
1668agent-browser eval --stdin << 'EVALEOF'
1669JSON.stringify(
1670  Array.from(document.querySelectorAll("img"))
1671    .filter(i => !i.alt)
1672    .map(i => ({ src: i.src.split("/").pop(), width: i.width }))
1673)
1674EVALEOF
1675
1676# Base64 encoding (avoids all shell escaping issues)
1677agent-browser eval -b "$(echo -n 'document.title' | base64)"
1678\`\`\`
1679
1680> If the app under test exposes a global state object (a store, a debug handle),
1681> eval is how you read it for assertion. Don't assume a specific global name —
1682> discover it from the app you are verifying.
1683
1684## Ref lifecycle
1685
1686Refs (\`@e1\`, \`@e2\`, …) are invalidated when the page changes. Always re-snapsh
1686ot
1687after clicking links/buttons that navigate, form submissions, or dynamic content
1688loading. After a hot-reload (HMR) during dev, refs also break — re-snapshot.
1689
1690## Annotated screenshots (vision mode)
1691
1692\`\`\`bash
1693agent-browser screenshot --annotate
1694# Output includes the image path and a legend:
1695#   [1] @e1 button "Submit"
1696#   [2] @e2 link "Home"
1697agent-browser click @e2 # click using ref from annotated screenshot
1698\`\`\`
1699
1700## Parallel sessions
1701
1702\`\`\`bash
1703agent-browser --session site1 open https://site-a.com
1704agent-browser --session site2 open https://site-b.com
1705agent-browser session list
1706\`\`\`
1707
1708A named \`--session\` auto-saves and restores cookies + localStorage, which is the
1709basis for the auth recipes in [auth.md](./auth.md).
1710
1711## Connect to an existing browser / app
1712
1713\`\`\`bash
1714agent-browser --auto-connect snapshot # Auto-discover a running Chrome
1715agent-browser --cdp 9222 snapshot     # Explicit CDP port (Electron apps, see ../surfaces/electron.md)
1716\`\`\`
1717
1718## Cloud providers & engine selection
1719
1720\`\`\`bash
1721agent-browser -p browserbase open example.com      # run against a cloud browser
1722agent-browser --engine lightpanda open example.com # 10x faster, 10x less memory
1723\`\`\`
1724
1725Providers: \`agentcore\`, \`browserbase\`, \`browserless\`, \`browseruse\`, \`kernel\`.
1726
1727## Gotchas
1728
1729- **Daemon can get stuck** — if commands hang, \`agent-browser close --all\` or
1730  \`pkill -f agent-browser\` to reset.
1731- **HMR invalidates everything** — after code changes during dev, refs break;
1732  re-snapshot or restart.
1733- **\`snapshot -i\` doesn't find contenteditable** — use \`snapshot -i -C\` for rich
1734  text editors; \`fill\` doesn't work on contenteditable, use \`type\`.
1735- **Screenshots written to a path are easiest** — \`agent-browser screenshot
1736./proof/x.png\` then upload that path; with no path they land in
1737  \`~/.agent-browser/tmp/screenshots/\`.
1738- **Dialogs block all commands** — if commands time out, check
1739  \`agent-browser dialog status\`.
1740- **Default timeout is 25s** — override with \`AGENT_BROWSER_DEFAULT_TIMEOUT\` (ms)
1741  or use explicit waits.
1742- **Shell quoting corrupts eval** — use \`eval --stdin <<'EVALEOF'\` for complex JS.
1743`})),Toe,Eoe=e((()=>{Toe=`# Auth — getting past the login gate (portable)
1744
1745If the state a criterion checks is behind a login, you must authenticate the
1746surface **before** capturing — otherwise every screenshot lands on the sign-in
1747page and the evidence is worthless. Auth is a gate, but it is **surface-scoped**:
1748authenticate only the surface you're proving on, not all of them.
1749
1750This file is portable to any Chromium-based app. It does not assume any specific
1751auth provider, cookie name, or seed script — discover those from the app you are
1752verifying.
1753
1754## Decision flow
1755
17561. **Is the target behind auth at all?** Open it; if it renders the state under
1757   test without a login wall, skip this file.
17582. **Pick the cheapest mechanism that works for the surface** (table below).
17593. **Verify the session is authenticated** before you start capturing: navigate
1760   to a protected URL and assert you did _not_ get redirected to the sign-in page
1761   (\`agent-browser ... get url\` should not be the login route).
1762
1763## Mechanisms (web / Chrome surface)
1764
1765\`agent-browser\` has four built-in ways to carry auth — prefer these over manual
1766login, which is unreliable in headless/off-screen windows.
1767
1768\`\`\`bash
1769# 1. Named session — auto-saves & restores cookies + localStorage across commands
1770agent-browser --session app open https://app.example.com/login
1771# ... complete login once (or inject state) ...
1772agent-browser --session app open https://app.example.com/dashboard # restored
1773
1774# 2. State file — export/import a Playwright-style storageState
1775agent-browser state save auth.json
1776agent-browser state load auth.json
1777
1778# 3. Auth vault — store credentials encrypted, replay the login form
1779echo "$PASSWORD" | agent-browser auth save app --url https://app.example.com/login \\
1780  --username user --password-stdin
1781agent-browser auth login app
1782
1783# 4. Persistent profile — a dedicated user-data dir that keeps you logged in
1784agent-browser --profile ~/.app-profile open https://app.example.com/login
1785\`\`\`
1786
1787### Programmatic login (when the app has an email/password endpoint)
1788
1789If the app exposes a sign-in API, the most reliable headless path is to POST
1790credentials, capture the returned cookies, and load them as a state file — no UI
1791login needed. Shape (adapt the endpoint + cookie handling to the app):
1792
1793\`\`\`bash
1794# POST credentials, save the cookie jar, convert to a storageState file,
1795# then load it into the agent-browser session and verify you're not on /signin.
1796# (endpoint, field names, and cookie names are app-specific — inspect them first)
1797\`\`\`
1798
1799### Cookie-injection fallback (local dev only)
1800
1801When headless login isn't available, copy the session cookie out of a browser
1802where you're already logged in and inject it:
1803
18041. In a logged-in browser, open DevTools → **Network** tab → click any
1805   same-origin request → **Request Headers** → copy the full \`Cookie:\` value.
1806   It MUST come from a Network request, **not** \`document.cookie\` — HttpOnly
1807   session cookies are invisible to \`document.cookie\`.
18082. Build a state file with those cookies and \`agent-browser state load\` it (or use
1809   the session). Match the cookie **domain exactly** — e.g. \`localhost\`, not
1810   \`127.0.0.1\`, and no leading dot for local dev.
18113. Verify: open a protected URL, confirm you're not redirected to sign-in.
1812
1813Common failure modes:
1814
1815| Symptom                                    | Cause                                                   | Fix                                            |
1816| ------------------------------------------ | ------------------------------------------------------- | ---------------------------------------------- |
1817| Still redirects to sign-in after injection | Copied from \`document.cookie\` → missed HttpOnly session | Re-copy from a Network request's headers       |
1818| "no cookies found"                         | Pasted the wrong value                                  | Keep the raw \`Cookie:\` header verbatim         |
1819| Works briefly then expires                 | Session token rotated (logged out elsewhere)            | Re-copy and re-inject                          |
1820| Domain mismatch                            | Cookie domain must match the URL host exactly           | Use the literal host, no leading dot for local |
1821
1822## Desktop (Electron) {#desktop}
1823
1824A desktop app usually keeps its own persistent login state in its user-data
1825directory: **log in once inside the app** and it survives restarts. No injection.
1826Once connected over CDP, verify auth by reading the app's own signed-in state
1827(eval its global / a protected element) rather than assuming.
1828
1829## CLI / backend surface
1830
1831For text evidence from a CLI, the CLI carries its own auth (an API key or a stored
1832login). The \`lh\` CLI you use to upload evidence is already authed; a different
1833product CLI under test uses its own mechanism — ensure it's configured before
1834capturing its output.
1835
1836## Boundaries — read before touching cookies
1837
1838- **Local dev only.** These injection recipes are for local/dev targets. Don't
1839  inject cookies on production: production cookies are typically
1840  \`Secure; HttpOnly\` over HTTPS and must not be copied around.
1841- **Treat any cookie/token as a secret.** Never paste it into shared logs, PR
1842  descriptions, commit messages, or evidence you upload. Evidence artifacts are
1843  visible to reviewers — a screenshot or text dump must not contain a live token.
1844- **Injection is one-way.** It seeds the automation session; it does not flow back
1845  into your own browser.
1846- **Exercising the login UI itself needs a real browser flow.** If the criterion
1847  is _about_ the sign-in screen, drive a real Chromium with remote debugging
1848  rather than injecting past it.
1849`})),Doe,Ooe=e((()=>{Doe=`# macOS Computer Use (osascript) toolkit
1850
1851\`agent-browser\` drives Chromium surfaces (web, Electron). For everything it can't
1852reach, this is the escape hatch: **macOS Computer Use** via \`osascript\`
1853(AppleScript) and \`screencapture\`. Use it to drive native apps, handle OS-level
1854chrome, and read the screen when no CDP target exists.
1855
1856This is the native/OS counterpart of [agent-browser.md](./agent-browser.md). It is
1857**macOS-only and not cloud-portable** — prefer CDP automation when both can reach
1858the target; reach here only when CDP can't.
1859
1860## When you need it
1861
1862- **Native (non-Chromium) app under test** — the thing you're verifying is a native
1863  macOS app agent-browser can't attach to. Drive it here (see
1864  [../surfaces/native.md](../surfaces/native.md)).
1865- **OS-level steps inside a web/Electron flow** — a native file picker, a system
1866  permission prompt, a Save dialog, dock/menu-bar interaction, or a Spotlight/
1867  app-switch the page can't script. Drop to Computer Use for that step, then return
1868  to agent-browser.
1869- **Reading the screen** when no DOM/CDP is available — screenshot + visual read, or
1870  select-all-copy + \`pbpaste\`.
1871
1872## Core patterns
1873
1874### Activate an app
1875
1876\`\`\`bash
1877osascript -e 'tell application "AppName" to activate'
1878\`\`\`
1879
1880### Type / press keys
1881
1882\`\`\`bash
1883osascript -e 'tell application "System Events" to keystroke "Hello world"'
1884osascript -e 'tell application "System Events" to key code 36' # Enter (hardware code, layout-independent)
1885osascript -e 'tell application "System Events" to key code 48' # Tab
1886osascript -e 'tell application "System Events" to key code 53' # Escape
1887\`\`\`
1888
1889### Paste from clipboard (fast; required for long / non-ASCII text)
1890
1891\`\`\`bash
1892osascript -e 'set the clipboard to "Your long or 中文 / emoji message"'
1893osascript -e 'tell application "System Events" to keystroke "v" using command down'
1894\`\`\`
1895
1896### Keyboard shortcuts (modifiers)
1897
1898\`\`\`bash
1899osascript -e 'tell application "System Events" to keystroke "f" using command down'               # Cmd+F
1900osascript -e 'tell application "System Events" to keystroke "k" using {command down, shift down}' # Cmd+Shift+K
1901\`\`\`
1902
1903### Click at screen coordinates
1904
1905\`\`\`bash
1906osascript -e 'tell application "System Events" to click at {500, 300}'
1907\`\`\`
1908
1909### Window position / size / id
1910
1911\`\`\`bash
1912osascript -e '
1913tell application "System Events" to tell process "AppName"
1914  get {position, size} of window 1
1915end tell'
1916\`\`\`
1917
1918### Screenshot (OS-level)
1919
1920\`\`\`bash
1921screencapture /tmp/shot.png                 # full screen
1922screencapture -i /tmp/shot.png              # interactive region select
1923screencapture -l "$WINDOW_ID" /tmp/shot.png # specific window
1924\`\`\`
1925
1926Get a window id:
1927
1928\`\`\`bash
1929osascript -e 'tell application "System Events" to tell process "AppName" to get id of window 1'
1930\`\`\`
1931
1932### Read accessibility elements
1933
1934\`\`\`bash
1935osascript -e '
1936tell application "System Events" to tell process "AppName"
1937  get value of text field 1 of window 1
1938end tell'
1939\`\`\`
1940
1941> \`entire contents of window 1\` dumps the whole UI tree but is **extremely slow**
1942> on complex apps — prefer a screenshot + visual read, or the clipboard read below.
1943
1944### Read screen text via clipboard
1945
1946\`\`\`bash
1947osascript -e '
1948tell application "System Events"
1949  keystroke "a" using command down
1950  keystroke "c" using command down
1951end tell'
1952sleep 0.5
1953pbpaste
1954\`\`\`
1955
1956## Capturing as evidence
1957
1958- A \`screencapture\` PNG → \`--type screenshot --by cli\`.
1959- For time-based native behavior, OS screen-record to MP4/GIF — see
1960  [recording.md](./recording.md#path-2--os-screen-recording-macos-local-only).
1961- Text read via \`pbpaste\` → \`--type text --content "$(pbpaste)"\`.
1962
1963## Gotchas
1964
1965- **Accessibility permission required.** First run prompts for it; grant the host
1966  (Terminal / iTerm / the agent runner) in System Settings → Privacy & Security →
1967  Accessibility, or every \`System Events\` call silently fails.
1968- **\`keystroke\` is slow and mangles non-ASCII** — use clipboard paste (\`Cmd+V\`) for
1969  anything long or for Chinese / emoji / special characters.
1970- **\`key code 36\` is Enter** by hardware code, so it works regardless of keyboard
1971  layout. Some apps send-on-Enter — use \`Shift+Enter\` for a newline within input.
1972- **Add small \`delay\`/\`sleep\` between actions** — native apps need time to process
1973  UI events; back-to-back commands drop.
1974- **App name varies by locale** — e.g. \`微信\` vs \`WeChat\`; handle the name the
1975  running OS uses.
1976- **Not cloud-portable.** Everything here needs a real macOS session with a display.
1977  Keep evidence CDP-based when the target is reachable that way.
1978`})),koe,Aoe=e((()=>{koe=`# Capturing portable evidence
1979
1980The goal is an artifact a human (and the review agent) can open and believe. Pick
1981the lightest capture that proves the criterion, and prefer engine-level capture so
1982it works the same locally and headless/cloud. UI capture uses \`agent-browser\`
1983([agent-browser.md](./agent-browser.md)) on the surface you chose
1984([web](../surfaces/web.md) / [electron](../surfaces/electron.md); backend/CLI →
1985[cli](../surfaces/cli.md)).
1986
1987## Evidence type → how to capture
1988
1989### \`screenshot\` — UI state
1990
1991Screenshots via CDP (the browser engine) need no real display:
1992
1993\`\`\`bash
1994# web (named session)
1995agent-browser --session app open "<url>"
1996agent-browser --session app click @e1 # act, after snapshot -i to get refs
1997agent-browser --session app screenshot ./proof/after.png
1998
1999# desktop (Electron, over CDP)
2000agent-browser --cdp 9222 screenshot ./proof/desktop.png
2001\`\`\`
2002
2003Avoid macOS \`screencapture\` / osascript unless the criterion is explicitly
2004native/local-only — they don't run in the cloud.
2005
2006### \`dom_snapshot\` — structure / content proof
2007
2008When the proof is "this element/text exists with these values", a DOM dump is
2009smaller and more assertable than a pixel screenshot:
2010
2011\`\`\`bash
2012agent-browser --session app eval "document.querySelector('[data-testid=list]').outerHTML" > ./proof/list.html
2013\`\`\`
2014
2015Upload as \`--type dom_snapshot --file ./proof/list.html\`.
2016
2017### \`text\` — stdout, logs, computed values
2018
2019Backend / CLI behavior is best proven by the command output itself — upload inline,
2020no file:
2021
2022\`\`\`bash
2023lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type text \\
2024  --content "$(your-cli command --json)" \\
2025  --by cli --desc "command reports success after the change"
2026\`\`\`
2027
2028A network capture (HAR) or a request/response pair from a full-stack run also
2029uploads as \`text\` (\`--file ./proof/capture.har\` or \`--content\`).
2030
2031### \`transcript\` — conversation / request log
2032
2033A saved agent conversation, request/response pair, or event log file:
2034\`--type transcript --file ./proof/run.jsonl\`.
2035
2036### \`gif\` / \`video\` — behavior over time
2037
2038Required whenever a criterion asserts change over time (streaming output, a ticking
2039timer, a loading→loaded transition, an animation, a multi-step flow) — a static
2040screenshot cannot prove these. Record a clip and upload \`--type gif\` / \`--type
2041video --file …\`. Full recipes (portable CDP frame-sequence → MP4/GIF, OS screen
2042recording, GIF-vs-MP4): [recording.md](./recording.md).
2043
2044## Provenance (\`--by\`)
2045
2046Tag how the artifact was produced so the reviewer can weigh it:
2047
2048- \`agent-browser\` — captured through agent-browser (screenshots, DOM, eval)
2049- \`cdp\` — captured directly via Chrome DevTools Protocol
2050- \`cli\` — command stdout / computed text
2051- \`program\` — produced by a script or test you ran
2052
2053## Headless / cloud portability
2054
2055The decisive constraint per surface is **how a screenshot is captured**: engine-level
2056capture (CDP) needs no display; OS-level capture is macOS-only.
2057
2058| Surface    | macOS (local) | Linux / cloud (headless)                                        | Screenshot mechanism                             |
2059| ---------- | ------------- | --------------------------------------------------------------- | ------------------------------------------------ |
2060| CLI / text | ✅            | ✅                                                              | n/a — text output                                |
2061| Web        | ✅            | ✅ headless Chromium works natively                             | CDP — no display needed                          |
2062| Electron   | ✅            | ⚠️ runs but needs a display server: wrap launch with \`xvfb-run\` | CDP works under Xvfb; OS-window capture does NOT |
2063
2064Checklist:
2065
2066- ✅ \`agent-browser screenshot\` / \`eval\` (DOM, console) — engine-level, headless-safe
2067- ✅ \`--type text --content …\` — pure text, always works
2068- ❌ \`screencapture\`, osascript, native-app screen recording — macOS-only, not
2069  cloud-safe
2070
2071When a run must stay cloud-portable, prefer CDP-based evidence over OS-level
2072capture wherever both exist.
2073
2074## Don't leak secrets
2075
2076Evidence is visible to reviewers. Never capture a screenshot or text dump that
2077contains a live token, cookie, password, or other secret — see
2078[auth.md](./auth.md#boundaries--read-before-touching-cookies).
2079`})),joe,Moe=e((()=>{joe=`# Verify plan — machine-readable format
2080
2081The plan is the contract between the task config and you, the builder. It is
2082exposed through \`lh verify plan state\` keyed off your operation id. This file
2083documents its shape and how to turn it into a per-criterion worklist. You submit
2084each criterion's evidence by its \`checkItemId\` — no separate upload handle to
2085resolve.
2086
2087## (a) \`lh verify plan state $LOBE_OPERATION_ID --json\`
2088
2089Returns the run's verify state plus the **frozen plan** (immutable once
2090confirmed):
2091
2092\`\`\`jsonc
2093{
2094  "verifyStatus": "planned",
2095  "verifyPlanConfirmedAt": "2026-06-21T07:00:00.000Z",
2096  "verifyPlan": [
2097    {
2098      "id": "vci_a1b2c3", // checkItemId — the stable join key
2099      "index": 0,
2100      "title": "Login flow reaches the workspace",
2101      "description": "After sign-in the home renders the workspace switcher",
2102      "required": true, // true ⇒ blocks delivery if unproven
2103      "verifierType": "llm",
2104      "verifierConfig": {
2105        "requiredEvidence": [
2106          // the artifacts you MUST capture
2107          { "type": "screenshot", "hint": "logged-in home with workspace switcher" },
2108        ],
2109      },
2110    },
2111  ],
2112}
2113\`\`\`
2114
2115- \`verifyPlan[].id\` is the **checkItemId** — never use \`index\` as a key, it is
2116  display ordering only.
2117- \`verifyPlan[].verifierConfig.requiredEvidence\` is the list of \`{ type, hint }\`
2118  you must satisfy. Absent or empty ⇒ this criterion is judged on text alone.
2119- \`hint\` is guidance for what the artifact should show — it is not validated, but
2120  follow it so the reviewer can recognize the proof.
2121
2122## Your worklist → submit by checkItemId
2123
2124The plan (a) is all you need. For each \`verifyPlan[]\` item with non-empty
2125\`requiredEvidence\`, capture each \`type\` and submit it by \`checkItemId\`:
2126
2127| checkItemId  | title                            | requiredEvidence |
2128| ------------ | -------------------------------- | ---------------- |
2129| \`vci_a1b2c3\` | Login flow reaches the workspace | \`screenshot\`     |
2130
2131\`\`\`bash
2132OP="$LOBE_OPERATION_ID"
2133lh acceptance run result submit --operation "$OP" --item vci_a1b2c3 --type screenshot \\
2134  --file ./proof/home.png --by agent-browser --desc "…"
2135\`\`\`
2136
2137\`lh acceptance run result submit\` resolves the session from the operation id and **creates the
2138check-result row for you** (idempotent on \`checkItemId\`), then attaches the
2139evidence — there is no \`checkResultId\` to look up first.
2140
2141## Self-check after submitting (optional)
2142
2143Once you've submitted, the result rows exist. To confirm coverage, read them back
2144and list each row's evidence:
2145
2146\`\`\`jsonc
2147// lh acceptance run result list --operation "$OP" --json
2148[
2149  {
2150    "id": "vcr_x9y8z7", // checkResultId (created by submit)
2151    "checkItemId": "vci_a1b2c3", // joins back to verifyPlan[].id
2152    "status": "running",
2153  },
2154]
2155\`\`\`
2156
2157\`\`\`bash
2158lh acceptance run evidence list "$CHECK_RESULT_ID" --json # confirm each required type is present
2159\`\`\`
2160`})),Noe,Poe=e((()=>{Noe=`# Recording — GIF & MP4 evidence
2161
2162When a criterion asserts behavior **over time** — streaming output, a loading→
2163loaded transition, a ticking timer, an animation, a multi-step flow — a static
2164screenshot can't prove it. Record a clip and upload it as \`gif\` or \`video\`
2165evidence. This is a first-class capability, not a nice-to-have: time-based claims
2166are unverifiable without it.
2167
2168Two ways to record. **Prefer the CDP frame-sequence path** — it's headless/
2169cloud-portable; OS screen recording is macOS-only.
2170
2171## Path 1 — CDP frame sequence → MP4/GIF (portable, recommended)
2172
2173Capture a sequence of \`agent-browser\` screenshots while the behavior happens, then
2174assemble with \`ffmpeg\`. Works on web (\`--session\`) and Electron (\`--cdp\`), and runs
2175headless (no display, cloud-safe) because frames come from the browser engine, not
2176the OS screen. It also sidesteps the corrupt-MP4-on-kill problem that ffmpeg screen
2177capture has.
2178
2179\`\`\`bash
2180# 1. capture frames while driving the scenario
2181FRAMES=$(mktemp -d)
2182TARGET="--session app" # or "--cdp 9222" for Electron
2183i=0
2184# start your scenario in the background or in another step, then:
2185while [ $i -lt 40 ]; do # ~20s at 0.5s/frame
2186  printf -v n "%06d" $i
2187  agent-browser $TARGET screenshot "$FRAMES/frame_$n.png"
2188  i=$((i + 1))
2189  sleep 0.5
2190done
2191
2192# 2a. assemble an MP4 (~2 fps)
2193ffmpeg -y -framerate 2 -i "$FRAMES/frame_%06d.png" \\
2194  -c:v libx264 -crf 23 -pix_fmt yuv420p ./proof/flow.mp4
2195
2196# 2b. or a GIF (good palette = legible inline)
2197ffmpeg -y -framerate 2 -i "$FRAMES/frame_%06d.png" \\
2198  -vf "scale=900:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" \\
2199  ./proof/flow.gif
2200
2201rm -rf "$FRAMES"
2202\`\`\`
2203
2204Tune the frame interval to the behavior: faster (\`0.25s\`) for quick animations,
2205slower (\`1s\`) for long flows. Keep the clip scoped — a few seconds of the actual
2206behavior, not the whole session.
2207
2208## Path 2 — OS screen recording (macOS, local only)
2209
2210When you must capture the real screen — native windows, OS chrome, a non-Chromium
2211app driven via [computer-use.md](./computer-use.md) — record at the OS level. This
2212is **macOS-only and not cloud-portable**.
2213
2214\`\`\`bash
2215# built-in: record the screen to MP4 (Ctrl-C / kill to stop; or -V N for N seconds)
2216screencapture -v ./proof/demo.mp4
2217screencapture -V 15 ./proof/demo.mp4 # fixed 15s capture
2218
2219# ffmpeg avfoundation (list devices first: ffmpeg -f avfoundation -list_devices true -i "")
2220ffmpeg -y -f avfoundation -framerate 30 -i "1:none" -t 15 \\
2221  -c:v libx264 -crf 23 -pix_fmt yuv420p ./proof/demo.mp4
2222\`\`\`
2223
2224Convert an MP4 to GIF when you need an inline-renderable artifact:
2225
2226\`\`\`bash
2227ffmpeg -y -i ./proof/demo.mp4 \\
2228  -vf "fps=8,scale=900:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" \\
2229  ./proof/demo.gif
2230\`\`\`
2231
2232## GIF vs MP4 — which to upload
2233
2234- **GIF** — short (≤ \\~10s) UI behavior that should render inline in the report
2235  (loading state, a toast, a streamed line appearing). Renders without a player.
2236- **MP4** — longer demos or multi-step flows where file size matters and a player
2237  is acceptable. Larger, but better quality per byte.
2238
2239## Upload
2240
2241\`\`\`bash
2242lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type gif \\
2243  --file ./proof/flow.gif --by agent-browser \\
2244  --desc "Response streams in token-by-token after send"
2245
2246lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type video \\
2247  --file ./proof/demo.mp4 --by cdp --desc "End-to-end import flow completes"
2248\`\`\`
2249
2250## Prerequisites & portability
2251
2252- **ffmpeg** — \`brew install ffmpeg\` (or \`bun add -g ffmpeg-static\`). Needed for
2253  both paths' assembly/conversion.
2254- **agent-browser** — for the CDP frame path ([agent-browser.md](./agent-browser.md)).
2255- Path 1 is headless/cloud-safe; Path 2 is macOS-only — see
2256  [evidence.md](./evidence.md#headless--cloud-portability).
2257`})),Foe=e((()=>{})),Ioe,Loe=e((()=>{Ioe=`# CLI / backend surface
2258
2259The default surface for backend, CLI, library, and data-logic changes. The proof
2260is the command's own output — text, not pixels. This is the cheapest and strongest
2261evidence: a passing assertion or a correct JSON result is harder to fake than a
2262screenshot, and it runs anywhere (no browser, no display).
2263
2264Use this surface when your change is verifiable by running something and reading
2265what it prints. Escalate to [web.md](./web.md) or [electron.md](./electron.md)
2266only when the criterion is actually about rendered UI.
2267
2268## How to verify
2269
22701. Run the command, test, or query that exercises the change. Prefer a machine
2271   output mode (\`--json\`, a structured dump) so the proof is assertable, not prose.
22722. Capture the output and upload it as \`text\` evidence — inline with \`--content\`
2273   for short output, or \`--file\` for a larger dump.
2274
2275\`\`\`bash
2276# CHECK_ITEM_ID is the criterion's plan item id (from \`lh verify plan state\`).
2277# short result → inline
2278lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type text \\
2279  --content "$(your-cli command --json)" \\
2280  --by cli --desc "command reports the new field after the change"
2281
2282# larger output (test log, full dump) → file
2283your-cli command --json > ./proof/result.json
2284lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type text \\
2285  --file ./proof/result.json --by cli --desc "full result set"
2286
2287# a test run is itself proof
2288your-test-runner path/to/spec > ./proof/test.log 2>&1
2289lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type text \\
2290  --file ./proof/test.log --by program --desc "regression spec passes"
2291\`\`\`
2292
2293Provenance: \`cli\` for command stdout, \`program\` for a script/test you ran. See
2294[../references/evidence.md](../references/evidence.md) for the evidence contract.
2295
2296## Auth
2297
2298The \`lh\` CLI you upload with is already authed. A _different_ product CLI under
2299test carries its own auth (API key or stored login) — configure it before
2300capturing its output. See [../references/auth.md](../references/auth.md#cli--backend-surface).
2301
2302## Boundaries
2303
2304- **Don't open a browser for a backend change.** If the criterion is satisfied by
2305  output, a screenshot adds noise, not proof.
2306- **Make the assertion legible.** Upload the specific lines/fields that prove the
2307  criterion (or describe them in \`--desc\`), not a 10k-line log the reviewer must
2308  scan.
2309- **Never upload secrets.** Strip tokens/keys from output before uploading — see
2310  [../references/auth.md](../references/auth.md#boundaries--read-before-touching-cookies).
2311`}
2311)),Roe,zoe=e((()=>{Roe=`# Desktop (Electron) surface
2312
2313Use this surface for **desktop-only behavior** — native windows, IPC / main-process
2314code, tray/menu, auto-update, OS integration, or a packaged-only path. That code
2315doesn't exist in a plain web page, so [web.md](./web.md) can't prove it. You drive
2316the running app's renderer over CDP with \`agent-browser\`
2317([../references/agent-browser.md](../references/agent-browser.md)).
2318
2319For a change that behaves identically in a browser, prefer [web.md](./web.md) —
2320it's lighter and cloud-portable. Use Electron only when the criterion calls out
2321the desktop shell.
2322
2323## Setup
2324
23251. Start the desktop app in dev/debug mode with a CDP port open (commonly 9222).
2326   How you start it is app-specific (its own dev command); the requirement is a
2327   reachable CDP endpoint.
23282. Connect agent-browser to that port:
2329
2330\`\`\`bash
2331agent-browser --cdp 9222 snapshot -i
2332agent-browser --cdp 9222 get url # sanity-check you attached to the app
2333agent-browser --cdp 9222 screenshot ./proof/desktop-state.png
2334\`\`\`
2335
23363. Auth: a desktop app usually keeps its own persistent login state in its
2337   user-data dir — log in once in the app and it survives restarts; no injection
2338   needed (see [../references/auth.md](../references/auth.md#desktop)).
2339
2340## Reading app state
2341
2342If the app exposes a global state handle, eval it to assert behavior (discover the
2343actual global name from the app — don't assume one):
2344
2345\`\`\`bash
2346agent-browser --cdp 9222 eval --stdin << 'EVALEOF'
2347(function () {
2348  // example shape — replace with the app's real global / selectors
2349  var s = window.__APP_STATE__ && window.__APP_STATE__();
2350  return JSON.stringify({ route: location.hash || location.pathname, ready: !!s });
2351})()
2352EVALEOF
2353\`\`\`
2354
2355## Capturing console errors during a run
2356
2357\`\`\`bash
2358# install an interceptor before exercising the feature
2359agent-browser --cdp 9222 eval --stdin << 'EVALEOF'
2360(function () {
2361  window.__ERRORS__ = [];
2362  var orig = console.error;
2363  console.error = function () {
2364    window.__ERRORS__.push(Array.from(arguments).map(String).join(' '));
2365    orig.apply(console, arguments);
2366  };
2367  return 'installed';
2368})()
2369EVALEOF
2370# ... drive the feature ...
2371agent-browser --cdp 9222 eval "JSON.stringify(window.__ERRORS__)" # → text evidence
2372\`\`\`
2373
2374## Gotchas
2375
2376- **Dev builds often auto-open DevTools, which hijacks the CDP target.** Symptom:
2377  \`get url\` returns a \`devtools://…\` URL instead of the app. Fix: close the
2378  DevTools target and reconnect:
2379
2380  \`\`\`bash
2381  DT_ID=$(curl -s http://localhost:9222/json/list | python3 -c "import json,sys; ts=json.load(sys.stdin); print(next(t['id'] for t in ts if t['type']=='page' and t['url'].startswith('devtools://')))")
2382  curl -s "http://localhost:9222/json/close/$DT_ID" > /dev/null
2383  agent-browser close --all && agent-browser --cdp 9222 get url
2384  \`\`\`
2385
2386- **Clean up all processes when done.** \`pkill -f "Electron"\` only kills the main
2387  process; helper processes (GPU, renderer, network) survive. Prefer the app's own
2388  stop command or kill by the project's electron binary path.
2389
2390- **Don't resize the window after load** — many apps trigger a full reload on
2391  resize, invalidating refs and state.
2392
2393## Time-based behavior & OS-level steps
2394
2395- **Behavior over time** needs a clip — record CDP frames into MP4/GIF:
2396  [../references/recording.md](../references/recording.md).
2397- **Native chrome around the app** (file pickers, system dialogs, menu-bar/dock,
2398  permission prompts) lives outside the renderer — drive it with Computer Use:
2399  [../references/computer-use.md](../references/computer-use.md).
2400
2401## Boundaries — headless / cloud
2402
2403Electron runs on Linux but has no true headless mode — it needs a display server.
2404In a headless/cloud environment, wrap the launch with \`xvfb-run\` (virtual
2405framebuffer). Everything CDP-based keeps working under Xvfb (connection, snapshots,
2406eval, \`agent-browser screenshot\` — captured from the renderer, not the OS screen).
2407What does NOT work: OS-window capture (\`screencapture\`), osascript, and native
2408screen recording — all macOS-only. Keep evidence CDP-based to stay cloud-portable
2409(see [../references/evidence.md](../references/evidence.md#headless--cloud-portability)).
2410`})),Boe,Voe=e((()=>{Boe=`# Native macOS app surface (Computer Use)
2411
2412Use this surface when the thing under test is a **native macOS app** that \`agent-browser\`
2413can't drive — anything not Chromium-based: a native desktop app, a chat client you
2414verify against (Slack/WeChat/…), Finder/system UI, or any OS-level behavior. You
2415drive it with macOS Computer Use (osascript + screencapture) — the toolkit is in
2416[../references/computer-use.md](../references/computer-use.md).
2417
2418Prefer the other surfaces when they can reach the target: [web.md](./web.md) /
2419[electron.md](./electron.md) for Chromium UIs, [cli.md](./cli.md) for backend.
2420Native is the **local-macOS escape hatch** — it is not cloud-portable (needs a real
2421display + Accessibility permission), so reach for it only when CDP can't.
2422
2423## How to verify
2424
24251. Activate the app and navigate to the state under test (keystrokes / shortcuts /
2426   clicks — see the toolkit).
24272. Drive the action that exercises your change.
24283. Capture proof: a \`screencapture\` PNG, a screen recording for time-based behavior
2429   ([../references/recording.md](../references/recording.md#path-2--os-screen-recording-macos-local-only)),
2430   or screen text via select-all-copy + \`pbpaste\`.
2431
2432\`\`\`bash
2433APP="YourApp"
2434osascript -e "tell application \\"$APP\\" to activate"
2435sleep 1
2436# ... navigate + act via osascript (see computer-use.md) ...
2437sleep 2 # let the result settle
2438screencapture -l "$(osascript -e "tell application \\"System Events\\" to tell process \\"$APP\\" to get id of window 1")" ./proof/native-result.png
2439\`\`\`
2440
2441Upload as evidence (provenance \`cli\`, since osascript/screencapture are
2442shell-driven):
2443
2444\`\`\`bash
2445lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type screenshot \\
2446  --file ./proof/native-result.png --by cli \\
2447  --desc "Native app shows the expected state after the change"
2448\`\`\`
2449
2450## Mid-flow use from another surface
2451
2452You don't have to commit the whole run to this surface. A web or Electron flow can drop
2453into Computer Use for a single OS-level step it can't script — a native file picker,
2454a system permission prompt, a Save dialog — then hand control back to agent-browser.
2455Capture the proof on whichever surface owns the criterion.
2456
2457## Boundaries
2458
2459- **macOS + display only.** No headless/cloud — see
2460  [../references/computer-use.md](../references/computer-use.md#gotchas).
2461- **Accessibility permission is mandatory** or every \`System Events\` call silently
2462  no-ops. Grant it to the host once.
2463- **Prefer CDP when reachable.** A Chromium target driven over CDP is more robust
2464  and portable than coordinate clicks; use native only when there's no CDP path.
2465`})),Hoe,Uoe=e((()=>{Hoe=`# Web surface
2466
2467Default surface for frontend and full-stack changes — the browser is the one place
2468network requests and rendered UI are observable together, so you can assert both
2469sides of a contract in one run. Driven by \`agent-browser\`
2470([../references/agent-browser.md](../references/agent-browser.md)).
2471
2472Use web when the behavior is the same in a normal browser against the app's dev
2473server or a deployed URL. If the criterion depends on the desktop shell, use
2474[electron.md](./electron.md) instead; if it's backend/CLI, use [cli.md](./cli.md).
2475
2476## Setup
2477
24781. Have the app reachable at a URL: a local dev server you started (e.g.
2479   \`http://localhost:<port>\`), or a deployed/preview URL the task targets.
24802. If the state under test is behind login, authenticate the agent-browser
2481   session first — see [../references/auth.md](../references/auth.md). Use a named
2482   \`--session\` so cookies persist across commands.
2483
2484\`\`\`bash
2485SESSION=app
2486agent-browser --session $SESSION open "http://localhost:3000/"
2487agent-browser --session $SESSION snapshot -i
2488# interact via refs, then capture
2489agent-browser --session $SESSION screenshot ./proof/state.png
2490\`\`\`
2491
2492Use the authenticated session as the evidence source. Do **not** use a separate
2493ordinary-Chrome screenshot as proof — it doesn't prove the automated session
2494reached the state. Ordinary Chrome is only a cookie source for auth fallback.
2495
2496## Full-stack — assert both layers {#web-full-stack}
2497
2498When the criterion spans a new/changed API and the UI consuming it, capture both
2499the network exchange and the rendered result:
2500
2501\`\`\`bash
2502SESSION=app
2503agent-browser --session $SESSION network har start
2504# ... drive the scenario that triggers the API ...
2505agent-browser --session $SESSION network requests --type xhr,fetch # inspect calls
2506agent-browser --session $SESSION network har stop ./proof/capture.har
2507agent-browser --session $SESSION screenshot ./proof/result.png
2508\`\`\`
2509
2510Upload the screenshot (\`--type screenshot\`) and the network proof (the HAR as
2511\`--type text --file ./proof/capture.har\`, or a focused request/response as
2512\`--type text --content …\`). Asserting only one layer leaves the contract half-proven.
2513
2514## Local frontend against a remote backend
2515
2516If you can only run the frontend locally but the backend is remote, drive the
2517frontend URL the same way — just remember the backend is not your branch, so it
2518proves frontend behavior, not backend changes.
2519
2520## Time-based behavior & OS-level steps
2521
2522- **Behavior over time** (streaming, loading→loaded, animation) needs a clip, not a
2523  screenshot — record it: [../references/recording.md](../references/recording.md).
2524- **A native step the page can't script** (file picker, OS permission prompt, Save
2525  dialog) — drop to Computer Use for that step, then return:
2526  [../references/computer-use.md](../references/computer-use.md).
2527
2528## Boundaries
2529
2530- **Headless / cloud:** web is cloud-native — headless Chromium and CDP screenshots
2531  work without a display. Prefer CDP capture over OS-level capture (see
2532  [../references/evidence.md](../references/evidence.md#headless--cloud-portability)).
2533- **HMR breaks refs.** After a hot reload during dev, re-snapshot before interacting.
2534`})),Woe=e((()=>{Mc(),woe(),Eoe(),Ooe(),Aoe(),Moe(),Poe(),Foe(),Loe(),zoe(),Voe(),Uoe(),jc({"references/agent-browser.md":Coe,"references/auth.md":Toe,"references/computer-use.md":Doe,"references/evidence.md":koe,"references/plan-format.md":joe,"references/recording.md":Noe,"surfaces/cli.md":Ioe,"surfaces/electron.md":Roe,"surfaces/native.md":Boe,"surfaces/web.md":Hoe})})),Pc,Fc=e((()=>{Yie(),eae(),Qae(),aoe(),Soe(),Woe(),Pc=[Jie,$ie,Zae,ioe]})),Goe,Koe,qoe,Joe,Ic=e((()=>{Goe=`agent-signal-review`,Koe=`agent-signal-reflection`,qoe=`agent-signal-feedback-intent`,Joe=`agent-signal-skill-management`})),Lc,Rc=e((()=>{Lc=e=>({api:e.apis,identifier:e.identifier,meta:{description:e.description,title:e.title},systemRole:e.systemRole,type:`builtin`})})),zc,Bc,Vc,Hc,Uc,Wc,Yoe,Gc,Xoe,Zoe,Kc,qc=e((()=>{zc={type:`string`},Bc={additionalProperties:!0,type:`object`},Vc={items:{additionalProperties:!0,type:`object`},type:`array`},Hc=(e,t=[])=>({properties:e,required:[...t],type:`object`}),Uc={items:{properties:{id:{description:`Stable evidence identifier.`,...zc},summary:{description:`Optional note explaining why this evidence matters.`,...zc},type:{description:`Evidence object type.`,enum:[`topic`,`message`,`operation`,`source`,`receipt`,`tool_call`,`task`,`agent_document`,`memory`],type:`string`}},required:[`id`,`type`],type:`object`},type:`array`},Wc=Hc({evidenceRefs:Uc,idempotencyKey:zc,rationale:zc,risk:{enum:[`low`,`medium`,`high`],type:`string`},target:Bc,title:zc},[`idempotencyKey`,`rationale`,`risk`,`evidenceRefs`]),Yoe=Hc({confidence:{type:`number`},downgradeReason:{enum:[`approval_required`,`low_confidence`,`unsupported_in_reflection`],type:`string`},evidenceRefs:Uc,idempotencyKey:zc,intentType:{enum:[`memory`,`skill`,`tooling`,`workflow`],type:`string`},operation:Bc,rationale:zc,risk:{enum:[`low`,`medium`,`high`],type:`string`},target:Bc,title:zc,urgency:{enum:[`immediate`,`soon`,`later`],type:`string`}},[`idempotencyKey`,`intentType`,`confidence`,`urgency`,`rationale`,`evidenceRefs`]),Gc=[{description:`List managed skills visible in the reviewed agent scope.`,name:`listManagedSkills`,parameters:Hc({})},{description:`Read one managed skill by skill document id in the reviewed agent scope.`,name:`getManagedSkill`,parameters:Hc({skillDocumentId:zc},[`skillDocumentId`])},{description:`Write one durable user memory when evidence explicitly states a stable normal-sensitivity user preference. Prefer this over skill tools for summary/style/preferences.`,name:`writeMemory`,parameters:Hc({content:zc,evidenceRefs:Vc,idempotencyKey:zc,proposalKey:zc,summary:zc},[`idempotencyKey`,`content`,`evidenceRefs`])},{description:`Create one managed skill when no existing skill is selected.`,name:`createSkillIfAbsent`,parameters:Hc({bodyMarkdown:zc,description:zc,idempotencyKey:zc,name:zc,proposalKey:zc,summary:zc,title:zc},[`idempotencyKey`,`name`,`bodyMarkdown`])},{description:`Replace one existing managed skill after compare-and-swap preflight. Provide baseSnapshot when available; the server completes it from skillDocumentId when omitted.`,name:`replaceSkillContentCAS`,parameters:Hc({baseSnapshot:Bc,bodyMarkdown:zc,description:zc,idempotencyKey:zc,proposalKey:zc,skillDocumentId:zc,summary:zc},[`idempotencyKey`,`skillDocumentId`,`bodyMarkdown`])}],Xoe=Gc.filter(e=>e.name!==`writeMemory`),Zoe=[{description:`List active and historical self-review proposals in the reviewed agent scope.`,name:`listSelfReviewProposals`,parameters:Hc({})},{description:`Read one self-review proposal by proposal id or proposalKey. Never use topic, message, tool_call, or document evidence ids here.`,name:`readSelfReviewProposal`,parameters:Hc({proposalId:zc,proposalKey:zc})},{description:`Create one user-visible self-review proposal for later approval.`,name:`createSelfReviewProposal`,parameters:Hc({actions:Vc,idempotencyKey:zc,metadata:Bc,proposalKey:zc,summary:zc},[`idempotencyKey`,`proposalKey`,`summary`,`actions`])},{description:`Refresh an existing self-review proposal after rechecking evidence.`,name:`refreshSelfReviewProposal`,parameters:Hc({idempotencyKey:zc,proposalId:zc,proposalKey:zc,summary:zc},[`idempotencyKey`,`proposalId`])},{description:`Supersede an existing self-review proposal with a replacement proposal key.`,name:`supersedeSelfReviewProposal`,parameters:Hc({idempotencyKey:zc,proposalId:zc,proposalKey:zc,summary:zc,supersededBy:zc},[`idempotencyKey`,`proposalId`,`supersededBy`])},{description:`Close an existing self-review proposal with an optional lifecycle reason.`,name:`closeSelfReviewProposal`,parameters:Hc({idempotencyKey:zc,proposalId:zc,proposalKey:zc,reason:zc,summary:zc},[`idempotencyKey`,`proposalId`])}
2534,{description:`Record one non-actionable self-review idea or question as a Daily Brief artifact without creating an approval proposal.`,name:`recordSelfReviewIdea`,parameters:Wc}],Kc=[{description:`Record one immediate reflection idea into receipt metadata without creating a Daily Brief proposal.`,name:`recordReflectionIdea`,parameters:Wc},{description:`Record one approval-gated, structural, unsupported, or low-confidence self-feedback intent into receipt metadata for later self-review.`,name:`recordSelfFeedbackIntent`,parameters:Yoe}]})),Qoe,$oe=e((()=>{Qoe=`You are processing a self-feedback intent an agent declared during a turn, deciding whether it can be safely actioned now or should be deferred to nightly self-review.
2535
2536Read evidence first (getEvidenceDigest, listManagedSkills, getManagedSkill, listSelfReviewProposals, readSelfReviewProposal). Action immediately only when the intent is high-confidence and low-risk:
2537- writeMemory: stable, normal-sensitivity user preferences.
2538- createSkillIfAbsent / replaceSkillContentCAS: small, safe, well-grounded skill changes.
2539
2540Otherwise downgrade rather than mutate:
2541- recordSelfFeedbackIntent: record the approval-gated / structural / unsupported / low-confidence intent for later self-review.
2542- recordReflectionIdea: capture a non-actionable idea or open question.
2543
2544Always pass a stable idempotencyKey on writes and cite the evidenceRefs you read. When in doubt, record the intent instead of mutating.`})),Jc,ese=e((()=>{Ic(),Rc(),qc(),$oe(),Jc=Lc({apis:[...Gc,...Kc],description:`Read evidence and action or downgrade a declared self-feedback intent.`,identifier:qoe,systemRole:Qoe,title:`Agent Signal Self-Feedback Intent`})})),tse,nse=e((()=>{tse=`You are running an immediate post-turn self-reflection for one agent over a recent topic/task/operation window.
2545
2546Read evidence first (getEvidenceDigest, listManagedSkills, getManagedSkill, listSelfReviewProposals, readSelfReviewProposal). Reflection direct-applies only high-confidence, low-risk writes:
2547- writeMemory: stable, normal-sensitivity user preferences with strong evidence.
2548- createSkillIfAbsent / replaceSkillContentCAS: only when the skill change is small, safe, and well-grounded.
2549
2550When a change is approval-gated, structural, unsupported in reflection, or low-confidence, do NOT mutate — instead:
2551- recordReflectionIdea: capture the reflection idea into receipt metadata.
2552- recordSelfFeedbackIntent: downgrade the intent for later nightly self-review.
2553
2554Always pass a stable idempotencyKey on writes and cite evidenceRefs you read. Default to recording an idea/intent over a direct mutation when uncertain.`})),Yc,rse=e((()=>{Ic(),Rc(),qc(),nse(),Yc=Lc({apis:[...Gc,...Kc],description:`Read evidence and apply or downgrade safe resource operations during reflection.`,identifier:Koe,systemRole:tse,title:`Agent Signal Self-Reflection`})})),ise,ase=e((()=>{ise=`You are running the nightly self-review for one agent over a bounded local-night evidence window.
2555
2556Read evidence first (getEvidenceDigest, listManagedSkills, getManagedSkill, listSelfReviewProposals, readSelfReviewProposal), then apply only safe, evidence-grounded resource operations:
2557- writeMemory: durable, stable, normal-sensitivity user preferences.
2558- createSkillIfAbsent / replaceSkillContentCAS: managed-skill capabilities (use compare-and-swap to replace).
2559- createSelfReviewProposal / refreshSelfReviewProposal / supersedeSelfReviewProposal / closeSelfReviewProposal: user-visible proposals for changes that need approval.
2560- recordSelfReviewIdea: non-actionable ideas or open questions to surface in the Daily Brief without a proposal.
2561
2562Always pass a stable idempotencyKey on writes. Cite evidenceRefs you actually read. Be concise and conservative — prefer recording an idea or proposal over a direct mutation when confidence or sensitivity is borderline.`})),Xc,ose=e((()=>{Ic(),Rc(),qc(),ase(),Xc=Lc({apis:[...Gc,...Zoe],description:`Read evidence and apply safe resource operations for the nightly self-review.`,identifier:Goe,systemRole:ise,title:`Agent Signal Nightly Review`})})),Zc,sse,cse,lse=e((()=>{Zc=[`listManagedSkills`,`getManagedSkill`,`writeMemory`,`createSkillIfAbsent`,`replaceSkillContentCAS`],sse=[`listSelfReviewProposals`,`readSelfReviewProposal`,`createSelfReviewProposal`,`refreshSelfReviewProposal`,`supersedeSelfReviewProposal`,`closeSelfReviewProposal`,`recordSelfReviewIdea`],cse=[`recordReflectionIdea`,`recordSelfFeedbackIntent`],[...Zc,...sse],[...Zc,...cse]})),use=e((()=>{lse()})),dse,fse=e((()=>{dse=`You are the same-turn skill-management agent for one user agent. The user just gave feedback that has already been routed to the skill domain — it describes a reusable procedure / workflow / repeatable task the agent should perform consistently from now on.
2563
2564Your job: turn that feedback into exactly one durable managed-skill write, or do nothing.
2565
2566Read first (listManagedSkills, getManagedSkill) to see whether an existing skill already covers this procedure. Then:
2567- createSkillIfAbsent: when no existing skill covers it — author a concise, reusable skill (clear name, description, and step-by-step bodyMarkdown).
2568- replaceSkillContentCAS: when an existing skill should be refined/extended to incorporate the feedback. Provide baseSnapshot when available; the server completes it from skillDocumentId when omitted.
2569
2570The skill \`name\` MUST be a slug: lowercase ASCII letters, digits, and hyphens only (e.g. \`weekly-report-flow\`) — never spaces, uppercase, or non-ASCII characters. Put any human-readable / non-English label in \`title\` and \`description\`, not in \`name\`.
2571
2572Apply at most one skill mutation. If the feedback is vague, non-
2572procedural, or already fully covered by an existing skill, make no write. Always pass a stable idempotencyKey on writes. Be concise and evidence-driven.`})),Qc,pse=e((()=>{Ic(),Rc(),qc(),fse(),Qc=Lc({apis:[...Xoe],description:`Read managed skills and apply one safe skill create/refine from skill feedback.`,identifier:Joe,systemRole:dse,title:`Agent Signal Skill Management`})})),mse=e((()=>{ese(),$oe(),rse(),nse(),ose(),ase(),lse(),use(),Ic(),Rc(),qc(),pse(),fse()})),hse,gse=e((()=>{hse=`You have access to Brief communication tools. Use them to interact with the user:
2573
2574- **createBrief**: Report progress, deliver results, or request decisions from the user. Use type 'decision' when you need user input, 'result' for deliverables, 'insight' for observations. You can define custom action buttons for the user to respond with
2575- **requestCheckpoint**: Pause execution and ask the user to review your work before continuing. Use at natural review points
2576
2577When communicating:
25781. Use createBrief to deliver results and request feedback at key milestones
25792. Use requestCheckpoint when you need explicit approval before proceeding
25803. For decision briefs, provide clear action options (e.g. approve, reject, modify)`})),$c,_se=e((()=>{$c={createBrief:`createBrief`,requestCheckpoint:`requestCheckpoint`}})),vse,el,yse=e((()=>{gse(),_se(),vse=`lobe-brief`,el={api:[{description:`Create a brief to report progress, deliver results, or request decisions from the user. Use type 'decision' when you need user input, 'result' for deliverables, 'insight' for observations. Default actions are auto-generated based on type, but you can customize them.`,name:$c.createBrief,parameters:{properties:{actions:{description:`Custom action buttons for the user. Ignored when type is "result" (result briefs render a fixed approve button). For other types, if omitted, defaults are generated based on type. Each action has key (identifier), label (display text), and type ("resolve" to close, "comment" to prompt feedback).`,items:{properties:{key:{description:`Action identifier, e.g. "approve", "split"`,type:`string`},label:{description:`Display label, e.g. "✅ Agree to split"`,type:`string`},type:{description:`"resolve" closes the brief, "comment" prompts for text input`,enum:[`resolve`,`comment`],type:`string`}},required:[`key`,`label`,`type`],type:`object`},type:`array`},priority:{description:`Priority of the brief. Default is 'normal'.`,enum:[`urgent`,`normal`,`info`],type:`string`},summary:{description:`Detailed summary content of the brief.`,type:`string`},title:{description:`A short title for the brief.`,type:`string`},type:{description:`The type of brief: 'decision' for user input needed, 'result' for deliverables, 'insight' for observations.`,enum:[`decision`,`result`,`insight`],type:`string`}},required:[`type`,`title`,`summary`],type:`object`}},{description:`Pause execution and request the user to review your work before continuing. Use at natural review points.`,humanIntervention:`required`,name:$c.requestCheckpoint,parameters:{properties:{reason:{description:`The reason for requesting a checkpoint.`,type:`string`}},required:[`reason`],type:`object`}}],identifier:vse,meta:{avatar:`📋`,description:`Report progress, deliver results, and request user decisions`,title:`Brief Tools`},systemRole:hse,type:`builtin`}})),bse=e((()=>{yse(),_se()})),xse,Sse=e((()=>{xse="You can drive the in-app browser shown in the user's sidebar. The user watches every action live and can take over at any time, so keep actions purposeful.\n\nCore workflow:\n1. `navigate` to a URL (opens the browser panel if needed).\n2. `snapshot` to perceive the page — it returns interactive elements with stable refs like `[ref=e12]`.\n3. Act with `click` / `fill` / `press` / `scroll` using those refs.\n4. Re-`snapshot` after anything that changes the page (navigation, dialogs, dynamic content). Refs are invalidated by navigation.\n5. `readPage` extracts the page text when you need to quote or summarize content.\n\nNotes:\n- `fill` sets an input's value directly; pass `submit: true` to press Enter afterwards (search boxes, login forms).\n- `screenshot` renders a visual for the USER's chat — you cannot see it. Use `snapshot` / `readPage` for your own perception.\n- Prefer refs over coordinates. Coordinates are a fallback for canvas-like surfaces only.\n- The browser shares the user's logged-in profile. Never visit pages or perform actions the user did not ask for, and never extract credentials or other sensitive data."})),tl,nl,rl=e((()=>{tl=`lobe-browser`,nl={click:`click`,fill:`fill`,navigate:`navigate`,press:`press`,readPage:`readPage`,screenshot:`screenshot`,scroll:`scroll`,snapshot:`snapshot`}})),il,Cse=e((()=>{Sse(),rl(),il={api:[{description:`Open a URL in the in-app browser sidebar. Opens the panel automatically if it is closed.`,name:nl.navigate,parameters:{properties:{url:{description:`Absolute URL to open (http/https).`,type:`string`}},required:[`url`],type:`object`}},{description:`Capture an accessibility snapshot of the current page: interactive elements (links, buttons, inputs, headings) with stable refs like [ref=e12] for use in click/fill. Always snapshot before acting, and re-snapsh
2580ot after the page changes.`,name:nl.snapshot,parameters:{properties:{},type:`object`}},{description:`Click an element. Prefer a ref from the latest snapshot; viewport x/y coordinates are a fallback for canvas-like surfaces.`,name:nl.click,parameters:{properties:{ref:{description:`Element ref from the latest snapshot, e.g. "e12".`,type:`string`},x:{description:`Viewport x coordinate (only when no ref is available).`,type:`number`},y:{description:`Viewport y coordinate (only when no ref is available).`,type:`number`}},type:`object`}},{description:`Fill a text input, textarea, or contenteditable identified by a snapshot ref. Set submit=true to press Enter afterwards.`,name:nl.fill,parameters:{properties:{ref:{description:`Element ref from the latest snapshot.`,type:`string`},submit:{description:`Press Enter after filling (submit search/login forms).`,type:`boolean`},text:{description:`Text to fill.`,type:`string`}},required:[`ref`,`text`],type:`object`}},{description:`Send a keyboard key to the page, e.g. Enter, Tab, Escape, ArrowDown.`,name:nl.press,parameters:{properties:{key:{description:`KeyboardEvent.key value (Enter, Tab, Escape, ArrowDown, ...).`,type:`string`}},required:[`key`],type:`object`}},{description:`Scroll the page vertically (positive dy scrolls down) or horizontally.`,name:nl.scroll,parameters:{properties:{dx:{description:`Horizontal pixels to scroll.`,type:`number`},dy:{description:`Vertical pixels to scroll. Positive scrolls down.`,type:`number`}},required:[`dy`],type:`object`}},{description:`Capture a screenshot of the current page for the USER to see in chat. You cannot see the image yourself — use snapshot/readPage for perception.`,name:nl.screenshot,parameters:{properties:{},type:`object`}},{description:`Extract the readable text content of the current page (for quoting or summarizing).`,name:nl.readPage,parameters:{properties:{},type:`object`}}],executors:[`client`,`server`],identifier:tl,meta:{avatar:`🌐`,description:`Drive the in-app browser sidebar: navigate, inspect pages via accessibility snapshots, click, fill forms, and capture screenshots — visible to the user in real time.`,title:`Browser`},systemRole:xse,type:`builtin`}})),al=e((()=>{Cse(),Sse(),rl()})),wse,Tse=e((()=>{wse=class{constructor(e){this.base=e,this.N=e.length,this.index=[...e].reduce((e,t,n)=>(e[t]=n,e),{})}base;N;index;decode(e){let{index:t,N:n}=this,r=0;for(let i=e.length-1,a=0;a<=i;a++)r+=t[e[a]]*n**(i-a);return r}decodeBigInt(e){let{index:t,N:n}=this,r=BigInt(n),i=0n;for(let n=e.length-1,a=0;a<=n;a++)i+=BigInt(t[e[a]])*r**BigInt(n-a);return i}decodeBytes(e,t){let n=this.decodeBigInt(e);for(let e=t.length;e-- >0;)t[e]=Number(n&255n),n>>=8n;return t}validate(e){return RegExp(`^[${this.base}]+$`).test(e)}}})),ol,Ese=e((()=>{ol=`0123456789abcdef`})),Dse,Ose,kse,Ase=e((()=>{Ese(),Dse=BigInt(2**53-1),Ose=class{constructor(e){this.base=e,this.N=e.length}base;N;__pc=[];clear(){this.__pc.length=0}encode(e,t=0){let{base:n,N:r}=this;if(e===0)return this.__pad(n[0],t);let i=``;for(;e>0;)i=n[e%r]+i,e=Math.floor(e/r);return this.__pad(i,t)}encodeBigInt(e,t=0){if(e<=Dse)return this.encode(Number(e),t);let{base:n,N:r}=this;if(e===0n)return this.__pad(n[0],t);let i=BigInt(r),a=``;for(;e>0n;)a=n[Number(e%i)]+a,e/=i;return this.__pad(a,t)}encodeBytes(e,t=0){let n=`0x`;for(let t=0,r=e.length;t<r;t++)n+=kse(e[t]);return this.encodeBigInt(BigInt(n),t)}size(e){return Math.ceil(Math.log(e)/Math.log(this.N))}__pad(e,t){let n=t-e.length;return n>0?(this.__pc[n]||(this.__pc[n]=this.base[0].repeat(n)))+e:e}},kse=e=>ol[e>>>4&15]+ol[e&15]})),sl,jse,Mse=e((()=>{Tse(),Ase(),sl=e=>new jse(e),jse=class{constructor(e){this.base=e,this.N=e.length,this.enc=new Ose(e),this.dec=new wse(e)}base;N;enc;dec;clear(){this.enc.clear()}encode(e,t){return this.enc.encode(e,t)}encodeBigInt(e,t){return this.enc.encodeBigInt(e,t)}encodeBytes(e,t){return this.enc.encodeBytes(e,t)}decode(e){return this.dec.decode(e)}decodeBigInt(e){return this.dec.decodeBigInt(e)}decodeBytes(e,t){return this.dec.decodeBytes(e,t)}validate(e){return this.dec.validate(e)}size(e){return this.enc.size(e)}}})),cl,ll=e((()=>{cl={relTol:1e-12,absTol:1e-15,matrix:`Matrix`,number:`number`,numberFallback:`number`,precision:64,predictable:!1,randomSeed:null,legacySubset:!1}}
2580));function ul(e,t){if(fl(e,t)||Nse(e,t))return e[t];throw pl(e,t)?Error(`Cannot access method "${t}" as a property`):e==null?TypeError(`Cannot access property "${t}": object is ${e}`):Error(`No access to property "`+t+`"`)}function dl(e,t,n){if(fl(e,t)||Nse(e,t))return e[t]=n,n;throw Error(`No access to property "${t}"`)}function fl(e,t){return Ise(e)?!(t in Object.prototype):!1}function Nse(e,t){return Array.isArray(e)?typeof t==`number`||typeof t==`string`&&Pse(t)||t===`length`:!1}function Pse(e){return/^\d+$/.test(e)}function Fse(e,t){if(!pl(e,t))throw Error(`No access to method "`+t+`"`);return e[t]}function pl(e,t){return e==null||typeof e[t]!=`function`||nu(e,t)&&Object.getPrototypeOf&&t in Object.getPrototypeOf(e)?!1:Lse.has(t)?!0:!(t in Object.prototype||t in Function.prototype)}function Ise(e){return typeof e==`object`&&e&&e.constructor===Object}var Lse,ml=e((()=>{ru(),Lse=new Set([`toString`,`valueOf`,`toLocaleString`])}));function Rse(e,t){return{next:()=>{var n=e.next();return n.done?n:{value:t(n.value),done:!1}}}}function hl(){return new Map}function gl(e){if(!e)return hl();if(Il(e))return e;if(Fl(e))return new _l(e);throw Error(`createMap can create maps from objects or Maps`)}function zse(e){if(e instanceof _l)return e.wrappedObject;var t={};for(var n of e.keys())dl(t,n,e.get(n));return t}var _l,vl,yl=e((()=>{ml(),Ql(),_l=class{constructor(e){this.wrappedObject=e,this[Symbol.iterator]=this.entries}keys(){return Object.keys(this.wrappedObject).filter(e=>this.has(e)).values()}get(e){return ul(this.wrappedObject,e)}set(e,t){return dl(this.wrappedObject,e,t),this}has(e){return fl(this.wrappedObject,e)&&e in this.wrappedObject}entries(){return Rse(this.keys(),e=>[e,this.get(e)])}forEach(e){for(var t of this.keys())e(this.get(t),t,this)}delete(e){fl(this.wrappedObject,e)&&delete this.wrappedObject[e]}clear(){for(var e of this.keys())this.delete(e)}get size(){return Object.keys(this.wrappedObject).length}},vl=class{constructor(e,t,n){this.a=e,this.b=t,this.bKeys=n,this[Symbol.iterator]=this.entries}get(e){return this.bKeys.has(e)?this.b.get(e):this.a.get(e)}set(e,t){return this.bKeys.has(e)?this.b.set(e,t):this.a.set(e,t),this}has(e){return this.b.has(e)||this.a.has(e)}keys(){return new Set([...this.a.keys(),...this.b.keys()])[Symbol.iterator]()}entries(){return Rse(this.keys(),e=>[e,this.get(e)])}forEach(e){for(var t of this.keys())e(this.get(t),t,this)}delete(e){return this.bKeys.has(e)?this.b.delete(e):this.a.delete(e)}clear(){this.a.clear(),this.b.clear()}get size(){return[...this.keys()].length}}}));function bl(e){return typeof e==`number`}function xl(e){return!e||typeof e!=`object`||typeof e.constructor!=`function`?!1:e.isBigNumber===!0&&typeof e.constructor.prototype==`object`&&e.constructor.prototype.isBigNumber===!0||typeof e.constructor.isDecimal==`function`&&e.constructor.isDecimal(e)===!0}function Sl(e){return typeof e==`bigint`}function Cl(e){return e&&typeof e==`object`&&Object.getPrototypeOf(e).isComplex===!0||!1}function wl(e){return e&&typeof e==`object`&&Object.getPrototypeOf(e).isFraction===!0||!1}function Tl(e){return e&&e.constructor.prototype.isUnit===!0||!1}function El(e){return typeof e==`string`}function Dl(e){return e&&e.constructor.prototype.isMatrix===!0||!1}function Ol(e){return Array.isArray(e)||Dl(e)}function kl(e){return e&&e.isDenseMatrix&&e.constructor.prototype.isMatrix===!0||!1}function Al(e){return e&&e.isSparseMatrix&&e.constructor.prototype.isMatrix===!0||!1}function jl(e){return e&&e.constructor.prototype.isRange===!0||!1}function Ml(e){return e&&e.constructor.prototype.isIndex===!0||!1}function Bse(e){return typeof e==`boolean`}function Vse(e){return e&&e.constructor.prototype.isResultSet===!0||!1}function Nl(e){return e&&e.constructor.prototype.isHelp===!0||!1}function Pl(e){return typeof e==`function`}function Hse(e){return e instanceof Date}function Use(e){return e instanceof RegExp}function Fl(e){return!!(e&&typeof e==`object`&&e.constructor===Object&&!Cl(e)&&!wl(e))}function Il(e){return e?e instanceof Map||e instanceof _l||typeof e.set==`function`&&typeof e.get==`function`&&typeof e.keys==`function`&&typeof e.has==`function`:!1}function Wse(e){return Il(e)&&Il(e.a)&&Il(e.b)}function Gse(e){return Il(e)&&Fl(e.wrappedObject)}function Kse(e){return e===null}function qse(e){return e===void 0}function Ll(e){return e&&e.isAccessorNode===!0&&e.constructor.prototype.isNode===!0||!1}function Rl(e){return e&&e.isArrayNode===!0&&e.constructor.prototype.isNode===!0||!1}function Jse(e){return e&&e.isAssignmentNode===!0&&e.constructor.prototype.isNode===!0||!1}function Yse(e){return e&&e.isBlockNode===!0&&e.constructor.prototype.isNode===!0||!1}function Xse(e){return e&&e.isConditionalNode===!0&&e.constructor.prototype.isNode===!0||!1}function zl(e){return e&&e.isConstantNode===!0&&e.constructor.prototype.isNode===!0||!1}function Bl(e){return zl(e)||Kl(e)&&e.args.length===1&&zl(e.args[0])&&`-+~`.includes(e.op)}function Vl(e){return e&&e.isFunctionAssignmentNode===!0&&e.constructor.prototype.isNode===!0||!1}function Hl(e){return e&&e.isFunctionNode===!0&&e.constructor.prototype.isNode===!0||!1}function Ul(e){return e&&e.isIndexNode===!0&&e.constructor.prototype.isNode===!0||!1}function Wl(e){return e&&e.isNode===!0&&e.constructor.prototype.isNode===!0||!1}function Gl(e){return e&&e.isObjectNode===!0&&e.constructor.prototype.isNode===!0||!1}function Kl(e){return e&&e.isOperatorNode===!0&&e.constructor.prototype.isNode===!0||!1}function ql(e){return e&&e.isParenthesisNode===!0&&e.constructor.prototype.isNode===!0||!1}function Zse(e){return e&&e.isRangeNode===!0&&e.constructor.prototype.isNode===!0||!1}function Qse(e){return e&&e.isRelationalNode===!0&&e.constructor.prototype.isNode===!0||!1}function Jl(e){return e&&e.isSymbolNode===!0&&e.constructor.prototype.isNode===!0||!1}function Yl(e){return e&&e.constructor.prototype.isChain===!0||!1}function Xl(e){var t=typeof e;return t===`object`?e===null?`null`:xl(e)?`BigNumber`:e.constructor&&e.constructor.name?e.constructor.name:`Object`:t}var Zl,Ql=e((()=>{yl(),Zl=Array.isArray}));function $l(e){var t=typeof e;if(t===`number`||t===`bigint`||t===`string`||t===`boolean`||e==null)return e;if(typeof e.clone==`function`)return e.clone();
2580if(Array.isArray(e))return e.map(function(e){return $l(e)});if(e instanceof Date)return new Date(e.valueOf());if(xl(e))return e;if(Fl(e))return $se(e,$l);if(t===`function`)return e;throw TypeError(`Cannot clone: unknown type of value (value: ${e})`)}function $se(e,t){var n={};for(var r in e)nu(e,r)&&(n[r]=t(e[r]));return n}function ece(e,t){for(var n in t)nu(t,n)&&(e[n]=t[n]);return e}function tce(e,t){if(Array.isArray(t))throw TypeError(`Arrays are not supported by deepExtend`);for(var n in t)if(nu(t,n)&&!(n in Object.prototype)&&!(n in Function.prototype))if(t[n]&&t[n].constructor===Object)e[n]===void 0&&(e[n]={}),e[n]&&e[n].constructor===Object?tce(e[n],t[n]):e[n]=t[n];else if(Array.isArray(t[n]))throw TypeError(`Arrays are not supported by deepExtend`);else e[n]=t[n];return e}function eu(e,t){var n,r,i;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(r=0,i=e.length;r<i;r++)if(!eu(e[r],t[r]))return!1;return!0}else if(typeof e==`function`)return e===t;else if(e instanceof Object){if(Array.isArray(t)||!(t instanceof Object))return!1;for(n in e)if(!(n in t)||!eu(e[n],t[n]))return!1;for(n in t)if(!(n in e))return!1;return!0}else return e===t}function nce(e){var t={};return rce(e,t),t}function rce(e,t){for(var n in e)if(nu(e,n)){var r=e[n];typeof r==`object`&&r?rce(r,t):t[n]=r}}function tu(e,t,n){var r=!0,i;Object.defineProperty(e,t,{get:function(){return r&&=(i=n(),!1),i},set:function(e){i=e,r=!1},configurable:!0,enumerable:!0})}function nu(e,t){return e&&Object.hasOwnProperty.call(e,t)}function ice(e){return e&&typeof e.factory==`function`}function ace(e,t){for(var n={},r=0;r<t.length;r++){var i=t[r],a=e[i];a!==void 0&&(n[i]=a)}return n}var ru=e((()=>{Ql()}));function oce(e,t){function n(r){if(r){if(r.epsilon!==void 0){console.warn(`Warning: The configuration option "epsilon" is deprecated. Use "relTol" and "absTol" instead.`);var i=$l(r);return i.relTol=r.epsilon,i.absTol=r.epsilon*.001,delete i.epsilon,n(i)}r.legacySubset===!0&&console.warn(`Warning: The configuration option "legacySubset" is for compatibility only and might be deprecated 
2580in the future.`);var a=$l(e);sce(r,`matrix`,iu),sce(r,`number`,au),tce(e,r);var o=$l(e);return t(`config`,o,a,$l(r)),o}else return $l(e)}return n.MATRIX_OPTIONS=iu,n.NUMBER_OPTIONS=au,Object.keys(cl).forEach(t=>{Object.defineProperty(n,t,{get:()=>e[t],enumerable:!0,configurable:!0})}),n}function sce(e,t,n){e[t]!==void 0&&!n.includes(e[t])&&console.warn(`Warning: Unknown value "`+e[t]+`" for configuration option "`+t+`". Available options: `+n.map(e=>JSON.stringify(e)).join(`, `)+`.`)}var iu,au,cce=e((()=>{ru(),ll(),iu=[`Matrix`,`Array`],au=[`number`,`BigNumber`,`bigint`,`Fraction`]})),J,ou=e((()=>{Bn(),ll(),cce(),J=function(e){if(e)throw Error(`The global config is readonly. 
2581Please create a mathjs instance if you want to change the default configuration. 
2582Example:
2583
2584  import { create, all } from 'mathjs';
2585  const mathjs = create(all);
2586  mathjs.config({ number: 'BigNumber' });
2587`);return Object.freeze(cl)},zn(J,cl,{MATRIX_OPTIONS:iu,NUMBER_OPTIONS:au})})),su=r(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n=typeof globalThis<`u`?globalThis:n||self,n.typed=r())})(e,(function(){function e(){return!0}function t(){return!1}function n(){}let r=`Argument is not a typed-function.`;function i(){function a(e){return typeof e==`object`&&!!e&&e.constructor===Object}let o=[{name:`number`,test:function(e){return typeof e==`number`}},{name:`string`,test:function(e){return typeof e==`string`}},{name:`boolean`,test:function(e){return typeof e==`boolean`}},{name:`Function`,test:function(e){return typeof e==`function`}},{name:`Array`,test:Array.isArray},{name:`Date`,test:function(e){return e instanceof Date}},{name:`RegExp`,test:function(e){return e instanceof RegExp}},{name:`Object`,test:a},{name:`null`,test:function(e){return e===null}},{name:`undefined`,test:function(e){return e===void 0}}],s={name:`any`,test:e,isAny:!0},c,l,u=0,d={createCount:0};function f(e){let t=c.get(e);if(t)return t;let n=`Unknown type "`+e+`"`,r=e.toLowerCase(),i;for(i of l)if(i.toLowerCase()===r){n+=`. Did you mean "`+i+`" ?`;break}throw TypeError(n)}function p(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`any`,n=t?f(t).index:l.length,r=[];for(let t=0;t<e.length;++t){if(!e[t]||typeof e[t].name!=`string`||typeof e[t].test!=`function`)throw TypeError(`Object with properties {name: string, test: function} expected`);let i=e[t].name;if(c.has(i))throw TypeError(`Duplicate type name "`+i+`"`);r.push(i),c.set(i,{name:i,test:e[t].test,isAny:e[t].isAny,index:n+t,conversionsTo:[]})}let i=l.slice(n);l=l.slice(0,n).concat(r).concat(i);for(let e=n+r.length;e<l.length;++e)c.get(l[e]).index=e}function m(){c=new Map,l=[],u=0,p([s],!1)}m(),p(o);function h(){let e;for(e of l)c.get(e).conversionsTo=[];u=0}function g(e){let t=l.filter(t=>{let n=c.get(t);return!n.isAny&&n.test(e)});return t.length?t:[`any`]}function _(e){return e&&typeof e==`function`&&`_typedFunctionData`in e}function v(e,t,n){if(!_(e))throw TypeError(r);let i=n&&n.exact,a=T(Array.isArray(t)?t.join(`,`):t),o=x(a);if(!i||o in e.signatures){let t=e._typedFunctionData.signatureMap.get(o);if(t)return t}let s=a.length,c;if(i){c=[];let t;for(t in e.signatures)c.push(e._typedFunctionData.signatureMap.get(t))}else c=e._typedFunctionData.signatures;for(let e=0;e<s;++e){let t=a[e],n=[],r;for(r of c){let i=k(r.params,e);if(!(!i||t.restParam&&!i.restParam)){if(!i.hasAny){let e=w(i);if(t.types.some(t=>!e.has(t.name)))continue}n.push(r)}}if(c=n,c.length===0)break}let l;for(l of c)if(l.params.length<=s)return l;throw TypeError(`Signature not found (signature: `+(e.name||`unnamed`)+`(`+x(a,`, `)+`))`)}function y(e,t,n){return v(e,t,n).implementation}function b(e,t){let n=f(t);if(n.test(e))return e;let r=n.conversionsTo;if(r.length===0)throw Error(`There are no conversions to `+t+` defined.`);for(let t=0;t<r.length;t++)if(f(r[t].from).test(e))return r[t].convert(e);throw Error(`Cannot convert `+e+` to `+t)}function x(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`,`;return e.map(e=>e.name).join(t)}function S(e){let t=e.indexOf(`...`)===0,n=(t?e.length>3?e.slice(3):`any`:e).split(`|`).map(e=>f(e.trim())),r=!1,i=t?`...`:``;return{types:n.map(function(e){return r=e.isAny||r,i+=e.name+`|`,{name:e.name,typeIndex:e.index,test:e.test,isAny:e.isAny,conversion:null,conversionIndex:-1}}),name:i.slice(0,-1),hasAny:r,hasConversion:!1,restParam:t}}function C(e){let t=ee(e.types.map(e=>e.name)),n=e.hasAny,r=e.name,i=t.map(function(e){let t=f(e.from);return n=t.isAny||n,r+=`|`+e.from,{name:e.from,typeIndex:t.index,test:t.test,isAny:t.isAny,conversion:e,conversionIndex:e.index}});return{types:e.types.concat(i),name:r,hasAny:n,hasConversion:i.length>0,restParam:e.restParam}}function w(e){return e.typeSet||(e.typeSet=new Set,e.types.forEac
2587h(t=>e.typeSet.add(t.name))),e.typeSet}function T(e){let t=[];if(typeof e!=`string`)throw TypeError(`Signatures must be strings`);let n=e.trim();if(n===``)return t;let r=n.split(`,`);for(let e=0;e<r.length;++e){let n=S(r[e].trim());if(n.restParam&&e!==r.length-1)throw SyntaxError(`Unexpected rest parameter "`+r[e]+`": only allowed for the last parameter`);if(n.types.length===0)return null;t.push(n)}return t}function E(e){let t=se(e);return t?t.restParam:!1}function D(t){if(!t||t.types.length===0)return e;if(t.types.length===1)return f(t.types[0].name).test;if(t.types.length===2){let e=f(t.types[0].name).test,n=f(t.types[1].name).test;return function(t){return e(t)||n(t)}}else{let e=t.types.map(function(e){return f(e.name).test});return function(t){for(let n=0;n<e.length;n++)if(e[n](t))return!0;return!1}}}function O(e){let t,n,r;if(E(e)){t=oe(e).map(D);let n=t.length,r=D(se(e)),i=function(e){for(let t=n;t<e.length;t++)if(!r(e[t]))return!1;return!0};return function(e){for(let n=0;n<t.length;n++)if(!t[n](e[n]))return!1;return i(e)&&e.length>=n+1}}else if(e.length===0)return function(e){return e.length===0};else if(e.length===1)return n=D(e[0]),function(e){return n(e[0])&&e.length===1};else if(e.length===2)return n=D(e[0]),r=D(e[1]),function(e){return n(e[0])&&r(e[1])&&e.length===2};else return t=e.map(D),function(e){for(let n=0;n<t.length;n++)if(!t[n](e[n]))return!1;return e.length===t.length}}function k(e,t){return t<e.length?e[t]:E(e)?se(e):null}function A(e,t){let n=k(e,t);return n?w(n):new Set}function j(e){return e.conversion===null||e.conversion===void 0}function M(e,t){let n=new Set;return e.forEach(e=>{let r=A(e.params,t),i;for(i of r)n.add(i)}),n.has(`any`)?[`any`]:Array.from(n)}function N(e,t,n){let r,i,a=e||`unnamed`,o=n,s;for(s=0;s<t.length;s++){let e=[];
2587if(o.forEach(n=>{let r=D(k(n.params,s));(s<n.params.length||E(n.params))&&r(t[s])&&e.push(n)}),e.length===0){if(i=M(o,s),i.length>0){let e=g(t[s]);return r=TypeError(`Unexpected type of argument in function `+a+` (expected: `+i.join(` or `)+`, actual: `+e.join(` | `)+`, index: `+s+`)`),r.data={category:`wrongType`,fn:a,index:s,actual:e,expected:i},r}}else o=e}let c=o.map(function(e){return E(e.params)?1/0:e.params.length});if(t.length<Math.min.apply(null,c))return i=M(o,s),r=TypeError(`Too few arguments in function `+a+` (expected: `+i.join(` or `)+`, index: `+t.length+`)`),r.data={category:`tooFewArgs`,fn:a,index:t.length,expected:i},r;let l=Math.max.apply(null,c);if(t.length>l)return r=TypeError(`Too many arguments in function `+a+` (expected: `+l+`, actual: `+t.length+`)`),r.data={category:`tooManyArgs`,fn:a,index:t.length,expectedLength:l},r;let u=[];for(let e=0;e<t.length;++e)u.push(g(t[e]).join(`|`));return r=TypeError(`Arguments of type "`+u.join(`, `)+`" do not match any of the defined signatures of function `+a+`.`),r.data={category:`mismatch`,actual:u},r}function P(e){let t=l.length+1;for(let n=0;n<e.types.length;n++)t=Math.min(t,e.types[n].typeIndex);return t}function F(e){let t=u+1;for(let n=0;n<e.types.length;n++)j(e.types[n])||(t=Math.min(t,e.types[n].conversionIndex));return t}function I(e,t){if(e.hasAny){if(!t.hasAny)return .1}else if(t.hasAny)return-.1;if(e.restParam){if(!t.restParam)return .01}else if(t.restParam)return-.01;let n=P(e)-P(t);if(n<0)return-.001;if(n>0)return .001;let r=F(e),i=F(t);if(e.hasConversion){if(!t.hasConversion)return(1+r)*1e-6}else if(t.hasConversion)return-(1+i)*1e-6;let a=r-i;return a<0?-1e-7:a>0?1e-7:0}function L(e,t){let n=e.params,r=t.params,i=se(n),a=se(r),o=E(n),s=E(r);if(o&&i.hasAny){if(!s||!a.hasAny)return 1e7}else if(s&&a.hasAny)return-1e7;let c=0,l=0,u;for(u of n)u.hasAny&&++c,u.hasConversion&&++l;let d=0,f=0;for(u of r)u.hasAny&&++d,u.hasConversion&&++f;if(c!==d)return(c-d)*1e6;if(o&&i.hasConversion){if(!s||!a.hasConversion)return 1e5}else if(s&&a.hasConversion)return-1e5;if(l!==f)return(l-f)*1e4;if(o){if(!s)return 1e3}else if(s)return-1e3;let p=(n.length-r.length)*(o?-100:100);if(p!==0)return p;let m=[],h=0;for(let e=0;e<n.length;++e){let t=I(n[e],r[e]);m.push(t),h+=t}if(h!==0)return(h<0?-10:10)+h;let g,_=9,v=_/(m.length+1);for(g of m){if(g!==0)return(g<0?-_:_)+g;_-=v}return 0}function ee(e){if(e.length===0)return[];let t=e.map(f);if(e.length===1)return t[0].conversionsTo;let n=new Set(e),r=new Set;for(let e=0;e<t.length;++e)for(let i of t[e].conversionsTo)n.has(i.from)||r.add(i.from);let i=[];for(let e of r){let n=u+1,r=null;for(let i=0;i<t.length;++i)for(let a of t[i].conversionsTo)a.from===e&&a.index<n&&(n=a.index,r=a);i.push(r)}return i}function R(e,t){let n=t,r=``;if(e.some(e=>e.hasConversion)){let i=E(e),a=e.map(te);r=a.map(e=>e.name).join(`;`),n=function(){let e=[],n=i?arguments.length-1:arguments.length;for(let t=0;t<n;t++)e[t]=a[t](arguments[t]);return i&&(e[n]=arguments[n].map(a[n])),t.apply(this,e)}}let i=n;if(E(e)){let t=e.length-1;i=function(){return n.apply(this,ce(arguments,0,t).concat([ce(arguments,t)]))}}return r&&Object.defineProperty(i,"name",{value:r}),i}function te(e){let t,n,r,i,a=[],o=[],s=``;e.types.forEach(function(e){e.conversion&&(s+=e.conversion.from+`~>`+e.conversion.to+`,`,a.push(f(e.conversion.from).test),o.push(e.conversion.convert))}),s=s?s.slice(0,-1):`pass`;let c=e=>e;switch(o.length){case 0:break;case 1:t=a[0],r=o[0],c=function(e){return t(e)?r(e):e};break;case 2:t=a[0],n=a[1],r=o[0],i=o[1],c=function(e){return t(e)?r(e):n(e)?i(e):e};break;default:c=function(e){for(let t=0;t<o.length;t++)if(a[t](e))return o[t](e);return e}}return Object.defineProperty(c,"name",{value:s}),c}function z(e){function t(e,n,r){if(n<e.length){let i=e[n],a=[];if(i.restParam){let e=i.types.filter(j);e.length<i.types.length&&a.push({types:e,name:`...`+e.map(e=>e.name).join(`|`),hasAny:e.some(e=>e.isAny),hasConversion:!1,restParam:!0}),a.push(i)}else a=i.types.map(function(e){return{types:[e],name:e.name,hasAny:e.isAny,hasConversion:e.conversion,restParam:!1}});return ue(a,function(i){return t(e,n+1,r.concat([i]))})}else return[r]}return t(e,0,[])}function ne(e,t){let n=Math.max(e.length,t.length);for(let r=0;r<n;r++){let n=A(e,r),i=A(t,r),a=!1,o;for(o of i)if(n.has(o)){a=!0;break}if(!a)return!1}let r=e.length,i=t.length,a=E(e),o=E(t);return a?o?r===i:i>=r:o?r>=i:r===i}function B(e){return e.map(e=>he(e)?pe(e.referToSelf.callback):me(e)?fe(e.referTo.references,e.referTo.callback):e)}
2587function V(e,t,n){let r=[],i;for(i of e){let e=n[i];if(typeof e!=`number`)throw TypeError(`No definition for referenced signature "`+i+`"`);if(e=t[e],typeof e!=`function`)return!1;r.push(e)}return r}function H(e,t,n){let r=B(e),i=Array(r.length).fill(!1),a=!0;for(;a;){a=!1;let e=!0;for(let o=0;o<r.length;++o){if(i[o])continue;let s=r[o];if(he(s))r[o]=s.referToSelf.callback(n),r[o].referToSelf=s.referToSelf,i[o]=!0,e=!1;else if(me(s)){let n=V(s.referTo.references,r,t);n?(r[o]=s.referTo.callback.apply(this,n),r[o].referTo=s.referTo,i[o]=!0,e=!1):a=!0}}if(e&&a)throw SyntaxError(`Circular reference detected in resolving typed.referTo`)}return r}function re(e){let t=/\bthis(\(|\.signatures\b)/;Object.keys(e).forEach(n=>{let r=e[n];if(t.test(r.toString()))throw SyntaxError("Using `this` to self-reference a function is deprecated since typed-function@3. Use typed.referTo and typed.referToSelf instead.")})}function ie(e,r){if(d.createCount++,Object.keys(r).length===0)throw SyntaxError(`No signatures provided`);d.warnAgainstDeprecatedThis&&re(r);let i=[],a=[],o={},s=[],c;for(c in r){if(!Object.prototype.hasOwnProperty.call(r,c))continue;let e=T(c);if(!e)continue;
vendor: 5,246 bytes, line 2587
2587i.forEach(function(t){if(ne(t,e))throw TypeError(`Conflicting signatures "`+x(t)+`" and "`+x(e)+`".`)}),i.push(e);let t=a.length;a.push(r[c]);let n=e.map(C),l;for(l of z(n)){let e=x(l);s.push({params:l,name:e,fn:t}),l.every(e=>!e.hasConversion)&&(o[e]=t)}}s.sort(L);let l=H(a,o,ye),u;for(u in o)Object.prototype.hasOwnProperty.call(o,u)&&(o[u]=l[o[u]]);let f=[],p=new Map;for(u of s)p.has(u.name)||(u.fn=l[u.fn],f.push(u),p.set(u.name,u));let m=f[0]&&f[0].params.length<=2&&!E(f[0].params),h=f[1]&&f[1].params.length<=2&&!E(f[1].params),g=f[2]&&f[2].params.length<=2&&!E(f[2].params),_=f[3]&&f[3].params.length<=2&&!E(f[3].params),v=f[4]&&f[4].params.length<=2&&!E(f[4].params),y=f[5]&&f[5].params.length<=2&&!E(f[5].params),b=m&&h&&g&&_&&v&&y;for(let e=0;e<f.length;++e)f[e].test=O(f[e].params);let S=m?D(f[0].params[0]):t,w=h?D(f[1].params[0]):t,k=g?D(f[2].params[0]):t,A=_?D(f[3].params[0]):t,j=v?D(f[4].params[0]):t,M=y?D(f[5].params[0]):t,N=m?D(f[0].params[1]):t,P=h?D(f[1].params[1]):t,F=g?D(f[2].params[1]):t,I=_?D(f[3].params[1]):t,ee=v?D(f[4].params[1]):t,te=y?D(f[5].params[1]):t;for(let e=0;e<f.length;++e)f[e].implementation=R(f[e].params,f[e].fn);let B=m?f[0].implementation:n,V=h?f[1].implementation:n,ie=g?f[2].implementation:n,ae=_?f[3].implementation:n,oe=v?f[4].implementation:n,se=y?f[5].implementation:n,ce=m?f[0].params.length:-1,le=h?f[1].params.length:-1,ue=g?f[2].params.length:-1,de=_?f[3].params.length:-1,fe=v?f[4].params.length:-1,pe=y?f[5].params.length:-1,me=b?6:0,he=f.length,ge=f.map(e=>e.test),_e=f.map(e=>e.implementation),ve=function(){for(let e=me;e<he;e++)if(ge[e](arguments))return _e[e].apply(this,arguments);return d.onMismatch(e,arguments,f)};function ye(e,t){return arguments.length===ce&&S(e)&&N(t)?B.apply(this,arguments):arguments.length===le&&w(e)&&P(t)?V.apply(this,arguments):arguments.length===ue&&k(e)&&F(t)?ie.apply(this,arguments):arguments.length===de&&A(e)&&I(t)?ae.apply(this,arguments):arguments.length===fe&&j(e)&&ee(t)?oe.apply(this,arguments):arguments.length===pe&&M(e)&&te(t)?se.apply(this,arguments):ve.apply(this,arguments)}try{Object.defineProperty(ye,"name",{value:e})}catch{}return ye.signatures=o,ye._typedFunctionData={signatures:f,signatureMap:p},ye}function ae(e,t,n){throw N(e,t,n)}function oe(e){return ce(e,0,e.length-1)}function se(e){return e[e.length-1]}function ce(e,t,n){return Array.prototype.slice.call(e,t,n)}function le(e,t){for(let n=0;n<e.length;n++)if(t(e[n]))return e[n]}function ue(e,t){return Array.prototype.concat.apply([],e.map(t))}function de(){let e=oe(arguments).map(e=>x(T(e))),t=se(arguments);if(typeof t!=`function`)throw TypeError(`Callback function expected as last argument`);return fe(e,t)}function fe(e,t){return{referTo:{references:e,callback:t}}}function pe(e){if(typeof e!=`function`)throw TypeError(`Callback function expected as first argument`);return{referToSelf:{callback:e}}}function me(e){return e&&typeof e.referTo==`object`&&Array.isArray(e.referTo.references)&&typeof e.referTo.callback==`function`}function he(e){return e&&typeof e.referToSelf==`object`&&typeof e.referToSelf.callback==`function`}function ge(e,t){if(!e)return t;if(t&&t!==e){let n=Error(`Function names do not match (expected: `+e+`, actual: `+t+`)`);throw n.data={actual:t,expected:e},n}return e}function _e(e){let t;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(_(e[n])||typeof e[n].signature==`string`)&&(t=ge(t,e[n].name));return t}function ve(e,t){let n;for(n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(n in e&&t[n]!==e[n]){let r=Error(`Signature "`+n+`" is defined twice`);throw r.data={signature:n,sourceFunction:t[n],destFunction:e[n]},r}e[n]=t[n]}}let ye=d;d=function(e){let t=typeof e==`string`,n=+!!t,r=t?e:``,i={};for(let e=n;e<arguments.length;++e){let n=arguments[e],o={},s;if(typeof n==`function`?(s=n.name,typeof n.signature==`string`?o[n.signature]=n:_(n)&&(o=n.signatures)):a(n)&&(o=n,t||(s=_e(n))),Object.keys(o).length===0){let t=TypeError(`Argument to 'typed' at index `+e+` is not a (typed) function, nor an object with signatures as keys and functions as values.`);throw t.data={index:e,argument:n},t}t||(r=ge(r,s)),ve(i,o)}return ie(r||``,i)},d.create=i,d.createCount=ye.createCount,d.onMismatch=ae,d.throwMismatchError=ae,d.createError=N,d.clear=m,d.clearConversions=h,d.addTypes=p,d._findType=f,d.referTo=de,d.referToSelf=pe,d.convert=b,d.findSignature=v,d.find=y,d.isTypedFunction=_,d.warnAgainstDeprecatedThis=!0,d.addType=function(e,t){let n=`any`;t!==!1&&c.has(`Object`)&&(n=`Object`),d.addTypes([e],n)};function be(e){if(!e||typeof e.from!=`string`||typeof e.to!=`string`||typeof e.convert!=`function`)throw TypeError(`Object with properties {from: string, to: string, convert: function} expected`);if(e.to===e.from)throw SyntaxError(`Illegal to define conversion from "`+e.from+`" to itself.`)}return d.addConversion=function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{override:!1};be(e);let n=f(e.to),r=n.conversionsTo.find(t=>t.from===e.from);if(r)if(t&&t.override)d.removeConversion({from:r.from,to:e.to,convert:r.convert});else throw Error(`There is already a conversion from "`+e.from+`" to "`+n.name+`"`);n.conversionsTo.push({from:e.from,to:n.name,convert:e.convert,index:u++})}
2587,d.addConversions=function(e,t){e.forEach(e=>d.addConversion(e,t))},d.removeConversion=function(e){be(e);let t=f(e.to),n=le(t.conversionsTo,t=>t.from===e.from);if(!n)throw Error(`Attempt to remove nonexistent conversion from `+e.from+` to `+e.to);if(n.convert!==e.convert)throw Error(`Conversion to remove does not match existing conversion`);let r=t.conversionsTo.indexOf(n);t.conversionsTo.splice(r,1)},d.resolve=function(e,t){if(!_(e))throw TypeError(r);let n=e._typedFunctionData.signatures;for(let e=0;e<n.length;++e)if(n[e].test(t))return n[e];return null},d}return i()}))}));function Y(e,t,n,r){function i(r){var i=ace(r,t.map(dce));return lce(e,t,r),n(i)}return i.isFactory=!0,i.fn=e,i.dependencies=t.slice().sort(),r&&(i.meta=r),i}function cu(e){return typeof e==`function`&&typeof e.fn==`string`&&Array.isArray(e.dependencies)}function lce(e,t,n){if(!t.filter(e=>!uce(e)).every(e=>n[e]!==void 0)){var r=t.filter(e=>n[e]===void 0);throw Error(`Cannot create function "${e}", some dependencies are missing: ${r.map(e=>`"${e}"`).join(`, `)}.`)}}function uce(e){return e&&e[0]===`?`}function dce(e){return e&&e[0]===`?`?e.slice(1):e}var X=e((()=>{ru()}));function lu(e){return typeof e==`boolean`?!0:Number.isFinite(e)?e===Math.round(e):!1}function uu(e,t){if(t.number===`bigint`)try{BigInt(e)}catch{return t.numberFallback}return t.number}function du(e,t,n){var r={2:`0b`,8:`0o`,16:`0x`}[t],i=``;if(n){if(n<1)throw Error(`size must be in greater than 0`);if(!lu(n))throw Error(`size must be an integer`);if(e>2**(n-1)-1||e<-(2**(n-1)))throw Error(`Value must be in range [-2^${n-1}, 2^${n-1}-1]`);if(!lu(e))throw Error(`Value must be an integer`);e<0&&(e+=2**n),i=`i${n}`}var a=``;return e<0&&(e=-e,a=`-`),`${a}${r}${e.toString(t)}${i}`}function fu(e,t){if(typeof t==`function`)return t(e);if(e===1/0)return`Infinity`;if(e===-1/0)return`-Infinity`;if(isNaN(e))return`NaN`;var{notation:n,precision:r,wordSize:i}=pu(t);switch(n){case`fixed`:return hu(e,r);case`exponential`:return gu(e,r);case`engineering`:return fce(e,r);case`bin`:return du(e,2,i);case`oct`:return du(e,8,i);case`hex`:return du(e,16,i);case`auto`:return pce(e,r,t).replace(/((\.\d*?)(0+))($|e)/,function(){var e=arguments[2],t=arguments[4];return e===`.`?t:e+t});default:throw Error(`Unknown notation "`+n+`". Choose "auto", "exponential", "fixed", "bin", "oct", or "hex.`)}}function pu(e){var t=`auto`,n,r;if(e!==void 0)if(bl(e))n=e;else if(xl(e))n=e.toNumber();else if(Fl(e))e.precision!==void 0&&(n=bu(e.precision,()=>{throw Error(`Option "precision" must be a number or BigNumber`)})),e.wordSize!==void 0&&(r=bu(e.wordSize,()=>{throw Error(`Option "wordSize" must be a number or BigNumber`)})),e.notation&&(t=e.notation);else throw Error(`Unsupported type of options, number, BigNumber, or object expected`);return{notation:t,precision:n,wordSize:r}}function mu(e){var t=String(e).toLowerCase().match(/^(-?)(\d+\.?\d*)(e([+-]?\d+))?$/);if(!t)throw SyntaxError(`Invalid number `+e);var n=t[1],r=t[2],i=parseFloat(t[4]||`0`),a=r.indexOf(`.`);i+=a===-1?r.length-1:a-1;var o=r.replace(`.`,``).replace(/^0*/,function(e){return i-=e.length,``}).replace(/0*$/,``).split(``).map(function(e){return parseInt(e)});return o.length===0&&(o.push(0),i++),{sign:n,coefficients:o,exponent:i}}function fce(e,t){if(isNaN(e)||!Number.isFinite(e))return String(e);var n=_u(mu(e),t),r=n.exponent,i=n.coefficients,a=r%3==0?r:r<0?r-3-r%3:r-r%3;if(bl(t))for(;t>i.length||r-a+1>i.length;)i.push(0);else for(var o=Math.abs(r-a)-(i.length-1),s=0;s<o;s++)i.push(0);for(var c=Math.abs(r-a),l=1;c>0;)l++,c--;var u=i.slice(l).join(``),d=bl(t)&&u.length||u.match(/[1-9]/)?`.`+u:``,f=i.slice(0,l).join(``)+d+`e`+(r>=0?`+`:``)+a.toString();return n.sign+f}function hu(e,t){if(isNaN(e)||!Number.isFinite(e))return String(e);var n=mu(e),r=typeof t==`number`?_u(n,n.exponent+1+t):n,i=r.coefficients,a=r.exponent+1,o=a+(t||0);return i.length<o&&(i=i.concat(vu(o-i.length))),a<0&&(i=vu(-a+1).concat(i),a=1),a<i.length&&i.splice(a,0,a===0?`0.`:`.`),r.sign+i.join(``)}function gu(e,t){if(isNaN(e)||!Number.isFinite(Number(e)))return String(e);var n=mu(e),r=t?_u(n,t):n,i=r.coefficients,a=r.exponent;i.length<t&&(i=i.concat(vu(t-i.length)));var o=i.shift();return r.sign+o+(i.length>0?`.`+i.join(``):``)+`e`+(a>=0?`+`:``)+a}function pce(e,t,n){if(isNaN(e)||!Number.isFinite(e))return String(e);var r=xu(n?.lowerExp,-3),i=xu(n?.upperExp,5),a=mu(e),o=t?_u(a,t):a;if(o.exponent<r||o.exponent>=i)return gu(e,t);var s=o.coefficients,c=o.exponent;s.length<t&&(s=s.concat(vu(t-s.length))),s=s.concat(vu(c-s.length+1+(s.length<t?t-s.length:0))),s=vu(-c).concat(s);var l=c>0?c:0;return l<s.length-1&&s.splice(l+1,0,`.`),o.sign+s.join(``)}function _u(e,t){for(var n={sign:e.sign,coefficients:e.coefficients,exponent:e.exponent},r=n.coefficients;t<=0;)r.unshift(0),n.exponent++,t++;if(r.length>t&&r.splice(t,r.length-t)[0]>=5){var i=t-1;for(r[i]++;r[i]===10;)r.pop(),i===0&&(r.unshift(0),n.exponent++,i++),i--,r[i]++}return n}function vu(e){for(var t=[],n=0;n<e;n++)t.push(0);return t}function mce(e){return e.toExponential().replace(/e.*$/,``).replace(/^0\.?0*|\./,``).length}function yu(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1e-8,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0;
2587if(n<=0)throw Error(`Relative tolerance must be greater than 0`);if(r<0)throw Error(`Absolute tolerance must be at least 0`);return isNaN(e)||isNaN(t)?!1:!Number.isFinite(e)||!Number.isFinite(t)?e===t:e===t?!0:Math.abs(e-t)<=Math.max(n*Math.max(Math.abs(e),Math.abs(t)),r)}function hce(e,t){return(e>0?!0:e<0?!1:1/e==1/0)^(t>0?!0:t<0?!1:1/t==1/0)?-e:e}function bu(e,t){if(bl(e))return e;if(xl(e))return e.toNumber();t()}function xu(e,t){return bl(e)?e:xl(e)?e.toNumber():t}var Su,Cu,wu,Tu,Eu,Du,Ou,ku,Au,ju,Mu,Nu,Pu=e((()=>{Ql(),Su=Math.sign||function(e){return e>0?1:e<0?-1:0},Cu=Math.log2||function(e){return Math.log(e)/Math.LN2},wu=Math.log10||function(e){return Math.log(e)/Math.LN10},Tu=Math.log1p||function(e){return Math.log(e+1)},Eu=Math.cbrt||function(e){if(e===0)return e;var t=e<0,n;return t&&(e=-e),Number.isFinite(e)?(n=Math.exp(Math.log(e)/3),n=(e/(n*n)+2*n)/3):n=e,t?-n:n},Du=Math.expm1||function(e){return e>=2e-4||e<=-2e-4?Math.exp(e)-1:e+e*e/2+e*e*e/6},Ou=Math.acosh||function(e){return Math.log(Math.sqrt(e*e-1)+e)},ku=Math.asinh||function(e){return Math.log(Math.sqrt(e*e+1)+e)},Au=Math.atanh||function(e){return Math.log((1+e)/(1-e))/2},ju=Math.cosh||function(e){return(Math.exp(e)+Math.exp(-e))/2},Mu=Math.sinh||function(e){return(Math.exp(e)-Math.exp(-e))/2},Nu=Math.tanh||function(e){var t=Math.exp(2*e);return(t-1)/(t+1)}}));function Fu(e){throw Error(`Cannot convert value ${e} into a BigNumber: no class 'BigNumber' provided`)}function Iu(e){throw Error(`Cannot convert value ${e} into a Complex number: no class 'Complex' provided`)}function gce(){throw Error(`Cannot convert array into a Matrix: no class 'DenseMatrix' provided`)}function Lu(e){throw Error(`Cannot convert value ${e} into a Fraction, no class 'Fraction' provided.`)}var Ru,zu,Bu,Vu,_ce=e((()=>{Ru=t(su(),1),X(),Ql(),Pu(),zu=function(){return zu=Ru.default.create,Ru.default},Bu=[`?BigNumber`,`?Complex`,`?DenseMatrix`,`?Fraction`],Vu=Y(`typed`,Bu,function(e){var{BigNumber:t,Complex:n,DenseMatrix:r,Fraction:i}=e,a=zu();return a.clear(),a.addTypes([{name:`number`,test:bl},{name:`Complex`,test:Cl},{name:`BigNumber`,test:xl},{name:`bigint`,test:Sl},{name:`Fraction`,test:wl},{name:`Unit`,test:Tl},{name:`identifier`,test:e=>El&&/^(?:[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088F\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5C\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDC-\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7DC\uA7F1-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFB
2587D3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC\uDDC0-\uDDF3\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67\uDF80-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD40-\uDD59\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDD4A-\uDD65\uDD6F-\uDD85\uDE80-\uDEA9\uDEB0\uDEB1\uDEC2-\uDEC7\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDF70-\uDF81\uDFB0-\uDFC4\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC71\uDC72\uDC75\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE3F\uDE40\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61\uDF80-\uDF89\uDF8B\uDF8E\uDF90-\uDFB5\uDFB7\uDFD1\uDFD3]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDEB8\uDF00-\uDF1A\uDF40-\uDF46]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCDF\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEB0-\uDEF8\uDFC0-\uDFE0]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDDB0-\uDDDB\uDEE0-\uDEF2\uDF02\uDF04-\uDF10\uDF12-\uDF33\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|\uD80B[\uDF90-\uDFF0]|[\uD80C\uD80E\uD80F\uD81C-\uD822\uD840-\uD868\uD86A-\uD86D\uD86F-\uD872\uD874-\uD879\uD880-\uD883\uD885-\uD88C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2F\uDC41-\uDC46\uDC60-\uDFFF]|\uD810[\uDC00-\uDFFA]|\uD811[\uDC00-\uDE46]|\uD818[\uDD00-\uDD1D]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE70-\uDEBE\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDD40-\uDD6C\uDE40-\uDE7F\uDEA0-\uDEB8\uDEBB-\uDED3\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3\uDFF2\uDFF3]|\uD823[\uDC00-\uDCD5\uDCFF-\uDD1E\uDD80-\uDDF2]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00-\uDD22\uDD32\uDD50-\uDD52\uDD55\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD837[\uDF00-\uDF1E\uDF25-\uDF2A]|\uD838[\uDC30-\uDC6D\uDD00-\uDD2C\uDD37-\uDD3D\uDD4E\uDE90-\uDEAD\uDEC0-\uDEEB]|\uD839[\uDCD0-\uDCEB\uDDD0-\uDDED\uDDF0\uDEC0-\uDEDE\uDEE0-\uDEE2\uDEE4\uDEE5\uDEE7-\uDEED\uDEF0-\uDEF4\uDEFE\uDEFF\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD4B]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEAD\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0\uDFF0-\uDFFF]|\uD87B[\uDC00-\uDE5D]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A\uDF50-\uDFFF]|\uD88D[\uDC00-\uDC79])(?:[0-9A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088F\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5C\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDC-\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u
25870EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7DC\uA7F1-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC\uDDC0-\uDDF3\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67\uDF80-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD40-\uDD59\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDD4A-\uDD65\uDD6F-\uDD85\uDE80-\uDEA9\uDEB0\uDEB1\uDEC2-\uDEC7\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDF70-\uDF81\uDFB0-\uDFC4\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC71\uDC72\uDC75\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE3F\uDE40\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61\uDF80-\uDF89\uDF8B\uDF8E\uDF90-\uDFB5\uDFB7\uDFD1\uDFD3]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDEB8\uDF00-\uDF1A\uDF40-\uDF46]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCDF\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEB0-\uDEF8\uDFC0-\uDFE0]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDDB0-\uDDDB\uDEE0-\uDEF2\uDF02\uDF04-\uDF10\uDF12-\uDF33\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|\uD80B[\uDF90-\uDFF0]|[\uD80C\uD80E\uD80F\uD81C-\uD822\uD840-\uD868\uD86A-\uD86D\uD86F-\uD872\uD874-\uD879\uD880-\uD883\uD885-\uD88C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2F\uDC41-\uDC46\uDC60-\uDFFF]|\uD810[\uDC00-\uDFFA]|\uD811[\uDC00-\uDE46]|\uD818[\uDD00-\uDD1D]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE70-\uDEBE\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDD40-\uDD6C\uDE4
25870-\uDE7F\uDEA0-\uDEB8\uDEBB-\uDED3\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3\uDFF2\uDFF3]|\uD823[\uDC00-\uDCD5\uDCFF-\uDD1E\uDD80-\uDDF2]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00-\uDD22\uDD32\uDD50-\uDD52\uDD55\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD837[\uDF00-\uDF1E\uDF25-\uDF2A]|\uD838[\uDC30-\uDC6D\uDD00-\uDD2C\uDD37-\uDD3D\uDD4E\uDE90-\uDEAD\uDEC0-\uDEEB]|\uD839[\uDCD0-\uDCEB\uDDD0-\uDDED\uDDF0\uDEC0-\uDEDE\uDEE0-\uDEE2\uDEE4\uDEE5\uDEE7-\uDEED\uDEF0-\uDEF4\uDEFE\uDEFF\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD4B]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEAD\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0\uDFF0-\uDFFF]|\uD87B[\uDC00-\uDE5D]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A\uDF50-\uDFFF]|\uD88D[\uDC00-\uDC79])*$/.test(e)},{name:`string`,test:El},{name:`Chain`,test:Yl},{name:`Array`,test:Zl},{name:`Matrix`,test:Dl},{name:`DenseMatrix`,test:kl},{name:`SparseMatrix`,test:Al},{name:`Range`,test:jl},{name:`Index`,test:Ml},{name:`boolean`,test:Bse},{name:`ResultSet`,test:Vse},{name:`Help`,test:Nl},{name:`function`,test:Pl},{name:`Date`,test:Hse},{name:`RegExp`,test:Use},{name:`null`,test:Kse},{name:`undefined`,test:qse},{name:`AccessorNode`,test:Ll},{name:`ArrayNode`,test:Rl},{name:`AssignmentNode`,test:Jse},{name:`BlockNode`,test:Yse},{name:`ConditionalNode`,test:Xse},{name:`ConstantNode`,test:zl},{name:`FunctionNode`,test:Hl},{name:`FunctionAssignmentNode`,test:Vl},{name:`IndexNode`,test:Ul},{name:`Node`,test:Wl},{name:`ObjectNode`,test:Gl},{name:`OperatorNode`,test:Kl},{name:`ParenthesisNode`,test:ql},{name:`RangeNode`,test:Zse},{name:`RelationalNode`,test:Qse},{name:`SymbolNode`,test:Jl},{name:`Map`,test:Il},{name:`Object`,test:Fl}]),a.addConversions([{from:`number`,to:`BigNumber`,convert:function(e){if(t||Fu(e),mce(e)>15)throw TypeError(`Cannot implicitly convert a number with >15 significant digits to BigNumber (value: `+e+`). Use function bignumber(x) to convert to BigNumber.`);return new t(e)}},{from:`number`,to:`Complex`,convert:function(e){return n||Iu(e),new n(e,0)}},{from:`BigNumber`,to:`Complex`,convert:function(e){return n||Iu(e),new n(e.toNumber(),0)}},{from:`bigint`,to:`number`,convert:function(e){if(e>2**53-1)throw TypeError(`Cannot implicitly convert bigint to number: value exceeds the max safe integer value (value: `+e+`)`);return Number(e)}},{from:`bigint`,to:`BigNumber`,convert:function(e){return t||Fu(e),new t(e.toString())}},{from:`bigint`,to:`Fraction`,convert:function(e){return i||Lu(e),new i(e)}},{from:`Fraction`,to:`BigNumber`,convert:function(e){throw TypeError(`Cannot implicitly convert a Fraction to BigNumber or vice versa. Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.`)}},{from:`Fraction`,to:`Complex`,convert:function(e){return n||Iu(e),new n(e.valueOf(),0)}},{from:`number`,to:`Fraction`,convert:function(e){i||Lu(e);var t=new i(e);if(t.valueOf()!==e)throw TypeError(`Cannot implicitly convert a number to a Fraction when there will be a loss of precision (value: `+e+`). Use function fraction(x) to convert to Fraction.`);return t}},{from:`string`,to:`number`,convert:function(e){var t=Number(e);if(isNaN(t))throw Error(`Cannot convert "`+e+`" to a number`);return t}},{from:`string`,to:`BigNumber`,convert:function(e){t||Fu(e);try{return new t(e)}catch{throw Error(`Cannot convert "`+e+`" to BigNumber`)}}},{from:`string`,to:`bigint`,convert:function(e){try{return BigInt(e)}catch{throw Error(`Cannot convert "`+e+`" to BigInt`)}}},{from:`string`,to:`Fraction`,convert:function(e){i||Lu(e);try{return new i(e)}catch{throw Error(`Cannot convert "`+e+`" to Fraction`)}}},{from:`string`,to:`Complex`,convert:function(e){n||Iu(e);try{return new n(e)}catch{throw Error(`Cannot convert "`+e+`" to Complex`)}}},{from:`boolean`,to:`number`,convert:function(e){return+e}},{from:`boolean`,to:`BigNumber`,convert:function(e){return t||Fu(e),new t(+e)}},{from:`boolean`,to:`bigint`,convert:function(e){return BigInt(+e)}},{from:`boolean`,to:`Fraction`,convert:function(e){return i||Lu(e),new i(+e)}},{from:`boolean`,to:`string`,convert:function(e){return String(e)}}
vendor: 4,407 bytes, line 2587
2587,{from:`Array`,to:`Matrix`,convert:function(e){return r||gce(),new r(e)}},{from:`Matrix`,to:`Array`,convert:function(e){return e.valueOf()}}]),a.onMismatch=(e,t,n)=>{var r=a.createError(e,t,n);if([`wrongType`,`mismatch`].includes(r.data.category)&&t.length===1&&Ol(t[0])&&n.some(e=>!e.params.includes(`,`))){var i=TypeError(`Function '${e}' doesn't apply to matrices. To call it elementwise on a matrix 'M', try 'map(M, ${e})'.`);throw i.data=r.data,i}throw r},a.onMismatch=(e,t,n)=>{var r=a.createError(e,t,n);if([`wrongType`,`mismatch`].includes(r.data.category)&&t.length===1&&Ol(t[0])&&n.some(e=>!e.params.includes(`,`))){var i=TypeError(`Function '${e}' doesn't apply to matrices. To call it elementwise on a matrix 'M', try 'map(M, ${e})'.`);throw i.data=r.data,i}throw r},a})})),Hu,Uu,Wu,vce=e((()=>{X(),Hu=`ResultSet`,Uu=[],Wu=Y(Hu,Uu,()=>{function e(t){if(!(this instanceof e))throw SyntaxError(`Constructor must be called with the new operator`);this.entries=t||[]}return e.prototype.type=`ResultSet`,e.prototype.isResultSet=!0,e.prototype.valueOf=function(){return this.entries},e.prototype.toString=function(){return`[`+this.entries.map(String).join(`, `)+`]`},e.prototype.toJSON=function(){return{mathjs:`ResultSet`,entries:this.entries}},e.fromJSON=function(t){return new e(t.entries)},e},{isClass:!0})}));function Gu(e){var t,n,r,i=e.length-1,a=``,o=e[0];if(i>0){for(a+=o,t=1;t<i;t++)r=e[t]+``,n=Ld-r.length,n&&(a+=td(n)),a+=r;o=e[t],r=o+``,n=Ld-r.length,n&&(a+=td(n))}else if(o===0)return`0`;for(;o%10==0;)o/=10;return a+o}function Ku(e,t,n){if(e!==~~e||e<t||e>n)throw Error(Ed+e)}function qu(e,t,n,r){var i,a,o,s;for(a=e[0];a>=10;a/=10)--t;return--t<0?(t+=Ld,i=0):(i=Math.ceil((t+1)/Ld),t%=Ld),a=jd(10,Ld-t),s=e[i]%a|0,r==null?t<3?(t==0?s=s/100|0:t==1&&(s=s/10|0),o=n<4&&s==99999||n>3&&s==49999||s==5e4||s==0):o=(n<4&&s+1==a||n>3&&s+1==a/2)&&(e[i+1]/a/100|0)==jd(10,t-2)-1||(s==a/2||s==0)&&(e[i+1]/a/100|0)==0:t<4?(t==0?s=s/1e3|0:t==1?s=s/100|0:t==2&&(s=s/10|0),o=(r||n<4)&&s==9999||!r&&n>3&&s==4999):o=((r||n<4)&&s+1==a||!r&&n>3&&s+1==a/2)&&(e[i+1]/a/1e3|0)==jd(10,t-3)-1,o}function Ju(e,t,n){for(var r,i=[0],a,o=0,s=e.length;o<s;){for(a=i.length;a--;)i[a]*=t;for(i[0]+=vd.indexOf(e.charAt(o++)),r=0;r<i.length;r++)i[r]>n-1&&(i[r+1]===void 0&&(i[r+1]=0),i[r+1]+=i[r]/n|0,i[r]%=n)}return i.reverse()}function yce(e,t){var n,r,i;if(t.isZero())return t;r=t.d.length,r<32?(n=Math.ceil(r/3),i=(1/ud(4,n)).toString()):(n=16,i=`2.3283064365386962890625e-10`),e.precision+=n,t=ld(e,1,t.times(i),new e(1));for(var a=n;a--;){var o=t.times(t);t=o.times(o).minus(o).times(8).plus(1)}return e.precision-=n,t}function Yu(e,t,n,r){var i,a,o,s,c,l,u,d,f,p=e.constructor;out:if(t!=null){if(d=e.d,!d)return e;for(i=1,s=d[0];s>=10;s/=10)i++;if(a=t-i,a<0)a+=Ld,o=t,u=d[f=0],c=u/jd(10,i-o-1)%10|0;else if(f=Math.ceil((a+1)/Ld),s=d.length,f>=s)if(r){for(;s++<=f;)d.push(0);u=c=0,i=1,a%=Ld,o=a-Ld+1}else break out;else{for(u=s=d[f],i=1;s>=10;s/=10)i++;a%=Ld,o=a-Ld+i,c=o<0?0:u/jd(10,i-o-1)%10|0}if(r=r||t<0||d[f+1]!==void 0||(o<0?u:u%jd(10,i-o-1)),l=n<4?(c||r)&&(n==0||n==(e.s<0?3:2)):c>5||c==5&&(n==4||r||n==6&&(a>0?o>0?u/jd(10,i-o):0:d[f-1])%10&1||n==(e.s<0?8:7)),t<1||!d[0])return d.length=0,l?(t-=e.e+1,d[0]=jd(10,(Ld-t%Ld)%Ld),e.e=-t||0):d[0]=e.e=0,e;if(a==0?(d.length=f,s=1,f--):(d.length=f+1,s=jd(10,Ld-a),d[f]=o>0?(u/jd(10,i-o)%jd(10,o)|0)*s:0),l)for(;;)if(f==0){for(a=1,o=d[0];o>=10;o/=10)a++;for(o=d[0]+=s,s=1;o>=10;o/=10)s++;a!=s&&(e.e++,d[0]==Id&&(d[0]=1));break}else{if(d[f]+=s,d[f]!=Id)break;d[f--]=0,s=1}for(a=d.length;d[--a]===0;)d.pop()}return wd&&(e.e>p.maxE?(e.d=null,e.e=NaN):e.e<p.minE&&(e.e=0,e.d=[0])),e}function Xu(e,t,n){if(!e.isFinite())return sd(e);var r,i=e.e,a=Gu(e.d),o=a.length;return t?(n&&(r=n-o)>0?a=a.charAt(0)+`.`+a.slice(1)+td(r):o>1&&(a=a.charAt(0)+`.`+a.slice(1)),a=a+(e.e<0?`e`:`e+`)+e.e):i<0?(a=`0.`+td(-i-1)+a,n&&(r=n-o)>0&&(a+=td(r))):i>=o?(a+=td(i+1-o),n&&(r=n-i-1)>0&&(a=a+`.`+td(r))):((r=i+1)<o&&(a=a.slice(0,r)+`.`+a.slice(r)),n&&(r=n-o)>0&&(i+1===o&&(a+=`.`),a+=td(r))),a}function Zu(e,t){var n=e[0];for(t*=Ld;n>=10;n/=10)t++;return t}function Qu(e,t,n){if(t>zd)throw wd=!0,n&&(e.precision=n),Error(Dd);return Yu(new e(yd),t,1,!0)}function $u(e,t,n){if(t>Bd)throw Error(Dd);return Yu(new e(bd),t,n,!0)}function ed(e){var t=e.length-1,n=t*Ld+1;if(t=e[t],t){for(;t%10==0;t/=10)n--;for(t=e[0];t>=10;t/=10)n++}return n}function td(e){for(var t=``;e--;)t+=`0`;return t}
vendor: 15,485 bytes, line 2587
2587function nd(e,t,n,r){var i,a=new e(1),o=Math.ceil(r/Ld+4);for(wd=!1;;){if(n%2&&(a=a.times(t),pd(a.d,o)&&(i=!0)),n=Ad(n/2),n===0){n=a.d.length-1,i&&a.d[n]===0&&++a.d[n];break}t=t.times(t),pd(t.d,o)}return wd=!0,a}function rd(e){return e.d[e.d.length-1]&1}function id(e,t,n){for(var r,i,a=new e(t[0]),o=0;++o<t.length;){if(i=new e(t[o]),!i.s){a=i;break}r=a.cmp(i),(r===n||r===0&&a.s===n)&&(a=i)}return a}function ad(e,t){var n,r,i,a,o,s,c,l=0,u=0,d=0,f=e.constructor,p=f.rounding,m=f.precision;if(!e.d||!e.d[0]||e.e>17)return new f(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:NaN);for(t==null?(wd=!1,c=m):c=t,s=new f(.03125);e.e>-2;)e=e.times(s),d+=5;for(r=Math.log(jd(2,d))/Math.LN10*2+5|0,c+=r,n=a=o=new f(1),f.precision=c;;){if(a=Yu(a.times(e),c,1),n=n.times(++u),s=o.plus(Vd(a,n,c,1)),Gu(s.d).slice(0,c)===Gu(o.d).slice(0,c)){for(i=d;i--;)o=Yu(o.times(o),c,1);if(t==null)if(l<3&&qu(o.d,c-r,p,l))f.precision=c+=10,n=a=s=new f(1),u=0,l++;else return Yu(o,f.precision=m,p,wd=!0);else return f.precision=m,o}o=s}}function od(e,t){var n,r,i,a,o,s,c,l,u,d,f,p=1,m=10,h=e,g=h.d,_=h.constructor,v=_.rounding,y=_.precision;if(h.s<0||!g||!g[0]||!h.e&&g[0]==1&&g.length==1)return new _(g&&!g[0]?-1/0:h.s==1?g?0:h:NaN);if(t==null?(wd=!1,u=y):u=t,_.precision=u+=m,n=Gu(g),r=n.charAt(0),Math.abs(a=h.e)<0x5543df729c000){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)h=h.times(e),n=Gu(h.d),r=n.charAt(0),p++;a=h.e,r>1?(h=new _(`0.`+n),a++):h=new _(r+`.`+n.slice(1))}else return l=Qu(_,u+2,y).times(a+``),h=od(new _(r+`.`+n.slice(1)),u-m).plus(l),_.precision=y,t==null?Yu(h,y,v,wd=!0):h;for(d=h,c=o=h=Vd(h.minus(1),h.plus(1),u,1),f=Yu(h.times(h),u,1),i=3;;){if(o=Yu(o.times(f),u,1),l=c.plus(Vd(o,new _(i),u,1)),Gu(l.d).slice(0,u)===Gu(c.d).slice(0,u))if(c=c.times(2),a!==0&&(c=c.plus(Qu(_,u+2,y).times(a+``))),c=Vd(c,new _(p),u,1),t==null)if(qu(c.d,u-m,v,s))_.precision=u+=m,l=o=h=Vd(d.minus(1),d.plus(1),u,1),f=Yu(h.times(h),u,1),i=s=1;else return Yu(c,_.precision=y,v,wd=!0);else return _.precision=y,c;c=l,i+=2}}function sd(e){return String(e.s*e.s/0)}function cd(e,t){var n,r,i;for((n=t.indexOf(`.`))>-1&&(t=t.replace(`.`,``)),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;t.charCodeAt(r)===48;r++);for(i=t.length;t.charCodeAt(i-1)===48;--i);if(t=t.slice(r,i),t){if(i-=r,e.e=n=n-r-1,e.d=[],r=(n+1)%Ld,n<0&&(r+=Ld),r<i){for(r&&e.d.push(+t.slice(0,r)),i-=Ld;r<i;)e.d.push(+t.slice(r,r+=Ld));t=t.slice(r),r=Ld-t.length}else r-=i;for(;r--;)t+=`0`;e.d.push(+t),wd&&(e.e>e.constructor.maxE?(e.d=null,e.e=NaN):e.e<e.constructor.minE&&(e.e=0,e.d=[0]))}else e.e=0,e.d=[0];return e}function bce(e,t){var n,r,i,a,o,s,c,l,u;if(t.indexOf(`_`)>-1){if(t=t.replace(/(\d)_(?=\d)/g,`$1`),Fd.test(t))return cd(e,t)}else if(t===`Infinity`||t===`NaN`)return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(Nd.test(t))n=16,t=t.toLowerCase();else if(Md.test(t))n=2;else if(Pd.test(t))n=8;else throw Error(Ed+t);for(a=t.search(/p/i),a>0?(c=+t.slice(a+1),t=t.substring(2,a)):t=t.slice(2),a=t.indexOf(`.`),o=a>=0,r=e.constructor,o&&(t=t.replace(`.`,``),s=t.length,a=s-a,i=nd(r,new r(n),a,a*2)),l=Ju(t,n,Id),u=l.length-1,a=u;l[a]===0;--a)l.pop();return a<0?new r(e.s*0):(e.e=Zu(l,u),e.d=l,wd=!1,o&&(e=Vd(e,i,s*4)),c&&(e=e.times(Math.abs(c)<54?jd(2,c):Hd.pow(2,c))),wd=!0,e)}function xce(e,t){var n,r=t.d.length;if(r<3)return t.isZero()?t:ld(e,2,t,t);n=1.4*Math.sqrt(r),n=n>16?16:n|0,t=t.times(1/ud(5,n)),t=ld(e,2,t,t);for(var i,a=new e(5),o=new e(16),s=new e(20);n--;)i=t.times(t),t=t.times(a.plus(i.times(o.times(i).minus(s))));return t}function ld(e,t,n,r,i){var a,o,s,c,l=1,u=e.precision,d=Math.ceil(u/Ld);for(wd=!1,c=n.times(n),s=new e(r);;){if(o=Vd(s.times(c),new e(t++*t++),u,1),s=i?r.plus(o):r.minus(o),r=Vd(o.times(c),new e(t++*t++),u,1),o=s.plus(r),o.d[d]!==void 0){for(a=d;o.d[a]===s.d[a]&&a--;);if(a==-1)break}a=s,s=r,r=o,o=a,l++}return wd=!0,o.d.length=d+1,o}function ud(e,t){for(var n=e;--t;)n*=e;return n}function dd(e,t){var n,r=t.s<0,i=$u(e,e.precision,1),a=i.times(.5);if(t=t.abs(),t.lte(a))return Cd=r?4:1,t;if(n=t.divToInt(i),n.isZero())Cd=r?3:2;else{if(t=t.minus(n.times(i)),t.lte(a))return Cd=rd(n)?r?2:3:r?4:1,t;Cd=rd(n)?r?1:4:r?3:2}return t.minus(i).abs()}function fd(e,t,n,r){var i,a,o,s,c,l,u,d,f,p=e.constructor,m=n!==void 0;if(m?(Ku(n,1,_d),r===void 0?r=p.rounding:Ku(r,0,8)):(n=p.precision,r=p.rounding),!e.isFinite())u=sd(e);else{for(u=Xu(e),o=u.indexOf(`.`),m?(i=2,t==16?n=n*4-3:t==8&&(n=n*3-2)):i=t,o>=0&&(u=u.replace(`.`,``),f=new p(1),f.e=u.length-o,f.d=Ju(Xu(f),10,i),f.e=f.d.length),d=Ju(u,10,i),a=c=d.length;d[--c]==0;)d.pop();if(!d[0])u=m?`0p+0`:`0`;else{if(o<0?a--:(e=new p(e),e.d=d,e.e=a,e=Vd(e,f,n,r,0,i),d=e.d,a=e.e,l=Sd),o=d[n],s=i/2,l||=d[n+1]!==void 0,l=r<4?(o!==void 0||l)&&(r===0||r===(e.s<0?3:2)):o>s||o===s&&(r===4||l||r===6&&d[n-1]&1||r===(e.s<0?8:7)),d.length=n,l)for(;++d[--n]>i-1;)d[n]=0,n||(++a,d.unshift(1));for(c=d.length;!d[c-1];--c);for(o=0,u=``;o<c;o++)u+=vd.charAt(d[o]);if(m){if(c>1)if(t==16||t==8){for(o=t==16?4:3,--c;c%o;c++)u+=`0`;for(d=Ju(u,i,t),c=d.length;!d[c-1];--c);for(o=1,u=`1.`;o<c;o++)u+=vd.charAt(d[o])}else u=u.charAt(0)+`.`+u.slice(1);u=u+(a<0?`p`:`p+`)+a}else if(a<0){for(;++a;)u=`0`+u;u=`0.`+u}else if(++a>c)for(a-=c;a--;)u+=`0`;else a<c&&(u=u.slice(0,a)+`.`+u.slice(a))}u=(t==16?`0x`:t==2?`0b`:t==8?`0o`:``)+u}return e.s<0?`-`+u:u}function pd(e,t){if(e.length>t)return e.length=t,!0}function Sce(e){return new this(e).abs()}function Cce(e){return new this(e).acos()}function wce(e){return new this(e).acosh()}function Tce(e,t){return new this(e).plus(t)}function Ece(e){return new this(e).asin()}function Dce(e){return new this(e).asinh()}function Oce(e){return new this(e).atan()}function kce(e){return new this(e).atanh()}function Ace(e,t){e=new this(e),t=new this(t);var n,r=this.precision,i=this.rounding,a=r+4;return!e.s||!t.s?n=new this(NaN):!e.d&&!t.d?(n=$u(this,a,1).times(t.s>0?.25:.75),n.s=e.s):!t.d||e.isZero()?(n=t.s<0?$u(this,r,i):new this(0),n.s=e.s):!e.d||t.isZero()?(n=$u(this,a,1).times(.5),n.s=e.s):t.s<0?(this.precision=a,this.rounding=1,n=this.atan(Vd(e,t,a,1)),t=$u(this,a,1),this.precision=r,this.rounding=i,n=e.s<0?n.minus(t):n.plus(t)):n=this.atan(Vd(e,t,a,1)),n}function jce(e){return new this(e).cbrt()}function Mce(e){return Yu(e=new this(e),e.e+1,2)}function Nce(e,t,n){return new this(e).clamp(t,n)}function Pce(e){if(!e||typeof e!=`object`)throw Error(Td+`Object expected`);var t,n,r,i=e.defaults===!0,a=[`precision`,1,_d,`rounding`,0,8,`toExpNeg`,-gd,0,`toExpPos`,0,gd,`maxE`,0,gd,`minE`,-gd,0,`modulo`,0,9];for(t=0;t<a.length;t+=3)if(n=a[t],i&&(this[n]=xd[n]),(r=e[n])!==void 0)if(Ad(r)===r&&r>=a[t+1]&&r<=a[t+2])this[n]=r;else throw Error(Ed+n+`: `+r);if(n=`crypto`,i&&(this[n]=xd[n]),(r=e[n])!==void 0)if(r===!0||r===!1||r===0||r===1)if(r)if(typeof crypto<`u`&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[n]=!0;else throw Error(Od);else this[n]=!1;else throw Error(Ed+n+`: `+r);return this}function Fce(e){return new this(e).cos()}function Ice(e){return new this(e).cosh()}function md(e){var t,n,r;function i(e){var t,n,r,a=this;if(!(a instanceof i))return new i(e);if(a.constructor=i,hd(e)){a.s=e.s,wd?!e.d||e.e>i.maxE?(a.e=NaN,a.d=null):e.e<i.minE?(a.e=0,a.d=[0]):(a.e=e.e,a.d=e.d.slice()):(a.e=e.e,a.d=e.d?e.d.slice():e.d);return}if(r=typeof e,r===`number`){if(e===0){a.s=1/e<0?-1:1,a.e=0,a.d=[0];return}if(e<0?(e=-e,a.s=-1):a.s=1,e===~~e&&e<1e7){for(t=0,n=e;n>=10;n/=10)t++;wd?t>i.maxE?(a.e=NaN,a.d=null):t<i.minE?(a.e=0,a.d=[0]):(a.e=t,a.d=[e]):(a.e=t,a.d=[e]);return}if(e*0!=0){e||(a.s=NaN),a.e=NaN,a.d=null;return}return cd(a,e.toString())}if(r===`string`)return(n=e.charCodeAt(0))===45?(e=e.slice(1),a.s=-1):(n===43&&(e=e.slice(1)),a.s=1),Fd.test(e)?cd(a,e):bce(a,e);if(r===`bigint`)return e<0?(e=-e,a.s=-1):a.s=1,cd(a,e.toString());throw Error(Ed+e)}if(i.prototype=Z,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.EUCLID=9,i.config=i.set=Pce,i.clone=md,i.isDecimal=hd,i.abs=Sce,i.acos=Cce,i.acosh=wce,i.add=Tce,i.asin=Ece,i.asinh=Dce,i.atan=Oce,i.atanh=kce,i.atan2=Ace,i.cbrt=jce,i.ceil=Mce,i.clamp=Nce,i.cos=Fce,i.cosh=Ice,i.div=Lce,i.exp=Rce,i.floor=zce,i.hypot=Bce,i.ln=Vce,i.log=Hce,i.log10=Wce,i.log2=Uce,i.max=Gce,i.min=Kce,i.mod=qce,i.mul=Jce,i.pow=Yce,i.random=Xce,i.round=Zce,i.sign=Qce,i.sin=$ce,i.sinh=ele,i.sqrt=tle,i.sub=nle,i.sum=rle,i.tan=ile,i.tanh=ale,i.trunc=ole,e===void 0&&(e={}),e&&e.defaults!==!0)for(r=[`precision`,`rounding`,`toExpNeg`,`toExpPos`,`maxE`,`minE`,`modulo`,`crypto`],t=0;t<r.length;)e.hasOwnProperty(n=r[t++])||(e[n]=this[n]);return i.config(e),i}function Lce(e,t){return new this(e).div(t)}function Rce(e){return new this(e).exp()}function zce(e){return Yu(e=new this(e),e.e+1,3)}function Bce(){var e,t,n=new this(0);for(wd=!1,e=0;e<arguments.length;)if(t=new this(arguments[e++]),t.d)n.d&&(n=n.plus(t.times(t)));else{if(t.s)return wd=!0,new this(1/0);n=t}return wd=!0,n.sqrt()}function hd(e){return e instanceof Hd||e&&e.toStringTag===kd||!1}function Vce(e){return new this(e).ln()}function Hce(e,t){return new this(e).log(t)}function Uce(e){return new this(e).log(2)}function Wce(e){return new this(e).log(10)}function Gce(){return id(this,arguments,-1)}function Kce(){return id(this,arguments,1)}function qce(e,t){return new this(e).mod(t)}function Jce(e,t){return new this(e).mul(t)}function Yce(e,t){return new this(e).pow(t)}function Xce(e){var t,n,r,i,a=0,o=new this(1),s=[];if(e===void 0?e=this.precision:Ku(e,1,_d),r=Math.ceil(e/Ld),!this.crypto)for(;a<r;)s[a++]=Math.random()*1e7|0;else if(crypto.getRandomValues)for(t=crypto.getRandomValues(new Uint32Array(r));a<r;)i=t[a],i>=429e7?t[a]=crypto.getRandomValues(new Uint32Array(1))[0]:s[a++]=i%1e7;else if(crypto.randomBytes){for(t=crypto.randomBytes(r*=4);a<r;)i=t[a]+(t[a+1]<<8)+(t[a+2]<<16)+((t[a+3]&127)<<24),i>=214e7?crypto.randomBytes(4).copy(t,a):(s.push(i%1e7),a+=4);a=r/4}else throw Error(Od);for(r=s[--a],e%=Ld,r&&e&&(i=jd(10,Ld-e),s[a]=(r/i|0)*i);s[a]===0;a--)s.pop();if(a<0)n=0,s=[0];else{for(n=-1;s[0]===0;n-=Ld)s.shift();for(r=1,i=s[0];i>=10;i/=10)r++;r<Ld&&(n-=Ld-r)}return o.e=n,o.d=s,o}function Zce(e){return Yu(e=new this(e),e.e+1,this.rounding)}function Qce(e){return e=new this(e),e.d?e.d[0]?e.s:0*e.s:e.s||NaN}function $ce(e){return new this(e).sin()}function ele(e){return new this(e).sinh()}function tle(e){return new this(e).sqrt()}function nle(e,t){return new this(e).sub(t)}function rle(){var e=0,t=arguments,n=new this(t[e]);for(wd=!1;n.s&&++e<t.length;)n=n.plus(t[e]);return wd=!0,Yu(n,this.precision,this.rounding)}function ile(e){return new this(e).tan()}function ale(e){return new this(e).tanh()}function ole(e){return Yu(e=new this(e),e.e+1,1)}var gd,_d,vd,yd,bd,xd,Sd,Cd,wd,Td,Ed,Dd,Od,kd,Ad,jd,Md,Nd,Pd,Fd,Id,Ld,Rd,zd,Bd,Z,Vd,Hd,Ud=e((()=>{gd=9e15,_d=1e9,vd=`0123456789abcdef`,yd=`2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058`,bd=`3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789`,xd={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-gd,maxE:gd,crypto:!1},wd=!0,Td=`[DecimalError] `,Ed=Td+`Invalid argument: `,Dd=Td+`Precision limit exceeded`,Od=Td+`crypto unavailable`,kd=`[object Decimal]`,Ad=Math.floor,jd=Math.pow,Md=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,Nd=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,Pd=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Fd=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Id=1e7,Ld=7,Rd=9007199254740991,zd=yd.length-1,Bd=bd.length-1,Z={toStringTag:kd},Z.absoluteValue=Z.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),Yu(e)},Z.ceil=function(){return Yu(new this.constructor(this),this.e+1,2)},Z.clampedTo=Z.clamp=function(e,t){var n,r=this,i=r.constructor;if(e=new i(e),t=new i(t),!e.s||!t.s)return new i(NaN);if(e.gt(t))throw Error(Ed+t);return n=r.cmp(e),n<0?e:r.cmp(t)>0?t:new i(r)},Z.comparedTo=Z.cmp=function(e){var t,n,r,i,a=this,o=a.d,s=(e=new a.constructor(e)).d,c=a.s,l=e.s;if(!o||!s)return!c||!l?NaN:c===l?o===s?0:!o^c<0?1:-1:c;if(!o[0]||!s[0])return o[0]?c:s[0]?-l:0;if(c!==l)return c;if(a.e!==e.e)return a.e>e.e^c<0?1:-1;for(r=o.length,i=s.length,t=0,n=r<i?r:i;t<n;++t)if(o[t]!==s[t])return o[t]>s[t]^c<0?1:-1;return r===i?0:r>i^c<0?1:-1},Z.cosine=Z.cos=function(){var e,t,n=this,r=n.constructor;return n.d?n.d[0]?(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+Ld,r.rounding=1,n=yce(r,dd(r,n)),r.precision=e,r.rounding=t,Yu(Cd==2||Cd==3?n.neg():n,e,t,!0)):new r(1):new r(NaN)},Z.cubeRoot=Z.cbrt=function(){var e,t,n,r,i,a,o,s,c,l,u=this,d=u.constructor;if(!u.isFinite()||u.isZero())return new d(u);for(wd=!1,a=u.s*jd(u.s*u,1/3),!a||Math.abs(a)==1/0?(n=Gu(u.d),e=u.e,(a=(e-n.length+1)%3)&&(n+=a==1||a==-2?`0`:`00`),a=jd(n,1/3),e=Ad((e+1)/3)-(e%3==(e<0?-1:2)),a==1/0?n=`5e`+e:(n=a.toExponential(),n=n.slice(0,n.indexOf(`e`)+1)+e),r=new d(n),r.s=u.s):r=new d(a.toString()),o=(e=d.precision)+3;;)if(s=r,c=s.times(s).times(s),l=c.plus(u),r=Vd(l.plus(u).times(s),l.plus(c),o+2,1),Gu(s.d).slice(0,o)===(n=Gu(r.d)).slice(0,o))if(n=n.slice(o-3,o+1),n==`9999`||!i&&n==`4999`){if(!i&&(Yu(s,e+1,0),s.times(s).times(s).eq(u))){r=s;break}o+=4,i=1}else{(!+n||!+n.slice(1)&&n.charAt(0)==`5`)&&(Yu(r,e+1,1),t=!r.times(r).times(r).eq(u));break}return wd=!0,Yu(r,e,d.rounding,t)},Z.decimalPlaces=Z.dp=function(){var e,t=this.d,n=NaN;if(t){if(e=t.length-1,n=(e-Ad(this.e/Ld))*Ld,e=t[e],e)for(;e%10==0;e/=10)n--;n<0&&(n=0)}return n},Z.dividedBy=Z.div=function(e){return Vd(this,new this.constructor(e))},Z.dividedToIntegerBy=Z.divToInt=function(e){var t=this,n=t.constructor;
2587return Yu(Vd(t,new n(e),0,1,1),n.precision,n.rounding)},Z.equals=Z.eq=function(e){return this.cmp(e)===0},Z.floor=function(){return Yu(new this.constructor(this),this.e+1,3)},Z.greaterThan=Z.gt=function(e){return this.cmp(e)>0},Z.greaterThanOrEqualTo=Z.gte=function(e){var t=this.cmp(e);return t==1||t===0},Z.hyperbolicCosine=Z.cosh=function(){var e,t,n,r,i,a=this,o=a.constructor,s=new o(1);if(!a.isFinite())return new o(a.s?1/0:NaN);if(a.isZero())return s;n=o.precision,r=o.rounding,o.precision=n+Math.max(a.e,a.sd())+4,o.rounding=1,i=a.d.length,i<32?(e=Math.ceil(i/3),t=(1/ud(4,e)).toString()):(e=16,t=`2.3283064365386962890625e-10`),a=ld(o,1,a.times(t),new o(1),!0);for(var c,l=e,u=new o(8);l--;)c=a.times(a),a=s.minus(c.times(u.minus(c.times(u))));return Yu(a,o.precision=n,o.rounding=r,!0)},Z.hyperbolicSine=Z.sinh=function(){var e,t,n,r,i=this,a=i.constructor;if(!i.isFinite()||i.isZero())return new a(i);if(t=a.precision,n=a.rounding,a.precision=t+Math.max(i.e,i.sd())+4,a.rounding=1,r=i.d.length,r<3)i=ld(a,2,i,i,!0);else{e=1.4*Math.sqrt(r),e=e>16?16:e|0,i=i.times(1/ud(5,e)),i=ld(a,2,i,i,!0);for(var o,s=new a(5),c=new a(16),l=new a(20);e--;)o=i.times(i),i=i.times(s.plus(o.times(c.times(o).plus(l))))}return a.precision=t,a.rounding=n,Yu(i,t,n,!0)},Z.hyperbolicTangent=Z.tanh=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+7,r.rounding=1,Vd(n.sinh(),n.cosh(),r.precision=e,r.rounding=t)):new r(n.s)},Z.inverseCosine=Z.acos=function(){var e=this,t=e.constructor,n=e.abs().cmp(1),r=t.precision,i=t.rounding;return n===-1?e.isZero()?$u(t,r+4,i).times(.5):(t.precision=r+6,t.rounding=1,e=new t(1).minus(e).div(e.plus(1)).sqrt().atan(),t.precision=r,t.rounding=i,e.times(2)):n===0?e.isNeg()?$u(t,r,i):new t(0):new t(NaN)},Z.inverseHyperbolicCosine=Z.acosh=function(){var e,t,n=this,r=n.constructor;return n.lte(1)?new r(n.eq(1)?0:NaN):n.isFinite()?(e=r.precision,t=r.rounding,r.precision=e+Math.max(Math.abs(n.e),n.sd())+4,r.rounding=1,wd=!1,n=n.times(n).minus(1).sqrt().plus(n),wd=!0,r.precision=e,r.rounding=t,n.ln()):new r(n)},Z.inverseHyperbolicSine=Z.asinh=function(){var e,t,n=this,r=n.constructor;return!n.isFinite()||n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+2*Math.max(Math.abs(n.e),n.sd())+6,r.rounding=1,wd=!1,n=n.times(n).plus(1).sqrt().plus(n),wd=!0,r.precision=e,r.rounding=t,n.ln())},Z.inverseHyperbolicTangent=Z.atanh=function(){var e,t,n,r,i=this,a=i.constructor;return i.isFinite()?i.e>=0?new a(i.abs().eq(1)?i.s/0:i.isZero()?i:NaN):(e=a.precision,t=a.rounding,r=i.sd(),Math.max(r,e)<2*-i.e-1?Yu(new a(i),e,t,!0):(a.precision=n=r-i.e,i=Vd(i.plus(1),new a(1).minus(i),n+e,1),a.precision=e+4,a.rounding=1,i=i.ln(),a.precision=e,a.rounding=t,i.times(.5))):new a(NaN)},Z.inverseSine=Z.asin=function(){var e,t,n,r,i=this,a=i.constructor;return i.isZero()?new a(i):(t=i.abs().cmp(1),n=a.precision,r=a.rounding,t===-1?(a.precision=n+6,a.rounding=1,i=i.div(new a(1).minus(i.times(i)).sqrt().plus(1)).atan(),a.precision=n,a.rounding=r,i.times(2)):t===0?(e=$u(a,n+4,r).times(.5),e.s=i.s,e):new a(NaN))},Z.inverseTangent=Z.atan=function(){var e,t,n,r,i,a,o,s,c,l=this,u=l.constructor,d=u.precision,f=u.rounding;if(!l.isFinite()){if(!l.s)return new u(NaN);if(d+4<=Bd)return o=$u(u,d+4,f).times(.5),o.s=l.s,o}else if(l.isZero())return new u(l);else if(l.abs().eq(1)&&d+4<=Bd)return o=$u(u,d+4,f).times(.25),o.s=l.s,o;for(u.precision=s=d+10,u.rounding=1,n=Math.min(28,s/Ld+2|0),e=n;e;--e)l=l.div(l.times(l).plus(1).sqrt().plus(1));for(wd=!1,t=Math.ceil(s/Ld),r=1,c=l.times(l),o=new u(l),i=l;e!==-1;)if(i=i.times(c),a=o.minus(i.div(r+=2)),i=i.times(c),o=a.plus(i.div(r+=2)),o.d[t]!==void 0)for(e=t;o.d[e]===a.d[e]&&e--;);return n&&(o=o.times(2<<n-1)),wd=!0,Yu(o,u.precision=d,u.rounding=f,!0)},Z.isFinite=function(){return!!this.d},Z.isInteger=Z.isInt=function(){return!!this.d&&Ad(this.e/Ld)>this.d.length-2},Z.isNaN=function(){return!this.s},Z.isNegative=Z.isNeg=function(){return this.s<0},Z.isPositive=Z.isPos=function(){return this.s>0},Z.isZero=function(){return!!this.d&&this.d[0]===0},Z.lessThan=Z.lt=function(e){return this.cmp(e)<0}
vendor: 7,178 bytes, line 2587
2587,Z.lessThanOrEqualTo=Z.lte=function(e){return this.cmp(e)<1},Z.logarithm=Z.log=function(e){var t,n,r,i,a,o,s,c,l=this,u=l.constructor,d=u.precision,f=u.rounding,p=5;if(e==null)e=new u(10),t=!0;else{if(e=new u(e),n=e.d,e.s<0||!n||!n[0]||e.eq(1))return new u(NaN);t=e.eq(10)}if(n=l.d,l.s<0||!n||!n[0]||l.eq(1))return new u(n&&!n[0]?-1/0:l.s==1?n?0:1/0:NaN);if(t)if(n.length>1)a=!0;else{for(i=n[0];i%10==0;)i/=10;a=i!==1}if(wd=!1,s=d+p,o=od(l,s),r=t?Qu(u,s+10):od(e,s),c=Vd(o,r,s,1),qu(c.d,i=d,f))do if(s+=10,o=od(l,s),r=t?Qu(u,s+10):od(e,s),c=Vd(o,r,s,1),!a){+Gu(c.d).slice(i+1,i+15)+1==0x5af3107a4000&&(c=Yu(c,d+1,0));break}while(qu(c.d,i+=10,f));return wd=!0,Yu(c,d,f)},Z.minus=Z.sub=function(e){var t,n,r,i,a,o,s,c,l,u,d,f,p=this,m=p.constructor;if(e=new m(e),!p.d||!e.d)return!p.s||!e.s?e=new m(NaN):p.d?e.s=-e.s:e=new m(e.d||p.s!==e.s?p:NaN),e;if(p.s!=e.s)return e.s=-e.s,p.plus(e);if(l=p.d,f=e.d,s=m.precision,c=m.rounding,!l[0]||!f[0]){if(f[0])e.s=-e.s;else if(l[0])e=new m(p);else return new m(c===3?-0:0);return wd?Yu(e,s,c):e}if(n=Ad(e.e/Ld),u=Ad(p.e/Ld),l=l.slice(),a=u-n,a){for(d=a<0,d?(t=l,a=-a,o=f.length):(t=f,n=u,o=l.length),r=Math.max(Math.ceil(s/Ld),o)+2,a>r&&(a=r,t.length=1),t.reverse(),r=a;r--;)t.push(0);t.reverse()}else{for(r=l.length,o=f.length,d=r<o,d&&(o=r),r=0;r<o;r++)if(l[r]!=f[r]){d=l[r]<f[r];break}a=0}for(d&&(t=l,l=f,f=t,e.s=-e.s),o=l.length,r=f.length-o;r>0;--r)l[o++]=0;for(r=f.length;r>a;){if(l[--r]<f[r]){for(i=r;i&&l[--i]===0;)l[i]=Id-1;--l[i],l[r]+=Id}l[r]-=f[r]}for(;l[--o]===0;)l.pop();for(;l[0]===0;l.shift())--n;return l[0]?(e.d=l,e.e=Zu(l,n),wd?Yu(e,s,c):e):new m(c===3?-0:0)},Z.modulo=Z.mod=function(e){var t,n=this,r=n.constructor;return e=new r(e),!n.d||!e.s||e.d&&!e.d[0]?new r(NaN):!e.d||n.d&&!n.d[0]?Yu(new r(n),r.precision,r.rounding):(wd=!1,r.modulo==9?(t=Vd(n,e.abs(),0,3,1),t.s*=e.s):t=Vd(n,e,0,r.modulo,1),t=t.times(e),wd=!0,n.minus(t))},Z.naturalExponential=Z.exp=function(){return ad(this)},Z.naturalLogarithm=Z.ln=function(){return od(this)},Z.negated=Z.neg=function(){var e=new this.constructor(this);return e.s=-e.s,Yu(e)},Z.plus=Z.add=function(e){var t,n,r,i,a,o,s,c,l,u,d=this,f=d.constructor;if(e=new f(e),!d.d||!e.d)return!d.s||!e.s?e=new f(NaN):d.d||(e=new f(e.d||d.s===e.s?d:NaN)),e;if(d.s!=e.s)return e.s=-e.s,d.minus(e);if(l=d.d,u=e.d,s=f.precision,c=f.rounding,!l[0]||!u[0])return u[0]||(e=new f(d)),wd?Yu(e,s,c):e;if(a=Ad(d.e/Ld),r=Ad(e.e/Ld),l=l.slice(),i=a-r,i){for(i<0?(n=l,i=-i,o=u.length):(n=u,r=a,o=l.length),a=Math.ceil(s/Ld),o=a>o?a+1:o+1,i>o&&(i=o,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for(o=l.length,i=u.length,o-i<0&&(i=o,n=u,u=l,l=n),t=0;i;)t=(l[--i]=l[i]+u[i]+t)/Id|0,l[i]%=Id;for(t&&(l.unshift(t),++r),o=l.length;l[--o]==0;)l.pop();return e.d=l,e.e=Zu(l,r),wd?Yu(e,s,c):e},Z.precision=Z.sd=function(e){var t,n=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(Ed+e);return n.d?(t=ed(n.d),e&&n.e+1>t&&(t=n.e+1)):t=NaN,t},Z.round=function(){var e=this,t=e.constructor;return Yu(new t(e),e.e+1,t.rounding)},Z.sine=Z.sin=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+Ld,r.rounding=1,n=xce(r,dd(r,n)),r.precision=e,r.rounding=t,Yu(Cd>2?n.neg():n,e,t,!0)):new r(NaN)},Z.squareRoot=Z.sqrt=function(){var e,t,n,r,i,a,o=this,s=o.d,c=o.e,l=o.s,u=o.constructor;if(l!==1||!s||!s[0])return new u(!l||l<0&&(!s||s[0])?NaN:s?o:1/0);for(wd=!1,l=Math.sqrt(+o),l==0||l==1/0?(t=Gu(s),(t.length+c)%2==0&&(t+=`0`),l=Math.sqrt(t),c=Ad((c+1)/2)-(c<0||c%2),l==1/0?t=`5e`+c:(t=l.toExponential(),t=t.slice(0,t.indexOf(`e`)+1)+c),r=new u(t)):r=new u(l.toString()),n=(c=u.precision)+3;;)if(a=r,r=a.plus(Vd(o,a,n+2,1)).times(.5),Gu(a.d).slice(0,n)===(t=Gu(r.d)).slice(0,n))if(t=t.slice(n-3,n+1),t==`9999`||!i&&t==`4999`){if(!i&&(Yu(a,c+1,0),a.times(a).eq(o))){r=a;break}n+=4,i=1}else{(!+t||!+t.slice(1)&&t.charAt(0)==`5`)&&(Yu(r,c+1,1),e=!r.times(r).eq(o));break}return wd=!0,Yu(r,c,u.rounding,e)},Z.tangent=Z.tan=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+10,r.rounding=1,n=n.sin(),n.s=1,n=Vd(n,new r(1).minus(n.times(n)).sqrt(),e+10,0),r.precision=e,r.rounding=t,Yu(Cd==2||Cd==4?n.neg():n,e,t,!0)):new r(NaN)},Z.times=Z.mul=function(e){var t,n,r,i,a,o,s,c,l,u=this,d=u.constructor,f=u.d,p=(e=new d(e)).d;if(e.s*=u.s,!f||!f[0]||!p||!p[0])return new d(!e.s||f&&!f[0]&&!p||p&&!p[0]&&!f?NaN:!f||!p?e.s/0:e.s*0);for(n=Ad(u.e/Ld)+Ad(e.e/Ld),c=f.length,l=p.length,c<l&&(a=f,f=p,p=a,o=c,c=l,l=o),a=[],o=c+l,r=o;r--;)a.push(0);for(r=l;--r>=0;){for(t=0,i=c+r;i>r;)s=a[i]+p[r]*f[i-r-1]+t,a[i--]=s%Id|0,t=s/Id|0;a[i]=(a[i]+t)%Id|0}for(;!a[--o];)a.pop();return t?++n:a.shift(),e.d=a,e.e=Zu(a,n),wd?Yu(e,d.precision,d.rounding):e},Z.toBinary=function(e,t){return fd(this,2,e,t)},Z.toDecimalPlaces=Z.toDP=function(e,t){var n=this,r=n.constructor;return n=new r(n),e===void 0?n:(Ku(e,0,_d),t===void 0?t=r.rounding:Ku(t,0,8),Yu(n,e+n.e+1,t))},Z.toExponential=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=Xu(r,!0):(Ku(e,0,_d),t===void 0?t=i.rounding:Ku(t,0,8),r=Yu(new i(r),e+1,t),n=Xu(r,!0,e+1)),r.isNeg()&&!r.isZero()?`-`+n:n},Z.toFixed=function(e,t){var n,r,i=this,a=i.constructor;return e===void 0?n=Xu(i):(Ku(e,0,_d),t===void 0?t=a.rounding:Ku(t,0,8),r=Yu(new a(i),e+i.e+1,t),n=Xu(r,!1,e+r.e+1)),i.isNeg()&&!i.isZero()?`-`+n:n},Z.toFraction=function(e){var t,n,r,i,a,o,s,c,l,u,d,f,p=this,m=p.d,h=p.constructor;if(!m)return new h(p);if(l=n=new h(1),r=c=new h(0),t=new h(r),a=t.e=ed(m)-p.e-1,o=a%Ld,t.d[0]=jd(10,o<0?Ld+o:o),e==null)e=a>0?t:l;else{if(s=new h(e),!s.isInt()||s.lt(l))throw Error(Ed+s);e=s.gt(t)?a>0?t:l:s}for(wd=!1,s=new h(Gu(m)),u=h.precision,h.precision=a=m.length*Ld*2;d=Vd(s,t,0,1,1),i=n.plus(d.times(r)),i.cmp(e)!=1;)n=r,r=i,i=l,l=c.plus(d.times(i)),c=i,i=t,t=s.minus(d.times(i)),s=i;return i=Vd(e.minus(n),r,0,1,1),c=c.plus(i.times(l)),n=n.plus(i.times(r)),c.s=l.s=p.s,f=Vd(l,r,a,1).minus(p).abs().cmp(Vd(c,n,a,1).minus(p).abs())<1?[l,r]:[c,n],h.precision=u,wd=!0,f},Z.toHexadecimal=Z.toHex=function(e,t){return fd(this,16,e,t)},Z.toNearest=function(e,t){var n=this,r=n.constructor;if(n=new r(n),e==null){if(!n.d)return n;e=new r(1),t=r.rounding}else{if(e=new r(e),t===void 0?t=r.rounding:Ku(t,0,8),!n.d)return e.s?n:e;if(!e.d)return e.s&&=n.s,e}return e.d[0]?(wd=!1,n=Vd(n,e,0,t,1).times(e),wd=!0,Yu(n)):(e.s=n.s,n=e),n},Z.toNumber=function(){return+this},Z.toOctal=function(e,t){return fd(this,8,e,t)},Z.toPower=Z.pow=function(e){var t,n,r,i,a,o,s=this,c=s.constructor,l=+(e=new c(e));if(!s.d||!e.d||!s.d[0]||!e.d[0])return new c(jd(+s,l));if(s=new c(s),s.eq(1))return s;if(r=c.precision,a=c.rounding,e.eq(1))return Yu(s,r,a);if(t=Ad(e.e/Ld),t>=e.d.length-1&&(n=l<0?-l:l)<=Rd)return i=nd(c,s,n,r),e.s<0?new c(1).div(i):Yu(i,r,a);if(o=s.s,o<0){if(t<e.d.length-1)return new c(NaN);if(e.d[t]&1||(o=1),s.e==0&&s.d[0]==1&&s.d.length==1)return s.s=o,s}return n=jd(+s,l),t=n==0||!isFinite(n)?Ad(l*(Math.log(`0.`+Gu(s.d))/Math.LN10+s.e+1)):new c(n+``).e,t>c.maxE+1||t<c.minE-1?new c(t>0?o/0:0):(wd=!1,c.rounding=s.s=1,n=Math.min(12,(t+``).length),i=ad(e.times(od(s,r+n)),r),i.d&&(i=Yu(i,r+5,1),qu(i.d,r,a)&&(t=r
2587+10,i=Yu(ad(e.times(od(s,t+n)),t),t+5,1),+Gu(i.d).slice(r+1,r+15)+1==0x5af3107a4000&&(i=Yu(i,r+1,0)))),i.s=o,wd=!0,c.rounding=a,Yu(i,r,a))},Z.toPrecision=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=Xu(r,r.e<=i.toExpNeg||r.e>=i.toExpPos):(Ku(e,1,_d),t===void 0?t=i.rounding:Ku(t,0,8),r=Yu(new i(r),e,t),n=Xu(r,e<=r.e||r.e<=i.toExpNeg,e)),r.isNeg()&&!r.isZero()?`-`+n:n},Z.toSignificantDigits=Z.toSD=function(e,t){var n=this,r=n.constructor;return e===void 0?(e=r.precision,t=r.rounding):(Ku(e,1,_d),t===void 0?t=r.rounding:Ku(t,0,8)),Yu(new r(n),e,t)},Z.toString=function(){var e=this,t=e.constructor,n=Xu(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?`-`+n:n},Z.truncated=Z.trunc=function(){return Yu(new this.constructor(this),this.e+1,1)},Z.valueOf=Z.toJSON=function(){var e=this,t=e.constructor,n=Xu(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()?`-`+n:n},Vd=(function(){function e(e,t,n){var r,i=0,a=e.length;for(e=e.slice();a--;)r=e[a]*t+i,e[a]=r%n|0,i=r/n|0;return i&&e.unshift(i),e}function t(e,t,n,r){var i,a;if(n!=r)a=n>r?1:-1;else for(i=a=0;i<n;i++)if(e[i]!=t[i]){a=e[i]>t[i]?1:-1;break}return a}function n(e,t,n,r){for(var i=0;n--;)e[n]-=i,i=+(e[n]<t[n]),e[n]=i*r+e[n]-t[n];for(;!e[0]&&e.length>1;)e.shift()}return function(r,i,a,o,s,c){var l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k=r.constructor,A=r.s==i.s?1:-1,j=r.d,M=i.d;if(!j||!j[0]||!M||!M[0])return new k(!r.s||!i.s||(j?M&&j[0]==M[0]:!M)?NaN:j&&j[0]==0||!M?A*0:A/0);for(c?(p=1,u=r.e-i.e):(c=Id,p=Ld,u=Ad(r.e/p)-Ad(i.e/p)),D=M.length,T=j.length,_=new k(A),v=_.d=[],d=0;M[d]==(j[d]||0);d++);if(M[d]>(j[d]||0)&&u--,a==null?(S=a=k.precision,o=k.rounding):S=s?a+(r.e-i.e)+1:a,S<0)v.push(1),m=!0;else{if(S=S/p+2|0,d=0,D==1){for(f=0,M=M[0],S++;(d<T||f)&&S--;d++)C=f*c+(j[d]||0),v[d]=C/M|0,f=C%M|0;m=f||d<T}else{for(f=c/(M[0]+1)|0,f>1&&(M=e(M,f,c),j=e(j,f,c),D=M.length,T=j.length),w=D,y=j.slice(0,D),b=y.length;b<D;)y[b++]=0;O=M.slice(),O.unshift(0),E=M[0],M[1]>=c/2&&++E;do f=0,l=t(M,y,D,b),l<0?(x=y[0],D!=b&&(x=x*c+(y[1]||0)),f=x/E|0,f>1?(f>=c&&(f=c-1),h=e(M,f,c),g=h.length,b=y.length,l=t(h,y,g,b),l==1&&(f--,n(h,D<g?O:M,g,c))):(f==0&&(l=f=1),h=M.slice()),g=h.length,g<b&&h.unshift(0),n(y,h,b,c),l==-1&&(b=y.length,l=t(M,y,D,b),l<1&&(f++,n(y,D<b?O:M,b,c))),b=y.length):l===0&&(f++,y=[0]),v[d++]=f,l&&y[0]?y[b++]=j[w]||0:(y=[j[w]],b=1);while((w++<T||y[0]!==void 0)&&S--);m=y[0]!==void 0}v[0]||v.shift()}if(p==1)_.e=u,Sd=m;else{for(d=1,f=v[0];f>=10;f/=10)d++;_.e=d+u*p-1,Yu(_,s?a+_.e+1:a,o,m)}return _}})(),Z[Symbol.for(`nodejs.util.inspect.custom`)]=Z.toString,Z[Symbol.toStringTag]=`Decimal`,Hd=Z.constructor=md(xd),yd=new Hd(yd),bd=new Hd(bd)})),Wd,Gd,Kd,sle=e((()=>{Ud(),X(),Wd=`BigNumber`,Gd=[`?on`,`config`],Kd=Y(Wd,Gd,e=>{var{on:t,config:n}=e,r=Hd.clone({precision:n.precision,modulo:Hd.EUCLID});return r.prototype=Object.create(r.prototype),r.prototype.type=`BigNumber`,r.prototype.isBigNumber=!0,r.prototype.toJSON=function(){return{mathjs:`BigNumber`,value:this.toString()}},r.fromJSON=function(e){return new r(e.value)},t&&t(`config`,function(e,t){e.precision!==t.precision&&r.config({precision:e.precision})}),r},{isClass:!0})}));function qd(e,t){let n=Math.abs(e),r=Math.abs(t);return e===0?Math.log(r):t===0?Math.log(n):n<3e3&&r<3e3?Math.log(e*e+t*t)*.5:(e*=.5,t*=.5,.5*Math.log(e*e+t*t)+Math.LN2)}function Q(e,t){if(!(this instanceof Q))return new Q(e,t);let n=ef(e,t);this.re=n.re,this.im=n.im}var Jd,Yd,Xd,Zd,Qd,$d,ef,cle=e((()=>{Jd=Math.cosh||function(e){return Math.abs(e)<1e-9?1-e:(Math.exp(e)+Math.exp(-e))*.5},Yd=Math.sinh||function(e){return Math.abs(e)<1e-9?e:(Math.exp(e)-Math.exp(-e))*.5},Xd=e=>{let t=Math.sin(.5*e);return-2*t*t},Zd=function(e,t){return e=Math.abs(e),t=Math.abs(t),e<t&&([e,t]=[t,e]),e<1e8?Math.sqrt(e*e+t*t):(t/=e,e*Math.sqrt(1+t*t))},Qd=function(){throw SyntaxError(`Invalid Param`)},$d={re:0,im:0},ef=function(e,t){let n=$d;if(e==null)n.re=n.im=0;else if(t!==void 0)n.re=e,n.im=t;else switch(typeof e){case`object`:if(`im`in e&&`re`in e)n.re=e.re,n.im=e.im;else if(`abs`in e&&`arg`in e){if(!isFinite(e.abs)&&isFinite(e.arg))return Q.INFINITY;n.re=e.abs*Math.cos(e.arg),n.im=e.abs*Math.sin(e.arg)}else if(`r`in e&&`phi`in e){if(!isFinite(e.r)&&isFinite(e.phi))return Q.INFINITY;n.re=e.r*Math.cos(e.phi),n.im=e.r*Math.sin(e.phi)}else e.length===2?(n.re=e[0],n.im=e[1]):Qd();break;case`string`:n.im=n.re=0;let t=e.replace(/_/g,``).match(/\d+\.?\d*e[+-]?\d+|\d+\.?\d*|\.\d+|./g),r=1,i=0;t===null&&Qd();for(let e=0;e<t.length;e++){let a=t[e];a===` `||a===`	`||a===`
2588`||(a===`+`?r++:a===`-`?i++:a===`i`||a===`I`?(r+i===0&&Qd(),t[e+1]!==` `&&!isNaN(t[e+1])?(n.im+=parseFloat((i%2?`-`:``)+t[e+1]),e++):n.im+=parseFloat((i%2?`-`:``)+`1`),r=i=0):((r+i===0||isNaN(a))&&Qd(),t[e+1]===`i`||t[e+1]===`I`?
2588(n.im+=parseFloat((i%2?`-`:``)+a),e++):n.re+=parseFloat((i%2?`-`:``)+a),r=i=0))}r+i>0&&Qd();break;case`number`:n.im=0,n.re=e;break;default:Qd()}return isNaN(n.re)||isNaN(n.im),n},Q.prototype={re:0,im:0,sign:function(){let e=Zd(this.re,this.im);return new Q(this.re/e,this.im/e)},add:function(e,t){let n=ef(e,t),r=this.isInfinite(),i=!(isFinite(n.re)&&isFinite(n.im));return r||i?r&&i?Q.NAN:Q.INFINITY:new Q(this.re+n.re,this.im+n.im)},sub:function(e,t){let n=ef(e,t),r=this.isInfinite(),i=!(isFinite(n.re)&&isFinite(n.im));return r||i?r&&i?Q.NAN:Q.INFINITY:new Q(this.re-n.re,this.im-n.im)},mul:function(e,t){let n=ef(e,t),r=this.isInfinite(),i=!(isFinite(n.re)&&isFinite(n.im)),a=this.re===0&&this.im===0,o=n.re===0&&n.im===0;return r&&o||i&&a?Q.NAN:r||i?Q.INFINITY:n.im===0&&this.im===0?new Q(this.re*n.re,0):new Q(this.re*n.re-this.im*n.im,this.re*n.im+this.im*n.re)},div:function(e,t){let n=ef(e,t),r=this.isInfinite(),i=!(isFinite(n.re)&&isFinite(n.im)),a=this.re===0&&this.im===0,o=n.re===0&&n.im===0;if(a&&o||r&&i)return Q.NAN;if(o||r)return Q.INFINITY;if(a||i)return Q.ZERO;if(n.im===0)return new Q(this.re/n.re,this.im/n.re);if(Math.abs(n.re)<Math.abs(n.im)){let e=n.re/n.im,t=n.re*e+n.im;return new Q((this.re*e+this.im)/t,(this.im*e-this.re)/t)}else{let e=n.im/n.re,t=n.im*e+n.re;return new Q((this.re+this.im*e)/t,(this.im-this.re*e)/t)}},pow:function(e,t){let n=ef(e,t),r=this.re===0&&this.im===0;if(n.re===0&&n.im===0)return Q.ONE;if(n.im===0){if(this.im===0&&this.re>0)return new Q(this.re**+n.re,0);if(this.re===0)switch((n.re%4+4)%4){case 0:return new Q(this.im**+n.re,0);case 1:return new Q(0,this.im**+n.re);case 2:return new Q(-(this.im**+n.re),0);case 3:return new Q(0,-(this.im**+n.re))}}if(r&&n.re>0)return Q.ZERO;let i=Math.atan2(this.im,this.re),a=qd(this.re,this.im),o=Math.exp(n.re*a-n.im*i),s=n.im*a+n.re*i;return new Q(o*Math.cos(s),o*Math.sin(s))},sqrt:function(){let e=this.re,t=this.im;if(t===0)return e>=0?new Q(Math.sqrt(e),0):new Q(0,Math.sqrt(-e));let n=Zd(e,t),r=Math.sqrt(.5*(n+Math.abs(e))),i=Math.abs(t)/(2*r);return e>=0?new Q(r,t<0?-i:i):new Q(i,t<0?-r:r)},exp:function(){let e=Math.exp(this.re);return this.im===0?new Q(e,0):new Q(e*Math.cos(this.im),e*Math.sin(this.im))},expm1:function(){let e=this.re,t=this.im;return new Q(Math.expm1(e)*Math.cos(t)+Xd(t),Math.exp(e)*Math.sin(t))},log:function(){let e=this.re,t=this.im;return t===0&&e>0?new Q(Math.log(e),0):new Q(qd(e,t),Math.atan2(t,e))},abs:function(){return Zd(this.re,this.im)},arg:function(){return Math.atan2(this.im,this.re)},sin:function(){let e=this.re,t=this.im;return new Q(Math.sin(e)*Jd(t),Math.cos(e)*Yd(t))},cos:function(){let e=this.re,t=this.im;return new Q(Math.cos(e)*Jd(t),-Math.sin(e)*Yd(t))},tan:function(){let e=2*this.re,t=2*this.im,n=Math.cos(e)+Jd(t);return new Q(Math.sin(e)/n,Yd(t)/n)},cot:function(){let e=2*this.re,t=2*this.im,n=Math.cos(e)-Jd(t);return new Q(-Math.sin(e)/n,Yd(t)/n)},sec:function(){let e=this.re,t=this.im,n=.5*Jd(2*t)+.5*Math.cos(2*e);return new Q(Math.cos(e)*Jd(t)/n,Math.sin(e)*Yd(t)/n)},csc:function(){let e=this.re,t=this.im,n=.5*Jd(2*t)-.5*Math.cos(2*e);return new Q(Math.sin(e)*Jd(t)/n,-Math.cos(e)*Yd(t)/n)},asin:function(){let e=this.re,t=this.im,n=new Q(t*t-e*e+1,-2*e*t).sqrt(),r=new Q(n.re-t,n.im+e).log();return new Q(r.im,-r.re)},acos:function(){let e=this.re,t=this.im,n=new Q(t*t-e*e+1,-2*e*t).sqrt(),r=new Q(n.re-t,n.im+e).log();return new Q(Math.PI/2-r.im,r.re)},atan:function(){let e=this.re,t=this.im;if(e===0){if(t===1)return new Q(0,1/0);if(t===-1)return new Q(0,-1/0)}let n=e*e+(1-t)*(1-t),r=new Q((1-t*t-e*e)/n,-2*e/n).log();return new Q(-.5*r.im,.5*r.re)},acot:function(){let e=this.re,t=this.im;if(t===0)return new Q(Math.atan2(1,e),0);let n=e*e+t*t;return n===0?new Q(e===0?0:e/0,t===0?0:-t/0).atan():new Q(e/n,-t/n).atan()},asec:function(){let e=this.re,t=this.im;if(e===0&&t===0)return new Q(0,1/0);let n=e*e+t*t;return n===0?new Q(e===0?0:e/0,t===0?0:-t/0).acos():new Q(e/n,-t/n).acos()},acsc:function(){let e=this.re,t=this.im;if(e===0&&t===0)return new Q(Math.PI/2,1/0);let n=e*e+t*t;return n===0?new Q(e===0?0:e/0,t===0?0:-t/0).asin():new Q(e/n,-t/n).asin()},sinh:function(){let e=this.re,t=this.im;return new Q(Yd(e)*Math.cos(t),Jd(e)*Math.sin(t))},cosh:function(){let e=this.re,t=this.im;return new Q(Jd(e)*Math.cos(t),Yd(e)*Math.sin(t))},tanh:function(){let e=2*this.re,t=2*this.im,n=Jd(e)+Math.cos(t);return new Q(Yd(e)/n,Math.sin(t)/n)},coth:function(){let e=2*this.re,t=2*this.im,n=Jd(e)-Math.cos(t);return new Q(Yd(e)/n,-Math.sin(t)/n)},csch:function(){let e=this.re,t=this.im,n=Math.cos(2*t)-Jd(2*e);return new Q(-2*Yd(e)*Math.cos(t)/n,2*Jd(e)*Math.sin(t)/n)},sech:function(){let e=this.re,t=this.im,n=Math.cos(2*t)+Jd(2*e);return new Q(2*Jd(e)*Math.cos(t)/n,-2*Yd(e)*Math.sin(t)/n)},asinh:function(){let e=this.re,t=this.im;if(t===0){if(e===0)return new Q(0,0);let t=Math.abs(e),n=Math.log(t+Math.sqrt(t*t+1));return new Q(e<0?-n:n,0)}let n=new Q(e*e-t*t+1,2*e*t).sqrt();return new Q(e+n.re,t+n.im).log()},acosh:function(){let e=this.re,t=this.im;if(t===0){if(e>1)return new Q(Math.log(e+Math.sqrt(e-1)*Math.sqrt(e+1)),0);if(e<-1){let t=Math.sqrt(e*e-1);return new Q(Math.log(-e+t),Math.PI)}return new Q(0,Math.acos(e))}let n=new Q(e-1,t).sqrt(),r=new Q(e+1,t).sqrt();return new Q(e+n.re*r.re-n.im*r.im,t+n.re*r.im+n.im*r.re).log()},atanh:function(){let e=this.re,t=this.im;if(t===0){if(e===0)return new Q(0,0);if(e===1)return new Q(1/0,0);if(e===-1)return new Q(-1/0,0);if(-1<e&&e<1)return new Q(.5*Math.log((1+e)/(1-e)),0);if(e>1){let t=(e+1)/(e-1);return new Q(.5*Math.log(t),-Math.PI/2)}let t=(1+e)/(1-e);return new Q(.5*Math.log(-t),Math.PI/2)}let n=1-e,r=1+e,i=n*n+t*t;if(i===0)return new Q(e===-1?0:e/0,t===0?0:t/0);let a=(r*n-t*t)/i,o=(t*n+r*t)/i;return new Q(qd(a,o)/2,Math.atan2(o,a)/2)},acoth:function(){let e=this.re,t=this.im;if(e===0&&t===0)return new Q(0,Math.PI/2);let n=e*e+t*t;return n===0?new Q(e===0?0:e/0,t===0?0:-t/0).atanh():new Q(e/n,-t/n).atanh()},acsch:function(){let e=this.re,t=this.im;if(t===0){if(e===0)return new Q(1/0,0);let t=1/e;return new Q(Math.log(t+Math.sqrt(t*t+1)),0)}let n=e*e+t*t;return n===0?new Q(e===0?0:e/0,t===0?0:-t/0).asinh():new Q(e/n,-t/n).asinh()},asech:function(){let e=this.re,t=this.im;if(this.isZero())return Q.INFINITY;let n=e*e+t*t;return n===0?new Q(e===0?0:e/0,t===0?0:-t/0).acosh():new Q(e/n,-t/n).acosh()},inverse:function(){if(this.isZero())return Q.INFINITY;if(this.isInfinite())return Q.ZERO;let e=this.re,t=this.im,n=e*e+t*t;return new Q(e/n,-t/n)},conjugate:function(){return new Q(this.re,-this.im)},neg:function(){return new Q(-this.re,-this.im)},ceil:function(e){return e=10**(e||0),new Q(Math.ceil(this.re*e)/e,Math.
2588ceil(this.im*e)/e)},floor:function(e){return e=10**(e||0),new Q(Math.floor(this.re*e)/e,Math.floor(this.im*e)/e)},round:function(e){return e=10**(e||0),new Q(Math.round(this.re*e)/e,Math.round(this.im*e)/e)},equals:function(e,t){let n=ef(e,t);return Math.abs(n.re-this.re)<=Q.EPSILON&&Math.abs(n.im-this.im)<=Q.EPSILON},clone:function(){return new Q(this.re,this.im)},toString:function(){let e=this.re,t=this.im,n=``;return this.isNaN()?`NaN`:this.isInfinite()?`Infinity`:(Math.abs(e)<Q.EPSILON&&(e=0),Math.abs(t)<Q.EPSILON&&(t=0),t===0?n+e:(e===0?t<0&&(t=-t,n+=`-`):(n+=e,n+=` `,t<0?(t=-t,n+=`-`):n+=`+`,n+=` `),t!==1&&(n+=t),n+`i`))},toVector:function(){return[this.re,this.im]},valueOf:function(){return this.im===0?this.re:null},isNaN:function(){return isNaN(this.re)||isNaN(this.im)},isZero:function(){return this.im===0&&this.re===0},isFinite:function(){return isFinite(this.re)&&isFinite(this.im)},isInfinite:function(){return!this.isFinite()}},Q.ZERO=new Q(0,0),Q.ONE=new Q(1,0),Q.I=new Q(0,1),Q.PI=new Q(Math.PI,0),Q.E=new Q(Math.E,0),Q.INFINITY=new Q(1/0,1/0),Q.NAN=new Q(NaN,NaN),Q.EPSILON=1e-15})),tf,nf,rf,lle=e((()=>{cle(),Pu(),Ql(),X(),tf=`Complex`,nf=[],rf=Y(tf,nf,()=>(Object.defineProperty(Q,"name",{value:`Complex`}),Q.prototype.constructor=Q,Q.prototype.type=`Complex`,Q.prototype.isComplex=!0,Q.prototype.toJSON=function(){return{mathjs:`Complex`,re:this.re,im:this.im}},Q.prototype.toPolar=function(){return{r:this.abs(),phi:this.arg()}},Q.prototype.format=function(e){var t=``,n=this.im,r=this.re,i=fu(this.re,e),a=fu(this.im,e),o=bl(e)?e:e?e.precision:null;if(o!==null){var s=10**-o;Math.abs(r/n)<s&&(r=0),Math.abs(n/r)<s&&(n=0)}return t=n===0?i:r===0?n===1?`i`:n===-1?`-i`:a+`i`:n<0?n===-1?i+` - i`:i+` - `+a.substring(1)+`i`:n===1?i+` + i`:i+` + `+a+`i`,t},Q.fromPolar=function(e){switch(arguments.length){case 1:var t=arguments[0];if(typeof t==`object`)return Q(t);throw TypeError(`Input has to be an object with r and phi keys.`);case 2:var n=arguments[0],r=arguments[1];if(bl(n)){if(Tl(r)&&r.hasBase(`ANGLE`)&&(r=r.toNumber(`rad`)),bl(r))return new Q({r:n,phi:r});throw TypeError(`Phi is not a number nor an angle unit.`)}else throw TypeError(`Radius r is not a number.`);default:throw SyntaxError(`Wrong number of arguments in function fromPolar`)}},Q.prototype.valueOf=Q.prototype.toString,Q.fromJSON=function(e){return new Q(e)},Q.compare=function(e,t){return e.re>t.re?1:e.re<t.re?-1:e.im>t.im?1:e.im<t.im?-1:0},Q),{isClass:!0})}));function af(e,t){try{e=BigInt(e)}catch{throw Sf()}return e*t}function of(e){return typeof e==`bigint`?e:Math.floor(e)}function sf(e,t){if(t===df)throw xf();let n=Object.create(uf.prototype);n.s=e<df?-ff:ff,e=e<df?-e:e;let r=lf(e,t);return n.n=e/r,n.d=t/r,n}function cf(e){let t=Object.create(null);if(e<=ff)return t[e]=ff,t;let n=e=>{t[e]=(t[e]||df)+ff};for(;e%pf===df;)n(pf),e/=pf;for(;e%mf===df;)n(mf),e/=mf;for(;e%hf===df;)n(hf),e/=hf;for(let t=0,r=pf+hf;r*r<=e;){for(;e%r===df;)n(r),e/=r;r+=yf[t],t=t+1&7}return e>ff&&n(e),t}function ule(e,t,n){let r=ff;for(;t>df;e=e*e%n,t>>=ff)t&ff&&(r=r*e%n);return r}function dle(e,t){for(;t%pf===df;t/=pf);for(;t%hf===df;t/=hf);if(t===ff)return df;let n=gf%t,r=1;for(;n!==ff;r++)if(n=n*gf%t,r>_f)return df;return BigInt(r)}function fle(e,t,n){let r=ff,i=ule(gf,n,t);for(let e=0;e<300;e++){if(r===i)return BigInt(e);r=r*gf%t,i=i*gf%t}return 0}function lf(e,t){if(!e)return t;if(!t)return e;for(;;){if(e%=t,!e)return t;if(t%=e,!t)return e}}function uf(e,t){if(bf(e,t),this instanceof uf)e=lf(vf.d,vf.n),this.s=vf.s,this.n=vf.n/e,this.d=vf.d/e;else return sf(vf.s*vf.n,vf.d)}var df,ff,pf,mf,hf,gf,_f,vf,yf,bf,xf,Sf,Cf,ple=e((()=>{typeof BigInt>`u`&&(BigInt=function(e){if(isNaN(e))throw Error(``);return e}),df=BigInt(0),ff=BigInt(1),pf=BigInt(2),mf=BigInt(3),hf=BigInt(5),gf=BigInt(10),BigInt(2**53-1),_f=2e3,vf={s:ff,n:df,d:ff},yf=[pf*pf,pf,pf*pf,pf,pf*pf,pf*mf,pf,pf*mf],bf=function(e,t){let n=df,r=ff,i=ff;if(e!=null)if(t!==void 0){if(typeof e==`bigint`)n=e;else if(isNaN(e))throw Sf();else if(e%1!=0)throw Cf();else n=BigInt(e);if(typeof t==`bigint`)r=t;else if(isNaN(t))throw Sf();else if(t%1!=0)throw Cf();else r=BigInt(t);i=n*r}else if(typeof e==`object`){if(`d`in e&&`n`in e)n=BigInt(e.n),r=BigInt(e.d),`s`in e&&(n*=BigInt(e.s));else if(0 in e)n=BigInt(e[0]),1 in e&&(r=BigInt(e[1]));else if(typeof e==`bigint`)n=e;else throw Sf();i=n*r}else if(typeof e==`number`){if(isNaN(e))throw Sf();if(e<0&&(i=-ff,e=-e),e%1==0)n=BigInt(e);else{let t=1,i=0,a=1,o=1,s=1,c=1e7;for(e>=1&&(t=10**Math.floor(1+Math.log10(e)),e/=t);a<=c&&s<=c;){let t=(i+o)/(a+s);if(e===t){a+s<=c?(n=i+o,r=a+s):s>a?(n=o,r=s):(n=i,r=a);break}else e>t?(i+=o,a+=s):(o+=i,s+=a),a>c?(n=o,r=s):(n=i,r=a)}n=BigInt(n)*BigInt(t),r=BigInt(r)}}else if(typeof e==`string`){let t=0,a=df,o=df,s=df,c=ff,l=ff,u=e.replace(/_/g,``).match(/\d+|./g);if(u===null)throw Sf();if(u[t]===`-`?(i=-ff,t++):u[t]===`+`&&t++,u.length===t+1?o=af(u[t++],i):u[t+1]===`.`||u[t]===`.`?(u[t]!==`.`&&(a=af(u[t++],i)),t++,(t+1===u.length||u[t+1]===`(`&&u[t+3]===`)`||u[t+1
2588]===`'`&&u[t+3]===`'`)&&(o=af(u[t],i),c=gf**BigInt(u[t].length),t++),(u[t]===`(`&&u[t+2]===`)`||u[t]===`'`&&u[t+2]===`'`)&&(s=af(u[t+1],i),l=gf**BigInt(u[t+1].length)-ff,t+=3)):u[t+1]===`/`||u[t+1]===`:`?(o=af(u[t],i),c=af(u[t+2],ff),t+=3):u[t+3]===`/`&&u[t+1]===` `&&(a=af(u[t],i),o=af(u[t+2],i),c=af(u[t+4],ff),t+=5),u.length<=t)r=c*l,i=n=s+r*a+l*o;else throw Sf()}else if(typeof e==`bigint`)n=e,i=e,r=ff;else throw Sf();if(r===df)throw xf();vf.s=i<df?-ff:ff,vf.n=n<df?-n:n,vf.d=r<df?-r:r},xf=function(){return Error(`Division by Zero`)},Sf=function(){return Error(`Invalid argument`)},Cf=function(){return Error(`Parameters must be integer`)},uf.prototype={s:ff,n:df,d:ff,abs:function(){return sf(this.n,this.d)},neg:function(){return sf(-this.s*this.n,this.d)},add:function(e,t){return bf(e,t),sf(this.s*this.n*vf.d+vf.s*this.d*vf.n,this.d*vf.d)},sub:function(e,t){return bf(e,t),sf(this.s*this.n*vf.d-vf.s*this.d*vf.n,this.d*vf.d)},mul:function(e,t){return bf(e,t),sf(this.s*vf.s*this.n*vf.n,this.d*vf.d)},div:function(e,t){return bf(e,t),sf(this.s*vf.s*this.n*vf.d,this.d*vf.n)},clone:function(){return sf(this.s*this.n,this.d)},mod:function(e,t){if(e===void 0)return sf(this.s*this.n%this.d,ff);if(bf(e,t),df===vf.n*this.d)throw xf();return sf(this.s*(vf.d*this.n)%(vf.n*this.d),vf.d*this.d)},gcd:function(e,t){return bf(e,t),sf(lf(vf.n,this.n)*lf(vf.d,this.d),vf.d*this.d)},lcm:function(e,t){return bf(e,t),vf.n===df&&this.n===df?sf(df,ff):sf(vf.n*this.n,lf(vf.n,this.n)*lf(vf.d,this.d))},inverse:function(){return sf(this.s*this.d,this.n)},pow:function(e,t){if(bf(e,t),vf.d===ff)return vf.s<df?sf((this.s*this.d)**vf.n,this.n**vf.n):sf((this.s*this.n)**vf.n,this.d**vf.n);if(this.s<df)return null;let n=cf(this.n),r=cf(this.d),i=ff,a=ff;for(let e in n)if(e!==`1`){if(e===`0`){i=df;break}if(n[e]*=vf.n,n[e]%vf.d===df)n[e]/=vf.d;else return null;i*=BigInt(e)**n[e]}for(let e in r)if(e!==`1`){if(r[e]*=vf.n,r[e]%vf.d===df)r[e]/=vf.d;else return null;a*=BigInt(e)**r[e]}return vf.s<df?sf(a,i):sf(i,a)},log:function(e,t){if(bf(e,t),this.s<=df||vf.s<=df)return null;let n=Object.create(null),r=cf(vf.n),i=cf(vf.d),a=cf(this.n),o=cf(this.d);for(let e in i)r[e]=(r[e]||df)-i[e];for(let e in o)a[e]=(a[e]||df)-o[e];for(let e in r)e!==`1`&&(n[e]=!0);for(let e in a)e!==`1`&&(n[e]=!0);let s=null,c=null;for(let e in n){let t=r[e]||df,n=a[e]||df;if(t===df){if(n!==df)return null;continue}let i=n,o=t,l=lf(i,o);if(i/=l,o/=l,s===null&&c===null)s=i,c=o;else if(i*c!==s*o)return null}return s!==null&&c!==null?sf(s,c):null},equals:function(e,t){return bf(e,t),this.s*this.n*vf.d===vf.s*vf.n*this.d},lt:function(e,t){return bf(e,t),this.s*this.n*vf.d<vf.s*vf.n*this.d},lte:function(e,t){return bf(e,t),this.s*this.n*vf.d<=vf.s*vf.n*this.d},gt:function(e,t){return bf(e,t),this.s*this.n*vf.d>vf.s*vf.n*this.d},gte:function(e,t){return bf(e,t),this.s*this.n*vf.d>=vf.s*vf.n*this.d},compare:function(e,t){bf(e,t);let n=this.s*this.n*vf.d-vf.s*vf.n*this.d;return(df<n)-(n<df)},ceil:function(e){return e=gf**BigInt(e||0),sf(of(this.s*e*this.n/this.d)+(e*this.n%this.d>df&&this.s>=df?ff:df),e)},floor:function(e){return e=gf**BigInt(e||0),sf(of(this.s*e*this.n/this.d)-(e*this.n%this.d>df&&this.s<df?ff:df),e)},round:function(e){return e=gf**BigInt(e||0),sf(of(this.s*e*this.n/this.d)+this.s*((this.s>=df?ff:df)+pf*(e*this.n%this.d)>this.d?ff:df),e)},roundTo:function(e,t){bf(e,t);let n=this.n*vf.d,r=this.d*vf.n,i=n%r,a=of(n/r);return i+i>=r&&a++,sf(this.s*a*vf.n,vf.d)},divisible:function(e,t){return bf(e,t),vf.n===df?!1:this.n*vf.d%(vf.n*this.d)===df},valueOf:function(){return Number(this.s*this.n)/Number(this.d)},toString:function(e=15){let t=this.n,n=this.d,r=dle(t,n),i=fle(t,n,r),a=this.s<df?`-`:``;if(a+=of(t/n),t%=n,t*=gf,t&&(a+=`.`),r){for(let e=i;e--;)a+=of(t/n),t%=n,t*=gf;a+=`(`;for(let e=r;e--;)a+=of(t/n),t%=n,t*=gf;a+=`)`}else for(let r=e;t&&r--;)a+=of(t/n),t%=n,t*=gf;return a},toFraction:function(e=!1){let t=this.n,n=this.d,r=this.s<df?`-`:``;if(n===ff)r+=t;else{let i=of(t/n);e&&i>df&&(r+=i,r+=` `,t%=n),r+=t,r+=`/`,r+=n}return r},toLatex:function(e=!1){let t=this.n,n=this.d,r=this.s<df?`-`:``;if(n===ff)r+=t;else{let i=of(t/n);e&&i>df&&(r+=i,t%=n),r+=`\\frac{`,r+=t,r+=`}{`,r+=n,r+=`}`}return r},toContinued:function(){let e=this.n,t=this.d,n=[];for(;t;){n.push(of(e/t));let r=e%t;e=t,t=r}return n},simplify:function(e=.001){let t=BigInt(Math.ceil(1/e)),n=this.abs(),r=n.toContinued();for(let e=1;e<r.length;e++){let i=sf(r[e-1],ff);for(let t=e-2;t>=0;t--)i=i.inverse().add(r[t]);let a=i.sub(n);if(a.n*t<a.d)return i.mul(this.s)}return this}}})),wf,Tf,Ef,mle=e((()=>{ple(),X(),wf=`Fraction`,Tf=[],Ef=Y(wf,Tf,()=>(Object.defineProperty(uf,"name",{value:`Fraction`}),uf.prototype.constructor=uf,uf.prototype.type=`Fraction`,uf.prototype.isFraction=!0,uf.prototype.toJSON=function(){return{mathjs:`Fraction`,n:String(this.s*this.n),d:String(this.d)}},uf.fromJSON=function(e){return new uf(e)},uf),{isClass:!0})})),Df,Of,kf,hle=e((()=>{Ql(),Pu(),X(),Df=`Range`,Of=[],kf=Y(Df,Of,()=>{function e(t,n,r){if(!(this instanceof e))throw SyntaxError(`Constructor must be called with the new operator`);var i=t!=null,a=n!=null,o=r!=null;if(i){if(xl(t))t=t.toNumber();else if(typeof t!=`number`&&!Sl(t))throw TypeError(`Parameter start must be a number or bigint`)}if(a){if(xl(n))n=n.toNumber();else if(typeof n!=`number`&&!Sl(n))throw TypeError(`Parameter end must be a number or bigint`)}if(o){if(xl(r))r=r.toNumber();else if(typeof r!=`number`&&!Sl(r))throw TypeError(`Parameter step must be a number or bigint`)}if(this.start=i?parseFloat(t):0,this.end=a?parseFloat(n):0,this.step=o?parseFloat(r):1,o&&yu(this.step,0))throw Error(`Step must not be zero`)}return e.prototype.type=`Range`,e.prototype.isRange=!0,e.parse=function(t){if(typeof t!=`string`)return null;var n=t.split(`:`).map(function(e){return parseFloat(e)});if(n.some(function(e){return isNaN(e)}))return null;switch(n.length){case 2:return new e(n[0],n[1]);case 3:return new e(n[0],n[2],n[1]);default:return null}},e.prototype.clone=function(){return new e(this.start,this.end,this.step)},e.prototype.size=function(){var e=0,t=this.start,n=this.step,r=this.end-t;return Su(n)===Su(r)?e=Math.ceil(r/n):r===0&&(e=0),isNaN(e)&&(e=0),[e]},e.prototype.min=function(){var e=this.size()[0];if(e>0)return this.step>0?this.start:this.start+(e-1)*this.step},e.prototype.max=function(){var e=this.size()[0];if(e>0)return this.step>0?this.start+(e-1)*this.step:this.start},e.prototype.forEach=function(e){var t=this.start,n=this.step,r=this.end,i=0;if(n>0)for(;t<r;)e(t,[i],this),t+=n,i++;else if(n<0)for(;t>r;)e(t,[i],this),t+=n,i++},e.prototype.map=function(e){var t=[];return this.forEach(function(n,r,i){t[r[0]]=e(n,r,i)}),t},e.prototype.toArray=function(){var e=[];return this.forEach(function(t,n){e[n[0]]=t}),e},e.prototype.valueOf=function(){return this.toArray()},e.prototype.format=function(e){var t=fu(this.start,e);return this.step!==1&&(t+=`:`+fu(this.step,e)),t+=`:`+fu(this.end,e),t},e.prototype.toString=function(){return this.format()},e.prototype.toJSON=function(){return{mathjs:`Range`,start:this.start,end:this.end,step:this.step}},e.fromJSON=function(t){return new e(t.start,t.end,t.step)},e},{isClass:!0})})),Af,jf,Mf,gle=e((()=>{X(),Af=`Matrix`,jf=[],Mf=Y(Af,jf,()=>{function e(){if(!(this instanceof e))throw SyntaxError(`Constructor must be called with the new operator`)}return e.prototype.type=`Matrix`,e.prototype.isMatrix=!0,e.prototype.storage=function(){throw Error(`Cannot invoke storage on a Matrix interface`)},e.prototype.datatype=function(){throw Error(`Cannot invoke datatype on a Matrix interface`)},e.prototype.create=function(e,t){throw Error(`Cannot invoke create on a Matrix interface`)},e.prototype.subset=function(e,t,n){throw Error(`Cannot invoke subset on a Matrix interface`)},e.prototype.get=function(e){throw Error(`Cannot invoke get on a Matrix interface`)},e.prototype.set=function(e,t,n){throw Error(`Cannot invoke set on a Matrix interface`)},e.prototype.resize=function(e,t){throw Error(`Cannot invoke resize on a Matrix interface`)},e.prototype.reshape=function(e,t){throw Error(`Cannot invoke reshape on a Matrix interface`)},e.prototype.clone=function(){throw Error(`Cannot invoke clone on a Matrix interface`)},e.prototype.size=function(){throw Error(`Cannot invoke size on a Matrix interface`)},e.prototype.map=function(e,t){throw Error(`Cannot invoke map on a Matrix interface`)},e.prototype.forEach=function(e){throw Error(`Cannot invoke forEach on a Matrix interface`)},e.prototype[Symbol.iterator]=function(){throw Error(`Cannot iterate a Matrix interface`)},e.prototype.toArray=function(){throw Error(`Cannot invoke toArray on a Matrix interface`)},e.prototype.valueOf=function(){throw Error(`Cannot invoke valueOf on a Matrix interface`)},e.prototype.format=function(e){throw Error(`Cannot invoke format on a Matrix interface`)},e.prototype.toString=function(){throw Error(`Cannot invoke toString on a Matrix interface`)},e},{isClass:!0})}));function Nf(e,t,n){var r=e.constructor,i=new r(2),a=``;if(n){if(n<1)throw Error(`size must be in greater than 0`);if(!lu(n))throw Error(`size must be an integer`);if(e.greaterThan(i.pow(n-1).sub(1))||e.lessThan(i.pow(n-1).mul(-1)))throw Error(`Value must be in range [-2^${n-1}, 2^${n-1}-1]`);
2588if(!e.isInteger())throw Error(`Value must be an integer`);e.lessThan(0)&&(e=e.add(i.pow(n))),a=`i${n}`}switch(t){case 2:return`${e.toBinary()}${a}`;case 8:return`${e.toOctal()}${a}`;case 16:return`${e.toHexadecimal()}${a}`;default:throw Error(`Base ${t} not supported `)}}function _le(e,t){if(typeof t==`function`)return t(e);if(!e.isFinite())return e.isNaN()?`NaN`:e.gt(0)?`Infinity`:`-Infinity`;var{notation:n,precision:r,wordSize:i}=pu(t);switch(n){case`fixed`:return yle(e,r);case`exponential`:return Pf(e,r);case`engineering`:return vle(e,r);case`bin`:return Nf(e,2,i);case`oct`:return Nf(e,8,i);case`hex`:return Nf(e,16,i);case`auto`:var a=Ff(t?.lowerExp,-3),o=Ff(t?.upperExp,5);if(e.isZero())return`0`;var s,c=e.toSignificantDigits(r),l=c.e;return s=l>=a&&l<o?c.toFixed():Pf(e,r),s.replace(/((\.\d*?)(0+))($|e)/,function(){var e=arguments[2],t=arguments[4];return e===`.`?t:e+t});default:throw Error(`Unknown notation "`+n+`". Choose "auto", "exponential", "fixed", "bin", "oct", or "hex.`)}}function vle(e,t){var n=e.e,r=n%3==0?n:n<0?n-3-n%3:n-n%3,i=e.mul(10**-r).toPrecision(t);if(i.includes(`e`)){var a=e.constructor;i=new a(i).toFixed()}return i+`e`+(n>=0?`+`:``)+r.toString()}function Pf(e,t){return t===void 0?e.toExponential():e.toExponential(t-1)}function yle(e,t){return e.toFixed(t)}function Ff(e,t){return bl(e)?e:xl(e)?e.toNumber():t}var ble=e((()=>{Ql(),Pu()}));function xle(e,t){var n=e.length-t.length,r=e.length;return e.substring(n,r)===t}function If(e,t){var n=Sle(e,t);return t&&typeof t==`object`&&`truncate`in t&&n.length>t.truncate?n.substring(0,t.truncate-3)+`...`:n}function Sle(e,t){return typeof e==`number`?fu(e,t):xl(e)?_le(e,t):Cle(e)?!t||t.fraction!==`decimal`?`${e.s*e.n}/${e.d}`:e.toString():Array.isArray(e)?zf(e,t):El(e)?Lf(e):typeof e==`function`?e.syntax?String(e.syntax):`function`:e&&typeof e==`object`?typeof e.format==`function`?e.format(t):e&&e.toString(t)!=={}.toString()?e.toString(t):`{`+Object.keys(e).map(n=>Lf(n)+`: `+If(e[n],t)).join(`, `)+`}`:String(e)}function Lf(e){for(var t=String(e),n=``,r=0;r<t.length;){var i=t.charAt(r);n+=i in Vf?Vf[i]:i,r++}return`"`+n+`"`}function Rf(e){var t=String(e);return t=t.replace(/&/g,`&amp;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`),t}function zf(e,t){if(Array.isArray(e)){for(var n=`[`,r=e.length,i=0;i<r;i++)i!==0&&(n+=`, `),n+=zf(e[i],t);return n+=`]`,n}else return If(e,t)}function Cle(e){return e&&typeof e==`object`&&typeof e.s==`bigint`&&typeof e.n==`bigint`&&typeof e.d==`bigint`||!1}function Bf(e,t){if(!El(e))throw TypeError(`Unexpected type of argument in function compareText (expected: string or Array or Matrix, actual: `+Xl(e)+`, index: 0)`);if(!El(t))throw TypeError(`Unexpected type of argument in function compareText (expected: string or Array or Matrix, actual: `+Xl(t)+`, index: 1)`);return e===t?0:e>t?1:-1}var Vf,Hf=e((()=>{Ql(),Pu(),ble(),Vf={'"':`\\"`,"\\":`\\\\`,"\b":`\\b`,"\f":`\\f`,"\n":`\\n`,"\r":`\\r`,"	":`\\t`}}));function Uf(e,t,n){if(!(this instanceof Uf))throw SyntaxError(`Constructor must be called with the new operator`);this.actual=e,this.expected=t,this.relation=n,this.message=`Dimension mismatch (`+(Array.isArray(e)?`[`+e.join(`, `)+`]`:e)+` `+(this.relation||`!=`)+` `+(Array.isArray(t)?`[`+t.join(`, `)+`]`:t)+`)`,this.stack=Error().stack}var Wf=e((()=>{Uf.prototype=RangeError(),Uf.prototype.constructor=RangeError,Uf.prototype.name=`DimensionError`,Uf.prototype.isDimensionError=!0}));function Gf(e,t,n){if(!(this instanceof Gf))throw SyntaxError(`Constructor must be called with the new operator`);this.index=e,arguments.length<3?(this.min=0,this.max=t):(this.min=t,this.max=n),this.min!==void 0&&this.index<this.min?this.message=`Index out of range (`+this.index+` < `+this.min+`)`:this.max!==void 0&&this.index>=this.max?this.message=`Index out of range (`+this.index+` > `+(this.max-1)+`)`:this.message=`Index out of range (`+this.index+`)`,this.stack=Error().stack}var Kf=e((()=>{Gf.prototype=RangeError(),Gf.prototype.constructor=RangeError,Gf.prototype.name=`IndexError`,Gf.prototype.isIndexError=!0}));function qf(e){for(var t=[];Array.isArray(e);)t.push(e.length),e=e[0];return t}function Jf(e,t,n){var r,i=e.length;if(i!==t[n])throw new Uf(i,t[n]);if(n<t.length-1){var a=n+1;for(r=0;r<i;r++){var o=e[r];if(!Array.isArray(o))throw new Uf(t.length-1,t.length,`<`);Jf(e[r],t,a)}}else for(r=0;r<i;r++)if(Array.isArray(e[r]))throw new Uf(t.length+1,t.length,`>`)}function Yf(e,t){if(t.length===0){if(Array.isArray(e))throw new Uf(e.length,0)}else Jf(e,t,0)}function Xf(e,t){var n=e.isMatrix?e._size:qf(e);t._sourceSize.forEach((e,t)=>{if(e!==null&&e!==n[t])throw new Uf(e,n[t])})}function Zf(e,t){if(e!==void 0){if(!bl(e)||!lu(e))throw TypeError(`Index must be an integer (value: `+e+`)`);if(e<0||typeof t==`number`&&e>=t)throw new Gf(e,t)}}function Qf(e){for(var t=0;t<e._dimensions.length;++t){var n=e._dimensions[t];
2588if(n._data&&Zl(n._data)){if(n._size[0]===0)return!0}else if(n.isRange){if(n.start===n.end)return!0}else if(El(n)&&n.length===0)return!0}return!1}function $f(e,t,n){if(!Array.isArray(t))throw TypeError(`Array expected`);if(t.length===0)throw Error(`Resizing to scalar is not supported`);return t.forEach(function(e){if(!bl(e)||!lu(e)||e<0)throw TypeError(`Invalid size, must contain positive integers (size: `+If(t)+`)`)}),(bl(e)||xl(e))&&(e=[e]),ep(e,t,0,n===void 0?0:n),e}function ep(e,t,n,r){var i,a,o=e.length,s=t[n],c=Math.min(o,s);if(e.length=s,n<t.length-1){var l=n+1;for(i=0;i<c;i++)a=e[i],Array.isArray(a)||(a=[a],e[i]=a),ep(a,t,l,r);for(i=c;i<s;i++)a=[],e[i]=a,ep(a,t,l,r)}else{for(i=0;i<c;i++)for(;Array.isArray(e[i]);)e[i]=e[i][0];for(i=c;i<s;i++)e[i]=r}}function tp(e,t){var n=cp(e,!0),r=n.length;if(!Array.isArray(e)||!Array.isArray(t))throw TypeError(`Array expected`);if(t.length===0)throw new Uf(0,r,`!=`);t=np(t,r);var i=rp(t);if(r!==i)throw new Uf(i,r,`!=`);try{return wle(n,t)}catch(e){throw e instanceof Uf?new Uf(i,r,`!=`):e}}function np(e,t){var n=rp(e),r=e.slice(),i=-1,a=e.indexOf(i);if(e.indexOf(i,a+1)>=0)throw Error(`More than one wildcard in sizes`);var o=a>=0,s=t%n===0;if(o)if(s)r[a]=-t/n;else throw Error(`Could not replace wildcard, since `+t+` is no multiple of `+-n);return r}function rp(e){return e.reduce((e,t)=>e*t,1)}function wle(e,t){for(var n=e,r,i=t.length-1;i>0;i--){var a=t[i];r=[];for(var o=n.length/a,s=0;s<o;s++)r.push(n.slice(s*a,(s+1)*a));n=r}return n}function ip(e,t){for(var n=t||qf(e);Array.isArray(e)&&e.length===1;)e=e[0],n.shift();for(var r=n.length;n[r-1]===1;)r--;return r<n.length&&(e=ap(e,r,0),n.length=r),e}function ap(e,t,n){var r,i;if(n<t){var a=n+1;for(r=0,i=e.length;r<i;r++)e[r]=ap(e[r],t,a)}else for(;Array.isArray(e);)e=e[0];return e}function op(e,t,n,r){var i=r||qf(e);if(n)for(var a=0;a<n;a++)e=[e],i.unshift(1);for(e=sp(e,t,0);i.length<t;)i.push(1);return e}
2588function sp(e,t,n){var r,i;if(Array.isArray(e)){var a=n+1;for(r=0,i=e.length;r<i;r++)e[r]=sp(e[r],t,a)}else for(var o=n;o<t;o++)e=[e];return e}function cp(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(!Array.isArray(e))return e;if(typeof t!=`boolean`)throw TypeError(`Boolean expected for second argument of flatten`);var n=[];return t?i(e):r(e),n;function r(e){for(var t=0;t<e.length;t++){var i=e[t];Array.isArray(i)?r(i):n.push(i)}}function i(e){if(Array.isArray(e[0]))for(var t=0;t<e.length;t++)i(e[t]);else for(var r=0;r<e.length;r++)n.push(e[r])}}function lp(e,t){return Array.prototype.map.call(e,t)}function up(e,t){Array.prototype.forEach.call(e,t)}function dp(e,t){if(qf(e).length!==1)throw Error(`Only one dimensional matrices supported`);return Array.prototype.filter.call(e,t)}function fp(e,t){if(qf(e).length!==1)throw Error(`Only one dimensional matrices supported`);return Array.prototype.filter.call(e,e=>t.test(e))}function pp(e,t){return Array.prototype.join.call(e,t)}function mp(e){if(!Array.isArray(e))throw TypeError(`Array input expected`);if(e.length===0)return e;var t=[],n=0;t[0]={value:e[0],identifier:0};for(var r=1;r<e.length;r++)e[r]===e[r-1]?n++:n=0,t.push({value:e[r],identifier:n});return t}function hp(e){if(!Array.isArray(e))throw TypeError(`Array input expected`);if(e.length===0)return e;for(var t=[],n=0;n<e.length;n++)t.push(e[n].value);return t}function gp(e,t){for(var n,r=0,i=0;i<e.length;i++){var a=e[i],o=Array.isArray(a);if(i===0&&o&&(r=a.length),o&&a.length!==r)return;var s=o?gp(a,t):t(a);if(n===void 0)n=s;else if(n!==s)return`mixed`}return n}function _p(e,t,n,r){if(r<n){if(e.length!==t.length)throw new Uf(e.length,t.length);for(var i=[],a=0;a<e.length;a++)i[a]=_p(e[a],t[a],n,r+1);return i}else return e.concat(t)}function vp(){var e=Array.prototype.slice.call(arguments,0,-1),t=Array.prototype.slice.call(arguments,-1);if(e.length===1)return e[0];if(e.length>1)return e.slice(1).reduce(function(e,n){return _p(e,n,t,0)},e[0]);throw Error(`Wrong number of arguments in function concat`)}function yp(){for(var e=[...arguments],t=e.map(e=>e.length),n=Math.max(...t),r=Array(n).fill(null),i=0;i<e.length;i++)for(var a=e[i],o=t[i],s=0;s<o;s++){var c=n-o+s;a[s]>r[c]&&(r[c]=a[s])}for(var l=0;l<e.length;l++)bp(e[l],r);return r}function bp(e,t){for(var n=t.length,r=e.length,i=0;i<r;i++){var a=n-r+i;if(e[i]<t[a]&&e[i]>1||e[i]>t[a])throw Error(`shape mismatch: mismatch is found in arg with shape (${e}) not possible to broadcast dimension ${r} with size ${e[i]} to size ${t[a]}`)}}function xp(e,t){var n=qf(e);if(eu(n,t))return e;bp(n,t);var r=yp(n,t),i=r.length,a=[...Array(i-n.length).fill(1),...n],o=Ele(e);n.length<i&&(o=tp(o,a),n=qf(o));for(var s=0;s<i;s++)n[s]<r[s]&&(o=Tle(o,r[s],s),n=qf(o));return o}function Tle(e,t,n){return vp(...Array(t).fill(e),n)}function Sp(e,t){if(!Array.isArray(e))throw Error(`Array expected`);if(!Array.isArray(t))throw Error(`Array expected for index`);var n=qf(e);if(t.length!==n.length)throw new Uf(t.length,n.length);for(var r=0;r<t.length;r++)Zf(t[r],n[r]);return t.reduce((e,t)=>e[t],e)}function Cp(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;if(e.length===0)return[];if(n)return a(e);var r=[];return i(e,0);function i(n,a){if(Array.isArray(n)){for(var o=n.length,s=Array(o),c=0;c<o;c++)r[a]=c,s[c]=i(n[c],a+1);return s}else return t(n,r.slice(0,a),e)}function a(e){if(Array.isArray(e)){for(var n=e.length,r=Array(n),i=0;i<n;i++)r[i]=a(e[i]);return r}else return t(e)}}function wp(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;if(e.length===0)return;if(n){a(e);return}var r=[];i(e,0);function i(n,a){if(Array.isArray(n))for(var o=n.length,s=0;s<o;s++)r[a]=s,i(n[s],a+1);else t(n,r.slice(0,a),e)}function a(e){if(Array.isArray(e))for(var n=e.length,r=0;r<n;r++)a(e[r]);else t(e)}}function Ele(e){return zn([],e)}var Tp=e((()=>{Bn(),Pu(),Ql(),Hf(),Wf(),Kf(),ru()}));function Ep(e,t,n,r){if(Op.default.isTypedFunction(e)){var i;if(r)i=1;else{var a=t.isMatrix?t.size():qf(t);if(!a.length||a[a.length-1]===0)return{isUnary:r,fn:e};var o=a.map(()=>0);i=kle(e,t.isMatrix?t.get(o):Sp(t,o),o,t)}var s;if(t.isMatrix&&t.dataType!==`mixed`&&t.dataType!==void 0){var c=Dle(e,i);s=c===void 0?e:c}else s=e;return i>=1&&i<=3?{isUnary:i===1,fn:function(){return Dp(s,[...arguments].slice(0,i),n,e.name)}}:{isUnary:!1,fn:function(){return Dp(s,[...arguments],n,e.name)}}}return r===void 0?{isUnary:Ole(e),fn:e}:{isUnary:r,fn:e}}function Dle(e,t){var n=[];
2588if(Object.entries(e.signatures).forEach(e=>{var[r,i]=e;r.split(`,`).length===t&&n.push(i)}),n.length===1)return n[0]}function Ole(e){if(e.length!==1)return!1;var t=e.toString();if(/arguments/.test(t))return!1;var n=t.match(/\(.*?\)/);return!/\.\.\./.test(n)}function kle(e,t,n,r){for(var i=[t,n,r],a=3;a>0;a--){var o=i.slice(0,a);if(Op.default.resolve(e,o)!==null)return a}}function Dp(e,t,n,r){try{return e(...t)}catch(e){Ale(e,t,n,r)}}function Ale(e,t,n,r){if(e instanceof TypeError&&e.data?.category===`wrongType`){var i=[];throw i.push(`value: ${Xl(t[0])}`),t.length>=2&&i.push(`index: ${Xl(t[1])}`),t.length>=3&&i.push(`array: ${Xl(t[2])}`),TypeError(`Function ${n} cannot apply callback arguments ${r}(${i.join(`, `)}) at index ${JSON.stringify(t[1])}`)}else throw TypeError(`Function ${n} cannot apply callback arguments to function ${r}: ${e.message}`)}var Op,kp=e((()=>{Op=t(su(),1),Tp(),Ql()})),Ap,jp,Mp,jle=e((()=>{Ql(),Tp(),Hf(),Pu(),ru(),Wf(),X(),kp(),Ap=`DenseMatrix`,jp=[`Matrix`,`config`],Mp=Y(Ap,jp,e=>{var{Matrix:t,config:n}=e;function r(e,t){if(!(this instanceof r))throw SyntaxError(`Constructor must be called with the new operator`);if(t&&!El(t))throw Error(`Invalid datatype: `+t);if(Dl(e))e.type===`DenseMatrix`?(this._data=$l(e._data),this._size=$l(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&Zl(e.data)&&Zl(e.size))this._data=e.data,this._size=e.size,Yf(this._data,this._size),this._datatype=t||e.datatype;else if(Zl(e))this._data=u(e),this._size=qf(this._data),Yf(this._data,this._size),this._datatype=t;else if(e)throw TypeError(`Unsupported type of data (`+Xl(e)+`)`);else this._data=[],this._size=[0],this._datatype=t}r.prototype=new t,r.prototype.createDenseMatrix=function(e,t){return new r(e,t)},Object.defineProperty(r,"name",{value:`DenseMatrix`}),r.prototype.constructor=r,r.prototype.type=`DenseMatrix`,r.prototype.isDenseMatrix=!0,r.prototype.getDataType=function(){return gp(this._data,Xl)},r.prototype.storage=function(){return`dense`},r.prototype.datatype=function(){return this._datatype},r.prototype.create=function(e,t){return new r(e,t)},r.prototype.subset=function(e,t,n){switch(arguments.length){case 1:return i(this,e);case 2:case 3:return o(this,e,t,n);default:throw SyntaxError(`Wrong number of arguments`)}},r.prototype.get=function(e){return Sp(this._data,e)},r.prototype.set=function(e,t,n){if(!Zl(e))throw TypeError(`Array expected`);if(e.length<this._size.length)throw new Uf(e.length,this._size.length,`<`);var r,i,a,o=e.map(function(e){return e+1});l(this,o,n);var s=this._data;for(r=0,i=e.length-1;r<i;r++)a=e[r],Zf(a,s.length),s=s[a];return a=e[e.length-1],Zf(a,s.length),s[a]=t,this};function i(e,t){if(!Ml(t))throw TypeError(`Invalid index`);if(n.legacySubset?t.size().every(e=>e===1):t.isScalar())return e.get(t.min());var i=t.size();if(i.length!==e._size.length)throw new Uf(i.length,e._size.length);for(var o=t.min(),s=t.max(),c=0,l=e._size.length;c<l;c++)Zf(o[c],e._size[c]),Zf(s[c],e._size[c]);var u=new r,d=a(e._data,t);return u._size=d.size,u._datatype=e._datatype,u._data=d.data,n.legacySubset?u.reshape(t.size()):u}function a(e,t){var n=t.size().length-1,r=Array(n);return{data:i(e),size:r.filter(e=>e!==null)};function i(e){var a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,o=t.dimension(a);function s(e,t){return bl(e)?t(e):e.map(t).valueOf()}return bl(o)?r[a]=null:r[a]=o.size()[0],a<n?s(o,t=>(Zf(t,e.length),i(e[t],a+1))):s(o,t=>(Zf(t,e.length),e[t]))}}function o(e,t,n,r){if(!t||t.isIndex!==!0)throw TypeError(`Invalid index`);var i=t.size(),a=t.isScalar(),o;if(Dl(n)?(o=n.size(),n=n.valueOf()):o=qf(n),a){if(o.length!==0)throw TypeError(`Scalar expected`);e.set(t.min(),n,r)}else{if(!eu(o,i)){if(o.length===0)n=xp([n],i);else try{n=xp(n,i)}catch{}o=qf(n)}if(i.length<e._size.length)throw new Uf(i.length,e._size.length,`<`);if(o.length<i.length){for(var c=0,u=0;i[c]===1&&o[c]===1;)c++;for(;i[c]===1;)u++,c++;n=op(n,i.length,u,o)}if(!eu(i,o))throw new Uf(i,o,`>`);l(e,t.max().map(function(e){return e+1}),r),s(e._data,t,n)}return e}function s(e,t,n){var r=t.size().length-1;i(e,n);function i(e,n){var a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,o=t.dimension(a),s=(t,r)=>{Zf(t,e.length),i(e[t],n[r[0]],a+1)},c=(t,r)=>{Zf(t,e.length),e[t]=n[r[0]]};
2588a<r?bl(o)?s(o,[0]):o.forEach(s):bl(o)?c(o,[0]):o.forEach(c)}}r.prototype.resize=function(e,t,n){if(!Ol(e))throw TypeError(`Array or Matrix expected`);var r=e.valueOf().map(e=>Array.isArray(e)&&e.length===1?e[0]:e);return c(n?this.clone():this,r,t)};function c(e,t,n){if(t.length===0){for(var r=e._data;Zl(r);)r=r[0];return r}return e._size=t.slice(0),e._data=$f(e._data,e._size,n),e}r.prototype.reshape=function(e,t){var n=t?this.clone():this;return n._data=tp(n._data,e),n._size=np(e,n._size.reduce((e,t)=>e*t)),n};function l(e,t,n){for(var r=e._size.slice(0),i=!1;r.length<t.length;)r.push(0),i=!0;for(var a=0,o=t.length;a<o;a++)t[a]>r[a]&&(r[a]=t[a],i=!0);i&&c(e,r,n)}r.prototype.clone=function(){return new r({data:$l(this._data),size:$l(this._size),datatype:this._datatype})},r.prototype.size=function(){return this._size.slice(0)},r.prototype.map=function(e){arguments.length>1&&arguments[1]!==void 0&&arguments[1];var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=this,r=n._size.length-1;if(r<0)return n.clone();var i=Ep(e,n,`map`,t),a=i.fn,o=n.create(void 0,n._datatype);if(o._size=n._size,t||i.isUnary)return o._data=f(n._data),o;
2588if(r===0){for(var s=n.valueOf(),c=Array(s.length),l=0;l<s.length;l++)c[l]=a(s[l],[l],n);return o._data=c,o}var u=[];return o._data=d(n._data),o;function d(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=Array(e.length);if(t<r)for(var o=0;o<e.length;o++)u[t]=o,i[o]=d(e[o],t+1);else for(var s=0;s<e.length;s++)u[t]=s,i[s]=a(e[s],u.slice(),n);return i}function f(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=Array(e.length);if(t<r)for(var i=0;i<e.length;i++)n[i]=f(e[i],t+1);else for(var o=0;o<e.length;o++)n[o]=a(e[o]);return n}},r.prototype.forEach=function(e){arguments.length>1&&arguments[1]!==void 0&&arguments[1];var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=this,r=n._size.length-1;if(r<0)return;var i=Ep(e,n,`map`,t),a=i.fn;if(t||i.isUnary){l(n._data);return}if(r===0){for(var o=0;o<n._data.length;o++)a(n._data[o],[o],n);return}var s=[];c(n._data);function c(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;if(t<r)for(var i=0;i<e.length;i++)s[t]=i,c(e[i],t+1);else for(var o=0;o<e.length;o++)s[t]=o,a(e[o],s.slice(),n)}function l(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;if(t<r)for(var n=0;n<e.length;n++)l(e[n],t+1);else for(var i=0;i<e.length;i++)a(e[i])}},r.prototype[Symbol.iterator]=function*(){var e=this._size.length-1;if(!(e<0)){if(e===0){for(var t=0;t<this._data.length;t++)yield{value:this._data[t],index:[t]};return}for(var n=Array(e+1).fill(0),r=this._size.reduce((e,t)=>e*t,1),i=0;i<r;i++){for(var a=this._data,o=0;o<e;o++)a=a[n[o]];yield{value:a[n[e]],index:n.slice()};for(var s=e;s>=0&&(n[s]++,!(n[s]<this._size[s]));s--)n[s]=0}}},r.prototype.rows=function(){var e=[];if(this.size().length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var t of this._data)e.push(new r([t],this._datatype));return e},r.prototype.columns=function(){var e=this,t=[],n=this.size();if(n.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var i=this._data,a=function(n){var a=i.map(e=>[e[n]]);t.push(new r(a,e._datatype))},o=0;o<n[1];o++)a(o);return t}
2588,r.prototype.toArray=function(){return $l(this._data)},r.prototype.valueOf=function(){return this._data},r.prototype.format=function(e){return If(this._data,e)},r.prototype.toString=function(){return If(this._data)},r.prototype.toJSON=function(){return{mathjs:`DenseMatrix`,data:this._data,size:this._size,datatype:this._datatype}},r.prototype.diagonal=function(e){if(e){if(xl(e)&&(e=e.toNumber()),!bl(e)||!lu(e))throw TypeError(`The parameter k must be an integer number`)}else e=0;for(var t=e>0?e:0,n=e<0?-e:0,i=this._size[0],a=this._size[1],o=Math.min(i-n,a-t),s=[],c=0;c<o;c++)s[c]=this._data[c+n][c+t];return new r({data:s,size:[o],datatype:this._datatype})},r.diagonal=function(e,t,n,i){if(!Zl(e))throw TypeError(`Array expected, size parameter`);if(e.length!==2)throw Error(`Only two dimensions matrix are supported`);if(e=e.map(function(e){if(xl(e)&&(e=e.toNumber()),!bl(e)||!lu(e)||e<1)throw Error(`Size values must be positive integers`);return e}),n){if(xl(n)&&(n=n.toNumber()),!bl(n)||!lu(n))throw TypeError(`The parameter k must be an integer number`)}else n=0;var a=n>0?n:0,o=n<0?-n:0,s=e[0],c=e[1],l=Math.min(s-o,c-a),u;if(Zl(t)){if(t.length!==l)throw Error(`Invalid value array length`);u=function(e){return t[e]}}else if(Dl(t)){var d=t.size();if(d.length!==1||d[0]!==l)throw Error(`Invalid matrix length`);u=function(e){return t.get([e])}}else u=function(){return t};i||=xl(u(0))?u(0).mul(0):0;var f=[];if(e.length>0){f=$f(f,e,i);for(var p=0;p<l;p++)f[p+o][p+a]=u(p)}return new r({data:f,size:[s,c]})},r.fromJSON=function(e){return new r(e)},r.prototype.swapRows=function(e,t){if(!bl(e)||!lu(e)||!bl(t)||!lu(t))throw Error(`Row index must be positive integers`);if(this._size.length!==2)throw Error(`Only two dimensional matrix is supported`);return Zf(e,this._size[0]),Zf(t,this._size[0]),r._swapRows(e,t,this._data),this},r._swapRows=function(e,t,n){var r=n[e];n[e]=n[t],n[t]=r};function u(e){return Dl(e)?u(e.valueOf()):Zl(e)?e.map(u):e}return r},{isClass:!0})})),Np,Pp,Fp,Mle=e((()=>{ru(),X(),Np=`clone`,Pp=[`typed`],Fp=Y(Np,Pp,e=>{var{typed:t}=e;return t(Np,{any:$l})})}));function Ip(e){var t=e.length,n=e[0].length,r,i,a=[];for(i=0;i<n;i++){var o=[];for(r=0;r<t;r++)o.push(e[r][i]);a.push(o)}return a}var Lp=e((()=>{}));function Rp(e){for(var t=0;t<e.length;t++)if(Ol(e[t]))return!0;return!1}function zp(e,t){Dl(e)?e.forEach(e=>t(e),!1,!0):wp(e,t,!0)}function Bp(e,t,n){if(!n)return Dl(e)?e.map(e=>t(e),!1,!0):Cp(e,t,!0);var r=e=>e===0?e:t(e);return Dl(e)?e.map(e=>r(e),!1,!0):Cp(e,r,!0)}function Vp(e,t,n){var r=Array.isArray(e)?qf(e):e.size();if(t<0||t>=r.length)throw new Gf(t,r.length);return Dl(e)?e.create(Hp(e.valueOf(),t,n),e.datatype()):Hp(e,t,n)}function Hp(e,t,n){var r,i,a,o;if(t<=0)if(Array.isArray(e[0])){for(o=Ip(e),i=[],r=0;r<o.length;r++)i[r]=Hp(o[r],t-1,n);return i}else{for(a=e[0],r=1;r<e.length;r++)a=n(a,e[r]);return a}else{for(i=[],r=0;r<e.length;r++)i[r]=Hp(e[r],t-1,n);return i}}function Up(e,t,n,r,i,a,o,s,c,l,u){var d=e._values,f=e._index,p=e._ptr,m,h,g,_;if(r)for(h=p[t],g=p[t+1],m=h;m<g;m++)_=f[m],n[_]===a?(r[_]=c?s(d[m],r[_]):s(r[_],d[m]),i[_]=a):(n[_]=a,o.push(_),l?(r[_]=c?s(d[m],u):s(u,d[m]),i[_]=a):r[_]=d[m]);else for(h=p[t],g=p[t+1],m=h;m<g;m++)_=f[m],n[_]===a?i[_]=a:(n[_]=a,o.push(_))}var Wp=e((()=>{Ql(),Kf(),Tp(),Lp()})),Gp,Kp,qp,Nle=e((()=>{Wp(),X(),Gp=`isInteger`,Kp=[`typed`,`equal`],qp=Y(Gp,Kp,e=>{var{typed:t,equal:n}=e;return t(Gp,{number:e=>Number.isFinite(e)?n(e,Math.round(e)):!1,BigNumber:e=>e.isFinite()?n(e.round(),e):!1,bigint:e=>!0,Fraction:e=>e.d===1n,"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})}));function Jp(e){return Math.abs(e)}function Yp(e,t){return e+t}function Xp(e,t){return e-t}function Zp(e,t){return e*t}function Ple(e,t){return e/t}function Qp(e){return-e}function $p(e){return e}function em(e){return Eu(e)}function tm(e){return e*e*e}function nm(e){return Math.exp(e)}function rm(e){return Du(e)}function Fle(e,t){if(!lu(e)||!lu(t))throw Error(`Parameters in function gcd must be integer numbers`);for(var n;t!==0;)n=e%t,e=t,t=n;return e<0?-e:e}function im(e,t){if(!lu(e)||!lu(t))throw Error(`Parameters in function lcm must be integer numbers`);if(e===0||t===0)return 0;for(var n,r=e*t;t!==0;)n=t,t=e%n,e=n;return Math.abs(r/e)}function am(e,t){return t?Math.log(e)/Math.log(t):Math.log(e)}function om(e){return wu(e)}function sm(e){return Cu(e)}function Ile(e){return Tu(e)}function Lle(e,t){return t===0?e:e-t*Math.floor(e/t)}function cm(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2,n=t<0;if(n&&(t=-t),t===0)throw Error(`Root must be non-zero`);if(e<0&&Math.abs(t)%2!=1)throw Error(`Root must be odd when a is negative.`);if(e===0)return n?1/0:0;
2588if(!isFinite(e))return n?0:e;var r=Math.abs(e)**(1/t);return r=e<0?-r:r,n?1/r:r}function lm(e){return Su(e)}function Rle(e){return Math.sqrt(e)}function um(e){return e*e}function dm(e,t){var n,r,i,a=0,o=1,s=1,c=0;if(!lu(e)||!lu(t))throw Error(`Parameters in function xgcd must be integer numbers`);for(;t;)r=Math.floor(e/t),i=e-r*t,n=a,a=o-r*a,o=n,n=s,s=c-r*s,c=n,e=t,t=i;return e<0?[-e,-o,-c]:[e,e?o:0,c]}function fm(e,t){return e*e<1&&t===1/0||e*e>1&&t===-1/0?0:e**+t}function pm(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;if(!lu(t)||t<0||t>15)throw Error(`Number of decimals in function round must be an integer from 0 to 15 inclusive`);return parseFloat(hu(e,t))}function zle(e){return Math.abs(e)}var mm,hm,Ble=e((()=>{Pu(),mm=`number`,hm=`number, number`,Jp.signature=mm,Yp.signature=hm,Xp.signature=hm,Zp.signature=hm,Ple.signature=hm,Qp.signature=mm,$p.signature=mm,em.signature=mm,tm.signature=mm,nm.signature=mm,rm.signature=mm,Fle.signature=hm,im.signature=hm,om.signature=mm,sm.signature=mm,Ile.signature=mm,Lle.signature=hm,lm.signature=mm,Rle.signature=mm,um.signature=mm,dm.signature=hm,fm.signature=hm,zle.signature=mm}));function gm(e,t){if(!lu(e)||!lu(t))throw Error(`Integers expected in function bitAnd`);return e&t}function _m(e){if(!lu(e))throw Error(`Integer expected in function bitNot`);return~e}function vm(e,t){if(!lu(e)||!lu(t))throw Error(`Integers expected in function bitOr`);return e|t}function ym(e,t){if(!lu(e)||!lu(t))throw Error(`Integers expected in function bitXor`);return e^t}function bm(e,t){if(!lu(e)||!lu(t))throw Error(`Integers expected in function leftShift`);return e<<t}function xm(e,t){if(!lu(e)||!lu(t))throw Error(`Integers expected in function rightArithShift`);return e>>t}function Sm(e,t){if(!lu(e)||!lu(t))throw Error(`Integers expected in function rightLogShift`);return e>>>t}var Cm,wm,Vle=e((()=>{Pu(),Cm=`number`,wm=`number, number`,gm.signature=wm,_m.signature=Cm,vm.signature=wm,ym.signature=wm,bm.signature=wm,xm.signature=wm,Sm.signature=wm}));function Tm(e,t){if(t<e)return 1;if(t===e)return t;var n=t+e>>1;return Tm(e,n)*Tm(n+1,t)}var Em=e((()=>{}));function Dm(e,t){if(!lu(e)||e<0||!lu(t)||t<0)throw TypeError(`Positive integer value expected in function combinations`);if(t>e)throw TypeError(`k must be less than or equal to n`);for(var n=e-t,r=1,i=t<n?n+1:t+1,a=2,o=t<n?t:n,s=i;s<=e;++s)for(r*=s;a<=o&&r%a===0;)r/=a,++a;return a<=o&&(r/=Tm(a,o)),r}var Om=e((()=>{Pu(),Em(),Dm.signature=`number, number`})),km,Am,jm,Mm,Hle=e((()=>{km=Math.PI,Am=2*Math.PI,jm=Math.E,Mm=1.618033988749895}));function Nm(e){return!e}function Pm(e,t){return!!(e||t)}function Fm(e,t){return!!e!=!!t}function Im(e,t){return!!(e&&t)}var Lm,Rm,Ule=e((()=>{Lm=`number`,Rm=`number, number`,Nm.signature=Lm,Pm.signature=Rm,Fm.signature=Rm,Im.signature=Rm})),Wle=e((()=>{}));function zm(e){var t;if(lu(e))return e<=0?Number.isFinite(e)?1/0:NaN:e>171?1/0:Tm(1,e-1);if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*zm(1-e));if(e>=171.35)return 1/0;if(e>85){var n=e*e,r=n*e,i=r*e,a=i*e;return Math.sqrt(2*Math.PI/e)*(e/Math.E)**+e*(1+1/(12*e)+1/(288*n)-139/(51840*r)-571/(2488320*i)+163879/(209018880*a)+5246819/(75246796800*a*e))}--e,t=Hm[0];for(var o=1;o<Hm.length;++o)t+=Hm[o]/(e+o);var s=e+Vm+.5;return Math.sqrt(2*Math.PI)*s**+(e+.5)*Math.exp(-s)*t}function Bm(e){if(e<0)return NaN;if(e===0)return 1/0;if(!Number.isFinite(e))return e;if(e<.5)return Math.log(Math.PI/Math.sin(Math.PI*e))-Bm(1-e);--e;for(var t=e+5+.5,n=Wm[0],r=6;r>=1;r--)n+=Wm[r]/(e+r);return Um+(e+.5)*Math.log(t)-t+Math.log(n)}var Vm,Hm,Um,Wm,Gle=e((()=>{Pu(),Em(),zm.signature=`number`,Vm=4.7421875,Hm=[.9999999999999971,57.15623566586292,-59.59796035547549,14.136097974741746,-.4919138160976202,3399464998481189e-20,4652362892704858e-20,-9837447530487956e-20,.0001580887032249125,-.00021026444172410488,.00021743961811521265,-.0001643181065367639,8441822398385275e-20,-26190838401581408e-21,36899182659531625e-22],Um=.9189385332046728,Wm=[1.000000000190015,76.18009172947146,-86.50532032941678,24.01409824083091,-1.231739572450155,.001208650973866179,-5395239384953e-18],Bm.signature=`number`}));function Kle(e){return Math.acos(e)}function Gm(e){return Ou(e)}function Km(e){return Math.atan(1/e)}function qm(e){return Number.isFinite(e)?(Math.log((e+1)/e)+Math.log(e/(e-1)))/2:0}function Jm(e){return Math.asin(1/e)}function Ym(e){var t=1/e;return Math.log(t+Math.sqrt(t*t+1))}function Xm(e){return Math.acos(1/e)}function Zm(e){var t=1/e,n=Math.sqrt(t*t-1);return Math.log(n+t)}function qle(e){return Math.asin(e)}function Qm(e){return ku(e)}function Jle(e){return Math.atan(e)}function Yle(e,t){return Math.atan2(e,t)}function $m(e){return Au(e)}function Xle(e){return Math.cos(e)}function Zle(e){return ju(e)}function eh(e){return 1/Math.tan(e)}function th(e){var t=Math.exp(2*e);return(t+1)/(t-1)}function nh(e){return 1/Math.sin(e)}function rh(e){return e===0?1/0:Math.abs(2/(Math.exp(e)-Math.exp(-e)))*Su(e)}function ih(e){return 1/Math.cos(e)}function ah(e){return 2/(Math.exp(e)+Math.exp(-e))}function Qle(e){return Math.sin(e)}function oh(e){return Mu(e)}function $le(e){return Math.tan(e)}function eue(e){return Nu(e)}var sh,ch,tue=e((()=>{Pu(),sh=`number`,ch=`number, number`,Kle.signature=sh,Gm.signature=sh,Km.signature=sh,qm.signature=sh,Jm.signature=sh,Ym.signature=sh,Xm.signature=sh,Zm.signature=sh,qle.signature=sh,Qm.signature=sh,Jle.signature=sh,Yle.signature=ch,$m.signature=sh,Xle.signature=sh,Zle.signature=sh,eh.signature=sh,th.signature=sh,nh.signature=sh,rh.signature=sh,ih.signature=sh,ah.signature=sh,Qle.signature=sh,oh.signature=sh,$le.signature=sh,eue.signature=sh}));function nue(e){return lu(e)}function lh(e){return e<0}function uh(e){return e>0}function rue(e){return e===0}function dh(e){return Number.isNaN(e)}var fh,iue=e((()=>{Pu(),fh=`number`,nue.signature=fh,lh.signature=fh,uh.signature=fh,rue.signature=fh,dh.signature=fh})),ph=e((()=>{Ble(),Vle(),Om(),Hle(),Ule(),Wle(),Gle(),tue(),iue()}));function mh(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1e-9,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0;
2588if(n<=0)throw Error(`Relative tolerance must be greater than 0`);if(r<0)throw Error(`Absolute tolerance must be at least 0`);return e.isNaN()||t.isNaN()?!1:!e.isFinite()||!t.isFinite()?e.eq(t):e.eq(t)?!0:e.minus(t).abs().lte(e.constructor.max(e.constructor.max(e.abs(),t.abs()).mul(n),r))}var hh=e((()=>{})),gh,_h,vh,aue=e((()=>{Wp(),X(),ph(),hh(),Pu(),gh=`isNegative`,_h=[`typed`,`config`],vh=Y(gh,_h,e=>{var{typed:t,config:n}=e;return t(gh,{number:e=>yu(e,0,n.relTol,n.absTol)?!1:lh(e),BigNumber:e=>mh(e,new e.constructor(0),n.relTol,n.absTol)?!1:e.isNeg()&&!e.isZero()&&!e.isNaN(),bigint:e=>e<0n,Fraction:e=>e.s<0n,Unit:t.referToSelf(e=>n=>t.find(e,n.valueType())(n.value)),"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),yh,bh,xh,oue=e((()=>{Wp(),X(),yh=`isNumeric`,bh=[`typed`],xh=Y(yh,bh,e=>{var{typed:t}=e;return t(yh,{"number | BigNumber | bigint | Fraction | boolean":()=>!0,"Complex | Unit | string | null | undefined | Node":()=>!1,"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),Sh,Ch,wh,sue=e((()=>{X(),Sh=`hasNumericValue`,Ch=[`typed`,`isNumeric`],wh=Y(Sh,Ch,e=>{var{typed:t,isNumeric:n}=e;return t(Sh,{boolean:()=>!0,string:function(e){return e.trim().length>0&&!isNaN(Number(e))},any:function(e){return n(e)}})})})),Th,Eh,Dh,cue=e((()=>{Wp(),X(),ph(),hh(),Pu(),Th=`isPositive`,Eh=[`typed`,`config`],Dh=Y(Th,Eh,e=>{var{typed:t,config:n}=e;return t(Th,{number:e=>yu(e,0,n.relTol,n.absTol)?!1:uh(e),BigNumber:e=>mh(e,new e.constructor(0),n.relTol,n.absTol)?!1:!e.isNeg()&&!e.isZero()&&!e.isNaN(),bigint:e=>e>0n,Fraction:e=>e.s>0n&&e.n>0n,Unit:t.referToSelf(e=>n=>t.find(e,n.valueType())(n.value)),"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),Oh,kh,Ah,lue=e((()=>{Wp(),X(),Oh=`isZero`,kh=[`typed`,`equalScalar`],Ah=Y(Oh,kh,e=>{var{typed:t,equalScalar:n}=e;return t(Oh,{"number | BigNumber | Complex | Fraction":e=>n(e,0),bigint:e=>e===0n,Unit:t.referToSelf(e=>n=>t.find(e,n.valueType())(n.value)),"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),jh,Mh,Nh,uue=e((()=>{Wp(),X(),ph(),jh=`isNaN`,Mh=[`typed`],Nh=Y(jh,Mh,e=>{var{typed:t}=e;return t(jh,{number:dh,BigNumber:function(e){return e.isNaN()},bigint:function(e){return!1},Fraction:function(e){return!1},Complex:function(e){return e.isNaN()},Unit:function(e){return Number.isNaN(e.value)},"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),Ph,Fh,Ih,due=e((()=>{X(),Ph=`isBounded`,Fh=[`typed`],Ih=Y(Ph,Fh,e=>{var{typed:t}=e;return t(Ph,{number:e=>Number.isFinite(e),"BigNumber | Complex":e=>e.isFinite(),"bigint | Fraction":()=>!0,"null | undefined":()=>!1,Unit:t.referToSelf(e=>t=>e(t.value)),"Array | Matrix":t.referToSelf(e=>t=>(Array.isArray(t)||(t=t.valueOf()),t.every(t=>e(t))))})})})),Lh,Rh,zh,fue=e((()=>{X(),Lh=`isFinite`,Rh=[`typed`,`isBounded`,`map`],zh=Y(Lh,Rh,e=>{var{typed:t,isBounded:n,map:r}=e;return t(Lh,{"Array | Matrix":e=>r(e,n),any:e=>n(e)})})})),Bh,Vh,Hh,pue=e((()=>{X(),Ql(),Bh=`typeOf`,Vh=[`typed`],Hh=Y(Bh,Vh,e=>{var{typed:t}=e;return t(Bh,{any:Xl})})}));function mue(e,t,n,r){return yu(e.re,t.re,n,r)&&yu(e.im,t.im,n,r)}var hue=e((()=>{Pu()})),Uh,Wh=e((()=>{X(),Uh=Y(`compareUnits`,[`typed`],e=>{var{typed:t}=e;return{"Unit, Unit":t.referToSelf(e=>(n,r)=>{if(!n.equalBase(r))throw Error(`Cannot compare units with different base`);return t.find(e,[n.valueType(),r.valueType()])(n.value,r.value)})}})})),Gh,Kh,qh,gue=e((()=>{hh(),Pu(),X(),hue(),Wh(),Gh=`equalScalar`,Kh=[`typed`,`config`],qh=Y(Gh,Kh,e=>{var{typed:t,config:n}=e;return t(Gh,{"boolean, boolean":function(e,t){return e===t},"number, number":function(e,t){return yu(e,t,n.relTol,n.absTol)},"BigNumber, BigNumber":function(e,t){return e.eq(t)||mh(e,t,n.relTol,n.absTol)},"bigint, bigint":function(e,t){return e===t},"Fraction, Fraction":function(e,t){return e.equals(t)},"Complex, Complex":function(e,t){return mue(e,t,n.relTol,n.absTol)}},Uh({typed:t}))}),Y(Gh,[`typed`,`config`],e=>{var{typed:t,config:n}=e;return t(Gh,{"number, number":function(e,t){return yu(e,t,n.relTol,n.absTol)}})})})),Jh,Yh,Xh,_ue=e((()=>{Ql(),Pu(),Hf(),ru(),Tp(),X(),Wf(),kp(),Jh=`SparseMatrix`,Yh=[`typed`,`equalScalar`,`Matrix`],Xh=Y(Jh,Yh,e=>{var{typed:t,equalScalar:n,Matrix:r}=e;function i(e,t){if(!(this instanceof i))throw SyntaxError(`Constructor must be called with the new operator`);if(t&&!El(t))throw Error(`Invalid datatype: `+t);if(Dl(e))a(this,e,t);else if(e&&Zl(e.index)&&Zl(e.ptr)&&Zl(e.size))this._values=e.values,this._index=e.index,this._ptr=e.ptr,this._size=e.size,this._datatype=t||e.datatype;else if(Zl(e))o(this,e,t);else if(e)throw TypeError(`Unsupported type of data (`+Xl(e)+`)`);else this._values=[],this._index=[],this._ptr=[0],this._size=[0,0],this._datatype=t}function a(e,t,n){t.type===`SparseMatrix`?(e._values=t._values?$l(t._values):void 0,e._index=$l(t._index),e._ptr=$l(t._ptr),e._size=$l(t._size),e._datatype=n||t._datatype):o(e,t.valueOf(),n||t._datatype)}function o(e,r,i){e._values=[],e._index=[],e._ptr=[],e._datatype=i;var a=r.length,o=0,s=n,c=0;if(El(i)&&(s=t.find(n,[i,i])||n,c=t.convert(0,i)),a>0){var l=0;do{e._ptr.push(e._index.length);for(var u=0;u<a;u++){var d=r[u];if(Zl(d)){if(l===0&&o<d.length&&(o=d.length),l<d.length){var f=d[l];s(f,c)||(e._values.push(f),e._index.push(u))}}else l===0&&o<1&&(o=1),s(d,c)||(e._values.push(d),e._index.push(u))}l++}while(l<o)}for(;e._ptr.length<=o;)e._ptr.push(e._index.length);e._size=[a,o]}i.prototype=new r,i.prototype.createSparseMatrix=function(e,t){return new i(e,t)},Object.defineProperty(i,"name",{value:`SparseMatrix`}),i.prototype.constructor=i,i.prototype.type=`SparseMatrix`,i.prototype.isSparseMatrix=!0,i.prototype.getDataType=function(){return gp(this._values,Xl)},i.prototype.storage=function(){return`sparse`},i.prototype.datatype=function(){return this._datatype},i.prototype.create=function(e,t){return new i(e,t)},i.prototype.density=function(){var e=this._size[0],t=this._size[1];return e!==0&&t!==0?this._index.length/(e*t):0},i.prototype.subset=function(e,t,n){if(!this._values)throw Error(`Cannot invoke subset on a Pattern only matrix`);switch(arguments.length){case 1:return s(this,e);case 2:case 3:return c(this,e,t,n);default:throw SyntaxError(`Wrong number of arguments`)}};function s(e,t){if(!Ml(t))throw TypeError(`Invalid index`);if(t.isScalar())return e.get(t.min());var n=t.size();if(n.length!==e._size.length)throw new Uf(n.length,e._size.length);var r,a,o,s,c=t.min(),l=t.max();for(r=0,a=e._size.length;r<a;r++)Zf(c[r],e._size[r]),Zf(l[r],e._size[r]);var u=e._values,d=e._index,f=e._ptr,p=t.dimension(0),m=t.dimension(1),h=[],g=[];function _(e,t){g[e]=t[0],h[e]=!0}
2588Number.isInteger(p)?_(p,[0]):p.forEach(_);var v=u?[]:void 0,y=[],b=[];function x(e){for(b.push(y.length),o=f[e],s=f[e+1];o<s;o++)r=d[o],h[r]===!0&&(y.push(g[r]),v&&v.push(u[o]))}return Number.isInteger(m)?x(m):m.forEach(x),b.push(y.length),new i({values:v,index:y,ptr:b,size:n,datatype:e._datatype})}function c(e,t,n,r){if(!t||t.isIndex!==!0)throw TypeError(`Invalid index`);var i=t.size(),a=t.isScalar(),o;if(Dl(n)?(o=n.size(),n=n.toArray()):o=qf(n),a){if(o.length!==0)throw TypeError(`Scalar expected`);e.set(t.min(),n,r)}else{if(i.length!==1&&i.length!==2)throw new Uf(i.length,e._size.length,`<`);if(o.length<i.length){for(var s=0,c=0;i[s]===1&&o[s]===1;)s++;for(;i[s]===1;)c++,s++;n=op(n,i.length,c,o)}if(!eu(i,o))throw new Uf(i,o,`>`);if(i.length===1)d(t.dimension(0),(t,i)=>{Zf(t),e.set([t,0],n[i[0]],r)});else{var l=t.dimension(0),u=t.dimension(1);d(l,(t,i)=>{Zf(t),d(u,(a,o)=>{Zf(a),e.set([t,a],n[i[0]][o[0]],r)})})}}return e;function d(e,t){bl(e)?t(e,[0]):e.forEach(t)}}i.prototype.get=function(e){if(!Zl(e))throw TypeError(`Array expected`);if(e.length!==this._size.length)throw new Uf(e.length,this._size.length);if(!this._values)throw Error(`Cannot invoke get on a Pattern only matrix`);var t=e[0],n=e[1];Zf(t,this._size[0]),Zf(n,this._size[1]);var r=l(t,this._ptr[n],this._ptr[n+1],this._index);return r<this._ptr[n+1]&&this._index[r]===t?this._values[r]:0},i.prototype.set=function(e,r,i){if(!Zl(e))throw TypeError(`Array expected`);if(e.length!==this._size.length)throw new Uf(e.length,this._size.length);if(!this._values)throw Error(`Cannot invoke set on a Pattern only matrix`);var a=e[0],o=e[1],s=this._size[0],c=this._size[1],p=n,m=0;El(this._datatype)&&(p=t.find(n,[this._datatype,this._datatype])||n,m=t.convert(0,this._datatype)),(a>s-1||o>c-1)&&(f(this,Math.max(a+1,s),Math.max(o+1,c),i),s=this._size[0],c=this._size[1]),Zf(a,s),Zf(o,c);var h=l(a,this._ptr[o],this._ptr[o+1],this._index);return h<this._ptr[o+1]&&this._index[h]===a?p(r,m)?u(h,o,this._values,this._index,this._ptr):this._values[h]=r:p(r,m)||d(h,a,o,r,this._values,this._index,this._ptr),this};function l(e,t,n,r){if(n-t===0)return n;for(var i=t;i<n;i++)if(r[i]===e)return i;return t}function u(e,t,n,r,i){n.splice(e,1),r.splice(e,1);for(var a=t+1;a<i.length;a++)i[a]--}function d(e,t,n,r,i,a,o){i.splice(e,0,r),a.splice(e,0,t);for(var s=n+1;s<o.length;s++)o[s]++}i.prototype.resize=function(e,t,n){if(!Ol(e))throw TypeError(`Array or Matrix expected`);var r=e.valueOf().map(e=>Array.isArray(e)&&e.length===1?e[0]:e);if(r.length!==2)throw Error(`Only two dimensions matrix are supported`);return r.forEach(function(e){if(!bl(e)||!lu(e)||e<0)throw TypeError(`Invalid size, must contain positive integers (size: `+If(r)+`)`)}),f(n?this.clone():this,r[0],r[1],t)};function f(e,r,i,a){var o=a||0,s=n,c=0;El(e._datatype)&&(s=t.find(n,[e._datatype,e._datatype])||n,c=t.convert(0,e._datatype),o=t.convert(o,e._datatype));var l=!s(o,c),u=e._size[0],d=e._size[1],f,p,m;if(i>d){for(p=d;p<i;p++)if(e._ptr[p]=e._values.length,l)for(f=0;f<u;f++)e._values.push(o),e._index.push(f);e._ptr[i]=e._values.length}else i<d&&(e._ptr.splice(i+1,d-i),e._values.splice(e._ptr[i],e._values.length),e._index.splice(e._ptr[i],e._index.length));if(d=i,r>u){if(l){var h=0;for(p=0;p<d;p++){e._ptr[p]=e._ptr[p]+h,m=e._ptr[p+1]+h;var g=0;for(f=u;f<r;f++,g++)e._values.splice(m+g,0,o),e._index.splice(m+g,0,f),h++}e._ptr[d]=e._values.length}}else if(r<u){var _=0;for(p=0;p<d;p++){e._ptr[p]=e._ptr[p]-_;var v=e._ptr[p],y=e._ptr[p+1]-_;for(m=v;m<y;m++)f=e._index[m],f>r-1&&(e._values.splice(m,1),e._index.splice(m,1),_++)}e._ptr[p]=e._values.length}return e._size[0]=r,e._size[1]=i,e}i.prototype.reshape=function(e,t){if(!Zl(e))throw TypeError(`Array expected`);if(e.length!==2)throw Error(`Sparse matrices can only be reshaped in two dimensions`);e.forEach(function(t){if(!bl(t)||!lu(t)||t<=-2||t===0)throw TypeError(`Invalid size, must contain positive integers or -1 (size: `+If(e)+`)`)});var n=this._size[0]*this._size[1];if(e=np(e,n),n!==e[0]*e[1])throw Error(`Reshaping sparse matrix will result in the wrong number of elements`);var r=t?this.clone():this;if(this._size[0]===e[0]&&this._size[1]===e[1])return r;for(var i=[],a=0;a<r._ptr.length;a++)for(var o=0;o<r._ptr[a+1]-r._ptr[a];o++)i.push(a);for(var s=r._values.slice(),c=r._index.slice(),u=0;u<r._index.length;u++){var f=c[u],p=i[u],m=f*r._size[1]+p;i[u]=m%e[1],c[u]=Math.floor(m/e[1])}r._values.length=0,r._index.length=0,r._ptr.length=e[1]+1,r._size=e.slice();for(var h=0;h<r._ptr.length;h++)r._ptr[h]=0;for(var g=0;g<s.length;g++){var _=c[g],v=i[g],y=s[g];d(l(_,r._ptr[v],r._ptr[v+1],r._index),_,v,y,r._values,r._index,r._ptr)}return r},i.prototype.clone=function(){return new i({values:this._values?$l(this._values):void 0,index:$l(this._index),ptr:$l(this._ptr),size:$l(this._size),datatype:this._datatype})},i.prototype.size=function(){return this._size.slice(0)},i.prototype.map=function(e,t){if(!this._values)throw Error(`Cannot invoke map on a Pattern only matrix`);var n=this,r=this._size[0],i=this._size[1],a=Ep(e,n,`map`);return p(this,0,r-1,0,i-1,function(e,t,r){return a.fn(e,[t,r],n)},t)};function p(e,r,a,o,s,c,l){var u=[],d=[],f=[],p=n,m=0;El(e._datatype)&&(p=t.find(n,[e._datatype,e._datatype])||n,m=t.convert(0,e._datatype));for(var h=function(e,t,n){var r=c(e,t,n);
2588p(r,m)||(u.push(r),d.push(t))},g=o;g<=s;g++){f.push(u.length);var _=e._ptr[g],v=e._ptr[g+1];if(l)for(var y=_;y<v;y++){var b=e._index[y];b>=r&&b<=a&&h(e._values[y],b-r,g-o)}else{for(var x={},S=_;S<v;S++){var C=e._index[S];x[C]=e._values[S]}for(var w=r;w<=a;w++)h(w in x?x[w]:0,w-r,g-o)}}return f.push(u.length),new i({values:u,index:d,ptr:f,size:[a-r+1,s-o+1]})}i.prototype.forEach=function(e,t){if(!this._values)throw Error(`Cannot invoke forEach on a Pattern only matrix`);for(var n=this,r=this._size[0],i=this._size[1],a=Ep(e,n,`forEach`),o=0;o<i;o++){var s=this._ptr[o],c=this._ptr[o+1];if(t)for(var l=s;l<c;l++){var u=this._index[l];a.fn(this._values[l],[u,o],n)}else{for(var d={},f=s;f<c;f++){var p=this._index[f];d[p]=this._values[f]}for(var m=0;m<r;m++){var h=m in d?d[m]:0;a.fn(h,[m,o],n)}}}},i.prototype[Symbol.iterator]=function*(){if(!this._values)throw Error(`Cannot iterate a Pattern only matrix`);for(var e=this._size[1],t=0;t<e;t++)for(var n=this._ptr[t],r=this._ptr[t+1],i=n;i<r;i++){var a=this._index[i];yield{value:this._values[i],index:[a,t]}}},i.prototype.toArray=function(){return m(this._values,this._index,this._ptr,this._size,!0)},i.prototype.valueOf=function(){return m(this._values,this._index,this._ptr,this._size,!1)};function m(e,t,n,r,i){var a=r[0],o=r[1],s=[],c,l;for(c=0;c<a;c++)for(s[c]=[],l=0;l<o;l++)s[c][l]=0;for(l=0;l<o;l++)for(var u=n[l],d=n[l+1],f=u;f<d;f++)c=t[f],s[c][l]=e?i?$l(e[f]):e[f]:1;return s}return i.prototype.format=function(e){for(var t=this._size[0],n=this._size[1],r=this.density(),i=`Sparse Matrix [`+If(t,e)+` x `+If(n,e)+`] density: `+If(r,e)+`
2589`,a=0;a<n;a++)for(var o=this._ptr[a],s=this._ptr[a+1],c=o;c<s;c++){var l=this._index[c];i+=`
2590    (`+If(l,e)+`, `+If(a,e)+`) ==> `+(this._values?If(this._values[c],e):`X`)}return i},i.prototype.toString=function(){return If(this.toArray())},i.prototype.toJSON=function(){return{mathjs:`SparseMatrix`,values:this._values,index:this._index,ptr:this._ptr,size:this._size,datatype:this._datatype}},i.prototype.diagonal=function(e){if(e){if(xl(e)&&(e=e.toNumber()),!bl(e)||!lu(e))throw TypeError(`The parameter k must be an integer number`)}else e=0;var t=e>0?e:0,n=e<0?-e:0,r=this._size[0],a=this._size[1],o=Math.min(r-n,a-t),s=[],c=[],l=[];l[0]=0;for(var u=t;u<a&&s.length<o;u++)for(var d=this._ptr[u],f=this._ptr[u+1],p=d;p<f;p++){var m=this._index[p];if(m===u-t+n){s.push(this._values[p]),c[s.length-1]=m-n;break}}return l.push(s.length),new i({values:s,index:c,ptr:l,size:[o,1]})},i.fromJSON=function(e){return new i(e)},i.diagonal=function(e,r,a,o,s){if(!Zl(e))throw TypeError(`Array expected, size parameter`);if(e.length!==2)throw Error(`Only two dimensions matrix are supported`);if(e=e.map(function(e){if(xl(e)&&(e=e.toNumber()),!bl(e)||!lu(e)||e<1)throw Error(`Size values must be positive integers`);return e}),a){if(xl(a)&&(a=a.toNumber()),!bl(a)||!lu(a))throw TypeError(`The parameter k must be an integer number`)}else a=0;var c=n,l=0;El(s)&&(c=t.find(n,[s,s])||n,l=t.convert(0,s));var u=a>0?a:0,d=a<0?-a:0,f=e[0],p=e[1],m=Math.min(f-d,p-u),h;if(Zl(r)){if(r.length!==m)throw Error(`Invalid value array length`);h=function(e){return r[e]}}else if(Dl(r)){var g=r.size();if(g.length!==1||g[0]!==m)throw Error(`Invalid matrix length`);h=function(e){return r.get([e])}}else h=function(){return r};for(var _=[],v=[],y=[],b=0;b<p;b++){y.push(_.length);var x=b-u;if(x>=0&&x<m){var S=h(x);c(S,l)||(v.push(x+d),_.push(S))}}return y.push(_.length),new i({values:_,index:v,ptr:y,size:[f,p]})},i.prototype.swapRows=function(e,t){if(!bl(e)||!lu(e)||!bl(t)||!lu(t))throw Error(`Row index must be positive integers`);if(this._size.length!==2)throw Error(`Only two dimensional matrix is supported`);return Zf(e,this._size[0]),Zf(t,this._size[0]),i._swapRows(e,t,this._size[1],this._values,this._index,this._ptr),this},i._forEachRow=function(e,t,n,r,i){for(var a=r[e],o=r[e+1],s=a;s<o;s++)i(n[s],t[s])},i._swapRows=function(e,t,n,r,i,a){for(var o=0;o<n;o++){var s=a[o],c=a[o+1],u=l(e,s,c,i),d=l(t,s,c,i);if(u<c&&d<c&&i[u]===e&&i[d]===t){if(r){var f=r[u];r[u]=r[d],r[d]=f}continue}if(u<c&&i[u]===e&&(d>=c||i[d]!==t)){var p=r?r[u]:void 0;i.splice(d,0,t),r&&r.splice(d,0,p),i.splice(d<=u?u+1:u,1),r&&r.splice(d<=u?u+1:u,1);continue}if(d<c&&i[d]===t&&(u>=c||i[u]!==e)){var m=r?r[d]:void 0;i.splice(u,0,e),r&&r.splice(u,0,m),i.splice(u<=d?d+1:d,1),r&&r.splice(u<=d?d+1:d,1)}}},i},{isClass:!0})}));function vue(e){var t=e.match(/(0[box])([0-9a-fA-F]*)\.([0-9a-fA-F]*)/);return t?{input:e,radix:{"0b":2,"0o":8,"0x":16}[t[1]],integerPart:t[2],fractionalPart:t[3]}:null}function yue(e){for(var t=parseInt(e.integerPart,e.radix),n=0,r=0;r<e.fractionalPart.length;r++){var i=parseInt(e.fractionalPart[r],e.radix);n+=i/e.radix**+(r+1)}var a=t+n;if(isNaN(a))throw SyntaxError(`String "`+e.input+`" is not a valid number`);return a}var Zh,Qh,$h,bue=e((()=>{X(),Wp(),Zh=`number`,Qh=[`typed`],$h=Y(Zh,Qh,e=>{var{typed:t}=e,n=t(`number`,{"":function(){return 0},number:function(e){return e},string:function(e){if(e===`NaN`)return NaN;var t=vue(e);if(t)return yue(t);var n=0,r=e.match(/(0[box][0-9a-fA-F]*)i([0-9]*)/);r&&(n=Number(r[2]),e=r[1]);var i=Number(e);if(isNaN(i))throw SyntaxError(`String "`+e+`" is not a valid number`);if(r){if(i>2**n-1)throw SyntaxError(`String "${e}" is out of range`);i>=2**(n-1)&&(i-=2**n)}return i},BigNumber:function(e){return e.toNumber()},bigint:function(e){return Number(e)},Fraction:function(e){return e.valueOf()},Unit:t.referToSelf(e=>t=>{var n=t.clone();return n.value=e(t.value),n}),null:function(e){return 0},"Unit, string | Unit":function(e,t){return e.toNumber(t)},"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))});return n.fromJSON=function(e){return parseFloat(e.value)},n})})),eg,tg,ng,xue=e((()=>{X(),Wp(),eg=`bigint`,tg=[`typed`],ng=Y(eg,tg,e=>{var{typed:t}=e,n=t(`bigint`,{"":function(){return 0n},bigint:function(e){return e},number:function(e){return BigInt(e.toFixed())},BigNumber:function(e){return BigInt(e.round().toString())},Fraction:function(e){return BigInt(e.valueOf().toFixed())},"string | boolean":function(e){return BigInt(e)},null:function(e){return 0n},"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))});return n.fromJSON=function(e){return BigInt(e.value)},n})})),rg,ig,ag,Sue=e((()=>{X(),Wp(),Pu(),rg=`string`,ig=[`typed`],ag=Y(rg,ig,e=>{var{typed:t}=e;return t(rg,{"":function(){return``},number:fu,null:function(e){return`null`},boolean:function(e){return e+``},string:function(e){return e},"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e)),any:function(e){return String(e)}})})})),og,sg,cg,Cue=e((()=>{X(),Wp(),og=`boolean`,sg=[`typed`],cg=Y(og,sg,e=>{var{typed:t}=e;return t(og,{"":function(){return!1},boolean:function(e){return e},number:function(e){return!!e},null:function(e){return!1},BigNumber:function(e){return!e.isZero()},string:function(e){var t=e.toLowerCase();if(t===`true`)return!0;
2590if(t===`false`)return!1;var n=Number(e);if(e!==``&&!isNaN(n))return!!n;throw Error(`Cannot convert "`+e+`" to a boolean`)},"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),lg,ug,dg,wue=e((()=>{X(),Wp(),lg=`bignumber`,ug=[`typed`,`BigNumber`],dg=Y(lg,ug,e=>{var{typed:t,BigNumber:n}=e;return t(`bignumber`,{"":function(){return new n(0)},number:function(e){return new n(e+``)},string:function(e){var t=e.match(/(0[box][0-9a-fA-F]*)i([0-9]*)/);if(t){var r=t[2],i=n(t[1]),a=new n(2).pow(Number(r));if(i.gt(a.sub(1)))throw SyntaxError(`String "${e}" is out of range`);var o=new n(2).pow(Number(r)-1);return i.gte(o)?i.sub(a):i}return new n(e)},BigNumber:function(e){return e},bigint:function(e){return new n(e.toString())},Unit:t.referToSelf(e=>t=>{var n=t.clone();return n.value=e(t.value),n}),Fraction:function(e){return new n(String(e.n)).div(String(e.d)).times(String(e.s))},null:function(e){return new n(0)},"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),fg,pg,mg,Tue=e((()=>{X(),Wp(),fg=`complex`,pg=[`typed`,`Complex`],mg=Y(fg,pg,e=>{var{typed:t,Complex:n}=e;return t(`complex`,{"":function(){return n.ZERO},number:function(e){return new n(e,0)},"number, number":function(e,t){return new n(e,t)},"BigNumber, BigNumber":function(e,t){return new n(e.toNumber(),t.toNumber())},Fraction:function(e){return new n(e.valueOf(),0)},Complex:function(e){return e.clone()},string:function(e){return n(e)},null:function(e){return n(0)},Object:function(e){if(`re`in e&&`im`in e)return new n(e.re,e.im);if(`r`in e&&`phi`in e||`abs`in e&&`arg`in e)return new n(e);throw Error(`Expected object with properties (re and im) or (r and phi) or (abs and arg)`)},"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),hg,gg,_g,Eue=e((()=>{X(),Wp(),hg=`fraction`,gg=[`typed`,`Fraction`],_g=Y(hg,gg,e=>{var{typed:t,Fraction:n}=e;return t(`fraction`,{number:function(e){if(!Number.isFinite(e)||isNaN(e))throw Error(e+` cannot be represented as a fraction`);return new n(e)},string:function(e){return new n(e)},"number, number":function(e,t){return new n(e,t)},"bigint, bigint":function(e,t){return new n(e,t)},null:function(e){return new n(0)},BigNumber:function(e){return new n(e.toString())},bigint:function(e){return new n(e.toString())},Fraction:function(e){return e},Unit:t.referToSelf(e=>t=>{var n=t.clone();return n.value=e(t.value),n}),Object:function(e){return new n(e)},"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),vg,yg,bg,Due=e((()=>{X(),vg=`matrix`,yg=[`typed`,`Matrix`,`DenseMatrix`,`SparseMatrix`],bg=Y(vg,yg,e=>{var{typed:t,Matrix:n,DenseMatrix:r,SparseMatrix:i}=e;return t(vg,{"":function(){return a([])},string:function(e){return a([],e)},"string, string":function(e,t){return a([],e,t)},Array:function(e){return a(e)},Matrix:function(e){return a(e,e.storage())},"Array | Matrix, string":a,"Array | Matrix, string, string":a});function a(e,t,n){if(t===`dense`||t==="default"||t===void 0)return new r(e,n);if(t===`sparse`)return new i(e,n);throw TypeError(`Unknown matrix type `+JSON.stringify(t)+`.`)}})})),xg,Sg,Cg,Oue=e((()=>{X(),xg=`matrixFromFunction`,Sg=[`typed`,`matrix`,`isZero`],Cg=Y(xg,Sg,e=>{var{typed:t,matrix:n,isZero:r}=e;return t(xg,{"Array | Matrix, function, string, string":function(e,t,n,r){return i(e,t,n,r)},"Array | Matrix, function, string":function(e,t,n){return i(e,t,n)},"Matrix, function":function(e,t){return i(e,t,`dense`)},"Array, function":function(e,t){return i(e,t,`dense`).toArray()},"Array | Matrix, string, function":function(e,t,n){return i(e,n,t)},"Array | Matrix, string, string, function":function(e,t,n,r){return i(e,r,t,n)}});function i(e,t,i,a){var o=a===void 0?n(i):n(i,a);return o.resize(e),o.forEach(function(e,n){var i=t(n);r(i)||o.set(n,i)}),o}})})),wg,Tg,Eg,kue=e((()=>{X(),wg=`matrixFromRows`,Tg=[`typed`,`matrix`,`flatten`,`size`],Eg=Y(wg,Tg,e=>{var{typed:t,matrix:n,flatten:r,size:i}=e;return t(wg,{"...Array":function(e){return a(e)},"...Matrix":function(e){return n(a(e.map(e=>e.toArray())))}});function a(e){if(e.length===0)throw TypeError(`At least one row is needed to construct a matrix.`);var t=o(e[0]),n=[];for(var i of e){var a=o(i);if(a!==t)throw TypeError(`The vectors had different length: `+(t|0)+` ≠ `+(a|0));
2590n.push(r(i))}return n}function o(e){var t=i(e);if(t.length===1)return t[0];if(t.length===2){if(t[0]===1)return t[1];if(t[1]===1)return t[0];throw TypeError(`At least one of the arguments is not a vector.`)}else throw TypeError(`Only one- or two-dimensional vectors are supported.`)}})})),Dg,Og,kg,Aue=e((()=>{X(),Dg=`matrixFromColumns`,Og=[`typed`,`matrix`,`flatten`,`size`],kg=Y(Dg,Og,e=>{var{typed:t,matrix:n,flatten:r,size:i}=e;return t(Dg,{"...Array":function(e){return a(e)},"...Matrix":function(e){return n(a(e.map(e=>e.toArray())))}});function a(e){if(e.length===0)throw TypeError(`At least one column is needed to construct a matrix.`);for(var t=o(e[0]),n=[],i=0;i<t;i++)n[i]=[];for(var a of e){var s=o(a);if(s!==t)throw TypeError(`The vectors had different length: `+(t|0)+` ≠ `+(s|0));for(var c=r(a),l=0;l<t;l++)n[l].push(c[l])}return n}function o(e){var t=i(e);if(t.length===1)return t[0];if(t.length===2){if(t[0]===1)return t[1];if(t[1]===1)return t[0];throw TypeError(`At least one of the arguments is not a vector.`)}else throw TypeError(`Only one- or two-dimensional vectors are supported.`)}})})),Ag,jg,Mg,jue=e((()=>{X(),Ag=`splitUnit`,jg=[`typed`],Mg=Y(Ag,jg,e=>{var{typed:t}=e;return t(Ag,{"Unit, Array":function(e,t){return e.splitUnit(t)}})})})),Ng,Pg,Fg,Mue=e((()=>{X(),Wp(),ph(),Ng=`unaryMinus`,Pg=[`typed`],Fg=Y(Ng,Pg,e=>{var{typed:t}=e;return t(Ng,{number:Qp,"Complex | BigNumber | Fraction":e=>e.neg(),bigint:e=>-e,Unit:t.referToSelf(e=>n=>{var r=n.clone();return r.value=t.find(e,r.valueType())(n.value),r}),"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e,!0))})})})),Ig,Lg,Rg,Nue=e((()=>{X(),Wp(),ph(),Pu(),Ig=`unaryPlus`,Lg=[`typed`,`config`,`numeric`],Rg=Y(Ig,Lg,e=>{var{typed:t,config:n,numeric:r}=e;return t(Ig,{number:$p,Complex:function(e){return e},BigNumber:function(e){return e},bigint:function(e){return e},Fraction:function(e){return e},Unit:function(e){return e.clone()},"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e,!0)),boolean:function(e){return r(+!!e,n.number)},string:function(e){return r(e,uu(e,n))}})})})),zg,Bg,Vg,Pue=e((()=>{X(),Wp(),ph(),zg=`abs`,Bg=[`typed`],Vg=Y(zg,Bg,e=>{var{typed:t}=e;return t(zg,{number:Jp,"Complex | BigNumber | Fraction | Unit":e=>e.abs(),bigint:e=>e<0n?-e:e,"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e,!0))})})}));function Hg(e,t,n){var r,i,a;if(t<=0)if(Array.isArray(e[0])){for(a=Fue(e),i=[],r=0;r<a.length;r++)i[r]=Hg(a[r],t-1,n);return i}else return n(e);else{for(i=[],r=0;r<e.length;r++)i[r]=Hg(e[r],t-1,n);return i}}function Fue(e){var t=e.length,n=e[0].length,r,i,a=[];for(i=0;i<n;i++){var o=[];for(r=0;r<t;r++)o.push(e[r][i]);a.push(o)}return a}var Ug,Wg,Gg,Kg=e((()=>{X(),Tp(),Ql(),Kf(),Ug=`mapSlices`,Wg=[`typed`,`isInteger`],Gg=Y(Ug,Wg,e=>{var{typed:t,isInteger:n}=e;return t(Ug,{"Array | Matrix, number | BigNumber, function":function(e,t,r){if(!n(t))throw TypeError(`Integer number expected for dimension`);var i=Array.isArray(e)?qf(e):e.size();if(t<0||t>=i.length)throw new Gf(t,i.length);return Dl(e)?e.create(Hg(e.valueOf(),t,r),e.datatype()):Hg(e,t,r)}})},{formerly:`apply`})})),qg,Jg,Yg,Iue=e((()=>{X(),ph(),qg=`addScalar`,Jg=[`typed`],Yg=Y(qg,Jg,e=>{var{typed:t}=e;return t(qg,{"number, number":Yp,"Complex, Complex":function(e,t){return e.add(t)},"BigNumber, BigNumber":function(e,t){return e.plus(t)},"bigint, bigint":function(e,t){return e+t},"Fraction, Fraction":function(e,t){return e.add(t)},"Unit, Unit":t.referToSelf(e=>(n,r)=>{if(n.value===null||n.value===void 0)throw Error(`Parameter x contains a unit with undefined value`);if(r.value===null||r.value===void 0)throw Error(`Parameter y contains a unit with undefined value`);if(!n.equalBase(r))throw Error(`Units do not match`);var i=n.clone();return i.value=t.find(e,[i.valueType(),r.valueType()])(i.value,r.value),i.fixPrefix=!1,i})})})})),Xg,Zg,Qg,Lue=e((()=>{X(),ph(),Xg=`subtractScalar`,Zg=[`typed`],Qg=Y(Xg,Zg,e=>{var{typed:t}=e;return t(Xg,{"number, number":Xp,"Complex, Complex":function(e,t){return e.sub(t)},"BigNumber, BigNumber":function(e,t){return e.minus(t)},"bigint, bigint":function(e,t){return e-t},"Fraction, Fraction":function(e,t){return e.sub(t)},"Unit, Unit":t.referToSelf(e=>(n,r)=>{if(n.value===null||n.value===void 0)throw Error(`Parameter x contains a unit with undefined value`);if(r.value===null||r.value===void 0)throw Error(`Parameter y contains a unit with undefined value`);if(!n.equalBase(r))throw Error(`Units do not match`);var i=n.clone();return i.value=t.find(e,[i.valueType(),r.valueType()])(i.value,r.value),i.fixPrefix=!1,i})})})})),$g,e_,t_,Rue=e((()=>{X(),Ql(),ph(),$g=`cbrt`,e_=[`config`,`typed`,`isNegative`,`unaryMinus`,`matrix`,`Complex`,`BigNumber`,`Fraction`],t_=Y($g,e_,e=>{var{config:t,typed:n,isNegative:r,unaryMinus:i,matrix:a,Complex:o,BigNumber:s,Fraction:c}=e;return n($g,{number:em,Complex:l,"Complex, boolean":l,BigNumber:function(e){return e.cbrt()},Unit:u});function l(e,n){var r=e.arg()/3,i=e.abs(),s=new o(em(i),0).mul(new o(0,r).exp());if(n){var c=[s,new o(em(i),0).mul(new o(0,r+Math.PI*2/3).exp()),new o(em(i),0).mul(new o(0,r-Math.PI*2/3).exp())];return t.matrix===`Array`?c:a(c)}else return s}function u(e){if(e.value&&Cl(e.value)){var t=e.clone();return t.value=1,t=t.pow(1/3),t.value=l(e.value),t}else{var n=r(e.value);n&&(e.value=i(e.value));var a=xl(e.value)?new s(1).div(3):wl(e.value)?new c(1,3):1/3,o=e.pow(a);return n&&(o.value=i(o.value)),o}}})})),n_,r_,i_,a_=e((()=>{X(),n_=`matAlgo11xS0s`,r_=[`typed`,`equalScalar`],i_=Y(n_,r_,e=>{var{typed:t,equalScalar:n}=e;return function(e,r,i,a){var o=e._values,s=e._index,c=e._ptr,l=e._size,u=e._datatype;if(!o)throw Error(`Cannot perform operation on Pattern Sparse Matrix and Scalar value`);var d=l[0],f=l[1],p,m=n,h=0,g=i;typeof u==`string`&&(p=u,m=t.find(n,[p,p]),h=t.convert(0,p),r=t.convert(r,p),g=t.find(i,[p,p]));for(var _=[],v=[],y=[],b=0;b<f;b++){y[b]=v.length;for(var x=c[b],S=c[b+1],C=x;C<S;C++){var w=s[C],T=a?g(r,o[C]):g(o[C],r);m(T,h)||(v.push(w),_.push(T))}}return y[f]=v.length,e.createSparseMatrix({values:_,index:v,ptr:y,size:[d,f],datatype:p})}})})),o_,s_,c_,l_=e((()=>
2590{X(),o_=`matAlgo12xSfs`,s_=[`typed`,`DenseMatrix`],c_=Y(o_,s_,e=>{var{typed:t,DenseMatrix:n}=e;return function(e,r,i,a){var o=e._values,s=e._index,c=e._ptr,l=e._size,u=e._datatype;if(!o)throw Error(`Cannot perform operation on Pattern Sparse Matrix and Scalar value`);var d=l[0],f=l[1],p,m=i;typeof u==`string`&&(p=u,r=t.convert(r,p),m=t.find(i,[p,p]));for(var h=[],g=[],_=[],v=0;v<f;v++){for(var y=v+1,b=c[v],x=c[v+1],S=b;S<x;S++){var C=s[S];g[C]=o[S],_[C]=y}for(var w=0;w<d;w++)v===0&&(h[w]=[]),_[w]===y?h[w][v]=a?m(r,g[w]):m(g[w],r):h[w][v]=a?m(r,0):m(0,r)}return new n({data:h,size:[d,f],datatype:p})}})})),u_,d_,f_,p_=e((()=>{X(),ru(),u_=`matAlgo14xDs`,d_=[`typed`],f_=Y(u_,d_,e=>{var{typed:t}=e;return function(e,r,i,a){var o=e._data,s=e._size,c=e._datatype,l,u=i;typeof c==`string`&&(l=c,r=t.convert(r,l),u=t.find(i,[l,l]));var d=s.length>0?n(u,0,s,s[0],o,r,a):[];return e.createDenseMatrix({data:d,size:$l(s),datatype:l})};function n(e,t,r,i,a,o,s){var c=[];if(t===r.length-1)for(var l=0;l<i;l++)c[l]=s?e(o,a[l]):e(a[l],o);else for(var u=0;u<i;u++)c[u]=n(e,t+1,r,r[t+1],a[u],o,s);return c}})})),m_,h_,g_,__,v_,zue=e((()=>{Ud(),X(),Wp(),Pu(),hh(),a_(),l_(),p_(),m_=`ceil`,h_=[`typed`,`config`,`round`,`matrix`,`equalScalar`,`zeros`,`DenseMatrix`],g_=new Hd(10),__=Y(m_,[`typed`,`config`,`round`],e=>{var{typed:t,config:n,round:r}=e;function i(e){var t=Math.ceil(e),i=r(e);return t===i?t:yu(e,i,n.relTol,n.absTol)&&!yu(e,t,n.relTol,n.absTol)?i:t}return t(m_,{number:i,"number, number":function(e,t){if(!lu(t))throw RangeError(`number of decimals in function ceil must be an integer`);if(t<0||t>15)throw RangeError(`number of decimals in ceil number must be in range 0-15`);var n=10**t;return i(e*n)/n}})}),v_=Y(m_,h_,e=>{var{typed:t,config:n,round:r,matrix:i,equalScalar:a,zeros:o,DenseMatrix:s}=e,c=i_({typed:t,equalScalar:a}),l=c_({typed:t,DenseMatrix:s}),u=f_({typed:t}),d=__({typed:t,config:n,round:r});function f(e){var t=(e,t)=>mh(e,t,n.relTol,n.absTol),i=e.ceil(),a=r(e);return i.eq(a)?i:t(e,a)&&!t(e,i)?a:i}return t(`ceil`,{number:d.signatures.number,"number,number":d.signatures[`number,number`],Complex:function(e){return e.ceil()},"Complex, number":function(e,t){return e.ceil(t)},"Complex, BigNumber":function(e,t){return e.ceil(t.toNumber())},BigNumber:f,"BigNumber, BigNumber":function(e,t){var n=g_.pow(t);return f(e.mul(n)).div(n)},bigint:e=>e,"bigint, number":(e,t)=>e,"bigint, BigNumber":(e,t)=>e,Fraction:function(e){return e.ceil()},"Fraction, number":function(e,t){return e.ceil(t)},"Fraction, BigNumber":function(e,t){return e.ceil(t.toNumber())},"Unit, number, Unit":t.referToSelf(e=>function(t,n,r){var i=t.toNumeric(r);return r.multiply(e(i,n))}),"Unit, BigNumber, Unit":t.referToSelf(e=>(t,n,r)=>e(t,n.toNumber(),r)),"Array | Matrix, number | BigNumber, Unit":t.referToSelf(e=>(t,n,r)=>Bp(t,t=>e(t,n,r),!0)),"Array | Matrix | Unit, Unit":t.referToSelf(e=>(t,n)=>e(t,0,n)),"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e,!0)),"Array, number | BigNumber":t.referToSelf(e=>(t,n)=>Bp(t,t=>e(t,n),!0)),"SparseMatrix, number | BigNumber":t.referToSelf(e=>(t,n)=>c(t,n,e,!1)),"DenseMatrix, number | BigNumber":t.referToSelf(e=>(t,n)=>u(t,n,e,!1)),"number | Complex | Fraction | BigNumber, Array":t.referToSelf(e=>(t,n)=>u(i(n),t,e,!0).valueOf()),"number | Complex | Fraction | BigNumber, Matrix":t.referToSelf(e=>(t,n)=>a(t,0)?o(n.size(),n.storage()):n.storage()===`dense`?u(n,t,e,!0):l(n,t,e,!0))})})})),y_,b_,x_,Bue=e((()=>{X(),ph(),y_=`cube`,b_=[`typed`],x_=Y(y_,b_,e=>{var{typed:t}=e;return t(y_,{number:tm,Complex:function(e){return e.mul(e).mul(e)},BigNumber:function(e){return e.times(e).times(e)},bigint:function(e){return e*e*e},Fraction:function(e){return e.pow(3)},Unit:function(e){return e.pow(3)}})})})),S_,C_,w_,Vue=e((()=>{X(),ph(),S_=`exp`,C_=[`typed`],w_=Y(S_,C_,e=>{var{typed:t}=e;return t(S_,{number:nm,Complex:function(e){return e.exp()},BigNumber:function(e){return e.exp()}})})})),T_,E_,D_,Hue=e((()=>{X(),ph(),T_=`expm1`,E_=[`typed`,`Complex`],D_=Y(T_,E_,e=>{var{typed:t,Complex:n}=e;return t(T_,{number:rm,Complex:function(e){var t=Math.exp(e.re);return new n(t*Math.cos(e.im)-1,t*Math.sin(e.im))},BigNumber:function(e){return e.exp().minus(1)}})})})),O_,k_,A_,j_,Uue=e((()=>{X(),Wp(),l_(),p_(),O_=`fix`,k_=[`typed`,`Complex`,`matrix`,`ceil`,`floor`,`equalScalar`,`zeros`,`DenseMatrix`],A_=Y(O_,[`typed`,`ceil`,`floor`],e=>{var{typed:t,ceil:n,floor:r}=e;return t(O_,{number:function(e){return e>0?r(e):n(e)},"number, number":function(e,t){return e>0?r(e,t):n(e,t)}})}),j_=Y(O_,k_,e=>{var{typed:t,Complex:n,matrix:r,ceil:i,floor:a,equalScalar:o,zeros:s,DenseMatrix:c}=e,l=c_({typed:t,DenseMatrix:c}),u=f_({typed:t}),d=A_({typed:t,ceil:i,floor:a});return t(`fix`,{number:d.signatures.number,"number, number | BigNumber":d.signatures[`number,number`],Complex:function(e){return new n(e.re>0?Math.floor(e.re):Math.ceil(e.re),e.im>0?Math.floor(e.im):Math.ceil(e.im))},"Complex, number":function(e,t){return new n(e.re>0?a(e.re,t):i(e.re,t),e.im>0?a(e.im,t):i(e.im,t))},"Complex, BigNumber":function(e,t){var r=t.toNumber();return new n(e.re>0?a(e.re,r):i(e.re,r),e.im>0?a(e.im,r):i(e.im,r))},BigNumber:function(e){return e.isNegative()?i(e):a(e)},"BigNumber, number | BigNumber":function(e,t){return e.isNegative()?i(e,t):a(e,t)},bigint:e=>e,"bigint, number":(e,t)=>e,"bigint, BigNumber":(e,t)=>e,Fraction:function(e){return e.s<0n?e.ceil():e.floor()},"Fraction, number | BigNumber":function(e,t){return e.s<0n?i(e,t):a(e,t)},"Unit, number, Unit":t.referToSelf(e=>function(t,n,r){var i=t.toNumeric(r);return r.multiply(e(i,n))}),"Unit, BigNumber, Unit":t.referToSelf(e=>(t,n,r)=>e(t,n.toNumber(),r)),"Array | Matrix, number | BigNumber, Unit":t.referToSelf(e=>(t,n,r)=>Bp(t,t=>e(t,n,r),!0)),"Array | Matrix | Unit, Unit":t.referToSelf(e=>(t,n)=>e(t,0,n)),"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e,!0)),"Array | Matrix, number | BigNumber":t.referToSelf(e=>(t,n)=>Bp(t,t=>e(t,n),!0)),"number | Complex | Fraction | BigNumber, Array":t.referToSelf(e=>(t,n)=>u(r(n),t,e,!0).valueOf()),"number | Complex | Fraction | BigNumber, Matrix":t.referToSelf(e=>(t,n)=>o(t,0)?s(n.size(),n.storage()):n.storage()===`dense`?u(n,t,e,!0):l(n,t,e,!0))})})})),M_,N_,P_,F_,I_,L_=e((()=>{Ud(),X(),Wp(),Pu(),hh(),a_(),l_(),p_(),M_=`floor`,N_=[`typed`,`config`,`round`,`matrix`,`equalScalar`,`zeros`,`DenseMatrix`],P_=new Hd(10),F_=Y(M_,[`typed`,`config`,`round`],e=>{var{typed:t,config:n,round:r}=e;function i(e){var t=Math.floor(e),i=r(e);return t===i?t:yu(e,i,n.relTol,n.absTol)&&!yu(e,t,n.relTol,n.absTol)?i:t}return t(M_,{number:i,"number, number":function(e,t){if(!lu(t))throw RangeError(`number of decimals in function floor must be an integer`);if(t<0||t>15)throw RangeError(`number of decimals in floor number must be in range 0 - 15`);var n=10**t;return i(e*n)/n}})}),I_=Y(M_,N_,e=>{var{typed:t,config:n,round:r,matrix:i,equalScalar:a,zeros:o,DenseMatrix:s}=e,c=i_({typed:t,equalScalar:a}),l=c_({typed:t,DenseMatrix:s}),u=f_({typed:t}),d=F_({typed:t,config:n,round:r});function f(e){var t=(e,t)=>mh(e,t,n.relTol,n.absTol),i=e.floor(),a=r(e);return i.eq(a)?i:t(e,a)&&!t(e,i)?a:i}return t(`floor`,{number:d.signatures.number,"number,number":d.signatures[`number,number`],Complex:function(e){return e.floor()},"Complex, number":function(e,t){return e.floor(t)},"Complex, BigNumber":function(e,t){return e.floor(t.toNumber())},BigNumber:f,"BigNumber, BigNumber":function(e,t){var n=P_.pow(t);return f(e.mul(n)).div(n)},bigint:e=>e,"bigint, number":(e,t)=>e,"bigint, BigNumber":(e,t)=>e,Fraction:function(e){return e.floor()},"Fraction, number":function(e,t){return e.floor(t)},"Fraction, BigNumber":function(e,t){return e.floor(t.toNumber())},"Unit, number, Unit":t.referToSelf(e=>function(t,n,r){var i=t.toNumeric(r);return r.multiply(e(i,n))}),"Unit, BigNumber, Unit":t.referToSelf(e=>(t,n,r)=>e(t,n.toNumber(),r)),"Array | Matrix, number | BigNumber, Unit":t.referToSelf(e=>(t,n,r)=>Bp(t,t=>e(t,n,r),!0)),"Array | Matrix | Unit, Unit":t.referToSelf(e=>(t,n)=>e(t,0,n)),"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e,!0)),"Array, number | BigNumber":t.referToSelf(e=>(t,n)=>Bp(t,t=>e(t,n),!0)),"SparseMatrix, number | BigNumber":t.referToSelf(e=>(t,n)=>
2590c(t,n,e,!1)),"DenseMatrix, number | BigNumber":t.referToSelf(e=>(t,n)=>u(t,n,e,!1)),"number | Complex | Fraction | BigNumber, Array":t.referToSelf(e=>(t,n)=>u(i(n),t,e,!0).valueOf()),"number | Complex | Fraction | BigNumber, Matrix":t.referToSelf(e=>(t,n)=>a(t,0)?o(n.size(),n.storage()):n.storage()===`dense`?u(n,t,e,!0):l(n,t,e,!0))})})})),R_,z_,B_,V_=e((()=>{X(),Wf(),R_=`matAlgo02xDS0`,z_=[`typed`,`equalScalar`],B_=Y(R_,z_,e=>{var{typed:t,equalScalar:n}=e;return function(e,r,i,a){var o=e._data,s=e._size,c=e._datatype||e.getDataType(),l=r._values,u=r._index,d=r._ptr,f=r._size,p=r._datatype||r._data===void 0?r._datatype:r.getDataType();if(s.length!==f.length)throw new Uf(s.length,f.length);if(s[0]!==f[0]||s[1]!==f[1])throw RangeError(`Dimension mismatch. Matrix A (`+s+`) must match Matrix B (`+f+`)`);if(!l)throw Error(`Cannot perform operation on Dense Matrix and Pattern Sparse Matrix`);var m=s[0],h=s[1],g,_=n,v=0,y=i;typeof c==`string`&&c===p&&c!==`mixed`&&(g=c,_=t.find(n,[g,g]),v=t.convert(0,g),y=t.find(i,[g,g]));for(var b=[],x=[],S=[],C=0;C<h;C++){S[C]=x.length;for(var w=d[C],T=d[C+1],E=w;E<T;
vendor: 4,393 bytes, line 2590
2590E++){var D=u[E],O=a?y(l[E],o[D][C]):y(o[D][C],l[E]);_(O,v)||(x.push(D),b.push(O))}}return S[h]=x.length,r.createSparseMatrix({values:b,index:x,ptr:S,size:[m,h],datatype:c===e._datatype&&p===r._datatype?g:void 0})}})})),H_,U_,W_,G_=e((()=>{X(),Wf(),H_=`matAlgo03xDSf`,U_=[`typed`],W_=Y(H_,U_,e=>{var{typed:t}=e;return function(e,n,r,i){var a=e._data,o=e._size,s=e._datatype||e.getDataType(),c=n._values,l=n._index,u=n._ptr,d=n._size,f=n._datatype||n._data===void 0?n._datatype:n.getDataType();if(o.length!==d.length)throw new Uf(o.length,d.length);if(o[0]!==d[0]||o[1]!==d[1])throw RangeError(`Dimension mismatch. Matrix A (`+o+`) must match Matrix B (`+d+`)`);if(!c)throw Error(`Cannot perform operation on Dense Matrix and Pattern Sparse Matrix`);var p=o[0],m=o[1],h,g=0,_=r;typeof s==`string`&&s===f&&s!==`mixed`&&(h=s,g=t.convert(0,h),_=t.find(r,[h,h]));for(var v=[],y=0;y<p;y++)v[y]=[];for(var b=[],x=[],S=0;S<m;S++){for(var C=S+1,w=u[S],T=u[S+1],E=w;E<T;E++){var D=l[E];b[D]=i?_(c[E],a[D][S]):_(a[D][S],c[E]),x[D]=C}for(var O=0;O<p;O++)x[O]===C?v[O][S]=b[O]:v[O][S]=i?_(g,a[O][S]):_(a[O][S],g)}return e.createDenseMatrix({data:v,size:[p,m],datatype:s===e._datatype&&f===n._datatype?h:void 0})}})})),K_,q_,J_,Y_=e((()=>{X(),Wf(),K_=`matAlgo05xSfSf`,q_=[`typed`,`equalScalar`],J_=Y(K_,q_,e=>{var{typed:t,equalScalar:n}=e;return function(e,r,i){var a=e._values,o=e._index,s=e._ptr,c=e._size,l=e._datatype||e._data===void 0?e._datatype:e.getDataType(),u=r._values,d=r._index,f=r._ptr,p=r._size,m=r._datatype||r._data===void 0?r._datatype:r.getDataType();if(c.length!==p.length)throw new Uf(c.length,p.length);if(c[0]!==p[0]||c[1]!==p[1])throw RangeError(`Dimension mismatch. Matrix A (`+c+`) must match Matrix B (`+p+`)`);var h=c[0],g=c[1],_,v=n,y=0,b=i;typeof l==`string`&&l===m&&l!==`mixed`&&(_=l,v=t.find(n,[_,_]),y=t.convert(0,_),b=t.find(i,[_,_]));var x=a&&u?[]:void 0,S=[],C=[],w=x?[]:void 0,T=x?[]:void 0,E=[],D=[],O,k,A,j;for(k=0;k<g;k++){C[k]=S.length;var M=k+1;for(A=s[k],j=s[k+1];A<j;A++)O=o[A],S.push(O),E[O]=M,w&&(w[O]=a[A]);for(A=f[k],j=f[k+1];A<j;A++)O=d[A],E[O]!==M&&S.push(O),D[O]=M,T&&(T[O]=u[A]);if(x)for(A=C[k];A<S.length;){O=S[A];var N=E[O],P=D[O];if(N===M||P===M){var F=N===M?w[O]:y,I=P===M?T[O]:y,L=b(F,I);v(L,y)?S.splice(A,1):(x.push(L),A++)}}}return C[g]=S.length,e.createSparseMatrix({values:x,index:S,ptr:C,size:[h,g],datatype:l===e._datatype&&m===r._datatype?_:void 0})}})})),X_,Z_,Q_,$_=e((()=>{X(),Wf(),X_=`matAlgo13xDD`,Z_=[`typed`],Q_=Y(X_,Z_,e=>{var{typed:t}=e;return function(e,r,i){var a=e._data,o=e._size,s=e._datatype,c=r._data,l=r._size,u=r._datatype,d=[];if(o.length!==l.length)throw new Uf(o.length,l.length);for(var f=0;f<o.length;f++){if(o[f]!==l[f])throw RangeError(`Dimension mismatch. Matrix A (`+o+`) must match Matrix B (`+l+`)`);d[f]=o[f]}var p,m=i;typeof s==`string`&&s===u&&(p=s,m=t.find(i,[p,p]));var h=d.length>0?n(m,0,d,d[0],a,c):[];return e.createDenseMatrix({data:h,size:d,datatype:p})};function n(e,t,r,i,a,o){var s=[];if(t===r.length-1)for(var c=0;c<i;c++)s[c]=e(a[c],o[c]);else for(var l=0;l<i;l++)s[l]=n(e,t+1,r,r[t+1],a[l],o[l]);return s}})}));function ev(e,t){if(eu(e.size(),t.size()))return[e,t];var n=yp(e.size(),t.size());return[e,t].map(e=>Wue(e,n))}function Wue(e,t){return eu(e.size(),t)?e:e.create(xp(e.valueOf(),t),e.datatype())}var Gue=e((()=>{Tp(),ru()})),tv,nv,rv,iv=e((()=>{X(),ru(),$_(),p_(),Gue(),tv=`matrixAlgorithmSuite`,nv=[`typed`,`matrix`],rv=Y(tv,nv,e=>{var{typed:t,matrix:n}=e,r=Q_({typed:t}),i=f_({typed:t});return function(e){var a=e.elop,o=e.SD||e.DS,s;a?(s={"DenseMatrix, DenseMatrix":(e,t)=>r(...ev(e,t),a),"Array, Array":(e,t)=>r(...ev(n(e),n(t)),a).valueOf(),"Array, DenseMatrix":(e,t)=>r(...ev(n(e),t),a),"DenseMatrix, Array":(e,t)=>r(...ev(e,n(t)),a)},e.SS&&(s[`SparseMatrix, SparseMatrix`]=(t,n)=>e.SS(...ev(t,n),a,!1)),e.DS&&(s[`DenseMatrix, SparseMatrix`]=(t,n)=>e.DS(...ev(t,n),a,!1),s[`Array, SparseMatrix`]=(t,r)=>e.DS(...ev(n(t),r),a,!1)),o&&(s[`SparseMatrix, DenseMatrix`]=(e,t)=>o(...ev(t,e),a,!0),s[`SparseMatrix, Array`]=(e,t)=>o(...ev(n(t),e),a,!0))):(s={"DenseMatrix, DenseMatrix":t.referToSelf(e=>(t,n)=>r(...ev(t,n),e)),"Array, Array":t.referToSelf(e=>(t,i)=>r(...ev(n(t),n(i)),e).valueOf()),"Array, DenseMatrix":t.referToSelf(e=>(t,i)=>r(...ev(n(t),i),e)),"DenseMatrix, Array":t.referToSelf(e=>(t,i)=>r(...ev(t,n(i)),e))},e.SS&&(s[`SparseMatrix, SparseMatrix`]=t.referToSelf(t=>(n,r)=>
2590e.SS(...ev(n,r),t,!1))),e.DS&&(s[`DenseMatrix, SparseMatrix`]=t.referToSelf(t=>(n,r)=>e.DS(...ev(n,r),t,!1)),s[`Array, SparseMatrix`]=t.referToSelf(t=>(r,i)=>e.DS(...ev(n(r),i),t,!1))),o&&(s[`SparseMatrix, DenseMatrix`]=t.referToSelf(e=>(t,n)=>o(...ev(n,t),e,!0)),s[`SparseMatrix, Array`]=t.referToSelf(e=>(t,r)=>o(...ev(n(r),t),e,!0))));var c=e.scalar||`any`;(e.Ds||e.Ss)&&(a?(s[`DenseMatrix,`+c]=(e,t)=>i(e,t,a,!1),s[c+`, DenseMatrix`]=(e,t)=>i(t,e,a,!0),s[`Array,`+c]=(e,t)=>i(n(e),t,a,!1).valueOf(),s[c+`, Array`]=(e,t)=>i(n(t),e,a,!0).valueOf()):(s[`DenseMatrix,`+c]=t.referToSelf(e=>(t,n)=>i(t,n,e,!1)),s[c+`, DenseMatrix`]=t.referToSelf(e=>(t,n)=>i(n,t,e,!0)),s[`Array,`+c]=t.referToSelf(e=>(t,r)=>i(n(t),r,e,!1).valueOf()),s[c+`, Array`]=t.referToSelf(e=>(t,r)=>i(n(r),t,e,!0).valueOf())));var l=e.sS===void 0?e.Ss:e.sS;return a?(e.Ss&&(s[`SparseMatrix,`+c]=(t,n)=>e.Ss(t,n,a,!1)),l&&(s[c+`, SparseMatrix`]=(e,t)=>l(t,e,a,!0))):(e.Ss&&(s[`SparseMatrix,`+c]=t.referToSelf(t=>(n,r)=>e.Ss(n,r,t,!1))),l&&(s[c+`, SparseMatrix`]=t.referToSelf(e=>(t,n)=>l(n,t,e,!0)))),a&&a.signatures&&ece(s,a.signatures),s}})})),av,ov,sv,cv=e((()=>{X(),L_(),V_(),G_(),Y_(),a_(),l_(),iv(),av=`mod`,ov=[`typed`,`config`,`round`,`matrix`,`equalScalar`,`zeros`,`DenseMatrix`,`concat`],sv=Y(av,ov,e=>{var{typed:t,config:n,round:r,matrix:i,equalScalar:a,zeros:o,DenseMatrix:s,concat:c}=e,l=I_({typed:t,config:n,round:r,matrix:i,equalScalar:a,zeros:o,DenseMatrix:s}),u=B_({typed:t,equalScalar:a}),d=W_({typed:t}),f=J_({typed:t,equalScalar:a}),p=i_({typed:t,equalScalar:a}),m=c_({typed:t,DenseMatrix:s}),h=rv({typed:t,matrix:i,concat:c});return t(av,{"number, number":g,"BigNumber, BigNumber":function(e,t){return t.isZero()?e:e.sub(t.mul(l(e.div(t))))},"bigint, bigint":function(e,t){if(t===0n)return e;if(e<0){var n=e%t;return n===0n?n:n+t}return e%t},"Fraction, Fraction":function(e,t){return t.equals(0)?e:e.sub(t.mul(l(e.div(t))))}},h({SS:f,DS:d,SD:u,Ss:p,sS:m}));function g(e,t){return t===0?e:e-t*l(e/t)}})})),lv,uv,dv,fv=e((()=>{X(),Wf(),lv=`matAlgo01xDSid`,uv=[`typed`],dv=Y(lv,uv,e=>{var{typed:t}=e;return function(e,n,r,i){var a=e._data,o=e._size,s=e._datatype||e.getDataType(),c=n._values,l=n._index,u=n._ptr,d=n._size,f=n._datatype||n._data===void 0?n._datatype:n.getDataType();if(o.length!==d.length)throw new Uf(o.length,d.length);if(o[0]!==d[0]||o[1]!==d[1])throw RangeError(`Dimension mismatch. Matrix A (`+o+`) must match Matrix B (`+d+`)`);if(!c)throw Error(`Cannot perform operation on Dense Matrix and Pattern Sparse Matrix`);var p=o[0],m=o[1],h=typeof s==`string`&&s!==`mixed`&&s===f?s:void 0,g=h?t.find(r,[h,h]):r,_,v,y=[];for(_=0;_<p;_++)y[_]=[];var b=[],x=[];for(v=0;v<m;v++){for(var S=v+1,C=u[v],w=u[v+1],T=C;T<w;T++)_=l[T],b[_]=i?g(c[T],a[_][v]):g(a[_][v],c[T]),x[_]=S;for(_=0;_<p;_++)x[_]===S?y[_][v]=b[_]:y[_][v]=a[_][v]}return e.createDenseMatrix({data:y,size:[p,m],datatype:s===e._datatype&&f===n._datatype?h:void 0})}})})),pv,mv,hv,gv=e((()=>{X(),Wf(),pv=`matAlgo04xSidSid`,mv=[`typed`,`equalScalar`],hv=Y(pv,mv,e=>{var{typed:t,equalScalar:n}=e;return function(e,r,i){var a=e._values,o=e._index,s=e._ptr,c=e._size,l=e._datatype||e._data===void 0?e._datatype:e.getDataType(),u=r._values,d=r._index,f=r._ptr,p=r._size,m=r._datatype||r._data===void 0?r._datatype:r.getDataType();if(c.length!==p.length)throw new Uf(c.length,p.length);if(c[0]!==p[0]||c[1]!==p[1])throw RangeError(`Dimension mismatch. Matrix A (`+c+`) must match Matrix B (`+p+`)`);var h=c[0],g=c[1],_,v=n,y=0,b=i;typeof l==`string`&&l===m&&l!==`mixed`&&(_=l,v=t.find(n,[_,_]),y=t.convert(0,_),b=t.find(i,[_,_]));var x=a&&u?[]:void 0,S=[],C=[],w=a&&u?[]:void 0,T=a&&u?[]:void 0,E=[],D=[],O,k,A,j,M;for(k=0;k<g;k++){C[k]=S.length;var N=k+1;for(j=s[k],M=s[k+1],A=j;A<M;A++)O=o[A],S.push(O),E[O]=N,w&&(w[O]=a[A]);for(j=f[k],M=f[k+1],A=j;A<M;A++)if(O=d[A],E[O]===N){if(w){var P=b(w[O],u[A]);v(P,y)?E[O]=null:w[O]=P}}else S.push(O),D[O]=N,T&&(T[O]=u[A]);if(w&&T)for(A=C[k];A<S.length;)O=S[A],E[O]===N?(x[A]=w[O],A++):D[O]===N?(x[A]=T[O],A++):S.splice(A,1)}return C[g]=S.length,e.createSparseMatrix({values:x,index:S,ptr:C,size:[h,g],datatype:l===e._datatype&&m===r._datatype?_:void 0})}})})),_v,vv,yv,bv=e((()=>{X(),_v=`matAlgo10xSids`,vv=[`typed`,`DenseMatrix`],yv=Y(_v,vv,e=>{var{typed:t,DenseMatrix:n}=e;return function(e,r,i,a){var o=e._values,s=e._index,c=e._ptr,l=e._size,u=e._datatype;if(!o)throw Error(`Cannot perform operation on Pattern Sparse Matrix and Scalar value`);var d=l[0],f=l[1],p,m=i;typeof u==`string`&&(p=u,r=t.convert(r,p),m=t.find(i,[p,p]));for(var h=[],g=[],_=[],v=0;v<f;v++){for(var y=v+1,b=c[v],x=c[v+1],S=b;S<x;S++){var C=s[S];g[C]=o[S],_[C]=y}for(var w=0;w<d;w++)v===0&&(h[w]=[]),_[w]===y?h[w][v]=a?m(r,g[w]):m(g[w],r):h[w][v]=r}return new n({data:h,size:[d,f],datatype:p})}})}));function xv(e,t,n,r){if(!(this instanceof xv))throw SyntaxError(`Constructor must be called with the new operator`);this.fn=e,this.count=t,this.min=n,this.max=r,this.message=`Wrong number of arguments in function `+e+` (`+t+` provided, `+n+(r==null?``:`-`+r)+` expected)`,this.stack=Error().stack}var Sv=e((()=>{xv.prototype=Error(),xv.prototype.constructor=Error,xv.prototype.name=`ArgumentsError`,xv.prototype.isArgumentsError=!0}));
2590function Cv(e){return!e.some(e=>Array.isArray(e))}var wv,Tv,Ev,Dv,Ov,Kue=e((()=>{Pu(),X(),cv(),fv(),gv(),bv(),iv(),Sv(),wv=`gcd`,Tv=[`typed`,`config`,`round`,`matrix`,`equalScalar`,`zeros`,`BigNumber`,`DenseMatrix`,`concat`],Ev=`number | BigNumber | Fraction | Matrix | Array`,Dv=`${Ev}, ${Ev}, ...${Ev}`,Ov=Y(wv,Tv,e=>{var{typed:t,matrix:n,config:r,round:i,equalScalar:a,zeros:o,BigNumber:s,DenseMatrix:c,concat:l}=e,u=sv({typed:t,config:r,round:i,matrix:n,equalScalar:a,zeros:o,DenseMatrix:c,concat:l}),d=dv({typed:t}),f=hv({typed:t,equalScalar:a}),p=yv({typed:t,DenseMatrix:c}),m=rv({typed:t,matrix:n,concat:l});return t(wv,{"number, number":h,"BigNumber, BigNumber":g,"Fraction, Fraction":(e,t)=>e.gcd(t)},m({SS:f,DS:d,Ss:p}),{[Dv]:t.referToSelf(e=>(t,n,r)=>{for(var i=e(t,n),a=0;a<r.length;a++)i=e(i,r[a]);return i}),Array:t.referToSelf(e=>t=>{if(t.length===1&&Array.isArray(t[0])&&Cv(t[0]))return e(...t[0]);if(Cv(t))return e(...t);throw new xv(`gcd() supports only 1d matrices!`)}),Matrix:t.referToSelf(e=>t=>e(t.toArray()))});function h(e,t){if(!lu(e)||!lu(t))throw Error(`Parameters in function gcd must be integer numbers`);for(var n;t!==0;)n=u(e,t),e=t,t=n;return e<0?-e:e}function g(e,t){if(!e.isInt()||!t.isInt())throw Error(`Parameters in function gcd must be integer numbers`);for(var n=new s(0);!t.isZero();){var r=u(e,t);e=t,t=r}return e.lt(n)?e.neg():e}})})),kv,Av,jv,Mv=e((()=>{X(),Wf(),Wp(),kv=`matAlgo06xS0S0`,Av=[`typed`,`equalScalar`],jv=Y(kv,Av,e=>{var{typed:t,equalScalar:n}=e;return function(e,r,i){var a=e._values,o=e._size,s=e._datatype||e._data===void 0?e._datatype:e.getDataType(),c=r._values,l=r._size,u=r._datatype||r._data===void 0?r._datatype:r.getDataType();if(o.length!==l.length)throw new Uf(o.length,l.length);if(o[0]!==l[0]||o[1]!==l[1])throw RangeError(`Dimension mismatch. Matrix A (`+o+`) must match Matrix B (`+l+`)`);var d=o[0],f=o[1],p,m=n,h=0,g=i;typeof s==`string`&&s===u&&s!==`mixed`&&(p=s,m=t.find(n,[p,p]),h=t.convert(0,p),g=t.find(i,[p,p]));for(var _=a&&c?[]:void 0,v=[],y=[],b=_?[]:void 0,x=[],S=[],C=0;C<f;C++){y[C]=v.length;var w=C+1;if(Up(e,C,x,b,S,w,v,g),Up(r,C,x,b,S,w,v,g),b)for(var T=y[C];T<v.length;){var E=v[T];if(S[E]===w){var D=b[E];m(D,h)?v.splice(T,1):(_.push(D),T++)}else v.splice(T,1)}else for(var O=y[C];O<v.length;)S[v[O]]===w?O++:v.splice(O,1)}return y[f]=v.length,e.createSparseMatrix({values:_,index:v,ptr:y,size:[d,f],datatype:s===e._datatype&&u===r._datatype?p:void 0})}})})),Nv,Pv,Fv,que=e((()=>{X(),V_(),Mv(),a_(),iv(),ph(),Nv=`lcm`,Pv=[`typed`,`matrix`,`equalScalar`,`concat`],Fv=Y(Nv,Pv,e=>{var{typed:t,matrix:n,equalScalar:r,concat:i}=e,a=B_({typed:t,equalScalar:r}),o=jv({typed:t,equalScalar:r}),s=i_({typed:t,equalScalar:r}),c=rv({typed:t,matrix:n,concat:i}),l=`number | BigNumber | Fraction | Matrix | Array`,u={};return u[`${l}, ${l}, ...${l}`]=t.referToSelf(e=>(t,n,r)=>{for(var i=e(t,n),a=0;a<r.length;a++)i=e(i,r[a]);return i}),t(Nv,{"number, number":im,"BigNumber, BigNumber":d,"Fraction, Fraction":(e,t)=>e.lcm(t)},c({SS:o,DS:a,Ss:s}),u);function d(e,t){if(!e.isInt()||!t.isInt())throw Error(`Parameters in function lcm must be integer numbers`);if(e.isZero())return e;if(t.isZero())return t;for(var n=e.times(t);!t.isZero();){var r=t;t=e.mod(r),e=r}return n.div(e).abs()}})}));function Iv(e,t,n,r){return function(i){if(i>0||n.predictable){if(i<=0)return NaN;var a=i.toString(16),o=a.substring(0,15);return e*(a.length-o.length)+t(Number(`0x`+o))}return r(i.toNumber())}}var Lv=e((()=>{})),Rv,zv,Bv,Vv,Jue=e((()=>{ph(),Lv(),Wp(),X(),Rv=`log10`,zv=[`typed`,`config`,`Complex`],Bv=om(16),Vv=Y(Rv,zv,e=>{var{typed:t,config:n,Complex:r}=e;function i(e){return e.log().div(Math.LN10)}function a(e){return i(new r(e,0))}return t(Rv,{number:function(e){return e>=0||n.predictable?om(e):a(e)},bigint:Iv(Bv,om,n,a),Complex:i,BigNumber:function(e){return!e.isNegative()||n.predictable?e.log():a(e.toNumber())},"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),Hv,Uv,Wv,Yue=e((()=>{ph(),Lv(),Wp(),X(),Hv=`log2`,Uv=[`typed`,`config`,`Complex`],Wv=Y(Hv,Uv,e=>{var{typed:t,config:n,Complex:r}=e;function i(e){return a(new r(e,0))}return t(Hv,{number:function(e){return e>=0||n.predictable?sm(e):i(e)},bigint:Iv(4,sm,n,i),Complex:a,BigNumber:function(e){return!e.isNegative()||n.predictable?e.log(2):i(e.toNumber())},"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))});function a(e){var t=Math.sqrt(e.re*e.re+e.im*e.im);return new r(Math.log2?Math.log2(t):Math.log(t)/Math.LN2,Math.atan2(e.im,e.re)/Math.LN2)}})})),Gv,Kv,qv,Xue=e((()=>{X(),ph(),Gv=`multiplyScalar`,Kv=[`typed`],qv=Y(Gv,Kv,e=>{var{typed:t}=e;return t(`multiplyScalar`,{"number, number":Zp,"Complex, Complex":function(e,t){return e.mul(t)},"BigNumber, BigNumber":function(e,t){return e.times(t)},"bigint, bigint":function(e,t){return e*t},"Fraction, Fraction":function(e,t){return e.mul(t)},"number | Fraction | BigNumber | Complex, Unit":(e,t)=>t.multiply(e),"Unit, number | Fraction | BigNumber | Complex | Unit":(e,t)=>e.multiply(t)})})})),Jv,Yv,Xv,Zue=e((()=>{X(),Ql(),Tp(),a_(),p_(),Jv=`multiply`,Yv=[`typed`,`matrix`,`addScalar`,`multiplyScalar`,`equalScalar`,`dot`],Xv=Y(Jv,Yv,e=>{var{typed:t,matrix:n,addScalar:r,multiplyScalar:i,equalScalar:a,dot:o}=e,s=i_({typed:t,equalScalar:a}),c=f_({typed:t});function l(e,t){switch(e.length){case 1:switch(t.length){case 1:if(e[0]!==t[0])throw RangeError(`Dimension mismatch in multiplication. Vectors must have the same length`);break;case 2:if(e[0]!==t[0])throw RangeError(`Dimension mismatch in multiplication. Vector length (`+e[0]+`) must match Matrix rows (`+t[0]+`)`);break;default:throw Error(`Can only multiply a 1 or 2 dimensional matrix (Matrix B has `+t.length+` dimensions)`)}break;case 2:switch(t.length){case 1:if(e[1]!==t[0])throw RangeError(`Dimension mismatch in multiplication. Matrix columns (`+e[1]+`) must match Vector length (`+t[0]+`)`);break;case 2:if(e[1]!==t[0])throw RangeError(`Dimension mismatch in multiplication. Matrix A columns (`+e[1]+`) must match Matrix B rows (`+t[0]+`)`);break;default:throw Error(`Can only multiply a 1 or 2 dimensional matrix (Matrix B has `+t.length+` dimensions)`)}break;default:throw Error(`Can only multiply a 1 or 2 dimensional matrix (Matrix A has `+e.length+` dimensions)`)}}function u(e,t,n){if(n===0)throw Error(`Cannot multiply two empty vectors`);return o(e,t)}function d(e,t){if(t.storage()!==`dense`)throw Error(`Support for SparseMatrix not implemented`);return f(e,t)}function f(e,n){var a=e._data,o=e._size,s=e._datatype||e.getDataType(),c=n._data,l=n._size,u=n._datatype||n.getDataType(),d=o[0],f=l[1],p,m=r,h=i;s&&u&&s===u&&typeof s==`string`&&s!==`mixed`&&(p=s,m=t.find(r,[p,p]),h=t.find(i,[p,p]));for(var g=[],_=0;_<f;_++){for(var v=h(a[0],c[0][_]),y=1;y<d;y++)v=m(v,h(a[y],c[y][_]));g[_]=v}return e.createDenseMatrix({data:g,size:[f],datatype:s===e._datatype&&u===n._datatype?p:void 0})}
vendor: 7,079 bytes, line 2590
2590var p=t(`_multiplyMatrixVector`,{"DenseMatrix, any":h,"SparseMatrix, any":v}),m=t(`_multiplyMatrixMatrix`,{"DenseMatrix, DenseMatrix":g,"DenseMatrix, SparseMatrix":_,"SparseMatrix, DenseMatrix":y,"SparseMatrix, SparseMatrix":b});function h(e,n){var a=e._data,o=e._size,s=e._datatype||e.getDataType(),c=n._data,l=n._datatype||n.getDataType(),u=o[0],d=o[1],f,p=r,m=i;s&&l&&s===l&&typeof s==`string`&&s!==`mixed`&&(f=s,p=t.find(r,[f,f]),m=t.find(i,[f,f]));for(var h=[],g=0;g<u;g++){for(var _=a[g],v=m(_[0],c[0]),y=1;y<d;y++)v=p(v,m(_[y],c[y]));h[g]=v}return e.createDenseMatrix({data:h,size:[u],datatype:s===e._datatype&&l===n._datatype?f:void 0})}function g(e,n){var a=e._data,o=e._size,s=e._datatype||e.getDataType(),c=n._data,l=n._size,u=n._datatype||n.getDataType(),d=o[0],f=o[1],p=l[1],m,h=r,g=i;s&&u&&s===u&&typeof s==`string`&&s!==`mixed`&&s!==`mixed`&&(m=s,h=t.find(r,[m,m]),g=t.find(i,[m,m]));for(var _=[],v=0;v<d;v++){var y=a[v];_[v]=[];for(var b=0;b<p;b++){for(var x=g(y[0],c[0][b]),S=1;S<f;S++)x=h(x,g(y[S],c[S][b]));_[v][b]=x}}return e.createDenseMatrix({data:_,size:[d,p],datatype:s===e._datatype&&u===n._datatype?m:void 0})}function _(e,n){var o=e._data,s=e._size,c=e._datatype||e.getDataType(),l=n._values,u=n._index,d=n._ptr,f=n._size,p=n._datatype||n._data===void 0?n._datatype:n.getDataType();if(!l)throw Error(`Cannot multiply Dense Matrix times Pattern only Matrix`);var m=s[0],h=f[1],g,_=r,v=i,y=a,b=0;c&&p&&c===p&&typeof c==`string`&&c!==`mixed`&&(g=c,_=t.find(r,[g,g]),v=t.find(i,[g,g]),y=t.find(a,[g,g]),b=t.convert(0,g));for(var x=[],S=[],C=[],w=n.createSparseMatrix({values:x,index:S,ptr:C,size:[m,h],datatype:c===e._datatype&&p===n._datatype?g:void 0}),T=0;T<h;T++){C[T]=S.length;var E=d[T],D=d[T+1];if(D>E)for(var O=0,k=0;k<m;k++){for(var A=k+1,j=void 0,M=E;M<D;M++){var N=u[M];O===A?j=_(j,v(o[k][N],l[M])):(j=v(o[k][N],l[M]),O=A)}O===A&&!y(j,b)&&(S.push(k),x.push(j))}}return C[h]=S.length,w}function v(e,n){var o=e._values,s=e._index,c=e._ptr,l=e._datatype||e._data===void 0?e._datatype:e.getDataType();if(!o)throw Error(`Cannot multiply Pattern only Matrix times Dense Matrix`);var u=n._data,d=n._datatype||n.getDataType(),f=e._size[0],p=n._size[0],m=[],h=[],g=[],_,v=r,y=i,b=a,x=0;l&&d&&l===d&&typeof l==`string`&&l!==`mixed`&&(_=l,v=t.find(r,[_,_]),y=t.find(i,[_,_]),b=t.find(a,[_,_]),x=t.convert(0,_));var S=[],C=[];g[0]=0;for(var w=0;w<p;w++){var T=u[w];if(!b(T,x))for(var E=c[w],D=c[w+1],O=E;O<D;O++){var k=s[O];C[k]?S[k]=v(S[k],y(T,o[O])):(C[k]=!0,h.push(k),S[k]=y(T,o[O]))}}for(var A=h.length,j=0;j<A;j++)m[j]=S[h[j]];return g[1]=h.length,e.createSparseMatrix({values:m,index:h,ptr:g,size:[f,1],datatype:l===e._datatype&&d===n._datatype?_:void 0})}function y(e,n){var o=e._values,s=e._index,c=e._ptr,l=e._datatype||e._data===void 0?e._datatype:e.getDataType();if(!o)throw Error(`Cannot multiply Pattern only Matrix times Dense Matrix`);var u=n._data,d=n._datatype||n.getDataType(),f=e._size[0],p=n._size[0],m=n._size[1],h,g=r,_=i,v=a,y=0;l&&d&&l===d&&typeof l==`string`&&l!==`mixed`&&(h=l,g=t.find(r,[h,h]),_=t.find(i,[h,h]),v=t.find(a,[h,h]),y=t.convert(0,h));for(var b=[],x=[],S=[],C=e.createSparseMatrix({values:b,index:x,ptr:S,size:[f,m],datatype:l===e._datatype&&d===n._datatype?h:void 0}),w=[],T=[],E=0;E<m;E++){S[E]=x.length;for(var D=E+1,O=0;O<p;O++){var k=u[O][E];if(!v(k,y))for(var A=c[O],j=c[O+1],M=A;M<j;M++){var N=s[M];T[N]===D?w[N]=g(w[N],_(k,o[M])):(T[N]=D,x.push(N),w[N]=_(k,o[M]))}}for(var P=S[E],F=x.length,I=P;I<F;I++)b[I]=w[x[I]]}return S[m]=x.length,C}function b(e,n){var a=e._values,o=e._index,s=e._ptr,c=e._datatype||e._data===void 0?e._datatype:e.getDataType(),l=n._values,u=n._index,d=n._ptr,f=n._datatype||n._data===void 0?n._datatype:n.getDataType(),p=e._size[0],m=n._size[1],h=a&&l,g,_=r,v=i;c&&f&&c===f&&typeof c==`string`&&c!==`mixed`&&(g=c,_=t.find(r,[g,g]),v=t.find(i,[g,g]));for(var y=h?[]:void 0,b=[],x=[],S=e.createSparseMatrix({values:y,index:b,ptr:x,size:[p,m],datatype:c===e._datatype&&f===n._datatype?g:void 0}),C=h?[]:void 0,w=[],T,E,D,O,k,A,j,M,N=0;N<m;N++){x[N]=b.length;var P=N+1;for(k=d[N],A=d[N+1],O=k;O<A;O++)if(M=u[O],h)for(E=s[M],D=s[M+1],T=E;T<D;T++)j=o[T],w[j]===P?C[j]=_(C[j],v(l[O],a[T])):(w[j]=P,b.push(j),C[j]=v(l[O],a[T]));else for(E=s[M],D=s[M+1],T=E;T<D;T++)j=o[T],w[j]!==P&&(w[j]=P,b.push(j));if(h)for(var F=x[N],I=b.length,L=F;L<I;L++)y[L]=C[b[L]]}return x[m]=b.length,S}return t(Jv,i,{"Array, Array":t.referTo(`Matrix, Matrix`,e=>(t,r)=>{l(qf(t),qf(r));var i=e(n(t),n(r));return Dl(i)?i.valueOf():i}),"Matrix, Matrix":function(e,t){var n=e.size(),r=t.size();return l(n,r),n.length===1?r.length===1?u(e,t,n[0]):d(e,t):r.length===1?p(e,t):m(e,t)},"Matrix, Array":t.referTo(`Matrix,Matrix`,e=>(t,r)=>e(t,n(r))),"Array, Matrix":t.referToSelf(e=>(t,r)=>e(n(t,r.storage()),r)),"SparseMatrix, any":function(e,t){return s(e,t,i,!1)},"DenseMatrix, any":function(e,t){return c(e,t,i,!1)},"any, SparseMatrix":function(e,t){return s(t,e,i,!0)},"any, DenseMatrix":function(e,t){return c(t,e,i,!0)},"Array, any":function(e,t){return c(n(e),t,i,!1).valueOf()},"any, Array":function(e,t){return c(n(t),e,i,!0).valueOf()},"any, any":i,"any, any, ...any":t.referToSelf(e=>(t,n,r)=>{for(var i=e(t,n),a=0;a<r.length;a++)i=e(i,r[a]);return i})})})})),Zv,Qv,$v,Que=e((()=>{X(),fv(),V_(),Mv(),a_(),iv(),ph(),Zv=`nthRoot`,Qv=[`typed`,`matrix`,`equalScalar`,`BigNumber`,`concat`],$v=Y(Zv,Qv,e=>{var{typed:t,matrix:n,equalScalar:r,BigNumber:i,concat:a}=e,o=dv({typed:t}),s=B_({typed:t,equalScalar:r}),c=jv({typed:t,equalScalar:r}),l=i_({typed:t,equalScalar:r}),u=rv({typed:t,matrix:n,concat:a});function d(){throw Error(`Complex number not supported in function nthRoot. Use nthRoots instead.`)}return t(Zv,{number:cm,"number, number":cm,BigNumber:e=>f(e,new i(2)),"BigNumber, BigNumber":f,Complex:d,"Complex, number":d,Array:t.referTo(`DenseMatrix,number`,e=>t=>e(n(t),2).valueOf()),DenseMatrix:t.referTo(`DenseMatrix,number`,e=>t=>e(t,2)),SparseMatrix:t.referTo(`SparseMatrix,number`,e=>t=>e(t,2)),"SparseMatrix, SparseMatrix":t.referToSelf(e=>(t,n)=>{if(n.density()===1)return c(t,n,e);throw Error(`Root must be non-zero`)}),"DenseMatrix, SparseMatrix":t.referToSelf(e=>(t,n)=>{if(n.density()===1)return o(t,n,e,!1);throw Error(`Root must be non-zero`)}),"Array, SparseMatrix":t.referTo(`DenseMatrix,SparseMatrix`,e=>(t,r)=>e(n(t),r)),"number | BigNumber, SparseMatrix":t.referToSelf(e=>(t,n)=>{if(n.density()===1)return l(n,t,e,!0);throw Error(`Root must be non-zero`)})},u({scalar:`number | BigNumber`,SD:s,Ss:l,sS:!1}));function f(e,t){var n=i.precision,r=i.clone({precision:n+2}),a=new i(0),o=new r(1),s=t.isNegative();if(s&&(t=t.neg()),t.isZero())throw Error(`Root must be non-zero`);if(e.isNegative()&&!t.abs().mod(2).equals(1))throw Error(`Root must be odd when a is negative.`);if(e.isZero())return s?new r(1/0):0;if(!e.isFinite())return s?a:e;var c=e.abs().pow(o.div(t));return c=e.isNeg()?c.neg():c,new i((s?o.div(c):c).toPrecision(n))}})})),ey,ty,ny,$ue=e((()=>{X(),Wp(),ph(),ey=`sign`,ty=[`typed`,`BigNumber`,`Fraction`,`complex`],ny=Y(ey,ty,e=>{var{typed:t,BigNumber:n,complex:r,Fraction:i}=e;
2590return t(ey,{number:lm,Complex:function(e){return e.im===0?r(lm(e.re)):e.sign()},BigNumber:function(e){return new n(e.cmp(0))},bigint:function(e){return e>0n?1n:e<0n?-1n:0n},Fraction:function(e){return e.n===0n?new i(0):new i(e.s)},"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e,!0)),Unit:t.referToSelf(e=>n=>{if(!n._isDerived()&&n.units[0].unit.offset!==0)throw TypeError(`sign is ambiguous for units with offset`);return t.find(e,n.valueType())(n.value)})})})})),ry,iy,ay,ede=e((()=>{X(),ry=`sqrt`,iy=[`config`,`typed`,`Complex`],ay=Y(ry,iy,e=>{var{config:t,typed:n,Complex:r}=e;return n(`sqrt`,{number:i,Complex:function(e){return e.sqrt()},BigNumber:function(e){return!e.isNegative()||t.predictable?e.sqrt():i(e.toNumber())},Unit:function(e){return e.pow(.5)}});function i(e){return isNaN(e)?NaN:e>=0||t.predictable?Math.sqrt(e):new r(e,0).sqrt()}})})),oy,sy,cy,tde=e((()=>{X(),ph(),oy=`square`,sy=[`typed`],cy=Y(oy,sy,e=>{var{typed:t}=e;return t(oy,{number:um,Complex:function(e){return e.mul(e)},BigNumber:function(e){return e.times(e)},bigint:function(e){return e*e},Fraction:function(e){return e.mul(e)},Unit:function(e){return e.pow(2)}})})})),ly,uy,dy,nde=e((()=>{X(),fv(),G_(),Y_(),bv(),l_(),iv(),ly=`subtract`,uy=[`typed`,`matrix`,`equalScalar`,`subtractScalar`,`unaryMinus`,`DenseMatrix`,`concat`],dy=Y(ly,uy,e=>{var{typed:t,matrix:n,equalScalar:r,subtractScalar:i,unaryMinus:a,DenseMatrix:o,concat:s}=e,c=dv({typed:t}),l=W_({typed:t}),u=J_({typed:t,equalScalar:r}),d=yv({typed:t,DenseMatrix:o}),f=c_({typed:t,DenseMatrix:o}),p=rv({typed:t,matrix:n,concat:s});return t(ly,{"any, any":i},p({elop:i,SS:u,DS:c,SD:l,Ss:f,sS:d}))})})),fy,py,my,rde=e((()=>{X(),ph(),fy=`xgcd`,py=[`typed`,`config`,`matrix`,`BigNumber`],my=Y(fy,py,e=>{var{typed:t,config:n,matrix:r,BigNumber:i}=e;return t(fy,{"number, number":function(e,t){var i=dm(e,t);return n.matrix===`Array`?i:r(i)},"BigNumber, BigNumber":a});function a(e,t){var a,o,s,c=new i(0),l=new i(1),u=c,d=l,f=l,p=c;if(!e.isInt()||!t.isInt())throw Error(`Parameters in function xgcd must be integer numbers`);for(;!t.isZero();)o=e.div(t).floor(),s=e.mod(t),a=u,u=d.minus(o.times(u)),d=a,a=f,f=p.minus(o.times(f)),p=a,e=t,t=s;var m=e.lt(c)?[e.neg(),d.neg(),p.neg()]:[e,e.isZero()?0:d,p];return n.matrix===`Array`?m:r(m)}})})),hy,gy,_y,ide=e((()=>{X(),hy=`invmod`,gy=[`typed`,`config`,`BigNumber`,`xgcd`,`equal`,`smaller`,`mod`,`add`,`isInteger`],_y=Y(hy,gy,e=>{var{typed:t,config:n,BigNumber:r,xgcd:i,equal:a,smaller:o,mod:s,add:c,isInteger:l}=e;return t(hy,{"number, number":u,"BigNumber, BigNumber":u});function u(e,t){if(!l(e)||!l(t))throw Error(`Parameters in function invmod must be integer numbers`);if(e=s(e,t),a(t,0))throw Error(`Divisor must be non zero`);var n=i(e,t);n=n.valueOf();var[u,d]=n;return a(u,r(1))?(d=s(d,t),o(d,r(0))&&(d=c(d,t)),d):NaN}})})),vy,yy,by,ade=e((()=>{X(),Wf(),vy=`matAlgo09xS0Sf`,yy=[`typed`,`equalScalar`],by=Y(vy,yy,e=>{var{typed:t,equalScalar:n}=e;return function(e,r,i){var a=e._values,o=e._index,s=e._ptr,c=e._size,l=e._datatype||e._data===void 0?e._datatype:e.getDataType(),u=r._values,d=r._index,f=r._ptr,p=r._size,m=r._datatype||r._data===void 0?r._datatype:r.getDataType();if(c.length!==p.length)throw new Uf(c.length,p.length);if(c[0]!==p[0]||c[1]!==p[1])throw RangeError(`Dimension mismatch. Matrix A (`+c+`) must match Matrix B (`+p+`)`);var h=c[0],g=c[1],_,v=n,y=0,b=i;typeof l==`string`&&l===m&&l!==`mixed`&&(_=l,v=t.find(n,[_,_]),y=t.convert(0,_),b=t.find(i,[_,_]));var x=a&&u?[]:void 0,S=[],C=[],w=x?[]:void 0,T=[],E,D,O,k,A;for(D=0;D<g;D++){C[D]=S.length;var j=D+1;if(w)for(k=f[D],A=f[D+1],O=k;O<A;O++)E=d[O],T[E]=j,w[E]=u[O];for(k=s[D],A=s[D+1],O=k;O<A;O++)if(E=o[O],w){var M=T[E]===j?w[E]:y,N=b(a[O],M);v(N,y)||(S.push(E),x.push(N))}else S.push(E)}return C[g]=S.length,e.createSparseMatrix({values:x,index:S,ptr:C,size:[h,g],datatype:l===e._datatype&&m===r._datatype?_:void 0})}})})),xy,ode,Sy,sde=e((()=>{X(),V_(),ade(),a_(),iv(),xy=`dotMultiply`,ode=[`typed`,`matrix`,`equalScalar`,`multiplyScalar`,`concat`],Sy=Y(xy,ode,e=>
2590{var{typed:t,matrix:n,equalScalar:r,multiplyScalar:i,concat:a}=e,o=B_({typed:t,equalScalar:r}),s=by({typed:t,equalScalar:r}),c=i_({typed:t,equalScalar:r});return t(xy,rv({typed:t,matrix:n,concat:a})({elop:i,SS:s,DS:o,Ss:c}))})}));function cde(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw Error(`Integers expected in function bitAnd`);var n=e.constructor;if(e.isNaN()||t.isNaN())return new n(NaN);if(e.isZero()||t.eq(-1)||e.eq(t))return e;if(t.isZero()||e.eq(-1))return t;if(!e.isFinite()||!t.isFinite()){if(!e.isFinite()&&!t.isFinite())return e.isNegative()===t.isNegative()?e:new n(0);if(!e.isFinite())return t.isNegative()?e:e.isNegative()?new n(0):t;if(!t.isFinite())return e.isNegative()?t:t.isNegative()?new n(0):e}return wy(e,t,function(e,t){return e&t})}function Cy(e){if(e.isFinite()&&!e.isInteger())throw Error(`Integer expected in function bitNot`);var t=e.constructor,n=t.precision;t.config({precision:1e9});var r=e.plus(new t(1));return r.s=-r.s||null,t.config({precision:n}),r}function lde(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw Error(`Integers expected in function bitOr`);var n=e.constructor;if(e.isNaN()||t.isNaN())return new n(NaN);var r=new n(-1);return e.isZero()||t.eq(r)||e.eq(t)?t:t.isZero()||e.eq(r)?e:!e.isFinite()||!t.isFinite()?!e.isFinite()&&!e.isNegative()&&t.isNegative()||e.isNegative()&&!t.isNegative()&&!t.isFinite()?r:e.isNegative()&&t.isNegative()?e.isFinite()?e:t:e.isFinite()?t:e:wy(e,t,function(e,t){return e|t})}function wy(e,t,n){var r=e.constructor,i,a,o=+(e.s<0),s=+(t.s<0);if(o){i=Ty(Cy(e));for(var c=0;c<i.length;++c)i[c]^=1}else i=Ty(e);if(s){a=Ty(Cy(t));for(var l=0;l<a.length;++l)a[l]^=1}else a=Ty(t);var u,d,f;i.length<=a.length?(u=i,d=a,f=o):(u=a,d=i,f=s);var p=u.length,m=d.length,h=n(o,s)^1,g=new r(h^1),_=new r(1),v=new r(2),y=r.precision;for(r.config({precision:1e9});p>0;)n(u[--p],d[--m])===h&&(g=g.plus(_)),_=_.times(v);for(;m>0;)n(f,d[--m])===h&&(g=g.plus(_)),_=_.times(v);return r.config({precision:y}),h===0&&(g.s=-g.s),g}function Ty(e){for(var t=e.d,n=t[0]+``,r=1;r<t.length;++r){for(var i=t[r]+``,a=7-i.length;a--;)i=`0`+i;n+=i}for(var o=n.length;n.charAt(o)===`0`;)o--;var s=e.e,c=n.slice(0,o+1||1),l=c.length;if(s>0)if(++s>l)for(s-=l;s--;)c+=`0`;else s<l&&(c=c.slice(0,s)+`.`+c.slice(s));for(var u=[0],d=0;d<c.length;){for(var f=u.length;f--;)u[f]*=10;u[0]+=parseInt(c.charAt(d++));for(var p=0;p<u.length;++p)u[p]>1&&((u[p+1]===null||u[p+1]===void 0)&&(u[p+1]=0),u[p+1]+=u[p]>>1,u[p]&=1)}return u.reverse()}function ude(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw Error(`Integers expected in function bitXor`);var n=e.constructor;if(e.isNaN()||t.isNaN())return new n(NaN);if(e.isZero())return t;if(t.isZero())return e;if(e.eq(t))return new n(0);var r=new n(-1);return e.eq(r)?Cy(t):t.eq(r)?Cy(e):!e.isFinite()||!t.isFinite()?!e.isFinite()&&!t.isFinite()?r:new n(e.isNegative()===t.isNegative()?1/0:-1/0):wy(e,t,function(e,t){return e^t})}function dde(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw Error(`Integers expected in function leftShift`);var n=e.constructor;return e.isNaN()||t.isNaN()||t.isNegative()&&!t.isZero()?new n(NaN):e.isZero()||t.isZero()?e:!e.isFinite()&&!t.isFinite()?new n(NaN):t.lt(55)?e.times(2**t.toNumber()+``):e.times(new n(2).pow(t))}function fde(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw Error(`Integers expected in function rightArithShift`);var n=e.constructor;return e.isNaN()||t.isNaN()||t.isNegative()&&!t.isZero()?new n(NaN):e.isZero()||t.isZero()?e:t.isFinite()?t.lt(55)?e.div(2**t.toNumber()+``).floor():e.div(new n(2).pow(t)).floor():e.isNegative()?new n(-1):e.isFinite()?new n(0):new n(NaN)}var Ey=e((()=>{})),Dy,pde,Oy,mde=e((()=>{Ey(),V_(),a_(),Mv(),X(),iv(),ph(),Dy=`bitAnd`,pde=[`typed`,`matrix`,`equalScalar`,`concat`],Oy=Y(Dy,pde,e=>{var{typed:t,matrix:n,equalScalar:r,concat:i}=e,a=B_({typed:t,equalScalar:r}),o=jv({typed:t,equalScalar:r}),s=i_({typed:t,equalScalar:r}),c=rv({typed:t,matrix:n,concat:i});return t(Dy,{"number, number":gm,"BigNumber, BigNumber":cde,"bigint, bigint":(e,t)=>e&t},c({SS:o,DS:a,Ss:s}))})})),ky,hde,Ay,gde=e((()=>{Ey(),Wp(),X(),ph(),ky=`bitNot`,hde=[`typed`],Ay=Y(ky,hde,e=>{var{typed:t}=e;return t(ky,{number:_m,BigNumber:Cy,bigint:e=>~e,"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),jy,_de,My,vde=e((()=>{Ey(),X(),bv(),gv(),fv(),iv(),ph(),jy=`bitOr`,_de=[`typed`,`matrix`,`equalScalar`,`DenseMatrix`,`concat`],My=Y(jy,_de,e=>{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:i,concat:a}=e,o=dv({typed:t}),s=hv({typed:t,equalScalar:r}),c=yv({typed:t,DenseMatrix:i}),l=rv({typed:t,matrix:n,concat:a});return t(jy,{"number, number":vm,"BigNumber, BigNumber":lde,"bigint, bigint":(e,t)=>e|t},l({SS:s,DS:o,Ss:c}))})})),yde,bde,Ny,Py=e((()=>{X(),Wf(),yde=`matAlgo07xSSf`,bde=[`typed`,`SparseMatrix`],Ny=Y(yde,bde,e=>{var{typed:t,SparseMatrix:n}=e;return function(e,i,a){var o=e._size,s=e._datatype||e._data===void 0?e._datatype:e.getDataType(),c=i._size,l=i._datatype||i._data===void 0?i._datatype:i.getDataType();if(o.length!==c.length)throw new Uf(o.length,c.length);if(o[0]!==c[0]||o[1]!==c[1])throw RangeError(`Dimension mismatch. Matrix A (`+o+`) must match Matrix B (`+c+`)`);var u=o[0],d=o[1],f,p=0,m=a;typeof s==`string`&&s===l&&s!==`mixed`&&(f=s,p=t.convert(0,f),m=t.find(a,[f,f]));for(var h=[],g=[],_=Array(d+1).fill(0),v=[],y=[],b=[],x=[],S=0;S<d;S++){var C=S+1,w=0;r(e,S,b,v,C),r(i,S,x,y,C);for(var T=0;T<u;T++){var E=b[T]===C?v[T]:p,D=x[T]===C?y[T]:p,O=m(E,D);O!==0&&O!==!1&&(g.push(T),h.push(O),w++)}_[S+1]=_[S]+w}return new n({values:h,index:g,ptr:_,size:[u,d],datatype:s===e._datatype&&l===i._datatype?f:void 0})};function r(e,t,n,r,i){for(var a=e._values,o=e._index,s=e._ptr,c=s[t],l=s[t+1];c<l;c++){var u=o[c];n[u]=i,r[u]=a[c]}}})})),Fy,xde,Iy,Sde=e((()=>{Ey(),G_(),Py(),l_(),X(),iv(),ph(),Fy=`bitXor`,xde=[`typed`,`matrix`,`DenseMatrix`,`concat`,`SparseMatrix`],Iy=Y(Fy,xde,e=>{var{typed:t,matrix:n,DenseMatrix:r,concat:i,SparseMatrix:a}=e,o=W_({typed:t}),s=Ny({typed:t,SparseMatrix:a}),c=c_({typed:t,DenseMatrix:r}),l=rv({typed:t,matrix:n,concat:i});return t(Fy,{"number, number":ym,"BigNumber, BigNumber":ude,"bigint, bigint":(e,t)=>e^t},l({SS:s,DS:o,Ss:c}))})})),Ly,Cde,Ry,wde=e((()=>{X(),Wp(),Ly=`arg`,Cde=[`typed`],Ry=Y(Ly,Cde,e=>{var{typed:t}=e;return t(Ly,{number:function(e){return Math.atan2(0,e)},BigNumber:function(e){return e.constructor.atan2(0,e)},Complex:function(e){return e.arg()},"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),zy,Tde,By,Ede=e((()=>{X(),Wp(),zy=`conj`,Tde=[`typed`],By=Y(zy,Tde,e=>{var{typed:t}=e;return t(zy,{"number | BigNumber | Fraction":e=>e,Complex:e=>e.conjugate(),Unit:t.referToSelf(e=>t=>
2590new t.constructor(e(t.toNumeric()),t.formatUnits())),"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),Vy,Dde,Hy,Ode=e((()=>{X(),Wp(),Vy=`im`,Dde=[`typed`],Hy=Y(Vy,Dde,e=>{var{typed:t}=e;return t(Vy,{number:()=>0,"BigNumber | Fraction":e=>e.mul(0),Complex:e=>e.im,"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),Uy,kde,Wy,Ade=e((()=>{X(),Wp(),Uy=`re`,kde=[`typed`],Wy=Y(Uy,kde,e=>{var{typed:t}=e;return t(Uy,{"number | BigNumber | Fraction":e=>e,Complex:e=>e.re,"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),Gy,jde,Ky,Mde=e((()=>{Wp(),X(),ph(),Gy=`not`,jde=[`typed`],Ky=Y(Gy,jde,e=>{var{typed:t}=e;return t(Gy,{"null | undefined":()=>!0,number:Nm,Complex:function(e){return e.re===0&&e.im===0},BigNumber:function(e){return e.isZero()||e.isNaN()},bigint:e=>!e,Unit:t.referToSelf(e=>n=>t.find(e,n.valueType())(n.value)),"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),qy,Nde,Jy,Pde=e((()=>{X(),G_(),p_(),$_(),Wf(),qy=`nullish`,Nde=[`typed`,`matrix`,`size`,`flatten`,`deepEqual`],Jy=Y(qy,Nde,e=>{var{typed:t,matrix:n,size:r,flatten:i,deepEqual:a}=e,o=W_({typed:t}),s=f_({typed:t}),c=Q_({typed:t});return t(qy,{"number|bigint|Complex|BigNumber|Fraction|Unit|string|boolean|SparseMatrix, any":(e,t)=>e,"null, any":(e,t)=>t,"undefined, any":(e,t)=>t,"SparseMatrix, Array | Matrix":(e,t)=>{var n=r(e),i=r(t);if(a(n,i))return e;throw new Uf(n,i)},"DenseMatrix, DenseMatrix":t.referToSelf(e=>(t,n)=>c(t,n,e)),"DenseMatrix, SparseMatrix":t.referToSelf(e=>(t,n)=>o(t,n,e,!1)),"DenseMatrix, Array":t.referToSelf(e=>(t,r)=>c(t,n(r),e)),"DenseMatrix, any":t.referToSelf(e=>(t,n)=>s(t,n,e,!1)),"Array, Array":t.referToSelf(e=>(t,r)=>c(n(t),n(r),e).valueOf()),"Array, DenseMatrix":t.referToSelf(e=>(t,r)=>c(n(t),r,e)),"Array, SparseMatrix":t.referToSelf(e=>(t,r)=>o(n(t),r,e,!1)),"Array, any":t.referToSelf(e=>(t,r)=>s(n(t),r,e,!1).valueOf())})})})),Yy,Fde,Xy,Ide=e((()=>{G_(),l_(),Y_(),X(),iv(),ph(),Yy=`or`,Fde=[`typed`,`matrix`,`equalScalar`,`DenseMatrix`,`concat`],Xy=Y(Yy,Fde,e=>{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:i,concat:a}=e,o=W_({typed:t}),s=J_({typed:t,equalScalar:r}),c=c_({typed:t,DenseMatrix:i}),l=rv({typed:t,matrix:n,concat:a});return t(Yy,{"number, number":Pm,"Complex, Complex":function(e,t){return e.re!==0||e.im!==0||t.re!==0||t.im!==0},"BigNumber, BigNumber":function(e,t){return!e.isZero()&&!e.isNaN()||!t.isZero()&&!t.isNaN()},"bigint, bigint":Pm,"Unit, Unit":t.referToSelf(e=>(t,n)=>e(t.value||0,n.value||0))},l({SS:s,DS:o,Ss:c}))})})),Zy,Lde,Qy,Rde=e((()=>{G_(),Py(),l_(),X(),iv(),ph(),Zy=`xor`,Lde=[`typed`,`matrix`,`DenseMatrix`,`concat`,`SparseMatrix`],Qy=Y(Zy,Lde,e=>{var{typed:t,matrix:n,DenseMatrix:r,concat:i,SparseMatrix:a}=e,o=W_({typed:t}),s=Ny({typed:t,SparseMatrix:a}),c=c_({typed:t,DenseMatrix:r}),l=rv({typed:t,matrix:n,concat:i});return t(Zy,{"number, number":Fm,"Complex, Complex":function(e,t){return(e.re!==0||e.im!==0)!=(t.re!==0||t.im!==0)},"bigint, bigint":Fm,"BigNumber, BigNumber":function(e,t){return(!e.isZero()&&!e.isNaN())!=(!t.isZero()&&!t.isNaN())},"Unit, Unit":t.referToSelf(e=>(t,n)=>e(t.value||0,n.value||0))},l({SS:s,DS:o,Ss:c}))})})),$y,zde,eb,Bde=e((()=>{Ql(),ru(),Tp(),Kf(),Wf(),X(),$y=`concat`,zde=[`typed`,`matrix`,`isInteger`],eb=Y($y,zde,e=>{var{typed:t,matrix:n,isInteger:r}=e;return t($y,{"...Array | Matrix | number | BigNumber":function(e){var t,i=e.length,a=-1,o,s=!1,c=[];for(t=0;t<i;t++){var l=e[t];if(Dl(l)&&(s=!0),bl(l)||xl(l)){if(t!==i-1)throw Error(`Dimension must be specified as last argument`);if(o=a,a=l.valueOf(),!r(a))throw TypeError(`Integer number expected for dimension`);if(a<0||t>0&&a>o)throw new Gf(a,o+1)}else{var u=$l(l).valueOf(),d=qf(u);if(c[t]=u,o=a,a=d.length-1,t>0&&a!==o)throw new Uf(o+1,a+1)}}if(c.length===0)throw SyntaxError(`At least one matrix expected`);for(var f=c.shift();c.length;)f=vp(f,c.shift(),a);return s?n(f):f},"...string":function(e){return e.join(``)}})})})),tb,Vde,nb,Hde=e((()=>{X(),Ql(),ru(),Tp(),tb=`column`,Vde=[`typed`,`Index`,`matrix`,`range`],nb=Y(tb,Vde,e=>{var{typed:t,Index:n,matrix:r,range:i}=e;return t(tb,{"Matrix, number":a,"Array, number":function(e,t){return a(r($l(e)),t).valueOf()}});function a(e,t){if(e.size().length!==2)throw Error(`Only two dimensional matrix is supported`);Zf(t,e.size()[1]);
2590var a=new n(i(0,e.size()[0]),[t]),o=e.subset(a);return Dl(o)?o:r([[o]])}})})),rb,Ude,ib,Wde=e((()=>{X(),rb=`count`,Ude=[`typed`,`size`,`prod`],ib=Y(rb,Ude,e=>{var{typed:t,size:n,prod:r}=e;return t(rb,{string:function(e){return e.length},"Matrix | Array":function(e){return r(n(e))}})})})),ab,Gde,ob,Kde=e((()=>{Tp(),X(),ab=`cross`,Gde=[`typed`,`matrix`,`subtract`,`multiply`],ob=Y(ab,Gde,e=>{var{typed:t,matrix:n,subtract:r,multiply:i}=e;return t(ab,{"Matrix, Matrix":function(e,t){return n(a(e.toArray(),t.toArray()))},"Matrix, Array":function(e,t){return n(a(e.toArray(),t))},"Array, Matrix":function(e,t){return n(a(e,t.toArray()))},"Array, Array":a});function a(e,t){var n=Math.max(qf(e).length,qf(t).length);e=ip(e),t=ip(t);var a=qf(e),o=qf(t);if(a.length!==1||o.length!==1||a[0]!==3||o[0]!==3)throw RangeError(`Vectors with length 3 expected (Size A = [`+a.join(`, `)+`], B = [`+o.join(`, `)+`])`);var s=[r(i(e[1],t[2]),i(e[2],t[1])),r(i(e[2],t[0]),i(e[0],t[2])),r(i(e[0],t[1]),i(e[1],t[0]))];return n>1?[s]:s}})})),sb,qde,cb,Jde=e((()=>{Ql(),Tp(),Pu(),X(),sb=`diag`,qde=[`typed`,`matrix`,`DenseMatrix`,`SparseMatrix`],cb=Y(sb,qde,e=>{var{typed:t,matrix:n,DenseMatrix:r,SparseMatrix:i}=e;return t(sb,{Array:function(e){return a(e,0,qf(e),null)},"Array, number":function(e,t){return a(e,t,qf(e),null)},"Array, BigNumber":function(e,t){return a(e,t.toNumber(),qf(e),null)},"Array, string":function(e,t){return a(e,0,qf(e),t)},"Array, number, string":function(e,t,n){return a(e,t,qf(e),n)},"Array, BigNumber, string":function(e,t,n){return a(e,t.toNumber(),qf(e),n)},Matrix:function(e){return a(e,0,e.size(),e.storage())},"Matrix, number":function(e,t){return a(e,t,e.size(),e.storage())},"Matrix, BigNumber":function(e,t){return a(e,t.toNumber(),e.size(),e.storage())},"Matrix, string":function(e,t){return a(e,0,e.size(),t)},"Matrix, number, string":function(e,t,n){return a(e,t,e.size(),n)},"Matrix, BigNumber, string":function(e,t,n){return a(e,t.toNumber(),e.size(),n)}});function a(e,t,n,r){if(!lu(t))throw TypeError(`Second parameter in function diag must be an integer`);var i=t>0?t:0,a=t<0?-t:0;switch(n.length){case 1:return o(e,t,r,n[0],a,i);case 2:return s(e,t,r,n,a,i)}throw RangeError(`Matrix for function diag must be 2 dimensional`)}function o(e,t,n,a,o,s){var c=[a+o,a+s];if(n&&n!==`sparse`&&n!==`dense`)throw TypeError(`Unknown matrix type ${n}"`);var l=n===`sparse`?i.diagonal(c,e,t):r.diagonal(c,e,t);return n===null?l.valueOf():l}function s(e,t,r,i,a,o){if(Dl(e)){var s=e.diagonal(t);return r===null?s.valueOf():r===s.storage()?s:n(s,r)}for(var c=Math.min(i[0]-a,i[1]-o),l=[],u=0;u<c;u++)l[u]=e[u+a][u+o];return r===null?l:n(l)}})}));function Yde(e,t){var n=Ep(t,e,`filter`);return n.isUnary?dp(e,n.fn):dp(e,function(e,t,r){return n.fn(e,[t],r)})}var Xde,Zde,lb,Qde=e((()=>{kp(),Tp(),X(),Xde=`filter`,Zde=[`typed`],lb=Y(Xde,Zde,e=>{var{typed:t}=e;return t(`filter`,{"Array, function":Yde,"Matrix, function":function(e,t){return e.create(Yde(e.valueOf(),t),e.datatype())},"Array, RegExp":fp,"Matrix, RegExp":function(e,t){return e.create(fp(e.valueOf(),t),e.datatype())}})})})),ub,$de,db,efe=e((()=>{Tp(),X(),ub=`flatten`,$de=[`typed`],db=Y(ub,$de,e=>{var{typed:t}=e;return t(ub,{Array:function(e){return cp(e)},DenseMatrix:function(e){return e.create(cp(e.valueOf(),!0),e.datatype())},SparseMatrix:function(e){throw TypeError(`SparseMatrix is not supported by function flatten because it does not support 1D vectors. Convert to a DenseMatrix or Array first. Example: flatten(x.toArray())`)}})})}));function tfe(e,t){var n=Ep(t,e,fb);wp(e,n.fn,n.isUnary)}var fb,nfe,pb,rfe=e((()=>{kp(),X(),Tp(),fb=`forEach`,nfe=[`typed`],pb=Y(fb,nfe,e=>{var{typed:t}=e;return t(fb,{"Array, function":tfe,"Matrix, function":function(e,t){e.forEach(t)}})})})),mb,ife,hb,afe=e((()=>{X(),Tp(),Ql(),mb=`getMatrixDataType`,ife=[`typed`],hb=Y(mb,ife,e=>{var{typed:t}=e;return t(mb,{Array:function(e){return gp(e,Xl)},Matrix:function(e){return e.getDataType()}})})})),gb,ofe,_b,sfe=e((()=>{Ql(),Tp(),Pu(),X(),gb=`identity`,ofe=[`typed`,`config`,`matrix`,`BigNumber`,`DenseMatrix`,`SparseMatrix`],_b=Y(gb,ofe,e=>{var{typed:t,config:n,matrix:r,BigNumber:i,DenseMatrix:a,SparseMatrix:o}=e;
2590return t(gb,{"":function(){return n.matrix===`Matrix`?r([]):[]},string:function(e){return r(e)},"number | BigNumber":function(e){return c(e,e,n.matrix===`Matrix`?`dense`:void 0)},"number | BigNumber, string":function(e,t){return c(e,e,t)},"number | BigNumber, number | BigNumber":function(e,t){return c(e,t,n.matrix===`Matrix`?`dense`:void 0)},"number | BigNumber, number | BigNumber, string":function(e,t,n){return c(e,t,n)},Array:function(e){return s(e)},"Array, string":function(e,t){return s(e,t)},Matrix:function(e){return s(e.valueOf(),e.storage())},"Matrix, string":function(e,t){return s(e.valueOf(),t)}});function s(e,t){switch(e.length){case 0:return t?r(t):[];case 1:return c(e[0],e[0],t);case 2:return c(e[0],e[1],t);default:throw Error(`Vector containing two values expected`)}}function c(e,t,n){var r=xl(e)||xl(t)?i:null;if(xl(e)&&(e=e.toNumber()),xl(t)&&(t=t.toNumber()),!lu(e)||e<1||!lu(t)||t<1)throw Error(`Parameters in function identity must be positive integers`);var s=r?new i(1):1,c=r?new r(0):0,l=[e,t];if(n){if(n===`sparse`)return o.diagonal(l,s,0,c);if(n===`dense`)return a.diagonal(l,s,0,c);throw TypeError(`Unknown matrix type "${n}"`)}for(var u=$f([],l,c),d=e<t?e:t,f=0;f<d;f++)u[f][f]=s;return u}})})),vb,cfe,yb,lfe=e((()=>{Tp(),X(),vb=`kron`,cfe=[`typed`,`matrix`,`multiplyScalar`],yb=Y(vb,cfe,e=>{var{typed:t,matrix:n,multiplyScalar:r}=e;return t(vb,{"Matrix, Matrix":function(e,t){return n(a(e.toArray(),t.toArray()))},"Matrix, Array":function(e,t){return n(a(e.toArray(),t))},"Array, Matrix":function(e,t){return n(a(e,t.toArray()))},"Array, Array":a});function i(e,t){return e.flatMap(e=>t.map(t=>r(e,t)))}function a(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:-1;if(n<0){var r=qf(e).length,o=qf(t).length;for(n=Math.max(r,o);r++<n;)e=[e];for(;o++<n;)t=[t]}return n===1?i(e,t):e.flatMap(e=>t.map(t=>a(e,t,n-1)))}})})),bb,ufe,xb,dfe=e((()=>{kp(),Tp(),X(),bb=`map`,ufe=[`typed`],xb=Y(bb,ufe,e=>{var{typed:t}=e;return t(bb,{"Array, function":s,"Matrix, function":function(e,t){return e.map(t)},"Array|Matrix, Array|Matrix, ...Array|Matrix|function":(e,t,r)=>n([e,t,...r.slice(0,r.length-1)],r[r.length-1])});function n(e,n){if(typeof n!=`function`)throw Error(`Last argument must be a callback function`);var c=e[0].isMatrix,l=e.map(e=>e.isMatrix?e.size():qf(e)),u=yp(...l),d=e.length,f=c?(e,t)=>e.get(t):Sp,p=e.map((e,t)=>{var n=l[t].map(()=>0);return e.isMatrix?e.get(n):Sp(e,n)}),m=t.isTypedFunction(n)?o(n,p,u.map(()=>0),e):a(n,d);if(m<2)return r(e,i(m,n,null));var h=c?e.map(t=>t.isMatrix?t.create(xp(t.toArray(),u),t.datatype()):e[0].create(xp(t.valueOf(),u))):e.map(e=>e.isMatrix?xp(e.toArray(),u):xp(e,u)),g=i(m,n,h),_=(e,t)=>g([e,...h.slice(1).map(e=>f(e,t))],t);return c?h[0].map(_):s(h[0],_)}function r(e,t){var n=e[0],r=e.map(e=>e.isMatrix?e.valueOf():e),i=e.map(e=>e.isMatrix?e.size():qf(e)),a=yp(...i),o=i.map(e=>a.length-e.length),s=a.length-1,c=t.length>1?[]:null,l=d(r,0);if(n.isMatrix){var u=n.create();return u._data=l,u._size=a,u}else return l;function d(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=a[n],i=Array(r);if(n<s)for(var l=function(t){c&&(c[n]=t),i[t]=d(e.map((e,r)=>o[r]>n?e:e.length===1?e[0]:e[t]),n+1)},u=0;u<r;u++)l(u);else for(var f=function(r){c&&(c[n]=r),i[r]=t(e.map(e=>e.length===1?e[0]:e[r]),c?c.slice():void 0)},p=0;p<r;p++)f(p);return i}}function i(e,t,n){switch(e){case 0:return e=>t(...e);case 1:return(e,n)=>t(...e,n);case 2:return(e,r)=>t(...e,r,...n)}}function a(e,t){var n=e.toString();if(/arguments/.test(n))return 2;var r=n.match(/\(.*?\)/);return/\.\.\./.test(r)||e.length>t+1?2:+(e.length===t+1)}function o(e,n,r,i){return t.resolve(e,[...n,r,...i])===null?t.resolve(e,[...n,r])===null?(t.resolve(e,n),0):1:2}function s(e,t){var n=Ep(t,e,bb);return Cp(e,n.fn,n.isUnary)}})})),Sb,ffe,Cb,pfe=e((()=>{X(),Pu(),Ql(),Sb=`diff`,ffe=[`typed`,`matrix`,`subtract`,`number`],Cb=Y(Sb,ffe,e=>{var{typed:t,matrix:n,subtract:r,number:i}=e;return t(Sb,{"Array | Matrix":function(e){return Dl(e)?n(o(e.toArray())):o(e)},"Array | Matrix, number":function(e,t){if(!lu(t))throw RangeError(`Dimension must be a whole number`);return Dl(e)?n(a(e.toArray(),t)):a(e,t)},"Array, BigNumber":t.referTo(`Array,number`,e=>(t,n)=>e(t,i(n))),"Matrix, BigNumber":t.referTo(`Matrix,number`,e=>(t,n)=>e(t,i(n)))});function a(e,t){if(Dl(e)&&(e=e.toArray()),!Array.isArray(e))throw RangeError(`Array/Matrix does not have that many dimensions`);if(t>0){var n=[];
2590return e.forEach(e=>{n.push(a(e,t-1))}),n}else if(t===0)return o(e);else throw RangeError(`Cannot have negative dimension`)}function o(e){for(var t=[],n=e.length,r=1;r<n;r++)t.push(s(e[r-1],e[r]));return t}function s(e,t){Dl(e)&&(e=e.toArray()),Dl(t)&&(t=t.toArray());var n=Array.isArray(e),i=Array.isArray(t);if(n&&i)return c(e,t);if(!n&&!i)return r(t,e);throw TypeError(`Cannot calculate difference between 1 array and 1 non-array`)}function c(e,t){if(e.length!==t.length)throw RangeError(`Not all sub-arrays have the same length`);for(var n=[],r=e.length,i=0;i<r;i++)n.push(s(e[i],t[i]));return n}})})),mfe,hfe,wb,gfe=e((()=>{Ql(),Pu(),Tp(),X(),mfe=`ones`,hfe=[`typed`,`config`,`matrix`,`BigNumber`],wb=Y(mfe,hfe,e=>{var{typed:t,config:n,matrix:r,BigNumber:i}=e;return t(`ones`,{"":function(){return n.matrix===`Array`?a([]):a([],`default`)},"...number | BigNumber | string":function(e){return typeof e[e.length-1]==`string`?a(e,e.pop()):n.matrix===`Array`?a(e):a(e,`default`)},Array:a,Matrix:function(e){var t=e.storage();return a(e.valueOf(),t)},"Array | Matrix, string":function(e,t){return a(e.valueOf(),t)}});function a(e,t){var n=o(e)?new i(1):1;if(s(e),t){var a=r(t);return e.length>0?a.resize(e,n):a}else{var c=[];return e.length>0?$f(c,e,n):c}}function o(e){var t=!1;return e.forEach(function(e,n,r){xl(e)&&(t=!0,r[n]=e.toNumber())}),t}function s(e){e.forEach(function(e){if(typeof e!=`number`||!lu(e)||e<0)throw Error(`Parameters in function ones must be positive integers`)})}})}));function Tb(){throw Error(`No "bignumber" implementation available`)}function _fe(){throw Error(`No "fraction" implementation available`)}function vfe(){throw Error(`No "matrix" implementation available`)}var Eb=e((()=>{})),Db,yfe,Ob,bfe=e((()=>{X(),Eb(),Db=`range`,yfe=[`typed`,`config`,`?matrix`,`?bignumber`,`equal`,`smaller`,`smallerEq`,`larger`,`largerEq`,`add`,`isZero`,`isPositive`],Ob=Y(Db,yfe,e=>{var{typed:t,config:n,matrix:r,bignumber:i,smaller:a,smallerEq:o,larger:s,largerEq:c,add:l,isZero:u,isPositive:d}=e;return t(Db,{string:p,"string, boolean":p,number:function(e){throw TypeError(`Too few arguments to function range(): ${e}`)},boolean:function(e){throw TypeError(`Unexpected type of argument 1 to function range(): ${e}, number|bigint|BigNumber|Fraction`)},"number, number":function(e,t){return f(m(e,t,1,!1))},"number, number, number":function(e,t,n){return f(m(e,t,n,!1))},"number, number, boolean":function(e,t,n){return f(m(e,t,1,n))},"number, number, number, boolean":function(e,t,n,r){return f(m(e,t,n,r))},"bigint, bigint|number":function(e,t){return f(m(e,t,1n,!1))},"number, bigint":function(e,t){return f(m(BigInt(e),t,1n,!1))},"bigint, bigint|number, bigint|number":function(e,t,n){return f(m(e,t,BigInt(n),!1))},"number, bigint, bigint|number":function(e,t,n){return f(m(BigInt(e),t,BigInt(n),!1))},"bigint, bigint|number, boolean":function(e,t,n){return f(m(e,t,1n,n))},"number, bigint, boolean":function(e,t,n){return f(m(BigInt(e),t,1n,n))},"bigint, bigint|number, bigint|number, boolean":function(e,t,n,r){return f(m(e,t,BigInt(n),r))},"number, bigint, bigint|number, boolean":function(e,t,n,r){return f(m(BigInt(e),t,BigInt(n),r))},"BigNumber, BigNumber":function(e,t){var n=e.constructor;return f(m(e,t,new n(1),!1))},"BigNumber, BigNumber, BigNumber":function(e,t,n){return f(m(e,t,n,!1))},"BigNumber, BigNumber, boolean":function(e,t,n){var r=e.constructor;return f(m(e,t,new r(1),n))},"BigNumber, BigNumber, BigNumber, boolean":function(e,t,n,r){return f(m(e,t,n,r))},"Fraction, Fraction":function(e,t){return f(m(e,t,1,!1))},"Fraction, Fraction, Fraction":function(e,t,n){return f(m(e,t,n,!1))},"Fraction, Fraction, boolean":function(e,t,n){return f(m(e,t,1,n))},"Fraction, Fraction, Fraction, boolean":function(e,t,n,r){return f(m(e,t,n,r))},"Unit, Unit, Unit":function(e,t,n){return f(m(e,t,n,!1))},"Unit, Unit, Unit, boolean":function(e,t,n,r){return f(m(e,t,n,r))}});function f(e){return n.matrix===`Matrix`?r?r(e):vfe():e}function p(e,t){var r=h(e);if(!r)throw SyntaxError(`String "`+e+`" is no valid range`);return n.number===`BigNumber`?(i===void 0&&Tb(),f(m(i(r.start),i(r.end
2590),i(r.step)),t)):f(m(r.start,r.end,r.step,t))}function m(e,t,n,r){var i=[];if(u(n))throw Error(`Step must be non-zero`);for(var f=d(n)?r?o:a:r?c:s,p=e;f(p,t);)i.push(p),p=l(p,n);return i}function h(e){var t=e.split(`:`).map(function(e){return Number(e)});if(t.some(function(e){return isNaN(e)}))return null;switch(t.length){case 2:return{start:t[0],end:t[1],step:1};case 3:return{start:t[0],end:t[2],step:t[1]};default:return null}}})})),kb,xfe,Ab,Sfe=e((()=>{Tp(),X(),kb=`reshape`,xfe=[`typed`,`isInteger`,`matrix`],Ab=Y(kb,xfe,e=>{var{typed:t,isInteger:n}=e;return t(kb,{"Matrix, Array":function(e,t){return e.reshape(t,!0)},"Array, Array":function(e,t){return t.forEach(function(e){if(!n(e))throw TypeError(`Invalid size for dimension: `+e)}),tp(e,t)}})})})),Cfe,wfe,jb,Tfe=e((()=>{Ql(),Wf(),Sv(),Pu(),Hf(),ru(),Tp(),X(),Cfe=`resize`,wfe=[`config`,`matrix`],jb=Y(Cfe,wfe,e=>{var{config:t,matrix:n}=e;return function(e,i,a){if(arguments.length!==2&&arguments.length!==3)throw new xv(`resize`,arguments.length,2,3);if(Dl(i)&&(i=i.valueOf()),xl(i[0])&&(i=i.map(function(e){return xl(e)?e.toNumber():e})),Dl(e))return e.resize(i,a,!0);if(typeof e==`string`)return r(e,i,a);var o=Array.isArray(e)?!1:t.matrix!==`Array`;if(i.length===0){for(;Array.isArray(e);)e=e[0];return $l(e)}else{Array.isArray(e)||(e=[e]),e=$l(e);var s=$f(e,i,a);return o?n(s):s}};function r(e,t,n){if(n!==void 0){if(typeof n!=`string`||n.length!==1)throw TypeError(`Single character expected as defaultValue`)}else n=` `;if(t.length!==1)throw new Uf(t.length,1);var r=t[0];if(typeof r!=`number`||!lu(r))throw TypeError(`Invalid size, must contain positive integers (size: `+If(t)+`)`);if(e.length>r)return e.substring(0,r);if(e.length<r){for(var i=e,a=0,o=r-e.length;a<o;a++)i+=n;return i}else return e}})})),Mb,Efe,Nb,Dfe=e((()=>{X(),Tp(),Mb=`rotate`,Efe=[`typed`,`multiply`,`rotationMatrix`],Nb=Y(Mb,Efe,e=>{var{typed:t,multiply:n,rotationMatrix:r}=e;return t(Mb,{"Array , number | BigNumber | Complex | Unit":function(e,t){return i(e,2),n(r(t),e).toArray()},"Matrix , number | BigNumber | Complex | Unit":function(e,t){return i(e,2),n(r(t),e)},"Array, number | BigNumber | Complex | Unit, Array | Matrix":function(e,t,a){return i(e,3),n(r(t,a),e)},"Matrix, number | BigNumber | Complex | Unit, Array | Matrix":function(e,t,a){return i(e,3),n(r(t,a),e)}});function i(e,t){var n=Array.isArray(e)?qf(e):e.size();if(n.length>2||n.length===2&&n[1]!==1||n[0]!==t)throw RangeError(`Vector must be of dimensions 1x${t}`)}})})),Pb,Ofe,Fb,kfe=e((()=>{Ql(),X(),Pb=`rotationMatrix`,Ofe=[`typed`,`config`,`multiplyScalar`,`addScalar`,`unaryMinus`,`norm`,`matrix`,`BigNumber`,`DenseMatrix`,`SparseMatrix`,`cos`,`sin`],Fb=Y(Pb,Ofe,e=>{var{typed:t,config:n,multiplyScalar:r,addScalar:i,unaryMinus:a,norm:o,BigNumber:s,matrix:c,DenseMatrix:l,SparseMatrix:u,cos:d,sin:f}=e;return t(Pb,{"":function(){return n.matrix===`Matrix`?c([]):[]},string:function(e){return c(e)},"number | BigNumber | Complex | Unit":function(e){return p(e,n.matrix===`Matrix`?`dense`:void 0)},"number | BigNumber | Complex | Unit, string":function(e,t){return p(e,t)},"number | BigNumber | Complex | Unit, Array":function(e,t){var n=c(t);return m(n),_(e,n,void 0)},"number | BigNumber | Complex | Unit, Matrix":function(e,t){return m(t),_(e,t,t.storage()||(n.matrix===`Matrix`?`dense`:void 0))},"number | BigNumber | Complex | Unit, Array, string":function(e,t,n){var r=c(t);return m(r),_(e,r,n)},"number | BigNumber | Complex | Unit, Matrix, string":function(e,t,n){return m(t),_(e,t,n)}});function p(e,t){var n=xl(e)?new s(-1):-1,i=d(e),a=f(e);return g([[i,r(n,a)],[a,i]],t)}function m(e){var t=e.size();if(t.length<1||t[0]!==3)throw RangeError(`Vector must be of dimensions 1x3`)}function h(e){return e.reduce((e,t)=>r(e,t))}function g(e,t){if(t){if(t===`sparse`)return new u(e);
2590if(t===`dense`)return new l(e);throw TypeError(`Unknown matrix type "${t}"`)}return e}function _(e,t,n){var r=o(t);if(r===0)throw RangeError(`Rotation around zero vector`);var c=xl(e)?s:null,l=c?new c(1):1,u=c?new c(-1):-1,p=c?new c(t.get([0])/r):t.get([0])/r,m=c?new c(t.get([1])/r):t.get([1])/r,_=c?new c(t.get([2])/r):t.get([2])/r,v=d(e),y=i(l,a(v)),b=f(e),x=i(v,h([p,p,y])),S=i(h([p,m,y]),h([u,_,b])),C=i(h([p,_,y]),h([m,b])),w=i(h([p,m,y]),h([_,b])),T=i(v,h([m,m,y])),E=i(h([m,_,y]),h([u,p,b])),D=i(h([p,_,y]),h([u,m,b])),O=i(h([m,_,y]),h([p,b])),k=i(v,h([_,_,y]));return g([[x,S,C],[w,T,E],[D,O,k]],n)}})})),Ib,Afe,Lb,jfe=e((()=>{X(),Ql(),ru(),Tp(),Ib=`row`,Afe=[`typed`,`Index`,`matrix`,`range`],Lb=Y(Ib,Afe,e=>{var{typed:t,Index:n,matrix:r,range:i}=e;return t(Ib,{"Matrix, number":a,"Array, number":function(e,t){return a(r($l(e)),t).valueOf()}});function a(e,t){if(e.size().length!==2)throw Error(`Only two dimensional matrix is supported`);Zf(t,e.size()[0]);var a=i(0,e.size()[1]),o=new n([t],a),s=e.subset(o);return Dl(s)?s:r([[s]])}})})),Rb,Mfe,zb,Nfe=e((()=>{Tp(),X(),Rb=`size`,Mfe=[`typed`],zb=Y(Rb,Mfe,e=>{var{typed:t}=e;return t(Rb,{Matrix:e=>e.size(),Array:qf,string:e=>[e.length],"number | Complex | BigNumber | Unit | boolean | null":e=>[]})})})),Bb,Pfe,Vb,Ffe=e((()=>{ru(),Tp(),X(),Bb=`squeeze`,Pfe=[`typed`],Vb=Y(Bb,Pfe,e=>{var{typed:t}=e;return t(Bb,{Array:function(e){return ip($l(e))},Matrix:function(e){var t=ip(e.toArray());return Array.isArray(t)?e.create(t,e.datatype()):t},any:function(e){return $l(e)}})})}));function Ife(e,t){if(!Ml(t))throw TypeError(`Index expected`);if(Qf(t))return``;if(Xf(Array.from(e),t),t.size().length!==1)throw new Uf(t.size().length,1);var n=e.length;Zf(t.min()[0],n),Zf(t.max()[0],n);var r=t.dimension(0),i=``;function a(t){i+=e.charAt(t)}return Number.isInteger(r)?a(r):r.forEach(a),i}function Lfe(e,t,n,r){if(!t||t.isIndex!==!0)throw TypeError(`Index expected`);if(Qf(t))return e;if(Xf(Array.from(e),t),t.size().length!==1)throw new Uf(t.size().length,1);if(r!==void 0){if(typeof r!=`string`||r.length!==1)throw TypeError(`Single character expected as defaultValue`)}else r=` `;var i=t.dimension(0);if((Number.isInteger(i)?1:i.size()[0])!==n.length)throw new Uf(i.size()[0],n.length);var a=e.length;Zf(t.min()[0]),Zf(t.max()[0]);for(var o=[],s=0;s<a;s++)o[s]=e.charAt(s);function c(e,t){o[e]=n.charAt(t[0])}if(Number.isInteger(i)?c(i,[0]):i.forEach(c),o.length>a)for(var l=a-1,u=o.length;l<u;l++)o[l]||(o[l]=r);return o.join(``)}function Rfe(e,t){if(!Qf(t)){if(t.size().length!==1)throw new Uf(t.size(),1);var n=t.dimension(0);if(typeof n!=`string`)throw TypeError(`String expected as index to retrieve an object property`);return ul(e,n)}}function zfe(e,t,n){if(Qf(t))return e;if(t.size().length!==1)throw new Uf(t.size(),1);var r=t.dimension(0);if(typeof r!=`string`)throw TypeError(`String expected as index to retrieve an object property`);var i=$l(e);return dl(i,r,n),i}var Hb,Bfe,Ub,Vfe=e((()=>{Ql(),ru(),Tp(),ml(),Wf(),X(),Hb=`subset`,Bfe=[`typed`,`matrix`,`zeros`,`add`],Ub=Y(Hb,Bfe,e=>{var{typed:t,matrix:n,zeros:r,add:i}=e;return t(Hb,{"Matrix, Index":function(e,t){return Qf(t)?n():(Xf(e,t),e.subset(t))},"Array, Index":t.referTo(`Matrix, Index`,function(e){return function(t,r){var i=e(n(t),r);return r.isScalar()?i:i.valueOf()}}),"Object, Index":Rfe,"string, Index":Ife,"Matrix, Index, any, any":function(e,t,n,r){return Qf(t)?e:(Xf(e,t),e.clone().subset(t,a(n,t),r))},"Array, Index, any, any":t.referTo(`Matrix, Index, any, any`,function(e){return function(t,r,i,a){var o=e(n(t),r,i,a);return o.isMatrix?o.valueOf():o}}),"Array, Index, any":t.referTo(`Matrix, Index, any, any`,function(e){return function(t,r,i){return e(n(t),r,i,void 0).valueOf()}}),"Matrix, Index, any":t.referTo(`Matrix, Index, any, any`,function(e){return function(t,n,r){return e(t,n,r,void 0)}}),"string, Index, string":Lfe,"string, Index, string, string":Lfe,"Object, Index, any":zfe});function a(e,t){if(typeof e==`string`)throw Error(`can't boradcast a string`);if(t.isScalar())return e;var n=t.size();if(n.every(e=>e>0))try{return i(e,r(n))}catch{return e}else return e}})})),Wb,Hfe,Gb,Ufe=e((()=>{ru(),Hf(),X(),Wb=`transpose`,Hfe=[`typed`,`matrix`],Gb=Y(Wb,Hfe,e=>{var{typed:t,matrix:n}=e;return t(Wb,{Array:e=>r(n(e)).valueOf(),Matrix:r,any:$l});function r(e){var t=e.size(),n;switch(t.length){case 1:n=e.clone();break;case 2:var r=t[0],o=t[1];if(o===0)throw RangeError(`Cannot transpose a 2D matrix with no columns (size: `+If(t)+`)`);switch(e.storage()){case`dense`:n=i(e,r,o);break;case`sparse`:n=a(e,r,o);break}break;default:throw RangeError(`Matrix must be a vector or two dimensional (size: `+If(t)+`)`)}return n}function i(e,t,n){for(var r=e._data,i=[],a,o=0;o<n;o++){a=i[o]=[];for(var s=0;s<t;s++)a[s]=$l(r[s][o])}return e.createDenseMatrix({data:i,size:[n,t],datatype:e._datatype})}function a(e,t,n){for(var r=e._values,i=e._index,a=e._ptr,o=r?[]:void 0,s=[],c=[],l=[],u=0;u<t;u++)l[u]=0;var d,f,p;for(d=0,f=i.length;d<f;d++)l[i[d]]++;for(var m=0,h=0;h<t;h++)c.push(m),m+=l[h],l[h]=c[h];for(c.push(m),p=0;p<n;p++)for(var g=a[p],_=a[p+1],v=g;v<_;v++){var y=l[i[v]]++;s[y]=p,r&&(o[y]=$l(r[v]))}return e.createSparseMatrix({values:o,index:s,ptr:c,size:[n,t],datatype:e._datatype})}})})),Kb,Wfe,qb,Gfe=e((()=>{X(),Kb=`ctranspose`,Wfe=[`typed`,`transpose`,`conj`],qb=Y(Kb,Wfe,e=>{var{typed:t,transpose:n,conj:r}=e;return t(Kb,{any:function(e){return r(n(e))}})})})),Jb,Kfe,Yb,qfe=e((()=>{Ql(),Pu(),Tp(),X(),Jb=`zeros`,Kfe=[`typed`,`config`,`matrix`,`BigNumber`],Yb=Y(Jb,Kfe,e=>{var{typed:t,config:n,matrix:r,BigNumber:i}=e;return t(Jb,{"":function(){return n.matrix===`Array`?a([]):a([],`default`)},"...number | BigNumber | string":function(e){return typeof e[e.length-1]==`string`?a(e,e.pop()):n.matrix===`Array`?a(e):a(e,`default`)},Array:a,Matrix:function(e){var t=e.storage();return a(e.valueOf(),t)},"Array | Matrix, string":function(e,t){return a(e.valueOf(),t)}});
2590function a(e,t){var n=o(e)?new i(0):0;if(s(e),t){var a=r(t);return e.length>0?a.resize(e,n):a}else{var c=[];return e.length>0?$f(c,e,n):c}}function o(e){var t=!1;return e.forEach(function(e,n,r){xl(e)&&(t=!0,r[n]=e.toNumber())}),t}function s(e){e.forEach(function(e){if(typeof e!=`number`||!lu(e)||e<0)throw Error(`Parameters in function zeros must be positive integers`)})}})})),Xb,Jfe,Zb,Yfe=e((()=>{Tp(),X(),Xb=`fft`,Jfe=[`typed`,`matrix`,`addScalar`,`multiplyScalar`,`divideScalar`,`exp`,`tau`,`i`,`dotDivide`,`conj`,`pow`,`ceil`,`log2`],Zb=Y(Xb,Jfe,e=>{var{typed:t,matrix:n,addScalar:r,multiplyScalar:i,divideScalar:a,exp:o,tau:s,i:c,dotDivide:l,conj:u,pow:d,ceil:f,log2:p}=e;return t(Xb,{Array:m,Matrix:function(e){return e.create(m(e.valueOf()),e.datatype())}});function m(e){var t=qf(e);return t.length===1?_(e,t[0]):h(e.map(e=>m(e,t.slice(1))),0)}function h(e,t){var n=qf(e);if(t!==0)return Array(n[0]).fill(0).map((n,r)=>h(e[r],t-1));if(n.length===1)return _(e);function r(e){var t=qf(e);return Array(t[1]).fill(0).map((n,r)=>Array(t[0]).fill(0).map((t,n)=>e[n][r]))}return r(h(r(e),1))}function g(e){for(var t=e.length,n=o(a(i(-1,i(c,s)),t)),r=[],h=1-t;h<t;h++)r.push(d(n,a(d(h,2),2)));for(var g=d(2,f(p(t+t-1))),v=[...Array(t).fill(0).map((n,a)=>i(e[a],r[t-1+a])),...Array(g-t).fill(0)],y=[...Array(t+t-1).fill(0).map((e,t)=>a(1,r[t])),...Array(g-(t+t-1)).fill(0)],b=_(v),x=_(y),S=l(u(m(u(Array(g).fill(0).map((e,t)=>i(b[t],x[t]))))),g),C=[],w=t-1;w<t+t-1;w++)C.push(i(S[w],r[w]));return C}function _(e){var t=e.length;if(t===1)return[e[0]];if(t%2==0){for(var n=[..._(e.filter((e,t)=>t%2==0),t/2),..._(e.filter((e,t)=>t%2==1),t/2)],l=0;l<t/2;l++){var u=n[l],d=i(n[l+t/2],o(i(i(s,c),a(-l,t))));n[l]=r(u,d),n[l+t/2]=r(u,i(-1,d))}return n}else return g(e)}})})),Qb,Xfe,$b,Zfe=e((()=>{Tp(),X(),Ql(),Qb=`ifft`,Xfe=[`typed`,`fft`,`dotDivide`,`conj`],$b=Y(Qb,Xfe,e=>{var{typed:t,fft:n,dotDivide:r,conj:i}=e;return t(Qb,{"Array | Matrix":function(e){var t=Dl(e)?e.size():qf(e);return r(i(n(i(e))),t.reduce((e,t)=>e*t,1))}})})}));function Qfe(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function $fe(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Qfe(Object(n),!0).forEach(function(t){Rn(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Qfe(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var epe,tpe,ex,npe=e((()=>{Ln(),Ql(),X(),epe=`solveODE`,tpe=[`typed`,`add`,`subtract`,`multiply`,`divide`,`max`,`map`,`abs`,`isPositive`,`isNegative`,`larger`,`smaller`,`matrix`,`bignumber`,`unaryMinus`],ex=Y(epe,tpe,e=>{var{typed:t,add:n,subtract:r,multiply:i,divide:a,max:o,map:s,abs:c,isPositive:l,isNegative:u,larger:d,smaller:f,matrix:p,bignumber:m,unaryMinus:h}=e;function g(e){return function(t,p,g,_){if(!(p.length===2&&(p.every(S)||p.every(Tl))))throw Error(`"tspan" must be an Array of two numeric values or two units [tStart, tEnd]`);var v=p[0],y=p[1],C=d(y,v),w=_.firstStep;if(w!==void 0&&!l(w))throw Error(`"firstStep" must be positive`);var T=_.maxStep;if(T!==void 0&&!l(T))throw Error(`"maxStep" must be positive`);var E=_.minStep;if(E&&u(E))throw Error(`"minStep" must be positive or zero`);var D=[v,y,w,E,T].filter(e=>e!==void 0);if(!(D.every(S)||D.every(Tl)))throw Error(`Inconsistent type of "t" dependant variables`);for(var O=1,k=_.tol?_.tol:1e-4,A=_.minDelta?_.minDelta:.2,j=_.maxDelta?_.maxDelta:5,M=_.maxIter?_.maxIter:1e4,N=[v,y,...g,T,E].some(xl),[P,F,I,L]=N?[m(e.a),m(e.c),m(e.b),m(e.bp)]:[e.a,e.c,e.b,e.bp],ee=w?C?w:h(w):a(r(y,v),O),R=[v],te=[g],z=r(I,L),ne=0,B=0,V=b(C),H=x(C);V(R[ne],y);){var re=[];ee=H(R[ne],y,ee),re.push(t(R[ne],te[ne]));for(var ie=1;ie<F.length;++ie)re.push(t(n(R[ne],i(F[ie],ee)),n(te[ne],i(ee,P[ie],re))));var ae=o(c(s(i(z,re),e=>Tl(e)?e.value:e)));ae<k&&k/ae>1/4&&(R.push(n(R[ne],ee)),te.push(n(te[ne],i(ee,I,re))),ne++);var oe=.84*(k/ae)**(1/5);if(f(oe,A)?oe=A:d(oe,j)&&(oe=j),oe=N?m(oe):oe,ee=i(ee,oe),T&&d(c(ee),T)?ee=C?T:h(T):E&&f(c(ee),E)&&(ee=C?E:h(E)),B++,B>M)throw Error(`Maximum number of iterations reached, try changing options`)}return{t:R,y:te}}}function _(e,t,n,r){return g({a:[[],[1/2],[0,3/4],[2/9,1/3,4/9]],c:[null,1/2,3/4,1],b:[2/9,1/3,4/9,0],bp:[7/24,1/4,1/3,1/8]})(e,t,n,r)}function v(e,t,n,r){return g({a:[[],[1/5],[3/40,9/40],[44/45,-56/15,32/9],[19372/6561,-25360/2187,64448/6561,-212/729],[9017/3168,-355/33,46732/5247,49/176,-5103/18656],[35/384,0,500/1113,125/192,-2187/6784,11/84]],c:[null,1/5,3/10,4/5,8/9,1,1],b:[35/384,0,500/1113,125/192,-2187/6784,11/84,0],bp:[5179/57600,0,7571/16695,393/640,-92097/339200,187/2100,1/40]})(e,t,n,r)}function y(e,t,n,r){var i=r.method?r.method:`RK45`,a={RK23:_,RK45:v};if(i.toUpperCase()in a){var o=$fe({},r);return delete o.method,a[i.toUpperCase()](e,t,n,o)}else{var s=Object.keys(a).map(e=>`"${e}"`),c=`${s.slice(0,-1).join(`, `)} and ${s.slice(-1)}`;throw Error(`Unavailable method "${i}". Available methods are ${c}`)}}function b(e){return e?f:d}function x(e){var t=e?d:f;return function(e,i,a){return t(n(e,a),i)?r(i,e):a}}function S(e){return xl(e)||bl(e)}function C(e,t,n,r){var i=y(e,t.toArray(),n.toArray(),r);return{t:p(i.t),y:p(i.y)}}return t(`solveODE`,{"function, Array, Array, Object":y,"function, Matrix, Matrix, Object":C,"function, Array, Array":(e,t,n
vendor: 4,332 bytes, line 2590
2590)=>y(e,t,n,{}),"function, Matrix, Matrix":(e,t,n)=>C(e,t,n,{}),"function, Array, number | BigNumber | Unit":(e,t,n)=>{var r=y(e,t,[n],{});return{t:r.t,y:r.y.map(e=>e[0])}},"function, Matrix, number | BigNumber | Unit":(e,t,n)=>{var r=y(e,t.toArray(),[n],{});return{t:p(r.t),y:p(r.y.map(e=>e[0]))}},"function, Array, number | BigNumber | Unit, Object":(e,t,n,r)=>{var i=y(e,t,[n],r);return{t:i.t,y:i.y.map(e=>e[0])}},"function, Matrix, number | BigNumber | Unit, Object":(e,t,n,r)=>{var i=y(e,t.toArray(),[n],r);return{t:p(i.t),y:p(i.y.map(e=>e[0]))}}})})})),rpe,ipe,tx,ape,ope,nx,rx,spe,cpe=e((()=>{Wp(),Pu(),X(),rpe=`erf`,ipe=[`typed`],tx=Y(rpe,ipe,e=>{var{typed:t}=e;return t(`name`,{number:function(e){var t=Math.abs(e);return t>=spe?Su(e):t<=ape?Su(e)*n(t):t<=4?Su(e)*(1-r(t)):Su(e)*(1-i(t))},"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))});function n(e){var t=e*e,n=nx[0][4]*t,r=t,i;for(i=0;i<3;i+=1)n=(n+nx[0][i])*t,r=(r+rx[0][i])*t;return e*(n+nx[0][3])/(r+rx[0][3])}function r(e){var t=nx[1][8]*e,n=e,r;for(r=0;r<7;r+=1)t=(t+nx[1][r])*e,n=(n+rx[1][r])*e;var i=(t+nx[1][7])/(n+rx[1][7]),a=parseInt(e*16)/16,o=(e-a)*(e+a);return Math.exp(-a*a)*Math.exp(-o)*i}function i(e){var t=1/(e*e),n=nx[2][5]*t,r=t,i;for(i=0;i<4;i+=1)n=(n+nx[2][i])*t,r=(r+rx[2][i])*t;var a=t*(n+nx[2][4])/(r+rx[2][4]);a=(ope-a)/e,t=parseInt(e*16)/16;var o=(e-t)*(e+t);return Math.exp(-t*t)*Math.exp(-o)*a}}),ape=.46875,ope=.5641895835477563,nx=[[3.1611237438705655,113.86415415105016,377.485237685302,3209.3775891384694,.18577770618460315],[.5641884969886701,8.883149794388377,66.11919063714163,298.6351381974001,881.952221241769,1712.0476126340707,2051.0783778260716,1230.3393547979972,2.1531153547440383e-8],[.30532663496123236,.36034489994980445,.12578172611122926,.016083785148742275,.0006587491615298378,.016315387137302097]],rx=[[23.601290952344122,244.02463793444417,1282.6165260773723,2844.236833439171],[15.744926110709835,117.6939508913125,537.1811018620099,1621.3895745666903,3290.7992357334597,4362.619090143247,3439.3676741437216,1230.3393548037495],[2.568520192289822,1.8729528499234604,.5279051029514285,.06051834131244132,.0023352049762686918]],spe=2**53})),ix,lpe,ax,upe=e((()=>{X(),ix=`zeta`,lpe=[`typed`,`config`,`multiply`,`pow`,`divide`,`factorial`,`equal`,`smallerEq`,`isBounded`,`isNegative`,`gamma`,`sin`,`subtract`,`add`,`?Complex`,`?BigNumber`,`pi`],ax=Y(ix,lpe,e=>{var{typed:t,config:n,multiply:r,pow:i,divide:a,factorial:o,equal:s,smallerEq:c,isBounded:l,isNegative:u,gamma:d,sin:f,subtract:p,add:m,Complex:h,BigNumber:g,pi:_}=e;return t(ix,{number:e=>v(e,e=>e,()=>20),BigNumber:e=>v(e,e=>new g(e),()=>Math.abs(Math.log10(n.relTol))),Complex:y});function v(e,t,n){return s(e,0)?t(-.5):s(e,1)?t(NaN):l(e)?b(e,t,n,e=>e):u(e)?t(NaN):t(1)}function y(e){return e.re===0&&e.im===0?new h(-.5):e.re===1?new h(NaN,NaN):e.re===1/0&&e.im===0?new h(1):e.im===1/0||e.re===-1/0?new h(NaN,NaN):b(e,e=>e,e=>Math.round(1.3*15+.9*Math.abs(e.im)),e=>e.re)}function b(e,t,n,o){var s=n(e);if(o(e)>-(s-1)/2)return S(e,t(s),t);var c=r(i(2,e),i(t(_),p(e,1)));return c=r(c,f(r(a(t(_),2),e))),c=r(c,d(p(1,e))),r(c,b(p(1,e),t,n,o))}function x(e,t){for(var n=e,s=e;c(s,t);s=m(s,1)){var l=a(r(o(m(t,p(s,1))),i(4,s)),r(o(p(t,s)),o(r(2,s))));n=m(n,l)}return r(t,n)}function S(e,t,n){for(var o=a(1,r(x(n(0),t),p(1,i(2,p(1,e))))),s=n(0),l=n(1);c(l,t);l=m(l,1))s=m(s,a(r((-1)**(l-1),x(l,t)),i(l,e)));return r(o,s)}})})),ox,dpe,sx,fpe=e((()=>{Tp(),X(),ox=`mode`,dpe=[`typed`,`isNaN`,`isNumeric`],sx=Y(ox,dpe,e=>{var{typed:t,isNaN:n,isNumeric:r}=e;return t(ox,{"Array | Matrix":i,"...":function(e){return i(e)}});function i(e){if(e=cp(e.valueOf()),e.length===0)throw Error(`Cannot calculate mode of an empty array`);for(var t={},i=[],a=0,o=0;o<e.length;o++){var s=e[o];if(r(s)&&n(s))throw Error(`Cannot calculate mode of an array containing NaN values`);s in t||(t[s]=0),t[s]++,t[s]===a?i.push(s):t[s]>a&&(a=t[s],i=[s])}return i}})}));function cx(e,t,n){var r;return String(e).includes(`Unexpected type`)?(r=arguments.length>2?` (type: `+Xl(n)+`, value: `+JSON.stringify(n)+`)`:` (type: `+e.data.actual+`)`,TypeError(`Cannot calculate `+t+`, unexpected type of argument`+r)):String(e).includes(`complex numbers`)?(r=arguments.length>2?` (type: `+Xl(n)+`, value: `+JSON.stringify(n)+`)`:``,TypeError(`Cannot calculate `+t+`, no ordering relation is defined for c
2590omplex numbers`+r)):e}var lx=e((()=>{Ql()})),ux,ppe,dx,mpe=e((()=>{Wp(),X(),Pu(),lx(),ux=`prod`,ppe=[`typed`,`config`,`multiplyScalar`,`numeric`],dx=Y(ux,ppe,e=>{var{typed:t,config:n,multiplyScalar:r,numeric:i}=e;return t(ux,{"Array | Matrix":a,"Array | Matrix, number | BigNumber":function(e,t){throw Error(`prod(A, dim) is not yet supported`)},"...":function(e){return a(e)}});function a(e){var t;if(zp(e,function(e){try{t=t===void 0?e:r(t,e)}catch(t){throw cx(t,`prod`,e)}}),typeof t==`string`&&(t=i(t,uu(t,n))),t===void 0)throw Error(`Cannot calculate prod of an empty array`);return t}})})),fx,hpe,px,gpe=e((()=>{Hf(),X(),fx=`format`,hpe=[`typed`],px=Y(fx,hpe,e=>{var{typed:t}=e;return t(fx,{any:If,"any, Object | function | number | BigNumber":If})})})),mx,_pe,hx,vpe=e((()=>{X(),mx=`bin`,_pe=[`typed`,`format`],hx=Y(mx,_pe,e=>{var{typed:t,format:n}=e;return t(mx,{"number | BigNumber":function(e){return n(e,{notation:`bin`})},"number | BigNumber, number | BigNumber":function(e,t){return n(e,{notation:`bin`,wordSize:t})}})})})),gx,ype,_x,bpe=e((()=>{X(),gx=`oct`,ype=[`typed`,`format`],_x=Y(gx,ype,e=>{var{typed:t,format:n}=e;return t(gx,{"number | BigNumber":function(e){return n(e,{notation:`oct`})},"number | BigNumber, number | BigNumber":function(e,t){return n(e,{notation:`oct`,wordSize:t})}})})})),vx,xpe,yx,Spe=e((()=>{X(),vx=`hex`,xpe=[`typed`,`format`],yx=Y(vx,xpe,e=>{var{typed:t,format:n}=e;return t(vx,{"number | BigNumber":function(e){return n(e,{notation:`hex`})},"number | BigNumber, number | BigNumber":function(e,t){return n(e,{notation:`hex`,wordSize:t})}})})})),bx,Cpe=e((()=>{bx=/\$([\w.]+)/g}));function wpe(e,t,n){return e.replace(bx,function(e,r){var i=r.split(`.`),a=t[i.shift()];for(a!==void 0&&a.isMatrix&&(a=a.toArray());i.length&&a!==void 0;){var o=i.shift();a=o?a[o]:a+`.`}return a===void 0?e:El(a)?a:If(a,n)})}var xx,Tpe,Sx,Epe=e((()=>{Hf(),Ql(),X(),Cpe(),xx=`print`,Tpe=[`typed`],Sx=Y(xx,Tpe,e=>{var{typed:t}=e;return t(xx,{"string, Object | Array":wpe,"string, Object | Array, number | Object":wpe})})})),Cx,Dpe,wx,Ope=e((()=>{X(),iv(),Cx=`to`,Dpe=[`typed`,`matrix`,`concat`],wx=Y(Cx,Dpe,e=>{var{typed:t,matrix:n,concat:r}=e;return t(Cx,{"Unit, Unit | string":(e,t)=>e.to(t)},rv({typed:t,matrix:n,concat:r})({Ds:!0}))})})),Tx,kpe,Ex,Ape=e((()=>{X(),Tx=`toBest`,kpe=[`typed`],Ex=Y(Tx,kpe,e=>{var{typed:t}=e;return t(Tx,{Unit:e=>e.toBest(),"Unit, string":(e,t)=>e.toBest(t.split(`,`)),"Unit, string, Object":(e,t,n)=>e.toBest(t.split(`,`),n),"Unit, Array":(e,t)=>e.toBest(t),"Unit, Array, Object":(e,t,n)=>e.toBest(t,n)})})})),Dx,jpe,Ox,Mpe=e((()=>{Wp(),X(),Dx=`isPrime`,jpe=[`typed`],Ox=Y(Dx,jpe,e=>{var{typed:t}=e;return t(Dx,{number:function(e){if(e<=3)return e>1;if(e%2==0||e%3==0)return!1;for(var t=5;t*t<=e;t+=6)if(e%t===0||e%(t+2)===0)return!1;return!0},bigint:function(e){if(e<=3n)return e>1n;if(e%2n==0n||e%3n==0n)return!1;for(var t=5n;t*t<=e;t+=6n)if(e%t===0n||e%(t+2n)===0n)return!1;return!0},BigNumber:function(e){if(e.lte(3))return e.gt(1);if(e.mod(2).eq(0)||e.mod(3).eq(0))return!1;if(e.lt(2**32)){for(var t=e.toNumber(),n=5;n*n<=t;n+=6)if(t%n===0||t%(n+2)===0)return!1;return!0}function r(e,t,n){for(var r=1;!t.eq(0);)t.mod(2).eq(0)?(t=t.div(2),e=e.mul(e).mod(n)):(t=t.sub(1),r=e.mul(r).mod(n));return r}e=new(e.constructor.clone({precision:e.toFixed(0).length*2}))(e);for(var i=0,a=e.sub(1);a.mod(2).eq(0);)a=a.div(2),i+=1;var o=null;if(e.lt(`3317044064679887385961981`))o=[2,3,5,7,11,13,17,19,23,29,31,37,41].filter(t=>t<e);else{var s=Math.min(e.toNumber()-2,Math.floor(2*(e.toFixed(0).length*Math.log(10))**2));o=[];for(var c=2;c<=s;c+=1)o.push(s)}for(var l=0;l<o.length;l+=1){var u=o[l],d=r(e.sub(e).add(u),a,e);if(!d.eq(1)){for(var f=0,p=d;!p.eq(e.sub(1));f+=1,p=p.mul(p).mod(e))if(f===i-1)return!1}}return!0},"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),Npe,Ppe,kx,Fpe=e((()=>{Ql(),X(),Eb(),Npe=`numeric`,Ppe=[`number`,`?bignumber`,`?fraction`],kx=Y(Npe,Ppe,e=>{var{number:t,bignumber:n,fraction:r}=e,i={string:!0,number:!0,BigNumber:!0,Fraction:!0},a={number:e=>t(e),BigNumber:n?e=>n(e):Tb,bigint:e=>BigInt(e),Fraction:r?e=>r(e):_fe};return function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`number`;if((arguments.length>2?arguments[2]:void 0)!==void 0)throw SyntaxError(`numeric() takes one or tw
2590o arguments`);var n=Xl(e);if(!(n in i))throw TypeError(`Cannot convert `+e+` of type "`+n+`"; valid input types are `+Object.keys(i).join(`, `));if(!(t in a))throw TypeError(`Cannot convert `+e+` to type "`+t+`"; valid output types are `+Object.keys(a).join(`, `));return t===n?e:a[t](e)}})})),Ax,Ipe,jx,Lpe=e((()=>{X(),Ax=`divideScalar`,Ipe=[`typed`,`numeric`],jx=Y(Ax,Ipe,e=>{var{typed:t,numeric:n}=e;return t(Ax,{"number, number":function(e,t){return e/t},"Complex, Complex":function(e,t){return e.div(t)},"BigNumber, BigNumber":function(e,t){return e.div(t)},"bigint, bigint":function(e,t){return e/t},"Fraction, Fraction":function(e,t){return e.div(t)},"Unit, number | Complex | Fraction | BigNumber | Unit":(e,t)=>e.divide(t),"number | Fraction | Complex | BigNumber, Unit":(e,t)=>t.divideInto(e)})})})),Mx,Rpe,Nx,zpe=e((()=>{X(),Pu(),Tp(),ph(),Mx=`pow`,Rpe=[`typed`,`config`,`identity`,`multiply`,`matrix`,`inv`,`fraction`,`number`,`Complex`],Nx=Y(Mx,Rpe,e=>{var{typed:t,config:n,identity:r,multiply:i,matrix:a,inv:o,number:s,fraction:c,Complex:l}=e;return t(Mx,{"number, number":u,"Complex, Complex":function(e,t){return e.pow(t)},"BigNumber, BigNumber":function(e,t){return t.isInteger()||e>=0||n.predictable?e.pow(t):new l(e.toNumber(),0).pow(t.toNumber(),0)},"bigint, bigint":(e,t)=>e**t,"Fraction, Fraction":function(e,t){var r=e.pow(t);if(r!=null)return r;if(n.predictable)throw Error(`Result of pow is non-rational and cannot be expressed as a fraction`);return u(e.valueOf(),t.valueOf())},"Array, number":d,"Array, BigNumber":function(e,t){return d(e,t.toNumber())},"Matrix, number":f,"Matrix, BigNumber":function(e,t){return f(e,t.toNumber())},"Unit, number | BigNumber":function(e,t){return e.pow(t)}});function u(e,t){if(n.predictable&&!lu(t)&&e<0)try{var r=c(t),i=s(r);if((t===i||Math.abs((t-i)/t)<1e-14)&&r.d%2n==1n)return(r.n%2n==0n?1:-1)*(-e)**+t}catch{}return n.predictable&&(e<-1&&t===1/0||e>-1&&e<0&&t===-1/0)?NaN:lu(t)||e>=0||n.predictable?fm(e,t):e*e<1&&t===1/0||e*e>1&&t===-1/0?0:new l(e,0).pow(t,0)}function d(e,t){if(!lu(t))throw TypeError(`For A^b, b must be an integer (value is `+t+`)`);var n=qf(e);if(n.length!==2)throw Error(`For A^b, A must be 2 dimensional (A has `+n.length+` dimensions)`);if(n[0]!==n[1])throw Error(`For A^b, A must be square (size is `+n[0]+`x`+n[1]+`)`);if(t<0)try{return d(o(e),-t)}catch(e){throw e.message===`Cannot calculate inverse, determinant is zero`?TypeError(`For A^b, when A is not invertible, b must be a positive integer (value is `+t+`)`):e}for(var a=r(n[0]).valueOf(),s=e;t>=1;)(t&1)==1&&(a=i(s,a)),t>>=1,s=i(s,s);return a}function f(e,t){return a(d(e.valueOf(),t))}})})),Px,Fx,Bpe,Ix,Vpe=e((()=>{X(),Wp(),Pu(),hh(),a_(),l_(),p_(),ph(),Px=`Number of decimals in function round must be an integer`,Fx=`round`,Bpe=[`typed`,`config`,`matrix`,`equalScalar`,`zeros`,`BigNumber`,`DenseMatrix`],Ix=Y(Fx,Bpe,e=>{var{typed:t,config:n,matrix:r,equalScalar:i,zeros:a,BigNumber:o,DenseMatrix:s}=e,c=i_({typed:t,equalScalar:i}),l=c_({typed:t,DenseMatrix:s}),u=f_({typed:t});function d(e){return Math.abs(mu(e).exponent)}return t(Fx,{number:function(e){var t=pm(e,d(n.relTol));return pm(yu(e,t,n.relTol,n.absTol)?t:e)},"number, number":function(e,t){var r=d(n.relTol);if(t>=r)return pm(e,t);var i=pm(e,r);return pm(yu(e,i,n.relTol,n.absTol)?i:e,t)},"number, BigNumber":function(e,t){if(!t.isInteger())throw TypeError(Px);return new o(e).toDecimalPlaces(t.toNumber())},Complex:function(e){return e.round()},"Complex, number":function(e,t){if(t%1)throw TypeError(Px);return e.round(t)},"Complex, BigNumber":function(e,t){if(!t.isInteger())throw TypeError(Px);var n=t.toNumber();return e.round(n)},BigNumber:function(e){var t=new o(e).toDecimalPlaces(d(n.relTol));return(mh(e,t,n.relTol,n.absTol)?t:e).toDecimalPlaces(0)},"BigNumber, BigNumber":function(e,t){if(!t.isInteger())throw TypeError(Px);var r=d(n.relTol);if(t>=r)return e.toDecimalPlaces(t.toNumber());var i=e.toDecimalPlaces(r);return(mh(e,i,n.relTol,n.absTol)?i:e).toDecimalPlaces(t.toNumber())},bigint:e=>e,"bigint, number":(e,t)=>e,"bigint, BigNumber":(e,t)=>e,Fraction:function(e){return e.round()},"Fraction, number":function(e,t){if(t%1)throw TypeError(Px);return e.round(t)},"Fraction, BigNumber":function(e,t){if(!t.isInteger())throw TypeError(Px);return e.round(t.toNumber())},"Unit, number, Unit":t.referToSelf(e=>function(t,n,r){var i=t.toNumeric(r);return r.multiply(e(i,n))}),"Unit, BigNumber, Unit":t.referToSelf(e=>(t,n,r)=>e(t,n.toNumber(),r)),"Array | Matrix, number | BigNumber, Unit":t.referToSelf(e=>(t,n,r)=>Bp(t,t=>e(t,n,r),!0)),"Array | Matrix | Unit, Unit":t.referToSelf(e=>(t,n)=>e(t,0,n)),"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e,!0)),"SparseMatrix, number | BigNumber":t.referToSelf(e=>(t,n)=>
2590c(t,n,e,!1)),"DenseMatrix, number | BigNumber":t.referToSelf(e=>(t,n)=>u(t,n,e,!1)),"Array, number | BigNumber":t.referToSelf(e=>(t,n)=>u(r(t),n,e,!1).valueOf()),"number | Complex | BigNumber | Fraction, SparseMatrix":t.referToSelf(e=>(t,n)=>i(t,0)?a(n.size(),n.storage()):l(n,t,e,!0)),"number | Complex | BigNumber | Fraction, DenseMatrix":t.referToSelf(e=>(t,n)=>i(t,0)?a(n.size(),n.storage()):u(n,t,e,!0)),"number | Complex | BigNumber | Fraction, Array":t.referToSelf(e=>(t,n)=>u(r(n),t,e,!0).valueOf())})})})),Lx,Hpe,Upe,Rx,Wpe=e((()=>{X(),Lv(),ph(),Lx=`log`,Hpe=[`config`,`typed`,`typeOf`,`divideScalar`,`Complex`],Upe=Math.log(16),Rx=Y(Lx,Hpe,e=>{var{typed:t,typeOf:n,config:r,divideScalar:i,Complex:a}=e;function o(e){return e.log()}function s(e){return o(new a(e,0))}return t(Lx,{number:function(e){return e>=0||r.predictable?am(e):s(e)},bigint:Iv(Upe,am,r,s),Complex:o,BigNumber:function(e){return!e.isNegative()||r.predictable?e.ln():s(e.toNumber())},"any, any":t.referToSelf(e=>(t,r)=>{if(n(t)===`Fraction`&&n(r)===`Fraction`){var a=t.log(r);if(a!==null)return a}return i(e(t),e(r))})})})})),zx,Gpe,Bx,Kpe=e((()=>{X(),Wp(),Pu(),zx=`log1p`,Gpe=[`typed`,`config`,`divideScalar`,`log`,`Complex`],Bx=Y(zx,Gpe,e=>{var{typed:t,config:n,divideScalar:r,log:i,Complex:a}=e;return t(zx,{number:function(e){return e>=-1||n.predictable?Tu(e):o(new a(e,0))},Complex:o,BigNumber:function(e){var t=e.plus(1);return!t.isNegative()||n.predictable?t.ln():o(new a(e.toNumber(),0))},"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e)),"any, any":t.referToSelf(e=>(t,n)=>r(e(t),i(n)))});function o(e){var t=e.re+1;return new a(Math.log(Math.sqrt(t*t+e.im*e.im)),Math.atan2(e.im,t))}})})),Vx,qpe,Hx,Jpe=e((()=>{X(),Vx=`nthRoots`,qpe=[`config`,`typed`,`divideScalar`,`Complex`],Hx=Y(Vx,qpe,e=>{var{typed:t,config:n,divideScalar:r,Complex:i}=e,a=[function(e){return new i(e,0)},function(e){return new i(0,e)},function(e){return new i(-e,0)},function(e){return new i(0,-e)}];function o(e,t){if(t<0)throw Error(`Root must be greater than zero`);if(t===0)throw Error(`Root must be non-zero`);if(t%1!=0)throw Error(`Root must be an integer`);if(e===0||e.abs()===0)return[new i(0,0)];var n=typeof e==`number`,r;(n||e.re===0||e.im===0)&&(r=n?2*(e<0):e.im===0?2*(e.re<0):2*(e.im<0)+1);for(var o=e.arg(),s=e.abs(),c=[],l=s**(1/t),u=0;u<t;u++){var d=(r+4*u)/t;if(d===Math.round(d)){c.push(a[d%4](l));continue}c.push(new i({r:l,phi:(o+2*Math.PI*u)/t}))}return c}return t(Vx,{Complex:function(e){return o(e,2)},"Complex, number":o})})})),Ux,Ype,Wx,Xpe=e((()=>{X(),G_(),Py(),a_(),l_(),iv(),Ux=`dotPow`,Ype=[`typed`,`equalScalar`,`matrix`,`pow`,`DenseMatrix`,`concat`,`SparseMatrix`],Wx=Y(Ux,Ype,e=>{var{typed:t,equalScalar:n,matrix:r,pow:i,DenseMatrix:a,concat:o,SparseMatrix:s}=e,c=W_({typed:t}),l=Ny({typed:t,SparseMatrix:s}),u=i_({typed:t,equalScalar:n}),d=c_({typed:t,DenseMatrix:a}),f=rv({typed:t,matrix:r,concat:o}),p={};for(var m in i.signatures)Object.prototype.hasOwnProperty.call(i.signatures,m)&&!m.includes(`Matrix`)&&!m.includes(`Array`)&&(p[m]=i.signatures[m]);return t(Ux,f({elop:t(p),SS:l,DS:c,Ss:u,sS:d}))})})),Gx,Zpe,Kx,Qpe=e((()=>{X(),V_(),G_(),Py(),a_(),l_(),iv(),Gx=`dotDivide`,Zpe=[`typed`,`matrix`,`equalScalar`,`divideScalar`,`DenseMatrix`,`concat`,`SparseMatrix`],Kx=Y(Gx,Zpe,e=>{var{typed:t,matrix:n,equalScalar:r,divideScalar:i,DenseMatrix:a,concat:o,SparseMatrix:s}=e,c=B_({typed:t,equalScalar:r}),l=W_({typed:t}),u=Ny({typed:t,SparseMatrix:s}),d=i_({typed:t,equalScalar:r}),f=c_({typed:t,DenseMatrix:a});return t(Gx,rv({typed:t,matrix:n,concat:o})({elop:i,SS:u,DS:l,SD:c,Ss:d,sS:f}))})}));function qx(e){var{DenseMatrix:t}=e;return function(e,n,r){var i=e.size();if(i.length!==2)throw RangeError(`Matrix must be two dimensional (size: `+If(i)+`)`);var a=i[0];if(a!==i[1])throw RangeError(`Matrix must be square (size: `+If(i)+`)`);var o=[];if(Dl(n)){var s=n.size(),c=n._data;if(s.length===1){if(s[0]!==a)throw RangeError(`Dimension mismatch. Matrix columns must match vector length.`);for(var l=0;l<a;l++)o[l]=[c[l]];return new t({data:o,size:[a,1],datatype:n._datatype})}if(s.length===2){if(s[0]!==a||s[1]!==1)throw RangeError(`Dimension mismatch. Matrix columns must match vector length.`);if(kl(n)){if(r){o=[];for(var u=0;u<a;u++)o[u]=[c[u][0]];return new t({data:o,size:[a,1],datatype:n._datatype})}return n}if(Al(n)){for(var d=0;d<a;d++)o[d]=[0];for(var f=n._values,p=n._index,m=n._ptr,h=m[1],g=m[0];g<h;g++){var _=p[g];o[_][0]=f[g]}
2590return new t({data:o,size:[a,1],datatype:n._datatype})}}throw RangeError(`Dimension mismatch. The right side has to be either 1- or 2-dimensional vector.`)}if(Zl(n)){var v=qf(n);if(v.length===1){if(v[0]!==a)throw RangeError(`Dimension mismatch. Matrix columns must match vector length.`);for(var y=0;y<a;y++)o[y]=[n[y]];return new t({data:o,size:[a,1]})}if(v.length===2){if(v[0]!==a||v[1]!==1)throw RangeError(`Dimension mismatch. Matrix columns must match vector length.`);for(var b=0;b<a;b++)o[b]=[n[b][0]];return new t({data:o,size:[a,1]})}throw RangeError(`Dimension mismatch. The right side has to be either 1- or 2-dimensional vector.`)}}}var Jx=e((()=>{Ql(),Tp(),Hf()})),Yx,$pe,Xx,eme=e((()=>{X(),Jx(),Yx=`lsolve`,$pe=[`typed`,`matrix`,`divideScalar`,`multiplyScalar`,`subtractScalar`,`equalScalar`,`DenseMatrix`],Xx=Y(Yx,$pe,e=>{var{typed:t,matrix:n,divideScalar:r,multiplyScalar:i,subtractScalar:a,equalScalar:o,DenseMatrix:s}=e,c=qx({DenseMatrix:s});return t(Yx,{"SparseMatrix, Array | Matrix":function(e,t){return u(e,t)},"DenseMatrix, Array | Matrix":function(e,t){return l(e,t)},"Array, Array | Matrix":function(e,t){return l(n(e),t).valueOf()}});function l(e,t){t=c(e,t,!0);for(var n=t._data,l=e._size[0],u=e._size[1],d=[],f=e._data,p=0;p<u;p++){var m=n[p][0]||0,h=void 0;if(o(m,0))h=0;else{var g=f[p][p];if(o(g,0))throw Error(`Linear system cannot be solved since matrix is singular`);h=r(m,g);for(var _=p+1;_<l;_++)n[_]=[a(n[_][0]||0,i(h,f[_][p]))]}d[p]=[h]}return new s({data:d,size:[l,1]})}function u(e,t){t=c(e,t,!0);for(var n=t._data,l=e._size[0],u=e._size[1],d=e._values,f=e._index,p=e._ptr,m=[],h=0;h<u;h++){var g=n[h][0]||0;if(o(g,0))m[h]=[0];else{for(var _=0,v=[],y=[],b=p[h],x=p[h+1],S=b;S<x;S++){var C=f[S];C===h?_=d[S]:C>h&&(v.push(d[S]),y.push(C))}if(o(_,0))throw Error(`Linear system cannot be solved since matrix is singular`);for(var w=r(g,_),T=0,E=y.length;T<E;T++){var D=y[T];n[D]=[a(n[D][0]||0,i(w,v[T]))]}m[h]=[w]}}return new s({data:m,size:[l,1]})}})})),Zx,tme,Qx,nme=e((()=>{X(),Jx(),Zx=`usolve`,tme=[`typed`,`matrix`,`divideScalar`,`multiplyScalar`,`subtractScalar`,`equalScalar`,`DenseMatrix`],Qx=Y(Zx,tme,e=>{var{typed:t,matrix:n,divideScalar:r,multiplyScalar:i,subtractScalar:a,equalScalar:o,DenseMatrix:s}=e,c=qx({DenseMatrix:s});return t(Zx,{"SparseMatrix, Array | Matrix":function(e,t){return u(e,t)},"DenseMatrix, Array | Matrix":function(e,t){return l(e,t)},"Array, Array | Matrix":function(e,t){return l(n(e),t).valueOf()}});function l(e,t){t=c(e,t,!0);for(var n=t._data,l=e._size[0],u=e._size[1],d=[],f=e._data,p=u-1;p>=0;p--){var m=n[p][0]||0,h=void 0;if(o(m,0))h=0;else{var g=f[p][p];if(o(g,0))throw Error(`Linear system cannot be solved since matrix is singular`);h=r(m,g);for(var _=p-1;_>=0;_--)n[_]=[a(n[_][0]||0,i(h,f[_][p]))]}d[p]=[h]}return new s({data:d,size:[l,1]})}function u(e,t){t=c(e,t,!0);for(var n=t._data,l=e._size[0],u=e._size[1],d=e._values,f=e._index,p=e._ptr,m=[],h=u-1;h>=0;h--){var g=n[h][0]||0;if(o(g,0))m[h]=[0];else{for(var _=0,v=[],y=[],b=p[h],x=p[h+1]-1;x>=b;x--){var S=f[x];S===h?_=d[x]:S<h&&(v.push(d[x]),y.push(S))}if(o(_,0))throw Error(`Linear system cannot be solved since matrix is singular`);for(var C=r(g,_),w=0,T=y.length;w<T;w++){var E=y[w];n[E]=[a(n[E][0],i(C,v[w]))]}m[h]=[C]}}return new s({data:m,size:[l,1]})}})})),$x,rme,eS,ime=e((()=>{X(),Jx(),$x=`lsolveAll`,rme=[`typed`,`matrix`,`divideScalar`,`multiplyScalar`,`subtractScalar`,`equalScalar`,`DenseMatrix`],eS=Y($x,rme,e=>{var{typed:t,matrix:n,divideScalar:r,multiplyScalar:i,subtractScalar:a,equalScalar:o,DenseMatrix:s}=e,c=qx({DenseMatrix:s});return t($x,{"SparseMatrix, Array | Matrix":function(e,t){return u(e,t)},"DenseMatrix, Array | Matrix":function(e,t){return l(e,t)},"Array, Array | Matrix":function(e,t){return l(n(e),t).map(e=>e.valueOf())}});function l(e,t){for(var n=[c(e,t,!0)._data.map(e=>e[0])],l=e._data,u=e._size[0],d=e._size[1],f=0;f<d;f++)for(var p=n.length,m=0;m<p;m++){var h=n[m];if(!o(l[f][f],0)){h[f]=r(h[f],l[f][f]);for(var g=f+1;g<d;g++)h[g]=a(h[g],i(h[f],l[g][f]))}else if(!o(h[f],0)){if(m===0)return[];n.splice(m,1),--m,--p}else if(m===0){var _=[...h];_[f]=1;for(var v=f+1;v<d;v++)_[v]=a(_[v],l[v][f]);n.push(_)}}return n.map(e=>new s({data:e.map(e=>[e]),size:[u,1]}))}function u(e,t){for(var n=[c(e,t,!0)._data.map(e=>e[0])],l=e._size[0],u=e._size[1],d=e._values,f=e._index,p=e._ptr,m=0;m<u;m++)for(var h=n.length,g=0;g<h;g++){for(var _=n[g],v=[],y=[],b=p[m],x=p[m+1],S=0,C=b;C<x;C++){var w=f[C];w===m?S=d[C]:w>m&&(v.push(d[C]),y.push(w))}if(!o(S,0)){_[m]=r(_[m],S);for(var T=0,E=y.length;T<E;T++){var D=y[T];_[D]=a(_[D],i(_[m],v[T]))}}else if(!o(_[m],0)){if(g===0)return[];n.splice(g,1),--g,--h}else if(g===0){var O=[..._];O[m]=1;for(var k=0,A=y.length;k<A;k++){var j=y[k];O[j]=a(O[j],v[k])}n.push(O)}}return n.map(e=>new s({data:e.map(e=>[e]),size:[l,1]}))}})})),tS,ame,nS,ome=e((()=>{X(),Jx(),tS=`usolveAll`,ame=[`typed`,`matrix`,`divideScalar`,`multiplyScalar`,`subtractScalar`,`equalScalar`,`DenseMatrix`],nS=Y(tS,ame,e=>{var{typed:t,matrix:n,divideScalar:r,multiplyScalar:i,subtractScalar:a,equalScalar:o,DenseMatrix:s}=e,c=qx({DenseMatrix:s});return t(tS,{"SparseMatrix, Array | Matrix":function(e,t){return u(e,t)},"DenseMatrix, Array | Matrix":function(e,t){return l(e,t)},"Array, Array | Matrix":function(e,t){return l(n(e),t).map(e=>e.valueOf())}});function l(e,t){for(var n=[c(e,t,!0)._data.map(e=>e[0])],l=e._data,u=e._size[0],d=e._size[1]-1;d>=0;d--)for(var f=n.length,p=0;p<f;p++){var m=n[p];if(!o(l[d][d],0)){m[d]=r(m[d],l[d][d]);for(var h=d-1;h>=0;h--)m[h]=a(m[h],i(m[d],l[h][d]))}else if(!o(m[d],0)){if(p===0)return[];n.splice(p,1),--p,--f}else if(p===0){var g=[...m];g[d]=1;for(var _=d-1;_>=0;_--)g[_]=a(g[_],l[_][d]);n.push(g)}}return n.map(e=>new s({data:e.map(e=>[e]),size:[u,1]}))}function u(e,t){for(var n=[c(e,t,!0)._data.map(e=>e[0])],l=e._size[0],u=e._size[1],d=e._values,f=e._index,p=e._ptr,m=u-1;m>=0;m--)for(var h=n.length,g=0;g<h;g++){for(var _=n[g],v=[],y=[],b=p[m],x=p[m+1],S=0,C=x-1;C>=b;C--){var w=f[C];w===m?S=d[C]:w<m&&(v.push(d[C]),y.push(w))}if(!o(S,0)){_[m]=r(_[m],S);for(var T=0,E=y.length;T<E;T++){var D=y[T];_[D]=a(_[D],i(_[m],v[T]))}}else if(!o(_[m],0)){if(g===0)return[];n.splice(g,1),--g,--h}else if(g===0){var O=[..._];O[m]=1;for(var k=0,A=y.length;k<A;k++){var j=y[k];O[j]=a(O[j],v[k])}n.push(O)}}return n.map(e=>new s({data:e.map(e=>[e]),size:[l,1]}))}})})),sme,cme,rS,iS=e((()=>{X(),Wf(),sme=`matAlgo08xS0Sid`,cme=[`typed`,`equalScalar`],rS=Y(sme,cme,e=>{var{typed:t,equalScalar:n}=e;return function(e,r,i){var a=e._values,o=e._index,s=e._ptr,c=e._size,l=e._datatype||e._data===void 0?e._datatype:e.getDataType(),u=r._values,d=r._index,f=r._ptr,p=r._size,m=r._datatype||r._data===void 0?r._datatype:r.getDataType();if(c.length!==p.length)throw new Uf(c.length,p.length);if(c[0]!==p[0]||c[1]!==p[1])throw RangeError(`Dimension mismatch. Matrix A (`+c+`) must match Matrix B (`+p+`)`);if(!a||!u)throw Error(`Cannot perform operation on Pattern Sparse Matrices`);var h=c[0],g=c[1],_,v=n,y=0,b=i;typeof l==`string`&&l===m&&l!==`mixed`&&(_=l,v=t.find(n,[_,_]),y=t.convert(0,_),b=t.find(i,[_,_]));for(var x=[],S=[],C=[],w=[],T=[],E,D,O,k,A=0;A<g;A++){C[A]=S.length;var j=A+1;for(D=s[A],O=s[A+1],E=D;E<O;E++)k=o[E],T[k]=j,w[k]=a[E],S.push(k);for(D=f[A],O=f[A+1],E=D;E<O;E++)k=d[E],T[k]===j&&(w[k]=b(w[k],u[E]));for(E=C[A];E<S.length;){k=S[E];var M=w[k];v(M,y)?S.splice(E,1):(x.push(M),E++)}}return C[g]=S.length,e.createSparseMatrix({values:x,index:S,ptr:C,size:[h,g],datatype:l===e._datatype&&m===r._datatype?_:void 0})}})})),aS,oS=e((()=>{X(),aS=Y(`useMatrixForArrayScalar`,[`typed`,`matrix`],e=>{var{typed:t,matrix:n}=e;return{"Array, number":t.referTo(`DenseMatrix, number`,e=>(t,r)=>e(n(t),r).valueOf()),"Array, BigNumber":t.referTo(`DenseMatrix, BigNumber`,e=>(t,r)=>e(n(t),r).valueOf()),"number, Array":t.referTo(`number, DenseMatrix`,e=>(t,r)=>e(t,n(r)).valueOf()),"BigNumber, Array":t.referTo(`BigNumber, DenseMatrix`,e=>(t,r)=>e(t,n(r)).valueOf())}})})),sS,lme,cS,ume=e((()=>{V_(),a_(),p_(),fv(),bv(),iS(),X(),iv(),oS(),ph(),Ey(),sS=`leftShift`,lme=[`typed`,`matrix`,`equalScalar`,`zeros`,`DenseMatrix`,`concat`],cS=Y(sS,lme,e=>{var{typed:t,matrix:n,equalScalar:r,zeros:i,DenseMatrix:a,concat:o}=e,s=dv({typed:t}),c=B_({typed:t,equalScalar:r}),l=rS({typed:t,equalScalar:r}),u=yv({typed:t,DenseMatrix:a}),d=i_({typed:t,equalScalar:r}),f=f_({typed:t}),p=rv({typed:t,matrix:n,concat:o}),m=aS({typed:t,matrix:n});return t(sS,{"number, number":bm,"BigNumber, BigNumber":dde,"bigint, bigint":(e,t)=>e<<t,"SparseMatrix, number | BigNumber":t.referToSelf(e=>(t,n)=>
vendor: 4,127 bytes, line 2590
2590r(n,0)?t.clone():d(t,n,e,!1)),"DenseMatrix, number | BigNumber":t.referToSelf(e=>(t,n)=>r(n,0)?t.clone():f(t,n,e,!1)),"number | BigNumber, SparseMatrix":t.referToSelf(e=>(t,n)=>r(t,0)?i(n.size(),n.storage()):u(n,t,e,!0)),"number | BigNumber, DenseMatrix":t.referToSelf(e=>(t,n)=>r(t,0)?i(n.size(),n.storage()):f(n,t,e,!0))},m,p({SS:l,DS:s,SD:c}))})})),lS,dme,uS,fme=e((()=>{Ey(),V_(),a_(),p_(),fv(),bv(),iS(),X(),iv(),oS(),ph(),lS=`rightArithShift`,dme=[`typed`,`matrix`,`equalScalar`,`zeros`,`DenseMatrix`,`concat`],uS=Y(lS,dme,e=>{var{typed:t,matrix:n,equalScalar:r,zeros:i,DenseMatrix:a,concat:o}=e,s=dv({typed:t}),c=B_({typed:t,equalScalar:r}),l=rS({typed:t,equalScalar:r}),u=yv({typed:t,DenseMatrix:a}),d=i_({typed:t,equalScalar:r}),f=f_({typed:t}),p=rv({typed:t,matrix:n,concat:o}),m=aS({typed:t,matrix:n});return t(lS,{"number, number":xm,"BigNumber, BigNumber":fde,"bigint, bigint":(e,t)=>e>>t,"SparseMatrix, number | BigNumber":t.referToSelf(e=>(t,n)=>r(n,0)?t.clone():d(t,n,e,!1)),"DenseMatrix, number | BigNumber":t.referToSelf(e=>(t,n)=>r(n,0)?t.clone():f(t,n,e,!1)),"number | BigNumber, SparseMatrix":t.referToSelf(e=>(t,n)=>r(t,0)?i(n.size(),n.storage()):u(n,t,e,!0)),"number | BigNumber, DenseMatrix":t.referToSelf(e=>(t,n)=>r(t,0)?i(n.size(),n.storage()):f(n,t,e,!0))},m,p({SS:l,DS:s,SD:c}))})})),dS,pme,fS,mme=e((()=>{V_(),a_(),p_(),fv(),bv(),iS(),X(),iv(),ph(),oS(),dS=`rightLogShift`,pme=[`typed`,`matrix`,`equalScalar`,`zeros`,`DenseMatrix`,`concat`],fS=Y(dS,pme,e=>{var{typed:t,matrix:n,equalScalar:r,zeros:i,DenseMatrix:a,concat:o}=e,s=dv({typed:t}),c=B_({typed:t,equalScalar:r}),l=rS({typed:t,equalScalar:r}),u=yv({typed:t,DenseMatrix:a}),d=i_({typed:t,equalScalar:r}),f=f_({typed:t}),p=rv({typed:t,matrix:n,concat:o}),m=aS({typed:t,matrix:n});return t(dS,{"number, number":Sm,"SparseMatrix, number | BigNumber":t.referToSelf(e=>(t,n)=>r(n,0)?t.clone():d(t,n,e,!1)),"DenseMatrix, number | BigNumber":t.referToSelf(e=>(t,n)=>r(n,0)?t.clone():f(t,n,e,!1)),"number | BigNumber, SparseMatrix":t.referToSelf(e=>(t,n)=>r(t,0)?i(n.size(),n.storage()):u(n,t,e,!0)),"number | BigNumber, DenseMatrix":t.referToSelf(e=>(t,n)=>r(t,0)?i(n.size(),n.storage()):f(n,t,e,!0))},m,p({SS:l,DS:s,SD:c}))})})),pS,hme,mS,gme=e((()=>{V_(),a_(),p_(),Mv(),X(),iv(),ph(),pS=`and`,hme=[`typed`,`matrix`,`equalScalar`,`zeros`,`not`,`concat`],mS=Y(pS,hme,e=>{var{typed:t,matrix:n,equalScalar:r,zeros:i,not:a,concat:o}=e,s=B_({typed:t,equalScalar:r}),c=jv({typed:t,equalScalar:r}),l=i_({typed:t,equalScalar:r}),u=f_({typed:t}),d=rv({typed:t,matrix:n,concat:o});return t(pS,{"number, number":Im,"Complex, Complex":function(e,t){return(e.re!==0||e.im!==0)&&(t.re!==0||t.im!==0)},"BigNumber, BigNumber":function(e,t){return!e.isZero()&&!t.isZero()&&!e.isNaN()&&!t.isNaN()},"bigint, bigint":Im,"Unit, Unit":t.referToSelf(e=>(t,n)=>e(t.value||0,n.value||0)),"SparseMatrix, any":t.referToSelf(e=>(t,n)=>a(n)?i(t.size(),t.storage()):l(t,n,e,!1)),"DenseMatrix, any":t.referToSelf(e=>(t,n)=>a(n)?i(t.size(),t.storage()):u(t,n,e,!1)),"any, SparseMatrix":t.referToSelf(e=>(t,n)=>a(t)?i(t.size(),t.storage()):l(n,t,e,!0)),"any, DenseMatrix":t.referToSelf(e=>(t,n)=>a(t)?i(t.size(),t.storage()):u(n,t,e,!0)),"Array, any":t.referToSelf(e=>(t,r)=>e(n(t),r).valueOf()),"any, Array":t.referToSelf(e=>(t,r)=>e(t,n(r)).valueOf())},d({SS:c,DS:s}))})})),hS,_me,gS,vme,yme=e((()=>{hh(),Pu(),X(),G_(),l_(),Y_(),iv(),Wh(),hS=`compare`,_me=[`typed`,`config`,`matrix`,`equalScalar`,`BigNumber`,`Fraction`,`DenseMatrix`,`concat`],gS=Y(hS,_me,e=>{var{typed:t,config:n,equalScalar:r,matrix:i,BigNumber:a,Fraction:o,DenseMatrix:s,concat:c}=e,l=W_({typed:t}),u=J_({typed:t,equalScalar:r}),d=c_({typed:t,DenseMatrix:s}),f=rv({typed:t,matrix:i,concat:c}),p=Uh({typed:t});return t(hS,vme({typed:t,config:n}),{"boolean, boolean":function(e,t){return e===t?0:e>t?1:-1},"BigNumber, BigNumber":function(e,t){return mh(e,t,n.relTol,n.absTol)?new a(0):new a(e.cmp(t))},"bigint, bigint":function(e,t){return e===t?0n:e>t?1n:-1n},"Fraction, Fraction":function(e,t){return new o(e.compare(t))},"Complex, Complex":function(){throw TypeError(`No ordering relation is defined for c
2590omplex numbers`)}},p,f({SS:u,DS:l,Ss:d}))}),vme=Y(hS,[`typed`,`config`],e=>{var{typed:t,config:n}=e;return t(hS,{"number, number":function(e,t){return yu(e,t,n.relTol,n.absTol)?0:e>t?1:-1}})})})),bme=r(((e,t)=>{t.exports=function e(t,n){var r=/(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi,i=/(^[ ]*|[ ]*$)/g,a=/(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,o=/^0x[0-9a-f]+$/i,s=/^0/,c=function(t){return e.insensitive&&(``+t).toLowerCase()||``+t},l=c(t).replace(i,``)||``,u=c(n).replace(i,``)||``,d=l.replace(r,`\0$1\0`).replace(/\0$/,``).replace(/^\0/,``).split(`\0`),f=u.replace(r,`\0$1\0`).replace(/\0$/,``).replace(/^\0/,``).split(`\0`),p=parseInt(l.match(o),16)||d.length!==1&&l.match(a)&&Date.parse(l),m=parseInt(u.match(o),16)||p&&u.match(a)&&Date.parse(u)||null,h,g;if(m){if(p<m)return-1;if(p>m)return 1}for(var _=0,v=Math.max(d.length,f.length);_<v;_++){if(h=!(d[_]||``).match(s)&&parseFloat(d[_])||d[_]||0,g=!(f[_]||``).match(s)&&parseFloat(f[_])||f[_]||0,isNaN(h)!==isNaN(g))return isNaN(h)?1:-1;if(typeof h!=typeof g&&(h+=``,g+=``),h<g)return-1;if(h>g)return 1}return 0}}));function xme(e,t){return e.re>t.re?1:e.re<t.re?-1:e.im>t.im?1:e.im<t.im?-1:0}var _S,vS,Sme,yS,Cme=e((()=>{_S=t(bme(),1),Ql(),X(),vS=`compareNatural`,Sme=[`typed`,`compare`],yS=Y(vS,Sme,e=>{var{typed:t,compare:n}=e,r=n.signatures[`boolean,boolean`];return t(vS,{"any, any":i});function i(e,t){var c=Xl(e),l=Xl(t),u;if((c===`number`||c===`BigNumber`||c===`Fraction`||c===`bigint`)&&(l===`number`||l===`BigNumber`||l===`Fraction`||l===`bigint`))return u=n(e,t),u.toString()===`0`?(0,_S.default)(c,l):u>0?1:-1;var d=[`Array`,`DenseMatrix`,`SparseMatrix`];if(d.includes(c)||d.includes(l))return u=a(i,e,t),u===0?(0,_S.default)(c,l):u;if(c!==l)return(0,_S.default)(c,l);if(c===`Complex`)return xme(e,t);if(c===`Unit`)return e.equalBase(t)?i(e.value,t.value):o(i,e.formatUnits(),t.formatUnits());if(c===`boolean`)return r(e,t);if(c===`string`)return(0,_S.default)(e,t);if(c===`Object`)return s(i,e,t);if(c===`null`||c===`undefined`)return 0;throw TypeError(`Unsupported type of value "`+c+`"`)}function a(e,t,n){return Al(t)&&Al(n)?o(e,t.toJSON().values,n.toJSON().values):Al(t)?a(e,t.toArray(),n):Al(n)?a(e,t,n.toArray()):kl(t)?a(e,t.toJSON().data,n):kl(n)?a(e,t,n.toJSON().data):Array.isArray(t)?Array.isArray(n)?o(e,t,n):a(e,t,[n]):a(e,[t],n)}function o(e,t,n){for(var r=0,i=Math.min(t.length,n.length);r<i;r++){var a=e(t[r],n[r]);if(a!==0)return a}return t.length>n.length?1:t.length<n.length?-1:0}function s(e,t,n){var r=Object.keys(t),i=Object.keys(n);r.sort(_S.default),i.sort(_S.default);var a=o(e,r,i);if(a!==0)return a;for(var s=0;s<r.length;s++){var c=e(t[r[s]],n[i[s]]);if(c!==0)return c}return 0}})})),bS,wme,xS,Tme=e((()=>{Hf(),X(),iv(),bS=`compareText`,wme=[`typed`,`matrix`,`concat`],Bf.signature=`any, any`,xS=Y(bS,wme,e=>{var{typed:t,matrix:n,concat:r}=e;return t(bS,Bf,rv({typed:t,matrix:n,concat:r})({elop:Bf,Ds:!0}))})})),SS,Eme,CS,Dme,Ome=e((()=>{X(),G_(),Py(),l_(),iv(),SS=`equal`,Eme=[`typed`,`matrix`,`equalScalar`,`DenseMatrix`,`SparseMatrix`],CS=Y(SS,Eme,e=>{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:i,concat:a,SparseMatrix:o}=e,s=W_({typed:t}),c=Ny({typed:t,SparseMatrix:o}),l=c_({typed:t,DenseMatrix:i}),u=rv({typed:t,matrix:n});return t(SS,Dme({typed:t,equalScalar:r}),u({elop:r,SS:c,DS:s,Ss:l}))}),Dme=Y(SS,[`typed`,`equalScalar`],e=>{var{typed:t,equalScalar:n}=e;return t(SS,{"any, any":function(e,t){return e===null?t===null:t===null?e===null:e===void 0?t===void 0:t===void 0?e===void 0:n(e,t)}})})})),wS,kme,TS,Ame=e((()=>{X(),wS=`equalText`,kme=[`typed`,`compareText`,`isZero`],TS=Y(wS,kme,e=>{var{typed:t,compareText:n,isZero:r}=e;return t(wS,{"any, any":function(e,t){return r(n(e,t))}})})})),ES,jme,DS,Mme,Nme=e((()=>{hh(),Pu(),X(),G_(),Py(),l_(),iv(),Wh(),ES=`smaller`,jme=[`typed`,`config`,`bignumber`,`matrix`,`DenseMatrix`,`concat`,`SparseMatrix`],DS=Y(ES,jme,e=>{var{typed:t,config:n,bignumber:r,matrix:i,DenseMatrix:a,concat:o,SparseMatrix:s}=e,c=W_({typed:t}),l=Ny({typed:t,SparseMatrix:s}),u=c_({typed:t,DenseMatrix:a}),d=rv({typed:t,matrix:i,concat:o}),f=Uh({typed:t});function p(e,t){return e.lt(t)&&!mh(e,t,n.relTol,n.absTol)}return t(ES,Mme({typed:t,config:n}),{"boolean, boolean":(e,t)=>
2590e<t,"BigNumber, BigNumber":p,"bigint, bigint":(e,t)=>e<t,"Fraction, Fraction":(e,t)=>e.compare(t)===-1,"Fraction, BigNumber":function(e,t){return p(r(e),t)},"BigNumber, Fraction":function(e,t){return p(e,r(t))},"Complex, Complex":function(e,t){throw TypeError(`No ordering relation is defined for complex numbers`)}},f,d({SS:l,DS:c,Ss:u}))}),Mme=Y(ES,[`typed`,`config`],e=>{var{typed:t,config:n}=e;return t(ES,{"number, number":function(e,t){return e<t&&!yu(e,t,n.relTol,n.absTol)}})})})),OS,Pme,kS,Fme,Ime=e((()=>{hh(),Pu(),X(),G_(),Py(),l_(),iv(),Wh(),OS=`smallerEq`,Pme=[`typed`,`config`,`matrix`,`DenseMatrix`,`concat`,`SparseMatrix`],kS=Y(OS,Pme,e=>{var{typed:t,config:n,matrix:r,DenseMatrix:i,concat:a,SparseMatrix:o}=e,s=W_({typed:t}),c=Ny({typed:t,SparseMatrix:o}),l=c_({typed:t,DenseMatrix:i}),u=rv({typed:t,matrix:r,concat:a}),d=Uh({typed:t});return t(OS,Fme({typed:t,config:n}),{"boolean, boolean":(e,t)=>e<=t,"BigNumber, BigNumber":function(e,t){return e.lte(t)||mh(e,t,n.relTol,n.absTol)},"bigint, bigint":(e,t)=>e<=t,"Fraction, Fraction":(e,t)=>e.compare(t)!==1,"Complex, Complex":function(){throw TypeError(`No ordering relation is defined for complex numbers`)}},d,u({SS:c,DS:s,Ss:l}))}),Fme=Y(OS,[`typed`,`config`],e=>{var{typed:t,config:n}=e;return t(OS,{"number, number":function(e,t){return e<=t||yu(e,t,n.relTol,n.absTol)}})})})),AS,Lme,jS,Rme,zme=e((()=>{hh(),Pu(),X(),G_(),Py(),l_(),iv(),Wh(),AS=`larger`,Lme=[`typed`,`config`,`bignumber`,`matrix`,`DenseMatrix`,`concat`,`SparseMatrix`],jS=Y(AS,Lme,e=>{var{typed:t,config:n,bignumber:r,matrix:i,DenseMatrix:a,concat:o,SparseMatrix:s}=e,c=W_({typed:t}),l=Ny({typed:t,SparseMatrix:s}),u=c_({typed:t,DenseMatrix:a}),d=rv({typed:t,matrix:i,concat:o}),f=Uh({typed:t});function p(e,t){return e.gt(t)&&!mh(e,t,n.relTol,n.absTol)}return t(AS,Rme({typed:t,config:n}),{"boolean, boolean":(e,t)=>
2590e>t,"BigNumber, BigNumber":p,"bigint, bigint":(e,t)=>e>t,"Fraction, Fraction":(e,t)=>e.compare(t)===1,"Fraction, BigNumber":function(e,t){return p(r(e),t)},"BigNumber, Fraction":function(e,t){return p(e,r(t))},"Complex, Complex":function(){throw TypeError(`No ordering relation is defined for complex numbers`)}},f,d({SS:l,DS:c,Ss:u}))}),Rme=Y(AS,[`typed`,`config`],e=>{var{typed:t,config:n}=e;return t(AS,{"number, number":function(e,t){return e>t&&!yu(e,t,n.relTol,n.absTol)}})})})),MS,Bme,NS,Vme,Hme=e((()=>{hh(),Pu(),X(),G_(),Py(),l_(),iv(),Wh(),MS=`largerEq`,Bme=[`typed`,`config`,`matrix`,`DenseMatrix`,`concat`,`SparseMatrix`],NS=Y(MS,Bme,e=>{var{typed:t,config:n,matrix:r,DenseMatrix:i,concat:a,SparseMatrix:o}=e,s=W_({typed:t}),c=Ny({typed:t,SparseMatrix:o}),l=c_({typed:t,DenseMatrix:i}),u=rv({typed:t,matrix:r,concat:a}),d=Uh({typed:t});return t(MS,Vme({typed:t,config:n}),{"boolean, boolean":(e,t)=>e>=t,"BigNumber, BigNumber":function(e,t){return e.gte(t)||mh(e,t,n.relTol,n.absTol)},"bigint, bigint":function(e,t){return e>=t},"Fraction, Fraction":(e,t)=>e.compare(t)!==-1,"Complex, Complex":function(){throw TypeError(`No ordering relation is defined for complex numbers`)}},d,u({SS:c,DS:s,Ss:l}))}),Vme=Y(MS,[`typed`,`config`],e=>{var{typed:t,config:n}=e;return t(MS,{"number, number":function(e,t){return e>=t||yu(e,t,n.relTol,n.absTol)}})})})),PS,Ume,FS,Wme=e((()=>{X(),PS=`deepEqual`,Ume=[`typed`,`equal`],FS=Y(PS,Ume,e=>{var{typed:t,equal:n}=e;return t(PS,{"any, any":function(e,t){return r(e.valueOf(),t.valueOf())}});function r(e,t){if(Array.isArray(e))if(Array.isArray(t)){var i=e.length;if(i!==t.length)return!1;for(var a=0;a<i;a++)if(!r(e[a],t[a]))return!1;return!0}else return!1;else if(Array.isArray(t))return!1;else return n(e,t)}})})),IS,Gme,LS,Kme,qme=e((()=>{X(),G_(),Py(),l_(),iv(),IS=`unequal`,Gme=[`typed`,`config`,`equalScalar`,`matrix`,`DenseMatrix`,`concat`,`SparseMatrix`],LS=Y(IS,Gme,e=>{var{typed:t,config:n,equalScalar:r,matrix:i,DenseMatrix:a,concat:o,SparseMatrix:s}=e,c=W_({typed:t}),l=Ny({typed:t,SparseMatrix:s}),u=c_({typed:t,DenseMatrix:a}),d=rv({typed:t,matrix:i,concat:o});return t(IS,Kme({typed:t,equalScalar:r}),d({elop:f,SS:l,DS:c,Ss:u}));function f(e,t){return!r(e,t)}}),Kme=Y(IS,[`typed`,`equalScalar`],e=>{var{typed:t,equalScalar:n}=e;return t(IS,{"any, any":function(e,t){return e===null?t!==null:t===null?e!==null:e===void 0?t!==void 0:t===void 0?e!==void 0:!n(e,t)}})})})),RS,Jme,zS,Yme=e((()=>{Ql(),Pu(),X(),RS=`partitionSelect`,Jme=[`typed`,`isNumeric`,`isNaN`,`compare`],zS=Y(RS,Jme,e=>{var{typed:t,isNumeric:n,isNaN:r,compare:i}=e,a=i,o=(e,t)=>-i(e,t);return t(RS,{"Array | Matrix, number":function(e,t){return s(e,t,a)},"Array | Matrix, number, string":function(e,t,n){if(n===`asc`)return s(e,t,a);if(n===`desc`)return s(e,t,o);throw Error(`Compare string must be "asc" or "desc"`)},"Array | Matrix, number, function":s});function s(e,t,n){if(!lu(t)||t<0)throw Error(`k must be a non-negative integer`);if(Dl(e)){if(e.size().length>1)throw Error(`Only one dimensional matrices supported`);return c(e.valueOf(),t,n)}if(Array.isArray(e))return c(e,t,n)}function c(e,t,i){if(t>=e.length)throw Error(`k out of bounds`);for(var a=0;a<e.length;a++)if(n(e[a])&&r(e[a]))return e[a];for(var o=0,s=e.length-1;o<s;){for(var c=o,l=s,u=e[Math.floor(Math.random()*(s-o+1))+o];c<l;)if(i(e[c],u)>=0){var d=e[l];e[l]=e[c],e[c]=d,--l}else ++c;i(e[c],u)>0&&--c,t<=c?s=c:o=c+1}return e[t]}})})),BS,Xme,VS,Zme=e((()=>{Tp(),X(),BS=`sort`,Xme=[`typed`,`matrix`,`compare`,`compareNatural`],VS=Y(BS,Xme,e=>{var{typed:t,matrix:n,compare:r,compareNatural:i}=e,a=r,o=(e,t)=>-r(e,t);return t(BS,{Array:function(e){return c(e),e.sort(a)},Matrix:function(e){return l(e),n(e.toArray().sort(a),e.storage())},"Array, function":function(e,t){return c(e),e.sort(t)},"Matrix, function":function(e,t){return l(e),n(e.toArray().sort(t),e.storage())},"Array, string":function(e,t){return c(e),e.sort(s(t))},"Matrix, string":function(e,t){return l(e),n(e.toArray().sort(s(t)),e.storage())}});function s(e){if(e===`asc`)return a;
2590if(e===`desc`)return o;if(e===`natural`)return i;throw Error(`String "asc", "desc", or "natural" expected`)}function c(e){if(qf(e).length!==1)throw Error(`One dimensional array expected`)}function l(e){if(e.size().length!==1)throw Error(`One dimensional matrix expected`)}})})),HS,Qme,US,$me=e((()=>{Wp(),X(),Pu(),lx(),HS=`max`,Qme=[`typed`,`config`,`numeric`,`larger`,`isNaN`],US=Y(HS,Qme,e=>{var{typed:t,config:n,numeric:r,larger:i,isNaN:a}=e;return t(HS,{"Array | Matrix":s,"Array | Matrix, number | BigNumber":function(e,t){return Vp(e,t.valueOf(),o)},"...":function(e){if(Rp(e))throw TypeError(`Scalar values expected in function max`);return s(e)}});function o(e,t){try{return i(e,t)?e:t}catch(e){throw cx(e,`max`,t)}}function s(e){var t;if(zp(e,function(e){try{(a(e)||t===void 0||i(e,t))&&(t=e)}catch(t){throw cx(t,`max`,e)}}),t===void 0)throw Error(`Cannot calculate max of an empty array`);return typeof t==`string`&&(t=r(t,uu(t,n))),t}})})),WS,ehe,GS,the=e((()=>{Wp(),X(),Pu(),lx(),WS=`min`,ehe=[`typed`,`config`,`numeric`,`smaller`,`isNaN`],GS=Y(WS,ehe,e=>{var{typed:t,config:n,numeric:r,smaller:i,isNaN:a}=e;return t(WS,{"Array | Matrix":s,"Array | Matrix, number | BigNumber":function(e,t){return Vp(e,t.valueOf(),o)},"...":function(e){if(Rp(e))throw TypeError(`Scalar values expected in function min`);return s(e)}});function o(e,t){try{return i(e,t)?e:t}catch(e){throw cx(e,`min`,t)}}function s(e){var t;if(zp(e,function(e){try{(a(e)||t===void 0||i(e,t))&&(t=e)}catch(t){throw cx(t,`min`,e)}}),t===void 0)throw Error(`Cannot calculate min of an empty array`);return typeof t==`string`&&(t=r(t,uu(t,n))),t}})})),nhe,rhe,KS,ihe=e((()=>{Ql(),ru(),X(),nhe=`ImmutableDenseMatrix`,rhe=[`smaller`,`DenseMatrix`],KS=Y(nhe,rhe,e=>{var{smaller:t,DenseMatrix:n}=e;function r(e,t){if(!(this instanceof r))throw SyntaxError(`Constructor must be called with the new operator`);if(t&&!El(t))throw Error(`Invalid datatype: `+t);if(Dl(e)||Zl(e)){var i=new n(e,t);this._data=i._data,this._size=i._size,this._datatype=i._datatype,this._min=null,this._max=null}else if(e&&Zl(e.data)&&Zl(e.size))this._data=e.data,this._size=e.size,this._datatype=e.datatype,this._min=e.min===void 0?null:e.min,this._max=e.max===void 0?null:e.max;else if(e)throw TypeError(`Unsupported type of data (`+Xl(e)+`)`);else this._data=[],this._size=[0],this._datatype=t,this._min=null,this._max=null}return r.prototype=new n,r.prototype.type=`ImmutableDenseMatrix`,r.prototype.isImmutableDenseMatrix=!0,r.prototype.subset=function(e){switch(arguments.length){case 1:var t=n.prototype.subset.call(this,e);return Dl(t)?new r({data:t._data,size:t._size,datatype:t._datatype}):t;case 2:case 3:throw Error(`Cannot invoke set subset on an Immutable Matrix instance`);default:throw SyntaxError(`Wrong number of arguments`)}},r.prototype.set=function(){throw Error(`Cannot invoke set on an Immutable Matrix instance`)},r.prototype.resize=function(){throw Error(`Cannot invoke resize on an Immutable Matrix instance`)},r.prototype.reshape=function(){throw Error(`Cannot invoke reshape on an Immutable Matrix instance`)},r.prototype.clone=function(){return new r({data:$l(this._data),size:$l(this._size),datatype:this._datatype})},r.prototype.toJSON=function(){return{mathjs:`ImmutableDenseMatrix`,data:this._data,size:this._size,datatype:this._datatype}},r.fromJSON=function(e){return new r(e)},r.prototype.swapRows=function(){throw Error(`Cannot invoke swapRows on an Immutable Matrix instance`)},r.prototype.min=function(){if(this._min===null){var e=null;this.forEach(function(n){(e===null||t(n,e))&&(e=n)}),this._min=e===null?void 0:e}return this._min},r.prototype.max=function(){if(this._max===null){var e=null;this.forEach(function(n){(e===null||t(e,n))&&(e=n)}),this._max=e===null?void 0:e}return this._max},r},{isClass:!0})}));function ahe(e){var t=[];return e.forEach((e,n)=>{e&&t.push(n)}),t}var ohe,she,qS,che=e((()=>{Ql(),ru(),Pu(),X(),ohe=`Index`,she=[`ImmutableDenseMatrix`,`getMatrixDataType`],qS=Y(ohe,she,e=>{var{ImmutableDenseMatrix:t,getMatrixDataType:n}=e;function r(){if(!(this instanceof r))throw SyntaxError(`Constructor must be called with the new operator`);this._dimensions=[],this._sourceSize=[],this._isScalar=!0;for(var e=0,t=arguments.length;e<t;e++){var a=e<0||arguments.length<=e?void 0:arguments[e],o=Zl(a),s=Dl(a),c=typeof a,l=null;if(jl(a))this._dimensions.push(a),this._isScalar=!1;else if(o||s){var u=void 0;this._isScalar=!1,n(a)===`boolean`?(o&&(u=i(ahe(a).valueOf())),s&&(u=i(ahe(a._data).valueOf())),l=a.valueOf().length):u=i(a.valueOf()),this._dimensions.push(u)}else if(c===`number`)this._dimensions.push(a);else if(c===`bigint`)this._dimensions.push(Number(a));else if(c===`string`)this._dimensions.push(a);else throw TypeError(`Dimension must be an Array, Matrix, number, bigint, string, or Range`);this._sourceSize.push(l)}}r.prototype.type=`Index`,r.prototype.isIndex=!0;function i(e){for(var n=0,r=e.length;n<r;n++)if(!bl(e[n])||!lu(e[n]))throw TypeError(`Index parameters must be positive integer numbers`);var i=new t;return i._data=e,i._size=[e.length],i}return r.prototype.clone=function(){var e=new r;return e._dimensions=$l(this._dimensions),e._isScalar=this._isScalar,e._sourceSize=this._sourceSize,e},r.create=function(e){var t=new r;return r.apply(t,e),t},r.prototype.size=function(){for(var e=[],t=0,n=this._dimensions.length;t<n;t++){var r=this._dimensions[t];e[t]=El(r)||bl(r)?1:r.size()[0]}return e},r.prototype.max=function(){for(var e=[],t=0,n=this._dimensions.length;t<n;t++){var r=this._dimensions[t];e[t]=El(r)||bl(r)?r:r.max()}return e},r.prototype.min=function(){for(var e=[],t=0,n=this._dimensions.length;t<n;t++){var r=this._dimensions[t];e[t]=El(r)||bl(r)?r:r.min()}return e},r.prototype.forEach=function(e){for(var t=0,n=this._dimensions.length;t<n;t++)e(this._dimensions[t],t,this)},r.prototype.dimension=function(e){return bl(e)?this._dimensions[e]??null:null},r.prototype.isObjectProperty=function(){return this._dimensions.length===1&&El(this._dimensions[0])},r.prototype.getObjectProperty=function(){return this.isObjectProperty()?this._dimensions[0]:null},r.prototype.isScalar=function(){return this._isScalar},r.prototype.toArray=function(){for(var e=[],t=0,n=this._dimensions.length;t<n;t++){var r=this._dimensions[t];e.push(El(r)||bl(r)?r:r.toArray())}return e},r.prototype.valueOf=r.prototype.toArray,r.prototype.toString=function(){for(var e=[],t=0,n=this._dimensions.length;t<n;t++){var r=this._dimensions[t];El(r)?e.push(JSON.stringify(r)):e.push(r.toString())}return`[`+e.join(`, `)+`]`},r.prototype.toJSON=function(){return{mathjs:`Index`,dimensions:this._dimensions}},r.fromJSON=function(e){return r.create(e.dimensions)},r},{isClass:!0})})),lhe,uhe,JS,dhe=e((()=>{X(),lhe=`FibonacciHeap`,uhe=[`smaller`,`larger`],JS=Y(lhe,uhe,e=>{var{smaller:t,larger:n}=e,r=1/Math.log((1+Math.sqrt(5))/2);function i(){if(!(this instanceof i))throw SyntaxError(`Constructor must be called with the new operator`);this._minimum=null,this._size=0}i.prototype.type=`FibonacciHeap`,i.prototype.isFibonacciHeap=!0,i.prototype.insert=function(e,n){var r={key:e,value:n,degree:0};if(this._minimum){var i=this._minimum;r.left=i,r.right=i.right,i.right=r,r.right.left=r,t(e,i.key)&&(this._minimum=r)}else r.left=r,r.right=r,this._minimum=r;return this._size++,r},i.prototype.size=function(){return this._size},i.prototype.clear=function(){this._minimum=null,this._size=0},i.prototype.isEmpty=function(){return this._size===0},i.prototype.extractMinimum=function(){var e=this._minimum;if(e===null)return e;for(var t=this._minimum,n=e.degree,r=e.child;n>0;){var i=r.right;r.left.right=r.right,r.right.left=r.left,r.left=t,r.right=t.right,t.right=r,r.right.left=r,r.parent=null,r=i,n--}return e.left.right=e.right,e.right.left=e.left,e===e.right?t=null:(t=e.right,t=l(t,this._size)),this._size--,this._minimum=t,e},i.prototype.remove=function(e){this._minimum=a(this._minimum,e,-1),this.extractMinimum()};function a(e,n,r){n.key=r;var i=n.parent;return i&&t(n.key,i.key)&&(o(e,n,i),s(e,i)),t(n.key,e.key)&&(e=n),e}function o(e,t,n){t.left.right=t.right,t.right.left=t.left,n.degree--,n.child===t&&(n.child=t.right),n.degree===0&&(n.child=null),t.left=e,t.right=e.right,e.right=t,t.right.left=t,t.parent=null,t.mark=!1}function s(e,t){var n=t.parent;n&&(t.mark?(o(e,t,n),s(n)):t.mark=!0)}var c=function(e,t){e.left.right=e.right,e.right.left=e.left,e.parent=t,t.child?(e.left=t.child,e.right=t.child.right,t.child.right=e,e.right.left=e):(t.child=e,e.right=e,e.left=e),t.degree++,e.mark=!1};function l(e,i){var a=Math.floor(Math.log(i)*r)+1,o=Array(a),s=0,l=e;if(l)for(s++,l=l.right;l!==e;)s++,l=l.right;for(var u;s>0;){for(var d=l.degree,f=l.right;u=o[d],u;){if(n(l.key,u.key)){var p=u;u=l,l=p}c(u,l),o[d]=null,d++}o[d]=l,l=f,s--}e=null;for(var m=0;m<a;m++)u=o[m],u&&(e?(u.left.right=u.right,u.right.left=u.left,u.left=e,u.right=e.right,e.right=u,u.right.left=u,t(u.key,e.key)&&(e=u)):e=u);return e}return i},{isClass:!0})})),fhe,phe,YS,mhe=e((()=>{X(),fhe=`Spa`,phe=[`addScalar`,`equalScalar`,`FibonacciHeap`],YS=Y(fhe,phe,e=>{var{addScalar:t,equalScalar:n,FibonacciHeap:r}=e;function i(){if(!(this instanceof i))throw SyntaxError(`Constructor must be called with the new operator`);this._values=[],this._heap=new r}return i.prototype.type=`Spa`,i.prototype.isSpa=!0,i.prototype.set=function(e,t){if(this._values[e])this._values[e].value=t;else{var n=this._heap.insert(e,t);this._values[e]=n}},i.prototype.get=function(e){var t=this._values[e];return t?t.value:0},i.prototype.accumulate=function(e,n){var r=this._values[e];r?r.value=t(r.value,n):(r=this._heap.insert(e,n),this._values[e]=r)},i.prototype.forEach=function(e,t,r){var i=this._heap,a=this._values,o=[],s=i.extractMinimum();for(s&&o.push(s);s&&s.key<=t;)s.key>=e&&(n(s.value,0)||r(s.key,s.value,this)),s=i.extractMinimum(),s&&o.push(s);for(var c=0;c<o.length;c++){var l=o[c];s=i.insert(l.key,l.value),a[s.key]=s}},i.prototype.swap=function(e,t){var n=this._values[e],r=this._values[t];if(!n&&r)n=this._heap.insert(e,r.value),this._heap.remove(r),this._values[e]=n,this._values[t]=void 0;else if(n&&!r)r=this._heap.insert(t,n.value),this._heap.remove(n),this._values[t]=r,this._values[e]=void 0;else if(n&&r){var i=n.value;n.value=r.value,r.value=i}},i},{isClass:!0})}));function hhe(e){var t=0,n=1,r=Object.create(null),i=Object.create(null),a=0,o=function(e){var o=i[e];if(o&&(delete r[o],delete i[e],--t,n===o)){if(!t){a=0,n=1;return}for(;!Object.prototype.hasOwnProperty.call(r,++n););}};return e=Math.abs(e),{hit:function(s){var c=i[s],l=++a;if(r[l]=s,i[s]=l,!c)return++t,t<=e?void 0:(s=r[n],o(s),s);if(delete r[c],n===c)for(;!Object.prototype.hasOwnProperty.call(r,++n););},delete:o,clear:function(){t=a=0,n=1,r=Object.create(null),i=Object.create(null)}}}var ghe=e((()=>{}));function XS(e){var{hasher:t,limit:n}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return n??=1/0,t??=JSON.stringify,function r(){typeof r.cache!=`object`&&(r.cache={values:new Map,lru:hhe(n||
25901/0)});var i=[...arguments],a=t(i);if(r.cache.values.has(a))return r.cache.lru.hit(a),r.cache.values.get(a);var o=e.apply(e,i);return r.cache.values.set(a,o),r.cache.values.delete(r.cache.lru.hit(a)),o}}var _he=e((()=>{ghe()}));function ZS(e){return e[0].precision}var vhe,yhe,QS,bhe,xhe=e((()=>{_he(),vhe=XS(function(e){return new e(1).exp()},{hasher:ZS}),yhe=XS(function(e){return new e(1).plus(new e(5).sqrt()).div(2)},{hasher:ZS}),QS=XS(function(e){return e.acos(-1)},{hasher:ZS}),bhe=XS(function(e){return QS(e).times(2)},{hasher:ZS})}));function She(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function $S(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?She(Object(n),!0).forEach(function(t){Rn(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):She(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var Che,whe,eC,The=e((()=>{Ln(),Bn(),Ql(),X(),_he(),Hf(),ru(),xhe(),Che=`Unit`,whe=[`?on`,`config`,`addScalar`,`subtractScalar`,`multiplyScalar`,`divideScalar`,`pow`,`abs`,`fix`,`round`,`equal`,`isNumeric`,`format`,`number`,`Complex`,`BigNumber`,`Fraction`],eC=Y(Che,whe,e=>{var{on:t,config:n,addScalar:r,subtractScalar:i,multiplyScalar:a,divideScalar:o,pow:s,abs:c,fix:l,round:u,equal:d,isNumeric:f,format:p,number:m,Complex:h,BigNumber:g,Fraction:_}=e,v=m,y=!1,b=!0;function x(e,t){if(!(this instanceof x))throw Error(`Constructor must be called with the new operator`);if(!(e==null||f(e)||Cl(e)))throw TypeError(`First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined`);if(this.fixPrefix=y,this.skipAutomaticSimplification=b,t===void 0)this.units=[],this.dimensions=te.map(e=>0);else if(typeof t==`string`){var n=x.parse(t);this.units=n.units,this.dimensions=n.dimensions}else if(Tl(t)&&t.value===null)this.fixPrefix=t.fixPrefix,this.skipAutomaticSimplification=t.skipAutomaticSimplification,this.dimensions=t.dimensions.slice(0),this.units=t.units.map(e=>zn({},e));else throw TypeError(`Second parameter in Unit constructor must be a string or valueless Unit`);this.value=this._normalize(e)}Object.defineProperty(x,"name",{value:`Unit`}),x.prototype.constructor=x,x.prototype.type=`Unit`,x.prototype.isUnit=!0;var S,C,w;function T(){for(;w===` `||w===`	`;)O()}function E(e){return e>=`0`&&e<=`9`||e===`.`}function D(e){return e>=`0`&&e<=`9`}function O(){C++,w=S.charAt(C)}function k(e){C=e,w=S.charAt(C)}function A(){var e=``,t=C;if(w===`+`?O():w===`-`&&(e+=w,O()),!E(w))return k(t),null;if(w===`.`){if(e+=w,O(),!D(w))return k(t),null}else{for(;D(w);)e+=w,O();w===`.`&&(e+=w,O())}for(;D(w);)e+=w,O();if(w===`E`||w===`e`){var n=``,r=C;if(n+=w,O(),(w===`+`||w===`-`)&&(n+=w,O()),!D(w))return k(r),e;for(e+=n;D(w);)e+=w,O()}return e}function j(){for(var e=``;D(w)||x.isValidAlpha(w);)e+=w,O();var t=e.charAt(0);return x.isValidAlpha(t)?e:null}function M(e){return w===e?(O(),e):null}x.parse=function(e,t){if(t||={},S=e,C=-1,w=``,typeof S!=`string`)throw TypeError(`Invalid argument in Unit.parse, string expected`);var r=new x;r.units=[];var i=1,a=!1;O(),T();var o=A(),s=null;if(o){if(n.number===`BigNumber`)s=new g(o);else if(n.number===`Fraction`)try{s=new _(o)}catch{s=parseFloat(o)}else s=parseFloat(o);T(),M(`*`)?(i=1,a=!0):M(`/`)&&(i=-1,a=!0)}for(var c=[],l=1;;){for(T();w===`(`;)c.push(i),l*=i,i=1,O(),T();var u=void 0;if(w){var d=w;if(u=j(),u===null)throw SyntaxError(`Unexpected "`+d+`" in "`+S+`" at index `+C.toString())}else break;var f=N(u);if(f===null)throw SyntaxError(`Unit "`+u+`" not found.`);var p=i*l;if(T(),M(`^`)){T();var m=A();if(m===null)throw SyntaxError(`In "`+e+`", "^" must be followed by a floating-point number`);p*=m}r.units.push({unit:f.unit,prefix:f.prefix,power:p});for(var h=0;h<te.length;h++)r.dimensions[h]+=(f.unit.dimensions[h]||0)*p;for(T();w===`)`;){if(c.length===0)throw SyntaxError(`Unmatched ")" in "`+S+`" at index `+C.toString());
2590l/=c.pop(),O(),T()}if(a=!1,M(`*`)?(i=1,a=!0):M(`/`)?(i=-1,a=!0):i=1,f.unit.base){var v=f.unit.base.key;ie.auto[v]={unit:f.unit,prefix:f.prefix}}}if(T(),w)throw SyntaxError(`Could not parse: "`+e+`"`);if(a)throw SyntaxError(`Trailing characters: "`+e+`"`);if(c.length!==0)throw SyntaxError(`Unmatched "(" in "`+S+`"`);if(r.units.length===0&&!t.allowNoUnits)throw SyntaxError(`"`+e+`" contains no units`);return r.value=s===void 0?null:r._normalize(s),r},x.prototype.clone=function(){var e=new x;e.fixPrefix=this.fixPrefix,e.skipAutomaticSimplification=this.skipAutomaticSimplification,e.value=$l(this.value),e.dimensions=this.dimensions.slice(0),e.units=[];for(var t=0;t<this.units.length;t++)for(var n in e.units[t]={},this.units[t])nu(this.units[t],n)&&(e.units[t][n]=this.units[t][n]);return e},x.prototype.valueType=function(){return Xl(this.value)},x.prototype._isDerived=function(){return this.units.length===0?!1:this.units.length>1||Math.abs(this.units[0].power-1)>1e-15},x.prototype._normalize=function(e){if(e==null||this.units.length===0)return e;for(var t=e,n=x._getNumberConverter(Xl(e)),r=0;r<this.units.length;r++){var i=n(this.units[r].unit.value),o=n(this.units[r].prefix.value),c=n(this.units[r].power);t=a(t,s(a(i,o),c))}return t},x.prototype._denormalize=function(e,t){if(e==null||this.units.length===0)return e;for(var n=e,r=x._getNumberConverter(Xl(e)),i=0;i<this.units.length;i++){var c=r(this.units[i].unit.value),l=r(this.units[i].prefix.value),u=r(this.units[i].power);n=o(n,s(a(c,l),u))}return n};var N=XS(e=>{if(nu(V,e)){var t=V[e];return{unit:t,prefix:t.prefixes[``]}}for(var n in V)if(nu(V,n)&&xle(e,n)){var r=V[n],i=e.length-n.length,a=e.substring(0,i),o=nu(r.prefixes,a)?r.prefixes[a]:void 0;if(o!==void 0)return{unit:r,prefix:o}}return null},{hasher:e=>e[0],limit:100});x.isValuelessUnit=function(e){return N(e)!==null},x.prototype.hasBase=function(e){if(typeof e==`string`&&(e=z[e]),!e)return!1;for(var t=0;t<te.length;t++)if(Math.abs((this.dimensions[t]||0)-(e.dimensions[t]||0))>1e-12)return!1;return!0},x.prototype.equalBase=function(e){for(var t=0;t<te.length;t++)if(Math.abs((this.dimensions[t]||0)-(e.dimensions[t]||0))>1e-12)return!1;return!0},x.prototype.equals=function(e){return this.equalBase(e)&&d(this.value,e.value)},x.prototype.multiply=function(e){for(var t=this.clone(),n=Tl(e)?e:new x(e),r=0;r<te.length;r++)t.dimensions[r]=(this.dimensions[r]||0)+(n.dimensions[r]||0);for(var i=0;i<n.units.length;i++){var o=$S({},n.units[i]);t.units.push(o)}return this.value!==null||n.value!==null?t.value=a(this.value===null?this._normalize(F(n.value)):this.value,n.value===null?n._normalize(F(this.value)):n.value):t.value=null,Tl(e)&&(t.skipAutomaticSimplification=!1),P(t)},x.prototype.divideInto=function(e){return new x(e).divide(this)},x.prototype.divide=function(e){for(var t=this.clone(),n=Tl(e)?e:new x(e),r=0;r<te.length;r++)t.dimensions[r]=(this.dimensions[r]||0)-(n.dimensions[r]||0);for(var i=0;i<n.units.length;i++){var a=$S($S({},n.units[i]),{},{power:-n.units[i].power});t.units.push(a)}return this.value!==null||n.value!==null?t.value=o(this.value===null?this._normalize(F(n.value)):this.value,n.value===null?n._normalize(F(this.value)):n.value):t.value=null,Tl(e)&&(t.skipAutomaticSimplification=!1),P(t)},x.prototype.pow=function(e){for(var t=this.clone(),n=0;n<te.length;n++)t.dimensions[n]=(this.dimensions[n]||0)*e;for(var r=0;r<t.units.length;r++)t.units[r].power*=e;return t.value===null?t.value=null:t.value=s(t.value,e),t.skipAutomaticSimplification=!1,P(t)};function P(e){return e.equalBase(z.NONE)&&e.value!==null&&!n.predictable?e.value:e}function F(e){return x._getNumberConverter(Xl(e))(1)}x.prototype.abs=function(){var e=this.clone();if(e.value!==null)if(e._isDerived()||e.units.length===0||e.units[0].unit.offset===0)e.value=c(e.value);else{var t=e._numberConverter(),n=a(t(e.units[0].unit.value),t(e.units[0].unit.offset));e.value=i(c(r(e.value,n)),n)}for(var o in e.units)(e.units[o].unit.name===`VA`||e.units[o].unit.name===`VAR`)&&(e.units[o].unit=V.W);return e},x.prototype.to=function(e){var t=this.value===null?this._normalize(1):this.value,
2590n;if(typeof e==`string`)n=x.parse(e);else if(Tl(e))n=e.clone();else throw Error(`String or Unit expected as parameter`);if(!this.equalBase(n))throw Error(`Units do not match ('${n.toString()}' != '${this.toString()}')`);if(n.value!==null)throw Error(`Cannot convert to a unit with a value`);if(this.value===null||this._isDerived()||this.units.length===0||n.units.length===0||this.units[0].unit.offset===n.units[0].unit.offset)n.value=$l(t);else{var o=x._getNumberConverter(Xl(t)),s=this.units[0].unit.value,c=this.units[0].unit.offset,l=a(s,c),u=n.units[0].unit.value,d=n.units[0].unit.offset,f=a(u,d);n.value=r(t,o(i(l,f)))}return n.fixPrefix=!0,n.skipAutomaticSimplification=!0,n},x.prototype.toNumber=function(e){return v(this.toNumeric(e))},x.prototype.toNumeric=function(e){var t=e?this.to(e):this.clone();return t._isDerived()||t.units.length===0?t._denormalize(t.value):t._denormalize(t.value,t.units[0].prefix.value)},x.prototype.toString=function(){return this.format()},x.prototype.toJSON=function(){return{mathjs:`Unit`,value:this._denormalize(this.value),unit:this.units.length>0?this.formatUnits():null,fixPrefix:this.fixPrefix,skipSimp:this.skipAutomaticSimplification}},x.fromJSON=function(e){var t=new x(e.value,e.unit??void 0);return t.fixPrefix=e.fixPrefix??y,t.skipAutomaticSimplification=e.skipSimp??b,t},x.prototype.valueOf=x.prototype.toString,x.prototype.simplify=function(){var e=this.clone(),t=[],n;for(var r in ae)if(nu(ae,r)&&e.hasBase(z[r])){n=r;break}if(n===`NONE`)e.units=[];else{var i;if(n&&nu(ae,n)&&(i=ae[n]),i)e.units=[{unit:i.unit,prefix:i.prefix,power:1}];else{for(var a=!1,o=0;o<te.length;o++){var s=te[o];Math.abs(e.dimensions[o]||0)>1e-12&&(nu(ae,s)?t.push({unit:ae[s].unit,prefix:ae[s].prefix,power:e.dimensions[o]||0}):a=!0)}t.length<e.units.length&&!a&&(e.units=t)}}return e},x.prototype.toSI=function(){for(var e=this.clone(),t=[],n=0;n<te.length;n++){var r=te[n];if(Math.abs(e.dimensions[n]||0)>1e-12)if(nu(ie.si,r))t.push({unit:ie.si[r].unit,prefix:ie.si[r].prefix,power:e.dimensions[n]||0});else throw Error(`Cannot express custom unit `+r+` in SI units`)}return e.units=t,e.fixPrefix=!0,e.skipAutomaticSimplification=!0,this.value===null?e:(e.value=null,this.to(e))},x.prototype.formatUnits=function(){for(var e=``,t=``,n=0,r=0,i=0;i<this.units.length;i++)this.units[i].power>0?(n++,e+=` `+this.units[i].prefix.name+this.units[i].unit.name,Math.abs(this.units[i].power-1)>1e-15&&(e+=`^`+this.units[i].power)):this.units[i].power<0&&r++;if(r>0)for(var a=0;a<this.units.length;a++)this.units[a].power<0&&(n>0?(t+=` `+this.units[a].prefix.name+this.units[a].unit.name,Math.abs(this.units[a].power+1)>1e-15&&(t+=`^`+-this.units[a].power)):(t+=` `+this.units[a].prefix.name+this.units[a].unit.name,t+=`^`+this.units[a].power));e=e.substr(1),t=t.substr(1),n>1&&r>0&&(e=`(`+e+`)`),r>1&&n>0&&(t=`(`+t+`)`);var o=e;return n>0&&r>0&&(o+=` / `),o+=t,o},x.prototype.toBest=function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(e&&!Array.isArray(e))throw Error(`Invalid unit type. Expected string or Unit.`);var n=this.units[0].unit.prefixes;if(e&&e.length>0){var r=e.map(e=>{var t=null;if(typeof e==`string`){if(t=x.parse(e),!t)throw Error(`Invalid unit type. Expected compatible string or Unit.`)}else if(!Tl(e))throw Error(`Invalid unit type. Expected compatible string or Unit.`);t===null&&(t=e.clone());try{return this.to(t.formatUnits()),t}catch{throw Error(`Invalid unit type. Expected compatible string or Unit.`)}}).map(e=>e.units[0].prefix);this.units[0].unit.prefixes=r.reduce((e,t)=>(e[t.name]=t,e),{}),this.units[0].prefix=r[0]}var i=I(this,t).simp;return this.units[0].unit.prefixes=n,i.fixPrefix=!0,i},x.prototype.format=function(e){var{simp:t,valueStr:n,unitStr:r}=I(this,e),i=n;return t.value&&Cl(t.value)&&(i=`(`+i+`)`),r.length>0&&i.length>0&&(i+=` `),i+=r,i};function I(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=e.skipAutomaticSimplification||e.value===null?e.clone():e.simplify();L(n),ee(n,t.offset);var r=n._denormalize(n.value);return{simp:n,valueStr:n.value===null?``:p(r,t||{}),unitStr:n.formatUnits()}}function L(e){var t=!1;for(var n in e.value!==void 0&&e.value!==null&&Cl(e.value)&&(t=Math.abs(e.value.re)<1e-14),e.units)nu(e.units,n)&&e.units[n].unit&&(e.units[n].unit.name===`VA`&&t?e.units[n].unit=V.VAR:e.units[n].unit.name===`VAR`&&!t&&(e.units[n].unit=V.VA))}function ee(e,t){e.units.length===1&&!e.fixPrefix&&Math.abs(e.units[0].power-Math.round(e.units[0].power))<1e-14&&(e.units[0].prefix=e._bestPrefix(t))}x.prototype._bestPrefix=function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1.2;if(this.units.length!==1||Math.abs(this.units[0].power-Math.round(this.units[0].power))>=1e-14)throw Error(`Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!`);var t=this.value===null?0:c(this.value),n=c(this.units[0].unit.value),r=this.units[0].prefix;if(t===0)return r;var i=this.units[0].power,a=Math.log(t/(r.value*n)**+i)/Math.LN10-e;if(a>-2.200001&&a<1.800001)return r;a=Math.abs(a);var o=this.units[0].unit.prefixes;for(var s in o)if(nu(o,s)){var l=o[s];if(l.scientific){var u=Math.abs(Math.log(t/(l.value*n)**+i)/Math.LN10-e);(u<a||u===a&&l.name.length<r.name.length)&&(r=l,a=u)}}return r},x.prototype.splitUnit=function(e){for(var t=this.clone(),n=[],a=0;a<e.length&&(t=t.to(e[a]),a!==e.length-1);a++){var o=t.toNumeric(),s=u(o),c=void 0;c=d(s,o)?s:l(t.toNumeric());var f=new x(c,e[a].toString());n.push(f),t=i(t,f)}for(var p=0,m=0;m<n.length;m++)p=r(p,n[m].value);return d(p,this.value)&&(t.value=0),n.push(t),n};var R={NONE:{"":{name:``,value:1,scientific:!0}},SHORT:{"":{name:``,value:1,scientific:!0},da:{name:`da`,value:10,scientific:!1},h:{name:`h`,value:100,scientific:!1},k:{name:`k`,value:1e3,scientific:!0},M:{name:`M`,value:1e6,scientific:!0},G:{name:`G`,value:1e9,scientific:!0},T:{name:`T`,value:0xe8d4a51000,scientific:!0},P:{name:`P`,value:0x38d7ea4c68000,scientific:!0},E:{name:`E`,value:0xde0b6b3a7640000,scientific:!0},Z:{name:`Z`,value:1e21,scientific:!0},Y:{name:`Y`,value:1e24,scientific:!0},R:{name:`R`,value:1e27,scientific:!0},Q:{name:`Q`,value:1e30,scientific:!0},d:{name:`d`,value:.1,scientific:!1},c:{name:`c`,value:.01,scientific:!1},m:{name:`m`,value:.001,scientific:!0},u:{name:`u`,value:1e-6,scientific:!0},n:{name:`n`,value:1e-9,scientific:!0},p:{name:`p`,value:1e-12,scientific:!0},f:{name:`f`,value:1e-15,scientific:!0},a:{name:`a`,value:1e-18,scientific:!0},z:{name:`z`,value:1e-21,scientific:!0},y:{name:`y`,value:1e-24,scientific:!0}
2590,r:{name:`r`,value:1e-27,scientific:!0},q:{name:`q`,value:1e-30,scientific:!0}},LONG:{"":{name:``,value:1,scientific:!0},deca:{name:`deca`,value:10,scientific:!1},hecto:{name:`hecto`,value:100,scientific:!1},kilo:{name:`kilo`,value:1e3,scientific:!0},mega:{name:`mega`,value:1e6,scientific:!0},giga:{name:`giga`,value:1e9,scientific:!0},tera:{name:`tera`,value:0xe8d4a51000,scientific:!0},peta:{name:`peta`,value:0x38d7ea4c68000,scientific:!0},exa:{name:`exa`,value:0xde0b6b3a7640000,scientific:!0},zetta:{name:`zetta`,value:1e21,scientific:!0},yotta:{name:`yotta`,value:1e24,scientific:!0},ronna:{name:`ronna`,value:1e27,scientific:!0},quetta:{name:`quetta`,value:1e30,scientific:!0},deci:{name:`deci`,value:.1,scientific:!1},centi:{name:`centi`,value:.01,scientific:!1},milli:{name:`milli`,value:.001,scientific:!0},micro:{name:`micro`,value:1e-6,scientific:!0},nano:{name:`nano`,value:1e-9,scientific:!0},pico:{name:`pico`,value:1e-12,scientific:!0},femto:{name:`femto`,value:1e-15,scientific:!0},atto:{name:`atto`,value:1e-18,scientific:!0},zepto:{name:`zepto`,value:1e-21,scientific:!0},yocto:{name:`yocto`,value:1e-24,scientific:!0},ronto:{name:`ronto`,value:1e-27,scientific:!0},quecto:{name:`quecto`,value:1e-30,scientific:!0}},SQUARED:{"":{name:``,value:1,scientific:!0},da:{name:`da`,value:100,scientific:!1},h:{name:`h`,value:1e4,scientific:!1},k:{name:`k`,value:1e6,scientific:!0},M:{name:`M`,value:0xe8d4a51000,scientific:!0},G:{name:`G`,value:0xde0b6b3a7640000,scientific:!0},T:{name:`T`,value:1e24,scientific:!0},P:{name:`P`,value:1e30,scientific:!0},E:{name:`E`,value:1e36,scientific:!0},Z:{name:`Z`,value:1e42,scientific:!0},Y:{name:`Y`,value:1e48,scientific:!0},R:{name:`R`,value:1e54,scientific:!0},Q:{name:`Q`,value:1e60,scientific:!0},d:{name:`d`,value:.01,scientific:!1},c:{name:`c`,value:1e-4,scientific:!1},m:{name:`m`,value:1e-6,scientific:!0},u:{name:`u`,value:1e-12,scientific:!0},n:{name:`n`,value:1e-18,scientific:!0},p:{name:`p`,value:1e-24,scientific:!0},f:{name:`f`,value:1e-30,scientific:!0},a:{name:`a`,value:1e-36,scientific:!0},z:{name:`z`,value:1e-42,scientific:!0},y:{name:`y`,value:1e-48,scientific:!0},r:{name:`r`,value:1e-54,scientific:!0},q:{name:`q`,value:1e-60,scientific:!0}},CUBIC:{"":{name:``,value:1,scientific:!0},da:{name:`da`,value:1e3,scientific:!1},h:{name:`h`,value:1e6,scientific:!1},k:{name:`k`,value:1e9,scientific:!0},M:{name:`M`,value:0xde0b6b3a7640000,scientific:!0},G:{name:`G`,value:1e27,scientific:!0},T:{name:`T`,value:1e36,scientific:!0},P:{name:`P`,value:1e45,scientific:!0},E:{name:`E`,value:1e54,scientific:!0},Z:{name:`Z`,value:1e63,scientific:!0},Y:{name:`Y`,value:1e72,scientific:!0},R:{name:`R`,value:1e81,scientific:!0},Q:{name:`Q`,value:1e90,scientific:!0},d:{name:`d`,value:.001,scientific:!1},c:{name:`c`,value:1e-6,scientific:!1},m:{name:`m`,value:1e-9,scientific:!0},u:{name:`u`,value:1e-18,scientific:!0},n:{name:`n`,value:1e-27,scientific:!0},p:{name:`p`,value:1e-36,scientific:!0},f:{name:`f`,value:1e-45,scientific:!0},a:{name:`a`,value:1e-54,scientific:!0},z:{name:`z`,value:1e-63,scientific:!0},y:{name:`y`,value:1e-72,scientific:!0},r:{name:`r`,value:1e-81,scientific:!0},q:{name:`q`,value:1e-90,scientific:!0}},BINARY_SHORT_SI:{"":{name:``,value:1,scientific:!0},k:{name:`k`,value:1e3,scientific:!0},M:{name:`M`,value:1e6,scientific:!0},G:{name:`G`,value:1e9,scientific:!0},T:{name:`T`,value:0xe8d4a51000,scientific:!0},P:{name:`P`,value:0x38d7ea4c68000,scientific:!0},E:{name:`E`,value:0xde0b6b3a7640000,scientific:!0},Z:{name:`Z`,value:1e21,scientific:!0},Y:{name:`Y`,value:1e24,scientific:!0}},BINARY_SHORT_IEC:{"":{name:``,value:1,scientific:!0},Ki:{name:`Ki`,value:1024,scientific:!0},Mi:{name:`Mi`,value:1024**2,scientific:!0},Gi:{name:`Gi`,value:1024**3,scientific:!0},Ti:{name:`Ti`,value:1024**4,scientific:!0},Pi:{name:`Pi`,value:1024**5,scientific:!0},Ei:{name:`Ei`,value:1024**6,scientific:!0},Zi:{name:`Zi`,value:1024**7,scientific:!0},Yi:{name:`Yi`,value:1024**8,scientific:!0}},BINARY_LONG_SI:{"":{name:``,value:1,scientific:!0},kilo:{name:`kilo`,value:1e3,scientific:!0},mega:{name:`mega`,value:1e6,scientific:!0},giga:{name:`giga`,value:1e9,scientific:!0},tera:{name:`tera`,value:0xe8d4a51000,scientific:!0},peta:{name:`peta`,value:0x38d7ea4c68000,scientific:!0},exa:{name:`exa`,value:0xde0b6b3a7640000,scientific:!0},zetta:{name:`zetta`,value:1e21,scientific:!0},yotta:{name:`yotta`,value:1e24,scientific:!0}},BINARY_LONG_IEC:{"":{name:``,value:1,scientific:!0},kibi:{name:`kibi`,value:1024,scientific:!0},mebi:{name:`mebi`,value:1024**2,scientific:!0},gibi:{name:`gibi`,value:1024**3,scientific:!0},tebi:{name:`tebi`,value:1024**4,scientific:!0},pebi:{name:`pebi`,value:1024**5,scientific:!0},exi:{name:`exi`,value:1024**6,scientific:!0},zebi:{name:`zebi`,value:1024**7,scientific:!0},yobi:{name:`yobi`,value:1024**8,scientific:!0}},BTU:{"":{name:``,value:1,scientific:!0},MM:{name:`MM`,value:1e6,scientific:!0}}};R.SHORTLONG=zn({},R.SHORT,R.LONG),R.BINARY_SHORT=zn({},R.BINARY_SHORT_SI,R.BINARY_SHORT_IEC),R.BINARY_LONG=zn({},R.BINARY_LONG_SI,R.BINARY_LONG_IEC);var te=[`MASS`,`LENGTH`,`TIME`,`CURRENT`,`TEMPERATURE`,`LUMINOUS_INTENSITY`,`AMOUNT_OF_SUBSTANCE`,`ANGLE`,`BIT`],z={NONE:{dimensions:[0,0,0,0,0,0,0,0,0]},MASS:{dimensions:[1,0,0,0,0,0,0,0,0]},LENGTH:{dimensions:[0,1,0,0,0,0,0,0,0]},TIME:{dimensions:[0,0,1,0,0,0,0,0,0]},CURRENT:{dimensions:[0,0,0,1,0,0,0,0,0]},TEMPERATURE:{dimensions:[0,0,0,0,1,0,0,0,0]},LUMINOUS_INTENSITY:{dimensions:[0,0,0,0,0,1,0,0,0]},AMOUNT_OF_SUBSTANCE:{dimensions:[0,0,0,0,0,0,1,0,0]},FORCE:{dimensions:[1,1,-2,0,0,0,0,0,0]},SURFACE:{dimensions:[0,2,0,0,0,0,0,0,0]},VOLUME:{dimensions:[0,3,0,0,0,0,0,0,0]},ENERGY:{dimensions:[1,2,-2,0,0,0,0,0,0]},POWER:{dimensions:[1,2,-3,0,0,0,0,0,0]},PRESSURE:{dimensions:[1,-1,-2,0,0,0,0,0,0]},ELECTRIC_CHARGE:{dimensions:[0,0,1,1,0,0,0,0,0]},ELECTRIC_CAPACITANCE:{dimensions:[-1,-2,4,2,0,0,0,0,0]},ELECTRIC_POTENTIAL:{dimensions:[1,2,-3,-1,0,0,0,0,0]},ELECTRIC_RESISTANCE:{dimensions:[1,2,-3,-2,0,0,0,0,0]},ELECTRIC_INDUCTANCE:{dimensions:[1,2,-2,-2,0,0,0,0,0]},ELECTRIC_CONDUCTANCE:{dimensions:[-1,-2,3,2,0,0,0,0,0]},MAGNETIC_FLUX:{dimensions:[1,2,-2,-1,0,0,0,0,0]},MAGNETIC_FLUX_DENSITY:{dimensions:[1,0,-2,-1,0,0,0,0,0]},FREQUENCY:{dimensions:[0,0,-1,0,0,0,0,0,0]},ANGLE:{dimensions:[0,0,0,0,0,0,0,1,0]},BIT:{dimensions:[0,0,0,0,0,0,0,0,1]}};for(var ne in z)nu(z,ne)&&(z[ne].key=ne);
2590var B={name:``,base:{},value:1,offset:0,dimensions:te.map(e=>0)},V={meter:{name:`meter`,base:z.LENGTH,prefixes:R.LONG,value:1,offset:0},inch:{name:`inch`,base:z.LENGTH,prefixes:R.NONE,value:.0254,offset:0},foot:{name:`foot`,base:z.LENGTH,prefixes:R.NONE,value:.3048,offset:0},yard:{name:`yard`,base:z.LENGTH,prefixes:R.NONE,value:.9144,offset:0},mile:{name:`mile`,base:z.LENGTH,prefixes:R.NONE,value:1609.344,offset:0},link:{name:`link`,base:z.LENGTH,prefixes:R.NONE,value:.201168,offset:0},rod:{name:`rod`,base:z.LENGTH,prefixes:R.NONE,value:5.0292,offset:0},chain:{name:`chain`,base:z.LENGTH,prefixes:R.NONE,value:20.1168,offset:0},angstrom:{name:`angstrom`,base:z.LENGTH,prefixes:R.NONE,value:1e-10,offset:0},m:{name:`m`,base:z.LENGTH,prefixes:R.SHORT,value:1,offset:0},in:{name:`in`,base:z.LENGTH,prefixes:R.NONE,value:.0254,offset:0},ft:{name:`ft`,base:z.LENGTH,prefixes:R.NONE,value:.3048,offset:0},yd:{name:`yd`,base:z.LENGTH,prefixes:R.NONE,value:.9144,offset:0},mi:{name:`mi`,base:z.LENGTH,prefixes:R.NONE,value:1609.344,offset:0},li:{name:`li`,base:z.LENGTH,prefixes:R.NONE,value:.201168,offset:0},rd:{name:`rd`,base:z.LENGTH,prefixes:R.NONE,value:5.02921,offset:0},ch:{name:`ch`,base:z.LENGTH,prefixes:R.NONE,value:20.1168,offset:0},mil:{name:`mil`,base:z.LENGTH,prefixes:R.NONE,value:254e-7,offset:0},m2:{name:`m2`,base:z.SURFACE,prefixes:R.SQUARED,value:1,offset:0},sqin:{name:`sqin`,base:z.SURFACE,prefixes:R.NONE,value:64516e-8,offset:0},sqft:{name:`sqft`,base:z.SURFACE,prefixes:R.NONE,value:.09290304,offset:0},sqyd:{name:`sqyd`,base:z.SURFACE,prefixes:R.NONE,value:.83612736,offset:0},sqmi:{name:`sqmi`,base:z.SURFACE,prefixes:R.NONE,value:2589988.110336,offset:0},sqrd:{name:`sqrd`,base:z.SURFACE,prefixes:R.NONE,value:25.29295,offset:0},sqch:{name:`sqch`,base:z.SURFACE,prefixes:R.NONE,value:404.6873,offset:0},sqmil:{name:`sqmil`,base:z.SURFACE,prefixes:R.NONE,value:64516e-14,offset:0},acre:{name:`acre`,base:z.SURFACE,prefixes:R.NONE,value:4046.86,offset:0},hectare:{name:`hectare`,base:z.SURFACE,prefixes:R.NONE,value:1e4,offset:0},m3:{name:`m3`,base:z.VOLUME,prefixes:R.CUBIC,value:1,offset:0},L:{name:`L`,base:z.VOLUME,prefixes:R.SHORT,value:.001,offset:0},l:{name:`l`,base:z.VOLUME,prefixes:R.SHORT,value:.001,offset:0},litre:{name:`litre`,base:z.VOLUME,prefixes:R.LONG,value:.001,offset:0},cuin:{name:`cuin`,base:z.VOLUME,prefixes:R.NONE,value:16387064e-12,offset:0},cuft:{name:`cuft`,base:z.VOLUME,prefixes:R.NONE,value:.028316846592,offset:0},cuyd:{name:`cuyd`,base:z.VOLUME,prefixes:R.NONE,value:.764554857984,offset:0},teaspoon:{name:`teaspoon`,base:z.VOLUME,prefixes:R.NONE,value:5e-6,offset:0},tablespoon:{name:`tablespoon`,base:z.VOLUME,prefixes:R.NONE,value:15e-6,offset:0},drop:{name:`drop`,base:z.VOLUME,prefixes:R.NONE,value:5e-8,offset:0},gtt:{name:`gtt`,base:z.VOLUME,prefixes:R.NONE,value:5e-8,offset:0},minim:{name:`minim`,base:z.VOLUME,prefixes:R.NONE,value:6.1611519921875e-8,offset:0},fluiddram:{name:`fluiddram`,base:z.VOLUME,prefixes:R.NONE,value:36966911953125e-19,offset:0},fluidounce:{name:`fluidounce`,base:z.VOLUME,prefixes:R.NONE,value:295735295625e-16,offset:0},gill:{name:`gill`,base:z.VOLUME,prefixes:R.NONE,value:.00011829411825,offset:0},cc:{name:`cc`,base:z.VOLUME,prefixes:R.NONE,value:1e-6,offset:0},cup:{name:`cup`,base:z.VOLUME,prefixes:R.NONE,value:.0002365882365,offset:0},pint:{name:`pint`,base:z.VOLUME,prefixes:R.NONE,value:.000473176473,offset:0},quart:{name:`quart`,base:z.VOLUME,prefixes:R.NONE,value:.000946352946,offset:0},gallon:{name:`gallon`,base:z.VOLUME,prefixes:R.NONE,value:.003785411784,offset:0},beerbarrel:{name:`beerbarrel`,base:z.VOLUME,prefixes:R.NONE,value:.117347765304,offset:0},oilbarrel:{name:`oilbarrel`,base:z.VOLUME,prefixes:R.NONE,value:.158987294928,offset:0},hogshead:{name:`hogshead`,base:z.VOLUME,prefixes:R.NONE,value:.238480942392,offset:0},g:{name:`g`,base:z.MASS,prefixes:R.SHORT,value:.001,offset:0},gram:{name:`gram`,base:z.MASS,prefixes:R.LONG,value:.001,offset:0},ton:{name:`ton`,base:z.MASS,prefixes:R.SHORT,value:907.18474,offset:0},t:{name:`t`,base:z.MASS,prefixes:R.SHORT,value:1e3,offset:0},tonne:{name:`tonne`,base:z.MASS,prefixes:R.LONG,value:1e3,offset:0},grain:{name:`grain`,base:z.MASS,prefixes:R.NONE,value:6479891e-11,offset:0}
2590,dram:{name:`dram`,base:z.MASS,prefixes:R.NONE,value:.0017718451953125,offset:0},ounce:{name:`ounce`,base:z.MASS,prefixes:R.NONE,value:.028349523125,offset:0},poundmass:{name:`poundmass`,base:z.MASS,prefixes:R.NONE,value:.45359237,offset:0},hundredweight:{name:`hundredweight`,base:z.MASS,prefixes:R.NONE,value:45.359237,offset:0},stick:{name:`stick`,base:z.MASS,prefixes:R.NONE,value:.115,offset:0},stone:{name:`stone`,base:z.MASS,prefixes:R.NONE,value:6.35029318,offset:0},gr:{name:`gr`,base:z.MASS,prefixes:R.NONE,value:6479891e-11,offset:0},dr:{name:`dr`,base:z.MASS,prefixes:R.NONE,value:.0017718451953125,offset:0},oz:{name:`oz`,base:z.MASS,prefixes:R.NONE,value:.028349523125,offset:0},lbm:{name:`lbm`,base:z.MASS,prefixes:R.NONE,value:.45359237,offset:0},cwt:{name:`cwt`,base:z.MASS,prefixes:R.NONE,value:45.359237,offset:0},s:{name:`s`,base:z.TIME,prefixes:R.SHORT,value:1,offset:0},min:{name:`min`,base:z.TIME,prefixes:R.NONE,value:60,offset:0},h:{name:`h`,base:z.TIME,prefixes:R.NONE,value:3600,offset:0},second:{name:`second`,base:z.TIME,prefixes:R.LONG,value:1,offset:0},sec:{name:`sec`,base:z.TIME,prefixes:R.LONG,value:1,offset:0},minute:{name:`minute`,base:z.TIME,prefixes:R.NONE,value:60,offset:0},hour:{name:`hour`,base:z.TIME,prefixes:R.NONE,value:3600,offset:0},day:{name:`day`,base:z.TIME,prefixes:R.NONE,value:86400,offset:0},week:{name:`week`,base:z.TIME,prefixes:R.NONE,value:7*86400,offset:0},month:{name:`month`,base:z.TIME,prefixes:R.NONE,value:2629800,offset:0},year:{name:`year`,base:z.TIME,prefixes:R.NONE,value:31557600,offset:0},decade:{name:`decade`,base:z.TIME,prefixes:R.NONE,value:315576e3,offset:0},century:{name:`century`,base:z.TIME,prefixes:R.NONE,value:315576e4,offset:0},millennium:{name:`millennium`,base:z.TIME,prefixes:R.NONE,value:315576e5,offset:0},hertz:{name:`Hertz`,base:z.FREQUENCY,prefixes:R.LONG,value:1,offset:0,reciprocal:!0},Hz:{name:`Hz`,base:z.FREQUENCY,prefixes:R.SHORT,value:1,offset:0,reciprocal:!0},rad:{name:`rad`,base:z.ANGLE,prefixes:R.SHORT,value:1,offset:0},radian:{name:`radian`,base:z.ANGLE,prefixes:R.LONG,value:1,offset:0},deg:{name:`deg`,base:z.ANGLE,prefixes:R.SHORT,value:null,offset:0},degree:{name:`degree`,base:z.ANGLE,prefixes:R.LONG,value:null,offset:0},grad:{name:`grad`,base:z.ANGLE,prefixes:R.SHORT,value:null,offset:0},gradian:{name:`gradian`,base:z.ANGLE,prefixes:R.LONG,value:null,offset:0},cycle:{name:`cycle`,base:z.ANGLE,prefixes:R.NONE,value:null,offset:0},arcsec:{name:`arcsec`,base:z.ANGLE,prefixes:R.NONE,value:null,offset:0},arcmin:{name:`arcmin`,base:z.ANGLE,prefixes:R.NONE,value:null,offset:0},A:{name:`A`,base:z.CURRENT,prefixes:R.SHORT,value:1,offset:0},ampere:{name:`ampere`,base:z.CURRENT,prefixes:R.LONG,value:1,offset:0},K:{name:`K`,base:z.TEMPERATURE,prefixes:R.SHORT,value:1,offset:0},degC:{name:`degC`,base:z.TEMPERATURE,prefixes:R.SHORT,value:1,offset:273.15},degF:{name:`degF`,base:z.TEMPERATURE,prefixes:R.SHORT,value:new _(5,9),offset:459.67},degR:{name:`degR`,base:z.TEMPERATURE,prefixes:R.SHORT,value:new _(5,9),offset:0},kelvin:{name:`kelvin`,base:z.TEMPERATURE,prefixes:R.LONG,value:1,offset:0},celsius:{name:`celsius`,base:z.TEMPERATURE,prefixes:R.LONG,value:1,offset:273.15},fahrenheit:{name:`fahrenheit`,base:z.TEMPERATURE,prefixes:R.LONG,value:new _(5,9),offset:459.67},rankine:{name:`rankine`,base:z.TEMPERATURE,prefixes:R.LONG,value:new _(5,9),offset:0},mol:{name:`mol`,base:z.AMOUNT_OF_SUBSTANCE,prefixes:R.SHORT,value:1,offset:0},mole:{name:`mole`,base:z.AMOUNT_OF_SUBSTANCE,prefixes:R.LONG,value:1,offset:0},cd:{name:`cd`,base:z.LUMINOUS_INTENSITY,prefixes:R.SHORT,value:1,offset:0},candela:{name:`candela`,base:z.LUMINOUS_INTENSITY,prefixes:R.LONG,value:1,offset:0},N:{name:`N`,base:z.FORCE,prefixes:R.SHORT,value:1,offset:0},newton:{name:`newton`,base:z.FORCE,prefixes:R.LONG,value:1,offset:0},dyn:{name:`dyn`,base:z.FORCE,prefixes:R.SHORT,value:1e-5,offset:0},dyne:{name:`dyne`,base:z.FORCE,prefixes:R.LONG,value:1e-5,offset:0},lbf:{name:`lbf`,base:z.FORCE,prefixes:R.NONE,value:4.4482216152605,offset:0},poundforce:{name:`poundforce`,base:z.FORCE,prefixes:R.NONE,value:4.4482216152605,offset:0},kip:{name:`kip`,base:z.FORCE,prefixes:R.LONG,value:4448.2216,offset:0}
2590,kilogramforce:{name:`kilogramforce`,base:z.FORCE,prefixes:R.NONE,value:9.80665,offset:0},J:{name:`J`,base:z.ENERGY,prefixes:R.SHORT,value:1,offset:0},joule:{name:`joule`,base:z.ENERGY,prefixes:R.LONG,value:1,offset:0},erg:{name:`erg`,base:z.ENERGY,prefixes:R.SHORTLONG,value:1e-7,offset:0},Wh:{name:`Wh`,base:z.ENERGY,prefixes:R.SHORT,value:3600,offset:0},BTU:{name:`BTU`,base:z.ENERGY,prefixes:R.BTU,value:1055.05585262,offset:0},eV:{name:`eV`,base:z.ENERGY,prefixes:R.SHORT,value:1602176565e-28,offset:0},electronvolt:{name:`electronvolt`,base:z.ENERGY,prefixes:R.LONG,value:1602176565e-28,offset:0},W:{name:`W`,base:z.POWER,prefixes:R.SHORT,value:1,offset:0},watt:{name:`watt`,base:z.POWER,prefixes:R.LONG,value:1,offset:0},hp:{name:`hp`,base:z.POWER,prefixes:R.NONE,value:745.6998715386,offset:0},VAR:{name:`VAR`,base:z.POWER,prefixes:R.SHORT,value:h.I,offset:0},VA:{name:`VA`,base:z.POWER,prefixes:R.SHORT,value:1,offset:0},Pa:{name:`Pa`,base:z.PRESSURE,prefixes:R.SHORT,value:1,offset:0},psi:{name:`psi`,base:z.PRESSURE,prefixes:R.NONE,value:6894.75729276459,offset:0},atm:{name:`atm`,base:z.PRESSURE,prefixes:R.NONE,value:101325,offset:0},bar:{name:`bar`,base:z.PRESSURE,prefixes:R.SHORTLONG,value:1e5,offset:0},torr:{name:`torr`,base:z.PRESSURE,prefixes:R.NONE,value:133.322,offset:0},mmHg:{name:`mmHg`,base:z.PRESSURE,prefixes:R.NONE,value:133.322,offset:0},mmH2O:{name:`mmH2O`,base:z.PRESSURE,prefixes:R.NONE,value:9.80665,offset:0},cmH2O:{name:`cmH2O`,base:z.PRESSURE,prefixes:R.NONE,value:98.0665,offset:0},coulomb:{name:`coulomb`,base:z.ELECTRIC_CHARGE,prefixes:R.LONG,value:1,offset:0},C:{name:`C`,base:z.ELECTRIC_CHARGE,prefixes:R.SHORT,value:1,offset:0},Ah:{name:`Ah`,base:z.ELECTRIC_CHARGE,prefixes:R.SHORT,value:3600,offset:0},farad:{name:`farad`,base:z.ELECTRIC_CAPACITANCE,prefixes:R.LONG,value:1,offset:0},F:{name:`F`,base:z.ELECTRIC_CAPACITANCE,prefixes:R.SHORT,value:1,offset:0},volt:{name:`volt`,base:z.ELECTRIC_POTENTIAL,prefixes:R.LONG,value:1,offset:0},V:{name:`V`,base:z.ELECTRIC_POTENTIAL,prefixes:R.SHORT,value:1,offset:0},ohm:{name:`ohm`,base:z.ELECTRIC_RESISTANCE,prefixes:R.SHORTLONG,value:1,offset:0},henry:{name:`henry`,base:z.ELECTRIC_INDUCTANCE,prefixes:R.LONG,value:1,offset:0},H:{name:`H`,base:z.ELECTRIC_INDUCTANCE,prefixes:R.SHORT,value:1,offset:0},siemens:{name:`siemens`,base:z.ELECTRIC_CONDUCTANCE,prefixes:R.LONG,value:1,offset:0},S:{name:`S`,base:z.ELECTRIC_CONDUCTANCE,prefixes:R.SHORT,value:1,offset:0},weber:{name:`weber`,base:z.MAGNETIC_FLUX,prefixes:R.LONG,value:1,offset:0},Wb:{name:`Wb`,base:z.MAGNETIC_FLUX,prefixes:R.SHORT,value:1,offset:0},tesla:{name:`tesla`,base:z.MAGNETIC_FLUX_DENSITY,prefixes:R.LONG,value:1,offset:0},T:{name:`T`,base:z.MAGNETIC_FLUX_DENSITY,prefixes:R.SHORT,value:1,offset:0},b:{name:`b`,base:z.BIT,prefixes:R.BINARY_SHORT,value:1,offset:0},bits:{name:`bits`,base:z.BIT,prefixes:R.BINARY_LONG,value:1,offset:0},B:{name:`B`,base:z.BIT,prefixes:R.BINARY_SHORT,value:8,offset:0},bytes:{name:`bytes`,base:z.BIT,prefixes:R.BINARY_LONG,value:8,offset:0}},H={meters:`meter`,inches:`inch`,feet:`foot`,yards:`yard`,miles:`mile`,links:`link`,rods:`rod`,chains:`chain`,angstroms:`angstrom`,lt:`l`,litres:`litre`,liter:`litre`,liters:`litre`,teaspoons:`teaspoon`,tablespoons:`tablespoon`,minims:`minim`,fldr:`fluiddram`,fluiddrams:`fluiddram`,floz:`fluidounce`,fluidounces:`fluidounce`,gi:`gill`,gills:`gill`,cp:`cup`,cups:`cup`,pt:`pint`,pints:`pint`,qt:`quart`,quarts:`quart`,gal:`gallon`,gallons:`gallon`,bbl:`beerbarrel`,beerbarrels:`beerbarrel`,obl:`oilbarrel`,oilbarrels:`oilbarrel`,hogsheads:`hogshead`,gtts:`gtt`,grams:`gram`,tons:`ton`,tonnes:`tonne`,grains:`grain`,drams:`dram`,ounces:`ounce`,poundmasses:`poundmass`,hundredweights:`hundredweight`,sticks:`stick`,lb:`lbm`,lbs:`lbm`,kips:`kip`,kgf:`kilogramforce`,acres:`acre`,hectares:`hectare`,sqfeet:`sqft`,sqyard:`sqyd`,sqmile:`sqmi`,sqmiles:`sqmi`,mmhg:`mmHg`,mmh2o:`mmH2O`,cmh2o:`cmH2O`,seconds:`second`,secs:`second`,minutes:`minute`,mins:`minute`,hours:`hour`,hr:`hour`,hrs:`hour`,days:`day`,weeks:`week`,months:`month`,years:`year`,decades:`decade`,centuries:`century`,millennia:`millennium`,hertz:`hertz`,radians:`radian`,degrees:`degree`,gradians:`gradian`,cycles:`cycle`,arcsecond:`arcsec`,arcseconds:`arcsec`,arcminute:`arcmin`,arcminutes:`arcmin`,BTUs:`BTU`,watts:`watt`,joules:`joule`,amperes:`ampere`,amps:`ampere`,amp:`ampere`,coulombs:`coulomb`,volts:`volt`,ohms:`ohm`,farads:`farad`,webers:`weber`,teslas:`tesla`,electronvolts:`electronvolt`,moles:`mole`,bit:`bits`,byte:`bytes`};function re(e){if(e.number===`BigNumber`){var t=QS(g);V.rad.value=new g(1),V.deg.value=t.div(180),V.grad.value=t.div(200),V.cycle.value=t.times(2),V.arcsec.value=t.div(648e3),V.arcmin.value=t.div(10800)}else V.rad.value=1,V.deg.value=Math.PI/180,V.grad.value=Math.PI/200,V.cycle.value=Math.PI*2,V.arcsec.value=Math.PI/648e3,V.arcmin.value=Math.PI/10800;V.radian.value=V.rad.value,V.degree.value=V.deg.value,V.gradian.value=V.grad.value}re(n),t&&t(`config`,function(e,t){e.number!==t.number&&re(e)});var ie={si:{NONE:{unit:B,prefix:R.NONE[``]},LENGTH:{unit:V.m,prefix:R.SHORT[``]},MASS:{unit:V.g,prefix:R.SHORT.k},TIME:{unit:V.s,prefix:R.SHORT[``]},CURRENT:{unit:V.A,prefix:R.SHORT[``]},TEMPERATURE:{unit:V.K,prefix:R.SHORT[``]},LUMINOUS_INTENSITY:{unit:V.cd,prefix:R.SHORT[``]},AMOUNT_OF_SUBSTANCE:{unit:V.mol,prefix:R.SHORT[``]},ANGLE:{unit:V.rad,prefix:R.SHORT[``]},BIT:{unit:V.bits,prefix:R.SHORT[``]},FORCE:{unit:V.N,prefix:R.SHORT[``]},ENERGY:{unit:V.J,prefix:R.SHORT[``]},POWER:{unit:V.W,prefix:R.SHORT[``]},PRESSURE:{unit:V.Pa,prefix:R.SHORT[``]},ELECTRIC_CHARGE:{unit:V.C,prefix:R.SHORT[``]},ELECTRIC_CAPACITANCE:{unit:V.F,prefix:R.SHORT[``]},ELECTRIC_POTENTIAL:{unit:V.V,prefix:R.SHORT[``]},ELECTRIC_RESISTANCE:{unit:V.ohm,prefix:R.SHORT[``]},ELECTRIC_INDUCTANCE:{unit:V.H,prefix:R.SHORT[``]},ELECTRIC_CONDUCTANCE:{unit:V.S,prefix:R.SHORT[``]},MAGNETIC_FLUX:{unit:V.Wb,prefix:R.SHORT[``]},MAGNETIC_FLUX_DENSITY:{unit:V.T,prefix:R.SHORT[``]},FREQUENCY:{unit:V.Hz,prefix:R.SHORT[``]}}};ie.cgs=JSON.parse(JSON.stringify(ie.si)),ie.cgs.LENGTH={unit:V.m,prefix:R.SHORT.c},ie.cgs.MASS={unit:V.g,prefix:R.SHORT[``]},ie.cgs.FORCE={unit:V.dyn,prefix:R.SHORT[``]},ie.cgs.ENERGY={unit:V.erg,prefix:R.NONE[``]},ie.us=JSON.parse(JSON.stringify(ie.si)),ie.us.LENGTH={unit:V.ft,prefix:R.NONE[``]},ie.us.MASS={unit:V.lbm,prefix:R.NONE[``]},ie.us.TEMPERATURE={unit:V.degF,prefix:R.NONE[``]},ie.us.FORCE={unit:V.lbf,prefix:R.NONE[``]},ie.us.ENERGY={unit:V.BTU,prefix:R.BTU[``]},ie.us.POWER={unit:V.hp,prefix:R.NONE[``]},ie.us.PRESSURE={unit:V.psi,prefix:R.NONE[``]},ie.auto=JSON.parse(JSON.stringify(ie.si));var ae=ie.auto;for(var oe in x.setUnitSystem=function(e){if(nu(ie,e))ae=ie[e];else throw Error(`Unit system `+e+` does not exist. Choices are: `+Object.keys(ie).join(`, `))},x.getUnitSystem=function(){for(var e in ie)if(nu(ie,e)&&ie[e]===ae)return e},x.typeConverters={BigNumber:function(e){return e!=null&&e.isFraction?new g(String(e.n)).div(String(e.d)).times(String(e.s)):new g(e+``)},Fraction:function(e){return new _(e)},Complex:function(e){return e},number:function(e){return e!=null&&e.isFraction?m(e):e}},x.prototype._numberConverter=function(){var e=x.typeConverters[this.valueType()];if(e)return e;throw TypeError(`Unsupported Unit value type "`+this.valueType()+`"`)},x._getNumberConverter=function(e){if(!x.typeConverters[e])throw TypeError(`Unsupported type "`+e+`"`);return x.typeConverters[e]},V)if(nu(V,oe)){var se=V[oe];se.dimensions=se.base.dimensions}for(var ce in H)if(nu(H,ce)){var le=V[H[ce]],ue={};for(var de in le)nu(le,de)&&(ue[de]=le[de]);ue.name=ce,V[ce]=ue}x.isValidAlpha=function(e){return/^[a-zA-Z]$/.test(e)};function fe(e){for(var t=0;t<e.length;t++){if(w=e.charAt(t),t===0&&!x.isValidAlpha(w))throw Error(`Invalid unit name (must begin with alpha character): "`+e+`"`);if(t>0&&!(x.isValidAlpha(w)||D(w)))throw Error(`Invalid unit name (only alphanumeric characters are allowed): "`+e+`"`)}}return x.createUnit=function(e,t){if(typeof e!=`object`)throw TypeError(`createUnit expects first parameter to be of type 'Object'`);if(t&&t.override){for(var n in e)if(nu(e,n)&&x.deleteUnit(n),e[n].aliases)for(var r=0;r<e[n].aliases.length;r++)x.deleteUnit(e[n].aliases[r])}var i;for(var a in e)nu(e,a)&&(i=x.createUnitSingle(a,e[a]));return i},x.createUnitSingle=function(e,t){if(t??={},typeof e!=`string`)throw TypeError(`createUnitSingle expects first parameter to be of type 'string'`);if(nu(V,e))throw Error(`Cannot create unit "`+e+`": a unit with that name already exists`);fe(e);var n=null,r=[],i=0,a,o,s;if(t&&t.type===`Unit`)n=t.clone();else if(typeof t==`string`)t!==``&&(a=t);else if(typeof t==`object`)a=t.definition,o=t.prefixes,i=t.offset,s=t.baseName,t.aliases&&(r=t.aliases.valueOf());else throw TypeError(`Cannot create unit "`+e+`" from "`+t.toString()+`": expecting "string" or "Unit" or "Object"`);if(r){for(var c=0;c<r.length;c++)if(nu(V,r[c]))throw Error(`Cannot create alias "`+r[c]+`": a unit with that name already exists`)}if(a&&typeof a==`string`&&!n)try{n=x.parse(a,{allowNoUnits:!0})}catch(t){throw t.message=`Could not create unit "`+e+`" from "`+a+`": `+t.message,t}else a&&a.type===`Unit`&&(n=a.clone());r||=[],i||=0,o=o&&o.toUpperCase&&R[o.toUpperCase()]||R.NONE;var l={};if(n){l={name:e,value:n.value,dimensions:n.dimensions.slice(0),prefixes:o,offset:i};var u=!1;for(var d in z)if(nu(z,d)){for(var f=!0,p=0;p<te.length;p++)if(Math.abs((l.dimensions[p]||0)-(z[d].dimensions[p]||0))>1e-12){f=!1;break}if(f){u=!0,l.base=z[d];break}}if(!u){s||=e+`_STUFF`;var m={dimensions:n.dimensions.slice(0)};m.key=s,z[s]=m,ae[s]={unit:l,prefix:R.NONE[``]},l.base=z[s]}}else{if(s||=e+`_STUFF`,te.indexOf(s)>=0)throw Error(`Cannot create new base unit "`+e+`": a base unit with that name already exists (and cannot be overridden)`);for(var h in te.push(s),z)nu(z,h)&&(z[h].dimensions[te.length-1]=0);for(var g={dimensions:[]},_=0;_<te.length;_++)g.dimensions[_]=0;g.dimensions[te.length-1]=1,g.key=s,z[s]=g,l={name:e,value:1,dimensions:z[s].dimensions.slice(0),prefixes:o,offset:i,base:z[s]},ae[s]={unit:l,prefix:R.NONE[``]}}x.UNITS[e]=l;for(var v=0;v<r.length;v++){var y=r[v],b={};for(var S in l)nu(l,S)&&(b[S]=l[S]);b.name=y,x.UNITS[y]=b}return delete N.cache,new x(null,e)},x.deleteUnit=function(e){delete x.UNITS[e],delete N.cache},x.PREFIXES=R,x.BASE_DIMENSIONS=te,x.BASE_UNITS=z,x.UNIT_SYSTEMS=ie,x.UNITS=V,x},{isClass:!0})})),tC,Ehe,nC,Dhe=e((()=>{X(),Wp(),tC=`unit`,Ehe=[`typed`,`Unit`],nC=Y(tC,Ehe,e=>{var{typed:t,Unit:n}=e;return t(tC,{Unit:function(e){return e.clone()},string:function(e){return n.isValuelessUnit(e)?new n(null,e):n.parse(e,{allowNoUnits:!0})},"number | BigNumber | Fraction | Complex, string | Unit":function(e,t){return new n(e,t)},"number | BigNumber | Fraction":function(e){return new n(e)},"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),rC,Ohe,iC,khe=e((()=>{X(),rC=`sparse`,Ohe=[`typed`,`SparseMatrix`],iC=Y(rC,Ohe,e=>{var{typed:t,SparseMatrix:n}=e;return t(rC,{"":function(){return new n([])}
2590,string:function(e){return new n([],e)},"Array | Matrix":function(e){return new n(e)},"Array | Matrix, string":function(e,t){return new n(e,t)}})})})),aC,Ahe,oC,jhe=e((()=>{X(),aC=`createUnit`,Ahe=[`typed`,`Unit`],oC=Y(aC,Ahe,e=>{var{typed:t,Unit:n}=e;return t(aC,{"Object, Object":function(e,t){return n.createUnit(e,t)},Object:function(e){return n.createUnit(e,{})},"string, Unit | string | Object, Object":function(e,t,r){var i={};return i[e]=t,n.createUnit(i,r)},"string, Unit | string | Object":function(e,t){var r={};return r[e]=t,n.createUnit(r,{})},string:function(e){var t={};return t[e]={},n.createUnit(t,{})}})})})),sC,Mhe,cC,Nhe=e((()=>{X(),sC=`acos`,Mhe=[`typed`,`config`,`Complex`],cC=Y(sC,Mhe,e=>{var{typed:t,config:n,Complex:r}=e;return t(sC,{number:function(e){return e>=-1&&e<=1||n.predictable?Math.acos(e):new r(e,0).acos()},Complex:function(e){return e.acos()},BigNumber:function(e){return e.acos()}})})})),lC,Phe,uC,Fhe=e((()=>{X(),ph(),lC=`acosh`,Phe=[`typed`,`config`,`Complex`],uC=Y(lC,Phe,e=>{var{typed:t,config:n,Complex:r}=e;return t(lC,{number:function(e){return e>=1||n.predictable?Gm(e):e<=-1?new r(Math.log(Math.sqrt(e*e-1)-e),Math.PI):new r(e,0).acosh()},Complex:function(e){return e.acosh()},BigNumber:function(e){return e.acosh()}})})})),dC,Ihe,fC,Lhe=e((()=>{X(),ph(),dC=`acot`,Ihe=[`typed`,`BigNumber`],fC=Y(dC,Ihe,e=>{var{typed:t,BigNumber:n}=e;return t(dC,{number:Km,Complex:function(e){return e.acot()},BigNumber:function(e){return new n(1).div(e).atan()}})})})),pC,Rhe,mC,zhe=e((()=>{X(),ph(),pC=`acoth`,Rhe=[`typed`,`config`,`Complex`,`BigNumber`],mC=Y(pC,Rhe,e=>{var{typed:t,config:n,Complex:r,BigNumber:i}=e;return t(pC,{number:function(e){return e>=1||e<=-1||n.predictable?qm(e):new r(e,0).acoth()},Complex:function(e){return e.acoth()},BigNumber:function(e){return new i(1).div(e).atanh()}})})})),hC,Bhe,gC,Vhe=e((()=>{X(),ph(),hC=`acsc`,Bhe=[`typed`,`config`,`Complex`,`BigNumber`],gC=Y(hC,Bhe,e=>{var{typed:t,config:n,Complex:r,BigNumber:i}=e;return t(hC,{number:function(e){return e<=-1||e>=1||n.predictable?Jm(e):new r(e,0).acsc()},Complex:function(e){return e.acsc()},BigNumber:function(e){return new i(1).div(e).asin()}})})})),_C,Hhe,vC,Uhe=e((()=>{X(),ph(),_C=`acsch`,Hhe=[`typed`,`BigNumber`],vC=Y(_C,Hhe,e=>{var{typed:t,BigNumber:n}=e;return t(_C,{number:Ym,Complex:function(e){return e.acsch()},BigNumber:function(e){return new n(1).div(e).asinh()}})})})),yC,Whe,bC,Ghe=e((()=>{X(),ph(),yC=`asec`,Whe=[`typed`,`config`,`Complex`,`BigNumber`],bC=Y(yC,Whe,e=>{var{typed:t,config:n,Complex:r,BigNumber:i}=e;return t(yC,{number:function(e){return e<=-1||e>=1||n.predictable?Xm(e):new r(e,0).asec()},Complex:function(e){return e.asec()},BigNumber:function(e){return new i(1).div(e).acos()}})})})),xC,Khe,SC,qhe=e((()=>{X(),ph(),xC=`asech`,Khe=[`typed`,`config`,`Complex`,`BigNumber`],SC=Y(xC,Khe,e=>{var{typed:t,config:n,Complex:r,BigNumber:i}=e;return t(xC,{number:function(e){if(e<=1&&e>=-1||n.predictable){var t=1/e;if(t>0||n.predictable)return Zm(e);var i=Math.sqrt(t*t-1);return new r(Math.log(i-t),Math.PI)}return new r(e,0).asech()},Complex:function(e){return e.asech()},BigNumber:function(e){return new i(1).div(e).acosh()}})})})),CC,Jhe,wC,Yhe=e((()=>{X(),CC=`asin`,Jhe=[`typed`,`config`,`Complex`],wC=Y(CC,Jhe,e=>{var{typed:t,config:n,Complex:r}=e;return t(CC,{number:function(e){return e>=-1&&e<=1||n.predictable?Math.asin(e):new r(e,0).asin()},Complex:function(e){return e.asin()},BigNumber:function(e){return e.asin()}})})})),Xhe,Zhe,TC,Qhe=e((()=>{X(),ph(),Xhe=`asinh`,Zhe=[`typed`],TC=Y(Xhe,Zhe,e=>{var{typed:t}=e;return t(`asinh`,{number:Qm,Complex:function(e){return e.asinh()},BigNumber:function(e){return e.asinh()}})})})),$he,ege,EC,tge=e((()=>{X(),$he=`atan`,ege=[`typed`],EC=Y($he,ege,e=>{var{typed:t}=e;return t(`atan`,{number:function(e){return Math.atan(e)},Complex:function(e){return e.atan()},BigNumber:function(e){return e.atan()}})})})),DC,nge,OC,rge=e((()=>{X(),V_(),G_(),ade(),a_(),l_(),iv(),DC=`atan2`,nge=[`typed`,`matrix`,`equalScalar`,`BigNumber`,`DenseMatrix`,`concat`],OC=Y(DC,nge,e=>{var{typed:t,matrix:n,equalScalar:r,BigNumber:i,DenseMatrix:a,concat:o}=e,s=B_({typed:t,equalScalar:r}),c=W_({typed:t}),l=by({typed:t,equalScalar:r}),u=i_({typed:t,equalScalar:r}),d=c_({typed:t,DenseMatrix:a}),f=rv({typed:t,matrix:n,concat:o});return t(DC,{"number, number":Math.atan2,"BigNumber, BigNumber":(e,t)=>i.atan2(e,t)},f({scalar:`number | BigNumber`,SS:l,DS:c,SD:s,Ss:u,sS:d}))})})),kC,ige,AC,age=e((()=>{X(),ph(),kC=`atanh`,ige=[`typed`,`config`,`Complex`],AC=Y(kC,ige,e=>{var{typed:t,config:n,Complex:r}=e;return t(kC,{number:function(e){return e<=1&&e>=-1||n.predictable?$m(e):new r(e,0).atanh()},Complex:function(e){return e.atanh()},BigNumber:function(e){return e.atanh()}})})})),jC,MC=e((()=>{X(),jC=Y(`trigUnit`,[`typed`],e=>{var{typed:t}=e;return{Unit:t.referToSelf(e=>n=>{if(!n.hasBase(n.constructor.BASE_UNITS.ANGLE))throw TypeError(`Unit in function cot is no angle`);return t.find(e,n.valueType())(n.value)})}})})),NC,oge,PC,sge=e((()=>{X(),MC(),NC=`cos`,oge=[`typed`],PC=Y(NC,oge,e=>{var{typed:t}=e,n=jC({typed:t});return t(NC,{number:Math.cos,"Complex | BigNumber":e=>e.cos()},n)})})),FC,cge,IC,lge=e((()=>{X(),Pu(),FC=`cosh`,cge=[`typed`],IC=Y(FC,cge,e=>{var{typed:t}=e;return t(FC,{number:ju,"Complex | BigNumber":e=>e.cosh()})})})),LC,uge,RC,dge=e((()=>{X(),ph(),MC(),LC=`cot`,uge=[`typed`,`BigNumber`],RC=Y(LC,uge,e=>{var{typed:t,BigNumber:n}=e,r=jC({typed:t});return t(LC,{number:eh,Complex:e=>e.cot(),BigNumber:e=>new n(1).div(e.tan())},r)})})),zC,fge,BC,pge=e((()=>{X(),ph(),zC=`coth`,fge=[`typed`,`BigNumber`],BC=Y(zC,fge,e=>{var{typed:t,BigNumber:n}=e;return t(zC,{number:th,Complex:e=>e.coth(),BigNumber:e=>new n(1).div(e.tanh())})})})),VC,mge,HC,hge=e((()=>{X(),ph(),MC(),VC=`csc`,mge=[`typed`,`BigNumber`],HC=Y(VC,mge,e=>{var{typed:t,BigNumber:n}=e,r=jC({typed:t});return t(VC,{number:nh,Complex:e=>e.csc(),BigNumber:e=>new n(1).div(e.sin())},r)})})),UC,gge,WC,_ge=e((()=>{X(),ph(),UC=`csch`,gge=[`typed`,`BigNumber`],WC=Y(UC,gge,e=>{var{typed:t,BigNumber:n}=e;return t(UC,{number:rh,Complex:e=>e.csch(),BigNumber:e=>new n(1).div(e.sinh())})})})),GC,vge,KC,yge=e((()=>{X(),ph(),MC(),GC=`sec`,vge=[`typed`,`BigNumber`],KC=Y(GC,vge,e=>{var{typed:t,BigNumber:n}=e,r=jC({typed:t});return t(GC,{number:ih,Complex:e=>e.sec(),BigNumber:e=>new n(1).div(e.cos())},r)})})),qC,bge,JC,xge=e((()=>{X(),ph(),qC=`sech`,bge=[`typed`,`BigNumber`],JC=Y(qC,bge,e=>{var{typed:t,BigNumber:n}=e;return t(qC,{number:ah,Complex:e=>e.sech(),BigNumber:e=>new n(1).div(e.cosh())})})})),YC,Sge,XC,Cge=e((()=>
vendor: 7,794 bytes, line 2590
2590{X(),MC(),YC=`sin`,Sge=[`typed`],XC=Y(YC,Sge,e=>{var{typed:t}=e,n=jC({typed:t});return t(YC,{number:Math.sin,"Complex | BigNumber":e=>e.sin()},n)})})),ZC,wge,QC,Tge=e((()=>{X(),ph(),ZC=`sinh`,wge=[`typed`],QC=Y(ZC,wge,e=>{var{typed:t}=e;return t(ZC,{number:oh,"Complex | BigNumber":e=>e.sinh()})})})),$C,Ege,ew,Dge=e((()=>{X(),MC(),$C=`tan`,Ege=[`typed`],ew=Y($C,Ege,e=>{var{typed:t}=e,n=jC({typed:t});return t($C,{number:Math.tan,"Complex | BigNumber":e=>e.tan()},n)})})),Oge,kge,tw,Age=e((()=>{X(),Pu(),Oge=`tanh`,kge=[`typed`],tw=Y(Oge,kge,e=>{var{typed:t}=e;return t(`tanh`,{number:Nu,"Complex | BigNumber":e=>e.tanh()})})})),nw,jge,rw,Mge=e((()=>{Tp(),X(),nw=`setCartesian`,jge=[`typed`,`size`,`subset`,`compareNatural`,`Index`,`DenseMatrix`],rw=Y(nw,jge,e=>{var{typed:t,size:n,subset:r,compareNatural:i,Index:a,DenseMatrix:o}=e;return t(nw,{"Array | Matrix, Array | Matrix":function(e,t){var s=[];if(r(n(e),new a(0))!==0&&r(n(t),new a(0))!==0){var c=cp(Array.isArray(e)?e:e.toArray()).sort(i),l=cp(Array.isArray(t)?t:t.toArray()).sort(i);s=[];for(var u=0;u<c.length;u++)for(var d=0;d<l.length;d++)s.push([c[u],l[d]])}return Array.isArray(e)&&Array.isArray(t)?s:new o(s)}})})})),iw,Nge,aw,Pge=e((()=>{Tp(),X(),iw=`setDifference`,Nge=[`typed`,`size`,`subset`,`compareNatural`,`Index`,`DenseMatrix`],aw=Y(iw,Nge,e=>{var{typed:t,size:n,subset:r,compareNatural:i,Index:a,DenseMatrix:o}=e;return t(iw,{"Array | Matrix, Array | Matrix":function(e,t){var s;if(r(n(e),new a(0))===0)s=[];else if(r(n(t),new a(0))===0)return cp(e.toArray());else{var c=mp(cp(Array.isArray(e)?e:e.toArray()).sort(i)),l=mp(cp(Array.isArray(t)?t:t.toArray()).sort(i));s=[];for(var u,d=0;d<c.length;d++){u=!1;for(var f=0;f<l.length;f++)if(i(c[d].value,l[f].value)===0&&c[d].identifier===l[f].identifier){u=!0;break}u||s.push(c[d])}}return Array.isArray(e)&&Array.isArray(t)?hp(s):new o(hp(s))}})})})),ow,Fge,sw,Ige=e((()=>{Tp(),X(),ow=`setDistinct`,Fge=[`typed`,`size`,`subset`,`compareNatural`,`Index`,`DenseMatrix`],sw=Y(ow,Fge,e=>{var{typed:t,size:n,subset:r,compareNatural:i,Index:a,DenseMatrix:o}=e;return t(ow,{"Array | Matrix":function(e){var t;if(r(n(e),new a(0))===0)t=[];else{var s=cp(Array.isArray(e)?e:e.toArray()).sort(i);t=[],t.push(s[0]);for(var c=1;c<s.length;c++)i(s[c],s[c-1])!==0&&t.push(s[c])}return Array.isArray(e)?t:new o(t)}})})})),cw,Lge,lw,Rge=e((()=>{Tp(),X(),cw=`setIntersect`,Lge=[`typed`,`size`,`subset`,`compareNatural`,`Index`,`DenseMatrix`],lw=Y(cw,Lge,e=>{var{typed:t,size:n,subset:r,compareNatural:i,Index:a,DenseMatrix:o}=e;return t(cw,{"Array | Matrix, Array | Matrix":function(e,t){var s;if(r(n(e),new a(0))===0||r(n(t),new a(0))===0)s=[];else{var c=mp(cp(Array.isArray(e)?e:e.toArray()).sort(i)),l=mp(cp(Array.isArray(t)?t:t.toArray()).sort(i));s=[];for(var u=0;u<c.length;u++)for(var d=0;d<l.length;d++)if(i(c[u].value,l[d].value)===0&&c[u].identifier===l[d].identifier){s.push(c[u]);break}}return Array.isArray(e)&&Array.isArray(t)?hp(s):new o(hp(s))}})})})),uw,zge,dw,Bge=e((()=>{Tp(),X(),uw=`setIsSubset`,zge=[`typed`,`size`,`subset`,`compareNatural`,`Index`],dw=Y(uw,zge,e=>{var{typed:t,size:n,subset:r,compareNatural:i,Index:a}=e;return t(uw,{"Array | Matrix, Array | Matrix":function(e,t){if(r(n(e),new a(0))===0)return!0;if(r(n(t),new a(0))===0)return!1;for(var o=mp(cp(Array.isArray(e)?e:e.toArray()).sort(i)),s=mp(cp(Array.isArray(t)?t:t.toArray()).sort(i)),c,l=0;l<o.length;l++){c=!1;for(var u=0;u<s.length;u++)if(i(o[l].value,s[u].value)===0&&o[l].identifier===s[u].identifier){c=!0;break}if(c===!1)return!1}return!0}})})})),fw,Vge,pw,Hge=e((()=>{Tp(),X(),fw=`setMultiplicity`,Vge=[`typed`,`size`,`subset`,`compareNatural`,`Index`],pw=Y(fw,Vge,e=>{var{typed:t,size:n,subset:r,compareNatural:i,Index:a}=e;return t(fw,{"number | BigNumber | Fraction | Complex, Array | Matrix":function(e,t){if(r(n(t),new a(0))===0)return 0;for(var o=cp(Array.isArray(t)?t:t.toArray()),s=0,c=0;c<o.length;c++)i(o[c],e)===0&&s++;return s}})})})),mw,Uge,hw,Wge=e((()=>{Tp(),X(),mw=`setPowerset`,Uge=[`typed`,`size`,`subset`,`compareNatural`,`Index`],hw=Y(mw,Uge,e=>{var{typed:t,size:n,subset:r,compareNatural:i,Index:a}=e;return t(mw,{"Array | Matrix":function(e){if(r(n(e),new a(0))===0)return[];for(var t=cp(Array.isArray(e)?e:e.toArray()).sort(i),c=[],l=0;l.toString(2).length<=t.length;)c.push(o(t,l.toString(2).split(``).reverse())),l++;return s(c)}});function o(e,t){for(var n=[],r=0;r<t.length;r++)t[r]===`1`&&n.push(e[r]);return n}function s(e){for(var t=[],n=e.length-1;n>0;n--)for(var r=0;r<n;r++)e[r].length>e[r+1].length&&(t=e[r],e[r]=e[r+1],e[r+1]=t);return e}})})),gw,Gge,_w,Kge=e((()=>{Tp(),X(),gw=`setSize`,Gge=[`typed`,`compareNatural`],_w=Y(gw,Gge,e=>{var{typed:t,compareNatural:n}=e;return t(gw,{"Array | Matrix":function(e){return Array.isArray(e)?cp(e).length:cp(e.toArray()).length},"Array | Matrix, boolean":function(e,t){if(t===!1||e.length===0)return Array.isArray(e)?cp(e).length:cp(e.toArray()).length;for(var r=cp(Array.isArray(e)?e:e.toArray()).sort(n),i=1,a=1;a<r.length;a++)n(r[a],r[a-1])!==0&&i++;return i}})})})),vw,qge,yw,Jge=e((()=>{Tp(),X(),vw=`setSymDifference`,qge=[`typed`,`size`,`concat`,`subset`,`setDifference`,`Index`],yw=Y(vw,qge,e=>{var{typed:t,size:n,concat:r,subset:i,setDifference:a,Index:o}=e;return t(vw,{"Array | Matrix, Array | Matrix":function(e,t){if(i(n(e),new o(0))===0)return cp(t);if(i(n(t),new o(0))===0)return cp(e);var s=cp(e),c=cp(t);return r(a(s,c),a(c,s))}})})})),bw,Yge,xw,Xge=e((()=>{Tp(),X(),bw=`setUnion`,Yge=[`typed`,`size`,`concat`,`subset`,`setIntersect`,`setSymDifference`,`Index`],xw=Y(bw,Yge,e=>{var{typed:t,size:n,concat:r,subset:i,setIntersect:a,setSymDifference:o,Index:s}=e;return t(bw,{"Array | Matrix, Array | Matrix":function(e,t){if(i(n(e),new s(0))===0)return cp(t);if(i(n(t),new s(0))===0)return cp(e);var c=cp(e),l=cp(t);return r(o(c,l),a(c,l))}})})})),Sw,Zge,Cw,Qge=e((()=>{X(),fv(),gv(),bv(),iv(),Sw=`add`,Zge=[`typed`,`matrix`,`addScalar`,`equalScalar`,`DenseMatrix`,`SparseMatrix`,`concat`],Cw=Y(Sw,Zge,e=>{var{typed:t,matrix:n,addScalar:r,equalScalar:i,DenseMatrix:a,SparseMatrix:o,concat:s}=e,c=dv({typed:t}),l=hv({typed:t,equalScalar:i}),u=yv({typed:t,DenseMatrix:a}),d=rv({typed:t,matrix:n,concat:s});return t(Sw,{"any, any":r,"any, any, ...any":t.referToSelf(e=>(t,n,r)=>{for(var i=e(t,n),a=0;a<r.length;a++)i=e(i,r[a]);return i})},d({elop:r,DS:c,SS:l,Ss:u}))})})),ww,$ge,Tw,e_e=e((()=>{X(),Tp(),Ql(),ww=`hypot`,$ge=[`typed`,`abs`,`addScalar`,`divideScalar`,`multiplyScalar`,`sqrt`,`smaller`,`isPositive`],Tw=Y(ww,$ge,e=>{var{typed:t,abs:n,addScalar:r,divideScalar:i,multiplyScalar:a,sqrt:o,smaller:s,isPositive:c}=e;return t(ww,{"... number | BigNumber":l,Array:l,Matrix:e=>l(cp(e.toArray(),!0))});function l(e){for(var t=0,l=0,u=0;u<e.length;u++){if(Cl(e[u]))throw TypeError(`Unexpected type of argument to hypot`);var d=n(e[u]);s(l,d)?(t=a(t,a(i(l,d),i(l,d))),t=r(t,1),l=d):t=r(t,c(d)?a(i(d,l),i(d,l)):d)}return a(l,o(t))}})})),Ew,t_e,Dw,n_e=e((()=>{X(),Ew=`norm`,t_e=[`typed`,`abs`,`add`,`pow`,`conj`,`sqrt`,`multiply`,`equalScalar`,`larger`,`smaller`,`matrix`,`ctranspose`,`eigs`],Dw=Y(Ew,t_e,e=>{var{typed:t,abs:n,add:r,pow:i,conj:a,sqrt:o,multiply:s,equalScalar:c,larger:l,smaller:u,matrix:d,ctranspose:f,eigs:p}=e;return t(Ew,{number:Math.abs,Complex:function(e){return e.abs()},BigNumber:function(e){return e.abs()},boolean:function(e){return Math.abs(e)},Array:function(e){return S(d(e),2)},Matrix:function(e){return S(e,2)},"Array, number | BigNumber | string":function(e,t){return S(d(e),t)},"Matrix, number | BigNumber | string":function(e,t){return S(e,t)}});function m(e){var t=0;return e.forEach(function(e){var r=n(e);l(r,t)&&(t=r)},!0),t}function h(e){var t;return e.forEach(function(e){var r=n(e);(!t||u(r,t))&&(t=r)},!0),t||0}function g(e,t){if(t===1/0||t===`inf`)return m(e);
2590if(t===-1/0||t===`-inf`)return h(e);if(t===`fro`)return S(e,2);if(typeof t==`number`&&!isNaN(t)){if(!c(t,0)){var a=0;return e.forEach(function(e){a=r(i(n(e),t),a)},!0),i(a,1/t)}return 1/0}throw Error(`Unsupported parameter value`)}function _(e){var t=0;return e.forEach(function(e,n){t=r(t,s(e,a(e)))}),n(o(t))}function v(e){var t=[],i=0;return e.forEach(function(e,a){var o=a[1],s=r(t[o]||0,n(e));l(s,i)&&(i=s),t[o]=s},!0),i}function y(e){var t=e.size();if(t[0]!==t[1])throw RangeError(`Invalid matrix dimensions`);var r=p(s(f(e),e)).values.toArray(),i=r[r.length-1];return n(o(i))}function b(e){var t=[],i=0;return e.forEach(function(e,a){var o=a[0],s=r(t[o]||0,n(e));l(s,i)&&(i=s),t[o]=s},!0),i}function x(e,t){if(t===1)return v(e);if(t===1/0||t===`inf`)return b(e);if(t===`fro`)return _(e);if(t===2)return y(e);throw Error(`Unsupported parameter value `+t)}function S(e,t){var n=e.size();if(n.length===1)return g(e,t);if(n.length===2){if(n[0]&&n[1])return x(e,t);throw RangeError(`Invalid matrix dimensions`)}}})})),Ow,kw,Aw,r_e=e((()=>{X(),Ql(),Ow=`dot`,kw=[`typed`,`addScalar`,`multiplyScalar`,`conj`,`size`],Aw=Y(Ow,kw,e=>{var{typed:t,addScalar:n,multiplyScalar:r,conj:i,size:a}=e;return t(Ow,{"Array | DenseMatrix, Array | DenseMatrix":s,"SparseMatrix, SparseMatrix":c});function o(e,t){var n=a(e),r=a(t),i,o;if(n.length===1)i=n[0];else if(n.length===2&&n[1]===1)i=n[0];else throw RangeError(`Expected a column vector, instead got a matrix of size (`+n.join(`, `)+`)`);if(r.length===1)o=r[0];else if(r.length===2&&r[1]===1)o=r[0];else throw RangeError(`Expected a column vector, instead got a matrix of size (`+r.join(`, `)+`)`);if(i!==o)throw RangeError(`Vectors must have equal length (`+i+` != `+o+`)`);if(i===0)throw RangeError(`Cannot calculate the dot product of empty vectors`);return i}function s(e,s){var c=o(e,s),l=Dl(e)?e._data:e,u=Dl(e)?e._datatype||e.getDataType():void 0,d=Dl(s)?s._data:s,f=Dl(s)?s._datatype||s.getDataType():void 0,p=a(e).length===2,m=a(s).length===2,h=n,g=r;if(u&&f&&u===f&&typeof u==`string`&&u!==`mixed`){var _=u;h=t.find(n,[_,_]),g=t.find(r,[_,_])}if(!p&&!m){for(var v=g(i(l[0]),d[0]),y=1;y<c;y++)v=h(v,g(i(l[y]),d[y]));return v}if(!p&&m){for(var b=g(i(l[0]),d[0][0]),x=1;x<c;x++)b=h(b,g(i(l[x]),d[x][0]));return b}if(p&&!m){for(var S=g(i(l[0][0]),d[0]),C=1;C<c;C++)S=h(S,g(i(l[C][0]),d[C]));return S}if(p&&m){for(var w=g(i(l[0][0]),d[0][0]),T=1;T<c;T++)w=h(w,g(i(l[T][0]),d[T][0]));return w}}function c(e,t){o(e,t);for(var i=e._index,a=e._values,s=t._index,c=t._values,l=0,u=n,d=r,f=0,p=0;f<i.length&&p<s.length;){var m=i[f],h=s[p];if(m<h){f++;continue}if(m>h){p++;continue}m===h&&(l=u(l,d(a[f],c[p])),f++,p++)}return l}})})),jw,Mw,Nw,i_e=e((()=>{ru(),Hf(),X(),jw=`trace`,Mw=[`typed`,`matrix`,`add`],Nw=Y(jw,Mw,e=>{var{typed:t,matrix:n,add:r}=e;return t(`trace`,{Array:function(e){return i(n(e))},SparseMatrix:a,DenseMatrix:i,any:$l});function i(e){var t=e._size,n=e._data;switch(t.length){case 1:if(t[0]===1)return $l(n[0]);throw RangeError(`Matrix must be square (size: `+If(t)+`)`);case 2:var i=t[0];if(i===t[1]){for(var a=0,o=0;o<i;o++)a=r(a,n[o][o]);return a}else throw RangeError(`Matrix must be square (size: `+If(t)+`)`);default:throw RangeError(`Matrix must be two dimensional (size: `+If(t)+`)`)}}function a(e){var t=e._values,n=e._index,i=e._ptr,a=e._size,o=a[0],s=a[1];if(o===s){var c=0;if(t.length>0)for(var l=0;l<s;l++)for(var u=i[l],d=i[l+1],f=u;f<d;f++){var p=n[f];if(p===l){c=r(c,t[f]);break}if(p>l)break}return c}throw RangeError(`Matrix must be square (size: `+If(a)+`)`)}})})),Pw,Fw,Iw,a_e=e((()=>{Ql(),X(),Pw=`index`,Fw=[`typed`,`Index`],Iw=Y(Pw,Fw,e=>{var{typed:t,Index:n}=e;return t(Pw,{"...number | string | BigNumber | Range | Array | Matrix":function(e){var t=e.map(function(e){return xl(e)?e.toNumber():Zl(e)||Dl(e)?e.map(function(e){return xl(e)?e.toNumber():e}):e}),r=new n;return n.apply(r,t),r}})})})),Lw,Rw=e((()=>{Lw=new Set([`end`])})),zw,Bw,Vw,o_e=e((()=>{Ql(),Rw(),ru(),X(),yl(),zw=`Node`,Bw=[`mathWithTransform`],Vw=Y(zw,Bw,e=>{var{mathWithTransform:t}=e;function n(e){for(var t of[...Lw])if(e.has(t))throw Error(`Scope contains an illegal symbol, "`+t+`" is a reserved keyword`)}class r{get type(){return`Node`}get isNode(){return!0}evaluate(e){return this.compile().evaluate(e)}compile(){var e=this._compile(t,{}),r={},i=null;function a(t){var a=gl(t);return n(a),e(a,r,i)}return{evaluate:a}}_compile(e,t){throw Error(`Method _compile must be implemented by type `+this.t
2590ype)}forEach(e){throw Error(`Cannot run forEach on a Node interface`)}map(e){throw Error(`Cannot run map on a Node interface`)}_ifNode(e){if(!Wl(e))throw TypeError(`Callback function must return a Node`);return e}traverse(e){e(this,null,null);function t(e,n){e.forEach(function(e,r,i){n(e,r,i),t(e,n)})}t(this,e)}transform(e){function t(n,r,i){var a=e(n,r,i);return a===n?n.map(t):a}return t(this,null,null)}filter(e){var t=[];return this.traverse(function(n,r,i){e(n,r,i)&&t.push(n)}),t}clone(){throw Error(`Cannot clone a Node interface`)}cloneDeep(){return this.map(function(e){return e.cloneDeep()})}equals(e){return e?this.type===e.type&&eu(this,e):!1}toString(e){var t=this._getCustomString(e);return t===void 0?this._toString(e):t}_toString(){throw Error(`_toString not implemented for `+this.type)}toJSON(){throw Error(`Cannot serialize object: toJSON not implemented by `+this.type)}toHTML(e){var t=this._getCustomString(e);return t===void 0?this._toHTML(e):t}_toHTML(){throw Error(`_toHTML not implemented for `+this.type)}toTex(e){var t=this._getCustomString(e);return t===void 0?this._toTex(e):t}_toTex(e){throw Error(`_toTex not implemented for `+this.type)}_getCustomString(e){if(e&&typeof e==`object`)switch(typeof e.handler){case`object`:case`undefined`:return;case`function`:return e.handler(this,e);default:throw TypeError(`Object or function expected as callback`)}}getIdentifier(){return this.type}getContent(){return this}}return r},{isClass:!0,isNode:!0})}));function Hw(e){return e&&e.isIndexError?new Gf(e.index+1,e.min+1,e.max===void 0?void 0:e.max+1):e}var Uw=e((()=>{Kf()}));function Ww(e){var{subset:t}=e;return function(e,n){try{if(Array.isArray(e))return t(e,n);if(e&&typeof e.subset==`function`)return e.subset(n);if(typeof e==`string`)return t(e,n);if(typeof e==`object`){if(!n.isObjectProperty())throw TypeError(`Cannot apply a numeric index as object property`);return ul(e,n.getObjectProperty())}else throw TypeError(`Cannot apply index: unsupported type of object`)}catch(e){throw Hw(e)}}}var Gw=e((()=>{Uw(),ml()})),Kw,qw,Jw,s_e=e((()=>{Ln(),Ql(),ml(),X(),Gw(),Kw=`AccessorNode`,qw=[`subset`,`Node`],Jw=Y(Kw,qw,e=>{var{subset:t,Node:n}=e,r=Ww({subset:t});function i(e){return!(Ll(e)||Rl(e)||zl(e)||Hl(e)||Gl(e)||ql(e)||Jl(e))}class a extends n{constructor(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;if(super(),!Wl(e))throw TypeError(`Node expected for parameter "object"`);if(!Ul(t))throw TypeError(`IndexNode expected for parameter "index"`);this.object=e,this.index=t,this.optionalChaining=n}get name(){return this.index?this.index.isObjectProperty()?this.index.getObjectProperty():``:this.object.name||``}get type(){return Kw}get isAccessorNode(){return!0}_compile(e,t){var n=this.object._compile(e,t),i=this.index._compile(e,t),a=this.optionalChaining,o=Ll(this.object)&&this.object.optionalChaining;if(this.index.isObjectProperty()){var s=this.index.getObjectProperty();return function(e,t,r){var i=r||{},c=n(e,t,i);if(a&&c==null){i.optionalShortCircuit=!0;return}if(!(o&&i!=null&&i.optionalShortCircuit))return ul(c,s)}}else return function(e,t,s){var c=s||{},l=n(e,t,c);if(a&&l==null){c.optionalShortCircuit=!0;return}if(!(o&&c!=null&&c.optionalShortCircuit))return r(l,i(e,t,l))}}forEach(e){e(this.object,`object`,this),e(this.index,`index`,this)}map(e){return new a(this._ifNode(e(this.object,`object`,this)),this._ifNode(e(this.index,`index`,this)),this.optionalChaining)}clone(){return new a(this.object,this.index,this.optionalChaining)}_toString(e){var t=this.object.toString(e);i(this.object)&&(t=`(`+t+`)`);var n=this.optionalChaining?this.index.dotNotation?`?`:`?.`:``;return t+n+this.index.toString(e)}_toHTML(e){var t=this.object.toHTML(e);return i(this.object)&&(t=`<span class="math-parenthesis math-round-parenthesis">(</span>`+t+`<span class="math-parenthesis math-round-parenthesis">)</span>`),t+this.index.toHTML(e)}_toTex(e){var t=this.object.toTex(e);return i(this.object)&&(t=`\\left(' + object + '\\right)`),t+this.index.toTex(e)}toJSON(){return{mathjs:Kw,object:this.object,index:this.index,optionalChaining:this.optionalChaining}}static fromJSON(e){return new a(e.object,e.index,e.optionalChaining)}}return Rn(a,`name`,Kw),a},{isClass:!0,isNode:!0})})),Yw,Xw,Zw,c_e=e((()=>{Ln(),Ql(),Tp(),X(),Yw=`ArrayNode`,Xw=[`Node`],Zw=Y(Yw,Xw,e=>{var{Node:t}=e;class n extends t{constructor(e){if(super(),this.items=e||[],!Array.isArray(this.items)||!this.items.every(Wl))throw TypeError(`Array containing Nodes expected`)}get type(){return Yw}get isArrayNode(){return!0}_compile(e,t){var n=lp(this.items,function(n){return n._compile(e,t)});if(e.config.matrix!==`Array`){var r=e.matrix;return function(e,t,i){return r(lp(n,function(n){return n(e,t,i)}))}}else return function(e,t,r){return lp(n,function(n){return n(e,t,r)})}}forEach(e){for(var t=0;t<this.items.length;t++){var n=this.items[t];e(n,`items[`+t+`]`,this)}}map(e){for(var t=[],r=0;r<this.items.length;r++)t[r]=this._ifNode(e(this.items[r],`items[`+r+`]`,this));return new n(t)}clone(){return new n(this.items.slice(0))}_toString(e){return`[`+this.items.map(function(t){return t.toString(e)}).join(`, `)+`]`}toJSON(){return{mathjs:Yw,items:this.items}}static fromJSON(e){return new n(e.items)}_toHTML(e){return`<span class="math-parenthesis math-square-parenthesis">[</span>`+this.items.map(function(t){return t.toHTML(e)}).join(`<span class="math-separator">,</span>`)+`<span class="math-parenthesis math-square-parenthesis">]</span>`}_toTex(e){function t(n,r){var i=n.some(Rl)&&!n.every(Rl),a=r||i,o=a?`&`:`\\\\`,s=n.map(function(n){return n.items?t(n.items,!r):n.toTex(e)}).join(o);return i||!a||a&&!r?`\\begin{bmatrix}`+s+`\\end{bmatrix}`:s}return t(this.items,!1)}}return Rn(n,`name`,Yw),n},{isClass:!0,isNode:!0})}));function l_e(e){var{subset:t,matrix:n}=e;return function(e,r,i){try{if(Array.isArray(e))return n(e).subset(r,i).valueOf().forEac
2590h((t,n)=>{e[n]=t}),e;if(e&&typeof e.subset==`function`)return e.subset(r,i);if(typeof e==`string`)return t(e,r,i);if(typeof e==`object`){if(!r.isObjectProperty())throw TypeError(`Cannot apply a numeric index as object property`);return dl(e,r.getObjectProperty(),i),e}else throw TypeError(`Cannot apply index: unsupported type of object`)}catch(e){throw Hw(e)}}}var u_e=e((()=>{Uw(),ml()}));function Qw(e,t){if(!t||t!==`auto`)return e;for(var n=e;ql(n);)n=n.content;return n}function $w(e,t,n,r){var i=e;t!==`keep`&&(i=e.getContent());for(var a=i.getIdentifier(),o=null,s=0;s<nT.length;s++)if(a in nT[s]){o=s;break}if(a===`OperatorNode:multiply`&&i.implicit&&n!==`show`){var c=Qw(i.args[0],t);!(zl(c)&&r&&r.getIdentifier()===`OperatorNode:divide`&&Bl(Qw(r.args[0],t)))&&!(c.getIdentifier()===`OperatorNode:divide`&&Bl(Qw(c.args[0],t))&&zl(Qw(c.args[1])))&&(o+=1)}return o}function eT(e,t){var n=e;t!==`keep`&&(n=e.getContent());var r=n.getIdentifier(),i=$w(n,t);if(i===null)return null;var a=nT[i][r];if(nu(a,`associativity`)){if(a.associativity===`left`)return`left`;if(a.associativity===`right`)return`right`;throw Error(`'`+r+`' has the invalid associativity '`+a.associativity+`'.`)}return null}function tT(e,t,n){var r=n===`keep`?e:e.getContent(),i=n===`keep`?t:e.getContent(),a=r.getIdentifier(),o=i.getIdentifier(),s=$w(r,n);if(s===null)return null;var c=nT[s][a];if(nu(c,`associativeWith`)&&c.associativeWith instanceof Array){for(var l=0;l<c.associativeWith.length;l++)if(c.associativeWith[l]===o)return!0;return!1}return null}function d_e(e){var t=`OperatorNode:`+e;for(var n of nT)if(t in n)return n[t].op;return null}var nT,rT=e((()=>{ru(),Ql(),nT=[{AssignmentNode:{},FunctionAssignmentNode:{}},{ConditionalNode:{latexLeftParens:!1,latexRightParens:!1,latexParens:!1}},{"OperatorNode:or":{op:`or`,associativity:`left`,associativeWith:[]}},{"OperatorNode:xor":{op:`xor`,associativity:`left`,associativeWith:[]}},{"OperatorNode:and":{op:`and`,associativity:`left`,associativeWith:[]}},{"OperatorNode:bitOr":{op:`|`,associativity:`left`,associativeWith:[]}},{"OperatorNode:bitXor":{op:`^|`,associativity:`left`,associativeWith:[]}},{"OperatorNode:bitAnd":{op:`&`,associativity:`left`,associativeWith:[]}},{"OperatorNode:equal":{op:`==`,associativity:`left`,associativeWith:[]},"OperatorNode:unequal":{op:`!=`,associativity:`left`,associativeWith:[]},"OperatorNode:smaller":{op:`<`,associativity:`left`,associativeWith:[]},"OperatorNode:larger":{op:`>`,associativity:`left`,associativeWith:[]},"OperatorNode:smallerEq":{op:`<=`,associativity:`left`,associativeWith:[]},"OperatorNode:largerEq":{op:`>=`,associativity:`left`,associativeWith:[]},RelationalNode:{associativity:`left`,associativeWith:[]}},{"OperatorNode:leftShift":{op:`<<`,associativity:`left`,associativeWith:[]},"OperatorNode:rightArithShift":{op:`>>`,associativity:`left`,associativeWith:[]},"OperatorNode:rightLogShift":{op:`>>>`,associativity:`left`,associativeWith:[]}},{"OperatorNode:to":{op:`to`,associativity:`left`,associativeWith:[]}},{RangeNode:{}},{"OperatorNode:add":{op:`+`,associativity:`left`,associativeWith:[`OperatorNode:add`,`OperatorNode:subtract`]},"OperatorNode:subtract":{op:`-`,associativity:`left`,associativeWith:[]}},{"OperatorNode:multiply":{op:`*`,associativity:`left`,associativeWith:[`OperatorNode:multiply`,`OperatorNode:divide`,`Operator:dotMultiply`,`Operator:dotDivide`]},"OperatorNode:divide":{op:`/`,associativity:`left`,associativeWith:[],latexLeftParens:!1,latexRightParens:!1,latexParens:!1},"OperatorNode:dotMultiply":{op:`.*`,associativity:`left`,associativeWith:[`OperatorNode:multiply`,`OperatorNode:divide`,`OperatorNode:dotMultiply`,`OperatorNode:doDivide`]},"OperatorNode:dotDivide":{op:`./`,associativity:`left`,associativeWith:[]},"OperatorNode:mod":{op:`mod`,associativity:`left`,associativeWith:[]}},{"OperatorNode:multiply":{associativity:`left`,associativeWith:[`OperatorNode:multiply`,`OperatorNode:divide`,`Operator:dotMultiply`,`Operator:dotDivide`]}},{"OperatorNode:unaryPlus":{op:`+`,associativity:`right`},"OperatorNode:unaryMinus":{op:`-`,associativity:`right`},"OperatorNode:bitNot":{op:`~`,associativity:`right`},"OperatorNode:not":{op:`not`,associativity:`right`}},{"OperatorNode:pow":{op:`^`,associativity:`right`,associativeWith:[],latexRightParens:!1},"OperatorNode:dotPow":{op:`.^`,associativity:`right`,associativeWith:[]}},{"OperatorNode:nullish":{op:`??`,associativity:`left`,associativeWith:[]}},{"OperatorNode:factorial":{op:`!`,associativity:`left`}},{"OperatorNode:ctranspose":{op:`'`,associativity:`left`}}]})),iT,aT,oT,f_e=e((()=>{Ln(),Ql(),ml(),X(),Gw(),u_e(),rT(),iT=`AssignmentNode`,aT=[`subset`,`?matrix`,`Node`],oT=Y(iT,aT,e=>{var{subset:t,matrix:n,Node:r}=e,i=Ww({subset:t}),a=l_e({subset:t,matrix:n});function o(e,t,n){t||=`keep`;
2590var r=$w(e,t,n),i=$w(e.value,t,n);return t===`all`||i!==null&&i<=r}class s extends r{constructor(e,t,n){if(super(),this.object=e,this.index=n?t:null,this.value=n||t,!Jl(e)&&!Ll(e))throw TypeError(`SymbolNode or AccessorNode expected as "object"`);if(Jl(e)&&e.name===`end`)throw Error(`Cannot assign to symbol "end"`);if(this.index&&!Ul(this.index))throw TypeError(`IndexNode expected as "index"`);if(!Wl(this.value))throw TypeError(`Node expected as "value"`)}get name(){return this.index?this.index.isObjectProperty()?this.index.getObjectProperty():``:this.object.name||``}get type(){return iT}get isAssignmentNode(){return!0}_compile(e,t){var n=this.object._compile(e,t),r=this.index?this.index._compile(e,t):null,o=this.value._compile(e,t),s=this.object.name;if(!this.index){if(!Jl(this.object))throw TypeError(`SymbolNode expected as object`);return function(e,t,n){var r=o(e,t,n);return e.set(s,r),r}}else if(this.index.isObjectProperty()){var c=this.index.getObjectProperty();return function(e,t,r){var i=n(e,t,r),a=o(e,t,r);return dl(i,c,a),a}}else if(Jl(this.object))return function(e,t,i){var c=n(e,t,i),l=o(e,t,i),u=r(e,t,c);return e.set(s,a(c,u,l)),l};else{var l=this.object.object._compile(e,t);if(this.object.index.isObjectProperty()){var u=this.object.index.getObjectProperty();return function(e,t,n){var i=l(e,t,n),s=ul(i,u),c=r(e,t,s),d=o(e,t,n);return dl(i,u,a(s,c,d)),d}}else{var d=this.object.index._compile(e,t);return function(e,t,n){var s=l(e,t,n),c=d(e,t,s),u=i(s,c),f=r(e,t,u),p=o(e,t,n);return a(s,c,a(u,f,p)),p}}}}forEach(e){e(this.object,`object`,this),this.index&&e(this.index,`index`,this),e(this.value,`value`,this)}map(e){return new s(this._ifNode(e(this.object,`object`,this)),this.index?this._ifNode(e(this.index,`index`,this)):null,this._ifNode(e(this.value,`value`,this)))}clone(){return new s(this.object,this.index,this.value)}_toString(e){var t=this.object.toString(e),n=this.index?this.index.toString(e):``,r=this.value.toString(e);return o(this,e&&e.parenthesis,e&&e.implicit)&&(r=`(`+r+`)`),t+n+` = `+r}toJSON(){return{mathjs:iT,object:this.object,index:this.index,value:this.value}}static fromJSON(e){return new s(e.object,e.index,e.value)}_toHTML(e){var t=this.object.toHTML(e),n=this.index?this.index.toHTML(e):``,r=this.value.toHTML(e);return o(this,e&&e.parenthesis,e&&e.implicit)&&(r=`<span class="math-paranthesis math-round-parenthesis">(</span>`+r+`<span class="math-paranthesis math-round-parenthesis">)</span>`),t+n+`<span class="math-operator math-assignment-operator math-variable-assignment-operator math-binary-operator">=</span>`+r}_toTex(e){var t=this.object.toTex(e),n=this.index?this.index.toTex(e):``,r=this.value.toTex(e);return o(this,e&&e.parenthesis,e&&e.implicit)&&(r=`\\left(${r}\\right)`),t+n+`=`+r}}return Rn(s,`name`,iT),s},{isClass:!0,isNode:!0})})),sT,cT,lT,p_e=e((()=>{Ln(),Ql(),Tp(),X(),sT=`BlockNode`,cT=[`ResultSet`,`Node`],lT=Y(sT,cT,e=>{var{ResultSet:t,Node:n}=e;class r extends n{constructor(e){if(super(),!Array.isArray(e))throw Error(`Array expected`);this.blocks=e.map(function(e){var t=e&&e.node,n=e&&e.visible!==void 0?e.visible:!0;if(!Wl(t))throw TypeError(`Property "node" must be a Node`);if(typeof n!=`boolean`)throw TypeError(`Property "visible" must be a boolean`);return{node:t,visible:n}})}get type(){return sT}get isBlockNode(){return!0}_compile(e,n){var r=lp(this.blocks,function(t){return{evaluate:t.node._compile(e,n),visible:t.visible}});return function(e,n,i){var a=[];return up(r,function(t){var r=t.evaluate(e,n,i);t.visible&&a.push(r)}),new t(a)}}forEach(e){for(var t=0;t<this.blocks.length;t++)e(this.blocks[t].node,`blocks[`+t+`].node`,this)}map(e){for(var t=[],n=0;n<this.blocks.length;n++){var i=this.blocks[n];t[n]={node:this._ifNode(e(i.node,`blocks[`+n+`].node`,this)),visible:i.visible}}return new r(t)}clone(){return new r(this.blocks.map(function(e){return{node:e.node,visible:e.visible}}))}_toString(e){return this.blocks.map(function(t){return t.node.toString(e)+(t.visible?``:`;`)}).join(`
2591`)}toJSON(){return{mathjs:sT,blocks:this.blocks}}static fromJSON(e){return new r(e.blocks)}_toHTML(e){return this.blocks.map(function(t){return t.node.toHTML(e)+(t.visible?``:`<span class="math-separator">;</span>`)}).join(`<span class="math-separator"><br /></span>`)}_toTex(e){return this.blocks.map(function(t){return t.node.toTex(e)+(t.visible?``:`;`)}).join(`\\;\\;
2592`)}}return Rn(r,`name`,sT),r},{isClass:!0,isNode:!0})})),uT,dT,fT,m_e=e((()=>{Ln(),Ql(),X(),rT(),uT=`ConditionalNode`,dT=[`Node`],fT=Y(uT,dT,e=>{var{Node:t}=e;function n(e){if(typeof e==`number`||typeof e==`boolean`||typeof e==`string`)return!!e;if(e){if(xl(e))return!e.isZero();
2592if(Cl(e))return!!(e.re||e.im);if(Tl(e))return!!e.value}if(e==null)return!1;throw TypeError(`Unsupported type of condition "`+Xl(e)+`"`)}class r extends t{constructor(e,t,n){if(super(),!Wl(e))throw TypeError(`Parameter condition must be a Node`);if(!Wl(t))throw TypeError(`Parameter trueExpr must be a Node`);if(!Wl(n))throw TypeError(`Parameter falseExpr must be a Node`);this.condition=e,this.trueExpr=t,this.falseExpr=n}get type(){return uT}get isConditionalNode(){return!0}_compile(e,t){var r=this.condition._compile(e,t),i=this.trueExpr._compile(e,t),a=this.falseExpr._compile(e,t);return function(e,t,o){return n(r(e,t,o))?i(e,t,o):a(e,t,o)}}forEach(e){e(this.condition,`condition`,this),e(this.trueExpr,`trueExpr`,this),e(this.falseExpr,`falseExpr`,this)}map(e){return new r(this._ifNode(e(this.condition,`condition`,this)),this._ifNode(e(this.trueExpr,`trueExpr`,this)),this._ifNode(e(this.falseExpr,`falseExpr`,this)))}clone(){return new r(this.condition,this.trueExpr,this.falseExpr)}_toString(e){var t=e&&e.parenthesis?e.parenthesis:`keep`,n=$w(this,t,e&&e.implicit),r=this.condition.toString(e),i=$w(this.condition,t,e&&e.implicit);(t===`all`||this.condition.type===`OperatorNode`||i!==null&&i<=n)&&(r=`(`+r+`)`);var a=this.trueExpr.toString(e),o=$w(this.trueExpr,t,e&&e.implicit);(t===`all`||this.trueExpr.type===`OperatorNode`||o!==null&&o<=n)&&(a=`(`+a+`)`);var s=this.falseExpr.toString(e),c=$w(this.falseExpr,t,e&&e.implicit);return(t===`all`||this.falseExpr.type===`OperatorNode`||c!==null&&c<=n)&&(s=`(`+s+`)`),r+` ? `+a+` : `+s}toJSON(){return{mathjs:uT,condition:this.condition,trueExpr:this.trueExpr,falseExpr:this.falseExpr}}static fromJSON(e){return new r(e.condition,e.trueExpr,e.falseExpr)}_toHTML(e){var t=e&&e.parenthesis?e.parenthesis:`keep`,n=$w(this,t,e&&e.implicit),r=this.condition.toHTML(e),i=$w(this.condition,t,e&&e.implicit);(t===`all`||this.condition.type===`OperatorNode`||i!==null&&i<=n)&&(r=`<span class="math-parenthesis math-round-parenthesis">(</span>`+r+`<span class="math-parenthesis math-round-parenthesis">)</span>`);var a=this.trueExpr.toHTML(e),o=$w(this.trueExpr,t,e&&e.implicit);(t===`all`||this.trueExpr.type===`OperatorNode`||o!==null&&o<=n)&&(a=`<span class="math-parenthesis math-round-parenthesis">(</span>`+a+`<span class="math-parenthesis math-round-parenthesis">)</span>`);var s=this.falseExpr.toHTML(e),c=$w(this.falseExpr,t,e&&e.implicit);return(t===`all`||this.falseExpr.type===`OperatorNode`||c!==null&&c<=n)&&(s=`<span class="math-parenthesis math-round-parenthesis">(</span>`+s+`<span class="math-parenthesis math-round-parenthesis">)</span>`),r+`<span class="math-operator math-conditional-operator">?</span>`+a+`<span class="math-operator math-conditional-operator">:</span>`+s}_toTex(e){return`\\begin{cases} {`+this.trueExpr.toTex(e)+`}, &\\quad{\\text{if }\\;`+this.condition.toTex(e)+`}\\\\{`+this.falseExpr.toTex(e)+`}, &\\quad{\\text{otherwise}}\\end{cases}`}}return Rn(r,`name`,uT),r},{isClass:!0,isNode:!0})})),h_e=r(((e,t)=>{var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},r={"{":`\\{`,"}":`\\}`,"\\":`\\textbackslash{}`,"#":`\\#`,$:`\\$`,"%":`\\%`,"&":`\\&`,"^":`\\textasciicircum{}`,_:`\\_`,"~":`\\textasciitilde{}`},i={"–":`\\--`,"—":`\\---`," ":`~`,"	":`\\qquad{}`,"\r\n":`\\newline{}`,"\n":`\\newline{}`},a=function(e,t){return n({},e,t)};t.exports=function(e){for(var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=t.preserveFormatting,s=o===void 0?!1:o,c=t.escapeMapFn,l=c===void 0?a:c,u=String(e),d=``,f=l(n({},r),s?n({},i):{}),p=Object.keys(f),m=function(){var e=!1;p.forEach(function(t,n){e||u.length>=t.length&&u.slice(0,t.length)===t&&(d+=f[p[n]],u=u.slice(t.length,u.length),e=!0)}),e||(d+=u.slice(0,1),u=u.slice(1,u.length))};u;)m();return d}}));function pT(e){return(0,hT.default)(e,{preserveFormatting:!0})}function mT(e,t){return t=t===void 0?!1:t,t?nu(bT,e)?bT[e]:`\\mathrm{`+pT(e)+`}`:nu(gT,e)?gT[e]:pT(e)}var hT,gT,_T,vT,yT,bT,xT=e((()=>{hT=t(h_e(),1),ru(),gT={Alpha:`A`,alpha:`\\alpha`,Beta:`B`,beta:`\\beta`,Gamma:`\\Gamma`,gamma:`\\gamma`,Delta:`\\Delta`,delta:`\\delta`,Epsilon:`E`,epsilon:`\\epsilon`,varepsilon:`\\varepsilon`,Zeta:`Z`,zeta:`\\zeta`,Eta:`H`,eta:`\\eta`,Theta:`\\Theta`,theta:`\\theta`,vartheta:`\\vartheta`,Iota:`I`,iota:`\\iota`,Kappa:`K`,kappa:`\\kappa`,varkappa:`\\varkappa`,Lambda:`\\Lambda`,lambda:`\\lambda`,Mu:`M`,mu:`\\mu`,Nu:`N`,nu:`\\nu`,Xi:`\\Xi`,xi:`\\xi`,Omicron:`O`,omicron:`o`,Pi:`\\Pi`,pi:`\\pi`,varpi:`\\varpi`,Rho:`P`,rho:`\\rho`,varrho:`\\varrho`,Sigma:`\\Sigma`,sigma:`\\sigma`,varsigma:`\\varsigma`,Tau:`T`,tau:`\\tau`,Upsilon:`\\Upsilon`,upsilon:`\\upsilon`,Phi:`\\Phi`,phi:`\\phi`,varphi:`\\varphi`,Chi:`X`,chi:`\\chi`,Psi:`\\Psi`,psi:`\\psi`,Omega:`\\Omega`,omega:`\\omega`,true:`\\mathrm{True}`,false:`\\mathrm{False}`,i:`i`,inf:`\\infty`,Inf:`\\infty`,infinity:`\\infty`,Infinity:`\\infty`,oo:`\\infty`,lim:`\\lim`,undefined:`\\mathbf{?}`},_T={transpose:`^\\top`,ctranspose:`^H`,factorial:`!`,pow:`^`,dotPow:`.^\\wedge`,unaryPlus:`+`,unaryMinus:`-`,bitNot:`\\~`,not:`\\neg`,multiply:`\\cdot`,divide:`\\frac`,dotMultiply:`.\\cdot`,dotDivide:`.:`,mod:`\\mod`,add:`+`,subtract:`-`,to:`\\rightarrow`,leftShift:`<<`,rightArithShift:`>>`,rightLogShift:`>>>`,equal:`=`,unequal:`\\neq`,smaller:`<`,larger:`>`,smallerEq:`\\leq`,largerEq:`\\geq`,bitAnd:`\\&`,bitXor:`\\underline{|}`,bitOr:`|`,and:`\\wedge`,xor:`\\veebar`,or:`\\vee`},vT={abs:{1:"\\left|${args[0]}\\right|"},add:{2:`\\left(\${args[0]}${_T.add}\${args[1]}\\right)`},cbrt:{1:"\\sqrt[3]{${args[0]}}"},ceil:{1:"\\left\\lceil${args[0]}\\right\\rceil"},cube:{1:"\\left(${args[0]}\\right)^3"},divide:{2:"\\frac{${args[0]}}{${args[1]}}"},dotDivide:{2:`\\left(\${args[0]}${_T.dotDivide}\${args[1]}\\right)`},dotMultiply:{2:`\\left(\${args[0]}${_T.dotMultiply}\${args[1]}\\right)`},dotPow:{2:`\\left(\${args[0]}${_T.dotPow}\${args[1]}\\right)`},exp:{1:"\\exp\\left(${args[0]}\\right)"},expm1:`\\left(e${_T.pow}{\${args[0]}}-1\\right)`,fix:{1:"\\mathrm{${name}}\\left(${args[0]}\\right)"},floor:{1:"\\left\\lfloor${args[0]}\\right\\rfloor"},fraction:{2:"\\frac{${args[0]}}{${args[1]}}"},gcd:"\\gcd\\left(${args}\\right)",hypot:"\\hypot\\left(${args}\\right)",log:{1:"\\ln\\left(${args[0]}\\right)",2:"\\log_{${args[1]}}\\left(${args[0]}\\right)"},log10:{1:"\\log_{10}\\left(${args[0]}\\right)"},log1p:{1:"\\ln\\left(${args[0]}+1\\right)",2:"\\log_{${args[1]}}\\left(${args[0]}+1\\right)"},log2:"\\log_{2}\\left(${args[0]}\\right)",mod:{2:`\\left(\${args[0]}${_T.mod}\${args[1]}\\right)`},multiply:{2:`\\left(\${args[0]}${_T.multiply}\${args[1]}\\right)`},norm:{1:"\\left\\|${args[0]}\\right\\|",2:void 0},nthRoot:{2:"\\sqrt[${args[1]}]{${args[0]}}"}
2592,nthRoots:{2:"\\{y : y^${args[1]} = {${args[0]}}\\}"},pow:{2:`\\left(\${args[0]}\\right)${_T.pow}{\${args[1]}}`},round:{1:"\\left\\lfloor${args[0]}\\right\\rceil",2:void 0},sign:{1:"\\mathrm{${name}}\\left(${args[0]}\\right)"},sqrt:{1:"\\sqrt{${args[0]}}"},square:{1:"\\left(${args[0]}\\right)^2"},subtract:{2:`\\left(\${args[0]}${_T.subtract}\${args[1]}\\right)`},unaryMinus:{1:`${_T.unaryMinus}\\left(\${args[0]}\\right)`},unaryPlus:{1:`${_T.unaryPlus}\\left(\${args[0]}\\right)`},bitAnd:{2:`\\left(\${args[0]}${_T.bitAnd}\${args[1]}\\right)`},bitNot:{1:_T.bitNot+"\\left(${args[0]}\\right)"},bitOr:{2:`\\left(\${args[0]}${_T.bitOr}\${args[1]}\\right)`},bitXor:{2:`\\left(\${args[0]}${_T.bitXor}\${args[1]}\\right)`},leftShift:{2:`\\left(\${args[0]}${_T.leftShift}\${args[1]}\\right)`},rightArithShift:{2:`\\left(\${args[0]}${_T.rightArithShift}\${args[1]}\\right)`},rightLogShift:{2:`\\left(\${args[0]}${_T.rightLogShift}\${args[1]}\\right)`},bellNumbers:{1:"\\mathrm{B}_{${args[0]}}"},catalan:{1:"\\mathrm{C}_{${args[0]}}"},stirlingS2:{2:"\\mathrm{S}\\left(${args}\\right)"},arg:{1:"\\arg\\left(${args[0]}\\right)"},conj:{1:"\\left(${args[0]}\\right)^*"},im:{1:"\\Im\\left\\lbrace${args[0]}\\right\\rbrace"},re:{1:"\\Re\\left\\lbrace${args[0]}\\right\\rbrace"},and:{2:`\\left(\${args[0]}${_T.and}\${args[1]}\\right)`},not:{1:_T.not+"\\left(${args[0]}\\right)"},or:{2:`\\left(\${args[0]}${_T.or}\${args[1]}\\right)`},xor:{2:`\\left(\${args[0]}${_T.xor}\${args[1]}\\right)`},cross:{2:"\\left(${args[0]}\\right)\\times\\left(${args[1]}\\right)"},ctranspose:{1:`\\left(\${args[0]}\\right)${_T.ctranspose}`},det:{1:"\\det\\left(${args[0]}\\right)"},dot:{2:"\\left(${args[0]}\\cdot${args[1]}\\right)"},expm:{1:"\\exp\\left(${args[0]}\\right)"},inv:{1:"\\left(${args[0]}\\right)^{-1}"},pinv:{1:"\\left(${args[0]}\\right)^{+}"},sqrtm:{1:`{\${args[0]}}${_T.pow}{\\frac{1}{2}}`},trace:{1:"\\mathrm{tr}\\left(${args[0]}\\right)"},transpose:{1:`\\left(\${args[0]}\\right)${_T.transpose}`},combinations:{2:"\\binom{${args[0]}}{${args[1]}}"},combinationsWithRep:{2:"\\left(\\!\\!{\\binom{${args[0]}}{${args[1]}}}\\!\\!\\right)"},factorial:{1:`\\left(\${args[0]}\\right)${_T.factorial}`},gamma:{1:"\\Gamma\\left(${args[0]}\\right)"},lgamma:{1:"\\ln\\Gamma\\left(${args[0]}\\right)"},equal:{2:`\\left(\${args[0]}${_T.equal}\${args[1]}\\right)`},larger:{2:`\\left(\${args[0]}${_T.larger}\${args[1]}\\right)`},largerEq:{2:`\\left(\${args[0]}${_T.largerEq}\${args[1]}\\right)`},smaller:{2:`\\left(\${args[0]}${_T.smaller}\${args[1]}\\right)`},smallerEq:{2:`\\left(\${args[0]}${_T.smallerEq}\${args[1]}\\right)`},unequal:{2:`\\left(\${args[0]}${_T.unequal}\${args[1]}\\right)`},erf:{1:"erf\\left(${args[0]}\\right)"},max:"\\max\\left(${args}\\right)",min:"\\min\\left(${args}\\right)",variance:"\\mathrm{Var}\\left(${args}\\right)",acos:{1:"\\cos^{-1}\\left(${args[0]}\\right)"},acosh:{1:"\\cosh^{-1}\\left(${args[0]}\\right)"},acot:{1:"\\cot^{-1}\\left(${args[0]}\\right)"},acoth:{1:"\\coth^{-1}\\left(${args[0]}\\right)"},acsc:{1:"\\csc^{-1}\\left(${args[0]}\\right)"},acsch:{1:"\\mathrm{csch}^{-1}\\left(${args[0]}\\right)"},asec:{1:"\\sec^{-1}\\left(${args[0]}\\right)"},asech:{1:"\\mathrm{sech}^{-1}\\left(${args[0]}\\right)"},asin:{1:"\\sin^{-1}\\left(${args[0]}\\right)"},asinh:{1:"\\sinh^{-1}\\left(${args[0]}\\right)"},atan:{1:"\\tan^{-1}\\left(${args[0]}\\right)"},atan2:{2:"\\mathrm{atan2}\\left(${args}\\right)"},atanh:{1:"\\tanh^{-1}\\left(${args[0]}\\right)"},cos:{1:"\\cos\\left(${args[0]}\\right)"},cosh:{1:"\\cosh\\left(${args[0]}\\right)"},cot:{1:"\\cot\\left(${args[0]}\\right)"},coth:{1:"\\coth\\left(${args[0]}\\right)"},csc:{1:"\\csc\\left(${args[0]}\\right)"},csch:{1:"\\mathrm{csch}\\left(${args[0]}\\right)"},sec:{1:"\\sec\\left(${args[0]}\\right)"},sech:{1:"\\mathrm{sech}\\left(${args[0]}\\right)"},sin:{1:"\\sin\\left(${args[0]}\\right)"},sinh:{1:"\\sinh\\left(${args[0]}\\right)"},tan:{1:"\\tan\\left(${args[0]}\\right)"},tanh:{1:"\\tanh\\left(${args[0]}\\right)"},to:{2:`\\left(\${args[0]}${_T.to}\${args[1]}\\right)`},numeric:function(e,t){return e.args[0].toTex()},number:{0:`0`,1:"\\left(${args[0]}\\right)",2:"\\left(\\left(${args[0]}\\right)${args[1]}\\right)"},string:{0:`\\mathtt{""}`,1:"\\mathrm{string}\\left(${args[0]}\\right)"},bignumber:{0:`0`,1:"\\left(${args[0]}\\right)"},bigint:{0:`0`,1:"\\left(${args[0]}\\right)"},complex:{0:`0`,1:"\\left(${args[0]}\\right)",2:`\\left(\\left(\${args[0]}\\right)+${gT.i}\\cdot\\left(\${args[1]}\\right)\\right)`},matrix:{0:`\\begin{bmatrix}\\end{bmatrix}`,1:"\\left(${args[0]}\\right)",2:"\\left(${args[0]}\\right)"},sparse:{0:`\\begin{bsparse}\\end{bsparse}`,1:"\\left(${args[0]}\\right)"},unit:{1:"\\left(${args[0]}\\right)",2:"\\left(\\left(${args[0]}\\right)${args[1]}\\right)"}},yT="\\mathrm{${name}}\\left(${args}\\right)",bT={deg:`^\\circ`}}
2592)),ST,CT,wT,g_e=e((()=>{Ln(),Hf(),Ql(),xT(),X(),ST=`ConstantNode`,CT=[`Node`,`isBounded`],wT=Y(ST,CT,e=>{var{Node:t,isBounded:n}=e;class r extends t{constructor(e){super(),this.value=e}get type(){return ST}get isConstantNode(){return!0}_compile(e,t){var n=this.value;return function(){return n}}forEach(e){}map(e){return this.clone()}clone(){return new r(this.value)}_toString(e){return If(this.value,e)}_toHTML(e){var t=this._toString(e);switch(Xl(this.value)){case`number`:case`bigint`:case`BigNumber`:case`Fraction`:return`<span class="math-number">`+t+`</span>`;case`string`:return`<span class="math-string">`+t+`</span>`;case`boolean`:return`<span class="math-boolean">`+t+`</span>`;case`null`:return`<span class="math-null-symbol">`+t+`</span>`;case`undefined`:return`<span class="math-undefined">`+t+`</span>`;default:return`<span class="math-symbol">`+t+`</span>`}}toJSON(){return{mathjs:ST,value:this.value}}static fromJSON(e){return new r(e.value)}_toTex(e){var t=this._toString(e);switch(Xl(this.value)){case`string`:return`\\mathtt{`+pT(t)+`}`;case`number`:case`BigNumber`:if(!n(this.value))return this.value.valueOf()<0?`-\\infty`:`\\infty`;var r=t.toLowerCase().indexOf(`e`);return r===-1?t:t.substring(0,r)+`\\cdot10^{`+t.substring(r+1)+`}`;case`bigint`:return t.toString();case`Fraction`:return this.value.toLatex();default:return t}}}return Rn(r,`name`,ST),r},{isClass:!0,isNode:!0})})),TT,ET,DT,__e=e((()=>{Ln(),Ql(),Rw(),Hf(),Tp(),xT(),rT(),X(),TT=`FunctionAssignmentNode`,ET=[`typed`,`Node`],DT=Y(TT,ET,e=>{var{typed:t,Node:n}=e;function r(e,t,n){var r=$w(e,t,n),i=$w(e.expr,t,n);return t===`all`||i!==null&&i<=r}class i extends n{constructor(e,t,n){if(super(),typeof e!=`string`)throw TypeError(`String expected for parameter "name"`);
2592if(!Array.isArray(t))throw TypeError(`Array containing strings or objects expected for parameter "params"`);if(!Wl(n))throw TypeError(`Node expected for parameter "expr"`);if(Lw.has(e))throw Error(`Illegal function name, "`+e+`" is a reserved keyword`);var r=new Set;for(var i of t){var a=typeof i==`string`?i:i.name;if(r.has(a))throw Error(`Duplicate parameter name "${a}"`);r.add(a)}this.name=e,this.params=t.map(function(e){return e&&e.name||e}),this.types=t.map(function(e){return e&&e.type||`any`}),this.expr=n}get type(){return TT}get isFunctionAssignmentNode(){return!0}_compile(e,n){var r=Object.create(n);up(this.params,function(e){r[e]=!0});var i=this.expr,a=i._compile(e,r),o=this.name,s=this.params,c=pp(this.types,`,`),l=o+`(`+pp(this.params,`, `)+`)`;return function(e,n,r){var u={};u[c]=function(){for(var t=Object.create(n),i=0;i<s.length;i++)t[s[i]]=arguments[i];return a(e,t,r)};var d=t(o,u);return d.syntax=l,d.expr=i.toString(),e.set(o,d),d}}forEach(e){e(this.expr,`expr`,this)}map(e){var t=this._ifNode(e(this.expr,`expr`,this));return new i(this.name,this.params.slice(0),t)}clone(){return new i(this.name,this.params.slice(0),this.expr)}_toString(e){var t=e&&e.parenthesis?e.parenthesis:`keep`,n=this.expr.toString(e);return r(this,t,e&&e.implicit)&&(n=`(`+n+`)`),this.name+`(`+this.params.join(`, `)+`) = `+n}toJSON(){var e=this.types;return{mathjs:TT,name:this.name,params:this.params.map(function(t,n){return{name:t,type:e[n]}}),expr:this.expr}}static fromJSON(e){return new i(e.name,e.params,e.expr)}_toHTML(e){for(var t=e&&e.parenthesis?e.parenthesis:`keep`,n=[],i=0;i<this.params.length;i++)n.push(`<span class="math-symbol math-parameter">`+Rf(this.params[i])+`</span>`);var a=this.expr.toHTML(e);return r(this,t,e&&e.implicit)&&(a=`<span class="math-parenthesis math-round-parenthesis">(</span>`+a+`<span class="math-parenthesis math-round-parenthesis">)</span>`),`<span class="math-function">`+Rf(this.name)+`</span><span class="math-parenthesis math-round-parenthesis">(</span>`+n.join(`<span class="math-separator">,</span>`)+`<span class="math-parenthesis math-round-parenthesis">)</span><span class="math-operator math-assignment-operator math-variable-assignment-operator math-binary-operator">=</span>`+a}_toTex(e){var t=e&&e.parenthesis?e.parenthesis:`keep`,n=this.expr.toTex(e);return r(this,t,e&&e.implicit)&&(n=`\\left(${n}\\right)`),`\\mathrm{`+this.name+`}\\left(`+this.params.map(mT).join(`,`)+`\\right)=`+n}}return Rn(i,`name`,TT),i},{isClass:!0,isNode:!0})})),OT,kT,AT,v_e=e((()=>{Ln(),Tp(),ml(),X(),Ql(),Hf(),OT=`IndexNode`,kT=[`Node`,`size`],AT=Y(OT,kT,e=>{var{Node:t,size:n}=e;class r extends t{constructor(e,t){if(super(),this.dimensions=e,this.dotNotation=t||!1,!Array.isArray(e)||!e.every(Wl))throw TypeError(`Array containing Nodes expected for parameter "dimensions"`);if(this.dotNotation&&!this.isObjectProperty())throw Error(`dotNotation only applicable for object properties`)}get type(){return OT}get isIndexNode(){return!0}_compile(e,t){var r=lp(this.dimensions,function(r,i){if(r.filter(e=>e.isSymbolNode&&e.name===`end`).length>0){var a=Object.create(t);a.end=!0;var o=r._compile(e,a);return function(e,t,r){if(!Dl(r)&&!Zl(r)&&!El(r))throw TypeError(`Cannot resolve "end": context must be a Matrix, Array, or string but is `+Xl(r));var a=n(r),s=Object.create(t);return s.end=a[i],o(e,s,r)}}else return r._compile(e,t)}),i=ul(e,`index`);return function(e,t,n){return i(...lp(r,function(r){return r(e,t,n)}))}}forEach(e){for(var t=0;t<this.dimensions.length;t++)e(this.dimensions[t],`dimensions[`+t+`]`,this)}map(e){for(var t=[],n=0;n<this.dimensions.length;n++)t[n]=this._ifNode(e(this.dimensions[n],`dimensions[`+n+`]`,this));return new r(t,this.dotNotation)}clone(){return new r(this.dimensions.slice(0),this.dotNotation)}isObjectProperty(){return this.dimensions.length===1&&zl(this.dimensions[0])&&typeof this.dimensions[0].value==`string`}getObjectProperty(){return this.isObjectProperty()?this.dimensions[0].value:null}_toString(e){return this.dotNotation?`.`+this.getObjectProperty():`[`+this.dimensions.join(`, `)+`]`}toJSON(){return{mathjs:OT,dimensions:this.dimensions,dotNotation:this.dotNotation}}static fromJSON(e){return new r(e.dimensions,e.dotNotation)}_toHTML(e){for(var t=[],n=0;n<this.dimensions.length;n++)t[n]=this.dimensions[n].toHTML();return this.dotNotation?`<span class="math-operator math-accessor-operator">.</span><span class="math-symbol math-property">`+Rf(this.getObjectProperty())+`</span>`:`<span class="math-parenthesis math-square-parenthesis">[</span>`+t.join(`<span class="math-separator">,</span>`)+`<span class="math-parenthesis math-square-parenthesis">]</span>`}_toTex(e){var t=this.dimensions.map(function(t){return t.toTex(e)});return this.dotNotation?`.`+this.getObjectProperty():`_{`+t.join(`,`)+`}`}}return Rn(r,`name`,OT),r},{isClass:!0,isNode:!0})})),jT,MT,NT,y_e=e((()=>{Ln(),ml(),X(),Ql(),ru(),Hf(),jT=`ObjectNode`,MT=[`Node`],NT=Y(jT,MT,e=>{var{Node:t}=e;class n extends t{constructor(e){if(super(),this.properties=e||{},e&&(typeof e!=`object`||!Object.keys(e).every(function(t){return Wl(e[t])})))throw TypeError(`Object containing Nodes expected`)}get type(){return jT}get isObjectNode(){return!0}_compile(e,t){var n={};for(var r in this.properties)if(nu(this.properties,r)){var i=Lf(r),a=JSON.parse(i);
2592n[a]=ul(this.properties,r)._compile(e,t)}return function(e,t,r){var i={};for(var a in n)nu(n,a)&&(i[a]=n[a](e,t,r));return i}}forEach(e){for(var t in this.properties)nu(this.properties,t)&&e(this.properties[t],`properties[`+Lf(t)+`]`,this)}map(e){var t={};for(var r in this.properties)nu(this.properties,r)&&(t[r]=this._ifNode(e(this.properties[r],`properties[`+Lf(r)+`]`,this)));return new n(t)}clone(){var e={};for(var t in this.properties)nu(this.properties,t)&&(e[t]=this.properties[t]);return new n(e)}_toString(e){var t=[];for(var n in this.properties)nu(this.properties,n)&&t.push(Lf(n)+`: `+this.properties[n].toString(e));return`{`+t.join(`, `)+`}`}toJSON(){return{mathjs:jT,properties:this.properties}}static fromJSON(e){return new n(e.properties)}_toHTML(e){var t=[];for(var n in this.properties)nu(this.properties,n)&&t.push(`<span class="math-symbol math-property">`+Rf(n)+`</span><span class="math-operator math-assignment-operator math-property-assignment-operator math-binary-operator">:</span>`+this.properties[n].toHTML(e));return`<span class="math-parenthesis math-curly-parenthesis">{</span>`+t.join(`<span class="math-separator">,</span>`)+`<span class="math-parenthesis math-curly-parenthesis">}</span>`}_toTex(e){var t=[];for(var n in this.properties)nu(this.properties,n)&&t.push(`\\mathbf{`+n+`:} & `+this.properties[n].toTex(e)+`\\\\`);return`\\left\\{\\begin{array}{ll}`+t.join(`
2593`)+`\\end{array}\\right\\}`}}return Rn(n,`name`,jT),n},{isClass:!0,isNode:!0})}));function PT(e,t){return new vl(e,new _l(t),new Set(Object.keys(t)))}var FT=e((()=>{yl()})),IT,LT,RT,b_e=e((()=>{Ln(),Ql(),Tp(),FT(),Hf(),ml(),rT(),xT(),X(),IT=`OperatorNode`,LT=[`Node`],RT=Y(IT,LT,e=>{var{Node:t}=e;function n(e,t){var r=e;if(t===`auto`)for(;ql(r);)r=r.content;return zl(r)?!0:Kl(r)?n(r.args[0],t):!1}function r(e,t,r,i,a){var o=$w(e,t,r),s=eT(e,t);if(t===`all`||i.length>2&&e.getIdentifier()!==`OperatorNode:add`&&e.getIdentifier()!==`OperatorNode:multiply`)return i.map(function(e){switch(e.getContent().type){case`ArrayNode`:case`ConstantNode`:case`SymbolNode`:case`ParenthesisNode`:return!1;default:return!0}});var c;switch(i.length){case 0:c=[];break;case 1:var l=$w(i[0],t,r,e);if(a&&l!==null){var u,d;if(t===`keep`?(u=i[0].getIdentifier(),d=e.getIdentifier()):(u=i[0].getContent().getIdentifier(),d=e.getContent().getIdentifier()),nT[o][d].latexLeftParens===!1){c=[!1];break}if(nT[l][u].latexParens===!1){c=[!1];break}}if(l===null){c=[!1];break}if(l<=o){c=[!0];break}c=[!1];break;case 2:var f,p=$w(i[0],t,r,e),m=tT(e,i[0],t);
vendor: 4,351 bytes, line 2593
2593f=p===null?!1:p===o&&s===`right`&&!m?!0:p<o;var h,g=$w(i[1],t,r,e),_=tT(e,i[1],t);if(h=g===null?!1:g===o&&s===`left`&&!_?!0:g<o,a){var v,y,b;t===`keep`?(v=e.getIdentifier(),y=e.args[0].getIdentifier(),b=e.args[1].getIdentifier()):(v=e.getContent().getIdentifier(),y=e.args[0].getContent().getIdentifier(),b=e.args[1].getContent().getIdentifier()),p!==null&&(nT[o][v].latexLeftParens===!1&&(f=!1),nT[p][y].latexParens===!1&&(f=!1)),g!==null&&(nT[o][v].latexRightParens===!1&&(h=!1),nT[g][b].latexParens===!1&&(h=!1))}c=[f,h];break;default:(e.getIdentifier()===`OperatorNode:add`||e.getIdentifier()===`OperatorNode:multiply`)&&(c=i.map(function(n){var i=$w(n,t,r,e),a=tT(e,n,t),c=eT(n,t);return i===null?!1:o===i&&s===c&&!a?!0:i<o}));break}if(i.length>=2&&e.getIdentifier()===`OperatorNode:multiply`&&e.implicit&&t!==`all`&&r===`hide`)for(var x=1;x<c.length;++x)n(i[x],t)&&!c[x-1]&&(t!==`keep`||!ql(i[x-1]))&&(c[x]=!0);return c}class i extends t{constructor(e,t,n,r,i){if(super(),typeof e!=`string`)throw TypeError(`string expected for parameter "op"`);if(typeof t!=`string`)throw TypeError(`string expected for parameter "fn"`);if(!Array.isArray(n)||!n.every(Wl))throw TypeError(`Array containing Nodes expected for parameter "args"`);this.implicit=r===!0,this.isPercentage=i===!0,this.op=e,this.fn=t,this.args=n||[]}get type(){return IT}get isOperatorNode(){return!0}_compile(e,t){if(typeof this.fn!=`string`||!pl(e,this.fn))throw e[this.fn]?Error(`No access to function "`+this.fn+`"`):Error(`Function `+this.fn+` missing in provided namespace "math"`);var n=ul(e,this.fn),r=lp(this.args,function(n){return n._compile(e,t)});if(typeof n==`function`&&n.rawArgs===!0){var i=this.args;return function(t,r,a){return n(i,e,PT(t,r))}}else if(r.length===1){var a=r[0];return function(e,t,r){return n(a(e,t,r))}}else if(r.length===2){var o=r[0],s=r[1];return function(e,t,r){return n(o(e,t,r),s(e,t,r))}}else return function(e,t,i){return n.apply(null,lp(r,function(n){return n(e,t,i)}))}}forEach(e){for(var t=0;t<this.args.length;t++)e(this.args[t],`args[`+t+`]`,this)}map(e){for(var t=[],n=0;n<this.args.length;n++)t[n]=this._ifNode(e(this.args[n],`args[`+n+`]`,this));return new i(this.op,this.fn,t,this.implicit,this.isPercentage)}clone(){return new i(this.op,this.fn,this.args.slice(0),this.implicit,this.isPercentage)}isUnary(){return this.args.length===1}isBinary(){return this.args.length===2}_toString(e){var t=e&&e.parenthesis?e.parenthesis:`keep`,n=e&&e.implicit?e.implicit:`hide`,i=this.args,a=r(this,t,n,i,!1);if(i.length===1){var o=eT(this,t),s=i[0].toString(e);a[0]&&(s=`(`+s+`)`);var c=/[a-zA-Z]+/.test(this.op);return o===`right`?this.op+(c?` `:``)+s:o===`left`?s+(c?` `:``)+this.op:s+this.op}else if(i.length===2){var l=i[0].toString(e),u=i[1].toString(e);return a[0]&&(l=`(`+l+`)`),a[1]&&(u=`(`+u+`)`),this.implicit&&this.getIdentifier()===`OperatorNode:multiply`&&n===`hide`?l+` `+u:l+` `+this.op+` `+u}else if(i.length>2&&(this.getIdentifier()===`OperatorNode:add`||this.getIdentifier()===`OperatorNode:multiply`)){var d=i.map(function(t,n){return t=t.toString(e),a[n]&&(t=`(`+t+`)`),t});return this.implicit&&this.getIdentifier()===`OperatorNode:multiply`&&n===`hide`?d.join(` `):d.join(` `+this.op+` `)}else return this.fn+`(`+this.args.join(`, `)+`)`}toJSON(){return{mathjs:IT,op:this.op,fn:this.fn,args:this.args,implicit:this.implicit,isPercentage:this.isPercentage}}static fromJSON(e){return new i(e.op,e.fn,e.args,e.implicit,e.isPercentage)}_toHTML(e){var t=e&&e.parenthesis?e.parenthesis:`keep`,n=e&&e.implicit?e.implicit:`hide`,i=this.args,a=r(this,t,n,i,!1);if(i.length===1){var o=eT(this,t),s=i[0].toHTML(e);return a[0]&&(s=`<span class="math-parenthesis math-round-parenthesis">(</span>`+s+`<span class="math-parenthesis math-round-parenthesis">)</span>`),o===`right`?`<span class="math-operator math-unary-operator math-lefthand-unary-operator">`+Rf(this.op)+`</span>`+s:s+`<span class="math-operator math-unary-operator math-righthand-unary-operator">`+Rf(this.op)+`</span>`}else if(i.length===2){var c=i[0].toHTML(e),l=i[1].toHTML(e);return a[0]&&(c=`<span class="math-parenthesis math-round-parenthesis">(</span>`+c+`<span class="math-parenthesis math-round-parenthesis">)</span>`),a[1]&&(l=`<span class="math-parenthesis math-round-parenthesis">(</span>`+l+`<span class="math-parenthesis math-round-parenthesis">)</span>
2593`),this.implicit&&this.getIdentifier()===`OperatorNode:multiply`&&n===`hide`?c+`<span class="math-operator math-binary-operator math-implicit-binary-operator"></span>`+l:c+`<span class="math-operator math-binary-operator math-explicit-binary-operator">`+Rf(this.op)+`</span>`+l}else{var u=i.map(function(t,n){return t=t.toHTML(e),a[n]&&(t=`<span class="math-parenthesis math-round-parenthesis">(</span>`+t+`<span class="math-parenthesis math-round-parenthesis">)</span>`),t});return i.length>2&&(this.getIdentifier()===`OperatorNode:add`||this.getIdentifier()===`OperatorNode:multiply`)?this.implicit&&this.getIdentifier()===`OperatorNode:multiply`&&n===`hide`?u.join(`<span class="math-operator math-binary-operator math-implicit-binary-operator"></span>`):u.join(`<span class="math-operator math-binary-operator math-explicit-binary-operator">`+Rf(this.op)+`</span>`):`<span class="math-function">`+Rf(this.fn)+`</span><span class="math-paranthesis math-round-parenthesis">(</span>`+u.join(`<span class="math-separator">,</span>`)+`<span class="math-paranthesis math-round-parenthesis">)</span>`}}_toTex(e){var t=e&&e.parenthesis?e.parenthesis:`keep`,n=e&&e.implicit?e.implicit:`hide`,i=this.args,a=r(this,t,n,i,!0),o=_T[this.fn];if(o=o===void 0?this.op:o,i.length===1){var s=eT(this,t),c=i[0].toTex(e);return a[0]&&(c=`\\left(${c}\\right)`),s===`right`?o+c:c+o}else if(i.length===2){var l=i[0],u=l.toTex(e);a[0]&&(u=`\\left(${u}\\right)`);var d=i[1].toTex(e);a[1]&&(d=`\\left(${d}\\right)`);var f=t===`keep`?l.getIdentifier():l.getContent().getIdentifier();switch(this.getIdentifier()){case`OperatorNode:divide`:return o+`{`+u+`}{`+d+`}`;case`OperatorNode:pow`:switch(u=`{`+u+`}`,d=`{`+d+`}`,f){case`ConditionalNode`:case`OperatorNode:divide`:u=`\\left(${u}\\right)`}break;case`OperatorNode:multiply`:if(this.implicit&&n===`hide`)return u+`~`+d}return u+o+d}else if(i.length>2&&(this.getIdentifier()===`OperatorNode:add`||this.getIdentifier()===`OperatorNode:multiply`)){var p=i.map(function(t,n){return t=t.toTex(e),a[n]&&(t=`\\left(${t}\\right)`),t});return this.getIdentifier()===`OperatorNode:multiply`&&this.implicit&&n===`hide`?p.join(`~`):p.join(o)}else return`\\mathrm{`+this.fn+`}\\left(`+i.map(function(t){return t.toTex(e)}).join(`,`)+`\\right)`}getIdentifier(){return this.type+`:`+this.fn}}return Rn(i,`name`,IT),i},{isClass:!0,isNode:!0})})),zT,BT,VT,x_e=e((()=>{Ln(),Ql(),X(),zT=`ParenthesisNode`,BT=[`Node`],VT=Y(zT,BT,e=>{var{Node:t}=e;class n extends t{constructor(e){if(super(),!Wl(e))throw TypeError(`Node expected for parameter "content"`);this.content=e}get type(){return zT}get isParenthesisNode(){return!0}_compile(e,t){return this.content._compile(e,t)}getContent(){return this.content.getContent()}forEach(e){e(this.content,`content`,this)}map(e){return new n(e(this.content,`content`,this))}clone(){return new n(this.content)}_toString(e){return!e||e&&!e.parenthesis||e&&e.parenthesis===`keep`?`(`+this.content.toString(e)+`)`:this.content.toString(e)}toJSON(){return{mathjs:zT,content:this.content}}static fromJSON(e){return new n(e.content)}_toHTML(e){return!e||e&&!e.parenthesis||e&&e.parenthesis===`keep`?`<span class="math-parenthesis math-round-parenthesis">(</span>`+this.content.toHTML(e)+`<span class="math-parenthesis math-round-parenthesis">)</span>`:this.content.toHTML(e)}_toTex(e){return!e||e&&!e.parenthesis||e&&e.parenthesis===`keep`?`\\left(${this.content.toTex(e)}\\right)`:this.content.toTex(e)}}return Rn(n,`name`,zT),n},{isClass:!0,isNode:!0})})),HT,UT,WT,S_e=e((()=>{Ln(),Ql(),X(),rT(),HT=`RangeNode`,UT=[`Node`],WT=Y(HT,UT,e=>{var{Node:t}=e;function n(e,t,n){var r=$w(e,t,n),i={},a=$w(e.start,t,n);if(i.start=a!==null&&a<=r||t===`all`,e.step){var o=$w(e.step,t,n);i.step=o!==null&&o<=r||t===`all`}var s=$w(e.end,t,n);return i.end=s!==null&&s<=r||t===`all`,i}class r extends t{constructor(e,t,n){if(super(),!Wl(e)||!Wl(t)||n&&!Wl(n))throw TypeError(`Node expected`);if(arguments.length>3)throw Error(`Too many arguments`);this.start=e,this.end=t,this.step=n||null}get type(){return HT}get isRangeNode(){return!0}needsEnd(){return this.filter(function(e){return Jl(e)&&e.name===`end`}).length>0}_compile(e,t){var n=e.range,r=this.start._compile(e,t),i=this.end._compile(e,t);if(this.step){var a=this.step._compile(e,t);return function(e,t,o){return n(r(e,t,o),i(e,t,o),a(e,t,o))}}else return function(e,t,a){return n(r(e,t,a),i(e,t,a))}}forEach(e){e(this.start,`start`,this),e(this.end,`end`,this),this.step&&e(this.step,`step`,this)}map(e){return new r(this._ifNode(e(this.start,`start`,this)),this._ifNode(e(this.end,`end`,this)),this.step&&this._ifNode(e(this.step,`step`,this)))}clone(){return new r(this.start,this.end,this.step&&this.step)}_toString(e){var t=e&&e.parenthesis?e.parenthesis:`keep`,r=n(this,t,e&&e.implicit),i,a=this.start.toString(e);if(r.start&&(a=`(`+a+`)`),i=a,this.step){var o=this.step.toString(e);r.step&&(o=`(`+o+`)`),i+=`:`+o}var s=this.end.toString(e);return r.end&&(s=`(`+s+`)`),i+=`:`+s,i}toJSON(){return{mathjs:HT,start:this.start,end:this.end,step:this.step}}static fromJSON(e){return new r(e.start,e.end,e.step)}_toHTML(e){var t=e&&e.parenthesis?e.parenthesis:`keep`,r=n(this,t,e&&e.implicit),i,a=this.start.toHTML(e);if(r.start&&(a=`<span class="math-parenthesis math-round-parenthesis">(</span>`+a+`<span class="math-parenthesis math-round-parenthesis">)</span>`),i=a,this.step){var o=this.step.toHTML(e);r.step&&(o=`<span class="math-parenthesis math-round-parenthesis">(</span>`+o+`<span class="math-parenthesis math-round-parenthesis">)</span>`),i+=`<span class="math-operator math-range-operator">:</span>`+o}var s=this.end.toHTML(e);return r.end&&(s=`<span class="math-parenthesis math-round-parenthesis">(</span>`+s+`<span class="math-parenthesis math-round-parenthesis">)</span>`),i+=`<span class="math-operator math-range-operator">:</span>`+s,i}_toTex(e){var t=e&&e.parenthesis?e.parenthesis:`keep`,r=n(this,t,e&&e.implicit),i=this.start.toTex(e);if(r.start&&(i=`\\left(${i}\\right)`),this.step){var a=this.step.toTex(e);r.step&&(a=`\\left(${a}\\right)`),i+=`:`+a}var o=this.end.toTex(e);return r.end&&(o=`\\left(${o}\\right)`),i+=`:`+o,i}}return Rn(r,`name`,HT),r},{isClass:!0,isNode:!0})})),GT,KT,qT,C_e=e((()=>{Ln(),rT(),Hf(),ml(),xT(),X(),GT=`RelationalNode`,KT=[`Node`],qT=Y(GT,KT,e=>{var{Node:t}=e,n={equal:`==`,unequal:`!=`,smaller:`<`,larger:`>`,smallerEq:`<=`,largerEq:`>=`};class r extends t{constructor(e,t){if(super(),!Array.isArray(e))throw TypeError(`Parameter conditionals must be an array`);if(!Array.isArray(t))throw TypeError(`Parameter params must be an array`);if(e.length!==t.length-1)throw TypeError(`Parameter params must contain exactly one more element than parameter conditionals`);this.conditionals=e,this.params=t}get type(){return GT}get isRelationalNode(){return!0}_compile(e,t){var n=this,r=this.params.map(n=>n._compile(e,t));return function(t,i,a){for(var o,s=r[0](t,i,a),c=0;c<n.conditionals.length;c++)if(o=s,s=r[c+1](t,i,a),!ul(e,n.conditionals[c])(o,s))return!1;return!0}}
2593forEach(e){this.params.forEach((t,n)=>e(t,`params[`+n+`]`,this),this)}map(e){return new r(this.conditionals.slice(),this.params.map((t,n)=>this._ifNode(e(t,`params[`+n+`]`,this)),this))}clone(){return new r(this.conditionals,this.params)}_toString(e){for(var t=e&&e.parenthesis?e.parenthesis:`keep`,r=$w(this,t,e&&e.implicit),i=this.params.map(function(n,i){var a=$w(n,t,e&&e.implicit);return t===`all`||a!==null&&a<=r?`(`+n.toString(e)+`)`:n.toString(e)}),a=i[0],o=0;o<this.conditionals.length;o++)a+=` `+n[this.conditionals[o]],a+=` `+i[o+1];return a}toJSON(){return{mathjs:GT,conditionals:this.conditionals,params:this.params}}static fromJSON(e){return new r(e.conditionals,e.params)}_toHTML(e){for(var t=e&&e.parenthesis?e.parenthesis:`keep`,r=$w(this,t,e&&e.implicit),i=this.params.map(function(n,i){var a=$w(n,t,e&&e.implicit);return t===`all`||a!==null&&a<=r?`<span class="math-parenthesis math-round-parenthesis">(</span>`+n.toHTML(e)+`<span class="math-parenthesis math-round-parenthesis">)</span>`:n.toHTML(e)}),a=i[0],o=0;o<this.conditionals.length;o++)a+=`<span class="math-operator math-binary-operator math-explicit-binary-operator">`+Rf(n[this.conditionals[o]])+`</span>`+i[o+1];return a}_toTex(e){for(var t=e&&e.parenthesis?e.parenthesis:`keep`,n=$w(this,t,e&&e.implicit),r=this.params.map(function(r,i){var a=$w(r,t,e&&e.implicit);return t===`all`||a!==null&&a<=n?`\\left(`+r.toTex(e)+`\right)`:r.toTex(e)}),i=r[0],a=0;a<this.conditionals.length;a++)i+=_T[this.conditionals[a]]+r[a+1];return i}}return Rn(r,`name`,GT),r},{isClass:!0,isNode:!0})})),JT,YT,XT,w_e=e((()=>{Hf(),ml(),X(),xT(),JT=`SymbolNode`,YT=[`math`,`?Unit`,`Node`],XT=Y(JT,YT,e=>{var{math:t,Unit:n,Node:r}=e;function i(e){return n?n.isValuelessUnit(e):!1}class a extends r{constructor(e){if(super(),typeof e!=`string`)throw TypeError(`String expected for parameter "name"`);this.name=e}get type(){return`SymbolNode`}get isSymbolNode(){return!0}_compile(e,t){var r=this.name;if(t[r]===!0)return function(e,t,n){return ul(t,r)};if(r in e)return function(t,n,i){return t.has(r)?t.get(r):ul(e,r)};var o=i(r);return function(e,t,i){return e.has(r)?e.get(r):o?new n(null,r):a.onUndefinedSymbol(r)}}forEach(e){}map(e){return this.clone()}static onUndefinedSymbol(e){throw Error(`Undefined symbol `+e)}clone(){return new a(this.name)}_toString(e){return this.name}_toHTML(e){var t=Rf(this.name);return t===`true`||t===`false`?`<span class="math-symbol math-boolean">`+t+`</span>`:t===`i`?`<span class="math-symbol math-imaginary-symbol">`+t+`</span>`:t===`Infinity`?`<span class="math-symbol math-infinity-symbol">`+t+`</span>`:t===`NaN`?`<span class="math-symbol math-nan-symbol">`+t+`</span>`:t===`null`?`<span class="math-symbol math-null-symbol">`+t+`</span>`:t===`undefined`?`<span class="math-symbol math-undefined-symbol">`+t+`</span>`:`<span class="math-symbol">`+t+`</span>`}toJSON(){return{mathjs:`SymbolNode`,name:this.name}}static fromJSON(e){return new a(e.name)}_toTex(e){var n=!1;t[this.name]===void 0&&i(this.name)&&(n=!0);var r=mT(this.name,n);return r[0]===`\\`?r:` `+r}}return a},{isClass:!0,isNode:!0})})),ZT,QT,$T,T_e=e((()=>{Ln(),Ql(),Hf(),ru(),ml(),FT(),X(),xT(),ZT=`FunctionNode`,QT=[`math`,`Node`,`SymbolNode`],$T=Y(ZT,QT,e=>{var t,{math:n,Node:r,SymbolNode:i}=e,a=e=>If(e,{truncate:78});function o(e,t,n){for(var r=``,i=/\$(?:\{([a-z_][a-z_0-9]*)(?:\[([0-9]+)\])?\}|\$)/gi,a=0,o;(o=i.exec(e))!==null;)if(r+=e.substring(a,o.index),a=o.index,o[0]===`$$`)r+=`$`,a++;else{a+=o[0].length;var s=t[o[1]];if(!s)throw ReferenceError(`Template: Property `+o[1]+` does not exist.`);if(o[2]===void 0)switch(typeof s){case`string`:r+=s;break;case`object`:if(Wl(s))r+=s.toTex(n);else if(Array.isArray(s))r+=s.map(function(e,t){if(Wl(e))return e.toTex(n);throw TypeError(`Template: `+o[1]+`[`+t+`] is not a Node.`)}).join(`,`);else throw TypeError(`Template: `+o[1]+` has to be a Node, String or array of Nodes`);break;default:throw TypeError(`Template: `+o[1]+` has to be a Node, String or array of Nodes`)}else if(Wl(s[o[2]]&&s[o[2]]))r+=s[o[2]].toTex(n);else throw TypeError(`Template: `+o[1]+`[`+o[2]+`] is not a Node.`)}
2593return r+=e.slice(a),r}class s extends r{constructor(e,t,n){if(super(),typeof e==`string`&&(e=new i(e)),!Wl(e))throw TypeError(`Node expected as parameter "fn"`);if(!Array.isArray(t)||!t.every(Wl))throw TypeError(`Array containing Nodes expected for parameter "args"`);var r=typeof n;if(!(r===`undefined`||r===`boolean`))throw TypeError(`optional flag, if specified, must be boolean`);this.fn=e,this.args=t||[],this.optional=!!n}get name(){return this.fn.name||``}get type(){return ZT}get isFunctionNode(){return!0}_compile(e,t){var n=this.args.map(n=>n._compile(e,t)),r=this.optional||Ll(this.fn)&&this.fn.optionalChaining;if(Jl(this.fn)){var i=this.fn.name;if(t[i]){var o=this.args;return function(t,s,c){var l=ul(s,i);if(!(r&&l===void 0)){if(typeof l!=`function`)throw TypeError(`Argument '${i}' was not a function; received: ${a(l)}`);if(l.rawArgs)return l(o,e,PT(t,s));var u=n.map(e=>e(t,s,c));return l.apply(l,u)}}}else{var c=i in e?ul(e,i):void 0,l=typeof c==`function`&&c.rawArgs===!0,u=t=>{var n;if(t.has(i))n=t.get(i);else if(i in e)n=ul(e,i);else if(r)n=void 0;else return s.onUndefinedFunction(i);if(typeof n==`function`||r&&n===void 0)return n;throw TypeError(`'${i}' is not a function; its value is:
2594  ${a(n)}`)};if(l){var d=this.args;return function(t,r,i){var a=u(t);return a.rawArgs===!0?a(d,e,PT(t,r)):a(...n.map(e=>e(t,r,i)))}}else switch(n.length){case 0:return function(e,t,n){var i=u(e);if(!(r&&i===void 0))return i()};case 1:return function(e,t,i){var a=u(e);if(!(r&&a===void 0)){var o=n[0];return a(o(e,t,i))}};case 2:return function(e,t,i){var a=u(e);if(!(r&&a===void 0)){var o=n[0],s=n[1];return a(o(e,t,i),s(e,t,i))}};default:return function(e,t,i){var a=u(e);if(!(r&&a===void 0))return a(...n.map(n=>n(e,t,i)))}}}}else if(Ll(this.fn)&&Ul(this.fn.index)&&this.fn.index.isObjectProperty()){var f=this.fn.object._compile(e,t),p=this.fn.index.getObjectProperty(),m=this.args;return function(t,i,a){var o=f(t,i,a);if(!(r&&(o==null||o[p]===void 0))){var s=Fse(o,p);if(s!=null&&s.rawArgs)return s(m,e,PT(t,i));var c=n.map(e=>e(t,i,a));return s.apply(o,c)}}}else{var h=this.fn.toString(),g=this.fn._compile(e,t),_=this.args;return function(t,i,o){var s=g(t,i,o);if(!(r&&s===void 0)){if(typeof s!=`function`)throw TypeError(`Expression '${h}' did not evaluate to a function; value is:
2595  ${a(s)}`);if(s.rawArgs)return s(_,e,PT(t,i));var c=n.map(e=>e(t,i,o));return s.apply(s,c)}}}}forEach(e){e(this.fn,`fn`,this);for(var t=0;t<this.args.length;t++)e(this.args[t],`args[`+t+`]`,this)}map(e){for(var t=this._ifNode(e(this.fn,`fn`,this)),n=[],r=0;r<this.args.length;r++)n[r]=this._ifNode(e(this.args[r],`args[`+r+`]`,this));return new s(t,n)}clone(){return new s(this.fn,this.args.slice(0))}toString(e){var t,n=this.fn.toString(e);return e&&typeof e.handler==`object`&&nu(e.handler,n)&&(t=e.handler[n](this,e)),t===void 0?super.toString(e):t}_toString(e){var t=this.args.map(function(t){return t.toString(e)});return(Vl(this.fn)?`(`+this.fn.toString(e)+`)`:this.fn.toString(e))+`(`+t.join(`, `)+`)`}toJSON(){return{mathjs:ZT,fn:this.fn,args:this.args}}_toHTML(e){var t=this.args.map(function(t){return t.toHTML(e)});return`<span class="math-function">`+Rf(this.fn)+`</span><span class="math-paranthesis math-round-parenthesis">(</span>`+t.join(`<span class="math-separator">,</span>`)+`<span class="math-paranthesis math-round-parenthesis">)</span>`}toTex(e){var t;return e&&typeof e.handler==`object`&&nu(e.handler,this.name)&&(t=e.handler[this.name](this,e)),t===void 0?super.toTex(e):t}_toTex(e){var t=this.args.map(function(t){return t.toTex(e)}),r;vT[this.name]&&(r=vT[this.name]),n[this.name]&&(typeof n[this.name].toTex==`function`||typeof n[this.name].toTex==`object`||typeof n[this.name].toTex==`string`)&&(r=n[this.name].toTex);var i;switch(typeof r){case`function`:i=r(this,e);break;case`string`:i=o(r,this,e);break;case`object`:switch(typeof r[t.length]){case`function`:i=r[t.length](this,e);break;case`string`:i=o(r[t.length],this,e);break}}return i===void 0?o(yT,this,e):i}getIdentifier(){return this.type+`:`+this.name}}return t=s,Rn(s,`name`,ZT),Rn(s,`onUndefinedFunction`,function(e){throw Error(`Undefined function `+e)}),Rn(s,`fromJSON`,function(e){return new t(e.fn,e.args)}),s},{isClass:!0,isNode:!0})})),eE,tE,nE,E_e=e((()=>{Bn(),X(),Ql(),Wp(),Pu(),ru(),eE=`parse`,tE=[`typed`,`numeric`,`config`,`AccessorNode`,`ArrayNode`,`AssignmentNode`,`BlockNode`,`ConditionalNode`,`ConstantNode`,`FunctionAssignmentNode`,`FunctionNode`,`IndexNode`,`ObjectNode`,`OperatorNode`,`ParenthesisNode`,`RangeNode`,`RelationalNode`,`SymbolNode`],nE=Y(eE,tE,e=>{var{typed:t,numeric:n,config:r,AccessorNode:i,ArrayNode:a,AssignmentNode:o,BlockNode:s,ConditionalNode:c,ConstantNode:l,FunctionAssignmentNode:u,FunctionNode:d,IndexNode:f,ObjectNode:p,OperatorNode:m,ParenthesisNode:h,RangeNode:g,RelationalNode:_,SymbolNode:v}=e,y=t(eE,{string:function(e){return L(e,{})},"Array | Matrix":function(e){return b(e,{})}
vendor: 4,794 bytes, lines 2595-2603
2595,"string, Object":function(e,t){return L(e,t.nodes===void 0?{}:t.nodes)},"Array | Matrix, Object":b});function b(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=t.nodes===void 0?{}:t.nodes;return Bp(e,function(e){if(typeof e!=`string`)throw TypeError(`String expected`);return L(e,n)})}var x={NULL:0,DELIMITER:1,NUMBER:2,SYMBOL:3,UNKNOWN:4},S={",":!0,"(":!0,")":!0,"[":!0,"]":!0,"{":!0,"}":!0,'"':!0,"'":!0,";":!0,"+":!0,"-":!0,"*":!0,".*":!0,"/":!0,"./":!0,"%":!0,"^":!0,".^":!0,"~":!0,"!":!0,"&":!0,"|":!0,"^|":!0,"=":!0,":":!0,"?":!0,"?.":!0,"??":!0,"==":!0,"!=":!0,"<":!0,">":!0,"<=":!0,">=":!0,"<<":!0,">>":!0,">>>":!0},C={mod:!0,to:!0,in:!0,and:!0,xor:!0,or:!0,not:!0},w={true:!0,false:!1,null:null,undefined:void 0},T=[`NaN`,`Infinity`],E={'"':`"`,"'":`'`,"\\":`\\`,"/":`/`,b:`\b`,f:`\f`,n:`
2596`,r:`\r`,t:`	`};function D(){return{extraNodes:{},expression:``,comment:``,index:0,token:``,tokenType:x.NULL,nestingLevel:0,conditionalLevel:null}}function O(e,t){return e.expression.substr(e.index,t)}function k(e){return O(e,1)}function A(e){e.index++}function j(e){return e.expression.charAt(e.index-1)}function M(e){return e.expression.charAt(e.index+1)}function N(e){for(e.tokenType=x.NULL,e.token=``,e.comment=``;;){if(k(e)===`#`)for(;k(e)!==`
2597`&&k(e)!==``;)e.comment+=k(e),A(e);if(y.isWhitespace(k(e),e.nestingLevel))A(e);else break}if(k(e)===``){e.tokenType=x.DELIMITER;return}if(k(e)===`
2598`&&!e.nestingLevel){e.tokenType=x.DELIMITER,e.token=k(e),A(e);return}var t=k(e),n=O(e,2),r=O(e,3);if(r.length===3&&S[r]){e.tokenType=x.DELIMITER,e.token=r,A(e),A(e),A(e);return}if(n.length===2&&S[n]&&(n!==`?.`||!y.isDigit(e.expression.charAt(e.index+2)))){e.tokenType=x.DELIMITER,e.token=n,A(e),A(e);return}if(S[t]){e.tokenType=x.DELIMITER,e.token=t,A(e);return}if(y.isDigitDot(t)){e.tokenType=x.NUMBER;var i=O(e,2);if(i===`0b`||i===`0o`||i===`0x`){for(e.token+=k(e),A(e),e.token+=k(e),A(e);y.isAlpha(k(e),j(e),M(e))||y.isDigit(k(e));)e.token+=k(e),A(e);if(k(e)===`.`)for(e.token+=`.`,A(e);y.isAlpha(k(e),j(e),M(e))||y.isDigit(k(e));)e.token+=k(e),A(e);else if(k(e)===`i`)for(e.token+=`i`,A(e);y.isDigit(k(e));)e.token+=k(e),A(e);return}if(k(e)===`.`){if(e.token+=k(e),A(e),!y.isDigit(k(e))){e.tokenType=x.DELIMITER;return}}else{for(;y.isDigit(k(e));)e.token+=k(e),A(e);y.isDecimalMark(k(e),M(e))&&(e.token+=k(e),A(e))}for(;y.isDigit(k(e));)e.token+=k(e),A(e);if(k(e)===`E`||k(e)===`e`){if(y.isDigit(M(e))||M(e)===`-`||M(e)===`+`){if(e.token+=k(e),A(e),(k(e)===`+`||k(e)===`-`)&&(e.token+=k(e),A(e)),!y.isDigit(k(e)))throw ke(e,`Digit expected, got "`+k(e)+`"`);for(;y.isDigit(k(e));)e.token+=k(e),A(e);if(y.isDecimalMark(k(e),M(e)))throw ke(e,`Digit expected, got "`+k(e)+`"`)}else if(y.isDecimalMark(M(e),e.expression.charAt(e.index+2)))throw A(e),ke(e,`Digit expected, got "`+k(e)+`"`)}return}if(y.isAlpha(k(e),j(e),M(e))){for(;y.isAlpha(k(e),j(e),M(e))||y.isDigit(k(e));)e.token+=k(e),A(e);nu(C,e.token)?e.tokenType=x.DELIMITER:e.tokenType=x.SYMBOL;return}for(e.tokenType=x.UNKNOWN;k(e)!==``;)e.token+=k(e),A(e);throw ke(e,`Syntax error in part "`+e.token+`"`)}function P(e){do N(e);while(e.token===`
2599`)}function F(e){e.nestingLevel++}function I(e){e.nestingLevel--}y.isAlpha=function(e,t,n){return y.isValidLatinOrGreek(e)||y.isValidMathSymbol(e,n)||y.isValidMathSymbol(t,e)},y.isValidLatinOrGreek=function(e){return/^[a-zA-Z_$\u00C0-\u02AF\u0370-\u03FF\u2100-\u214F]$/.test(e)},y.isValidMathSymbol=function(e,t){return/^[\uD835]$/.test(e)&&/^[\uDC00-\uDFFF]$/.test(t)&&/^[^\uDC55\uDC9D\uDCA0\uDCA1\uDCA3\uDCA4\uDCA7\uDCA8\uDCAD\uDCBA\uDCBC\uDCC4\uDD06\uDD0B\uDD0C\uDD15\uDD1D\uDD3A\uDD3F\uDD45\uDD47-\uDD49\uDD51\uDEA6\uDEA7\uDFCC\uDFCD]$/.test(t)},y.isWhitespace=function(e,t){return e===` `||e===`	`||e===`\xA0`||e===`
2600`&&t>0},y.isDecimalMark=function(e,t){return e===`.`&&t!==`/`&&t!==`*`&&t!==`^`},y.isDigitDot=function(e){return e>=`0`&&e<=`9`||e===`.`},y.isDigit=function(e){return e>=`0`&&e<=`9`};function L(e,t){var n=D();zn(n,{expression:e,extraNodes:t}),N(n);var r=ee(n);if(n.token!==``)throw n.tokenType===x.DELIMITER?Ae(n,`Unexpected operator `+n.token):ke(n,`Unexpected part "`+n.token+`"`);return r}function ee(e){var t,n=[],r;for(e.token!==``&&e.token!==`
2601`&&e.token!==`;`&&(t=R(e),e.comment&&(t.comment=e.comment));e.token===`
2602`||e.token===`;`;)n.length===0&&t&&(r=e.token!==`;`,n.push({node:t,visible:r})),N(e),e.token!==`
2603`&&e.token!==`;`&&e.token!==``&&(t=R(e),e.comment&&(t.comment=e.comment),r=e.token!==`;`,n.push({node:t,visible:r}));return n.length>0?new s(n):(t||(t=new l(void 0),e.comment&&(t.comment=e.comment)),t)}function R(e){var t,n,r,i,a=te(e);if(e.token===`=`){if(Jl(a))return t=a.name,P(e),r=R(e),new o(new v(t),r);if(Ll(a)){if(a.optionalChaining)throw ke(e,`Cannot assign to optional chain`);return P(e),r=R(e),new o(a.object,a.index,r)}
2603else if(Hl(a)&&Jl(a.fn)&&(i=!0,n=[],t=a.name,a.args.forEach(function(e,t){Jl(e)?n[t]=e.name:i=!1}),i))return P(e),r=R(e),new u(t,n,r);throw ke(e,`Invalid left hand side of assignment operator =`)}return a}function te(e){for(var t=z(e);e.token===`?`;){var n=e.conditionalLevel;e.conditionalLevel=e.nestingLevel,P(e);var r=t,i=R(e);if(e.token!==`:`)throw ke(e,`False part of conditional expression expected`);e.conditionalLevel=null,P(e),t=new c(r,i,R(e)),e.conditionalLevel=n}return t}function z(e){for(var t=ne(e);e.token===`or`;)P(e),t=new m(`or`,`or`,[t,ne(e)]);return t}function ne(e){for(var t=B(e);e.token===`xor`;)P(e),t=new m(`xor`,`xor`,[t,B(e)]);return t}function B(e){for(var t=V(e);e.token===`and`;)P(e),t=new m(`and`,`and`,[t,V(e)]);return t}function V(e){for(var t=H(e);e.token===`|`;)P(e),t=new m(`|`,`bitOr`,[t,H(e)]);return t}function H(e){for(var t=re(e);e.token===`^|`;)P(e),t=new m(`^|`,`bitXor`,[t,re(e)]);return t}function re(e){for(var t=ie(e);e.token===`&`;)P(e),t=new m(`&`,`bitAnd`,[t,ie(e)]);return t}function ie(e){for(var t=[ae(e)],n=[],r={"==":`equal`,"!=":`unequal`,"<":`smaller`,">":`larger`,"<=":`smallerEq`,">=":`largerEq`};nu(r,e.token);){var i={name:e.token,fn:r[e.token]};n.push(i),P(e),t.push(ae(e))}return t.length===1?t[0]:t.length===2?new m(n[0].name,n[0].fn,t):new _(n.map(e=>e.fn),t)}function ae(e){for(var t=oe(e),n,r,i,a={"<<":`leftShift`,">>":`rightArithShift`,">>>":`rightLogShift`};nu(a,e.token);)n=e.token,r=a[n],P(e),i=[t,oe(e)],t=new m(n,r,i);return t}function oe(e){for(var t=se(e),n,r,i,a={to:`to`,in:`to`};nu(a,e.token);)n=e.token,r=a[n],P(e),n===`in`&&`])},;`.includes(e.token)?t=new m(`*`,`multiply`,[t,new v(`in`)],!0):(i=[t,se(e)],t=new m(n,r,i));return t}function se(e){var t,n=[];if(e.token===`:`){if(e.conditionalLevel===e.nestingLevel)throw ke(e,`The true-expression of a conditional operator may not be empty`);t=new l(1)}else t=ce(e);if(e.token===`:`&&e.conditionalLevel!==e.nestingLevel){for(n.push(t);e.token===`:`&&n.length<3;)P(e),e.token===`)`||e.token===`]`||e.token===`,`||e.token===``?n.push(new v(`end`)):n.push(ce(e));t=n.length===3?new g(n[0],n[2],n[1]):new g(n[0],n[1])}return t}function ce(e){for(var t=le(e),n,r,i,a={"+":`add`,"-":`subtract`};nu(a,e.token);){n=e.token,r=a[n],P(e);var o=le(e);i=o.isPercentage?[t,new m(`*`,`multiply`,[t,o])]:[t,o],t=new m(n,r,i)}return t}function le(e){for(var t=ue(e),n=t,r,i,a={"*":`multiply`,".*":`dotMultiply`,"/":`divide`,"./":`dotDivide`,"%":`mod`,mod:`mod`};nu(a,e.token);)r=e.token,i=a[r],P(e),n=ue(e),t=new m(r,i,[t,n]);return t}function ue(e){for(var t=de(e),n=t;e.tokenType===x.SYMBOL||e.token===`in`&&zl(t)||e.token===`in`&&Kl(t)&&t.fn===`unaryMinus`&&zl(t.args[0])||e.tokenType===x.NUMBER&&!zl(n)&&(!Kl(n)||n.op===`!`)||e.token===`(`;)n=de(e),t=new m(`*`,`multiply`,[t,n],!0);return t}function de(e){for(var t=fe(e),n=t,r=[];e.token===`/`&&Bl(n);)if(r.push(zn({},e)),P(e),e.tokenType===x.NUMBER)if(r.push(zn({},e)),P(e),e.tokenType===x.SYMBOL||e.token===`(`||e.token===`in`)zn(e,r.pop()),r.pop(),n=fe(e),t=new m(`/`,`divide`,[t,n]);else{r.pop(),zn(e,r.pop());break}else{zn(e,r.pop());break}return t}function fe(e){var t=pe(e);if(e.token===`%`){var n=zn({},e);P(e);try{pe(e),zn(e,n)}catch{t=new m(`/`,`divide`,[t,new l(100)],!1,!0)}}return t}function pe(e){var t,n,r,i={"-":`unaryMinus`,"+":`unaryPlus`,"~":`bitNot`,not:`not`};return nu(i,e.token)?(r=i[e.token],t=e.token,P(e),n=[pe(e)],new m(t,r,n)):me(e)}function me(e){var t=he(e),n,r,i;return(e.token===`^`||e.token===`.^`)&&(n=e.token,r=n===`^`?`pow`:`dotPow`,P(e),i=[t,pe(e)],t=new m(n,r,i)),t}function he(e){for(var t=ge(e);e.token===`??`;)P(e),t=new m(`??`,`nullish`,[t,ge(e)]);return t}function ge(e){for(var t=_e(e),n,r,i,a={"!":`factorial`,"'":`ctranspose`};nu(a,e.token);)n=e.token,r=a[n],N(e),i=[t],t=new m(n,r,i),t=ye(e,t);return t}function _e(e){var t=[];if(e.tokenType===x.SYMBOL&&nu(e.extraNodes,e.token)){var n=e.extraNodes[e.token];if(N(e),e.token===`(`){if(t=[],F(e),N(e),e.token!==`)`)for(t.push(R(e));e.token===`,`;)N(e),t.push(R(e));if(e.token!==`)`)throw ke(e,`Parenthesis ) expected`);I(e),N(e)}return new n(t)}return ve(e)}function ve(e){var t,r;return e.tokenType===x.SYMBOL||e.tokenType===x.DELIMITER&&e.token in C?(r=e.token,N(e),t=nu(w,r)?new l(w[r]):T.includes(r)?new l(n(r,`number`)):new v(r),t=ye(e,t),t):be(e)}function ye(e,t,n){for(var r;;){var a=!1;e.token===`?.`&&(a=!0,N(e));var o=(e.token===`(`||e.token===`[`||e.token===`.`)&&(!n||n.includes(e.token));if(!(a||o))break;if(r=[],e.token===`(`)if(a||Jl(t)||Ll(t)){if(F(e),N(e),e.token!==`)`)for(r.push(R(e));e.token===`,`;)N(e),r.push(R(e));if(e.token!==`)`)throw ke(e,`Parenthesis ) expected`);I(e),N(e),t=new d(t,r,a)}else return t;else if(e.token===`[`){if(F(e),N(e),e.token!==`]`)for(r.push(R(e));e.token===`,`;)N(e),r.push(R(e));if(e.token!==`]`)throw ke(e,`Parenthesis ] expected`);I(e),N(e),t=new i(t,new f(r),a)}else{if(a||N(e),!(e.tokenType===x.SYMBOL||e.tokenType===x.DELIMITER&&e.token in C)){var s=`Property name expected after `;throw s+=a?`optional chain`:`dot`,ke(e,s)}r.push(new l(e.token)),N(e),t=new i(t,new f(r,!0),a)}}return t}function be(e){var t,n;return e.token===`"`||e.token===`'`?(n=xe(e,e.token),t=new l(n),t=ye(e,t),t):Se(e)}function xe(e,t){for(var n=``;k(e)!==``&&k(e)!==t;)if(k(e)===`\\`){A(e);var r=k(e),i=E[r];if(i!==void 0)n+=i,e.index+=1;else if(r===`u`){var a=e.expression.slice(e.index+1,e.index+5);if(/^[0-9A-Fa-f]{4}$/.test(a))n+=String.fromCharCode(parseInt(a,16)),e.index+=5;else throw ke(e,`Invalid unicode character \\u${a}`)}else throw ke(e,`Bad escape character \\${r}`)}else n+=k(e),A(e);if(N(e),e.token!==t)throw ke(e,`End of string ${t} expected`);return N(e),n}function Se(e){var t,n,r,i;if(e.token===`[`){if(F(e),N(e),e.token!==`]`){var o=Ce(e);if(e.token===`;`){for(r=1,n=[o];e.token===`;`;)N(e),e.token!==`]`&&(n[r]=Ce(e),r++);if(e.token!==`]`)throw ke(e,`End of matrix ] expected`);I(e),N(e),i=n[0].items.length;for(var s=1;s<r;s++)if(n[s].items.length!==i)throw Ae(e,`Column dimensions mismatch (`+n[s].items.length+` !== `+i+`)`);t=new a(n)}else{if(e.token!==`]`)throw ke(e,`End of matrix ] expected`);I(e),N(e),t=o}}else I(e),N(e),t=new a([]);return ye(e,t)}return we(e)}function Ce(e){for(var t=[R(e)],n=1;e.token===`,`;)N(e),e.token!==`]`&&e.token!==`;`&&(t[n]=R(e),n++);return new a(t)}function we(e){if(e.token===`{`){F(e);var t,n={};do if(N(e),e.token!==`}`){if(e.token===`"`||e.token===`'`)t=xe(e,e.token);else if(e.tokenType===x.SYMBOL||e.tokenType===x.DELIMITER&&e.token in C)t=e.token,N(e);else throw ke(e,`Symbol or string expected as object key`);if(e.token!==`:`)throw ke(e,`Colon : expected after object key`);N(e),n[t]=R(e)}while(e.token===`,`);if(e.token!==`}`)throw ke(e,`Comma , or bracket } expected after object value`);I(e),N(e);var r=new p(n);return r=ye(e,r),r}return Te(e)}function Te(e){var t;if(e.tokenType===x.NUMBER){t=e.token,N(e);var i=uu(t,r);return new l(n(t,i))}return Ee(e)}function Ee(e){var t;if(e.token===`(`){if(F(e),N(e),t=R(e),e.token!==`)`)throw ke(e,`Parenthesis ) expected`);return I(e),N(e),t=new h(t),t=ye(e,t),t}return De(e)}function De(e){throw e.token===``?ke(e,`Unexpected end of expression`):ke(e,`Value expected`)}function Oe(e){return e.index-e.token.length+1}function ke(e,t){var n=Oe(e),r=SyntaxError(t+` (char `+n+`)`);return r.char=n,r}function Ae(e,t){var n=Oe(e),r=SyntaxError(t+` (char `+n+`)`);return r.char=n,r}return t.addConversion({from:`string`,to:`Node`,convert:y}),y})})),rE,iE,aE,D_e=e((()=>{Wp(),X(),rE=`compile`,iE=[`typed`,`parse`],aE=Y(rE,iE,e=>{var{typed:t,parse:n}=e;return t(rE,{string:function(e){return n(e).compile()},"Array | Matrix":function(e){return Bp(e,function(e){return n(e).compile()})}})})})),oE,sE,cE,O_e=e((()=>{Wp(),X(),yl(),oE=`evaluate`,sE=[`typed`,`parse`],cE=Y(oE,sE,e=>{var{typed:t,parse:n}=e;return t(oE,{string:function(e){var t=hl();return n(e).compile().evaluate(t)},"string, Map | Object":function(e,t){return n(e).compile().evaluate(t)},"Array | Matrix":function(e){var t=hl();return Bp(e,function(e){return n(e).compile().evaluate(t)})},"Array | Matrix, Map | Object":function(e,t){return Bp(e,function(e){return n(e).compile().evaluate(t)})}})})}));function k_e(e){return typeof e==`function`&&typeof e.syntax==`string`&&typeof e.expr==`string`}var lE,uE,dE,A_e=e((()=>{X(),Ql(),yl(),lE=`Parser`,uE=[`evaluate`,`parse`],dE=Y(lE,uE,e=>{var{evaluate:t,parse:n}=e;function r(){if(!(this instanceof r))throw SyntaxError(`Constructor must be called with the new operator`);Object.defineProperty(this,"scope",{value:hl(),writable:!1})}r.prototype.type=`Parser`,r.prototype.isParser=!0,r.prototype.evaluate=function(e){return t(e,this.scope)},r.prototype.get=function(e){if(this.scope.has(e))return this.scope.get(e)},r.prototype.getAll=function(){return zse(this.scope)},r.prototype.getAllAsMap=function(){return this.scope};function i(e){if(e.length===0)return!1;for(var t=0;t<e.length;t++){var r=e.charAt(t-1),i=e.charAt(t),a=e.charAt(t+1);if(!(n.isAlpha(i,r,a)||t>0&&n.isDigit(i)))return!1}return!0}return r.prototype.set=function(e,t){if(!i(e))throw Error(`Invalid variable name: '${e}'. Variable names must follow the specified rules.`);return this.scope.set(e,t),t},r.prototype.remove=function(e){this.scope.delete(e)},r.prototype.clear=function(){this.scope.clear()},r.prototype.toJSON=function(){var e={mathjs:`Parser`,variables:{},functions:{}};
2603for(var[t,n]of this.scope)if(Pl(n)){if(!k_e(n))throw Error(`Cannot serialize external function ${t}`);e.functions[t]=`${n.syntax} = ${n.expr}`}else e.variables[t]=n;return e},r.fromJSON=function(e){var t=new r;return Object.entries(e.variables).forEach(e=>{var[n,r]=e;return t.set(n,r)}),Object.entries(e.functions).forEach(e=>{var[n,r]=e;return t.evaluate(r)}),t},r},{isClass:!0})})),fE,pE,mE,j_e=e((()=>{X(),fE=`parser`,pE=[`typed`,`Parser`],mE=Y(fE,pE,e=>{var{typed:t,Parser:n}=e;return t(fE,{"":function(){return new n}})})})),hE,gE,_E,M_e=e((()=>{ru(),X(),hE=`lup`,gE=[`typed`,`matrix`,`abs`,`addScalar`,`divideScalar`,`multiplyScalar`,`subtractScalar`,`larger`,`equalScalar`,`unaryMinus`,`DenseMatrix`,`SparseMatrix`,`Spa`],_E=Y(hE,gE,e=>{var{typed:t,matrix:n,abs:r,addScalar:i,divideScalar:a,multiplyScalar:o,subtractScalar:s,larger:c,equalScalar:l,unaryMinus:u,DenseMatrix:d,SparseMatrix:f,Spa:p}=e;return t(hE,{DenseMatrix:function(e){return m(e)},SparseMatrix:function(e){return h(e)},Array:function(e){var t=m(n(e));return{L:t.L.valueOf(),U:t.U.valueOf(),p:t.p}}});function m(e){var t=e._size[0],n=e._size[1],u=Math.min(t,n),f=$l(e._data),p=[],m=[t,u],h=[],g=[u,n],_,v,y,b=[];for(_=0;_<t;_++)b[_]=_;for(v=0;v<n;v++){if(v>0)for(_=0;_<t;_++){var x=Math.min(_,v),S=0;for(y=0;y<x;y++)S=i(S,o(f[_][y],f[y][v]));f[_][v]=s(f[_][v],S)}var C=v,w=0,T=0;for(_=v;_<t;_++){var E=f[_][v],D=r(E);c(D,w)&&(C=_,w=D,T=E)}if(v!==C&&(b[v]=[b[C],b[C]=b[v]][0],d._swapRows(v,C,f)),v<t)for(_=v+1;_<t;_++){var O=f[_][v];l(O,0)||(f[_][v]=a(f[_][v],T))}}for(v=0;v<n;v++)for(_=0;_<t;_++){if(v===0&&(_<n&&(h[_]=[]),p[_]=[]),_<v){_<n&&(h[_][v]=f[_][v]),v<t&&(p[_][v]=0);continue}if(_===v){_<n&&(h[_][v]=f[_][v]),v<t&&(p[_][v]=1);continue}_<n&&(h[_][v]=0),v<t&&(p[_][v]=f[_][v])}var k=new d({data:p,size:m}),A=new d({data:h,size:g}),j=[];for(_=0,u=b.length;_<u;_++)j[b[_]]=_;return{L:k,U:A,p:j,toString:function(){return`L: `+this.L.toString()+`
2604U: `+this.U.toString()+`
2605P: `+this.p}}}function h(e){var t=e._size[0],n=e._size[1],i=Math.min(t,n),s=e._values,d=e._index,m=e._ptr,h=[],g=[],_=[],v=[t,i],y=[],b=[],x=[],S=[i,n],C,w,T,E=[],D=[];for(C=0;C<t;C++)E[C]=C,D[C]=C;var O=function(e,t){var n=D[e],r=D[t];E[n]=t,E[r]=e,D[e]=r,D[t]=n},k=function(){var e=new p;w<t&&(_.push(h.length),h.push(1),g.push(w)),x.push(y.length);var n=m[w],i=m[w+1];for(T=n;T<i;T++)C=d[T],e.set(E[C],s[T]);w>0&&e.forEach(0,w-1,function(t,n){f._forEachRow(t,h,g,_,function(r,i){r>t&&e.accumulate(r,u(o(i,n)))})});var D=w,k=e.get(w),A=r(k);e.forEach(w+1,t-1,function(e,t){var n=r(t);c(n,A)&&(D=e,A=n,k=t)}),w!==D&&(f._swapRows(w,D,v[1],h,g,_),f._swapRows(w,D,S[1],y,b,x),e.swap(w,D),O(w,D)),e.forEach(0,t-1,function(e,t){e<=w?(y.push(t),b.push(e)):(t=a(t,k),l(t,0)||(h.push(t),g.push(e)))})};for(w=0;w<n;w++)k();return x.push(y.length),_.push(h.length),{L:new f({values:h,index:g,ptr:_,size:v}),U:new f({values:y,index:b,ptr:x,size:S}),p:E,toString:function(){return`L: `+this.L.toString()+`
2606U: `+this.U.toString()+`
2607P: `+this.p}}}})})),vE,yE,bE,N_e=e((()=>{Bn(),X(),vE=`qr`,yE=[`typed`,`matrix`,`zeros`,`identity`,`isZero`,`equal`,`sign`,`sqrt`,`conj`,`unaryMinus`,`addScalar`,`divideScalar`,`multiplyScalar`,`subtractScalar`,`complex`],bE=Y(vE,yE,e=>{var{typed:t,matrix:n,zeros:r,identity:i,isZero:a,equal:o,sign:s,sqrt:c,conj:l,unaryMinus:u,addScalar:d,divideScalar:f,multiplyScalar:p,subtractScalar:m,complex:h}=e;return zn(t(vE,{DenseMatrix:function(e){return _(e)},SparseMatrix:function(e){return v(e)},Array:function(e){var t=_(n(e));return{Q:t.Q.valueOf(),R:t.R.valueOf()}}}),{_denseQRimpl:g});function g(e){var t=e._size[0],n=e._size[1],h=i([t],`dense`),g=h._data,_=e.clone(),v=_._data,y,b,x,S=r([t],``);for(x=0;x<Math.min(n,t);++x){var C=v[x][x],w=u(o(C,0)?1:s(C)),T=l(w),E=0;for(y=x;y<t;y++)E=d(E,p(v[y][x],l(v[y][x])));var D=p(w,c(E));if(!a(D)){var O=m(C,D);for(S[x]=1,y=x+1;y<t;y++)S[y]=f(v[y][x],O);var k=u(l(f(O,D))),A=void 0;for(b=x;b<n;b++){for(A=0,y=x;y<t;y++)A=d(A,p(l(S[y]),v[y][b]));for(A=p(A,k),y=x;y<t;y++)v[y][b]=p(m(v[y][b],p(S[y],A)),T)}for(y=0;y<t;y++){for(A=0,b=x;b<t;b++)A=d(A,p(g[y][b],S[b]));for(A=p(A,k),b=x;b<t;++b)g[y][b]=f(m(g[y][b],p(A,l(S[b]))),T)}}}return{Q:h,R:_,toString:function(){return`Q: `+this.Q.toString()+`
2608R: `+this.R.toString()}}}function _(e){var t=g(e),n=t.R._data;if(e._data.length>0)for(var r=n[0][0].type===`Complex`?h(0):0,i=0;i<n.length;++i)for(var a=0;a<i&&a<(n[0]||[]).length;++a)n[i][a]=r;return t}function v(e){throw Error(`qr not implemented for sparse matrices yet`)}})}));function P_e(e,t,n,r){for(var i=e._values,a=e._index,o=e._ptr,s=e._size,c=e._datatype,l=s[0],u=s[1],d=r&&e._values?[]:null,f=[],p=[],m=0,h=0;h<u;h++){p[h]=m;for(var g=n?n[h]:h,_=o[g],v=o[g+1],y=_;y<v;y++)f[m]=t?t[a[y]]:a[y],d&&(d[m]=i[y]),m++}return p[u]=m,e.createSparseMatrix({values:d,index:f,ptr:p,size:[l,u],datatype:c})}var F_e=e((()=>{}));function xE(e,t,n,r,i,a,o){var s=0;for(n[o]=e;s>=0;){var c=n[o+s],l=n[r+c];l===-1?(s--,a[t++]=c):(n[r+c]=n[i+l],++s,n[o+s]=l)}return t}var SE=e((()=>{}));function I_e(e,t){if(!e)return null;var n=0,r,i=[],a=[],o=0,s=t,c=2*t;
vendor: 4,727 bytes, line 2608
2608for(r=0;r<t;r++)a[o+r]=-1;for(r=t-1;r>=0;r--)e[r]!==-1&&(a[s+r]=a[o+e[r]],a[o+e[r]]=r);for(r=0;r<t;r++)e[r]===-1&&(n=xE(r,n,a,o,s,i,c));return i}var L_e=e((()=>{SE()}));function R_e(e,t){if(!e)return null;var n=e._index,r=e._ptr,i=e._size,a=i[0],o=i[1],s=[],c=[],l=0,u=o,d,f;if(t)for(d=0;d<a;d++)c[u+d]=-1;for(var p=0;p<o;p++){s[p]=-1,c[l+p]=-1;for(var m=r[p],h=r[p+1],g=m;g<h;g++){var _=n[g];for(d=t?c[u+_]:_;d!==-1&&d<p;d=f)f=c[l+d],c[l+d]=p,f===-1&&(s[d]=p);t&&(c[u+_]=p)}}return s}var z_e=e((()=>{}));function B_e(e,t,n){for(var r=e._values,i=e._index,a=e._ptr,o=e._size[1],s=0,c=0;c<o;c++){var l=a[c];for(a[c]=s;l<a[c+1];l++)t(i[l],c,r?r[l]:1,n)&&(i[s]=i[l],r&&(r[s]=r[l]),s++)}return a[o]=s,i.splice(s,i.length-s),r&&r.splice(s,r.length-s),s}var V_e=e((()=>{}));function CE(e){return-e-2}var wE=e((()=>{})),TE,EE,DE,H_e=e((()=>{X(),V_e(),wE(),SE(),TE=`csAmd`,EE=[`add`,`multiply`,`transpose`],DE=Y(TE,EE,e=>{var{add:t,multiply:n,transpose:r}=e;return function(e,t){if(!t||e<=0||e>3)return null;var n=t._size,r=n[0],l=n[1],u=0,d=Math.max(16,10*Math.sqrt(l));d=Math.min(l-2,d);var f=i(e,t,r,l,d);B_e(f,c,null);for(var p=f._index,m=f._ptr,h=m[l],g=[],_=[],v=0,y=l+1,b=2*(l+1),x=3*(l+1),S=4*(l+1),C=5*(l+1),w=6*(l+1),T=7*(l+1),E=g,D=a(l,m,_,v,x,E,b,T,y,w,S,C),O=o(l,m,_,C,S,w,d,y,x,E,b),k=0,A,j,M,N,P,F,I,L,ee,R,te,z,ne,B,V,H;O<l;){for(M=-1;k<l&&(M=_[x+k])===-1;k++);_[b+M]!==-1&&(E[_[b+M]]=-1),_[x+k]=_[b+M];var re=_[S+M],ie=_[y+M];O+=ie;var ae=0;_[y+M]=-ie;var oe=m[M],se=re===0?oe:h,ce=se;for(N=1;N<=re+1;N++){for(N>re?(F=M,I=oe,L=_[v+M]-re):(F=p[oe++],I=m[F],L=_[v+F]),P=1;P<=L;P++)A=p[I++],!((ee=_[y+A])<=0)&&(ae+=ee,_[y+A]=-ee,p[ce++]=A,_[b+A]!==-1&&(E[_[b+A]]=E[A]),E[A]===-1?_[x+_[C+A]]=_[b+A]:_[b+E[A]]=_[b+A]);F!==M&&(m[F]=CE(M),_[w+F]=0)}for(re!==0&&(h=ce),_[C+M]=ae,m[M]=se,_[v+M]=ce-se,_[S+M]=-2,D=s(D,u,_,w,l),R=se;R<ce;R++)if(A=p[R],!((te=_[S+A])<=0)){ee=-_[y+A];var le=D-ee;for(oe=m[A],z=m[A]+te-1;oe<=z;oe++)F=p[oe],_[w+F]>=D?_[w+F]-=ee:_[w+F]!==0&&(_[w+F]=_[C+F]+le)}for(R=se;R<ce;R++){for(A=p[R],z=m[A],ne=z+_[S+A]-1,B=z,V=0,H=0,oe=z;oe<=ne;oe++)if(F=p[oe],_[w+F]!==0){var ue=_[w+F]-D;ue>0?(H+=ue,p[B++]=F,V+=F):(m[F]=CE(M),_[w+F]=0)}_[S+A]=B-z+1;var de=B,fe=z+_[v+A];for(oe=ne+1;oe<fe;oe++){j=p[oe];var pe=_[y+j];pe<=0||(H+=pe,p[B++]=j,V+=j)}H===0?(m[A]=CE(M),ee=-_[y+A],ae-=ee,ie+=ee,O+=ee,_[y+A]=0,_[S+A]=-1):(_[C+A]=Math.min(_[C+A],H),p[B]=p[de],p[de]=p[z],p[z]=M,_[v+A]=B-z+1,V=(V<0?-V:V)%l,_[b+A]=_[T+V],_[T+V]=A,E[A]=V)}for(_[C+M]=ae,u=Math.max(u,ae),D=s(D+u,u,_,w,l),R=se;R<ce;R++)if(A=p[R],!(_[y+A]>=0))for(V=E[A],A=_[T+V],_[T+V]=-1;A!==-1&&_[b+A]!==-1;A=_[b+A],D++){for(L=_[v+A],te=_[S+A],oe=m[A]+1;oe<=m[A]+L-1;oe++)_[w+p[oe]]=D;var me=A;for(j=_[b+A];j!==-1;){var he=_[v+j]===L&&_[S+j]===te;for(oe=m[j]+1;he&&oe<=m[j]+L-1;oe++)_[w+p[oe]]!==D&&(he=0);he?(m[j]=CE(A),_[y+A]+=_[y+j],_[y+j]=0,_[S+j]=-1,j=_[b+j],_[b+me]=j):(me=j,j=_[b+j])}}for(oe=se,R=se;R<ce;R++)A=p[R],!((ee=-_[y+A])<=0)&&(_[y+A]=ee,H=_[C+A]+ae-ee,H=Math.min(H,l-O-ee),_[x+H]!==-1&&(E[_[x+H]]=A),_[b+A]=_[x+H],E[A]=-1,_[x+H]=A,k=Math.min(k,H),_[C+A]=H,p[oe++]=A);_[y+M]=ie,(_[v+M]=oe-se)===0&&(m[M]=-1,_[w+M]=0),re!==0&&(h=oe)}for(A=0;A<l;A++)m[A]=CE(m[A]);for(j=0;j<=l;j++)_[x+j]=-1;for(j=l;j>=0;j--)_[y+j]>0||(_[b+j]=_[x+m[j]],_[x+m[j]]=j);for(F=l;F>=0;F--)_[y+F]<=0||m[F]!==-1&&(_[b+F]=_[x+m[F]],_[x+m[F]]=F);for(M=0,A=0;A<=l;A++)m[A]===-1&&(M=xE(A,M,_,x,b,g,w));return g.splice(g.length-1,1),g};function i(e,i,a,o,s){var c=r(i);if(e===1&&o===a)return t(i,c);if(e===2){for(var l=c._index,u=c._ptr,d=0,f=0;f<a;f++){var p=u[f];if(u[f]=d,!(u[f+1]-p>s))for(var m=u[f+1];p<m;p++)l[d++]=l[p]}return u[a]=d,i=r(c),n(c,i)}return n(c,i)}function a(e,t,n,r,i,a,o,c,l,u,d,f){for(var p=0;p<e;p++)n[r+p]=t[p+1]-t[p];n[r+e]=0;for(var m=0;m<=e;m++)n[i+m]=-1,a[m]=-1,n[o+m]=-1,n[c+m]=-1,n[l+m]=1,n[u+m]=1,n[d+m]=0,n[f+m]=n[r+m];var h=s(0,0,n,u,e);return n[d+e]=-2,t[e]=-1,n[u+e]=0,h}function o(e,t,n,r,i,a,o,s,c,l,u){for(var d=0,f=0;f<e;f++){var p=n[r+f];if(p===0)n[i+f]=-2,d++,t[f]=-1,n[a+f]=0;else if(p>o)n[s+f]=0,n[i+f]=-1,d++,t[f]=CE(e),n[s+e]++;else{var m=n[c+p];m!==-1&&(l[m]=f),n[u+f]=n[c+p],n[c+p]=f}}return d}function s(e,t,n,r,i){if(e<2||e+t<0){for(var a=0;a<i;a++)n[r+a]!==0&&(n[r+a]=1);e=2}return e}function c(e,t){return e!==t}})}));function U_e(e,t,n,r,i,a,o){var s,c,l=0,u;if(e<=t||n[r+t]<=n[i+e])return-1;n[i+e]=n[r+t];var d=n[a+e];if(n[a+e]=t,d===-1)l=1,u=e;else{for(l=2,u=d;u!==n[o+u];u=n[o+u]);for(s=d;s!==u;s=c)c=n[o+s],n[o+s]=u}return{jleaf:l,q:u}}var W_e=e((()=>{})),OE,kE,AE,G_e=e((()=>{X(),W_e(),OE=`csCounts`,kE=[`transpose`],AE=Y(OE,kE,e=>{var{transpose:t}=e;return function(e,n,r,i){if(!e||!n||!r)return null;var a=e._size,o=a[0],s=a[1],c,l,u,d,f,p,m,h=4*s+(i?s+o+1:0),g=[],_=0,v=s,y=2*s,b=3*s,x=4*s,S=5*s+1;for(u=0;
2608u<h;u++)g[u]=-1;var C=[],w=t(e),T=w._index,E=w._ptr;for(u=0;u<s;u++)for(l=r[u],C[l]=+(g[b+l]===-1);l!==-1&&g[b+l]===-1;l=n[l])g[b+l]=u;if(i){for(u=0;u<s;u++)g[r[u]]=u;for(c=0;c<o;c++){for(u=s,p=E[c],m=E[c+1],f=p;f<m;f++)u=Math.min(u,g[T[f]]);g[S+c]=g[x+u],g[x+u]=c}}for(c=0;c<s;c++)g[_+c]=c;for(u=0;u<s;u++){for(l=r[u],n[l]!==-1&&C[n[l]]--,d=i?g[x+u]:l;d!==-1;d=i?g[S+d]:-1)for(f=E[d];f<E[d+1];f++){c=T[f];var D=U_e(c,l,g,b,v,y,_);D.jleaf>=1&&C[l]++,D.jleaf===2&&C[D.q]--}n[l]!==-1&&(g[_+l]=n[l])}for(l=0;l<s;l++)n[l]!==-1&&(C[n[l]]+=C[l]);return C}})})),jE,ME,NE,K_e=e((()=>{F_e(),L_e(),z_e(),H_e(),G_e(),X(),jE=`csSqr`,ME=[`add`,`multiply`,`transpose`],NE=Y(jE,ME,e=>{var{add:t,multiply:n,transpose:r}=e,i=DE({add:t,multiply:n,transpose:r}),a=AE({transpose:r});return function(e,t,n){var r=t._ptr,s=t._size[1],c,l={};if(l.q=i(e,t),e&&!l.q)return null;if(n){var u=e?P_e(t,null,l.q,0):t;l.parent=R_e(u,1);var d=I_e(l.parent,s);if(l.cp=a(u,l.parent,d,1),u&&l.parent&&l.cp&&o(u,l))for(l.unz=0,c=0;c<s;c++)l.unz+=l.cp[c]}else l.unz=4*r[s]+s,l.lnz=l.unz;return l};function o(e,t){var n=e._ptr,r=e._index,i=e._size,a=i[0],o=i[1];t.pinv=[],t.leftmost=[];var s=t.parent,c=t.pinv,l=t.leftmost,u=[],d=0,f=a,p=a+o,m=a+2*o,h,g,_,v,y;for(g=0;g<o;g++)u[f+g]=-1,u[p+g]=-1,u[m+g]=0;for(h=0;h<a;h++)l[h]=-1;for(g=o-1;g>=0;g--)for(v=n[g],y=n[g+1],_=v;_<y;_++)l[r[_]]=g;for(h=a-1;h>=0;h--)c[h]=-1,g=l[h],g!==-1&&(u[m+g]++===0&&(u[p+g]=h),u[d+h]=u[f+g],u[f+g]=h);for(t.lnz=0,t.m2=a,g=0;g<o;g++)if(h=u[f+g],t.lnz++,h<0&&(h=t.m2++),c[h]=g,!(--m[g]<=0)){t.lnz+=u[m+g];var b=s[g];b!==-1&&(u[m+b]===0&&(u[p+b]=u[p+g]),u[d+u[p+g]]=u[f+b],u[f+b]=u[d+h],u[m+b]+=u[m+g])}for(h=0;h<a;h++)c[h]<0&&(c[h]=g++);return!0}})}));function PE(e,t){return e[t]<0}var FE=e((()=>{}));function IE(e,t){e[t]=CE(e[t])}var LE=e((()=>{wE()}));function RE(e){return e<0?CE(e):e}var q_e=e((()=>{wE()}));function J_e(e,t,n,r,i){var a=t._index,o=t._ptr,s=t._size[1],c,l,u,d=0;for(r[0]=e;d>=0;){e=r[d];var f=i?i[e]:e;PE(o,e)||(IE(o,e),r[s+d]=f<0?0:RE(o[f]));var p=1;for(l=r[s+d],u=f<0?0:RE(o[f+1]);l<u;l++)if(c=a[l],!PE(o,c)){r[s+d]=l,r[++d]=c,p=0;break}p&&(d--,r[--n]=e)}return n}var Y_e=e((()=>{FE(),LE(),q_e()}));function X_e(e,t,n,r,i){var a=e._ptr,o=e._size,s=t._index,c=t._ptr,l=o[1],u,d,f,p=l;for(d=c[n],f=c[n+1],u=d;u<f;u++){var m=s[u];PE(a,m)||(p=J_e(m,e,p,r,i))}for(u=p;u<l;u++)IE(a,r[u]);return p}var Z_e=e((()=>{FE(),LE(),Y_e()})),zE,BE,VE,Q_e=e((()=>{Z_e(),X(),zE=`csSpsolve`,BE=[`divideScalar`,`multiply`,`subtract`],VE=Y(zE,BE,e=>{var{divideScalar:t,multiply:n,subtract:r}=e;return function(e,i,a,o,s,c,l){var u=e._values,d=e._index,f=e._ptr,p=e._size[1],m=i._values,h=i._index,g=i._ptr,_,v,y,b,x=X_e(e,i,a,o,c);for(_=x;_<p;_++)s[o[_]]=0;for(v=g[a],y=g[a+1],_=v;_<y;_++)s[h[_]]=m[_];for(var S=x;
2608S<p;S++){var C=o[S],w=c?c[C]:C;if(!(w<0))for(v=f[w],y=f[w+1],s[C]=t(s[C],u[l?v:y-1]),_=l?v+1:v,b=l?y:y-1;_<b;_++){var T=d[_];s[T]=r(s[T],n(u[_],s[C]))}}return x}})})),HE,UE,WE,$_e=e((()=>{X(),Q_e(),HE=`csLu`,UE=[`abs`,`divideScalar`,`multiply`,`subtract`,`larger`,`largerEq`,`SparseMatrix`],WE=Y(HE,UE,e=>{var{abs:t,divideScalar:n,multiply:r,subtract:i,larger:a,largerEq:o,SparseMatrix:s}=e,c=VE({divideScalar:n,multiply:r,subtract:i});return function(e,i,l){if(!e)return null;var u=e._size[1],d,f=100,p=100;i&&(d=i.q,f=i.lnz||f,p=i.unz||p);var m=[],h=[],g=[],_=new s({values:m,index:h,ptr:g,size:[u,u]}),v=[],y=[],b=[],x=new s({values:v,index:y,ptr:b,size:[u,u]}),S=[],C,w,T=[],E=[];for(C=0;C<u;C++)T[C]=0,S[C]=-1,g[C+1]=0;f=0,p=0;for(var D=0;D<u;D++){g[D]=f,b[D]=p;var O=d?d[D]:D,k=c(_,e,O,E,T,S,1),A=-1,j=-1;for(w=k;w<u;w++)if(C=E[w],S[C]<0){var M=t(T[C]);a(M,j)&&(j=M,A=C)}else y[p]=S[C],v[p++]=T[C];if(A===-1||j<=0)return null;S[O]<0&&o(t(T[O]),r(j,l))&&(A=O);var N=T[A];for(y[p]=D,v[p++]=N,S[A]=D,h[f]=A,m[f++]=1,w=k;w<u;w++)C=E[w],S[C]<0&&(h[f]=C,m[f++]=n(T[C],N)),T[C]=0}for(g[u]=f,b[u]=p,w=0;w<f;w++)h[w]=S[h[w]];return m.splice(f,m.length-f),h.splice(f,h.length-f),v.splice(p,v.length-p),y.splice(p,y.length-p),{L:_,U:x,pinv:S}}})})),GE,KE,qE,eve=e((()=>{Pu(),X(),K_e(),$_e(),GE=`slu`,KE=[`typed`,`abs`,`add`,`multiply`,`transpose`,`divideScalar`,`subtract`,`larger`,`largerEq`,`SparseMatrix`],qE=Y(GE,KE,e=>{var{typed:t,abs:n,add:r,multiply:i,transpose:a,divideScalar:o,subtract:s,larger:c,largerEq:l,SparseMatrix:u}=e,d=NE({add:r,multiply:i,transpose:a}),f=WE({abs:n,divideScalar:o,multiply:i,subtract:s,larger:c,largerEq:l,SparseMatrix:u});return t(GE,{"SparseMatrix, number, number":function(e,t,n){if(!lu(t)||t<0||t>3)throw Error(`Symbolic Ordering and Analysis order must be an integer number in the interval [0, 3]`);if(n<0||n>1)throw Error(`Partial pivoting threshold must be a number from 0 to 1`);var r=d(t,e,!1),i=f(e,r,n);return{L:i.L,U:i.U,p:i.pinv,q:r.q,toString:function(){return`L: `+this.L.toString()+`
2609U: `+this.U.toString()+`
2610p: `+this.p.toString()+(this.q?`
2611q: `+this.q.toString():``)+`
2612`}}}})})}));function JE(e,t){var n,r=t.length,i=[];if(e)for(n=0;n<r;n++)i[e[n]]=t[n];else for(n=0;n<r;n++)i[n]=t[n];return i}var tve=e((()=>{})),YE,XE,ZE,nve=e((()=>{Ql(),X(),Jx(),tve(),YE=`lusolve`,XE=[`typed`,`matrix`,`lup`,`slu`,`usolve`,`lsolve`,`DenseMatrix`],ZE=Y(YE,XE,e=>{var{typed:t,matrix:n,lup:r,slu:i,usolve:a,lsolve:o,DenseMatrix:s}=e,c=qx({DenseMatrix:s});return t(YE,{"Array, Array | Matrix":function(e,t){e=n(e);var i=r(e);return u(i.L,i.U,i.p,null,t).valueOf()},"DenseMatrix, Array | Matrix":function(e,t){var n=r(e);return u(n.L,n.U,n.p,null,t)},"SparseMatrix, Array | Matrix":function(e,t){var n=r(e);return u(n.L,n.U,n.p,null,t)},"SparseMatrix, Array | Matrix, number, number":function(e,t,n,r){var a=i(e,n,r);return u(a.L,a.U,a.p,a.q,t)},"Object, Array | Matrix":function(e,t){return u(e.L,e.U,e.p,e.q,t)}});function l(e){if(Dl(e))return e;if(Zl(e))return n(e);throw TypeError(`Invalid Matrix LU decomposition`)}function u(e,t,n,r,i){e=l(e),t=l(t),n&&(i=c(e,i,!0),i._data=JE(n,i._data));var s=o(e,i),u=a(t,s);return r&&(u._data=JE(r,u._data)),u}})})),QE,$E,eD,rve=e((()=>{X(),QE=`polynomialRoot`,$E=[`typed`,`isZero`,`equalScalar`,`add`,`subtract`,`multiply`,`divide`,`sqrt`,`unaryMinus`,`cbrt`,`typeOf`,`im`,`re`],eD=Y(QE,$E,e=>{var{typed:t,isZero:n,equalScalar:r,add:i,subtract:a,multiply:o,divide:s,sqrt:c,unaryMinus:l,cbrt:u,typeOf:d,im:f,re:p}=e;return t(QE,{"number|Complex, ...number|Complex":(e,t)=>{for(var m=[e,...t];m.length>0&&n(m[m.length-1]);)m.pop();if(m.length<2)throw RangeError(`Polynomial [${e}, ${t}] must have a non-zero non-constant coefficient`);switch(m.length){case 2:return[l(s(m[0],m[1]))];case 3:var[h,g,_]=m,v=o(2,_),y=o(g,g),b=o(4,_,h);if(r(y,b))return[s(l(g),v)];var x=c(a(y,b));return[s(a(x,g),v),s(a(l(x),g),v)];case 4:var[S,C,w,T]=m,E=l(o(3,T)),D=o(w,w),O=o(3,T,C),k=i(o(2,w,w,w),o(27,T,T,S)),A=o(9,T,w,C);if(r(D,O)&&r(k,A))return[s(w,E)];var j=a(D,O),M=a(k,A);return r(i(o(18,T,w,C,S),o(w,w,C,C)),i(o(4,w,w,w,S),o(4,T,C,C,C),o(27,T,T,S,S)))?[
2612s(a(o(4,T,w,C),i(o(9,T,T,S),o(w,w,w))),o(T,j)),s(a(o(9,T,S),o(w,C)),o(2,j))]:u(r(D,O)?M:s(i(M,c(a(o(M,M),o(4,j,j,j)))),2),!0).toArray().map(e=>s(i(w,e,s(j,e)),E)).map(e=>d(e)===`Complex`&&r(p(e),p(e)+f(e))?p(e):e);default:throw RangeError(`only implemented for cubic or lower-order polynomials, not ${m}`)}}})})})),tD,nD,rD,ive=e((()=>{Ql(),ru(),Hf(),X(),tD=`Help`,nD=[`evaluate`],rD=Y(tD,nD,e=>{var{evaluate:t}=e;function n(e){if(!(this instanceof n))throw SyntaxError(`Constructor must be called with the new operator`);if(!e)throw Error(`Argument "doc" missing`);this.doc=e}return n.prototype.type=`Help`,n.prototype.isHelp=!0,n.prototype.toString=function(){var e=this.doc||{},n=`
2613`;if(e.name&&(n+=`Name: `+e.name+`
2614
2615`),e.category&&(n+=`Category: `+e.category+`
2616
2617`),e.description&&(n+=`Description:
2618    `+e.description+`
2619
2620`),e.syntax&&(n+=`Syntax:
2621    `+e.syntax.join(`
2622    `)+`
2623
2624`),e.examples){n+=`Examples:
2625`;for(var r=!1,i=t(`config()`),a={config:e=>(r=!0,t(`config(newConfig)`,{newConfig:e}))},o=0;o<e.examples.length;o++){var s=e.examples[o];n+=`    `+s+`
2626`;var c=void 0;try{c=t(s,a)}catch(e){c=e}c!==void 0&&!Nl(c)&&(n+=`        `+If(c,{precision:14})+`
2627`)}n+=`
2628`,r&&t(`config(originalConfig)`,{originalConfig:i})}return e.mayThrow&&e.mayThrow.length&&(n+=`Throws: `+e.mayThrow.join(`, `)+`
2629
2630`),e.seealso&&e.seealso.length&&(n+=`See also: `+e.seealso.join(`, `)+`
2631`),n},n.prototype.toJSON=function(){var e=$l(this.doc);return e.mathjs=`Help`,e},n.fromJSON=function(e){var t={};return Object.keys(e).filter(e=>e!==`mathjs`).forEach(n=>{t[n]=e[n]}),new n(t)},n.prototype.valueOf=n.prototype.toString,n},{isClass:!0})})),iD,aD,oD,ave=e((()=>{Ql(),Hf(),ru(),X(),iD=`Chain`,aD=[`?on`,`math`,`typed`],oD=Y(iD,aD,e=>{var{on:t,math:n,typed:r}=e;function i(e){if(!(this instanceof i))throw SyntaxError(`Constructor must be called with the new operator`);Yl(e)?this.value=e.value:this.value=e}i.prototype.type=`Chain`,i.prototype.isChain=!0,i.prototype.done=function(){return this.value},i.prototype.valueOf=function(){return this.value},i.prototype.toString=function(){return If(this.value)},i.prototype.toJSON=function(){return{mathjs:`Chain`,value:this.value}},i.fromJSON=function(e){return new i(e.value)};function a(e,t){typeof t==`function`&&(i.prototype[e]=s(t))}function o(e,t){tu(i.prototype,e,function(){var e=t();if(typeof e==`function`)return s(e)})}function s(e){return function(){if(arguments.length===0)return new i(e(this.value));for(var t=[this.value],n=0;n<arguments.length;n++)t[n+1]=arguments[n];if(r.isTypedFunction(e)){var a=r.resolve(e,t);if(a.params.length===1)throw Error(`chain function `+e.name+` cannot match rest parameter between chain value and additional arguments.`);return new i(a.implementation.apply(e,t))}return new i(e.apply(e,t))}}i.createProxy=function(e,t){if(typeof e==`string`)a(e,t);else{var n=function(t){nu(e,t)&&c[t]===void 0&&o(t,()=>e[t])};for(var r in e)n(r)}};var c={expression:!0,docs:!0,type:!0,classes:!0,json:!0,error:!0,isChain:!0};return i.createProxy(n),t&&t(`import`,function(e,t,n){n||o(e,t)}),i},{isClass:!0})})),sD,ove=e((()=>{sD={name:`e`,category:`Constants`,syntax:[`e`],description:`Euler's number, the base of the natural logarithm. Approximately equal to 2.71828`,examples:[`e`,`e ^ 2`,`exp(2)`,`log(e)`],seealso:[`exp`]}})),cD,sve=e((()=>{cD={name:`false`,category:`Constants`,syntax:[`false`],description:`Boolean value false`,examples:[`false`],seealso:[`true`]}})),lD,cve=e((()=>{lD={name:`i`,category:`Constants`,syntax:[`i`],description:`Imaginary unit, defined as i*i=-1. A complex number is described as a + b*i, where a is the real part, and b is the imaginary part.`,examples:[`i`,`i * i`,`sqrt(-1)`],seealso:[]}})),uD,lve=e((()=>{uD={name:`Infinity`,category:`Constants`,syntax:[`Infinity`],description:`Infinity, a number which is larger than the maximum number that can be handled by a floating point number.`,examples:[`Infinity`,`1 / 0`],seealso:[]}})),dD,uve=e((()=>{dD={name:`LN10`,category:`Constants`,syntax:[`LN10`],description:`Returns the natural logarithm of 10, approximately equal to 2.302`,examples:[`LN10`,`log(10)`],seealso:[]}})),fD,dve=e((()=>{fD={name:`LN2`,category:`Constants`,syntax:[`LN2`],description:`Returns the natural logarithm of 2, approximately equal to 0.693`,examples:[`LN2`,`log(2)`],seealso:[]}})),pD,fve=e((()=>{pD={name:`LOG10E`,category:`Constants`,syntax:[`LOG10E`],description:`Returns the base-10 logarithm of E, approximately equal to 0.434`,examples:[`LOG10E`,`log(e, 10)`],seealso:[]}})),mD,pve=e((()=>{mD={name:`LOG2E`,category:`Constants`,syntax:[`LOG2E`],description:`Returns the base-2 logarithm of E, approximately equal to 1.442`,examples:[`LOG2E`,`log(e, 2)`],seealso:[]}})),hD,mve=e((()=>{hD={name:`NaN`,category:`Constants`,syntax:[`NaN`],description:`Not a number`,examples:[`NaN`,`0 / 0`],seealso:[]}})),gD,hve=e((()=>{gD={name:`null`,category:`Constants`,syntax:[`null`],description:`Value null`,examples:[`null`],seealso:[`true`,`false`]}})),_D,gve=e((()=>{_D={name:`phi`,category:`Constants`,syntax:[`phi`],description:"Phi is the golden ratio. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities. Phi is defined as `(1 + sqrt(5)) / 2` and is approximately 1.618034...",examples:[`phi`],seealso:[]}})),vD,_ve=e((()=>{vD={name:`pi`,category:`Constants`,syntax:[`pi`],description:`The number pi is a mathematical constant that is the ratio of a circle's circumference to its diameter, and is approximately equal to 3.14159`,examples:[`pi`,`sin(pi/2)`],seealso:[`tau`]}})),yD,vve=e((()=>
2631{yD={name:`SQRT1_2`,category:`Constants`,syntax:[`SQRT1_2`],description:`Returns the square root of 1/2, approximately equal to 0.707`,examples:[`SQRT1_2`,`sqrt(1/2)`],seealso:[]}})),bD,yve=e((()=>{bD={name:`SQRT2`,category:`Constants`,syntax:[`SQRT2`],description:`Returns the square root of 2, approximately equal to 1.414`,examples:[`SQRT2`,`sqrt(2)`],seealso:[]}})),xD,bve=e((()=>{xD={name:`tau`,category:`Constants`,syntax:[`tau`],description:`Tau is the ratio constant of a circle's circumference to radius, equal to 2 * pi, approximately 6.2832.`,examples:[`tau`,`2 * pi`],seealso:[`pi`]}})),SD,xve=e((()=>{SD={name:`true`,category:`Constants`,syntax:[`true`],description:`Boolean value true`,examples:[`true`],seealso:[`false`]}})),CD,Sve=e((()=>{CD={name:`version`,category:`Constants`,syntax:[`version`],description:`A string with the version number of math.js`,examples:[`version`],seealso:[]}})),wD,Cve=e((()=>{wD={name:`bignumber`,category:`Construction`,syntax:[`bignumber(x)`],description:`Create a big number from a number or string.`,examples:[`0.1 + 0.2`,`bignumber(0.1) + bignumber(0.2)`,`bignumber("7.2")`,`bignumber("7.2e500")`,`bignumber([0.1, 0.2, 0.3])`],seealso:[`boolean`,`bigint`,`complex`,`fraction`,`index`,`matrix`,`string`,`unit`]}})),TD,wve=e((()=>{TD={name:`bigint`,category:`Construction`,syntax:[`bigint(x)`],description:`Create a bigint, an integer with an arbitrary number of digits, from a number or string.`,examples:[`123123123123123123 # a large number will lose digits`,`bigint("123123123123123123")`,`bignumber(["1", "3", "5"])`],seealso:[`boolean`,`bignumber`,`number`,`complex`,`fraction`,`index`,`matrix`,`string`,`unit`]}})),ED,Tve=e((()=>{ED={name:`boolean`,category:`Construction`,syntax:[`x`,`boolean(x)`],description:`Convert a string or number into a boolean.`,examples:[`boolean(0)`,`boolean(1)`,`boolean(3)`,`boolean("true")`,`boolean("false")`,`boolean([1, 0, 1, 1])`],seealso:[`bignumber`,`complex`,`index`,`matrix`,`number`,`string`,`unit`]}})),DD,Eve=e((()=>{DD={name:`complex`,category:`Construction`,syntax:[`complex()`,`complex(re, im)`,`complex(string)`],description:`Create a complex number.`,examples:[`complex()`,`complex(2, 3)`,`complex("7 - 2i")`],seealso:[`bignumber`,`boolean`,`index`,`matrix`,`number`,`string`,`unit`]}})),OD,Dve=e((()=>{OD={name:`createUnit`,category:`Construction`,syntax:[`createUnit(definitions)`,`createUnit(name, definition)`],description:`Create a user-defined unit and register it with the Unit type.`,examples:[`createUnit("foo")`,`createUnit("knot", {definition: "0.514444444 m/s", aliases: ["knots", "kt", "kts"]})`,`createUnit("mph", "1 mile/hour")`],seealso:[`unit`,`splitUnit`]}})),kD,Ove=e((()=>{kD={name:`fraction`,category:`Construction`,syntax:[`fraction(num)`,`fraction(matrix)`,`fraction(num,den)`,`fraction({n: num, d: den})`],description:`Create a fraction from a number or from integer numerator and denominator.`,examples:[`fraction(0.125)`,`fraction(1, 3) + fraction(2, 5)`,`fraction({n: 333, d: 53})`,`fraction([sqrt(9), sqrt(10), sqrt(11)])`],seealso:[`bignumber`,`boolean`,`complex`,`index`,`matrix`,`string`,`unit`]}})),AD,kve=e((()=>{AD={name:`index`,category:`Construction`,syntax:[`[start]`,`[start:end]`,`[start:step:end]`,`[start1, start 2, ...]`,`[start1:end1, start2:end2, ...]`,`[start1:step1:end1, start2:step2:end2, ...]`],description:`Create an index to get or replace a subset of a matrix`,examples:[`A = [1, 2, 3; 4, 5, 6]`,`A[1, :]`,`A[1, 2] = 50`,`A[1:2, 1:2] = 1`,`B = [1, 2, 3]`,`B[B>1 and B<3]`],seealso:[`bignumber`,`boolean`,`complex`,`matrix`,`number`,`range`,`string`,`unit`]}})),jD,Ave=e((()=>{jD={name:`matrix`,category:`Construction`,syntax:[`[]`,`[a1, b1, ...; a2, b2, ...]`,`matrix()`,`matrix("dense")`,`matrix([...])`],description:`Create a matrix.`,examples:[`[]`,`[1, 2, 3]`,`[1, 2, 3; 4, 5, 6]`,`matrix()`,`matrix([3, 4])`,`matrix([3, 4; 5, 6], "sparse")`,`matrix([3, 4; 5, 6], "sparse", "number")`],seealso:[`bignumber`,`boolean`,`complex`,`index`,`number`,`string`,`unit`,`sparse`]}})),MD,jve=e((()=>
2631{MD={name:`number`,category:`Construction`,syntax:[`x`,`number(x)`,`number(unit, valuelessUnit)`],description:`Create a number or convert a string or boolean into a number.`,examples:[`2`,`2e3`,`4.05`,`number(2)`,`number("7.2")`,`number(true)`,`number([true, false, true, true])`,`number(unit("52cm"), "m")`],seealso:[`bignumber`,`bigint`,`boolean`,`complex`,`fraction`,`index`,`matrix`,`string`,`unit`]}})),ND,Mve=e((()=>{ND={name:`sparse`,category:`Construction`,syntax:[`sparse()`,`sparse([a1, b1, ...; a1, b2, ...])`,`sparse([a1, b1, ...; a1, b2, ...], "number")`],description:`Create a sparse matrix.`,examples:[`sparse()`,`sparse([3, 4; 5, 6])`,`sparse([3, 0; 5, 0], "number")`],seealso:[`bignumber`,`boolean`,`complex`,`index`,`number`,`string`,`unit`,`matrix`]}})),PD,Nve=e((()=>{PD={name:`splitUnit`,category:`Construction`,syntax:[`splitUnit(unit: Unit, parts: Unit[])`],description:`Split a unit in an array of units whose sum is equal to the original unit.`,examples:[`splitUnit(1 m, ["feet", "inch"])`],seealso:[`unit`,`createUnit`]}})),FD,Pve=e((()=>{FD={name:`string`,category:`Construction`,syntax:[`"text"`,`string(x)`],description:`Create a string or convert a value to a string`,examples:[`"Hello World!"`,`string(4.2)`,`string(3 + 2i)`],seealso:[`bignumber`,`boolean`,`complex`,`index`,`matrix`,`number`,`unit`]}})),ID,Fve=e((()=>{ID={name:`unit`,category:`Construction`,syntax:[`value unit`,`unit(value, unit)`,`unit(string)`],description:`Create a unit.`,examples:[`5.5 mm`,`3 inch`,`unit(7.1, "kilogram")`,`unit("23 deg")`],seealso:[`bignumber`,`boolean`,`complex`,`index`,`matrix`,`number`,`string`]}})),LD,Ive=e((()=>{LD={name:`config`,category:`Core`,syntax:[`config()`,`config(options)`],description:`Get configuration or change configuration.`,examples:[`config()`,`1/3 + 1/4`,`config({number: "Fraction"})`,`1/3 + 1/4`],seealso:[]}})),RD,Lve=e((()=>{RD={name:`import`,category:`Core`,syntax:[`import(functions)`,`import(functions, options)`],description:`Import functions or constants from an object.`,examples:[`import({myFn: f(x)=x^2, myConstant: 32 })`,`myFn(2)`,`myConstant`],seealso:[]}})),zD,Rve=e((()=>{zD={name:`typed`,category:`Core`,syntax:[`typed(signatures)`,`typed(name, signatures)`],description:`Create a typed function.`,examples:[`double = typed({ "number": f(x)=x+x, "string": f(x)=concat(x,x) })`,`double(2)`,`double("hello")`],seealso:[]}})),BD,zve=e((()=>{BD={name:`derivative`,category:`Algebra`,syntax:[`derivative(expr, variable)`,`derivative(expr, variable, {simplify: boolean})`],description:`Takes the derivative of an expression expressed in parser Nodes. The derivative will be taken over the supplied variable in the second parameter. If there are multiple variables in the expression, it will return a partial derivative.`,examples:[`derivative("2x^3", "x")`,`derivative("2x^3", "x", {simplify: false})`,`derivative("2x^2 + 3x + 4", "x")`,`derivative("sin(2x)", "x")`,`f = parse("x^2 + x")`,`x = parse("x")`,`df = derivative(f, x)`,`df.evaluate({x: 3})`],seealso:[`simplify`,`parse`,`evaluate`]}})),VD,Bve=e((()=>{VD={name:`leafCount`,category:`Algebra`,syntax:[`leafCount(expr)`],description:`Computes the number of leaves in the parse tree of the given expression`,examples:[`leafCount("e^(i*pi)-1")`,`leafCount(parse("{a: 22/7, b: 10^(1/2)}"))`],seealso:[`simplify`]}})),HD,Vve=e((()=>{HD={name:`lsolve`,category:`Algebra`,syntax:[`x=lsolve(L, b)`],description:`Finds one solution of the linear system L * x = b where L is an [n x n] lower triangular matrix and b is a [n] column vector.`,examples:[`a = [-2, 3; 2, 1]`,`b = [11, 9]`,`x = lsolve(a, b)`],seealso:[`lsolveAll`,`lup`,`lusolve`,`usolve`,`matrix`,`sparse`]}})),UD,Hve=e((()=>{UD={name:`lsolveAll`,category:`Algebra`,syntax:[`x=lsolveAll(L, b)`],description:`Finds all solutions of the linear system L * x = b where L is an [n x n] lower triangular matrix and b is a [n] column vector.`,examples:[`a = [-2, 3; 2, 1]`,`b = [11, 9]`,`x = lsolve(a, b)`],seealso:[`lsolve`,`lup`,`lusolve`,`usolve`,`matrix`,`sparse`]}})),WD,Uve=e((()=>{WD={name:`lup`,category:`Algebra`,syntax:[`lup(m)`],description:`Calculate the Matrix LU decomposition with partial pivoting. Matrix A is decomposed in three matrices (L, U, P) where P * A = L * U`,examples:[`lup([[2, 
26311], [1, 4]])`,`lup(matrix([[2, 1], [1, 4]]))`,`lup(sparse([[2, 1], [1, 4]]))`],seealso:[`lusolve`,`lsolve`,`usolve`,`matrix`,`sparse`,`slu`,`qr`]}})),GD,Wve=e((()=>{GD={name:`lusolve`,category:`Algebra`,syntax:[`x=lusolve(A, b)`,`x=lusolve(lu, b)`],description:`Solves the linear system A * x = b where A is an [n x n] matrix and b is a [n] column vector.`,examples:[`a = [-2, 3; 2, 1]`,`b = [11, 9]`,`x = lusolve(a, b)`],seealso:[`lup`,`slu`,`lsolve`,`usolve`,`matrix`,`sparse`]}})),KD,Gve=e((()=>{KD={name:`polynomialRoot`,category:`Algebra`,syntax:[`x=polynomialRoot(-6, 3)`,`x=polynomialRoot(4, -4, 1)`,`x=polynomialRoot(-8, 12, -6, 1)`],description:`Finds the roots of a univariate polynomial given by its coefficients starting from constant, linear, and so on, increasing in degree.`,examples:[`a = polynomialRoot(-6, 11, -6, 1)`],seealso:[`cbrt`,`sqrt`]}})),qD,Kve=e((()=>{qD={name:`qr`,category:`Algebra`,syntax:[`qr(A)`],description:"Calculates the Matrix QR decomposition. Matrix `A` is decomposed in two matrices (`Q`, `R`) where `Q` is an orthogonal matrix and `R` is an upper triangular matrix.",examples:[`qr([[1, -1,  4], [1,  4, -2], [1,  4,  2], [1,  -1, 0]])`],seealso:[`lup`,`slu`,`matrix`]}})),JD,qve=e((()=>{JD={name:`rationalize`,category:`Algebra`,syntax:[`rationalize(expr)`,`rationalize(expr, scope)`,`rationalize(expr, scope, detailed)`],description:`Transform a rationalizable expression in a rational fraction. If rational fraction is one variable polynomial then converts the numerator and denominator in canonical form, with decreasing exponents, returning the coefficients of numerator.`,examples:[`rationalize("2x/y - y/(x+1)")`,`rationalize("2x/y - y/(x+1)", true)`],seealso:[`simplify`]}})),YD,Jve=e((()=>{YD={name:`resolve`,category:`Algebra`,syntax:[`resolve(node, scope)`],description:`Recursively substitute variables in an expression tree.`,examples:[`resolve(parse("1 + x"), { x: 7 })`,`resolve(parse("size(text)"), { text: "Hello World" })`,`resolve(parse("x + y"), { x: parse("3z") })`,`resolve(parse("3x"), { x: parse("y+z"), z: parse("w^y") })`],seealso:[`simplify`,`evaluate`],mayThrow:[`ReferenceError`]}})),XD,Yve=e((()=>{XD={name:`simplify`,category:`Algebra`,syntax:[`simplify(expr)`,`simplify(expr, rules)`],description:`Simplify an expression tree.`,examples:[`simplify("3 + 2 / 4")`,`simplify("2x + x")`,`f = parse("x * (x + 2 + x)")`,`simplified = simplify(f)`,`simplified.evaluate({x: 2})`],seealso:[`simplifyCore`,`derivative`,`evaluate`,`parse`,`rationalize`,`resolve`]}})),ZD,Xve=e((()=>{ZD={name:`simplifyConstant`,category:`Algebra`,syntax:[`simplifyConstant(expr)`,`simplifyConstant(expr, options)`],description:`Replace constant subexpressions of node with their values.`,examples:[`simplifyConstant("(3-3)*x")`,`simplifyConstant(parse("z-cos(tau/8)"))`],seealso:[`simplify`,`simplifyCore`,`evaluate`]}})),QD,Zve=e((()=>{QD={name:`simplifyCore`,category:`Algebra`,syntax:[`simplifyCore(node)`],description:`Perform simple one-pass simplifications on an expression tree.`,examples:[`simplifyCore(parse("0*x"))`,`simplifyCore(parse("(x+0)*2"))`],seealso:[`simplify`,`simplifyConstant`,`evaluate`]}})),$D,Qve=e((()=>{$D={name:`slu`,category:`Algebra`,syntax:[`slu(A, order, threshold)`],description:`Calculate the Matrix LU decomposition with full pivoting. Matrix A is decomposed in two matrices (L, U) and two permutation vectors (pinv, q) where P * A * Q = L * U`,examples:[`slu(sparse([4.5, 0, 3.2, 0; 3.1, 2.9, 0, 0.9; 0, 1.7, 3, 0; 3.5, 0.4, 0, 1]), 1, 0.001)`],seealso:[`lusolve`,`lsolve`,`usolve`,`matrix`,`sparse`,`lup`,`qr`]}})),eO,$ve=e((()=>{eO={name:`symbolicEqual`,category:`Algebra`,syntax:[`symbolicEqual(expr1, expr2)`,`symbolicEqual(expr1, expr2, options)`],description:`Returns true if the difference of the expressions simplifies to 0`,examples:[`symbolicEqual("x*y","y*x")`,`symbolicEqual("abs(x^2)", "x^2")`,`symbolicEqual("abs(x)", "x", {context: {abs: {trivial: true}}})`],seealso:[`simplify`,`evaluate`]}})),tO,eye=e((()=>{tO={name:`usolve`,category:`Algebra`,syntax:[`x=usolve(U, b)`],description:`Finds one solution of the linear system U * x = b where U is an [n x n] upper triangular matrix and b is a [n] column vector.`,examples:[`x=usolve(sparse([1, 1, 1, 1; 0, 1, 1, 1; 0, 0, 1, 1; 0, 0, 0, 1]), [1; 2; 3; 4])`],seealso:[`usolveAll`,`lup`,`lusolve`,`lsolve`,`matrix`,`sparse`]}})),nO,tye=e((()=>{nO={name:`usolveAll`,category:`Algebra`,syntax:[`x=usolve(U, b)`],description:`Finds all solutions of the linear system U * x = b where U is an [n x n] upper triangular matrix and b is a [n] column vector.`,examples:[`x=usolve(sparse([1, 1, 1, 1; 0, 1, 1, 1; 0, 0, 1, 1; 0, 0, 0, 1]), [1; 2; 3; 4])`],seealso:[`usolve`,`lup`,`lusolve`,`lsolve`,`matrix`,`sparse`]}})),rO,nye=e((()=>{rO={name:`abs`,category:`Arithmetic`,syntax:[`abs(x)`],description:`Compute the absolute value.`,examples:[`abs(3.5)`,`abs(-4.2)`],seealso:[`sign`]}}
2631)),iO,rye=e((()=>{iO={name:`add`,category:`Operators`,syntax:[`x + y`,`add(x, y)`],description:`Add two values.`,examples:[`a = 2.1 + 3.6`,`a - 3.6`,`3 + 2i`,`3 cm + 2 inch`,`"2.3" + "4"`],seealso:[`subtract`]}})),aO,iye=e((()=>{aO={name:`cbrt`,category:`Arithmetic`,syntax:[`cbrt(x)`,`cbrt(x, allRoots)`],description:"Compute the cubic root value. If x = y * y * y, then y is the cubic root of x. When `x` is a number or complex number, an optional second argument `allRoots` can be provided to return all three cubic roots. If not provided, the principal root is returned",examples:[`cbrt(64)`,`cube(4)`,`cbrt(-8)`,`cbrt(2 + 3i)`,`cbrt(8i)`,`cbrt(8i, true)`,`cbrt(27 m^3)`],seealso:[`square`,`sqrt`,`cube`,`multiply`]}})),oO,aye=e((()=>{oO={name:`ceil`,category:`Arithmetic`,syntax:[`ceil(x)`,`ceil(x, n)`,`ceil(unit, valuelessUnit)`,`ceil(unit, n, valuelessUnit)`],description:`Round a value towards plus infinity. If x is complex, both real and imaginary part are rounded towards plus infinity.`,examples:[`ceil(3.2)`,`ceil(3.8)`,`ceil(-4.2)`,`ceil(3.241cm, cm)`,`ceil(3.241cm, 2, cm)`],seealso:[`floor`,`fix`,`round`]}})),sO,oye=e((()=>{sO={name:`cube`,category:`Arithmetic`,syntax:[`cube(x)`],description:`Compute the cube of a value. The cube of x is x * x * x.`,examples:[`cube(2)`,`2^3`,`2 * 2 * 2`],seealso:[`multiply`,`square`,`pow`]}})),cO,sye=e((()=>
2631{cO={name:`divide`,category:`Operators`,syntax:[`x / y`,`divide(x, y)`],description:`Divide two values.`,examples:[`a = 2 / 3`,`a * 3`,`4.5 / 2`,`3 + 4 / 2`,`(3 + 4) / 2`,`18 km / 4.5`],seealso:[`multiply`]}})),lO,cye=e((()=>{lO={name:`dotDivide`,category:`Operators`,syntax:[`x ./ y`,`dotDivide(x, y)`],description:`Divide two values element wise.`,examples:[`a = [1, 2, 3; 4, 5, 6]`,`b = [2, 1, 1; 3, 2, 5]`,`a ./ b`],seealso:[`multiply`,`dotMultiply`,`divide`]}})),uO,lye=e((()=>{uO={name:`dotMultiply`,category:`Operators`,syntax:[`x .* y`,`dotMultiply(x, y)`],description:`Multiply two values element wise.`,examples:[`a = [1, 2, 3; 4, 5, 6]`,`b = [2, 1, 1; 3, 2, 5]`,`a .* b`],seealso:[`multiply`,`divide`,`dotDivide`]}})),dO,uye=e((()=>{dO={name:`dotPow`,category:`Operators`,syntax:[`x .^ y`,`dotPow(x, y)`],description:`Calculates the power of x to y element wise.`,examples:[`a = [1, 2, 3; 4, 5, 6]`,`a .^ 2`],seealso:[`pow`]}})),fO,dye=e((()=>{fO={name:`exp`,category:`Arithmetic`,syntax:[`exp(x)`],description:`Calculate the exponent of a value.`,examples:[`exp(1.3)`,`e ^ 1.3`,`log(exp(1.3))`,`x = 2.4`,`(exp(i*x) == cos(x) + i*sin(x))   # Euler's formula`],seealso:[`expm`,`expm1`,`pow`,`log`]}})),pO,fye=e((()=>{pO={name:`expm`,category:`Arithmetic`,syntax:[`exp(x)`],description:`Compute the matrix exponential, expm(A) = e^A. The matrix must be square. Not to be confused with exp(a), which performs element-wise exponentiation.`,examples:[`expm([[0,2],[0,0]])`],seealso:[`exp`]}})),mO,pye=e((()=>{mO={name:`expm1`,category:`Arithmetic`,syntax:[`expm1(x)`],description:`Calculate the value of subtracting 1 from the exponential value.`,examples:[`expm1(2)`,`pow(e, 2) - 1`,`log(expm1(2) + 1)`],seealso:[`exp`,`pow`,`log`]}})),hO,mye=e((()=>{hO={name:`fix`,category:`Arithmetic`,syntax:[`fix(x)`,`fix(x, n)`,`fix(unit, valuelessUnit)`,`fix(unit, n, valuelessUnit)`],description:`Round a value towards zero. If x is complex, both real and imaginary part are rounded towards zero.`,examples:[`fix(3.2)`,`fix(3.8)`,`fix(-4.2)`,`fix(-4.8)`,`fix(3.241cm, cm)`,`fix(3.241cm, 2, cm)`],seealso:[`ceil`,`floor`,`round`]}})),gO,hye=e((()=>{gO={name:`floor`,category:`Arithmetic`,syntax:[`floor(x)`,`floor(x, n)`,`floor(unit, valuelessUnit)`,`floor(unit, n, valuelessUnit)`],description:`Round a value towards minus infinity.If x is complex, both real and imaginary part are rounded towards minus infinity.`,examples:[`floor(3.2)`,`floor(3.8)`,`floor(-4.2)`,`floor(3.241cm, cm)`,`floor(3.241cm, 2, cm)`],seealso:[`ceil`,`fix`,`round`]}})),_O,gye=e((()=>{_O={name:`gcd`,category:`Arithmetic`,syntax:[`gcd(a, b)`,`gcd(a, b, c, ...)`],description:`Compute the greatest common divisor.`,examples:[`gcd(8, 12)`,`gcd(-4, 6)`,`gcd(25, 15, -10)`],seealso:[`lcm`,`xgcd`]}})),vO,_ye=e((()=>{vO={name:`hypot`,category:`Arithmetic`,syntax:[`hypot(a, b, c, ...)`,`hypot([a, b, c, ...])`],description:`Calculate the hypotenuse of a list with values.`,examples:[`hypot(3, 4)`,`sqrt(3^2 + 4^2)`,`hypot(-2)`,`hypot([3, 4, 5])`],seealso:[`abs`,`norm`]}})),yO,vye=e((()=>{yO={name:`invmod`,category:`Arithmetic`,syntax:[`invmod(a, b)`],description:`Calculate the (modular) multiplicative inverse of a modulo b. Solution to the equation ax ≣ 1 (mod b)`,examples:[`invmod(8, 12)`,`invmod(7, 13)`,`invmod(15151, 15122)`],seealso:[`gcd`,`xgcd`]}})),bO,yye=e((()=>{bO={name:`lcm`,category:`Arithmetic`,syntax:[`lcm(x, y)`],description:`Compute the least common multiple.`,examples:[`lcm(4, 6)`,`lcm(6, 21)`,`lcm(6, 21, 5)`],seealso:[`gcd`]}})),xO,bye=e((()=>{xO={name:`log`,category:`Arithmetic`,syntax:[`log(x)`,`log(x, base)`],description:`Compute the logarithm of a value. If no base is provided, the natural logarithm of x is calculated. If base if provided, the logarithm is calculated for the specified base. log(x, base) is defined as log(x) / log(base).`,examples:[`log(3.5)`,`a = log(2.4)`,`exp(a)`,`10 ^ 4`,`log(10000, 10)`,`log(10000) / log(10)`,`b = log(1024, 2)`,`2 ^ b`],seealso:[`exp`,`log1p`,`log2`,`log10`]}})),SO,xye=e((()=>{SO={name:`log10`,category:`Arithmetic`,syntax:[`log10(x)`],description:`Compute the 10-base logarithm of a value.`,examples:[`log10(0.00001)`,`log10(10000)`,`10 ^ 4`,`log(10000) / log(10)`,`log(10000, 10)`],seealso:[`exp`,`log`]}})),CO,Sye=e((()=>{CO={name:`log1p`,category:`Arithmetic`,syntax:[`log1p(x)`,`log1p(x, base)`],description:"Calculate the logarithm of a `value+1`",examples:[`log1p(2.5)`,`exp(log1p(1.4))`,`pow(10, 4)`,`log1p(9999, 10)`,`log1p(9999) / log(10)`],seealso:[`exp`,`log`,`log2`,`log10`]}})),wO,Cye=e((()=>{wO={name:`log2`,category:`Arithmetic`,syntax:[`log2(x)`],description:"Calculate the 2-base of a value. This is the same as calculating `log(x, 2)`.",examples:[`log2(0.03125)`,`log2(16)`,`log2(16) / log2(2)`,`pow(2, 4)`],seealso:[`exp`,`log1p`,`log`,`log10`]}})),TO,wye=e((()=>{TO={name:`mod`,category:`Operators`,syntax:[`x % y`,`x mod y`,`mod(x, y)`],description:`Calculates the modulus, the remainder of an integer division.`,examples:[`7 % 3`,`11 % 2`,`10 mod 4`,`isOdd(x) = x % 2`,`isOdd(2)`,`isOdd(3)`],seealso:[`divide`]}})),EO,Tye=e((()=>{EO={name:`multiply`,category:`Operators`,syntax:[`x * y`,`multiply(x, y)`],description:`multiply two values.`,examples:[`a = 2.1 * 3.4`,`a / 3.4`,`2 * 3 + 4`,`2 * (3 + 4)`,`3 * 2.1 km`],seealso:[`divide`]}}
2631)),DO,Eye=e((()=>{DO={name:`norm`,category:`Arithmetic`,syntax:[`norm(x)`,`norm(x, p)`],description:`Calculate the norm of a number, vector or matrix.`,examples:[`abs(-3.5)`,`norm(-3.5)`,`norm(3 - 4i)`,`norm([1, 2, -3], Infinity)`,`norm([1, 2, -3], -Infinity)`,`norm([3, 4], 2)`,`norm([[1, 2], [3, 4]], 1)`,`norm([[1, 2], [3, 4]], "inf")`,`norm([[1, 2], [3, 4]], "fro")`]}})),OO,Dye=e((()=>{OO={name:`nthRoot`,category:`Arithmetic`,syntax:[`nthRoot(a)`,`nthRoot(a, root)`],description:`Calculate the nth root of a value. The principal nth root of a positive real number A, is the positive real solution of the equation "x^root = A".`,examples:[`4 ^ 3`,`nthRoot(64, 3)`,`nthRoot(9, 2)`,`sqrt(9)`],seealso:[`nthRoots`,`pow`,`sqrt`]}})),kO,Oye=e((()=>{kO={name:`nthRoots`,category:`Arithmetic`,syntax:[`nthRoots(A)`,`nthRoots(A, root)`],description:`Calculate the nth roots of a value. An nth root of a positive real number A, is a positive real solution of the equation "x^root = A". This function returns an array of complex values.`,examples:[`nthRoots(1)`,`nthRoots(1, 3)`],seealso:[`sqrt`,`pow`,`nthRoot`]}})),AO,kye=e((()=>{AO={name:`pow`,category:`Operators`,syntax:[`x ^ y`,`pow(x, y)`],description:`Calculates the power of x to y, x^y.`,examples:[`2^3`,`2*2*2`,`1 + e ^ (pi * i)`,`pow([[1, 2], [4, 3]], 2)`,`pow([[1, 2], [4, 3]], -1)`],seealso:[`multiply`,`nthRoot`,`nthRoots`,`sqrt`]}})),jO,Aye=e((()=>{jO={name:`round`,category:`Arithmetic`,syntax:[`round(x)`,`round(x, n)`,`round(unit, valuelessUnit)`,`round(unit, n, valuelessUnit)`],description:`round a value towards the nearest integer.If x is complex, both real and imaginary part are rounded towards the nearest integer. When n is specified, the value is rounded to n decimals.`,examples:[`round(3.2)`,`round(3.8)`,`round(-4.2)`,`round(-4.8)`,`round(pi, 3)`,`round(123.45678, 2)`,`round(3.241cm, 2, cm)`,`round([3.2, 3.8, -4.7])`],seealso:[`ceil`,`floor`,`fix`]}})),MO,jye=e((()=>{MO={name:`sign`,category:`Arithmetic`,syntax:[`sign(x)`],description:`Compute the sign of a value. The sign of a value x is 1 when x>0, -1 when x<0, and 0 when x=0.`,examples:[`sign(3.5)`,`sign(-4.2)`,`sign(0)`],seealso:[`abs`]}})),NO,Mye=e((()=>{NO={name:`sqrt`,category:`Arithmetic`,syntax:[`sqrt(x)`],description:`Compute the square root value. If x = y * y, then y is the square root of x.`,examples:[`sqrt(25)`,`5 * 5`,`sqrt(-1)`],seealso:[`square`,`sqrtm`,`multiply`,`nthRoot`,`nthRoots`,`pow`]}})),PO,Nye=e((()=>{PO={name:`sqrtm`,category:`Arithmetic`,syntax:[`sqrtm(x)`],description:"Calculate the principal square root of a square matrix. The principal square root matrix `X` of another matrix `A` is such that `X * X = A`.",examples:[`sqrtm([[33, 24], [48, 57]])`],seealso:[`sqrt`,`abs`,`square`,`multiply`]}})),FO,Pye=e((()=>{FO={name:`sylvester`,category:`Algebra`,syntax:[`sylvester(A,B,C)`],description:`Solves the real-valued Sylvester equation AX+XB=C for X`,examples:[`sylvester([[-1, -2], [1, 1]], [[-2, 1], [-1, 2]], [[-3, 2], [3, 0]])`,`A = [[-1, -2], [1, 1]]; B = [[2, -1], [1, -2]]; C = [[-3, 2], [3, 0]]`,`sylvester(A, B, C)`],seealso:[`schur`,`lyap`]}})),IO,Fye=e((()=>{IO={name:`schur`,category:`Algebra`,syntax:[`schur(A)`],description:`Performs a real Schur decomposition of the real matrix A = UTU'`,examples:[`schur([[1, 0], [-4, 3]])`,`A = [[1, 0], [-4, 3]]`,`schur(A)`],seealso:[`lyap`,`sylvester`]}})),LO,Iye=e((()=>{LO={name:`lyap`,category:`Algebra`,syntax:[`lyap(A,Q)`],description:`Solves the Continuous-time Lyapunov equation AP+PA'+Q=0 for P`,examples:[`lyap([[-2, 0], [1, -4]], [[3, 1], [1, 3]])`,`A = [[-2, 0], [1, -4]]`,`Q = [[3, 1], [1, 3]]`,`lyap(A,Q)`],seealso:[`schur`,`sylvester`]}})),RO,Lye=e((()=>{RO={name:`square`,category:`Arithmetic`,syntax:[`square(x)`],description:`Compute the square of a value. The square of x is x * x.`,examples:[`square(3)`,`sqrt(9)`,`3^2`,`3 * 3`],seealso:[`multiply`,`pow`,`sqrt`,`cube`]}})),zO,Rye=e((()=>{zO={name:`subtract`,category:`Operators`,syntax:[`x - y`,`subtract(x, y)`],description:`subtract two values.`,examples:[`a = 5.3 - 2`,`a + 2`,`2/3 - 1/6`,`2 * 3 - 3`,`2.1 km - 500m`],seealso:[`add`]}})),BO,zye=e((()=>{BO={name:`unaryMinus`,category:`Operators`,syntax:[`-x`,`unaryMinus(x)`],description:`Inverse the sign of a value. Converts booleans and strings to numbers.`,examples:[`-4.5`,`-(-5.6)`,`-"22"`],seealso:[`add`,`subtract`,`unaryPlus`]}}
2631)),VO,Bye=e((()=>{VO={name:`unaryPlus`,category:`Operators`,syntax:[`+x`,`unaryPlus(x)`],description:`Converts booleans and strings to numbers.`,examples:[`+true`,`+"2"`],seealso:[`add`,`subtract`,`unaryMinus`]}})),HO,Vye=e((()=>{HO={name:`xgcd`,category:`Arithmetic`,syntax:[`xgcd(a, b)`],description:`Calculate the extended greatest common divisor for two values. The result is an array [d, x, y] with 3 entries, where d is the greatest common divisor, and d = x * a + y * b.`,examples:[`xgcd(8, 12)`,`gcd(8, 12)`,`xgcd(36163, 21199)`],seealso:[`gcd`,`lcm`]}})),UO,Hye=e((()=>{UO={name:`num`,category:`Fraction`,syntax:[`num(x)`],description:`Get the numerator of a fraction.`,examples:[`num(fraction(2, 3))`,`num(fraction(5, 8))`],seealso:[`den`,`fraction`]}})),WO,Uye=e((()=>{WO={name:`den`,category:`Fraction`,syntax:[`den(x)`],description:`Get the denominator of a fraction.`,examples:[`den(fraction(2, 3))`,`den(fraction(5, 8))`],seealso:[`num`,`fraction`]}})),GO,Wye=e((()=>{GO={name:`bitAnd`,category:`Bitwise`,syntax:[`x & y`,`bitAnd(x, y)`],description:`Bitwise AND operation. Performs the logical AND operation on each pair of the corresponding bits of the two given values by multiplying them. If both bits in the compared position are 1, the bit in the resulting binary representation is 1, otherwise, the result is 0`,examples:[`5 & 3`,`bitAnd(53, 131)`,`[1, 12, 31] & 42`],seealso:[`bitNot`,`bitOr`,`bitXor`,`leftShift`,`rightArithShift`,`rightLogShift`]}})),KO,Gye=e((()=>{KO={name:`bitNot`,category:`Bitwise`,syntax:[`~x`,`bitNot(x)`],description:`Bitwise NOT operation. Performs a logical negation on each bit of the given value. Bits that are 0 become 1, and those that are 1 become 0.`,examples:[`~1`,`~2`,`bitNot([2, -3, 4])`],seealso:[`bitAnd`,`bitOr`,`bitXor`,`leftShift`,`rightArithShift`,`rightLogShift`]}})),qO,Kye=e((()=>{qO={name:`bitOr`,category:`Bitwise`,syntax:[`x | y`,`bitOr(x, y)`],description:`Bitwise OR operation. Performs the logical inclusive OR operation on each pair of corresponding bits of the two given values. The result in each position is 1 if the first bit is 1 or the second bit is 1 or both bits are 1, otherwise, the result is 0.`,examples:[`5 | 3`,`bitOr([1, 2, 3], 4)`],seealso:[`bitAnd`,`bitNot`,`bitXor`,`leftShift`,`rightArithShift`,`rightLogShift`]}})),JO,qye=e((()=>{JO={name:`bitXor`,category:`Bitwise`,syntax:[`bitXor(x, y)`],description:`Bitwise XOR operation, exclusive OR. Performs the logical exclusive OR operation on each pair of corresponding bits of the two given values. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1.`,examples:[`bitOr(1, 2)`,`bitXor([2, 3, 4], 4)`],seealso:[`bitAnd`,`bitNot`,`bitOr`,`leftShift`,`rightArithShift`,`rightLogShift`]}})),YO,Jye=e((()=>{YO={name:`leftShift`,category:`Bitwise`,syntax:[`x << y`,`leftShift(x, y)`],description:`Bitwise left logical shift of a value x by y number of bits.`,examples:[`4 << 1`,`8 >> 1`],seealso:[`bitAnd`,`bitNot`,`bitOr`,`bitXor`,`rightArithShift`,`rightLogShift`]}})),XO,Yye=e((()=>{XO={name:`rightArithShift`,category:`Bitwise`,syntax:[`x >> y`,`rightArithShift(x, y)`],description:`Bitwise right arithmetic shift of a value x by y number of bits.`,examples:[`8 >> 1`,`4 << 1`,`-12 >> 2`],seealso:[`bitAnd`,`bitNot`,`bitOr`,`bitXor`,`leftShift`,`rightLogShift`]}})),ZO,Xye=e((()=>{ZO={name:`rightLogShift`,category:`Bitwise`,syntax:[`x >>> y`,`rightLogShift(x, y)`],description:`Bitwise right logical shift of a value x by y number of bits.`,examples:[`8 >>> 1`,`4 << 1`,`-12 >>> 2`],seealso:[`bitAnd`,`bitNot`,`bitOr`,`bitXor`,`leftShift`,`rightArithShift`]}})),QO,Zye=e((()=>{QO={name:`bellNumbers`,category:`Combinatorics`,syntax:[`bellNumbers(n)`],description:"The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S. `bellNumbers` only takes integer arguments. The following condition must be enforced: n >= 0.",examples:[`bellNumbers(3)`,`bellNumbers(8)`],seealso:[`stirlingS2`]}})),$O,Qye=e((()=>{$O={name:`catalan`,category:`Combinatorics`,syntax:[`catalan(n)`],description:`The Catalan Numbers enumerate combinatorial structures of many different types. catalan only takes integer arguments. The following condition must be enforced: n >= 0.`,examples:[`catalan(3)`,`catalan(8)`],seealso:[`bellNumbers`]}})),ek,$ye=e((()=>{ek={name:`composition`,category:`Combinatorics`,syntax:[`composition(n, k)`],description:`The composition counts of n into k parts. composition only takes integer arguments. The following condition must be enforced: k <= n.`,examples:[`composition(5, 3)`],seealso:[`combinations`]}})),tk,ebe=e((()=>{tk={name:`stirlingS2`,category:`Combinatorics`,syntax:[`stirlingS2
2631(n, k)`],description:"The Stirling numbers of the second kind, counts the number of ways to partition a set of n labelled objects into k nonempty unlabelled subsets. `stirlingS2` only takes integer arguments. The following condition must be enforced: k <= n. If n = k or k = 1, then s(n,k) = 1.",examples:[`stirlingS2(5, 3)`],seealso:[`bellNumbers`,`bernoulli`]}})),nk,tbe=e((()=>{nk={name:`arg`,category:`Complex`,syntax:[`arg(x)`],description:`Compute the argument of a complex value. If x = a+bi, the argument is computed as atan2(b, a).`,examples:[`arg(2 + 2i)`,`atan2(3, 2)`,`arg(2 + 3i)`],seealso:[`re`,`im`,`conj`,`abs`]}})),rk,nbe=e((()=>{rk={name:`conj`,category:`Complex`,syntax:[`conj(x)`],description:`Compute the complex conjugate of a complex value. If x = a+bi, the complex conjugate is a-bi.`,examples:[`conj(2 + 3i)`,`conj(2 - 3i)`,`conj(-5.2i)`],seealso:[`re`,`im`,`abs`,`arg`]}})),ik,rbe=e((()=>{ik={name:`im`,category:`Complex`,syntax:[`im(x)`],description:`Get the imaginary part of a complex number.`,examples:[`im(2 + 3i)`,`re(2 + 3i)`,`im(-5.2i)`,`im(2.4)`],seealso:[`re`,`conj`,`abs`,`arg`]}})),ak,ibe=e((()=>{ak={name:`re`,category:`Complex`,syntax:[`re(x)`],description:`Get the real part of a complex number.`,examples:[`re(2 + 3i)`,`im(2 + 3i)`,`re(-5.2i)`,`re(2.4)`],seealso:[`im`,`conj`,`abs`,`arg`]}})),ok,abe=e((()=>{ok={name:`evaluate`,category:`Expression`,syntax:[`evaluate(expression)`,`evaluate(expression, scope)`,`evaluate([expr1, expr2, expr3, ...])`,`evaluate([expr1, expr2, expr3, ...], scope)`],description:`Evaluate an expression or an array with expressions.`,examples:[`evaluate("2 + 3")`,`evaluate("sqrt(16)")`,`evaluate("2 inch to cm")`,`evaluate("sin(x * pi)", { "x": 1/2 })`,`evaluate(["width=2", "height=4","width*height"])`],seealso:[`parser`,`parse`,`compile`]}})),sk,obe=e((()=>{sk={name:`parser`,category:`Expression`,syntax:[`parser()`],description:`Create a parser object that keeps a context of variables and their values, allowing the evaluation of expressions in that context.`,examples:[`myParser = parser()`,`myParser.evaluate("sqrt(3^2 + 4^2)")`,`myParser.set("x", 3)`,`myParser.evaluate("y = x + 3")`,`myParser.evaluate(["y = x + 3", "y = y + 1"])`,`myParser.get("y")`],seealso:[`evaluate`,`parse`,`compile`]}})),ck,sbe=e((()=>{ck={name:`parse`,category:`Expression`,syntax:[`parse(expr)`,`parse(expr, options)`,`parse([expr1, expr2, expr3, ...])`,`parse([expr1, expr2, expr3, ...], options)`],description:`Parse an expression. Returns a node tree, which can be evaluated by invoking node.evaluate() or transformed into a functional object via node.compile().`,examples:[`node1 = parse("sqrt(3^2 + 4^2)")`,`node1.evaluate()`,`code1 = node1.compile()`,`code1.evaluate()`,`scope = {a: 3, b: 4}`,`node2 = parse("a * b")`,`node2.evaluate(scope)`,`code2 = node2.compile()`,`code2.evaluate(scope)`],seealso:[`parser`,`evaluate`,`compile`]}})),lk,cbe=e((()=>{lk={name:`compile`,category:`Expression`,syntax:[`compile(expr) `,`compile([expr1, expr2, expr3, ...])`],description:`Parse and compile an expression. Returns a an object with a function evaluate([scope]) to evaluate the compiled expression.`,examples:[`code1 = compile("sqrt(3^2 + 4^2)")`,`code1.evaluate() `,`code2 = compile("a * b")`,`code2.evaluate({a: 3, b: 4})`],seealso:[`parser`,`parse`,`evaluate`]}})),uk,lbe=e((()=>{uk={name:`help`,category:`Expression`,syntax:[`help(object)`,`help(string)`],description:`Display documentation on a function or data type.`,examples:[`help(sqrt)`,`help("complex")`],seealso:[]}})),dk,ube=e((()=>{dk={name:`distance`,category:`Geometry`,syntax:[`distance([x1, y1], [x2, y2])`,`distance([[x1, y1], [x2, y2]])`],description:`Calculates the Euclidean distance between two points.`,examples:[`distance([0,0], [4,4])`,`distance([[0,0], [4,4]])`],seealso:[]}})),fk,dbe=e((()=>{fk={name:`intersect`,category:`Geometry`,syntax:[`intersect(expr1, expr2, expr3, expr4)`,`intersect(expr1, expr2, expr3)`],description:`Computes the intersection point of lines and/or planes.`,examples:[`intersect([0, 0], [10, 10], [10, 0], [0, 10])`,`intersect([1, 0, 1],  [4, -2, 2], [1, 1, 1, 6])`],seealso:[]}})),pk,fbe=e((()=>{pk={name:`and`,category:`Logical`,syntax:[`x and y`,`and(x, y)`],description:`Logical and. Test whether two values are both defined with a nonzero/nonempty value.`,examples:[`true and false`,`true and true`,`2 and 4`],seealso:[`not`,`or`,`xor`]}})),mk,pbe=e((()=>
2631{mk={name:`not`,category:`Logical`,syntax:[`not x`,`not(x)`],description:`Logical not. Flips the boolean value of given argument.`,examples:[`not true`,`not false`,`not 2`,`not 0`],seealso:[`and`,`or`,`xor`]}})),hk,mbe=e((()=>{hk={name:`nullish`,category:`Logical`,syntax:[`x ?? y`,`nullish(x, y)`],description:`Nullish coalescing operator. Returns the right-hand operand when the left-hand operand is null or undefined, and otherwise returns the left-hand operand.`,examples:[`null ?? 42`,`undefined ?? 42`,`0 ?? 42`,`false ?? 42`,`null ?? undefined ?? 42`],seealso:[`and`,`or`,`not`]}})),gk,hbe=e((()=>{gk={name:`or`,category:`Logical`,syntax:[`x or y`,`or(x, y)`],description:`Logical or. Test if at least one value is defined with a nonzero/nonempty value.`,examples:[`true or false`,`false or false`,`0 or 4`],seealso:[`not`,`and`,`xor`]}})),_k,gbe=e((()=>{_k={name:`xor`,category:`Logical`,syntax:[`x xor y`,`xor(x, y)`],description:`Logical exclusive or, xor. Test whether one and only one value is defined with a nonzero/nonempty value.`,examples:[`true xor false`,`false xor false`,`true xor true`,`0 xor 4`],seealso:[`not`,`and`,`or`]}})),vk,_be=e((()=>{vk={name:`mapSlices`,category:`Matrix`,syntax:[`mapSlices(A, dim, callback)`],description:`Generate a matrix one dimension less than A by applying callback to each slice of A along dimension dim.`,examples:[`A = [[1, 2], [3, 4]]`,`mapSlices(A, 1, sum)`,`mapSlices(A, 2, prod)`],seealso:[`map`,`forEach`]}})),yk,vbe=e((()=>{yk={name:`column`,category:`Matrix`,syntax:[`column(x, index)`],description:`Return a column from a matrix or array.`,examples:[`A = [[1, 2], [3, 4]]`,`column(A, 1)`,`column(A, 2)`],seealso:[`row`,`matrixFromColumns`]}})),bk,ybe=e((()=>{bk={name:`concat`,category:`Matrix`,syntax:[`concat(A, B, C, ...)`,`concat(A, B, C, ..., dim)`],description:`Concatenate matrices. By default, the matrices are concatenated by the last dimension. The dimension on which to concatenate can be provided as last argument.`,examples:[`A = [1, 2; 5, 6]`,`B = [3, 4; 7, 8]`,`concat(A, B)`,`concat(A, B, 1)`,`concat(A, B, 2)`],seealso:[`det`,`diag`,`identity`,`inv`,`ones`,`range`,`size`,`squeeze`,`subset`,`trace`,`transpose`,`zeros`]}})),xk,bbe=e((()=>{xk={name:`count`,category:`Matrix`,syntax:[`count(x)`],description:`Count the number of elements of a matrix, array or string.`,examples:[`a = [1, 2; 3, 4; 5, 6]`,`count(a)`,`size(a)`,`count("hello world")`],seealso:[`size`]}})),Sk,xbe=e((()=>{Sk={name:`cross`,category:`Matrix`,syntax:[`cross(A, B)`],description:`Calculate the cross product for two vectors in three dimensional space.`,examples:[`cross([1, 1, 0],  [0, 1, 1])`,`cross([3, -3, 1], [4, 9, 2])`,`cross([2, 3, 4],  [5, 6, 7])`],seealso:[`multiply`,`dot`]}})),Ck,Sbe=e((()=>{Ck={name:`ctranspose`,category:`Matrix`,syntax:[`x'`,`ctranspose(x)`],description:`Complex Conjugate and Transpose a matrix`,examples:[`a = [1, 2, 3; 4, 5, 6]`,`a'`,`ctranspose(a)`],seealso:[`concat`,`det`,`diag`,`identity`,`inv`,`ones`,`range`,`size`,`squeeze`,`subset`,`trace`,`zeros`]}})),wk,Cbe=e((()=>{wk={name:`det`,category:`Matrix`,syntax:[`det(x)`],description:`Calculate the determinant of a matrix`,examples:[`det([1, 2; 3, 4])`,`det([-2, 2, 3; -1, 1, 3; 2, 0, -1])`],seealso:[`concat`,`diag`,`identity`,`inv`,`ones`,`range`,`size`,`squeeze`,`subset`,`trace`,`transpose`,`zeros`]}})),Tk,wbe=e((()=>{Tk={name:`diag`,category:`Matrix`,syntax:[`diag(x)`,`diag(x, k)`],description:`Create a diagonal matrix or retrieve the diagonal of a matrix. When x is a vector, a matrix with the vector values on the diagonal will be returned. When x is a matrix, a vector with the diagonal values of the matrix is returned. When k is provided, the k-th diagonal will be filled in or retrieved, if k is positive, the values are placed on the super diagonal. When k is negative, the values are placed on the sub diagonal.`,examples:[`diag(1:3)`,`diag(1:3, 1)`,`a = [1, 2, 3; 4, 5, 6; 7, 8, 9]`,`diag(a)`],seealso:[`concat`,`det`,`identity`,`inv`,`ones`,`range`,`size`,`squeeze`,`subset`,`trace`,`transpose`,`zeros`]}})),Ek,Tbe=e((()=>{Ek={name:`diff`,category:`Matrix`,syntax:[`diff(arr)`,`diff(arr, dim)`],description:[`Create a new matrix or array with the difference of the passed matrix or array.`,`Dim parameter is optional and used to indicate the dimension of the array/matrix to apply the difference`,`If no dimension parameter is passed it is assumed as dimension 0`,`Dimension is zero-based in javascript and one-based in the parser`,`Arrays must be 'rectangular' meaning arrays like [1, 2]`,`If something is passed as a matrix it will be returned as a matrix but other than that all matrices are converted to arrays`],examples:[`A = [1, 2, 4, 7, 0]`,`diff(A)`,`diff(A, 1)`,`B = [[1, 2], [3, 4]]`,`diff(B)`,`diff(B, 1)`,`diff(B, 2)`,`diff(B, bignumber(2))`,`diff([[1, 2], matrix([3, 4])], 2)`],seealso:[`subtract`,`partitionSelect`]}})),Dk,Ebe=e((()=>{Dk={name:`dot`,category:`Matrix`,syntax:[`dot(A, B)`,`A * B`],description:`Calculate the dot product of two vectors. The dot product of A = [a1, a2, a3, ..., an] and B = [b1, b2, b3, ..., bn] is defined as dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn`,examples:[`dot([2, 4, 1], [2, 2, 3])`,`[2, 4, 1] * [2, 2, 3]`],seealso:[`multiply`,`
2631cross`]}})),Ok,Dbe=e((()=>{Ok={name:`eigs`,category:`Matrix`,syntax:[`eigs(x)`],description:`Calculate the eigenvalues and optionally eigenvectors of a square matrix`,examples:[`eigs([[5, 2.3], [2.3, 1]])`,`eigs([[1, 2, 3], [4, 5, 6], [7, 8, 9]], { precision: 1e-6, eigenvectors: false })`],seealso:[`inv`]}})),kk,Obe=e((()=>{kk={name:`filter`,category:`Matrix`,syntax:[`filter(x, test)`],description:`Filter items in a matrix.`,examples:[`isPositive(x) = x > 0`,`filter([6, -2, -1, 4, 3], isPositive)`,`filter([6, -2, 0, 1, 0], x != 0)`],seealso:[`sort`,`map`,`forEach`]}})),Ak,kbe=e((()=>{Ak={name:`flatten`,category:`Matrix`,syntax:[`flatten(x)`],description:`Flatten a multi dimensional matrix into a single dimensional matrix.`,examples:[`a = [1, 2, 3; 4, 5, 6]`,`size(a)`,`b = flatten(a)`,`size(b)`],seealso:[`concat`,`resize`,`size`,`squeeze`]}})),jk,Abe=e((()=>{jk={name:`forEach`,category:`Matrix`,syntax:[`forEach(x, callback)`],description:`Iterates over all elements of a matrix/array, and executes the given callback function.`,examples:[`numberOfPets = {}`,`addPet(n) = numberOfPets[n] = (numberOfPets[n] ? numberOfPets[n]:0 ) + 1;`,`forEach(["Dog","Cat","Cat"], addPet)`,`numberOfPets`],seealso:[`map`,`sort`,`filter`]}})),Mk,jbe=e((()=>{Mk={name:`getMatrixDataType`,category:`Matrix`,syntax:[`getMatrixDataType(x)`],description:`Find the data type of all elements in a matrix or array, for example "number" if all items are a number and "Complex" if all values are complex numbers. If a matrix contains more than one data type, it will return "mixed".`,examples:[`getMatrixDataType([1, 2, 3])`,`getMatrixDataType([[5 cm], [2 inch]])`,`getMatrixDataType([1, "text"])`,`getMatrixDataType([1, bignumber(4)])`],seealso:[`matrix`,`sparse`,`typeOf`]}})),Nk,Mbe=e((()=>{Nk={name:`identity`,category:`Matrix`,syntax:[`identity(n)`,`identity(m, n)`,`identity([m, n])`],description:`Returns the identity matrix with size m-by-n. The matrix has ones on the diagonal and zeros elsewhere.`,examples:[`identity(3)`,`identity(3, 5)`,`a = [1, 2, 3; 4, 5, 6]`,`identity(size(a))`],seealso:[`concat`,`det`,`diag`,`inv`,`ones`,`range`,`size`,`squeeze`,`subset`,`trace`,`transpose`,`zeros`]}})),Pk,Nbe=e((()=>{Pk={name:`inv`,category:`Matrix`,syntax:[`inv(x)`],description:`Calculate the inverse of a matrix`,examples:[`inv([1, 2; 3, 4])`,`inv(4)`,`1 / 4`],seealso:[`concat`,`det`,`diag`,`identity`,`ones`,`range`,`size`,`squeeze`,`subset`,`trace`,`transpose`,`zeros`]}})),Fk,Pbe=e((()=>{Fk={name:`pinv`,category:`Matrix`,syntax:[`pinv(x)`],description:`Calculate the Moore–Penrose inverse of a matrix`,examples:[`pinv([1, 2; 3, 4])`,`pinv([[1, 0], [0, 1], [0, 1]])`,`pinv(4)`],seealso:[`inv`]}})),Ik,Fbe=e((()=>{Ik={name:`kron`,category:`Matrix`,syntax:[`kron(x, y)`],description:`Calculates the Kronecker product of 2 matrices or vectors.`,examples:[`kron([[1, 0], [0, 1]], [[1, 2], [3, 4]])`,`kron([1,1], [2,3,4])`],seealso:[`multiply`,`dot`,`cross`]}})),Lk,Ibe=e((()=>{Lk={name:`map`,category:`Matrix`,syntax:[`map(x, callback)`,`map(x, y, ..., callback)`],description:`Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array or the matrices/arrays.`,examples:[`map([1, 2, 3], square)`,`map([1, 2], [3, 4], f(a,b) = a + b)`],seealso:[`filter`,`forEach`]}})),Rk,Lbe=e((()=>{Rk={name:`matrixFromColumns`,category:`Matrix`,syntax:[`matrixFromColumns(...arr)`,`matrixFromColumns(row1, row2)`,`matrixFromColumns(row1, row2, row3)`],description:`Create a dense matrix from vectors as individual columns.`,examples:[`matrixFromColumns([1, 2, 3], [[4],[5],[6]])`],seealso:[`matrix`,`matrixFromRows`,`matrixFromFunction`,`zeros`]}})),zk,Rbe=e((()=>{zk={name:`matrixFromFunction`,category:`Matrix`,syntax:[`matrixFromFunction(size, fn)`,`matrixFromFunction(size, fn, format)`,`matrixFromFunction(size, fn, format, datatype)`,`matrixFromFunction(size, format, fn)`,`matrixFromFunction(size, format, datatype, fn
2631)`],description:`Create a matrix by evaluating a generating function at each index.`,examples:[`f(I) = I[1] - I[2]`,`matrixFromFunction([3,3], f)`,`g(I) = I[1] - I[2] == 1 ? 4 : 0`,`matrixFromFunction([100, 100], "sparse", g)`,`matrixFromFunction([5], random)`],seealso:[`matrix`,`matrixFromRows`,`matrixFromColumns`,`zeros`]}})),Bk,zbe=e((()=>{Bk={name:`matrixFromRows`,category:`Matrix`,syntax:[`matrixFromRows(...arr)`,`matrixFromRows(row1, row2)`,`matrixFromRows(row1, row2, row3)`],description:`Create a dense matrix from vectors as individual rows.`,examples:[`matrixFromRows([1, 2, 3], [[4],[5],[6]])`],seealso:[`matrix`,`matrixFromColumns`,`matrixFromFunction`,`zeros`]}})),Vk,Bbe=e((()=>{Vk={name:`ones`,category:`Matrix`,syntax:[`ones(m)`,`ones(m, n)`,`ones(m, n, p, ...)`,`ones([m])`,`ones([m, n])`,`ones([m, n, p, ...])`],description:`Create a matrix containing ones.`,examples:[`ones(3)`,`ones(3, 5)`,`ones([2,3]) * 4.5`,`a = [1, 2, 3; 4, 5, 6]`,`ones(size(a))`],seealso:[`concat`,`det`,`diag`,`identity`,`inv`,`range`,`size`,`squeeze`,`subset`,`trace`,`transpose`,`zeros`]}})),Hk,Vbe=e((()=>{Hk={name:`partitionSelect`,category:`Matrix`,syntax:[`partitionSelect(x, k)`,`partitionSelect(x, k, compare)`],description:`Partition-based selection of an array or 1D matrix. Will find the kth smallest value, and mutates the input array. Uses Quickselect.`,examples:[`partitionSelect([5, 10, 1], 2)`,`partitionSelect(["C", "B", "A", "D"], 1, compareText)`,`arr = [5, 2, 1]`,`partitionSelect(arr, 0) # returns 1, arr is now: [1, 2, 5]`,`arr`,`partitionSelect(arr, 1, 'desc') # returns 2, arr is now: [5, 2, 1]`,`arr`],seealso:[`sort`]}})),Uk,Hbe=e((()=>{Uk={name:`range`,category:`Type`,syntax:[`start:end`,`start:step:end`,`range(start, end)`,`range(start, end, step)`,`range(string)`],description:`Create a range. Lower bound of the range is included, upper bound is excluded.`,examples:[`1:5`,`3:-1:-3`,`range(3, 7)`,`range(0, 12, 2)`,`range("4:10")`,`range(1m, 1m, 3m)`,`a = [1, 2, 3, 4; 5, 6, 7, 8]`,`a[1:2, 1:2]`],seealso:[`concat`,`det`,`diag`,`identity`,`inv`,`ones`,`size`,`squeeze`,`subset`,`trace`,`transpose`,`zeros`]}})),Wk,Ube=e((()=>{Wk={name:`reshape`,category:`Matrix`,syntax:[`reshape(x, sizes)`],description:`Reshape a multi dimensional array to fit the specified dimensions.`,examples:[`reshape([1, 2, 3, 4, 5, 6], [2, 3])`,`reshape([[1, 2], [3, 4]], [1, 4])`,`reshape([[1, 2], [3, 4]], [4])`,`reshape([1, 2, 3, 4], [-1, 2])`],seealso:[`size`,`squeeze`,`resize`]}})),Gk,Wbe=e((()=>{Gk={name:`resize`,category:`Matrix`,syntax:[`resize(x, size)`,`resize(x, size, defaultValue)`],description:`Resize a matrix.`,examples:[`resize([1,2,3,4,5], [3])`,`resize([1,2,3], [5])`,`resize([1,2,3], [5], -1)`,`resize(2, [2, 3])`,`resize("hello", [8], "!")`],seealso:[`size`,`subset`,`squeeze`,`reshape`]}})),Kk,Gbe=e((()=>{Kk={name:`rotate`,category:`Matrix`,syntax:[`rotate(w, theta)`,`rotate(w, theta, v)`],description:`Returns a 2-D rotation matrix (2x2) for a given angle (in radians). Returns a 2-D rotation matrix (3x3) of a given angle (in radians) around given axis.`,examples:[`rotate([1, 0], pi / 2)`,`rotate(matrix([1, 0]), unit("35deg"))`,`rotate([1, 0, 0], unit("90deg"), [0, 0, 1])`,`rotate(matrix([1, 0, 0]), unit("90deg"), matrix([0, 0, 1]))`],seealso:[`matrix`,`rotationMatrix`]}})),qk,Kbe=e((()=>{qk={name:`rotationMatrix`,category:`Matrix`,syntax:[`rotationMatrix(theta)`,`rotationMatrix(theta, v)`,`rotationMatrix(theta, v, format)`],description:`Returns a 2-D rotation matrix (2x2) for a given angle (in radians). Returns a 2-D rotation matrix (3x3) of a given angle (in radians) around given axis.`,examples:[`rotationMatrix(pi / 2)`,`rotationMatrix(unit("45deg"), [0, 0, 1])`,`rotationMatrix(1, matrix([0, 0, 1]), "sparse")`],seealso:[`cos`,`sin`]}})),Jk,qbe=e((()=>{Jk={name:`row`,category:`Matrix`,syntax:[`row(x, index)`],description:`Return a row from a matrix or array.`,examples:[`A = [[1, 2], [3, 4]]`,`row(A, 1)`,`row(A, 2)`],seealso:[`column`,`matrixFromRows`]}})),Yk,Jbe=e((()=>{Yk={name:`size`,category:`Matrix`,syntax:[`size(x)`],description:`Calculate the size of a matrix.`,examples:[`size(2.3)`,`size("hello world")`,`a = [1, 2; 3, 4; 5, 6]`,`size(a)`,`size(1:6)`],seealso:[`concat`,`count`,`det`,`diag`,`identity`,`inv`,`ones`,`range`,`squeeze`,`subset`,`trace`,`transpose`,`zeros`]}})),Xk,Ybe=e((()=>{Xk={name:`sort`,category:`Matrix`,syntax:[`sort(x)`,`sort(x, compare)`],description:`Sort the items in a matrix. Compare can be a string "asc", "desc", "natural", or a custom sort function.`,examples:[`sort([5, 10, 1])`,`sort(["C", "B", "A", "D"], "natural")`,`sortByLength(a, b) = size(a)[1] - size(b)[1]`,`sort(["Langdon", "Tom", "Sara"], sortByLength)`,`sort(["10", "1", "2"], "natural")`],seealso:[`map`,`filter`,`forEach`]}})),Zk,Xbe=e((()=>
2631{Zk={name:`squeeze`,category:`Matrix`,syntax:[`squeeze(x)`],description:`Remove inner and outer singleton dimensions from a matrix.`,examples:[`a = zeros(3,2,1)`,`size(squeeze(a))`,`b = zeros(1,1,3)`,`size(squeeze(b))`],seealso:[`concat`,`det`,`diag`,`identity`,`inv`,`ones`,`range`,`size`,`subset`,`trace`,`transpose`,`zeros`]}})),Qk,Zbe=e((()=>{Qk={name:`subset`,category:`Matrix`,syntax:[`value(index)`,`value(index) = replacement`,`subset(value, [index])`,`subset(value, [index], replacement)`],description:"Get or set a subset of the entries of a matrix or characters of a string. Indexes are one-based. There should be one index specification for each dimension of the target. Each specification can be a single index, a list of indices, or a range in colon notation `l:u`. In a range, both the lower bound l and upper bound u are included; and if a bound is omitted it defaults to the most extreme valid value. The cartesian product of the indices specified in each dimension determines the target of the operation.",examples:[`d = [1, 2; 3, 4]`,`e = []`,`e[1, 1:2] = [5, 6]`,`e[2, :] = [7, 8]`,`f = d * e`,`f[2, 1]`,`f[:, 1]`,`f[[1,2], [1,3]] = [9, 10; 11, 12]`,`f`],seealso:[`concat`,`det`,`diag`,`identity`,`inv`,`ones`,`range`,`size`,`squeeze`,`trace`,`transpose`,`zeros`]}})),$k,Qbe=e((()=>{$k={name:`trace`,category:`Matrix`,syntax:[`trace(A)`],description:`Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix.`,examples:[`A = [1, 2, 3; -1, 2, 3; 2, 0, 3]`,`trace(A)`],seealso:[`concat`,`det`,`diag`,`identity`,`inv`,`ones`,`range`,`size`,`squeeze`,`subset`,`transpose`,`zeros`]}})),eA,$be=e((()=>{eA={name:`transpose`,category:`Matrix`,syntax:[`x'`,`transpose(x)`],description:`Transpose a matrix`,examples:[`a = [1, 2, 3; 4, 5, 6]`,`a'`,`transpose(a)`],seealso:[`concat`,`det`,`diag`,`identity`,`inv`,`ones`,`range`,`size`,`squeeze`,`subset`,`trace`,`zeros`]}})),tA,exe=e((()=>{tA={name:`zeros`,category:`Matrix`,syntax:[`zeros(m)`,`zeros(m, n)`,`zeros(m, n, p, ...)`,`zeros([m])`,`zeros([m, n])`,`zeros([m, n, p, ...])`],description:`Create a matrix containing zeros.`,examples:[`zeros(3)`,`zeros(3, 5)`,`a = [1, 2, 3; 4, 5, 6]`,`zeros(size(a))`],seealso:[`concat`,`det`,`diag`,`identity`,`inv`,`ones`,`range`,`size`,`squeeze`,`subset`,`trace`,`transpose`]}})),nA,txe=e((()=>{nA={name:`fft`,category:`Matrix`,syntax:[`fft(x)`],description:`Calculate N-dimensional Fourier transform`,examples:[`fft([[1, 0], [1, 0]])`],seealso:[`ifft`]}})),rA,nxe=e((()=>{rA={name:`ifft`,category:`Matrix`,syntax:[`ifft(x)`],description:`Calculate N-dimensional inverse Fourier transform`,examples:[`ifft([[2, 2], [0, 0]])`],seealso:[`fft`]}})),iA,rxe=e((()=>{iA={name:`bernoulli`,category:`Probability`,syntax:[`bernoulli(n)`],description:`The nth Bernoulli number`,examples:[`bernoulli(4)`,`bernoulli(fraction(12))`],seealso:[`combinations`,`gamma`,`stirlingS2`]}})),aA,ixe=e((()=>{aA={name:`combinations`,category:`Probability`,syntax:[`combinations(n, k)`],description:`Compute the number of combinations of n items taken k at a time`,examples:[`combinations(7, 5)`],seealso:[`combinationsWithRep`,`permutations`,`factorial`]}})),oA,axe=e((()=>{oA={name:`combinationsWithRep`,category:`Probability`,syntax:[`combinationsWithRep(n, k)`],description:`Compute the number of combinations of n items taken k at a time with replacements.`,examples:[`combinationsWithRep(7, 5)`],seealso:[`combinations`,`permutations`,`factorial`]}})),sA,oxe=e((()=>{sA={name:`factorial`,category:`Probability`,syntax:[`n!`,`factorial(n)`],description:`Compute the factorial of a value`,examples:[`5!`,`5 * 4 * 3 * 2 * 1`,`3!`],seealso:[`combinations`,`combinationsWithRep`,`permutations`,`gamma`]}})),cA,sxe=e((()=>{cA={name:`gamma`,category:`Probability`,syntax:[`gamma(n)`],description:`Compute the gamma function. For small values, the Lanczos approximation is used, and for large values the extended Stirling approximation.`,examples:[`gamma(4)`,`3!`,`gamma(1/2)`,`sqrt(pi)`],seealso:[`factorial`]}})),lA,cxe=e((()=>{lA={name:`lgamma`,category:`Probability`,syntax:[`lgamma(n)`],description:`Logarithm of the gamma function for real, positive numbers and complex numbers, using Lanczos approximation for numbers and Stirling series for complex numbers.`,examples:[`lgamma(4)`,`lgamma(1/2)`,`lgamma(i)`,`lgamma(complex(1.1, 2))`],seealso:[`gamma`]}})),uA,lxe=e((()=>{uA={name:`kldivergence`,category:`Probability`,syntax:[`kldivergence(x, y)`],description:`Calculate the Kullback-Leibler 
2631(KL) divergence  between two distributions.`,examples:[`kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5])`],seealso:[]}})),dA,uxe=e((()=>{dA={name:`multinomial`,category:`Probability`,syntax:[`multinomial(A)`],description:"Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from `n` possibilities. multinomial takes one array of integers as an argument. The following condition must be enforced: every ai > 0.",examples:[`multinomial([1, 2, 1])`],seealso:[`combinations`,`factorial`]}})),fA,dxe=e((()=>{fA={name:`permutations`,category:`Probability`,syntax:[`permutations(n)`,`permutations(n, k)`],description:`Compute the number of permutations of n items taken k at a time`,examples:[`permutations(5)`,`permutations(5, 3)`],seealso:[`combinations`,`combinationsWithRep`,`factorial`]}})),pA,fxe=e((()=>{pA={name:`pickRandom`,category:`Probability`,syntax:[`pickRandom(array)`,`pickRandom(array, number)`,`pickRandom(array, weights)`,`pickRandom(array, number, weights)`,`pickRandom(array, weights, number)`],description:`Pick a random entry from a given array.`,examples:[`pickRandom(0:10)`,`pickRandom([1, 3, 1, 6])`,`pickRandom([1, 3, 1, 6], 2)`,`pickRandom([1, 3, 1, 6], [2, 3, 2, 1])`,`pickRandom([1, 3, 1, 6], 2, [2, 3, 2, 1])`,`pickRandom([1, 3, 1, 6], [2, 3, 2, 1], 2)`],seealso:[`random`,`randomInt`]}})),mA,pxe=e((()=>{mA={name:`random`,category:`Probability`,syntax:[`random()`,`random(max)`,`random(min, max)`,`random(size)`,`random(size, max)`,`random(size, min, max)`],description:`Return a random number.`,examples:[`random()`,`random(10, 20)`,`random([2, 3])`],seealso:[`pickRandom`,`randomInt`]}})),hA,mxe=e((()=>{hA={name:`randomInt`,category:`Probability`,syntax:[`randomInt(max)`,`randomInt(min, max)`,`randomInt(size)`,`randomInt(size, max)`,`randomInt(size, min, max)`],description:`Return a random integer number`,examples:[`randomInt(10, 20)`,`randomInt([2, 3], 10)`],seealso:[`pickRandom`,`random`]}})),gA,hxe=e((()=>{gA={name:`compare`,category:`Relational`,syntax:[`compare(x, y)`],description:`Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x == y.`,examples:[`compare(2, 3)`,`compare(3, 2)`,`compare(2, 2)`,`compare(5cm, 40mm)`,`compare(2, [1, 2, 3])`],seealso:[`equal`,`unequal`,`smaller`,`smallerEq`,`largerEq`,`compareNatural`,`compareText`]}})),_A,gxe=e((()=>{_A={name:`compareNatural`,category:`Relational`,syntax:[`compareNatural(x, y)`],description:`Compare two values of any type in a deterministic, natural way. Returns 1 when x > y, -1 when x < y, and 0 when x == y.`,examples:[`compareNatural(2, 3)`,`compareNatural(3, 2)`,`compareNatural(2, 2)`,`compareNatural(5cm, 40mm)`,`compareNatural("2", "10")`,`compareNatural(2 + 3i, 2 + 4i)`,`compareNatural([1, 2, 4], [1, 2, 3])`,`compareNatural([1, 5], [1, 2, 3])`,`compareNatural([1, 2], [1, 2])`,`compareNatural({a: 2}, {a: 4})`],seealso:[`equal`,`unequal`,`smaller`,`smallerEq`,`largerEq`,`compare`,`compareText`]}})),vA,_xe=e((()=>{vA={name:`compareText`,category:`Relational`,syntax:[`compareText(x, y)`],description:`Compare two strings lexically. Comparison is case sensitive. Returns 1 when x > y, -1 when x < y, and 0 when x == y.`,examples:[`compareText("B", "A")`,`compareText("A", "B")`,`compareText("A", "A")`,`compareText("2", "10")`,`compare("2", "10")`,`compare(2, 10)`,`compareNatural("2", "10")`,`compareText("B", ["A", "B", "C"])`],seealso:[`compare`,`compareNatural`]}})),yA,vxe=e((()=>{yA={name:`deepEqual`,category:`Relational`,syntax:[`deepEqual(x, y)`],description:`Check equality of two matrices element wise. Returns true if the size of both matrices is equal and when and each of the elements are equal.`,examples:[`deepEqual([1,3,4], [1,3,4])`,`deepEqual([1,3,4], [1,3])`],seealso:[`equal`,`unequal`,`smaller`,`larger`,`smallerEq`,`largerEq`,`compare`]}})),bA,yxe=e((()=>{bA={name:`equal`,category:`Relational`,syntax:[`x == y`,`equal(x, y)`],description:`Check equality of two values. Returns true if the values are equal, and false if not.`,examples:[`2+2 == 3`,`2+2 == 4`,`a = 3.2`,`b = 6-2.8`,`a == b`,`50cm == 0.5m`],seealso:[`unequal`,`smaller`,`larger`,`smallerEq`,`largerEq`,`compare`,`deepEqual`,`equalText`]}})),xA,bxe=e((()=>{xA={name:`equalText`,category:`Relational`,syntax:[`equalText(x, y)`],description:`Check equality of two strings. Comparison is case sensitive. Returns true if the values are equal, and false if not.`,examples:[`equalText("Hello", "Hello")`,`equalText("a", "A")`,`equal("2e3", "2000")`,`equalText("2e3", "2000")`,`equalText("B", ["A", "B", "C"])`],seealso:[`compare`,`compareNatural`,`compareText`,`equal`]}})),SA,xxe=e((()=>{SA={name:`larger`,category:`Relational`,syntax:[`x > y`,`larger(x, y)`],description:`Check if value x is larger than y. Returns true if x is larger than y, and false if not. Comparing a value with NaN returns false.`,examples:[`2 > 3`,`5 > 2*2`,`a = 3.3`,`b = 6-2.8`,`(a > b)`,`(b < a)`,`5 cm > 2 inch`],seealso:[`equal`,`unequal`,`smaller`,`smallerEq`,`largerEq`,`compare`]}})),CA,Sxe=e((()=>{CA={name:`largerEq`,category:`Relational`,syntax:[`x >= y`,`largerEq(x, y)`],description:`Check if value x is larger or equal to y. Returns true if x is larger or equal to y, and false if not.`,examples:[`2 >= 1+1`,`2 > 1+1`,`a = 3.2`,`b = 6-2.8`,`(a >= b)`],seealso:[`equal`,`unequal`,`smallerEq`,`smaller`,`compare`]}})),wA,Cxe=e((()=>{wA={name:`smaller`,category:`Relational`,syntax:[`x < y`,`smaller(x, y)`],description:`Check if value x is smaller than value y. Returns true if x is smaller than y, and false if not. Comparing a value with NaN returns false.`,examples:[`2 < 3`,`5 < 2*2`,`a = 3.3`,`b = 6-2.8`,`(a < b)`,`5 cm < 2 inch`],seealso:[`equal`,`unequal`,`larger`,`smallerEq`,`largerEq`,`compare`]}})),TA,wxe=e((()=>{TA={name:`smallerEq`,category:`Relational`,syntax:[`x <= y`,`smallerEq(x, y)`],description:`Check if value x is smaller or equal to value y. Returns true if x is smaller than y, and false if not.`,examples:[`2 <= 1+1`,`2 < 1+1`,`a = 3.2`,`b = 6-2.8`,`(a <= b)`],seealso:[`equal`,`unequal`,`larger`,`smaller`,`largerEq`,`compare`]}})),EA,Txe=e((()=>{EA={name:`unequal`,category:`Relational`,syntax:[`x != y`,`unequal(x, y)`],description:`Check unequality of two values. Returns true if the values are unequal, and false if they are equal.`,examples:[`2+2 != 3`,`2+2 != 4`,`a = 3.2`,`b = 6-2.8`,`a != b`,`50cm != 0.5m`,`5 cm != 2 inch`],seealso:[`equal`,`smaller`,`larger`,`smallerEq`,`largerEq`,`compare`,`deepEqual`]}})),DA,Exe=e((()=>{DA={name:`setCartesian`,category:`Set`,syntax:[`setCartesian(set1, set2)`],description:`Create the cartesian product of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays and the values will be sorted in ascending order before the operation.`,examples:[`setCartesian([1, 2], [3, 4])`],seealso:[`setUnion`,`setIntersect`,`setDifference`,`setPowerset`]}})),OA,Dxe=e((()=>{OA={name:`setDifference`,category:`Set`,syntax:[`setDifference(set1, set2)`],description:`Create the difference of two (multi)sets: every element of set1, that is not the element of set2. Multi-dimension arrays will be converted to single-dimension arrays before the operation.`,examples:[`setDifference([1, 2, 3, 4], [3, 4, 5, 6])`,`setDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])`],seealso:[`setUnion`,`setIntersect`,`setSymDifference`]}})),kA,Oxe=e((()=>{kA={name:`setDistinct`,category:`Set`,syntax:[`setDistinct(set)`],description:`Collect the distinct elements of a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.`,examples:[`setDistinct([1, 1, 1, 2, 2, 3])`],seealso:[`setMultiplicity`]}})),AA,kxe=e((()=>{AA={name:`setIntersect`,category:`Set`,syntax:[`setIntersect(set1, set2)`],description:`Create the intersection of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.`,examples:[`setIntersect([1, 2, 3, 4], [3, 4, 5, 6])`,`setIntersect([[1, 2], [3, 4]], [[3, 4], [5, 6]])`],seealso:[`setUnion`,`setDifference`]}})),jA,Axe=e((()=>{jA={name:`setIsSubset`,category:`Set`,syntax:[`setIsSubset(set1, set2)`],description:`Check whether a (multi)set is a subset of another (multi)set: every element of set1 is the element of set2. Multi-dimension arrays will be converted to single-dimension arrays before the operation.`,examples:[`setIsSubset([1, 2], [3, 4, 5, 6])`,`setIsSubset([3, 4], [3, 4, 5, 6])`],seealso:[`setUnion`,`setIntersect`,`setDifference`]}})),MA,jxe=e((()=>{MA={name:`setMultiplicity`,category:`Set`,syntax:[`setMultiplicity(element, set)`],description:`Count the multiplicity of an element in a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.`,examples:[`setMultiplicity(1, [1, 2, 2, 4])`,`setMultiplicity(2, [1, 2, 2, 4])`],seealso:[`setDistinct`,`setSize`]}})),NA,Mxe=e((()=>{NA={name:`setPowerset`,category:`Set`,syntax:[`setPowerset(set)`],description:`Create the powerset of a (multi)set: the powerset contains very possible subsets of a (multi)set. A multi-dimension array will be converted to a single-dimension array before the operation.`,examples:[`setPowerset([1, 2, 3])`],seealso:[`setCartesian`]}
2631})),PA,Nxe=e((()=>{PA={name:`setSize`,category:`Set`,syntax:[`setSize(set)`,`setSize(set, unique)`],description:`Count the number of elements of a (multi)set. When the second parameter "unique" is true, count only the unique values. A multi-dimension array will be converted to a single-dimension array before the operation.`,examples:[`setSize([1, 2, 2, 4])`,`setSize([1, 2, 2, 4], true)`],seealso:[`setUnion`,`setIntersect`,`setDifference`]}})),FA,Pxe=e((()=>{FA={name:`setSymDifference`,category:`Set`,syntax:[`setSymDifference(set1, set2)`],description:`Create the symmetric difference of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.`,examples:[`setSymDifference([1, 2, 3, 4], [3, 4, 5, 6])`,`setSymDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])`],seealso:[`setUnion`,`setIntersect`,`setDifference`]}})),IA,Fxe=e((()=>{IA={name:`setUnion`,category:`Set`,syntax:[`setUnion(set1, set2)`],description:`Create the union of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.`,examples:[`setUnion([1, 2, 3, 4], [3, 4, 5, 6])`,`setUnion([[1, 2], [3, 4]], [[3, 4], [5, 6]])`],seealso:[`setIntersect`,`setDifference`]}})),LA,Ixe=e((()=>{LA={name:`zpk2tf`,category:`Signal`,syntax:[`zpk2tf(z, p, k)`],description:`Compute the transfer function of a zero-pole-gain model.`,examples:[`zpk2tf([1, 2], [-1, -2], 1)`,`zpk2tf([1, 2], [-1, -2])`,`zpk2tf([1 - 3i, 2 + 2i], [-1, -2])`],seealso:[]}})),RA,Lxe=e((()=>{RA={name:`freqz`,category:`Signal`,syntax:[`freqz(b, a)`,`freqz(b, a, w)`],description:`Calculates the frequency response of a filter given its numerator and denominator coefficients.`,examples:[`freqz([1, 2], [1, 2, 3])`,`freqz([1, 2], [1, 2, 3], [0, 1])`,`freqz([1, 2], [1, 2, 3], 512)`],seealso:[]}})),zA,Rxe=e((()=>{zA={name:`erf`,category:`Special`,syntax:[`erf(x)`],description:`Compute the erf function of a value using a rational Chebyshev approximations for different intervals of x`,examples:[`erf(0.2)`,`erf(-0.5)`,`erf(4)`],seealso:[]}})),BA,zxe=e((()=>{BA={name:`zeta`,category:`Special`,syntax:[`zeta(s)`],description:`Compute the Riemann Zeta Function using an infinite series and Riemann's Functional Equation for the entire complex plane`,examples:[`zeta(0.2)`,`zeta(-0.5)`,`zeta(4)`],seealso:[]}})),VA,Bxe=e((()=>{VA={name:`mad`,category:`Statistics`,syntax:[`mad(a, b, c, ...)`,`mad(A)`],description:`Compute the median absolute deviation of a matrix or a list with values. The median absolute deviation is defined as the median of the absolute deviations from the median.`,examples:[`mad(10, 20, 30)`,`mad([1, 2, 3])`],seealso:[`mean`,`median`,`std`,`abs`]}})),HA,Vxe=e((()=>{HA={name:`max`,category:`Statistics`,syntax:[`max(a, b, c, ...)`,`max(A)`,`max(A, dimension)`],description:`Compute the maximum value of a list of values. If any NaN values are found, the function yields the last NaN in the input.`,examples:[`max(2, 3, 4, 1)`,`max([2, 3, 4, 1])`,`max([2, 5; 4, 3])`,`max([2, 5; 4, 3], 1)`,`max([2, 5; 4, 3], 2)`,`max(2.7, 7.1, -4.5, 2.0, 4.1)`,`min(2.7, 7.1, -4.5, 2.0, 4.1)`],seealso:[`mean`,`median`,`min`,`prod`,`std`,`sum`,`variance`]}})),UA,Hxe=e((()=>{UA={name:`mean`,category:`Statistics`,syntax:[`mean(a, b, c, ...)`,`mean(A)`,`mean(A, dimension)`],description:`Compute the arithmetic mean of a list of values.`,examples:[`mean(2, 3, 4, 1)`,`mean([2, 3, 4, 1])`,`mean([2, 5; 4, 3])`,`mean([2, 5; 4, 3], 1)`,`mean([2, 5; 4, 3], 2)`,`mean([1.0, 2.7, 3.2, 4.0])`],seealso:[`max`,`median`,`min`,`prod`,`std`,`sum`,`variance`]}})),WA,Uxe=e((()=>{WA={name:`median`,category:`Statistics`,syntax:[`median(a, b, c, ...)`,`median(A)`],description:`Compute the median of all values. The values are sorted and the middle value is returned. In case of an even number of values, the average of the two middle values is returned.`,examples:[`median(5, 2, 7)`,`median([3, -1, 5, 7])`],seealso:[`max`,`mean`,`min`,`prod`,`std`,`sum`,`variance`,`quantileSeq`]}})),GA,Wxe=e((()=>{GA={name:`min`,category:`Statistics`,syntax:[`min(a, b, c, ...)`,`min(A)`,`min(A, dimension)`],description:`Compute the minimum value of a list of values. If any NaN values are found, the function yields the last NaN in the input.`,examples:[`min(2, 3, 4, 1)`,`min([2, 3, 4, 1])`,`min([2, 5; 4, 3])`,`min([2, 5; 4, 3], 1)`,`min([2, 5; 4, 3], 2)`,`min(2.7, 7.1, -4.5, 2.0, 4.1)`,`max(2.7, 7.1, -4.5, 2.0, 4.1)`],seealso:[`max`,`mean`,`median`,`prod`,`std`,`sum`,`variance`]}})),KA,Gxe=e((()=>{KA={name:`mode`,category:`Statistics`,syntax:[`mode(a, b, c, ...)`,`mode(A)`,`mode(A, a, b, B, c, ...)`],description:`Computes the mode of all values as an array. In case mode being more than one, multiple values are returned in an array.`,examples:[`mode(2, 1, 4, 3, 1)`,`mode([1, 2.7, 3.2, 4, 2.7])`,`mode(1, 4, 6, 1, 6)`],seealso:[`max`,`mean`,`min`,`median`,`prod`,`std`,`sum`,`variance`]}})),qA,Kxe=e((()=>{qA={name:`prod`,category:`Statistics`,syntax:[`prod(a, b, c, ...)`,`prod(A)`],description:`Compute the product of all values.`,examples:[`prod(2, 3, 4)`,`prod([2, 3, 4])`,`prod([2, 5; 4, 3])`],seealso:[`max`,`mean`,`min`,`median`,`min`,`std`,`sum`,`variance`]}})),JA,qxe=e((()=>{JA={name:`quantileSeq`,category:`Statistics`,syntax:[`quantileSeq(A, prob[, sorted])`,`quantileSeq(A, [prob1, prob2, ...][, sorted])`,`quantileSeq(A, N[, sorted])`],description:`Compute the prob order quantile of a matrix or a list with values. The sequence is sorted and the middle value is returned. Supported types of sequence values are: Number, BigNumber, Unit Supported types of probability are: Number, BigNumber. 
2632
2633In case of a (multi dimensional) array or matrix, the prob order quantile of all elements will be calculated.`,examples:[`quantileSeq([3, -1, 5, 7], 0.5)`,`quantileSeq([3, -1, 5, 7], [1/3, 2/3])`,`quantileSeq([3, -1, 5, 7], 2)`,`quantileSeq([-1, 3, 5, 7], 0.5, true)`],seealso:[`mean`,`median`,`min`,`max`,`prod`,`std`,`sum`,`variance`]}})),YA,Jxe=e((()=>{YA={name:`std`,category:`Statistics`,syntax:[`std(a, b, c, ...)`,`std(A)`,`std(A, dimension)`,`std(A, normalization)`,`std(A, dimension, normalization)`],description:`Compute the standard deviation of all values, defined as std(A) = sqrt(variance(A)). Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".`,examples:[`std(2, 4, 6)`,`std([2, 4, 6, 8])`,`std([2, 4, 6, 8], "uncorrected")`,`std([2, 4, 6, 8], "biased")`,`std([1, 2, 3; 4, 5, 6])`],seealso:[`max`,`mean`,`min`,`median`,`prod`,`sum`,`variance`]}})),XA,Yxe=e((()=>{XA={name:`cumsum`,category:`Statistics`,syntax:[`cumsum(a, b, c, ...)`,`cumsum(A)`],description:`Compute the cumulative sum of all values.`,examples:[`cumsum(2, 3, 4, 1)`,`cumsum([2, 3, 4, 1])`,`cumsum([1, 2; 3, 4])`,`cumsum([1, 2;
2633 3, 4], 1)`,`cumsum([1, 2; 3, 4], 2)`],seealso:[`max`,`mean`,`median`,`min`,`prod`,`std`,`sum`,`variance`]}})),ZA,Xxe=e((()=>{ZA={name:`sum`,category:`Statistics`,syntax:[`sum(a, b, c, ...)`,`sum(A)`,`sum(A, dimension)`],description:`Compute the sum of all values.`,examples:[`sum(2, 3, 4, 1)`,`sum([2, 3, 4, 1])`,`sum([2, 5; 4, 3])`],seealso:[`max`,`mean`,`median`,`min`,`prod`,`std`,`variance`]}})),QA,Zxe=e((()=>{QA={name:`variance`,category:`Statistics`,syntax:[`variance(a, b, c, ...)`,`variance(A)`,`variance(A, dimension)`,`variance(A, normalization)`,`variance(A, dimension, normalization)`],description:`Compute the variance of all values. Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".`,examples:[`variance(2, 4, 6)`,`variance([2, 4, 6, 8])`,`variance([2, 4, 6, 8], "uncorrected")`,`variance([2, 4, 6, 8], "biased")`,`variance([1, 2, 3; 4, 5, 6])`],seealso:[`max`,`mean`,`min`,`median`,`min`,`prod`,`std`,`sum`]}})),$A,Qxe=e((()=>{$A={name:`corr`,category:`Statistics`,syntax:[`corr(A,B)`],description:`Compute the correlation coefficient of a two list with values, For matrices, the matrix correlation coefficient is calculated.`,examples:[`corr([2, 4, 6, 8],[1, 2, 3, 6])`,`corr(matrix([[1, 2.2, 3, 4.8, 5], [1, 2, 3, 4, 5]]), matrix([[4, 5.3, 6.6, 7, 8], [1, 2, 3, 4, 5]]))`],seealso:[`max`,`mean`,`min`,`median`,`min`,`prod`,`std`,`sum`]}})),ej,$xe=e((()=>{ej={name:`acos`,category:`Trigonometry`,syntax:[`acos(x)`],description:`Compute the inverse cosine of a value in radians.`,examples:[`acos(0.5)`,`acos(cos(2.3))`],seealso:[`cos`,`atan`,`asin`]}})),tj,eSe=e((()=>{tj={name:`acosh`,category:`Trigonometry`,syntax:[`acosh(x)`],description:"Calculate the hyperbolic arccos of a value, defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.",examples:[`acosh(1.5)`],seealso:[`cosh`,`asinh`,`atanh`]}})),nj,tSe=e((()=>{nj={name:`acot`,category:`Trigonometry`,syntax:[`acot(x)`],description:`Calculate the inverse cotangent of a value.`,examples:[`acot(0.5)`,`acot(cot(0.5))`,`acot(2)`],seealso:[`cot`,`atan`]}})),rj,nSe=e((()=>{rj={name:`acoth`,category:`Trigonometry`,syntax:[`acoth(x)`],description:"Calculate the inverse hyperbolic tangent of a value, defined as `acoth(x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`.",examples:[`acoth(2)`,`acoth(0.5)`],seealso:[`acsch`,`asech`]}})),ij,rSe=e((()=>{ij={name:`acsc`,category:`Trigonometry`,syntax:[`acsc(x)`],description:`Calculate the inverse cotangent of a value.`,examples:[`acsc(2)`,`acsc(csc(0.5))`,`acsc(0.5)`],seealso:[`csc`,`asin`,`asec`]}})),aj,iSe=e((()=>{aj={name:`acsch`,category:`Trigonometry`,syntax:[`acsch(x)`],description:"Calculate the inverse hyperbolic cosecant of a value, defined as `acsch(x) = ln(1/x + sqrt(1/x^2 + 1))`.",examples:[`acsch(0.5)`],seealso:[`asech`,`acoth`]}})),oj,aSe=e((()=>{oj={name:`asec`,category:`Trigonometry`,syntax:[`asec(x)`],description:`Calculate the inverse secant of a value.`,examples:[`asec(0.5)`,`asec(sec(0.5))`,`asec(2)`],seealso:[`acos`,`acot`,`acsc`]}})),sj,oSe=e((()=>{sj={name:`asech`,category:`Trigonometry`,syntax:[`asech(x)`],description:`Calculate the inverse secant of a value.`,examples:[`asech(0.5)`],seealso:[`acsch`,`acoth`]}})),cj,sSe=e((()=>{cj={name:`asin`,category:`Trigonometry`,syntax:[`asin(x)`],description:`Compute the inverse sine of a value in radians.`,examples:[`asin(0.5)`,`asin(sin(0.5))`],seealso:[`sin`,`acos`,`atan`]}})),lj,cSe=e((()=>{lj={name:`asinh`,category:`Trigonometry`,syntax:[`asinh(x)`],description:"Calculate the hyperbolic arcsine of a value, defined as `asinh(x) = ln(x + sqrt(x^2 + 1))`.",examples:[`asinh(0.5)`],seealso:[`acosh`,`atanh`]}})),uj,lSe=e((()=>{uj={name:`atan`,category:`Trigonometry`,syntax:[`atan(x)`],description:`Compute the inverse tangent of a value in radians.`,examples:[`atan(0.5)`,`atan(tan(0.5))`],seealso:[`tan`,`acos`,`asin`]}})),dj,uSe=e((()=>{dj={name:`atan2`,category:`Trigonometry`,syntax:[`atan2(y, x)`],description:`Computes the principal value of the arc tangent of y/x in radians.`,examples:[`atan2(2, 2) / pi`,`angle = 60 deg in rad`,`x = cos(angle)`,`y = sin(angle)`,`atan2(y, x)`],seealso:[`sin`,`cos`,`tan`]}})),fj,dSe=e((()=>{fj={name:`atanh`,category:`Trigonometry`,syntax:[`atanh(x)`],description:"Calculate the hyperbolic arctangent of a value, defined as `atanh(x) = ln((1 + x)/(1 - x)) / 2`.",examples:[`atanh(0.5)`],seealso:[`acosh`,`asinh`]}})),pj,fSe=e((()=>{pj={name:`cos`,category:`Trigonometry`,syntax:[`cos(x)`],description:`Compute the cosine of x in radians.`,examples:[`cos(2)`,`cos(pi / 4) ^ 2`,`cos(180 deg)`,`cos(60 deg)`,`sin(0.2)^2 + cos(0.2)^2`],seealso:[`acos`,`sin`,`tan`]}})),mj,pSe=e((()=>{mj={name:`cosh`,category:`Trigonometry`,syntax:[`cosh(x)`],description:`Compute the hyperbolic cosine of x in radians.`,examples:[`cosh(0.5)`],seealso:[`sinh`,`tanh`,`
2633coth`]}})),hj,mSe=e((()=>{hj={name:`cot`,category:`Trigonometry`,syntax:[`cot(x)`],description:`Compute the cotangent of x in radians. Defined as 1/tan(x)`,examples:[`cot(2)`,`1 / tan(2)`],seealso:[`sec`,`csc`,`tan`]}})),gj,hSe=e((()=>{gj={name:`coth`,category:`Trigonometry`,syntax:[`coth(x)`],description:`Compute the hyperbolic cotangent of x in radians.`,examples:[`coth(2)`,`1 / tanh(2)`],seealso:[`sech`,`csch`,`tanh`]}})),_j,gSe=e((()=>{_j={name:`csc`,category:`Trigonometry`,syntax:[`csc(x)`],description:`Compute the cosecant of x in radians. Defined as 1/sin(x)`,examples:[`csc(2)`,`1 / sin(2)`],seealso:[`sec`,`cot`,`sin`]}})),vj,_Se=e((()=>{vj={name:`csch`,category:`Trigonometry`,syntax:[`csch(x)`],description:`Compute the hyperbolic cosecant of x in radians. Defined as 1/sinh(x)`,examples:[`csch(2)`,`1 / sinh(2)`],seealso:[`sech`,`coth`,`sinh`]}})),yj,vSe=e((()=>{yj={name:`sec`,category:`Trigonometry`,syntax:[`sec(x)`],description:`Compute the secant of x in radians. Defined as 1/cos(x)`,examples:[`sec(2)`,`1 / cos(2)`],seealso:[`cot`,`csc`,`cos`]}})),bj,ySe=e((()=>{bj={name:`sech`,category:`Trigonometry`,syntax:[`sech(x)`],description:`Compute the hyperbolic secant of x in radians. Defined as 1/cosh(x)`,examples:[`sech(2)`,`1 / cosh(2)`],seealso:[`coth`,`csch`,`cosh`]}})),xj,bSe=e((()=>{xj={name:`sin`,category:`Trigonometry`,syntax:[`sin(x)`],description:`Compute the sine of x in radians.`,examples:[`sin(2)`,`sin(pi / 4) ^ 2`,`sin(90 deg)`,`sin(30 deg)`,`sin(0.2)^2 + cos(0.2)^2`],seealso:[`asin`,`cos`,`tan`]}})),Sj,xSe=e((()=>{Sj={name:`sinh`,category:`Trigonometry`,syntax:[`sinh(x)`],description:`Compute the hyperbolic sine of x in radians.`,examples:[`sinh(0.5)`],seealso:[`cosh`,`tanh`]}})),Cj,SSe=e((()=>{Cj={name:`tan`,category:`Trigonometry`,syntax:[`tan(x)`],description:`Compute the tangent of x in radians.`,examples:[`tan(0.5)`,`sin(0.5) / cos(0.5)`,`tan(pi / 4)`,`tan(45 deg)`],seealso:[`atan`,`sin`,`cos`]}})),wj,CSe=e((()=>{wj={name:`tanh`,category:`Trigonometry`,syntax:[`tanh(x)`],description:`Compute the hyperbolic tangent of x in radians.`,examples:[`tanh(0.5)`,`sinh(0.5) / cosh(0.5)`],seealso:[`sinh`,`cosh`]}})),Tj,wSe=e((()=>{Tj={name:`to`,category:`Units`,syntax:[`x to unit`,`to(x, unit)`],description:`Change the unit of a value.`,examples:[`5 inch to cm`,`3.2kg to g`,`16 bytes in bits`],seealso:[]}})),Ej,TSe=e((()=>{Ej={name:`toBest`,category:`Units`,syntax:[`toBest(x)`,`toBest(x, unitList)`,`toBest(x, unitList, options)`],description:`Converts to the most appropriate display unit.`,examples:[`toBest(unit(5000, "m"))`,`toBest(unit(3500000, "W"))`,`toBest(unit(0.000000123, "A"))`,`toBest(unit(10, "m"), "cm")`,`toBest(unit(10, "m"), "mm,km", {offset: 1.5})`],seealso:[]}})),Dj,ESe=e((()=>{Dj={name:`bin`,category:`Utils`,syntax:[`bin(value)`],description:`Format a number as binary`,examples:[`bin(2)`],seealso:[`oct`,`hex`]}})),Oj,DSe=e((()=>{Oj={name:`clone`,category:`Utils`,syntax:[`clone(x)`],description:`Clone a variable. Creates a copy of primitive variables, and a deep copy of matrices`,examples:[`clone(3.5)`,`clone(2 - 4i)`,`clone(45 deg)`,`clone([1, 2; 3, 4])`,`clone("hello world")`],seealso:[]}})),kj,OSe=e((()=>{kj={name:`format`,category:`Utils`,syntax:[`format(value)`,`format(value, precision)`],description:`Format a value of any type as string.`,examples:[`format(2.3)`,`format(3 - 4i)`,`format([])`,`format(pi, 3)`],seealso:[`print`]}})),Aj,kSe=e((()=>{Aj={name:`hasNumericValue`,category:`Utils`,syntax:[`hasNumericValue(x)`],description:`Test whether a value is an numeric value. In case of a string, true is returned if the string contains a numeric value.`,examples:[`hasNumericValue(2)`,`hasNumericValue("2")`,`isNumeric("2")`,`hasNumericValue(0)`,`hasNumericValue(bignumber(500))`,`hasNumericValue(fraction(0.125))`,`hasNumericValue(2 + 3i)`,`hasNumericValue([2.3, "foo", false])`],seealso:[`isInteger`,`isZero`,`isNegative`,`isPositive`,`isNaN`,`isNumeric`]}})),jj,ASe=e((()=>{jj={name:`hex`,category:`Utils`,syntax:[`hex(value)`],description:`Format a number as hexadecimal`,examples:[`hex(240)`],seealso:[`bin`,`oct`]}})),Mj,jSe=e((()=>{Mj={name:`isInteger`,category:`Utils`,syntax:[`isInteger(x)`],description:`Test whether a value is an integer number.`,examples:[`isInteger(2)`,`isInteger(3.5)`,`isInteger([3, 0.5, -2])`],seealso:[`isNegative`,`isNumeric`,`isPositive`,`isZero`]}})),Nj,MSe=e((()=>{Nj={name:`isNaN`,category:`Utils`,syntax:[`isNaN(x)`],description:`Test whether a value is NaN (not a number)`,examples:[`isNaN(2)`,`isNaN(0 / 0)`,`isNaN(NaN)`,`isNaN(Infinity)`],seealso:[`isNegative`,`isNumeric`,`isPositive`,`isZero`,`isFinite`,`isBounded`]}})),Pj,NSe=e((()=>{Pj={name:`isBounded`,category:`Utils`,syntax:[`isBounded(x)`],description:`Test whether a value or its entries are bounded.`,examples:[`isBounded(Infinity)`,`isBounded(bigint(3))`,`isBounded([3, -Infinity, -3])`],seealso:[`isFinite`,`isNumeric`,`isNaN`,`isNegative`,`isPositive`]}})),Fj,PSe=e((()=>{Fj={name:`isFinite`,category:`Utils`,syntax:[`isFinite(x)`],description:`Test whether a value is finite, elementwise on collections.`,examples:[`isFinite(Infinity)`,`isFinite(bigint(3))`,`isFinite([3, -Infinity, -3])`],seealso:[`isBounded`,`isNumeric`,`isNaN`,`isNegative`,`isPositive`]}})),Ij,FSe=e((()=>{Ij={name:`isNegative`,category:`Utils`,syntax:[`isNegative(x)`],description:`Test whether a value is negative: smaller than zero.`,examples:[`isNegative(2)`,`isNegative(0)`,`isNegative(-4)`,`isNegative([3, 0.5, -2])`],seealso:[`isInteger`,`isNumeric`,`isPositive`,`isZero`]}})),Lj,ISe=e((()=>{Lj={name:`isNumeric`,category:`Utils`,syntax:[`isNumeric(x)`],description:`Test whether a value is a numeric value. Returns true when the input is a number, BigNumber, Fraction, or boolean.`,examples:[`isNumeric(2)`,`isNumeric("2")`,`hasNumericValue("2")`,`isNumeric(0)`,`isNumeric(bignumber(500))`,`isNumeric(fraction(0.125))`,`isNumeric(2 + 3i)`,`isNumeric([2.3, "foo", false])`],seealso:[`isInteger`,`isZero`,`isNegative`,`isPositive`,`isNaN`,`hasNumericValue`,`isFinite`,`isBounded`]}})),Rj,LSe=e((()=>{Rj={name:`isPositive`,category:`Utils`,syntax:[`isPositive(x)`],description:`Test whether a value is positive: larger than zero.`,examples:[`isPositive(2)`,`isPositive(0)`,`isPositive(-4)`,`isPositive([3, 0.5, -2])`],seealso:[`isInteger`,`isNumeric`,`isNegative`,`isZero`]}})),zj,RSe=e((()=>
2633{zj={name:`isPrime`,category:`Utils`,syntax:[`isPrime(x)`],description:`Test whether a value is prime: has no divisors other than itself and one.`,examples:[`isPrime(3)`,`isPrime(-2)`,`isPrime([2, 17, 100])`],seealso:[`isInteger`,`isNumeric`,`isNegative`,`isZero`]}})),Bj,zSe=e((()=>{Bj={name:`isZero`,category:`Utils`,syntax:[`isZero(x)`],description:`Test whether a value is zero.`,examples:[`isZero(2)`,`isZero(0)`,`isZero(-4)`,`isZero([3, 0, -2, 0])`],seealso:[`isInteger`,`isNumeric`,`isNegative`,`isPositive`]}})),Vj,BSe=e((()=>{Vj={name:`numeric`,category:`Utils`,syntax:[`numeric(x)`],description:`Convert a numeric input to a specific numeric type: number, BigNumber, bigint, or Fraction.`,examples:[`numeric("4")`,`numeric("4", "number")`,`numeric("4", "bigint")`,`numeric("4", "BigNumber")`,`numeric("4", "Fraction")`,`numeric(4, "Fraction")`,`numeric(fraction(2, 5), "number")`],seealso:[`number`,`bigint`,`fraction`,`bignumber`,`string`,`format`]}})),Hj,VSe=e((()=>{Hj={name:`oct`,category:`Utils`,syntax:[`oct(value)`],description:`Format a number as octal`,examples:[`oct(56)`],seealso:[`bin`,`hex`]}})),Uj,HSe=e((()=>{Uj={name:`print`,category:`Utils`,syntax:[`print(template, values)`,`print(template, values, precision)`],description:`Interpolate values into a string template.`,examples:[`print("Lucy is $age years old", {age: 5})`,`print("The value of pi is $pi", {pi: pi}, 3)`,`print("Hello, $user.name!", {user: {name: "John"}})`,`print("Values: $1, $2, $3", [6, 9, 4])`],seealso:[`format`]}})),Wj,USe=e((()=>{Wj={name:`typeOf`,category:`Utils`,syntax:[`typeOf(x)`],description:`Get the type of a variable.`,examples:[`typeOf(3.5)`,`typeOf(2 - 4i)`,`typeOf(45 deg)`,`typeOf("hello world")`],seealso:[`getMatrixDataType`]}})),Gj,WSe=e((()=>{Gj={name:`solveODE`,category:`Numeric`,syntax:[`solveODE(func, tspan, y0)`,`solveODE(func, tspan, y0, options)`],description:`Numerical Integration of Ordinary Differential Equations.`,examples:[`f(t,y) = y`,`tspan = [0, 4]`,`solveODE(f, tspan, 1)`,`solveODE(f, tspan, [1, 2])`,`solveODE(f, tspan, 1, { method:"RK23", maxStep:0.1 })`],seealso:[`derivative`,`simplifyCore`]}})),Kj,qj=e((()=>{ove(),sve(),cve(),lve(),uve(),dve(),fve(),pve(),mve(),hve(),gve(),_ve(),vve(),yve(),bve(),xve(),Sve(),Cve(),wve(),Tve(),Eve(),Dve(),Ove(),kve(),Ave(),jve(),Mve(),Nve(),Pve(),Fve(),Ive(),Lve(),Rve(),zve(),Bve(),Vve(),Hve(),Uve(),Wve(),Gve(),Kve(),qve(),Jve(),Yve(),Xve(),Zve(),Qve(),$ve(),eye(),tye(),nye(),rye(),iye(),aye(),oye(),sye(),cye(),lye(),uye(),dye(),fye(),pye(),mye(),hye(),gye(),_ye(),vye(),yye(),bye(),xye(),Sye(),Cye(),wye(),Tye(),Eye(),Dye(),Oye(),kye(),Aye(),jye(),Mye(),Nye(),Pye(),Fye(),Iye(),Lye(),Rye(),zye(),Bye(),Vye(),Hye(),Uye(),Wye(),Gye(),Kye(),qye(),Jye(),Yye(),Xye(),Zye(),Qye(),$ye(),ebe(),tbe(),nbe(),rbe(),ibe(),abe(),obe(),sbe(),cbe(),lbe(),ube(),dbe(),fbe(),pbe(),mbe(),hbe(),gbe(),_be(),vbe(),ybe(),bbe(),xbe(),Sbe(),Cbe(),wbe(),Tbe(),Ebe(),Dbe(),Obe(),kbe(),Abe(),jbe(),Mbe(),Nbe(),Pbe(),Fbe(),Ibe(),Lbe(),Rbe(),zbe(),Bbe(),Vbe(),Hbe(),Ube(),Wbe(),Gbe(),Kbe(),qbe(),Jbe(),Ybe(),Xbe(),Zbe(),Qbe(),$be(),exe(),txe(),nxe(),rxe(),ixe(),axe(),oxe(),sxe(),cxe(),lxe(),uxe(),dxe(),fxe(),pxe(),mxe(),hxe(),gxe(),_xe(),vxe(),yxe(),bxe(),xxe(),Sxe(),Cxe(),wxe(),Txe(),Exe(),Dxe(),Oxe(),kxe(),Axe(),jxe(),Mxe(),Nxe(),Pxe(),Fxe(),Ixe(),Lxe(),Rxe(),zxe(),Bxe(),Vxe(),Hxe(),Uxe(),Wxe(),Gxe(),Kxe(),qxe(),Jxe(),Yxe(),Xxe(),Zxe(),Qxe(),$xe(),eSe(),tSe(),nSe(),rSe(),iSe(),aSe(),oSe(),sSe(),cSe(),lSe(),uSe(),dSe(),fSe(),pSe(),mSe(),hSe(),gSe(),_Se(),vSe(),ySe(),bSe(),xSe(),SSe(),CSe(),wSe(),TSe(),ESe(),DSe(),OSe(),kSe(),ASe(),jSe(),MSe(),NSe(),PSe(),FSe(),ISe(),LSe(),RSe(),zSe(),BSe(),VSe(),HSe(),USe(),WSe(),Kj={bignumber:wD,bigint:TD,boolean:ED,complex:DD,createUnit:OD,fraction:kD,index:AD,matrix:jD,number:MD,sparse:ND,splitUnit:PD,string:FD,unit:ID,e:sD,E:sD,false:cD,i:lD,Infinity:uD,LN2:fD,LN10:dD,LOG2E:mD,LOG10E:pD,NaN:hD,null:gD,pi:vD,PI:vD,phi:_D,SQRT1_2:yD,SQRT2:bD,tau:xD,true:SD,version:CD,speedOfLight:{description:`Speed of light in vacuum`,examples:[`speedOfLight`]},gravitationConstant:{description:`Newtonian constant of gravitation`,examples:[`gravitationConstant`]},planckConstant:{description:`Planck constant`,examples:[`planckConstant`]},reducedPlanckConstant:{description:`Reduced Planck constant`,examples:[`reducedPlanckConstant`]},magneticConstant:{description:`Magnetic constant (vacuum permeability)`,examples:[`magneticConstant`]},electricConstant:{description:`Electric constant (vacuum permeability)`,examples:[`electricConstant`]},vacuumImpedance:{description:`Characteristic impedance of vacuum`,examples:[`vacuumImpedance`]}
2633,coulomb:{description:`Coulomb's constant. Deprecated in favor of coulombConstant`,examples:[`coulombConstant`]},coulombConstant:{description:`Coulomb's constant`,examples:[`coulombConstant`]},elementaryCharge:{description:`Elementary charge`,examples:[`elementaryCharge`]},bohrMagneton:{description:`Bohr magneton`,examples:[`bohrMagneton`]},conductanceQuantum:{description:`Conductance quantum`,examples:[`conductanceQuantum`]},inverseConductanceQuantum:{description:`Inverse conductance quantum`,examples:[`inverseConductanceQuantum`]},magneticFluxQuantum:{description:`Magnetic flux quantum`,examples:[`magneticFluxQuantum`]},nuclearMagneton:{description:`Nuclear magneton`,examples:[`nuclearMagneton`]},klitzing:{description:`Von Klitzing constant`,examples:[`klitzing`]},bohrRadius:{description:`Bohr radius`,examples:[`bohrRadius`]},classicalElectronRadius:{description:`Classical electron radius`,examples:[`classicalElectronRadius`]},electronMass:{description:`Electron mass`,examples:[`electronMass`]},fermiCoupling:{description:`Fermi coupling constant`,examples:[`fermiCoupling`]},fineStructure:{description:`Fine-structure constant`,examples:[`fineStructure`]},hartreeEnergy:{description:`Hartree energy`,examples:[`hartreeEnergy`]},protonMass:{description:`Proton mass`,examples:[`protonMass`]},deuteronMass:{description:`Deuteron Mass`,examples:[`deuteronMass`]},neutronMass:{description:`Neutron mass`,examples:[`neutronMass`]},quantumOfCirculation:{description:`Quantum of circulation`,examples:[`quantumOfCirculation`]},rydberg:{description:`Rydberg constant`,examples:[`rydberg`]},thomsonCrossSection:{description:`Thomson cross section`,examples:[`thomsonCrossSection`]},weakMixingAngle:{description:`Weak mixing angle`,examples:[`weakMixingAngle`]},efimovFactor:{description:`Efimov factor`,examples:[`efimovFactor`]},atomicMass:{description:`Atomic mass constant`,examples:[`atomicMass`]},avogadro:{description:`Avogadro's number`,examples:[`avogadro`]},boltzmann:{description:`Boltzmann constant`,examples:[`boltzmann`]},faraday:{description:`Faraday constant`,examples:[`faraday`]},firstRadiation:{description:`First radiation constant`,examples:[`firstRadiation`]},loschmidt:{description:`Loschmidt constant at T=273.15 K and p=101.325 kPa`,examples:[`loschmidt`]},gasConstant:{description:`Gas constant`,examples:[`gasConstant`]},molarPlanckConstant:{description:`Molar Planck constant`,examples:[`molarPlanckConstant`]},molarVolume:{description:`Molar volume of an ideal gas at T=273.15 K and p=101.325 kPa`,examples:[`molarVolume`]},sackurTetrode:{description:`Sackur-Tetrode constant at T=1 K and p=101.325 kPa`,examples:[`sackurTetrode`]},secondRadiation:{description:`Second radiation constant`,examples:[`secondRadiation`]},stefanBoltzmann:{description:`Stefan-Boltzmann constant`,examples:[`stefanBoltzmann`]},wienDisplacement:{description:`Wien displacement law constant`,examples:[`wienDisplacement`]},molarMass:{description:`Molar mass constant`,examples:[`molarMass`]},molarMassC12:{description:`Molar mass constant of carbon-12`,examples:[`molarMassC12`]},gravity:{description:`Standard acceleration of gravity (standard acceleration of free-fall on Earth)`,examples:[`gravity`]},planckLength:{description:`Planck length`,examples:[`planckLength`]},planckMass:{description:`Planck mass`,examples:[`planckMass`]},planckTime:{description:`Planck time`,examples:[`planckTime`]},planckCharge:{description:`Planck charge`,examples:[`planckCharge`]},planckTemperature:{description:`Planck temperature`,examples:[`planckTemperature`]},derivative:BD,lsolve:HD,lsolveAll:UD,lup:WD,lusolve:GD,leafCount:VD,polynomialRoot:KD,resolve:YD,simplify:XD,simplifyConstant:ZD,simplifyCore:QD,symbolicEqual:eO,rationalize:JD,slu:$D,usolve:tO,usolveAll:nO,qr:qD,abs:rO,add:iO,cbrt:aO,ceil:oO,cube:sO,divide:cO,dotDivide:lO,dotMultiply:uO,dotPow:dO,exp:fO,expm:pO,expm1:mO,fix:hO,floor:gO,gcd:_O,hypot:vO,lcm:bO,log:xO,log2:wO,log1p:CO,log10:SO,mod:TO,multiply:EO,norm:DO,nthRoot:OO,nthRoots:kO,pow:AO,round:jO,sign:MO,sqrt:NO,sqrtm:PO,square:RO,subtract:zO,unaryMinus:BO,unaryPlus:VO,xgcd:HO,invmod:yO,num:UO,de
2633n:WO,bitAnd:GO,bitNot:KO,bitOr:qO,bitXor:JO,leftShift:YO,rightArithShift:XO,rightLogShift:ZO,bellNumbers:QO,catalan:$O,composition:ek,stirlingS2:tk,config:LD,import:RD,typed:zD,arg:nk,conj:rk,re:ak,im:ik,evaluate:ok,help:uk,parse:ck,parser:sk,compile:lk,distance:dk,intersect:fk,and:pk,not:mk,nullish:hk,or:gk,xor:_k,mapSlices:vk,concat:bk,count:xk,cross:Sk,column:yk,ctranspose:Ck,det:wk,diag:Tk,diff:Ek,dot:Dk,getMatrixDataType:Mk,identity:Nk,filter:kk,flatten:Ak,forEach:jk,inv:Pk,pinv:Fk,eigs:Ok,kron:Ik,matrixFromFunction:zk,matrixFromRows:Bk,matrixFromColumns:Rk,map:Lk,ones:Vk,partitionSelect:Hk,range:Uk,resize:Gk,reshape:Wk,rotate:Kk,rotationMatrix:qk,row:Jk,size:Yk,sort:Xk,squeeze:Zk,subset:Qk,trace:$k,transpose:eA,zeros:tA,fft:nA,ifft:rA,sylvester:FO,schur:IO,lyap:LO,solveODE:Gj,bernoulli:iA,combinations:aA,combinationsWithRep:oA,factorial:sA,gamma:cA,kldivergence:uA,lgamma:lA,multinomial:dA,permutations:fA,pickRandom:pA,random:mA,randomInt:hA,compare:gA,compareNatural:_A,compareText:vA,deepEqual:yA,equal:bA,equalText:xA,larger:SA,largerEq:CA,smaller:wA,smallerEq:TA,unequal:EA,setCartesian:DA,setDifference:OA,setDistinct:kA,setIntersect:AA,setIsSubset:jA,setMultiplicity:MA,setPowerset:NA,setSize:PA,setSymDifference:FA,setUnion:IA,zpk2tf:LA,freqz:RA,erf:zA,zeta:BA,cumsum:XA,mad:VA,max:HA,mean:UA,median:WA,min:GA,mode:KA,prod:qA,quantileSeq:JA,std:YA,sum:ZA,variance:QA,corr:$A,acos:ej,acosh:tj,acot:nj,acoth:rj,acsc:ij,acsch:aj,asec:oj,asech:sj,asin:cj,asinh:lj,atan:uj,atanh:fj,atan2:dj,cos:pj,cosh:mj,cot:hj,coth:gj,csc:_j,csch:vj,sec:yj,sech:bj,sin:xj,sinh:Sj,tan:Cj,tanh:wj,to:Tj,toBest:Ej,clone:Oj,format:kj,bin:Dj,oct:Hj,hex:jj,isNaN:Nj,isBounded:Pj,isFinite:Fj,isInteger:Mj,isNegative:Ij,isNumeric:Lj,hasNumericValue:Aj,isPositive:Rj,isPrime:zj,isZero:Bj,print:Uj,typeOf:Wj,numeric:Vj}})),Jj,Yj,Xj,GSe=e((()=>{X(),ml(),qj(),ru(),Jj=`help`,Yj=[`typed`,`mathWithTransform`,`Help`],Xj=Y(Jj,Yj,e=>{var{typed:t,mathWithTransform:n,Help:r}=e;return t(Jj,{any:function(e){var t,i=e;if(typeof e!=`string`){for(t in n)if(nu(n,t)&&e===n[t]){i=t;break}}var a=ul(Kj,i);if(!a){var o=typeof i==`function`?i.name:i;throw Error(`No documentation found on "`+o+`"`)}return new r(a)}})})})),Zj,Qj,$j,KSe=e((()=>{X(),Zj=`chain`,Qj=[`typed`,`Chain`],$j=Y(Zj,Qj,e=>{var{typed:t,Chain:n}=e;return t(Zj,{"":function(){return new n},any:function(e){return new n(e)}})})})),eM,tM,nM,qSe=e((()=>{Ql(),ru(),Hf(),X(),eM=`det`,tM=[`typed`,`matrix`,`subtractScalar`,`multiply`,`divideScalar`,`isZero`,`unaryMinus`],nM=Y(eM,tM,e=>{var{typed:t,matrix:n,subtractScalar:r,multiply:i,divideScalar:a,isZero:o,unaryMinus:s}=e;return t(eM,{any:function(e){return $l(e)},"Array | Matrix":function(e){var t;switch(Dl(e)?t=e.size():Array.isArray(e)?(e=n(e),t=e.size()):t=[],t.length){case 0:return $l(e);case 1:if(t[0]===1)return $l(e.valueOf()[0]);if(t[0]===0)return 1;throw RangeError(`Matrix must be square (size: `+If(t)+`)`);case 2:var r=t[0],i=t[1];if(r===i)return c(e.clone().valueOf(),r,i);if(i===0)return 1;throw RangeError(`Matrix must be square (size: `+If(t)+`)`);default:throw RangeError(`Matrix must be two dimensional (size: `+If(t)+`)`)}}});function c(e,t,n){if(t===1)return $l(e[0][0]);if(t===2)return r(i(e[0][0],e[1][1]),i(e[1][0],e[0][1]));for(var c=!1,l=Array(t).fill(0).map((e,t)=>t),u=0;u<t;u++){var d=l[u];if(o(e[d][u])){var f=void 0;for(f=u+1;f<t;f++)if(!o(e[l[f]][u])){d=l[f],l[f]=l[u],l[u]=d,c=!c;break}if(f===t)return e[d][u]}for(var p=e[d][u],m=u===0?1:e[l[u-1]][u-1],h=u+1;h<t;h++)for(var g=l[h],_=u+1;_<t;_++)e[g][_]=a(r(i(e[g][_],p),i(e[g][u],e[d][_])),m)}var v=e[l[t-1]][t-1];return c?s(v):v}})})),rM,iM,aM,JSe=e((()=>{Ql(),Tp(),X(),Hf(),rM=`inv`,iM=[`typed`,`matrix`,`divideScalar`,`addScalar`,`multiply`,`unaryMinus`,`det`,`identity`,`abs`],aM=Y(rM,iM,e=>{var{typed:t,matrix:n,divideScalar:r,addScalar:i,multiply:a,unaryMinus:o,det:s,identity:c,abs:l}=e;return t(rM,{"Array | Matrix":function(e){var t=Dl(e)?e.size():qf(e);switch(t.length){case 1:if(t[0]===1)return Dl(e)?n([r(1,e.valueOf()[0])]):[r(1,e[0])];throw RangeError(`Matrix must be square (size: `+If(t)+`)`);case 2:var i=t[0],a=t[1];if(i===a)return Dl(e)?n(u(e.valueOf(),i,a),e.storage()):u(e,i,a);throw RangeError(`Matrix must be square (size: `+If(t)+`)`);
2633default:throw RangeError(`Matrix must be two dimensional (size: `+If(t)+`)`)}},any:function(e){return r(1,e)}});function u(e,t,n){var u,d,f,p,m;if(t===1){if(p=e[0][0],p===0)throw Error(`Cannot calculate inverse, determinant is zero`);return[[r(1,p)]]}else if(t===2){var h=s(e);if(h===0)throw Error(`Cannot calculate inverse, determinant is zero`);return[[r(e[1][1],h),r(o(e[0][1]),h)],[r(o(e[1][0]),h),r(e[0][0],h)]]}else{var g=e.concat();for(u=0;u<t;u++)g[u]=g[u].concat();for(var _=c(t).valueOf(),v=0;v<n;v++){var y=l(g[v][v]),b=v;for(u=v+1;u<t;)l(g[u][v])>y&&(y=l(g[u][v]),b=u),u++;if(y===0)throw Error(`Cannot calculate inverse, determinant is zero`);u=b,u!==v&&(m=g[v],g[v]=g[u],g[u]=m,m=_[v],_[v]=_[u],_[u]=m);var x=g[v],S=_[v];for(u=0;u<t;u++){var C=g[u],w=_[u];if(u!==v){if(C[v]!==0){for(f=r(o(C[v]),x[v]),d=v;d<n;d++)C[d]=i(C[d],a(f,x[d]));for(d=0;d<n;d++)w[d]=i(w[d],a(f,S[d]))}}else{for(f=x[v],d=v;d<n;d++)C[d]=r(C[d],f);for(d=0;d<n;d++)w[d]=r(w[d],f)}}}return _}}})})),oM,sM,cM,YSe=e((()=>{Ql(),Tp(),X(),Hf(),ru(),oM=`pinv`,sM=[`typed`,`matrix`,`inv`,`deepEqual`,`equal`,`dotDivide`,`dot`,`ctranspose`,`divideScalar`,`multiply`,`add`,`Complex`],cM=Y(oM,sM,e=>{var{typed:t,matrix:n,inv:r,deepEqual:i,equal:a,dotDivide:o,dot:s,ctranspose:c,divideScalar:l,multiply:u,add:d,Complex:f}=e;return t(oM,{"Array | Matrix":function(e){var t=Dl(e)?e.size():qf(e);switch(t.length){case 1:return _(e)?c(e):t[0]===1?r(e):o(c(e),s(e,e));case 2:if(_(e))return c(e);var i=t[0],a=t[1];if(i===a)try{return r(e)}catch(e){if(!(e instanceof Error&&e.message.match(/Cannot calculate inverse, determinant is zero/)))throw e}return Dl(e)?n(p(e.valueOf(),i,a),e.storage()):p(e,i,a);default:throw RangeError(`Matrix must be two dimensional (size: `+If(t)+`)`)}},any:function(e){return a(e,0)?$l(e):l(1,e)}});function p(e,t,n){var{C:i,F:a}=h(e,t,n),o=u(r(u(c(i),i)),c(i));return u(u(c(a),r(u(a,c(a)))),o)}function m(e,t,n){for(var r=$l(e),i=0,a=0;a<t;a++){if(n<=i)return r;for(var s=a;g(r[s][i]);)if(s++,t===s&&(s=a,i++,n===i))return r;[r[s],r[a]]=[r[a],r[s]];for(var c=r[a][i],l=0;l<n;l++)r[a][l]=o(r[a][l],c);for(var f=0;f<t;f++)if(f!==a){c=r[f][i];for(var p=0;p<n;p++)r[f][p]=d(r[f][p],u(-1,u(c,r[a][p])))}i++}return r}function h(e,t,n){var r=m(e,t,n);return{C:e.map((e,n)=>e.filter((e,n)=>n<t&&!g(s(r[n],r[n])))),F:r.filter((e,t)=>!g(s(r[t],r[t])))}}function g(e){return a(d(e,f(1,1)),d(0,f(1,1)))}function _(e){return i(d(e,f(1,1)),d(u(e,0),f(1,1)))}})}));function XSe(e){var{addScalar:t,subtract:n,flatten:r,multiply:i,multiplyScalar:a,divideScalar:o,sqrt:s,abs:c,bignumber:l,diag:u,size:d,reshape:f,inv:p,qr:m,usolve:h,usolveAll:g,equal:_,complex:v,larger:y,smaller:b,matrixFromColumns:x,dot:S}=e;function C(e,t,n,r){var i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,a=w(e,t,n,r,i);T(e,t,n,r,i,a);var{values:o,C:s}=E(e,t,n,r,i);return i?{values:o,eigenvectors:D(e,t,s,a,o,n,r)}:{values:o}}function w(e,n,r,i,s){var d=i===`BigNumber`,f=i===`Complex`,p=d?l(0):0,m=d?l(1):f?v(1):1,h=d?l(1):1,g=d?l(10):2,x=a(g,g),S;s&&(S=Array(n).fill(m));for(var C=!1;!C;){C=!0;for(var w=0;w<n;w++){for(var T=p,E=p,D=0;D<n;D++)w!==D&&(T=t(T,c(e[D][w])),E=t(E,c(e[w][D])));if(!_(T,0)&&!_(E,0)){for(var O=h,k=T,A=o(E,g),j=a(E,g);b(k,A);)k=a(k,x),O=a(O,g);for(;y(k,j);)k=o(k,x),O=o(O,g);if(b(o(t(k,E),O),a(t(T,E),.95))){C=!1;for(var M=o(1,O),N=0;N<n;N++)w!==N&&(e[w][N]=a(e[w][N],M),e[N][w]=a(e[N][w],O));s&&(S[w]=a(S[w],M))}}}}return s?u(S):null}function T(e,r,i,s,u,d){var f=s===`BigNumber`,p=f?l(0):s===`Complex`?v(0):0;f&&(i=l(i));for(var m=0;m<r-2;m++){for(var h=0,g=p,_=m+1;_<r;_++){var y=e[_][m];b(c(g),c(y))&&(g=y,h=_)}if(!b(c(g),i)){if(h!==m+1){var x=e[h];e[h]=e[m+1],e[m+1]=x;for(var S=0;S<r;S++){var C=e[S][h];e[S][h]=e[S][m+1],e[S][m+1]=C}if(u){var w=d[h];d[h]=d[m+1],d[m+1]=w}}for(var T=m+2;T<r;T++){var E=o(e[T][m],g);if(E!==0){for(var D=0;D<r;D++)e[T][D]=n(e[T][D],a(E,e[m+1][D]));for(var O=0;O<r;O++)e[O][m+1]=t(e[O][m+1],a(E,e[O][T]));if(u)for(var k=0;k<r;k++)d[T][k]=n(d[T][k],a(E,d[m+1][k]))}}}}return d}function E(e,r,a,o,s){var d=o===`BigNumber`,f=d?l(1):o===`Complex`?v(1):1;d&&(a=l(a));for(var p=$l(e),h=[],g=r,_=[],y=s?u(Array(r).fill(f)):void 0,x=s?u(Array(g).fill(f)):void 0,S=0;S<=100;
vendor: 4,090 bytes, line 2633
2633){S+=1;for(var C=p[g-1][g-1],w=0;w<g;w++)p[w][w]=n(p[w][w],C);var{Q:T,R:E}=m(p);p=i(E,T);for(var D=0;D<g;D++)p[D][D]=t(p[D][D],C);if(s&&(x=i(x,T)),g===1||b(c(p[g-1][g-2]),a)){S=0,h.push(p[g-1][g-1]),s&&(_.unshift([[1]]),A(x,r),y=i(y,x),g>1&&(x=u(Array(g-1).fill(f)))),--g,p.pop();for(var M=0;M<g;M++)p[M].pop()}else if(g===2||b(c(p[g-2][g-3]),a)){S=0;var N=O(p[g-2][g-2],p[g-2][g-1],p[g-1][g-2],p[g-1][g-1]);h.push(...N),s&&(_.unshift(k(p[g-2][g-2],p[g-2][g-1],p[g-1][g-2],p[g-1][g-1],N[0],N[1],a,o)),A(x,r),y=i(y,x),g>2&&(x=u(Array(g-2).fill(f)))),g-=2,p.pop(),p.pop();for(var P=0;P<g;P++)p[P].pop(),p[P].pop()}if(g===0)break}if(h.sort((e,t)=>+n(c(e),c(t))),S>100){var F=Error(`The eigenvalues failed to converge. Only found these eigenvalues: `+h.join(`, `));throw F.values=h,F.vectors=[],F}return{values:h,C:s?i(y,j(_,r)):void 0}}function D(e,t,a,o,s,c,d){var f=i(p(a),e,a),m=d===`BigNumber`,h=d===`Complex`,y=m?l(0):h?v(0):0,b=m?l(1):h?v(1):1,x=[],S=[];for(var C of s){var w=M(x,C,_);w===-1?(x.push(C),S.push(1)):S[w]+=1}for(var T=[],E=x.length,D=Array(t).fill(y),O=u(Array(t).fill(b)),k=function(){var e=x[A],s=n(f,i(e,O)),l=g(s,D);for(l.shift();l.length<S[A];){var u=N(s,t,l,c,d);if(u===null)break;l.push(u)}var m=i(p(o),a);l=l.map(e=>i(m,e)),T.push(...l.map(t=>({value:e,vector:r(t)})))},A=0;A<E;A++)k();return T}function O(e,r,i,o){var c=t(e,o),l=n(a(e,o),a(r,i)),u=a(c,.5),d=a(s(n(a(c,c),a(4,l))),.5);return[t(u,d),n(u,d)]}function k(e,t,r,i,a,o,s,u){var d=u===`BigNumber`,f=u===`Complex`,p=d?l(0):f?v(0):0,m=d?l(1):f?v(1):1;if(b(c(r),s))return[[m,p],[p,m]];if(y(c(n(a,o)),s))return[[n(a,i),n(o,i)],[r,r]];var h=n(e,a),g=n(i,a);return b(c(t),s)&&b(c(g),s)?[[h,m],[r,p]]:[[t,p],[g,m]]}function A(e,t){for(var n=0;n<e.length;n++)e[n].push(...Array(t-e[n].length).fill(0));for(var r=e.length;r<t;r++)e.push(Array(t).fill(0)),e[r][r]=1;return e}function j(e,t){for(var n=[],r=0;r<t;r++)n[r]=Array(t).fill(0);var i=0;for(var a of e){for(var o=a.length,s=0;s<o;s++)for(var c=0;c<o;c++)n[i+s][i+c]=a[s][c];i+=o}return n}function M(e,t,n){for(var r=0;r<e.length;r++)if(n(e[r],t))return r;return-1}function N(e,t,n,r,i){for(var a=i===`BigNumber`?l(1e3):1e3,o,s=0;s<5;++s){o=P(t,n,i);try{o=h(e,o)}catch{continue}if(y(I(o),a))break}if(s>=5)return null;for(s=0;;){var c=h(e,o);if(b(I(F(o,[c])),r))break;if(++s>=10)return null;o=L(c)}return o}function P(e,t,n){var r=n===`BigNumber`,i=n===`Complex`,a=Array(e).fill(0).map(e=>2*Math.random()-1);return r&&(a=a.map(e=>l(e))),i&&(a=a.map(e=>v(e))),a=F(a,t),L(a,n)}function F(e,t){var r=d(e);for(var a of t)a=f(a,r),e=n(e,i(o(S(a,e),S(a,a)),a));return e}function I(e){return c(s(S(e,e)))}function L(e,t){return i(o(t===`BigNumber`?l(1):t===`Complex`?v(1):1,I(e)),e)}return C}var ZSe=e((()=>{ru()}));function QSe(e){var{config:t,addScalar:n,subtract:r,abs:i,atan:a,cos:o,sin:s,multiplyScalar:c,inv:l,bignumber:u,multiply:d,add:f}=e;function p(e,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:t.relTol,i=arguments.length>3?arguments[3]:void 0,a=arguments.length>4?arguments[4]:void 0;if(i===`number`)return m(e,r,a);if(i===`BigNumber`)return h(e,r,a);throw TypeError(`Unsupported data type: `+i)}function m(e,t,n){var r=e.length,i=Math.abs(t/r),a,o;if(n){o=Array(r);for(var s=0;s<r;s++)o[s]=Array(r).fill(0),o[s][s]=1}for(var c=S(e);Math.abs(c[1])>=Math.abs(i);){var l=c[0][0],u=c[0][1];a=g(e[l][l],e[u][u],e[l][u]),e=x(e,a,l,u),n&&(o=v(o,a,l,u)),c=S(e)}for(var d=Array(r).fill(0),f=0;f<r;f++)d[f]=e[f][f];return w($l(d),o,n)}function h(e,t,n){var r=e.length,a=i(t/r),o,s;if(n){s=Array(r);for(var c=0;c<r;c++)s[c]=Array(r).fill(0),s[c][c]=1}for(var l=C(e);i(l[1])>=i(a);){var u=l[0][0],d=l[0][1];o=_(e[u][u],e[d][d],e[u][d]),e=b(e,o,u,d),n&&(s=y(s,o,u,d)),l=C(e)}for(var f=Array(r).fill(0),p=0;p<r;p++)f[p]=e[p][p];return w($l(f),s,n)}function g(e,n,r){var i=n-e;return Math.abs(i)<=t.relTol?Math.PI/4:.5*Math.atan(2*r/(n-e))}function _(e,n,o){var s=r(n,e);return i(s)<=t.relTol?u(-1).acos().div(4):c(.5,a(d(2,o,l(s))))}function v(e,t,n,r){for(var i=e.length,a=Math.cos(t),o=Math.sin(t),s=Array(i).fill(0),c=Array(i).fill(0),l=0;l<i;
2633l++)s[l]=a*e[l][n]-o*e[l][r],c[l]=o*e[l][n]+a*e[l][r];for(var u=0;u<i;u++)e[u][n]=s[u],e[u][r]=c[u];return e}function y(e,t,i,a){for(var l=e.length,d=o(t),f=s(t),p=Array(l).fill(u(0)),m=Array(l).fill(u(0)),h=0;h<l;h++)p[h]=r(c(d,e[h][i]),c(f,e[h][a])),m[h]=n(c(f,e[h][i]),c(d,e[h][a]));for(var g=0;g<l;g++)e[g][i]=p[g],e[g][a]=m[g];return e}function b(e,t,i,a){for(var l=e.length,p=u(o(t)),m=u(s(t)),h=c(p,p),g=c(m,m),_=Array(l).fill(u(0)),v=Array(l).fill(u(0)),y=d(u(2),p,m,e[i][a]),b=n(r(c(h,e[i][i]),y),c(g,e[a][a])),x=f(c(g,e[i][i]),y,c(h,e[a][a])),S=0;S<l;S++)_[S]=r(c(p,e[i][S]),c(m,e[a][S])),v[S]=n(c(m,e[i][S]),c(p,e[a][S]));e[i][i]=b,e[a][a]=x,e[i][a]=u(0),e[a][i]=u(0);for(var C=0;C<l;C++)C!==i&&C!==a&&(e[i][C]=_[C],e[C][i]=_[C],e[a][C]=v[C],e[C][a]=v[C]);return e}function x(e,t,n,r){for(var i=e.length,a=Math.cos(t),o=Math.sin(t),s=a*a,c=o*o,l=Array(i).fill(0),u=Array(i).fill(0),d=s*e[n][n]-2*a*o*e[n][r]+c*e[r][r],f=c*e[n][n]+2*a*o*e[n][r]+s*e[r][r],p=0;p<i;p++)l[p]=a*e[n][p]-o*e[r][p],u[p]=o*e[n][p]+a*e[r][p];e[n][n]=d,e[r][r]=f,e[n][r]=0,e[r][n]=0;for(var m=0;m<i;m++)m!==n&&m!==r&&(e[n][m]=l[m],e[m][n]=l[m],e[r][m]=u[m],e[m][r]=u[m]);return e}function S(e){for(var t=e.length,n=0,r=[0,1],i=0;i<t;i++)for(var a=i+1;a<t;a++)Math.abs(n)<Math.abs(e[i][a])&&(n=Math.abs(e[i][a]),r=[i,a]);return[r,n]}function C(e){for(var t=e.length,n=0,r=[0,1],a=0;a<t;a++)for(var o=a+1;o<t;o++)i(n)<i(e[a][o])&&(n=i(e[a][o]),r=[a,o]);return[r,n]}function w(e,t,n){var r=e.length,a=Array(r),o;if(n){o=Array(r);for(var s=0;s<r;s++)o[s]=Array(r)}for(var c=0;c<r;c++){for(var l=0,u=e[0],d=0;d<e.length;d++)i(e[d])<i(u)&&(l=d,u=e[l]);if(a[c]=e.splice(l,1)[0],n)for(var f=0;f<r;f++)o[c][f]=t[f][l],t[f].splice(l,1)}return n?{values:a,eigenvectors:o.map((e,t)=>({value:a[t],vector:e}))}:{values:a}}return p}var $Se=e((()=>{ru()})),lM,uM,dM,eCe=e((()=>{Bn(),X(),Hf(),ZSe(),$Se(),Ql(),lM=`eigs`,uM=`config.typed.matrix.addScalar.equal.subtract.abs.atan.cos.sin.multiplyScalar.divideScalar.inv.bignumber.multiply.add.larger.column.flatten.number.complex.sqrt.diag.size.reshape.qr.usolve.usolveAll.im.re.smaller.matrixFromColumns.dot`.split(`.`),dM=Y(lM,uM,e=>{var{config:t,typed:n,matrix:r,addScalar:i,subtract:a,equal:o,abs:s,atan:c,cos:l,sin:u,multiplyScalar:d,divideScalar:f,inv:p,bignumber:m,multiply:h,add:g,larger:_,column:v,flatten:y,number:b,complex:x,sqrt:S,diag:C,size:w,reshape:T,qr:E,usolve:D,usolveAll:O,im:k,re:A,smaller:j,matrixFromColumns:M,dot:N}=e,P=QSe({config:t,addScalar:i,subtract:a,column:v,flatten:y,equal:o,abs:s,atan:c,cos:l,sin:u,multiplyScalar:d,inv:p,bignumber:m,complex:x,multiply:h,add:g}),F=XSe({config:t,addScalar:i,subtract:a,multiply:h,multiplyScalar:d,flatten:y,divideScalar:f,sqrt:S,abs:s,bignumber:m,diag:C,size:w,reshape:T,qr:E,inv:p,usolve:D,usolveAll:O,equal:o,complex:x,larger:_,smaller:j,matrixFromColumns:M,dot:N});return n(`eigs`,{Array:function(e){return I(r(e))},"Array, number|BigNumber":function(e,t){return I(r(e),{precision:t})},"Array, Object"(e,t){return I(r(e),t)},Matrix:function(e){return I(e,{matricize:!0})},"Matrix, number|BigNumber":function(e,t){return I(e,{precision:t,matricize:!0})},"Matrix, Object":function(e,t){var n={matricize:!0};return zn(n,t),I(e,n)}});function I(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=`eigenvectors`in n?n.eigenvectors:!0,a=L(e,n.precision??t.relTol,i);return n.matricize&&(a.values=r(a.values),i&&(a.eigenvectors=a.eigenvectors.map(e=>{var{value:t,vector:n}=e;return{value:t,vector:r(n)}}))),i&&Object.defineProperty(a,"vectors",{enumerable:!1,get:()=>{throw Error(`eigs(M).vectors replaced with eigs(M).eigenvectors`)}}),a}function L(e,t,n){var r=e.toArray(),i=e.size();if(i.length!==2||i[0]!==i[1])throw RangeError(`Matrix must be square (size: ${If(i)})`);var a=i[0];return R(r,a,t)&&(te(r,a),ee(r,a,t))?P(r,a,t,z(e,r,a),n):F(r,a,t,z(e,r,a),n)}function ee(e,t,n){for(var r=0;r<t;r++)for(var i=r;i<t;i++)if(_(m(s(a(e[r][i],e[i][r]))),n))return!1;return!0}function R(e,t,n){for(var r=0;r<t;r++)for(var i=0;i<t;i++)if(_(m(s(k(e[r][i]))),n))return!1;return!0}function te(e,t){for(var n=0;n<t;n++)for(var r=0;r<t;r++)e[n][r]=A(e[n][r])}function z(e,t,n){var r=e.datatype();if(r===`number`||r===`BigNumber`||r===`Complex`)return r;for(var i=!1,a=!1,o=!1,s=0;s<n;s++)for(var c=0;c<n;c++){var l=t[s][c];if(bl(l)||wl(l))i=!0;else if(xl(l))a=!0;else if(Cl(l))o=!0;else throw TypeError(`Unsupported type in Matrix: `+Xl(l))}if(a&&o&&console.warn(`Complex BigNumbers not supported, this operation will lose precission.`),o){for(var u=0;u<n;u++)for(var d=0;d<n;
2633d++)t[u][d]=x(t[u][d]);return`Complex`}if(a){for(var f=0;f<n;f++)for(var p=0;p<n;p++)t[f][p]=m(t[f][p]);return`BigNumber`}if(i){for(var h=0;h<n;h++)for(var g=0;g<n;g++)t[h][g]=b(t[h][g]);return`number`}else throw TypeError(`Matrix contains unsupported types only.`)}})})),fM,pM,mM,tCe=e((()=>{Ql(),Hf(),X(),fM=`expm`,pM=[`typed`,`abs`,`add`,`identity`,`inv`,`multiply`],mM=Y(fM,pM,e=>{var{typed:t,abs:n,add:r,identity:i,inv:a,multiply:o}=e;return t(fM,{Matrix:function(e){var t=e.size();if(t.length!==2||t[0]!==t[1])throw RangeError(`Matrix must be square (size: `+If(t)+`)`);for(var n=t[0],l=c(s(e),1e-15),u=l.q,d=l.j,f=o(e,2**-d),p=i(n),m=i(n),h=1,g=f,_=-1,v=1;v<=u;v++)v>1&&(g=o(g,f),_=-_),h=h*(u-v+1)/((2*u-v+1)*v),p=r(p,o(h,g)),m=r(m,o(h*_,g));for(var y=o(a(m),p),b=0;b<d;b++)y=o(y,y);return Al(e)?e.createSparseMatrix(y):y}});function s(e){for(var t=e.size()[0],r=0,i=0;i<t;i++){for(var a=0,o=0;o<t;o++)a+=n(e.get([i,o]));r=Math.max(a,r)}return r}function c(e,t){for(var n=30,r=0;r<n;r++)for(var i=0;i<=r;i++){var a=r-i;if(l(e,i,a)<t)return{q:i,j:a}}throw Error(`Could not find acceptable parameters to compute the matrix exponential (try increasing maxSearchSize in expm.js)`)}function l(e,t,n){for(var r=1,i=2;i<=t;i++)r*=i;for(var a=r,o=t+1;o<=2*t;o++)a*=o;var s=a*(2*t+1);return 8*(e/2**n)**(2*t)*r*r/(a*s)}})})),hM,gM,_M,nCe=e((()=>{Ql(),Hf(),Tp(),X(),hM=`sqrtm`,gM=[`typed`,`abs`,`add`,`multiply`,`map`,`sqrt`,`subtract`,`inv`,`size`,`max`,`identity`],_M=Y(hM,gM,e=>{var{typed:t,abs:n,add:r,multiply:i,map:a,sqrt:o,subtract:s,inv:c,size:l,max:u,identity:d}=e,f=1e3,p=1e-6;function m(e){var t,a=0,o=e,m=d(l(e));do{var h=o;if(o=i(.5,r(h,c(m))),m=i(.5,r(m,c(h))),t=u(n(s(o,h))),t>p&&++a>f)throw Error(`computing square root of matrix: iterative method could not converge`)}while(t>p);return o}return t(hM,{"Array | Matrix":function(e){var t=Dl(e)?e.size():qf(e);switch(t.length){case 1:if(t[0]===1)return a(e,o);throw RangeError(`Matrix must be square (size: `+If(t)+`)`);case 2:if(t[0]===t[1])return m(e);throw RangeError(`Matrix must be square (size: `+If(t)+`)`);default:throw RangeError(`Matrix must be at most two dimensional (size: `+If(t)+`)`)}}})})})),vM,yM,bM,rCe=e((()=>{X(),vM=`sylvester`,yM=[`typed`,`schur`,`matrixFromColumns`,`matrix`,`multiply`,`range`,`concat`,`transpose`,`index`,`subset`,`add`,`subtract`,`identity`,`lusolve`,`abs`],bM=Y(vM,yM,e=>{var{typed:t,schur:n,matrixFromColumns:r,matrix:i,multiply:a,range:o,concat:s,transpose:c,index:l,subset:u,add:d,subtract:f,identity:p,lusolve:m,abs:h,config:g}=e;return t(vM,{"Matrix, Matrix, Matrix":_,"Array, Matrix, Matrix":function(e,t,n){return _(i(e),t,n)},"Array, Array, Matrix":function(e,t,n){return _(i(e),i(t),n)},"Array, Matrix, Array":function(e,t,n){return _(i(e),t,i(n))},"Matrix, Array, Matrix":function(e,t,n){return _(e,i(t),n)},"Matrix, Array, Array":function(e,t,n){return _(e,i(t),i(n))},"Matrix, Matrix, Array":function(e,t,n){return _(e,t,i(n))},"Array, Array, Array":function(e,t,n){return _(i(e),i(t),i(n)).toArray()}});function _(e,t,g){for(var _=t.size()[0],v=e.size()[0],y=n(e),b=y.T,x=y.U,S=n(a(-1,t)),C=S.T,w=S.U,T=a(a(c(x),g),w),E=o(0,v),D=[],O=(e,t)=>s(e,t,1),k=(e,t)=>s(e,t,0),A=0;A<_;A++)if(A<_-1&&h(u(C,l(A+1,A)))>1e-5){for(var j=k(u(T,l(E,[A])),u(T,l(E,[A+1]))),M=0;M<A;M++)j=d(j,k(a(D[M],u(C,l(M,A))),a(D[M],u(C,l(M,A+1)))));var N=a(p(v),a(-1,u(C,l(A,A)))),P=a(p(v),a(-1,u(C,l(A+1,A)))),F=a(p(v),a(-1,u(C,l(A,A+1)))),I=a(p(v),a(-1,u(C,l(A+1,A+1)))),L=m(k(O(d(b,N),P),O(F,d(b,I))),j);D[A]=L.subset(l(o(0,v),[0])),D[A+1]=L.subset(l(o(v,2*v),[0])),A++}else{for(var ee=u(T,l(E,[A])),R=0;R<A;R++)ee=d(ee,a(D[R],u(C,l(R,A))));D[A]=m(f(b,a(u(C,l(A,A)),p(v))),ee)}return a(x,a(i(r(...D)),c(w)))}})})),xM,SM,CM,iCe=e((()=>{X(),xM=`schur`,SM=[`typed`,`matrix`,`identity`,`multiply`,`qr`,`norm`,`subtract`],CM=Y(xM,SM,e=>{var{typed:t,matrix:n,identity:r,multiply:i,qr:a,norm:o,subtract:s}=e;return t(xM,{Array:function(e){var t=c(n(e));return{U:t.U.valueOf(),T:t.T.valueOf()}},Matrix:function(e){return c(e)}});function c(e){var t=e.size()[0],n=e,c=r(t),l=0,u;do{u=n;var d=a(n),f=d.Q,p=d.R;if(n=i(p,f),c=i(c,f),l++>100)break}while(o(s(n,u))>1e-4);return{U:c,T:n}}})})),wM,TM,EM,aCe=e((()=>{X(),wM=`lyap`,TM=[`typed`,`matrix`,`sylvester`,`multiply`,`transpose`],EM=Y(wM,TM,e=>{var{typed:t,matrix:n,sylvester:r,multiply:i,transpose:a}=e;return t(wM,{"Matrix, Matrix":function(e,t){return r(e,a(e),i(-1,t))},"Array, Matrix":function(e,t){return r(n(e),a(n(e)),i(-1,t))},"Matrix, Array":function(e,t){return r(e,a(n(e)),n(i(-1,t)))},"Array, Array":function(e,t){return r(n(e),a(n(e)),n(i(-1,t))).toArray()}})})})),DM,OM,kM,oCe=e((()=>{X(),ru(),a_(),p_(),DM=`divide`,OM=[`typed`,`matrix`,`multiply`,`equalScalar`,`divideScalar`,`inv`],kM=Y(DM,OM,e=>{var{typed:t,matrix:n,multiply:r,equalScalar:i,divideScalar:a,inv:o}=e,s=i_({typed:t,equalScalar:i}),c=f_({typed:t});return t(`divide`,ece({"Array | Matrix, Array | Matrix":function(e,t){return r(e,o(t))},"DenseMatrix, any":function(e,t){return c(e,t,a,!1)},"SparseMatrix, any":function(e,t){return s(e,t,a,!1)},"Array, any":function(e,t){return c(n(e),t,a,!1).valueOf()},"any, Array | Matrix":function(e,t){return r(e,o(t))}},a.signatures))})})),AM,jM,MM,sCe=e((()=>{Ql(),X(),AM=`distance`,jM=[`typed`,`addScalar`,`subtractScalar`,`divideScalar`,`multiplyScalar`,`deepEqual`,`sqrt`,`abs`],MM=Y(AM,jM,e=>{var{typed:t,addScalar:n,subtractScalar:r,multiplyScalar:i,divideScalar:a,deepEqual:o,sqrt:s,abs:c}=e;return t(AM,{"Array, Array, Array":function(e,t,n){if(e.length===2&&t.length===2&&n.length===2){if(!u(e))throw TypeError(`Array with 2 numbers or BigNumbers expected for first argument`);if(!u(t))throw TypeError(`Array with 2 numbers or BigNumbers expected for second argument`);if(!u(n))throw TypeError(`Array with 2 numbers or BigNumbers expected for third argument`);if(o(t,n))throw TypeError(`LinePoint1 should not be same with LinePoint2`);var a=r(n[1],t[1]),s=r(t[0],n[0]),c=r(i(n[0],t[1]),i(t[0],n[1]));
2633return g(e[0],e[1],a,s,c)}else throw TypeError(`Invalid Arguments: Try again`)},"Object, Object, Object":function(e,t,n){if(Object.keys(e).length===2&&Object.keys(t).length===2&&Object.keys(n).length===2){if(!u(e))throw TypeError(`Values of pointX and pointY should be numbers or BigNumbers`);if(!u(t))throw TypeError(`Values of lineOnePtX and lineOnePtY should be numbers or BigNumbers`);if(!u(n))throw TypeError(`Values of lineTwoPtX and lineTwoPtY should be numbers or BigNumbers`);if(o(m(t),m(n)))throw TypeError(`LinePoint1 should not be same with LinePoint2`);if(`pointX`in e&&`pointY`in e&&`lineOnePtX`in t&&`lineOnePtY`in t&&`lineTwoPtX`in n&&`lineTwoPtY`in n){var a=r(n.lineTwoPtY,t.lineOnePtY),s=r(t.lineOnePtX,n.lineTwoPtX),c=r(i(n.lineTwoPtX,t.lineOnePtY),i(t.lineOnePtX,n.lineTwoPtY));return g(e.pointX,e.pointY,a,s,c)}else throw TypeError(`Key names do not match`)}else throw TypeError(`Invalid Arguments: Try again`)},"Array, Array":function(e,t){if(e.length===2&&t.length===3){if(!u(e))throw TypeError(`Array with 2 numbers or BigNumbers expected for first argument`);if(!d(t))throw TypeError(`Array with 3 numbers or BigNumbers expected for second argument`);return g(e[0],e[1],t[0],t[1],t[2])}else if(e.length===3&&t.length===6){if(!d(e))throw TypeError(`Array with 3 numbers or BigNumbers expected for first argument`);if(!p(t))throw TypeError(`Array with 6 numbers or BigNumbers expected for second argument`);return _(e[0],e[1],e[2],t[0],t[1],t[2],t[3],t[4],t[5])}else if(e.length===t.length&&e.length>0){if(!f(e)||!f(t))throw TypeError(`All values of an array should be numbers or BigNumbers`);return v(e,t)}else throw TypeError(`Invalid Arguments: Try again`)},"Object, Object":function(e,t){if(Object.keys(e).length===2&&Object.keys(t).length===3){if(!u(e))throw TypeError(`Values of pointX and pointY should be numbers or BigNumbers`);if(!d(t))throw TypeError(`Values of xCoeffLine, yCoeffLine and constant should be numbers or BigNumbers`);if(`pointX`in e&&`pointY`in e&&`xCoeffLine`in t&&`yCoeffLine`in t&&`constant`in t)return g(e.pointX,e.pointY,t.xCoeffLine,t.yCoeffLine,t.constant);throw TypeError(`Key names do not match`)}else if(Object.keys(e).length===3&&Object.keys(t).length===6){if(!d(e))throw TypeError(`Values of pointX, pointY and pointZ should be numbers or BigNumbers`);if(!p(t))throw TypeError(`Values of x0, y0, z0, a, b and c should be numbers or BigNumbers`);if(`pointX`in e&&`pointY`in e&&`x0`in t&&`y0`in t&&`z0`in t&&`a`in t&&`b`in t&&`c`in t)return _(e.pointX,e.pointY,e.pointZ,t.x0,t.y0,t.z0,t.a,t.b,t.c);throw TypeError(`Key names do not match`)}else if(Object.keys(e).length===2&&Object.keys(t).length===2){if(!u(e))throw TypeError(`Values of pointOneX and pointOneY should be numbers or BigNumbers`);if(!u(t))throw TypeError(`Values of pointTwoX and pointTwoY should be numbers or BigNumbers`);if(`pointOneX`in e&&`pointOneY`in e&&`pointTwoX`in t&&`pointTwoY`in t)return v([e.pointOneX,e.pointOneY],[t.pointTwoX,t.pointTwoY]);throw TypeError(`Key names do not match`)}else if(Object.keys(e).length===3&&Object.keys(t).length===3){if(!d(e))throw TypeError(`Values of pointOneX, pointOneY and pointOneZ should be numbers or BigNumbers`);if(!d(t))throw TypeError(`Values of pointTwoX, pointTwoY and pointTwoZ should be numbers or BigNumbers`);if(`pointOneX`in e&&`pointOneY`in e&&`pointOneZ`in e&&`pointTwoX`in t&&`pointTwoY`in t&&`pointTwoZ`in t)return v([e.pointOneX,e.pointOneY,e.pointOneZ],[t.pointTwoX,t.pointTwoY,t.pointTwoZ]);throw TypeError(`Key names do not match`)}else throw TypeError(`Invalid Arguments: Try again`)},Array:function(e){if(!h(e))throw TypeError(`Incorrect array format entered for pairwise distance calculation`);return y(e)}});function l(e){return typeof e==`number`||xl(e)}function u(e){return e.constructor!==Array&&(e=m(e)),l(e[0])&&l(e[1])}function d(e){return e.constructor!==Array&&(e=m(e)),l(e[0])&&l(e[1])&&l(e[2])}function f(e){return Array.isArray(e)||(e=m(e)),e.every(l)}function p(e){return e.constructor!==Array&&(e=m(e)),l(e[0])&&l(e[1])&&l(e[2])&&l(e[3])&&l(e[4])&&l(e[5])}function m(e){for(var t=Object.keys(e),n=[],r=0;r<t.length;r++)n.push(e[t[r]]);return n}function h(e){if(e[0].length===2&&l(e[0][0])&&l(e[0][1])){if(e.some(e=>e.length!==2||!l(e[0])||!l(e[1])))return!1}else if(e[0].length===3&&l(e[0][0])&&l(e[0][1])&&l(e[0][2])){if(e.some(e=>e.length!==3||!l(e[0])||!l(e[1])||!l(e[2])))return!1}else return!1;return!0}function g(e,t,r,o,l){return a(c(n(n(i(r,e),i(o,t)),l)),s(n(i(r,r),i(o,o))))}function _(e,t,o,c,l,u,d,f,p){var m=[r(i(r(l,t),p),i(r(u,o),f)),r(i(r(u,o),d),i(r(c,e),p)),r(i(r(c,e),f),i(r(l,t),d))];m=s(n(n(i(m[0],m[0]),i(m[1],m[1])),i(m[2],m[2])));var h=s(n(n(i(d,d),i(f,f)),i(p,p)));return a(m,h)}function v(e,t){for(var a=e.length,o=0,c=0,l=0;l<a;l++)c=r(e[l],t[l]),o=n(i(c,c),o);return s(o)}function y(e){for(var t=[],n=[],r=[],i=0;i<e.length-1;i++)for(var a=i+1;a<e.length;a++)e[0].length===2?(n=[e[i][0],e[i][1]],r=[e[a][0],e[a][1]]):e[0].length===3&&(n=[e[i][0],e[i][1],e[i][2]],r=[e[a][0],e[a][1],e[a][2]]),t.push(v(n,r));return t}})}
2633)),NM,PM,FM,cCe=e((()=>{X(),NM=`intersect`,PM=[`typed`,`config`,`abs`,`add`,`addScalar`,`matrix`,`multiply`,`multiplyScalar`,`divideScalar`,`subtract`,`smaller`,`equalScalar`,`flatten`,`isZero`,`isNumeric`],FM=Y(NM,PM,e=>{var{typed:t,config:n,abs:r,add:i,addScalar:a,matrix:o,multiply:s,multiplyScalar:c,divideScalar:l,subtract:u,smaller:d,equalScalar:f,flatten:p,isZero:m,isNumeric:h}=e;return t(`intersect`,{"Array, Array, Array":g,"Array, Array, Array, Array":_,"Matrix, Matrix, Matrix":function(e,t,n){var r=g(e.valueOf(),t.valueOf(),n.valueOf());return r===null?null:o(r)},"Matrix, Matrix, Matrix, Matrix":function(e,t,n,r){var i=_(e.valueOf(),t.valueOf(),n.valueOf(),r.valueOf());return i===null?null:o(i)}});function g(e,t,n){if(e=v(e),t=v(t),n=v(n),!b(e))throw TypeError(`Array with 3 numbers or BigNumbers expected for first argument`);if(!b(t))throw TypeError(`Array with 3 numbers or BigNumbers expected for second argument`);if(!x(n))throw TypeError(`Array with 4 numbers expected as third argument`);return T(e[0],e[1],e[2],t[0],t[1],t[2],n[0],n[1],n[2],n[3])}function _(e,t,n,r){if(e=v(e),t=v(t),n=v(n),r=v(r),e.length===2){if(!y(e))throw TypeError(`Array with 2 numbers or BigNumbers expected for first argument`);if(!y(t))throw TypeError(`Array with 2 numbers or BigNumbers expected for second argument`);if(!y(n))throw TypeError(`Array with 2 numbers or BigNumbers expected for third argument`);if(!y(r))throw TypeError(`Array with 2 numbers or BigNumbers expected for fourth argument`);return S(e,t,n,r)}else if(e.length===3){if(!b(e))throw TypeError(`Array with 3 numbers or BigNumbers expected for first argument`);if(!b(t))throw TypeError(`Array with 3 numbers or BigNumbers expected for second argument`);if(!b(n))throw TypeError(`Array with 3 numbers or BigNumbers expected for third argument`);if(!b(r))throw TypeError(`Array with 3 numbers or BigNumbers expected for fourth argument`);return w(e[0],e[1],e[2],t[0],t[1],t[2],n[0],n[1],n[2],r[0],r[1],r[2])}else throw TypeError(`Arrays with two or thee dimensional points expected`)}function v(e){return e.length===1?e[0]:e.length>1&&Array.isArray(e[0])&&e.every(e=>Array.isArray(e)&&e.length===1)?p(e):e}function y(e){return e.length===2&&h(e[0])&&h(e[1])}function b(e){return e.length===3&&h(e[0])&&h(e[1])&&h(e[2])}function x(e){return e.length===4&&h(e[0])&&h(e[1])&&h(e[2])&&h(e[3])}function S(e,t,o,f){var p=e,h=o,g=u(p,t),_=u(h,f),v=u(c(g[0],_[1]),c(_[0],g[1]));if(m(v)||d(r(v),n.relTol))return null;var y=c(_[0],p[1]),b=c(_[1],p[0]),x=c(_[0],h[1]),S=c(_[1],h[0]);return i(s(g,l(a(u(u(y,b),x),S),v)),p)}function C(e,t,n,r,i,o,s,l,d,f,p,m){var h=c(u(e,t),u(n,r)),g=c(u(i,o),u(s,l)),_=c(u(d,f),u(p,m));return a(a(h,g),_)}function w(e,t,n,r,i,o,s,d,p,h,g,_){var v=C(e,s,h,s,t,d,g,d,n,p,_,p),y=C(h,s,r,e,g,d,i,t,_,p,o,n),b=C(e,s,r,e,t,d,i,t,n,p,o,n),x=C(h,s,h,s,g,d,g,d,_,p,_,p),S=C(r,e,r,e,i,t,i,t,o,n,o,n),w=u(c(v,y),c(b,x)),T=u(c(S,x),c(y,y));if(m(T))return null;var E=l(w,T),D=l(a(v,c(E,y)),x),O=a(e,c(E,u(r,e))),k=a(t,c(E,u(i,t))),A=a(n,c(E,u(o,n))),j=a(s,c(D,u(h,s))),M=a(d,c(D,u(g,d))),N=a(p,c(D,u(_,p)));return f(O,j)&&f(k,M)&&f(A,N)?[O,k,A]:null}function T(e,t,n,r,i,o,s,d,f,p){var m=c(e,s),h=c(r,s),g=c(t,d),_=c(i,d),v=c(n,f),y=c(o,f),b=l(u(u(u(p,m),g),v),u(u(u(a(a(h,_),y),m),g),v));return[a(e,c(b,u(r,e))),a(t,c(b,u(i,t))),a(n,c(b,u(o,n)))]}})})),IM,LM,RM,zM=e((()=>{Wp(),X(),Pu(),lx(),IM=`sum`,LM=[`typed`,`config`,`add`,`numeric`],RM=Y(IM,LM,e=>{var{typed:t,config:n,add:r,numeric:i}=e;return t(IM,{"Array | Matrix":a,"Array | Matrix, number | BigNumber":o,"...":function(e){if(Rp(e))throw TypeError(`Scalar values expected in function sum`);return a(e)}});function a(e){var t;return zp(e,function(e){try{t=t===void 0?e:r(t,e)}catch(t){throw cx(t,`sum`,e)}}),t===void 0&&(t=i(0,n.number)),typeof t==`string`&&(t=i(t,uu(t,n))),t}function o(e,t){try{return Vp(e,t,r)}catch(e){throw cx(e,`sum`)}}})})),BM,VM,HM,UM=e((()=>{Wp(),X(),Lp(),lx(),Tp(),Kf(),BM=`cumsum`,VM=[`typed`,`add`,`unaryPlus`],HM=Y(BM,VM,e=>{var{typed:t,add:n,unaryPlus:r}=e;return t(BM,{Array:i,Matrix:function(e){return e.create(i(e.valueOf(),e.datatype()))},"Array, number | BigNumber":o,"Matrix, number | BigNumber":function(e,t){return e.create(o(e.valueOf(),t),e.datatype())},"...":function(e){if(Rp(e))throw TypeError(`All values expected to be scalar in function cumsum`);return i(e)}});function i(e){try{return a(e)}catch(e){throw cx(e,BM)}}function a(e){if(e.length===0)return[];for(var t=[r(e[0])],i=1;i<e.length;++i)t.push(n(t[i-1],e[i]));return t}function o(e,t){var n=qf(e);if(t<0||t>=n.length)throw new Gf(t,n.length);try{return s(e,t)}catch(e){throw cx(e,BM)}}function s(e,t){var n,r,i;if(t<=0){var o=e[0][0];if(Array.isArray(o)){for(i=Ip(e),r=[],n=0;n<i.length;n++)r[n]=s(i[n],t-1);return r}else return a(e)}else{for(r=[],n=0;n<e.length;n++)r[n]=s(e[n],t-1);return r}}})})),WM,GM,KM,qM=e((()=>{Wp(),Tp(),X(),lx(),WM=`mean`,GM=[`typed`,`add`,`divide`],KM=Y(WM,GM,e=>{var{typed:t,add:n,divide:r}=e;return t(WM,{"Array | Matrix":a,"Array | Matrix, number | BigNumber":i,"...":function(e){if(Rp(e))throw TypeError(`Scalar values expected in function mean`);return a(e)}});function i(e,t){try{return r(Vp(e,t,n),(Array.isArray(e)?qf(e):e.size())[t])}catch(e){throw cx(e,`mean`)}}function a(e){var t,i=0;if(zp(e,function(e){try{t=t===void 0?e:n(t,e),i++}catch(t){throw cx(t,`mean`,e)}}),i===0)throw Error(`Cannot calculate the mean of an empty array`);return r(t,i)}})})),JM,YM,XM,lCe=e((()=>{Wp(),Tp(),X(),lx(),JM=`median`,YM=[`typed`,`add`,`divide`,`compare`,`partitionSelect`],XM=Y(JM,YM,e=>{var{typed:t,add:n,divide:r,compare:i,partitionSelect:a}=e;function o(e){try{e=cp(e.valueOf());var t=e.length;if(t===0)throw Error(`Cannot calculate median of an empty array`);if(t%2==0){for(var n=t/2-1,r=a(e,n+1),o=e[n],l=0;l<n;++l)i(e[l],o)>0&&(o=e[l]);return c(o,r)}else return s(a(e,(t-1)/2))}catch(e){throw cx(e,`median`)}}var s=t({"number | BigNumber | Complex | Unit":function(e){return e}}),c=t({"number | BigNumber | Complex | Unit, number | BigNumber | Complex | Unit":function(e,t){return r(n(e,t),2)}});return t(JM,{"Array | Matrix":o,"Array | Matrix, number | BigNumber":function(e,t){throw Error(`median(A, dim) is not yet supported`)},"...":function(e){if(Rp(e))throw TypeError(`Scalar values expected in function median`);return o(e)}})})})),ZM,QM,$M,uCe=e((()=>{Tp(),X(),lx(),ZM=`mad`,QM=[`typed`,`abs`,`map`,`median`,`subtract`],$M=Y(ZM,QM,e=>{var{typed:t,abs:n,map:r,median:i,subtract:a}=e;return t(ZM,{"Array | Matrix":o,"...":function(e){return o(e)}});function o(e){if(e=cp(e.valueOf()),e.length===0)throw Error(`Cannot calculate median absolute deviation (mad) of an empty array`);try{var t=i(e);return i(r(e,function(e){return n(a(e,t))}))}catch(e){throw e instanceof TypeError&&e.message.includes(`median`)?TypeError(e.message.replace(`median`,`mad`)):cx(e,`mad`)}}})})),eN,tN,nN,rN,iN=e((()=>{Wp(),Ql(),X(),lx(),eN=`unbiased`,tN=`variance`,nN=[`typed`,`add`,`subtract`,`multiply`,`divide`,`mapSlices`,`isNaN`],rN=Y(tN,nN,e=>{var{typed:t,add:n,subtract:r,multiply:i,divide:a,mapSlices:o,isNaN:s}=e;return t(tN,{"Array | Matrix":function(e){return c(e,eN)},"Array | Matrix, string":c,"Array | Matrix, number | BigNumber":function(e,t){return l(e,t,eN)},"Array | Matrix, number | BigNumber, string":l,"...":function(e){return c(e,eN)}});function c(e,t){var o,c=0;if(e.length===0)throw SyntaxError(`Function variance requires one or more parameters (0 provided)`);if(zp(e,function(e){try{o=o===void 0?e:n(o,e),c++}catch(t){throw cx(t,`variance`,e)}}),c===0)throw Error(`Cannot calculate variance of an empty array`);var l=a(o,c);if(o=void 0,zp(e,function(e){var t=r(e,l);o=o===void 0?i(t,t):n(o,i(t,t))}),s(o))return o;switch(t){case`uncorrected`:return a(o,c);case`biased`:return a(o,c+1);case`unbiased`:var u=xl(o)?o.mul(0):0;return c===1?u:a(o,c-1);
2633default:throw Error(`Unknown normalization "`+t+`". Choose "unbiased" (default), "uncorrected", or "biased".`)}}function l(e,t,n){try{if(e.length===0)throw SyntaxError(`Function variance requires one or more parameters (0 provided)`);return o(e,t,e=>c(e,n))}catch(e){throw cx(e,`variance`)}}})})),aN,oN,sN,cN=e((()=>{Ql(),Tp(),X(),aN=`quantileSeq`,oN=[`typed`,`?bignumber`,`add`,`subtract`,`divide`,`multiply`,`partitionSelect`,`compare`,`isInteger`,`smaller`,`smallerEq`,`larger`,`mapSlices`],sN=Y(aN,oN,e=>{var{typed:t,bignumber:n,add:r,subtract:i,divide:a,multiply:o,partitionSelect:s,compare:c,isInteger:l,smaller:u,smallerEq:d,larger:f,mapSlices:p}=e;return t(aN,{"Array | Matrix, number | BigNumber":(e,t)=>h(e,t,!1),"Array | Matrix, number | BigNumber, number":(e,t,n)=>m(e,t,!1,n,h),"Array | Matrix, number | BigNumber, boolean":h,"Array | Matrix, number | BigNumber, boolean, number":(e,t,n,r)=>m(e,t,n,r,h),"Array | Matrix, Array | Matrix":(e,t)=>g(e,t,!1),"Array | Matrix, Array | Matrix, number":(e,t,n)=>m(e,t,!1,n,g),"Array | Matrix, Array | Matrix, boolean":g,"Array | Matrix, Array | Matrix, boolean, number":(e,t,n,r)=>m(e,t,n,r,g)});function m(e,t,n,r,i){return p(e,r,e=>i(e,t,n))}function h(e,t,i){var o,s=e.valueOf();if(u(t,0))throw Error(`N/prob must be non-negative`);if(d(t,1))return bl(t)?_(s,t,i):n(_(s,t,i));if(f(t,1)){if(!l(t))throw Error(`N must be a positive integer`);if(f(t,4294967295))throw Error(`N must be less than or equal to 2^32-1, as that is the maximum length of an Array`);var c=r(t,1);o=[];for(var p=0;u(p,t);p++){var m=a(p+1,c);o.push(_(s,m,i))}return bl(t)?o:n(o)}}function g(e,t,n){for(var r=e.valueOf(),i=t.valueOf(),a=[],o=0;o<i.length;++o)a.push(_(r,i[o],n));return a}function _(e,t,n){var a=cp(e),u=a.length;if(u===0)throw Error(`Cannot calculate quantile of an empty sequence`);var d=bl(t)?t*(u-1):t.times(u-1),f=bl(t)?Math.floor(d):d.floor().toNumber(),p=bl(t)?d%1:d.minus(f);if(l(d))return n?a[d]:s(a,bl(t)?d:d.valueOf());var m,h;if(n)m=a[f],h=a[f+1];else{h=s(a,f+1),m=a[f];for(var g=0;g<f;++g)c(a[g],m)>0&&(m=a[g])}return r(o(m,i(1,p)),o(h,p))}})})),lN,uN,dN,fN=e((()=>{X(),Ql(),lN=`std`,uN=[`typed`,`map`,`sqrt`,`variance`],dN=Y(lN,uN,e=>{var{typed:t,map:n,sqrt:r,variance:i}=e;return t(lN,{"Array | Matrix":a,"Array | Matrix, string":a,"Array | Matrix, number | BigNumber":a,"Array | Matrix, number | BigNumber, string":a,"...":function(e){return a(e)}});function a(e,t){if(e.length===0)throw SyntaxError(`Function std requires one or more parameters (0 provided)`);try{var a=i.apply(null,arguments);return Ol(a)?n(a,r):r(a)}catch(e){throw e instanceof TypeError&&e.message.includes(` variance`)?TypeError(e.message.replace(` variance`,` std`)):e}}})})),pN,mN,hN,dCe=e((()=>{X(),pN=`corr`,mN=[`typed`,`matrix`,`mean`,`sqrt`,`sum`,`add`,`subtract`,`multiply`,`pow`,`divide`],hN=Y(pN,mN,e=>{var{typed:t,matrix:n,sqrt:r,sum:i,add:a,subtract:o,multiply:s,pow:c,divide:l}=e;return t(pN,{"Array, Array":function(e,t){return u(e,t)},"Matrix, Matrix":function(e,t){var r=u(e.toArray(),t.toArray());return Array.isArray(r)?n(r):r}});function u(e,t){var n=[];if(Array.isArray(e[0])&&Array.isArray(t[0])){if(e.length!==t.length)throw SyntaxError(`Dimension mismatch. Array A and B must have the same length.`);for(var r=0;r<e.length;r++){if(e[r].length!==t[r].length)throw SyntaxError(`Dimension mismatch. Array A and B must have the same number of elements.`);n.push(d(e[r],t[r]))}return n}else{if(e.length!==t.length)throw SyntaxError(`Dimension mismatch. Array A and B must have the same number of elements.`);return d(e,t)}}function d(e,t){var n=e.length,u=i(e),d=i(t),f=e.reduce((e,n,r)=>a(e,s(n,t[r])),0),p=i(e.map(e=>c(e,2))),m=i(t.map(e=>c(e,2)));return l(o(s(n,f),s(u,d)),r(s(o(s(n,p),c(u,2)),o(s(n,m),c(d,2)))))}})}));function gN(e,t,n,r,i,a){if(e<0||!lu(e))throw RangeError(`Bernoulli index must be nonnegative integer`);if(e===0)return t(1);if(e===1)return a(t(-1),t(2));if(e%2==1)return t(0);var o=t(1);n.length===1&&n.push([a(o,t(-3)),a(o,t(-2)),a(o,t(6))]);for(var s=e/2,c=t(0),l=t(2);n.length<=s;){for(var u=n.length,d=Math.floor((u+1)/2),f=c,p=1;p<d;++p)f=r(f,i(n[p][0],n[u-p][0]));f=i(f,l),u%2==0&&(f=r(f,i(n[d][0],n[d][0]))),f=a(f,t(-(2*u+1)));var m=a(i(n[u-1][1],t(-u*(2*u-1))),l);n.push([f,m,i(m,f)])}return n[s][2]}var _N,vN,yN,fCe=e((()=>{X(),Pu(),_N=`bernoulli`,vN=[`typed`,`config`,`isInteger`,`number`,`?BigNumber`,`?Fraction`],yN=Y(_N,vN,e=>{var{typed:t,config:n,number:r,BigNumber:i,Fraction:a}=e,o=[void 0],s=[void 0],c=[void 0],l=50;return t(_N,{number:e=>gN(e,e=>
2633e,o,(e,t)=>e+t,(e,t)=>e*t,(e,t)=>e/t),"bigint | Fraction":e=>gN(r(e),e=>new a(e),s,(e,t)=>e.add(t),(e,t)=>e.mul(t),(e,t)=>e.div(t)),BigNumber:e=>(n.precision!==l&&(c=[void 0],l=n.precision),gN(r(e),e=>new i(e),c,(e,t)=>e.add(t),(e,t)=>e.mul(t),(e,t)=>e.div(t)))})})}));function bN(e){return e.isInteger()&&e.gte(0)}var xN,SN,CN,pCe=e((()=>{X(),Om(),xN=`combinations`,SN=[`typed`],CN=Y(xN,SN,e=>{var{typed:t}=e;return t(xN,{"number, number":Dm,"BigNumber, BigNumber":function(e,t){var n=e.constructor,r,i,a=e.minus(t),o=new n(1);if(!bN(e)||!bN(t))throw TypeError(`Positive integer value expected in function combinations`);if(t.gt(e))throw TypeError(`k must be less than n in function combinations`);if(r=o,t.lt(a))for(i=o;i.lte(a);i=i.plus(o))r=r.times(t.plus(i)).dividedBy(i);else for(i=o;i.lte(t);i=i.plus(o))r=r.times(a.plus(i)).dividedBy(i);return r}})})}));function wN(e){return e.isInteger()&&e.gte(0)}var TN,EN,DN,mCe=e((()=>{X(),Pu(),Em(),TN=`combinationsWithRep`,EN=[`typed`],DN=Y(TN,EN,e=>{var{typed:t}=e;return t(TN,{"number, number":function(e,t){if(!lu(e)||e<0||!lu(t)||t<0)throw TypeError(`Positive integer value expected in function combinationsWithRep`);if(e<1)throw TypeError(`k must be less than or equal to n + k - 1`);return t<e-1?Tm(e,e+t-1)/Tm(1,t):Tm(t+1,e+t-1)/Tm(1,e-1)},"BigNumber, BigNumber":function(e,t){var n=e.constructor,r,i,a=new n(1),o=e.minus(a);if(!wN(e)||!wN(t))throw TypeError(`Positive integer value expected in function combinationsWithRep`);if(e.lt(a))throw TypeError(`k must be less than or equal to n + k - 1 in function combinationsWithRep`);if(r=a,t.lt(o))for(i=a;i.lte(o);i=i.plus(a))r=r.times(t.plus(i)).dividedBy(i);else for(i=a;i.lte(t);i=i.plus(a))r=r.times(o.plus(i)).dividedBy(i);return r}})})})),ON,kN,AN,hCe=e((()=>{X(),ph(),ON=`gamma`,kN=[`typed`,`config`,`multiplyScalar`,`pow`,`BigNumber`,`Complex`],AN=Y(ON,kN,e=>{var{typed:t,config:n,multiplyScalar:r,pow:i,BigNumber:a,Complex:o}=e;function s(e){if(e.im===0)return zm(e.re);if(e.re<.5){var t=new o(1-e.re,-e.im),n=new o(Math.PI*e.re,Math.PI*e.im);return new o(Math.PI).div(n.sin()).div(s(t))}e=new o(e.re-1,e.im);for(var r=new o(Hm[0],0),i=1;i<Hm.length;++i){var a=new o(Hm[i],0);r=r.add(a.div(e.add(i)))}var c=new o(e.re+Vm+.5,e.im),l=Math.sqrt(2*Math.PI),u=c.pow(e.add(.5)),d=c.neg().exp();return r.mul(l).mul(u).mul(d)}return t(ON,{number:zm,Complex:s,BigNumber:function(e){if(e.isInteger())return e.isNegative()||e.isZero()?new a(1/0):c(e.minus(1));if(!e.isFinite())return new a(e.isNegative()?NaN:1/0);throw Error(`Integer BigNumber expected`)}});function c(e){if(e<8)return new a([1,1,2,6,24,120,720,5040][e]);var t=n.precision+(Math.log(e.toNumber())|0),r=a.clone({precision:t});if(e%2==1)return e.times(c(new a(e-1)));for(var i=e,o=new r(e),s=e.toNumber();i>2;)i-=2,s+=i,o=o.times(s);return new a(o.toPrecision(a.precision))}})})),jN,MN,NN,gCe=e((()=>{ph(),X(),Pu(),jN=`lgamma`,MN=[`Complex`,`typed`],NN=Y(jN,MN,e=>{var{Complex:t,typed:n}=e,r=7,i=7,a=[-.029550653594771242,.00641025641025641,-.0019175269175269176,.0008417508417508417,-.0005952380952380953,.0007936507936507937,-.002777777777777778,.08333333333333333];return n(jN,{number:Bm,Complex:o,BigNumber:function(){throw Error(`mathjs doesn't yet provide an implementation of the algorithm lgamma for BigNumber`)}});function o(e){var n=6.283185307179586,a=1.1447298858494002,l=.1;if(e.isNaN())return new t(NaN,NaN);if(e.im===0)return new t(Bm(e.re),0);if(e.re>=r||Math.abs(e.im)>=i)return s(e);if(e.re<=l){var u=hce(n,e.im)*Math.floor(.5*e.re+.25),d=e.mul(Math.PI).sin().log(),f=o(new t(1-e.re,-e.im));return new t(a,u).sub(d).sub(f)}else if(e.im>=0)return c(e);else return c(e.conjugate()).conjugate()}function s(e){for(var n=e.sub(.5).mul(e.log()).sub(e).add(Um),r=new t(1,0).div(e),i=r.div(e),o=a[0],s=a[1],c=2*i.re,l=i.re*i.re+i.im*i.im,u=2;u<8;u++){var d=s;s=-l*o+a[u],o=c*o+d}var f=r.mul(i.mul(o).add(s));return n.add(f)}function c(e){var n=0,i=0,a=e;for(e=e.add(1);e.re<=r;){a=a.mul(e);var o=+(a.im<0);o!==0&&i===0&&n++,i=o,e=e.add(1)}return s(e).sub(a.log()).sub(new t(0,n*2*Math.PI*1))}})})),PN,FN,IN,_Ce=e((()=>{Wp(),X(),PN=`factorial`,FN=[`typed`,`gamma`],IN=Y(PN,FN,e=>{var{typed:t,gamma:n}=e;return t(PN,{number:function(e){if(e<0)throw Error(`Value must be non-negative`);return n(e+1)},BigNumber:function(e){if(e.isNegative())throw Error(`Value must be non-negative`);return n(e.plus(1))},"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),LN,RN,zN,vCe=e((()=>{X(),LN=`kldivergence`,RN=[`typed`,`matrix`,`divide`,`sum`,`multiply`,`map`,`dotDivide`,`log`,`isNumeric`],zN=Y(LN,RN,e=>{var{typed:t,matrix:n,divide:r,sum:i,multiply:a,map:o,dotDivide:s,log:c,isNumeric:l}=e;return t(LN,{"Array, Array":function(e,t){return u(n(e),n(t))},"Matrix, Array":function(e,t){return u(e,n(t))},"Array, Matrix":function(e,t){return u(n(e),t)},"Matrix, Matrix":function(e,t){return u(e,t)}});function u(e,t){var n=t.size().length,u=e.size().length;if(n>1)throw Error(`first object must be one dimensional`);if(u>1)throw Error(`second object must be one dimensional`);if(n!==u)throw Error(`Length of two vectors must be equal`);if(i(e)===0)throw Error(`Sum of elements in first object must be non zero`);if(i(t)===0)throw Error(`Sum of elements in second object must be non zero`);var d=r(e,i(e)),f=i(a(d,o(s(d,r(t,i(t))),e=>c(e))));return l(f)?f:NaN}})})),BN,VN,HN,yCe=e((()=>{Wp(),X(),BN=`multinomial`,VN=[`typed`,`add`,`divide`,`multiply`,`factorial`,`isInteger`,`isPositive`],HN=Y(BN,VN,e=>{var{typed:t,add:n,divide:r,multiply:i,factorial:a,isInteger:o,isPositive:s}=e;return t(BN,{"Array | Matrix":function(e){var t=0,c=1;return zp(e,function(e){if(!o(e)||!s(e))throw TypeError(`Positive integer value expected in function multinomial`);t=n(t,e),c=i(c,a(e))}),r(a(t),c)}})})}));function UN(e){return e.isInteger()&&e.gte(0)}var WN,GN,KN,bCe=e((()=>{Pu(),Em(),X(),WN=`permutations`,GN=[`typed`,`factorial`],KN=Y(WN,GN,e=>{var{typed:t,factorial:n}=e;return t(WN,{"number | BigNumber":n,"number, number":function(e,t){if(!lu(e)||e<0||!lu(t)||t<0)throw TypeError(`Positive integer value expected in function permutations`);if(t>e)throw TypeError(`second argument k must be less than or equal to first argument n`);return Tm(e-t+1,e)},"BigNumber, BigNumber":function(e,t){var n,r;if(!UN(e)||!UN(t))throw TypeError(`Positive integer value expected in function permutations`);if(t.gt(e))throw TypeError(`second argument k must be less than or equal to first argument n`);
2633for(n=e.mul(0).add(1),r=e.minus(t).plus(1);r.lte(e);r=r.plus(1))n=n.times(r);return n}})})}));function qN(e){var t;function n(e){t=e===null?YN:(0,JN.default)(String(e))}n(e);function r(){return t()}return r}var JN,YN,XN=e((()=>{JN=t(nne(),1),YN=(0,JN.default)(Date.now())})),ZN,QN,$N,xCe=e((()=>{Tp(),X(),Ql(),XN(),ZN=`pickRandom`,QN=[`typed`,`config`,`?on`],$N=Y(ZN,QN,e=>{var{typed:t,config:n,on:r}=e,i=qN(n.randomSeed);return r&&r(`config`,function(e,t){e.randomSeed!==t.randomSeed&&(i=qN(e.randomSeed))}),t(ZN,{"Array | Matrix":function(e){return a(e,{})},"Array | Matrix, Object":function(e,t){return a(e,t)},"Array | Matrix, number":function(e,t){return a(e,{number:t})},"Array | Matrix, Array | Matrix":function(e,t){return a(e,{weights:t})},"Array | Matrix, Array | Matrix, number":function(e,t,n){return a(e,{number:n,weights:t})},"Array | Matrix, number, Array | Matrix":function(e,t,n){return a(e,{number:t,weights:n})}});function a(e,t){var{number:n,weights:r,elementWise:a=!0}=t,o=n===void 0;o&&(n=1);var s=Dl(e)?e.create:Dl(r)?r.create:null;e=e.valueOf(),r&&=r.valueOf(),a===!0&&(e=cp(e),r=cp(r));var c=0;if(r!==void 0){if(r.length!==e.length)throw Error(`Weights must have the same length as possibles`);for(var l=0,u=r.length;l<u;l++){if(!bl(r[l])||r[l]<0)throw Error(`Weights must be an array of positive numbers`);c+=r[l]}}for(var d=e.length,f=[],p;f.length<n;){if(r===void 0)p=e[Math.floor(i()*d)];else for(var m=i()*c,h=0,g=e.length;h<g;h++)if(m-=r[h],m<0){p=e[h];break}f.push(p)}return o?f[0]:s?s(f):f}})}));function eP(e,t){var n=[];if(e=e.slice(0),e.length>1)for(var r=0,i=e.shift();r<i;r++)n.push(eP(e,t));else for(var a=0,o=e.shift();a<o;a++)n.push(t());return n}var tP=e((()=>{})),nP,rP,iP,SCe=e((()=>{X(),Ql(),XN(),tP(),nP=`random`,rP=[`typed`,`config`,`?on`],iP=Y(nP,rP,e=>{var{typed:t,config:n,on:r}=e,i=qN(n.randomSeed);return r&&r(`config`,function(e,t){e.randomSeed!==t.randomSeed&&(i=qN(e.randomSeed))}),t(nP,{"":()=>o(0,1),number:e=>o(0,e),"number, number":(e,t)=>o(e,t),"Array | Matrix":e=>a(e,0,1),"Array | Matrix, number":(e,t)=>a(e,0,t),"Array | Matrix, number, number":(e,t,n)=>a(e,t,n)});function a(e,t,n){var r=eP(e.valueOf(),()=>o(t,n));return Dl(e)?e.create(r,`number`):r}function o(e,t){return e+i()*(t-e)}})})),aP,oP,sP,CCe=e((()=>{X(),tP(),XN(),Ql(),aP=`randomInt`,oP=[`typed`,`config`,`log2`,`?on`],sP=Y(aP,oP,e=>{var{typed:t,config:n,log2:r,on:i}=e,a=qN(n.randomSeed);return i&&i(`config`,function(e,t){e.randomSeed!==t.randomSeed&&(a=qN(e.randomSeed))}),t(aP,{"":()=>s(0,2),number:e=>s(0,e),"number, number":(e,t)=>s(e,t),bigint:e=>c(0n,e),"bigint, bigint":c,"Array | Matrix":e=>o(e,0,1),"Array | Matrix, number":(e,t)=>o(e,0,t),"Array | Matrix, number, number":(e,t,n)=>o(e,t,n)});function o(e,t,n){var r=eP(e.valueOf(),()=>s(t,n));return Dl(e)?e.create(r,`number`):r}function s(e,t){return Math.floor(e+a()*(t-e))}function c(e,t){var n=2n**30n,i=t-e;if(i<=n)return e+BigInt(s(0,Number(i)));for(var o=r(i),c=i;c>=i;){c=0n;for(var l=0;l<o;++l)c=2n*c+(a()<.5?0n:1n)}return e+c}})})),cP,lP,uP,wCe=e((()=>{X(),Ql(),cP=`stirlingS2`,lP=[`typed`,`addScalar`,`subtractScalar`,`multiplyScalar`,`divideScalar`,`pow`,`factorial`,`combinations`,`isNegative`,`isInteger`,`number`,`?bignumber`,`larger`],uP=Y(cP,lP,e=>{var{typed:t,addScalar:n,subtractScalar:r,multiplyScalar:i,divideScalar:a,pow:o,factorial:s,combinations:c,isNegative:l,isInteger:u,number:d,bignumber:f,larger:p}=e,m=[],h=[];return t(cP,{"number | BigNumber, number | BigNumber":function(e,t){if(!u(e)||l(e)||!u(t)||l(t))throw TypeError(`Non-negative integer value expected in function stirlingS2`);if(p(t,e))throw TypeError(`k must be less than or equal to n in function stirlingS2`);var r=!(bl(e)&&bl(t)),a=r?h:m,o=r?f:d,s=d(e),c=d(t);if(a[s]&&a[s].length>c)return a[s][c];for(var g=0;g<=s;++g)if(a[g]||(a[g]=[o(+(g===0))]),g!==0)for(var _=a[g],v=a[g-1],y=_.length;y<=g&&y<=c;++y)y===g?_[y]=1:_[y]=n(i(o(y),v[y]),v[y-1]);return a[s][c]}})})})),dP,fP,pP,TCe=e((()=>{X(),dP=`bellNumbers`,fP=[`typed`,`addScalar`,`isNegative`,`isInteger`,`stirlingS2`],pP=Y(dP,fP,e=>{var{typed:t,addScalar:n,isNegative:r,isInteger:i,stirlingS2:a}=e;return t(dP,{"number | BigNumber":function(e){if(!i(e)||r(e))throw TypeError(`Non-negative integer value expected in function bellNumbers`);for(var t=0,o=0;o<=e;o++)t=n(t,a(e,o));return t}})})})),mP,hP,gP,ECe=e((()=>{X(),mP=`catalan`,hP=[`typed`,`addScalar`,`divideScalar`,`multiplyScalar`,`combinations`,`isNegative`,`isInteger`],gP=Y(mP,hP,e=>
2633{var{typed:t,addScalar:n,divideScalar:r,multiplyScalar:i,combinations:a,isNegative:o,isInteger:s}=e;return t(mP,{"number | BigNumber":function(e){if(!s(e)||o(e))throw TypeError(`Non-negative integer value expected in function catalan`);return r(a(i(e,2),e),n(e,1))}})})})),_P,vP,yP,DCe=e((()=>{X(),_P=`composition`,vP=[`typed`,`addScalar`,`combinations`,`isNegative`,`isPositive`,`isInteger`,`larger`],yP=Y(_P,vP,e=>{var{typed:t,addScalar:n,combinations:r,isPositive:i,isNegative:a,isInteger:o,larger:s}=e;return t(_P,{"number | BigNumber, number | BigNumber":function(e,t){if(!o(e)||!i(e)||!o(t)||!i(t))throw TypeError(`Positive integer value expected in function composition`);if(s(t,e))throw TypeError(`k must be less than or equal to n in function composition`);return r(n(e,-1),n(t,-1))}})})})),bP,xP,SP,OCe=e((()=>{X(),bP=`leafCount`,xP=[`parse`,`typed`],SP=Y(bP,xP,e=>{var{parse:t,typed:n}=e;function r(e){var t=0;return e.forEach(e=>{t+=r(e)}),t||1}return n(bP,{Node:function(e){return r(e)}})})}));function CP(e){return zl(e)||Kl(e)&&e.isUnary()&&zl(e.args[0])}function wP(e){return!!(zl(e)||(Hl(e)||Kl(e))&&e.args.every(wP)||ql(e)&&wP(e.content))}var kCe=e((()=>{Ql()}));function TP(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function EP(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?TP(Object(n),!0).forEach(function(t){Rn(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):TP(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var DP,OP,kP,AP=e((()=>{Ln(),Ql(),X(),ru(),DP=`simplifyUtil`,OP=[`FunctionNode`,`OperatorNode`,`SymbolNode`],kP=Y(DP,OP,e=>{var{FunctionNode:t,OperatorNode:n,SymbolNode:r}=e,i=!0,a=!1,o=`defaultF`,s={add:{trivial:i,total:i,commutative:i,associative:i},unaryPlus:{trivial:i,total:i,commutative:i,associative:i},subtract:{trivial:a,total:i,commutative:a,associative:a},multiply:{trivial:i,total:i,commutative:i,associative:i},divide:{trivial:a,total:i,commutative:a,associative:a},paren:{trivial:i,total:i,commutative:i,associative:a},defaultF:{trivial:a,total:i,commutative:a,associative:a}},c={divide:{total:a},log:{total:a}},l={subtract:{total:a},abs:{trivial:i},log:{total:i}};function u(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:s,r=o;if(typeof e==`string`?r=e:Kl(e)?r=e.fn.toString():Hl(e)?r=e.name:ql(e)&&(r=`paren`),nu(n,r)){var i=n[r];if(nu(i,t))return i[t];if(nu(s,r))return s[r][t]}if(nu(n,o)){var a=n[o];return nu(a,t)?a[t]:s[o][t]}if(nu(s,r)){var c=s[r];if(nu(c,t))return c[t]}return s[o][t]}function d(e){return u(e,`commutative`,arguments.length>1&&arguments[1]!==void 0?arguments[1]:s)}function f(e){return u(e,`associative`,arguments.length>1&&arguments[1]!==void 0?arguments[1]:s)}function p(e,t){var n=EP({},e);for(var r in t)nu(e,r)?n[r]=EP(EP({},t[r]),e[r]):n[r]=t[r];return n}function m(e,t){if(!e.args||e.args.length===0)return e;e.args=h(e,t);for(var n=0;n<e.args.length;n++)m(e.args[n],t)}function h(e,t){var n,r=[],i=function(e){for(var t=0;t<e.args.length;t++){var a=e.args[t];Kl(a)&&n===a.op?i(a):r.push(a)}};return f(e,t)?(n=e.op,i(e),r):e.args}function g(e,t){if(!(!e.args||e.args.length===0)){for(var n=v(e),r=e.args.length,i=0;i<r;i++)g(e.args[i],t);if(r>2&&f(e,t)){for(var a=e.args.pop();e.args.length>0;)a=n([e.args.pop(),a]);e.args=a.args}}}function _(e,t){if(!(!e.args||e.args.length===0)){for(var n=v(e),r=e.args.length,i=0;i<r;i++)_(e.args[i],t);if(r>2&&f(e,t)){for(var a=e.args.shift();e.args.length>0;)a=n([a,e.args.shift()]);e.args=a.args}}}function v(e){return Kl(e)?function(t){try{return new n(e.op,e.fn,t,e.implicit)}catch(e){return console.error(e),[]}}:function(n){return new t(new r(e.name),n)}}return{createMakeNodeFunction:v,hasProperty:u,isCommutative:d,isAssociative:f,mergeContext:p,flatten:m,allChildren:h,unflattenr:g,unflattenl:_,defaultContext:s,realContext:c,positiveContext:l}})})),jP,MP,NP,ACe=e((()=>{Ql(),kCe(),X(),AP(),ru(),yl(),jP=`simplify`,MP=[`typed`,`parse`,`equal`,`resolve`,`simplifyConstant`,`simplifyCore`,`AccessorNode`,`ArrayNode`,`ConstantNode`,`FunctionNode`,`IndexNode`,`ObjectNode`,`OperatorNode`,`ParenthesisNode`,`SymbolNode`,`replacer`],NP=Y(jP,MP,e=>{var{typed:t,parse:n,equal:r,resolve:i,simplifyConstant:a,simplifyCore:o,AccessorNode:s,ArrayNode:c,ConstantNode:l,FunctionNode:u,IndexNode:d,ObjectNode:f,OperatorNode:p,ParenthesisNode:m,SymbolNode:h,replacer:g}=e,{hasProperty:_,isCommutative:v,isAssociative:y,mergeContext:b,flatten:x,unflattenr:S,unflattenl:C,createMakeNodeFunction:w,defaultContext:T,realContext:E,positiveContext:D}=kP({FunctionNode:u,OperatorNode:p,SymbolNode:h});t.addConversion({from:`Object`,to:`Map`,convert:gl});var O=t(`simplify`,{Node:F,"Node, Map":(e,t)=>
vendor: 8,327 bytes, line 2633
2633F(e,!1,t),"Node, Map, Object":(e,t,n)=>F(e,!1,t,n),"Node, Array":F,"Node, Array, Map":F,"Node, Array, Map, Object":F});t.removeConversion({from:`Object`,to:`Map`,convert:gl}),O.defaultContext=T,O.realContext=E,O.positiveContext=D;function k(e){return e.transform(function(e){return ql(e)?k(e.content):e})}var A={true:!0,false:!0,e:!0,i:!0,Infinity:!0,LN2:!0,LN10:!0,LOG2E:!0,LOG10E:!0,NaN:!0,phi:!0,pi:!0,SQRT1_2:!0,SQRT2:!0,tau:!0};O.rules=[o,{l:`log(e)`,r:`1`},{s:`n-n1 -> n+-n1`,assuming:{subtract:{total:!0}}},{s:`n-n -> 0`,assuming:{subtract:{total:!1}}},{s:`-(cl*v) -> v * (-cl)`,assuming:{multiply:{commutative:!0},subtract:{total:!0}}},{s:`-(cl*v) -> (-cl) * v`,assuming:{multiply:{commutative:!1},subtract:{total:!0}}},{s:`-(v*cl) -> v * (-cl)`,assuming:{multiply:{commutative:!1},subtract:{total:!0}}},{l:`-(n1/n2)`,r:`-n1/n2`},{l:`-v`,r:`v * (-1)`},{l:`(n1 + n2)*(-1)`,r:`n1*(-1) + n2*(-1)`,repeat:!0},{l:`n/n1^n2`,r:`n*n1^-n2`},{l:`n/n1`,r:`n*n1^-1`},{s:`(n1*n2)^n3 -> n1^n3 * n2^n3`,assuming:{multiply:{commutative:!0}}},{s:`(n1*n2)^(-1) -> n2^(-1) * n1^(-1)`,assuming:{multiply:{commutative:!1}}},{s:`(n ^ n1) ^ n2 -> n ^ (n1 * n2)`,assuming:{divide:{total:!0}}},{l:` vd   * ( vd   * n1 + n2)`,r:`vd^2       * n1 +  vd   * n2`},{s:` vd   * (vd^n4 * n1 + n2)   ->  vd^(1+n4)  * n1 +  vd   * n2`,assuming:{divide:{total:!0}}},{s:`vd^n3 * ( vd   * n1 + n2)   ->  vd^(n3+1)  * n1 + vd^n3 * n2`,assuming:{divide:{total:!0}}},{s:`vd^n3 * (vd^n4 * n1 + n2)   ->  vd^(n3+n4) * n1 + vd^n3 * n2`,assuming:{divide:{total:!0}}},{l:`n*n`,r:`n^2`},{s:`n * n^n1 -> n^(n1+1)`,assuming:{divide:{total:!0}}},{s:`n^n1 * n^n2 -> n^(n1+n2)`,assuming:{divide:{total:!0}}},a,{s:`n+n -> 2*n`,assuming:{add:{total:!0}}},{l:`n+-n`,r:`0`},{l:`vd*n + vd`,r:`vd*(n+1)`},{l:`n3*n1 + n3*n2`,r:`n3*(n1+n2)`},{l:`n3^(-n4)*n1 +   n3  * n2`,r:`n3^(-n4)*(n1 + n3^(n4+1) *n2)`},{l:`n3^(-n4)*n1 + n3^n5 * n2`,r:`n3^(-n4)*(n1 + n3^(n4+n5)*n2)`},{s:`n*vd + vd -> (n+1)*vd`,assuming:{multiply:{commutative:!1}}},{s:`vd + n*vd -> (1+n)*vd`,assuming:{multiply:{commutative:!1}}},{s:`n1*n3 + n2*n3 -> (n1+n2)*n3`,assuming:{multiply:{commutative:!1}}},{s:`n^n1 * n -> n^(n1+1)`,assuming:{divide:{total:!0},multiply:{commutative:!1}}},{s:`n1*n3^(-n4) + n2 * n3    -> (n1 + n2*n3^(n4 +  1))*n3^(-n4)`,assuming:{multiply:{commutative:!1}}},{s:`n1*n3^(-n4) + n2 * n3^n5 -> (n1 + n2*n3^(n4 + n5))*n3^(-n4)`,assuming:{multiply:{commutative:!1}}},{l:`n*cd + cd`,r:`(n+1)*cd`},{s:`cd*n + cd -> cd*(n+1)`,assuming:{multiply:{commutative:!1}}},{s:`cd + cd*n -> cd*(1+n)`,assuming:{multiply:{commutative:!1}}},a,{s:`(-n)*n1 -> -(n*n1)`,assuming:{subtract:{total:!0}}},{s:`n1*(-n) -> -(n1*n)`,assuming:{subtract:{total:!0},multiply:{commutative:!1}}},{s:`ce+ve -> ve+ce`,assuming:{add:{commutative:!0}},imposeContext:{add:{commutative:!1}}},{s:`vd*cd -> cd*vd`,assuming:{multiply:{commutative:!0}},imposeContext:{multiply:{commutative:!1}}},{l:`n+-n1`,r:`n-n1`},{l:`n+-(n1)`,r:`n-(n1)`},{s:`n*(n1^-1) -> n/n1`,assuming:{multiply:{commutative:!0}}},{s:`n*n1^-n2 -> n/n1^n2`,assuming:{multiply:{commutative:!0}}},{s:`n^-1 -> 1/n`,assuming:{multiply:{commutative:!0}}},{l:`n^1`,r:`n`},{s:`n*(n1/n2) -> (n*n1)/n2`,assuming:{multiply:{associative:!0}}},{s:`n-(n1+n2) -> n-n1-n2`,assuming:{addition:{associative:!0,commutative:!0}}},{l:`1*n`,r:`n`,imposeContext:{multiply:{commutative:!0}}},{s:`n1/(n2/n3) -> (n1*n3)/n2`,assuming:{multiply:{associative:!0}}},{l:`n1/(-n2)`,r:`-n1/n2`}];function j(e,t){var r={};if(e.s){var i=e.s.split(`->`);if(i.length===2)r.l=i[0],r.r=i[1];else throw SyntaxError(`Could not parse rule: `+e.s)}else r.l=e.l,r.r=e.r;r.l=k(n(r.l)),r.r=k(n(r.r));for(var a of[`imposeContext`,`repeat`,`assuming`])a in e&&(r[a]=e[a]);if(e.evaluate&&(r.evaluate=n(e.evaluate)),y(r.l,t)){var o=!v(r.l,t),s;o&&(s=P());var c=w(r.l),l=P();r.expanded={},r.expanded.l=c([r.l,l]),x(r.expanded.l,t),S(r.expanded.l,t),r.expanded.r=c([r.r,l]),o&&(r.expandedNC1={},r.expandedNC1.l=c([s,r.l]),r.expandedNC1.r=c([s,r.r]),r.expandedNC2={},r.expandedNC2.l=c([s,r.expanded.l]),r.expandedNC2.r=c([s,r.expanded.r]))}return r}function M(e,t){for(var n=[],r=0;r<e.length;r++){var i=e[r],a=void 0,o=typeof i;switch(o){case`string`:i={s:i};case`object`:a=j(i,t);break;case`function`:a=i;break;default:throw TypeError(`Unsupported type of rule: `+o)}n.push(a)}return n}var N=0;function P(){return new h(`_p`+ N++)}function F(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:hl(),r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},a=r.consoleDebug;t=M(t||O.rules,r.context);var o=i(e,n);o=k(o);for(var s={},c=o.toString({parenthesis:`all`});!s[c];){s[c]=!0,N=0;var l=c;a&&console.log(`Working on: `,c);for(var u=0;u<t.length;u++){var d=``;if(typeof t[u]==`function`?(o=t[u](o,r),a&&(d=t[u].name)):(x(o,r.context),o=L(o,t[u],r.context),a&&(d=`${t[u].l.toString()} -> ${t[u].r.toString()}`)),a){var f=o.toString({parenthesis:`all`});f!==l&&(console.log(`Applying`,d,`produced`,f),l=f)}C(o,r.context)}c=o.toString({parenthesis:`all`})}return o}function I(e,t,n){var r=e;if(e)for(var i=0;i<e.length;++i){var a=L(e[i],t,n);a!==e[i]&&(r===e&&(r=e.slice()),r[i]=a)}return r}function L(e,t,n){if(t.assuming){for(var r in t.assuming)for(var i in t.assuming[r])if(_(r,i,n)!==t.assuming[r][i])return e}var a=b(t.imposeContext,n),o=e;if(o instanceof p||o instanceof u){var l=I(o.args,t,n);l!==o.args&&(o=o.clone(),o.args=l)}else if(o instanceof m){if(o.content){var h=L(o.content,t,n);h!==o.content&&(o=new m(h))}}else if(o instanceof c){var g=I(o.items,t,n);g!==o.items&&(o=new c(g))}else if(o instanceof s){var v=o.object;o.object&&(v=L(o.object,t,n));var y=o.index;o.index&&(y=L(o.index,t,n)),(v!==o.object||y!==o.index)&&(o=new s(v,y))}else if(o instanceof d){var x=I(o.dimensions,t,n);x!==o.dimensions&&(o=new d(x))}else if(o instanceof f){var S=!1,C={};for(var w in o.properties)C[w]=L(o.properties[w],t,n),C[w]!==o.properties[w]&&(S=!0);S&&(o=new f(C))}var T=t.r,E=ne(t.l,o,a)[0];if(!E&&t.expanded&&(T=t.expanded.r,E=ne(t.expanded.l,o,a)[0]),!E&&t.expandedNC1&&(T=t.expandedNC1.r,E=ne(t.expandedNC1.l,o,a)[0],E||=(T=t.expandedNC2.r,ne(t.expandedNC2.l,o,a)[0])),E){var D=o.implicit;o=T.clone(),D&&`implicit`in T&&(o.implicit=!0),o=o.transform(function(e){return e.isSymbolNode&&nu(E.placeholders,e.name)?E.placeholders[e.name].clone():e})}return t.repeat&&o!==e&&(o=L(o,t,n)),o}function ee(e,t){var n=[],r,i,a=w(e);if(v(e,t))for(var o=0;o<e.args.length;o++)i=e.args.slice(0),i.splice(o,1),r=i.length===1?i[0]:a(i),n.push(a([e.args[o],r]));else for(var s=1;s<e.args.length;s++){var c=e.args[0];s>1&&(c=a(e.args.slice(0,s))),i=e.args.slice(s),r=i.length===1?i[0]:a(i),n.push(a([c,r]))}return n}function R(e,t){var n={placeholders:{}};if(!e.placeholders&&!t.placeholders)return n;if(!e.placeholders)return t;if(!t.placeholders)return e;for(var r in e.placeholders)if(nu(e.placeholders,r)&&(n.placeholders[r]=e.placeholders[r],nu(t.placeholders,r)&&!B(e.placeholders[r],t.placeholders[r])))return null;for(var i in t.placeholders)nu(t.placeholders,i)&&(n.placeholders[i]=t.placeholders[i]);return n}function te(e,t){var n=[];if(e.length===0||t.length===0)return n;for(var r,i=0;i<e.length;i++)for(var a=0;a<t.length;a++)r=R(e[i],t[a]),r&&n.push(r);return n}function z(e){if(e.length===0)return e;for(var t=e.reduce(te),n=[],r={},i=0;i<t.length;i++){var a=JSON.stringify(t[i],g);r[a]||(r[a]=!0,n.push(t[i]))}return n}function ne(e,t,n,i){var a=[{placeholders:{}}];if(e instanceof p&&t instanceof p||e instanceof u&&t instanceof u){if(e instanceof p){if(e.op!==t.op||e.fn!==t.fn)return[]}else if(e instanceof u&&e.name!==t.name)return[];if(t.args.length===1&&e.args.length===1||!y(t,n)&&t.args.length===e.args.length||i){for(var o=[],s=0;s<e.args.length;s++){var c=ne(e.args[s],t.args[s],n);if(c.length===0)break;o.push(c)}if(o.length!==e.args.length){if(!v(t,n)||e.args.length===1)return[];if(e.args.length>2)throw Error(`permuting >2 commutative non-associative rule arguments not yet implemented`);var d=ne(e.args[0],t.args[1],n);if(d.length===0)return[];var f=ne(e.args[1],t.args[0],n);if(f.length===0)return[];o=[d,f]}a=z(o)}else if(t.args.length>=2&&e.args.length===2){for(var m=ee(t,n),g=[],_=0;_<m.length;_++){var b=ne(e,m[_],n,!0);g=g.concat(b)}return g}else if(e.args.length>2)throw Error(`Unexpected non-binary associative function: `+e.toString());else return[]}
2633else if(e instanceof h){if(e.name.length===0)throw Error(`Symbol in rule has 0 length...!?`);if(A[e.name]){if(e.name!==t.name)return[]}else switch(e.name[1]>=`a`&&e.name[1]<=`z`?e.name.substring(0,2):e.name[0]){case`n`:case`_p`:a[0].placeholders[e.name]=t;break;case`c`:case`cl`:if(zl(t))a[0].placeholders[e.name]=t;else return[];break;case`v`:if(!zl(t))a[0].placeholders[e.name]=t;else return[];break;case`vl`:if(Jl(t))a[0].placeholders[e.name]=t;else return[];break;case`cd`:if(CP(t))a[0].placeholders[e.name]=t;else return[];break;case`vd`:if(!CP(t))a[0].placeholders[e.name]=t;else return[];break;case`ce`:if(wP(t))a[0].placeholders[e.name]=t;else return[];break;case`ve`:if(!wP(t))a[0].placeholders[e.name]=t;else return[];break;default:throw Error(`Invalid symbol in rule: `+e.name)}}else if(e instanceof l){if(!r(e.value,t.value))return[]}else return[];return a}function B(e,t){if(e instanceof l&&t instanceof l){if(!r(e.value,t.value))return!1}else if(e instanceof h&&t instanceof h){if(e.name!==t.name)return!1}else if(e instanceof p&&t instanceof p||e instanceof u&&t instanceof u){if(e instanceof p){if(e.op!==t.op||e.fn!==t.fn)return!1}else if(e instanceof u&&e.name!==t.name)return!1;if(e.args.length!==t.args.length)return!1;for(var n=0;n<e.args.length;n++)if(!B(e.args[n],t.args[n]))return!1}else return!1;return!0}return O})})),PP,FP,IP,jCe=e((()=>{Ql(),X(),Pu(),AP(),Eb(),PP=`simplifyConstant`,FP=[`typed`,`config`,`mathWithTransform`,`matrix`,`isBounded`,`?fraction`,`?bignumber`,`AccessorNode`,`ArrayNode`,`ConstantNode`,`FunctionNode`,`IndexNode`,`ObjectNode`,`OperatorNode`,`SymbolNode`],IP=Y(PP,FP,e=>{var{typed:t,config:n,mathWithTransform:r,matrix:i,isBounded:a,fraction:o,bignumber:s,AccessorNode:c,ArrayNode:l,ConstantNode:u,FunctionNode:d,IndexNode:f,ObjectNode:p,OperatorNode:m,SymbolNode:h}=e,{isCommutative:g,isAssociative:_,allChildren:v,createMakeNodeFunction:y}=kP({FunctionNode:d,OperatorNode:m,SymbolNode:h}),b=t(`simplifyConstant`,{Node:e=>w(j(e,{})),"Node, Object":function(e,t){return w(j(e,t))}});function x(e){return wl(e)?e.valueOf():e instanceof Array?e.map(x):Dl(e)?i(x(e.valueOf())):e}function S(e,t,n){try{return r[e].apply(null,t)}catch{return t=t.map(x),E(r[e].apply(null,t),n)}}var C=t({Fraction:O,number:function(e){return e<0?D(new u(-e)):new u(e)},BigNumber:function(e){return e<0?D(new u(-e)):new u(e)},bigint:function(e){return e<0n?D(new u(-e)):new u(e)},Complex:function(e){throw Error(`Cannot convert Complex number to Node`)},string:function(e){return new u(e)},Matrix:function(e){return new l(e.valueOf().map(e=>C(e)))}});function w(e){return Wl(e)?e:C(e)}function T(e,t){if(t&&t.exactFractions!==!1&&a(e)&&o){var n=o(e),r=t&&typeof t.fractionsLimit==`number`?t.fractionsLimit:1/0;if(n.valueOf()===e&&n.n<r&&n.d<r)return n}return e}var E=t({"string, Object":function(e,t){var r=uu(e,n);return r===`BigNumber`?(s===void 0&&Tb(),s(e)):r===`bigint`?BigInt(e):r===`Fraction`?(o===void 0&&_fe(),o(e)):T(parseFloat(e),t)},"Fraction, Object":function(e,t){return e},"BigNumber, Object":function(e,t){return e},"number, Object":function(e,t){return T(e,t)},"bigint, Object":function(e,t){return e},"Complex, Object":function(e,t){return e.im===0?T(e.re,t):e},"Matrix, Object":function(e,t){return i(T(e.valueOf()))},"Array, Object":function(e,t){return e.map(T)}});function D(e){return new m(`-`,`unaryMinus`,[e])}function O(e){var t=e=>n.number===`BigNumber`&&s?s(e):Number(e),r=e.s*e.n,i=r<0n?new m(`-`,`unaryMinus`,[new u(-t(r))]):new u(t(r));return e.d===1n?i:new m(`/`,`divide`,[i,new u(t(e.d))])}function k(e,t,n){if(!Ul(t))return new c(w(e),w(t));if(Rl(e)||Dl(e)){for(var r=Array.from(t.dimensions);r.length>0;)if(zl(r[0])&&typeof r[0].value!=`string`){var a=E(r.shift().value,n);Rl(e)?e=e.items[a-1]:(e=e.valueOf()[a-1],e instanceof Array&&(e=i(e)))}else if(r.length>1&&zl(r[1])&&typeof r[1].value!=`string`){var o=E(r[1].value,n),s=[],d=Rl(e)?e.items:e.valueOf();for(var p of d)if(Rl(p))s.push(p.items[o-1]);else if(Dl(e))s.push(p[o-1]);else break;if(s.length===d.length)e=Rl(e)?new l(s):i(s),r.splice(1,1);else break}else break;return r.length===t.dimensions.length?new c(w(e),t):r.length>0?(t=new f(r),new c(w(e),t)):e}if(Gl(e)&&t.dimensions.length===1&&zl(t.dimensions[0])){var m=t.dimensions[0].value;return m in e.properties?e.properties[m]:new u}return new c(w(e),t)}function A(e,t,n,r){var i=t.shift(),a=t.reduce((t,i)=>{if(!Wl(i)){var a=t.pop();if(Wl(a))return[a,i];try{return t.push(S(e,[a,i],r)),t}catch{t.push(a)}}
2633return t.push(w(t.pop())),[n([t.length===1?t[0]:n(t),w(i)])]},[i]);return a.length===1?a[0]:n([a[0],C(a[1])])}function j(e,t){switch(e.type){case`SymbolNode`:return e;case`ConstantNode`:switch(typeof e.value){case`number`:return E(e.value,t);case`bigint`:return E(e.value,t);case`string`:return e.value;default:if(!isNaN(e.value))return E(e.value,t)}return e;case`FunctionNode`:if(r[e.name]&&r[e.name].rawArgs)return e;if(![`add`,`multiply`].includes(e.name)){var n=e.args.map(e=>j(e,t));if(!n.some(Wl))try{return S(e.name,n,t)}catch{}if(e.name===`size`&&n.length===1&&Rl(n[0])){for(var a=[],o=n[0];Rl(o);)a.push(o.items.length),o=o.items[0];return i(a)}return new d(e.name,n.map(w))}case`OperatorNode`:var s=e.fn.toString(),c,u,m=y(e);if(Kl(e)&&e.isUnary())c=[j(e.args[0],t)],u=Wl(c[0])?m(c):S(s,c,t);else if(_(e,t.context))if(c=v(e,t.context),c=c.map(e=>j(e,t)),g(s,t.context)){for(var h=[],x=[],C=0;C<c.length;C++)Wl(c[C])?x.push(c[C]):h.push(c[C]);h.length>1?(u=A(s,h,m,t),x.unshift(u),u=A(s,x,m,t)):u=A(s,c,m,t)}else u=A(s,c,m,t);else c=e.args.map(e=>j(e,t)),u=A(s,c,m,t);return u;case`ParenthesisNode`:return j(e.content,t);case`AccessorNode`:return k(j(e.object,t),j(e.index,t),t);case`ArrayNode`:var T=e.items.map(e=>j(e,t));return T.some(Wl)?new l(T.map(w)):i(T);case`IndexNode`:return new f(e.dimensions.map(e=>b(e,t)));case`ObjectNode`:var D={};for(var O in e.properties)D[O]=b(e.properties[O],t);return new p(D);default:throw Error(`Unimplemented node type in simplifyConstant: ${e.type}`)}}return b})})),LP,RP,zP,MCe=e((()=>{Ql(),rT(),AP(),X(),LP=`simplifyCore`,RP=[`typed`,`parse`,`equal`,`isZero`,`add`,`subtract`,`multiply`,`divide`,`pow`,`AccessorNode`,`ArrayNode`,`ConstantNode`,`FunctionNode`,`IndexNode`,`ObjectNode`,`OperatorNode`,`ParenthesisNode`,`SymbolNode`],zP=Y(LP,RP,e=>{var{typed:t,parse:n,equal:r,isZero:i,add:a,subtract:o,multiply:s,divide:c,pow:l,AccessorNode:u,ArrayNode:d,ConstantNode:f,FunctionNode:p,IndexNode:m,ObjectNode:h,OperatorNode:g,ParenthesisNode:_,SymbolNode:v}=e,y=new f(0),b=new f(1),x=new f(!0),S=new f(!1);function C(e){return Kl(e)&&[`and`,`not`,`or`].includes(e.op)}var{hasProperty:w,isCommutative:T}=kP({FunctionNode:p,OperatorNode:g,SymbolNode:v});function E(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=t?t.context:void 0;if(w(e,`trivial`,n)){if(Hl(e)&&e.args.length===1)return E(e.args[0],t);var a=!1,o=0;if(e.forEach(e=>{++o,o===1&&(a=E(e,t))}),o===1)return a}var s=e;if(Hl(s)){var c=d_e(s.name);if(c){if(s.args.length>2&&w(s,`associative`,n))for(;s.args.length>2;){var l=s.args.pop(),f=s.args.pop();s.args.push(new g(c,s.name,[l,f]))}s=new g(c,s.name,s.args)}else return new p(E(s.fn),s.args.map(e=>E(e,t)))}if(Kl(s)&&s.isUnary()){var _=E(s.args[0],t);
2633if(s.op===`~`&&Kl(_)&&_.isUnary()&&_.op===`~`||s.op===`not`&&Kl(_)&&_.isUnary()&&_.op===`not`&&C(_.args[0]))return _.args[0];var v=!0;if(s.op===`-`&&Kl(_)&&(_.isBinary()&&_.fn===`subtract`&&(s=new g(`-`,`subtract`,[_.args[1],_.args[0]]),v=!1),_.isUnary()&&_.op===`-`))return _.args[0];if(v)return new g(s.op,s.fn,[_])}if(Kl(s)&&s.isBinary()){var D=E(s.args[0],t),O=E(s.args[1],t);if(s.op===`+`){if(zl(D)&&i(D.value))return O;if(zl(O)&&i(O.value))return D;Kl(O)&&O.isUnary()&&O.op===`-`&&(O=O.args[0],s=new g(`-`,`subtract`,[D,O]))}if(s.op===`-`)return Kl(O)&&O.isUnary()&&O.op===`-`?E(new g(`+`,`add`,[D,O.args[0]]),t):zl(D)&&i(D.value)?E(new g(`-`,`unaryMinus`,[O])):zl(O)&&i(O.value)?D:new g(s.op,s.fn,[D,O]);if(s.op===`*`){if(zl(D)){if(i(D.value))return y;if(r(D.value,1))return O}if(zl(O)){if(i(O.value))return y;if(r(O.value,1))return D;if(T(s,n))return new g(s.op,s.fn,[O,D],s.implicit)}return new g(s.op,s.fn,[D,O],s.implicit)}if(s.op===`/`)return zl(D)&&i(D.value)?y:zl(O)&&r(O.value,1)?D:new g(s.op,s.fn,[D,O]);if(s.op===`^`&&zl(O)){if(i(O.value))return b;if(r(O.value,1))return D}if(s.op===`and`){if(zl(D))if(D.value){if(C(O))return O;if(zl(O))return O.value?x:S}else return S;if(zl(O))if(O.value){if(C(D))return D}else return S}if(s.op===`or`){if(zl(D)){if(D.value)return x;if(C(O))return O}if(zl(O)){if(O.value)return x;if(C(D))return D}}return new g(s.op,s.fn,[D,O])}if(Kl(s))return new g(s.op,s.fn,s.args.map(e=>E(e,t)));if(Rl(s))return new d(s.items.map(e=>E(e,t)));if(Ll(s))return new u(E(s.object,t),E(s.index,t));if(Ul(s))return new m(s.dimensions.map(e=>E(e,t)));if(Gl(s)){var k={};for(var A in s.properties)k[A]=E(s.properties[A],t);return new h(k)}return s}return t(LP,{Node:E,"Node,Object":E})})})),BP,VP,HP,NCe=e((()=>{yl(),Ql(),X(),BP=`resolve`,VP=[`typed`,`parse`,`ConstantNode`,`FunctionNode`,`OperatorNode`,`ParenthesisNode`],HP=Y(BP,VP,e=>{var{typed:t,parse:n,ConstantNode:r,FunctionNode:i,OperatorNode:a,ParenthesisNode:o}=e;function s(e,t){var c=arguments.length>2&&arguments[2]!==void 0?arguments[2]:new Set;if(!t)return e;if(Jl(e)){if(c.has(e.name)){var l=Array.from(c).join(`, `);throw ReferenceError(`recursive loop of variable definitions among {${l}}`)}var u=t.get(e.name);if(Wl(u)){var d=new Set(c);return d.add(e.name),s(u,t,d)}else if(typeof u==`number`)return n(String(u));else if(u!==void 0)return new r(u);else return e}else if(Kl(e)){var f=e.args.map(function(e){return s(e,t,c)});return new a(e.op,e.fn,f,e.implicit)}else if(ql(e))return new o(s(e.content,t,c));else if(Hl(e)){var p=e.args.map(function(e){return s(e,t,c)});return new i(e.name,p)}return e.map(e=>s(e,t,c))}return t(`resolve`,{Node:s,"Node, Map | null | undefined":s,"Node, Object":(e,t)=>s(e,gl(t)),"Array | Matrix":t.referToSelf(e=>t=>t.map(t=>e(t))),"Array | Matrix, null | undefined":t.referToSelf(e=>t=>t.map(t=>e(t))),"Array, Object":t.referTo(`Array,Map`,e=>(t,n)=>e(t,gl(n))),"Matrix, Object":t.referTo(`Matrix,Map`,e=>(t,n)=>e(t,gl(n))),"Array | Matrix, Map":t.referToSelf(e=>(t,n)=>t.map(t=>e(t,n)))})})})),UP,WP,GP,PCe=e((()=>{Ql(),X(),UP=`symbolicEqual`,WP=[`parse`,`simplify`,`typed`,`OperatorNode`],GP=Y(UP,WP,e=>{var{parse:t,simplify:n,typed:r,OperatorNode:i}=e;function a(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},a=n(new i(`-`,`subtract`,[e,t]),{},r);return zl(a)&&!a.value}return r(UP,{"Node, Node":a,"Node, Node, Object":a})})})),KP,qP,JP,FCe=e((()=>{Ql(),X(),Pu(),KP=`derivative`,qP=[`typed`,`config`,`parse`,`simplify`,`equal`,`isZero`,`numeric`,`ConstantNode`,`FunctionNode`,`OperatorNode`,`ParenthesisNode`,`SymbolNode`],JP=Y(KP,qP,e=>{var{typed:t,config:n,parse:r,simplify:i,equal:a,isZero:o,numeric:s,ConstantNode:c,FunctionNode:l,OperatorNode:u,ParenthesisNode:d,SymbolNode:f}=e;function p(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{simplify:!0},r=new Map,a=t.name;function o(e){var t=r.get(e);if(t!==void 0)return t;var n=_(o,e,a);return r.set(e,n),n}var s=v(e,o);return n.simplify?i(s):s}function m(e){var t=r(e);if(!t.isSymbolNode)throw TypeError(`Invalid variable. Cannot parse ${JSON.stringify(e)} into a variable in function derivative`);return t}var h=t(KP,{"Node, SymbolNode":p,"Node, SymbolNode, Object":p,"Node, string":(e,t)=>p(e,m(t)),"Node, string, Object":(e,t,n)=>p(e,m(t),n)});h._simplify=!0,h.toTex=function(e){return g.apply(null,e.args)};var g=t(`_derivTex`,{"Node, SymbolNode":function(e,t){return zl(e)&&Xl(e.value)===`string`?g(r(e.value).toString(),t.toString(),1):g(e.toTex(),t.toString(),1)},"Node, ConstantNode":function(e,t){if(Xl(t.value)===`string`)return g(e,r(t.value));
2633throw Error(`The second parameter to 'derivative' is a non-string constant`)},"Node, SymbolNode, ConstantNode":function(e,t,n){return g(e.toString(),t.name,n.value)},"string, string, number":function(e,t,n){return(n===1?`{d\\over d`+t+`}`:`{d^{`+n+`}\\over d`+t+`^{`+n+`}}`)+`\\left[${e}\\right]`}}),_=t(`_isConst`,{"function, ConstantNode, string":function(){return!0},"function, SymbolNode, string":function(e,t,n){return t.name!==n},"function, ParenthesisNode, string":function(e,t,n){return e(t.content,n)},"function, FunctionAssignmentNode, string":function(e,t,n){return t.params.includes(n)?e(t.expr,n):!0},"function, FunctionNode | OperatorNode, string":function(e,t,n){return t.args.every(t=>e(t,n))}}),v=t(`_derivative`,{"ConstantNode, function":function(){return y(0)},"SymbolNode, function":function(e,t){return t(e)?y(0):y(1)},"ParenthesisNode, function":function(e,t){return new d(v(e.content,t))},"FunctionAssignmentNode, function":function(e,t){return t(e)?y(0):v(e.expr,t)},"FunctionNode, function":function(e,t){if(t(e))return y(0);var n=e.args[0],r,i=!1,a=!1,o;switch(e.name){case`cbrt`:i=!0,o=new u(`*`,`multiply`,[y(3),new u(`^`,`pow`,[n,new u(`/`,`divide`,[y(2),y(3)])])]);break;case`sqrt`:case`nthRoot`:if(e.args.length===1)i=!0,o=new u(`*`,`multiply`,[y(2),new l(`sqrt`,[n])]);else if(e.args.length===2)return r=new u(`/`,`divide`,[y(1),e.args[1]]),v(new u(`^`,`pow`,[n,r]),t);break;case`log10`:r=y(10);case`log`:if(!r&&e.args.length===1)o=n.clone(),i=!0;else if(e.args.length===1&&r||e.args.length===2&&t(e.args[1]))o=new u(`*`,`multiply`,[n.clone(),new l(`log`,[r||e.args[1]])]),i=!0;else if(e.args.length===2)return v(new u(`/`,`divide`,[new l(`log`,[n]),new l(`log`,[e.args[1]])]),t);break;case`pow`:if(e.args.length===2)return v(new u(`^`,`pow`,[n,e.args[1]]),t);break;case`exp`:o=new l(`exp`,[n.clone()]);break;case`sin`:o=new l(`cos`,[n.clone()]);break;case`cos`:o=new u(`-`,`unaryMinus`,[new l(`sin`,[n.clone()])]);break;case`tan`:o=new u(`^`,`pow`,[new l(`sec`,[n.clone()]),y(2)]);break;case`sec`:o=new u(`*`,`multiply`,[e,new l(`tan`,[n.clone()])]);break;case`csc`:a=!0,o=new u(`*`,`multiply`,[e,new l(`cot`,[n.clone()])]);break;case`cot`:a=!0,o=new u(`^`,`pow`,[new l(`csc`,[n.clone()]),y(2)]);break;case`asin`:i=!0,o=new l(`sqrt`,[new u(`-`,`subtract`,[y(1),new u(`^`,`pow`,[n.clone(),y(2)])])]);break;case`acos`:i=!0,a=!0,o=new l(`sqrt`,[new u(`-`,`subtract`,[y(1),new u(`^`,`pow`,[n.clone(),y(2)])])]);break;case`atan`:i=!0,o=new u(`+`,`add`,[new u(`^`,`pow`,[n.clone(),y(2)]),y(1)]);break;case`asec`:i=!0,o=new u(`*`,`multiply`,[new l(`abs`,[n.clone()]),new l(`sqrt`,[new u(`-`,`subtract`,[new u(`^`,`pow`,[n.clone(),y(2)]),y(1)])])]);break;case`acsc`:i=!0,a=!0,o=new u(`*`,`multiply`,[new l(`abs`,[n.clone()]),new l(`sqrt`,[new u(`-`,`subtract`,[new u(`^`,`pow`,[n.clone(),y(2)]),y(1)])])]);break;case`acot`:i=!0,a=!0,o=new u(`+`,`add`,[new u(`^`,`pow`,[n.clone(),y(2)]),y(1)]);break;case`sinh`:o=new l(`cosh`,[n.clone()]);break;case`cosh`:o=new l(`sinh`,[n.clone()]);break;case`tanh`:o=new u(`^`,`pow`,[new l(`sech`,[n.clone()]),y(2)]);break;case`sech`:a=!0,o=new u(`*`,`multiply`,[e,new l(`tanh`,[n.clone()])]);break;case`csch`:a=!0,o=new u(`*`,`multiply`,[e,new l(`coth`,[n.clone()])]);break;case`coth`:a=!0,o=new u(`^`,`pow`,[new l(`csch`,[n.clone()]),y(2)]);break;case`asinh`:i=!0,o=new l(`sqrt`,[new u(`+`,`add`,[new u(`^`,`pow`,[n.clone(),y(2)]),y(1)])]);break;case`acosh`:i=!0,o=new l(`sqrt`,[new u(`-`,`subtract`,[new u(`^`,`pow`,[n.clone(),y(2)]),y(1)])]);break;case`atanh`:i=!0,o=new u(`-`,`subtract`,[y(1),new u(`^`,`pow`,[n.clone(),y(2)])]);break;case`asech`:i=!0,a=!0,o=new u(`*`,`multiply`,[n.clone(),new l(`sqrt`,[new u(`-`,`subtract`,[y(1),new u(`^`,`pow`,[n.clone(),y(2)])])])]);break;case`acsch`:i=!0,a=!0,o=new u(`*`,`multiply`,[new l(`abs`,[n.clone()]),new l(`sqrt`,[new u(`+`,`add`,[new u(`^`,`pow`,[n.clone(),y(2)]),y(1)])])]);break;case`acoth`:i=!0,a=!0,o=new u(`-`,`subtract`,[y(1),new u(`^`,`pow`,[n.clone(),y(2)])]);break;case`abs`:o=new u(`/`,`divide`,[new l(new f(`abs`),[n.clone()]),n.clone()]);break;default:throw Error(`Cannot process function "`+e.name+`" in derivative: the function is not supported, undefined, or the number of arguments passed to it are not supported`)}var s,c;i?(s=`/`,c=`divide`):(s=`*`,c=`multiply`);var d=v(n,t);return a&&(d=new u(`-`,`unaryMinus`,[d])),new u(s,c,[d,o])},"OperatorNode, function":function(e,t){if(t(e))return y(0);if(e.op===`+`)return new u(e.op,e.fn,e.args.map(function(e){return v(e,t)}));if(e.op===`-`){if(e.isUnary())return new u(e.op,e.fn,[v(e.args[0],t)]);if(e.isBinary())return new u(e.op,e.fn,[v(e.args[0],t),v(e.args[1],t)])}if(e.op===`*`){var n=e.args.filter(function(e){return t(e)});if(n.length>0){var r=e.args.filter(function(e){return!t(e)}),i=r.length===1?r[0]:new u(`*`,`multiply`,r);return new u(`*`,`multiply`,n.concat(v(i,t)))}return new u(`+`,`add`,e.args.map(function(n){return new u(`*`,`multiply`,e.args.map(function(e){return e===n?v(e,t):e.clone()}))}))}if(e.op===`/`&&e.isBinary()){var s=e.args[0],c=e.args[1];return t(c)?new u(`/`,`divide`,[v(s,t),c]):t(s)?new u(`*`,`multiply`,[new u(`-`,`unaryMinus`,[s]),new u(`/`,`divide`,[v(c,t),new u(`^`,`pow`,[c.clone(),y(2)])])]):new u(`/`,`divide`,[new u(`-`,`subtract`,[new u(`*`,`multiply`,[v(s,t),c.clone()]),new u(`*`,`multiply`,[s.clone(),v(c,t)])]),new u(`^`,`pow`,[c.clone(),y(2)])])}if(e.op===`^`&&e.isBinary()){var d=e.args[0],f=e.args[1];if(t(d))return zl(d)&&(o(d.value)||a(d.value,1))?y(0):new u(`*`,`multiply`,[e,new u(`*`,`multiply`,[new l(`log`,[d.clone()]),v(f.clone(),t)])]);if(t(f)){if(zl(f)){if(o(f.value))return y(0);
2633if(a(f.value,1))return v(d,t)}var p=new u(`^`,`pow`,[d.clone(),new u(`-`,`subtract`,[f,y(1)])]);return new u(`*`,`multiply`,[f.clone(),new u(`*`,`multiply`,[v(d,t),p])])}return new u(`*`,`multiply`,[new u(`^`,`pow`,[d.clone(),f.clone()]),new u(`+`,`add`,[new u(`*`,`multiply`,[v(d,t),new u(`/`,`divide`,[f.clone(),d.clone()])]),new u(`*`,`multiply`,[v(f,t),new l(`log`,[d.clone()])])])])}throw Error(`Cannot process operator "`+e.op+`" in derivative: the operator is not supported, undefined, or the number of arguments passed to it are not supported`)}});function y(e,t){return new c(s(e,t||uu(String(e),n)))}return h})})),YP,XP,ZP,ICe=e((()=>{Pu(),X(),YP=`rationalize`,XP=`config.typed.equal.isZero.add.subtract.multiply.divide.pow.parse.simplifyConstant.simplifyCore.simplify.?bignumber.?fraction.mathWithTransform.matrix.AccessorNode.ArrayNode.ConstantNode.FunctionNode.IndexNode.ObjectNode.OperatorNode.SymbolNode.ParenthesisNode`.split(`.`),ZP=Y(YP,XP,e=>{var{config:t,typed:n,equal:r,isZero:i,add:a,subtract:o,multiply:s,divide:c,pow:l,parse:u,simplifyConstant:d,simplifyCore:f,simplify:p,fraction:m,bignumber:h,mathWithTransform:g,matrix:_,AccessorNode:v,ArrayNode:y,ConstantNode:b,FunctionNode:x,IndexNode:S,ObjectNode:C,OperatorNode:w,SymbolNode:T,ParenthesisNode:E}=e;function D(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=k(),i=O(e,t,!0,r.firstRules),a=i.variables.length,o={exactFractions:!1},s={exactFractions:!0};if(e=i.expression,a>=1){e=A(e);var c,l,u=!0,d=!1;e=p(e,r.firstRules,{},o);for(var f;l=u?r.distrDivRules:r.sucDivRules,e=p(e,l,{},s),u=!u,f=e.toString(),f!==c;)d=!0,c=f;d&&(e=p(e,r.firstRulesAgain,{},o)),e=p(e,r.finalRules,{},o)}var m=[],h={};return e.type===`OperatorNode`&&e.isBinary()&&e.op===`/`?(a===1&&(e.args[0]=j(e.args[0],m),e.args[1]=j(e.args[1])),n&&(h.numerator=e.args[0],h.denominator=e.args[1])):(a===1&&(e=j(e,m)),n&&(h.numerator=e,h.denominator=null)),n?(h.coefficients=m,h.variables=i.variables,h.expression=e,h):e}return n(YP,{Node:D,"Node, boolean":(e,t)=>
2633D(e,{},t),"Node, Object":D,"Node, Object, boolean":D});function O(e,t,n,r){var i=[],a=p(e,r,t,{exactFractions:!1});n=!!n;var o=`+-*`+(n?`/`:``);c(a);var s={};return s.expression=a,s.variables=i,s;function c(e){var t=e.type;if(t===`FunctionNode`)throw Error(`There is an unsolved function call`);if(t===`OperatorNode`)if(e.op===`^`){if(e.args[1].type!==`ConstantNode`||!lu(parseFloat(e.args[1].value)))throw Error(`There is a non-integer exponent`);c(e.args[0])}else{if(!o.includes(e.op))throw Error(`Operator `+e.op+` invalid in polynomial expression`);for(var n=0;n<e.args.length;n++)c(e.args[n])}else if(t===`SymbolNode`){var r=e.name;i.indexOf(r)===-1&&i.push(r)}else if(t===`ParenthesisNode`)c(e.content);else if(t!==`ConstantNode`)throw Error(`type `+t+` is not allowed in polynomial expression`)}}function k(){var e=[f,{l:`n+n`,r:`2*n`},{l:`n+-n`,r:`0`},d,{l:`n*(n1^-1)`,r:`n/n1`},{l:`n*n1^-n2`,r:`n/n1^n2`},{l:`n1^-1`,r:`1/n1`},{l:`n*(n1/n2)`,r:`(n*n1)/n2`},{l:`1*n`,r:`n`}],t=[{l:`(-n1)/(-n2)`,r:`n1/n2`},{l:`(-n1)*(-n2)`,r:`n1*n2`},{l:`n1--n2`,r:`n1+n2`},{l:`n1-n2`,r:`n1+(-n2)`},{l:`(n1+n2)*n3`,r:`(n1*n3 + n2*n3)`},{l:`n1*(n2+n3)`,r:`(n1*n2+n1*n3)`},{l:`c1*n + c2*n`,r:`(c1+c2)*n`},{l:`c1*n + n`,r:`(c1+1)*n`},{l:`c1*n - c2*n`,r:`(c1-c2)*n`},{l:`c1*n - n`,r:`(c1-1)*n`},{l:`v/c`,r:`(1/c)*v`},{l:`v/-c`,r:`-(1/c)*v`},{l:`-v*-c`,r:`c*v`},{l:`-v*c`,r:`-c*v`},{l:`v*-c`,r:`-c*v`},{l:`v*c`,r:`c*v`},{l:`-(-n1*n2)`,r:`(n1*n2)`},{l:`-(n1*n2)`,r:`(-n1*n2)`},{l:`-(-n1+n2)`,r:`(n1-n2)`},{l:`-(n1+n2)`,r:`(-n1-n2)`},{l:`(n1^n2)^n3`,r:`(n1^(n2*n3))`},{l:`-(-n1/n2)`,r:`(n1/n2)`},{l:`-(n1/n2)`,r:`(-n1/n2)`}],n=[{l:`(n1/n2 + n3/n4)`,r:`((n1*n4 + n3*n2)/(n2*n4))`},{l:`(n1/n2 + n3)`,r:`((n1 + n3*n2)/n2)`},{l:`(n1 + n2/n3)`,r:`((n1*n3 + n2)/n3)`}],r=[{l:`(n1/(n2/n3))`,r:`((n1*n3)/n2)`},{l:`(n1/n2/n3)`,r:`(n1/(n2*n3))`}],i={};return i.firstRules=e.concat(t,r),i.distrDivRules=n,i.sucDivRules=r,i.firstRulesAgain=e.concat(t),i.finalRules=[f,{l:`n*-n`,r:`-n^2`},{l:`n*n`,r:`n^2`},d,{l:`n*-n^n1`,r:`-n^(n1+1)`},{l:`n*n^n1`,r:`n^(n1+1)`},{l:`n^n1*-n^n2`,r:`-n^(n1+n2)`},{l:`n^n1*n^n2`,r:`n^(n1+n2)`},{l:`n^n1*-n`,r:`-n^(n1+1)`},{l:`n^n1*n`,r:`n^(n1+1)`},{l:`n^n1/-n`,r:`-n^(n1-1)`},{l:`n^n1/n`,r:`n^(n1-1)`},{l:`n/-n^n1`,r:`-n^(1-n1)`},{l:`n/n^n1`,r:`n^(1-n1)`},{l:`n^n1/-n^n2`,r:`n^(n1-n2)`},{l:`n^n1/n^n2`,r:`n^(n1-n2)`},{l:`n1+(-n2*n3)`,r:`n1-n2*n3`},{l:`v*(-c)`,r:`-c*v`},{l:`n1+-n2`,r:`n1-n2`},{l:`v*c`,r:`c*v`},{l:`(n1^n2)^n3`,r:`(n1^(n2*n3))`}],i}function A(e,t,n){var r=e.type,i=arguments.length>1;if(r===`OperatorNode`&&e.isBinary()){var a=!1,o;if(e.op===`^`&&(e.args[0].type===`ParenthesisNode`||e.args[0].type===`OperatorNode`)&&e.args[1].type===`ConstantNode`&&(o=parseFloat(e.args[1].value),a=o>=2&&lu(o)),a){if(o>2){var s=e.args[0];e=new w(`*`,`multiply`,[s,new w(`^`,`pow`,[e.args[0].cloneDeep(),new b(o-1)])])}else e=new w(`*`,`multiply`,[e.args[0],e.args[0].cloneDeep()]);i&&(n===`content`?t.content=e:t.args[n]=e)}}if(r===`ParenthesisNode`)A(e.content,e,`content`);else if(r!==`ConstantNode`&&r!==`SymbolNode`)for(var c=0;c<e.args.length;c++)A(e.args[c],e,c);if(!i)return e}function j(e,t){t===void 0&&(t=[]),t[0]=0;var n={};n.cte=1,n.oper=`+`,n.fire=``;var r=0,i=``;f(e,null,n),r=t.length-1;for(var a=!0,o,s=r;s>=0;s--)if(t[s]!==0){var c=new b(a?t[s]:Math.abs(t[s])),l=t[s]<0?`-`:`+`;if(s>0){var u=new T(i);if(s>1){var d=new b(s);u=new w(`^`,`pow`,[u,d])}c=t[s]===-1&&a?new w(`-`,`unaryMinus`,[u]):Math.abs(t[s])===1?u:new w(`*`,`multiply`,[c,u])}o=a?c:l===`+`?new w(`+`,`add`,[o,c]):new w(`-`,`subtract`,[o,c]),a=!1}if(a)return new b(0);return o;function f(e,n,a){var o=e.type;if(o===`FunctionNode`)throw Error(`There is an unsolved function call`);if(o===`OperatorNode`){if(!`+-*^`.includes(e.op))throw Error(`Operator `+e.op+` invalid`);if(n!==null&&((e.fn===`unaryMinus`||e.fn===`pow`)&&n.fn!==`add`&&n.fn!==`subtract`&&n.fn!==`multiply`||(e.fn===`subtract`||e.fn===`add`||e.fn===`multiply`)&&n.fn!==`add`&&n.fn!==`subtract`||(e.fn===`subtract`||e.fn===`add`||e.fn===`unaryMinus`)&&a.noFil!==0))throw Error(`Invalid `+e.op+` placing`);(e.op===`^`||e.op===`*`)&&(a.fire=e.op);for(var s=0;s<e.args.length;s++)e.fn===`unaryMinus`&&(a.oper=`-`),(e.op===`+`||e.fn===`subtract`)&&(a.fire=``,a.cte=1,a.oper=s===0?`+`:e.op),a.noFil=s,f(e.args[s],e,a)}else if(o===`SymbolNode`){if(e.name!==i&&i!==``)throw Error(`There is more than one variable`);if(i=e.name,n===null){t[1]=1;return}if(n.op===`^`&&a.noFil!==0)throw Error(`In power the variable should be the first parameter`);if(n.op===`*`&&a.noFil!==1)throw Error(`In multiply the variable should be the second parameter`);(a.fire===``||a.fire===`*`)&&(r<1&&(t[1]=0),t[1]+=a.cte*(a.oper===`+`?1:-1),r=M
2633ath.max(1,r))}else if(o===`ConstantNode`){var c=parseFloat(e.value);if(n===null){t[0]=c;return}if(n.op===`^`){if(a.noFil!==1)throw Error(`Constant cannot be powered`);if(!lu(c)||c<=0)throw Error(`Non-integer exponent is not allowed`);for(var l=r+1;l<c;l++)t[l]=0;c>r&&(t[c]=0),t[c]+=a.cte*(a.oper===`+`?1:-1),r=Math.max(c,r);return}a.cte=c,a.fire===``&&(t[0]+=a.cte*(a.oper===`+`?1:-1))}else throw Error(`Type `+o+` is not allowed`)}}})})),QP,$P,eF,LCe=e((()=>{X(),QP=`zpk2tf`,$P=[`typed`,`add`,`multiply`,`Complex`,`number`],eF=Y(QP,$P,e=>{var{typed:t,add:n,multiply:r,Complex:i,number:a}=e;return t(QP,{"Array,Array,number":function(e,t,n){return o(e,t,n)},"Array,Array":function(e,t){return o(e,t,1)},"Matrix,Matrix,number":function(e,t,n){return o(e.valueOf(),t.valueOf(),n)},"Matrix,Matrix":function(e,t){return o(e.valueOf(),t.valueOf(),1)}});function o(e,t,n){e.some(e=>e.type===`BigNumber`)&&(e=e.map(e=>a(e))),t.some(e=>e.type===`BigNumber`)&&(t=t.map(e=>a(e)));for(var o=[i(1,0)],c=[i(1,0)],l=0;l<e.length;l++){var u=e[l];typeof u==`number`&&(u=i(u,0)),o=s(o,[i(1,0),i(-u.re,-u.im)])}for(var d=0;d<t.length;d++){var f=t[d];typeof f==`number`&&(f=i(f,0)),c=s(c,[i(1,0),i(-f.re,-f.im)])}for(var p=0;p<o.length;p++)o[p]=r(o[p],n);return[o,c]}function s(e,t){for(var a=[],o=0;o<e.length+t.length-1;o++){a[o]=i(0,0);for(var s=0;s<e.length;s++)o-s>=0&&o-s<t.length&&(a[o]=n(a[o],r(e[s],t[o-s])))}return a}})})),tF,nF,rF,RCe=e((()=>{X(),tF=`freqz`,nF=[`typed`,`add`,`multiply`,`Complex`,`divide`,`matrix`],rF=Y(tF,nF,e=>{var{typed:t,add:n,multiply:r,Complex:i,divide:a,matrix:o}=e;return t(tF,{"Array, Array":function(e,t){return s(e,t,c(512))},"Array, Array, Array":function(e,t,n){return s(e,t,n)},"Array, Array, number":function(e,t,n){if(n<0)throw Error(`w must be a positive number`);return s(e,t,c(n))},"Matrix, Matrix":function(e,t){var n=c(512),{w:r,h:i}=s(e.valueOf(),t.valueOf(),n);return{w:o(r),h:o(i)}},"Matrix, Matrix, Matrix":function(e,t,n){var{h:r}=s(e.valueOf(),t.valueOf(),n.valueOf());return{h:o(r),w:o(n)}},"Matrix, Matrix, number":function(e,t,n){if(n<0)throw Error(`w must be a positive number`);var r=c(n),{h:i}=s(e.valueOf(),t.valueOf(),r);return{h:o(i),w:o(r)}}});function s(e,t,o){for(var s=[],c=[],l=0;l<o.length;l++){for(var u=i(0,0),d=i(0,0),f=0;f<e.length;f++)u=n(u,r(e[f],i(Math.cos(-f*o[l]),Math.sin(-f*o[l]))));for(var p=0;p<t.length;p++)d=n(d,r(t[p],i(Math.cos(-p*o[l]),Math.sin(-p*o[l]))));s.push(u),c.push(d)}for(var m=[],h=0;h<s.length;h++)m.push(a(s[h],c[h]));return{h:m,w:o}}function c(e){for(var t=[],n=0;n<e;n++)t.push(n/e*Math.PI);return t}})})),iF,aF,oF,zCe=e((()=>{X(),iF=`reviver`,aF=[`classes`],oF=Y(iF,aF,e=>{var{classes:t}=e;return function(e,n){var r=t[n&&n.mathjs];return r&&typeof r.fromJSON==`function`?r.fromJSON(n):n}})})),sF,cF,lF,BCe=e((()=>{X(),sF=`replacer`,cF=[],lF=Y(sF,cF,()=>function(e,t){return typeof t==`number`&&(!Number.isFinite(t)||isNaN(t))?{mathjs:`number`,value:String(t)}:typeof t==`bigint`?{mathjs:`bigint`,value:String(t)}:t})})),uF,VCe=e((()=>{uF=`15.2.0`}));function dF(e,t,n){return Y(e,t,n,{recreateOnConfigChange:!0})}var fF,pF,mF,hF,gF,_F,vF,yF,bF,xF,SF,CF,wF,TF,EF,DF,OF,kF,AF,HCe=e((()=>{X(),VCe(),xhe(),ph(),fF=Y(`true`,[],()=>!0),pF=Y(`false`,[],()=>!1),mF=Y(`null`,[],()=>null),hF=dF(`Infinity`,[`config`,`?BigNumber`],e=>{var{config:t,BigNumber:n}=e;return t.number===`BigNumber`?new n(1/0):1/0}),gF=dF(`NaN`,[`config`,`?BigNumber`],e=>{var{config:t,BigNumber:n}=e;return t.number===`BigNumber`?new n(NaN):NaN}),_F=dF(`pi`,[`config`,`?BigNumber`],e=>{var{config:t,BigNumber:n}=e;return t.number===`BigNumber`?QS(n):km}),vF=dF(`tau`,[`config`,`?BigNumber`],e=>{var{config:t,BigNumber:n}=e;return t.number===`BigNumber`?bhe(n):Am}),yF=dF(`e`,[`config`,`?BigNumber`],e=>{var{config:t,BigNumber:n}=e;return t.number===`BigNumber`?vhe(n):jm}),bF=dF(`phi`,[`config`,`?BigNumber`],e=>{var{config:t,BigNumber:n}=e;return t.number===`BigNumber`?yhe(n):Mm}),xF=dF(`LN2`,[`config`,`?BigNumber`],e=>{var{config:t,BigNumber:n}=e;return t.number===`BigNumber`?new n(2).ln():Math.LN2}),SF=dF(`LN10`,[`config`,`?BigNumber`],e=>{var{config:t,BigNumber:n}=e;return t.number===`BigNumber`?new n(10).ln():Math.LN10}),CF=dF(`LOG2E`,[`config`,`?BigNumber`],e=>{var{config:t,BigNumber:n}=e;return t.number===`BigNumber`?new n(1).div(new n(2).ln()):Math.LOG2E}
2633),wF=dF(`LOG10E`,[`config`,`?BigNumber`],e=>{var{config:t,BigNumber:n}=e;return t.number===`BigNumber`?new n(1).div(new n(10).ln()):Math.LOG10E}),TF=dF(`SQRT1_2`,[`config`,`?BigNumber`],e=>{var{config:t,BigNumber:n}=e;return t.number===`BigNumber`?new n(`0.5`).sqrt():Math.SQRT1_2}),EF=dF(`SQRT2`,[`config`,`?BigNumber`],e=>{var{config:t,BigNumber:n}=e;return t.number===`BigNumber`?new n(2).sqrt():Math.SQRT2}),DF=dF(`i`,[`Complex`],e=>{var{Complex:t}=e;return t.I}),OF=Y(`PI`,[`pi`],e=>{var{pi:t}=e;return t}),kF=Y(`E`,[`e`],e=>{var{e:t}=e;return t}),AF=Y(`version`,[],()=>uF)}));function jF(e,t,n){return Y(e,[`config`,`Unit`,`BigNumber`],e=>{var{config:r,Unit:i,BigNumber:a}=e,o=new i(r.number===`BigNumber`?new a(t):parseFloat(t),n);return o.fixPrefix=!0,o})}function MF(e,t){return Y(e,[`config`,`BigNumber`],e=>{var{config:n,BigNumber:r}=e;return n.number===`BigNumber`?new r(t):t})}var NF,PF,FF,IF,LF,RF,zF,BF,VF,HF,UF,WF,GF,KF,qF,JF,YF,XF,ZF,QF,$F,eI,tI,nI,rI,iI,aI,oI,sI,cI,lI,uI,dI,fI,pI,mI,hI,gI,_I,vI,yI,bI,xI,SI,CI,wI,TI,EI,DI,OI,kI,UCe=e((()=>{X(),NF=jF(`speedOfLight`,`299792458`,`m s^-1`),PF=jF(`gravitationConstant`,`6.67430e-11`,`m^3 kg^-1 s^-2`),FF=jF(`planckConstant`,`6.62607015e-34`,`J s`),IF=jF(`reducedPlanckConstant`,`1.0545718176461565e-34`,`J s`),LF=jF(`magneticConstant`,`1.25663706212e-6`,`N A^-2`),RF=jF(`electricConstant`,`8.8541878128e-12`,`F m^-1`),zF=jF(`vacuumImpedance`,`376.730313667`,`ohm`),BF=jF(`coulomb`,`8.987551792261171e9`,`N m^2 C^-2`),VF=jF(`coulombConstant`,`8.987551792261171e9`,`N m^2 C^-2`),HF=jF(`elementaryCharge`,`1.602176634e-19`,`C`),UF=jF(`bohrMagneton`,`9.2740100783e-24`,`J T^-1`),WF=jF(`conductanceQuantum`,`7.748091729863649e-5`,`S`),GF=jF(`inverseConductanceQuantum`,`12906.403729652257`,`ohm`),KF=jF(`magneticFluxQuantum`,`2.0678338484619295e-15`,`Wb`),qF=jF(`nuclearMagneton`,`5.0507837461e-27`,`J T^-1`),JF=jF(`klitzing`,`25812.807459304513`,`ohm`),YF=jF(`bohrRadius`,`5.29177210903e-11`,`m`),XF=jF(`classicalElectronRadius`,`2.8179403262e-15`,`m`),ZF=jF(`electronMass`,`9.1093837015e-31`,`kg`),QF=jF(`fermiCoupling`,`1.1663787e-5`,`GeV^-2`),$F=MF(`fineStructure`,.0072973525693),eI=jF(`hartreeEnergy`,`4.3597447222071e-18`,`J`),tI=jF(`protonMass`,`1.67262192369e-27`,`kg`),nI=jF(`deuteronMass`,`3.3435830926e-27`,`kg`),rI=jF(`neutronMass`,`1.6749271613e-27`,`kg`),iI=jF(`quantumOfCirculation`,`3.6369475516e-4`,`m^2 s^-1`),aI=jF(`rydberg`,`10973731.568160`,`m^-1`),oI=jF(`thomsonCrossSection`,`6.6524587321e-29`,`m^2`),sI=MF(`weakMixingAngle`,.2229),cI=MF(`efimovFactor`,22.7),lI=jF(`atomicMass`,`1.66053906660e-27`,`kg`),uI=jF(`avogadro`,`6.02214076e23`,`mol^-1`),dI=jF(`boltzmann`,`1.380649e-23`,`J K^-1`),fI=jF(`faraday`,`96485.33212331001`,`C mol^-1`),pI=jF(`firstRadiation`,`3.7417718521927573e-16`,`W m^2`),mI=jF(`loschmidt`,`2.686780111798444e25`,`m^-3`),hI=jF(`gasConstant`,`8.31446261815324`,`J K^-1 mol^-1`),gI=jF(`molarPlanckConstant`,`3.990312712893431e-10`,`J s mol^-1`),_I=jF(`molarVolume`,`0.022413969545014137`,`m^3 mol^-1`),vI=MF(`sackurTetrode`,-1.16487052358),yI=jF(`secondRadiation`,`0.014387768775039337`,`m K`),bI=jF(`stefanBoltzmann`,`5.67037441918443e-8`,`W m^-2 K^-4`),xI=jF(`wienDisplacement`,`2.897771955e-3`,`m K`),SI=jF(`molarMass`,`0.99999999965e-3`,`kg mol^-1`),CI=jF(`molarMassC12`,`11.9999999958e-3`,`kg mol^-1`),wI=jF(`gravity`,`9.80665`,`m s^-2`),TI=jF(`planckLength`,`1.616255e-35`,`m`),EI=jF(`planckMass`,`2.176435e-8`,`kg`),DI=jF(`planckTime`,`5.391245e-44`,`s`),OI=jF(`planckCharge`,`1.87554603778e-18`,`C`),kI=jF(`planckTemperature`,`1.416785e+32`,`K`)}));function AI(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function WCe(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?AI(Object(n),!0).forEach(function(t){Rn(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):AI(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var jI,MI,NI,GCe=e((()=>{Ln(),Uw(),X(),Kg(),Ql(),jI=`mapSlices`,MI=[`typed`,`isInteger`],NI=Y(jI,MI,e=>{var{typed:t,isInteger:n}=e,r=Gg({typed:t,isInteger:n});return t(`mapSlices`,{"...any":function(e){var t=e[1];bl(t)?e[1]=t-1:xl(t)&&(e[1]=t.minus(1));try{return r.apply(null,e)}catch(e){throw Hw(e)}}})},WCe({isTransformFunction:!0},Gg.meta))})),PI,FI,II,KCe=e((()=>{Uw(),X(),Hde(),Ql(),PI=`column`,FI=[`typed`,`Index`,`matrix`,`range`],II=Y(PI,FI,e=>{var{typed:t,Index:n,matrix:r,range:i}=e,a=nb({typed:t,Index:n,matrix:r,range:i});return t(`column`,{"...any":function(e){var t=e.length-1,n=e[t];bl(n)&&(e[t]=n-1);try{return a.apply(null,e)}catch(e){throw Hw(e)}}})},{isTransformFunction:!0})}));function LI(e,t,n){var r=e.filter(function(e){return Jl(e)&&!(e.name in t)&&!n.has(e.name)})[0];if(!r)throw Error(`No undefined variable found in inline expression "`+e+`"`);var i=r.name,a=new Map,o=new vl(n,a,new Set([i])),s=e.compile();return function(e){return a.set(i,e),s.evaluate(o)}}var RI=e((()=>{Ql(),yl()}));function zI(e,t,n){return t===n?e:t===n+1?function(){var t=[...arguments],r=t.slice(0,n),i=BI(t[n]);return e(...r,i)}:t>n+1?function(){var t=[...arguments],r=t.slice(0,n),i=BI(t[n]),a=t.slice(n+1);return e(...r,i,...a)}:e}function BI(e){return e.map(e=>e+1)}var VI,HI,UI,WI=e((()=>{X(),VI=`transformCallback`,HI=[`typed`],UI=Y(VI,HI,e=>{var{typed:t}=e;return function(e,r){return t.isTypedFunction(e)?n(e,r):zI(e,e.length,r)};function n(e,r){var i=Object.fromEntries(Object.entries(e.signatures).map(e=>{var[i,a]=e,o=i.split(`,`).length;return t.isTypedFunction(a)?[i,n(a,r)]:[i,zI(a,o,r)]}
2633));return typeof e.name==`string`?t(e.name,i):t(i)}})})),GI,KI,qI,qCe=e((()=>{Qde(),X(),Ql(),RI(),WI(),GI=`filter`,KI=[`typed`],qI=Y(GI,KI,e=>{var{typed:t}=e;function n(e,n,i){var a=lb({typed:t}),o=UI({typed:t});if(e.length===0)return a();var s=e[0];if(e.length===1)return a(s);var c=e.length-1,l=e[c];return s&&=r(s,i),l&&=Jl(l)||Vl(l)?r(l,i):LI(l,n,i),a(s,o(l,c))}n.rawArgs=!0;function r(e,t){return e.compile().evaluate(t)}return n},{isTransformFunction:!0})})),JI,YI,XI,JCe=e((()=>{rfe(),WI(),X(),Ql(),RI(),JI=`forEach`,YI=[`typed`],XI=Y(JI,YI,e=>{var{typed:t}=e,n=pb({typed:t}),r=UI({typed:t});function i(e,t,i){if(e.length===0)return n();var o=e[0];if(e.length===1)return n(o);var s=e.length-1,c=e[s];return o&&=a(o,i),c&&=Jl(c)||Vl(c)?a(c,i):LI(c,t,i),n(o,r(c,s))}i.rawArgs=!0;function a(e,t){return e.compile().evaluate(t)}return i},{isTransformFunction:!0})})),ZI,QI,$I,YCe=e((()=>{Ql(),X(),ZI=`index`,QI=[`Index`,`getMatrixDataType`],$I=Y(ZI,QI,e=>{var{Index:t,getMatrixDataType:n}=e;return function(){for(var e=[],r=0,i=arguments.length;r<i;r++){var a=arguments[r];if(jl(a))a.start--,a.end-=a.step>0?0:2;else if(a&&a.isSet===!0)a=a.map(function(e){return e-1});else if(Zl(a)||Dl(a))n(a)!==`boolean`&&(a=a.map(function(e){return e-1}));else if(bl(a)||Sl(a))a--;else if(xl(a))a=a.toNumber()-1;else if(typeof a!=`string`)throw TypeError(`Dimension must be an Array, Matrix, number, bigint, string, or Range`);e[r]=a}var o=new t;return t.apply(o,e),o}},{isTransformFunction:!0})})),eL,tL,nL,XCe=e((()=>{X(),Ql(),dfe(),RI(),WI(),eL=`map`,tL=[`typed`],nL=Y(eL,tL,e=>{var{typed:t}=e,n=xb({typed:t}),r=UI({typed:t});function i(e,t,i){if(e.length===0)return n();if(e.length===1)return n(e[0]);var a=e.length-1,o=e.slice(0,a),s=e[a];return o=o.map(e=>c(e,i)),s&&=Jl(s)||Vl(s)?c(s,i):LI(s,t,i),n(...o,r(s,a));function c(e,t){return e.compile().evaluate(t)}}return i.rawArgs=!0,i},{isTransformFunction:!0})}));function ZCe(e){return bl(e)?e-1:xl(e)?e.minus(1):e}function QCe(e){return bl(e)||xl(e)}var $Ce=e((()=>{Ql()}));function rL(e){if(e.length===2&&Ol(e[0])){e=e.slice();var t=e[1];QCe(t)&&(e[1]=ZCe(t))}return e}var iL=e((()=>{Ql(),$Ce()})),aL,oL,sL,ewe=e((()=>{X(),Uw(),$me(),iL(),aL=`max`,oL=[`typed`,`config`,`numeric`,`larger`,`isNaN`],sL=Y(aL,oL,e=>{var{typed:t,config:n,numeric:r,larger:i,isNaN:a}=e,o=US({typed:t,config:n,numeric:r,larger:i,isNaN:a});return t(`max`,{"...any":function(e){e=rL(e);try{return o.apply(null,e)}catch(e){throw Hw(e)}}})},{isTransformFunction:!0})})),cL,lL,uL,twe=e((()=>{X(),Uw(),qM(),iL(),cL=`mean`,lL=[`typed`,`add`,`divide`],uL=Y(cL,lL,e=>{var{typed:t,add:n,divide:r}=e,i=KM({typed:t,add:n,divide:r});return t(`mean`,{"...any":function(e){e=rL(e);try{return i.apply(null,e)}catch(e){throw Hw(e)}}})},{isTransformFunction:!0})})),dL,fL,pL,nwe=e((()=>{X(),Uw(),the(),iL(),dL=`min`,fL=[`typed`,`config`,`numeric`,`smaller`,`isNaN`],pL=Y(dL,fL,e=>{var{typed:t,config:n,numeric:r,smaller:i,isNaN:a}=e,o=GS({typed:t,config:n,numeric:r,smaller:i,isNaN:a});return t(`min`,{"...any":function(e){e=rL(e);try{return o.apply(null,e)}catch(e){throw Hw(e)}}})},{isTransformFunction:!0})})),mL,hL,gL,rwe=e((()=>{X(),bfe(),mL=`range`,hL=[`typed`,`config`,`?matrix`,`?bignumber`,`equal`,`smaller`,`smallerEq`,`larger`,`largerEq`,`add`,`isZero`,`isPositive`],gL=Y(mL,hL,e=>{var{typed:t,config:n,matrix:r,bignumber:i,equal:a,smaller:o,smallerEq:s,larger:c,largerEq:l,add:u,isZero:d,isPositive:f}=e,p=Ob({typed:t,config:n,matrix:r,bignumber:i,equal:a,smaller:o,smallerEq:s,larger:c,largerEq:l,add:u,isZero:d,isPositive:f});return t(`range`,{"...any":function(e){return typeof e[e.length-1]!=`boolean`&&e.push(!0),p.apply(null,e)}})},{isTransformFunction:!0})})),_L,vL,yL,iwe=e((()=>{X(),jfe(),Uw(),Ql(),_L=`row`,vL=[`typed`,`Index`,`matrix`,`range`],yL=Y(_L,vL,e=>{var{typed:t,Index:n,matrix:r,range:i}=e,a=Lb({typed:t,Index:n,matrix:r,range:i});return t(`row`,{"...any":function(e){var t=e.length-1,n=e[t];bl(n)&&(e[t]=n-1);try{return a.apply(null,e)}catch(e){throw Hw(e)}}})},{isTransformFunction:!0})})),bL,xL,SL,awe=e((()=>{X(),Uw(),Vfe(),bL=`subset`,xL=[`typed`,`matrix`,`zeros`,`add`],SL=Y(bL,xL,e=>{var{typed:t,matrix:n,zeros:r,add:i}=e,a=Ub({typed:t,matrix:n,zeros:r,add:i});return t(`subset`,{"...any":function(e){try{return a.apply(null,e)}catch(e){throw Hw(e)}}})},{isTransformFunction:!0})})),CL,wL,TL,owe=e((()=>{Ql(),Uw(),X(),Bde(),CL=`concat`,wL=[`typed`,`matrix`,`isInteger`],TL=Y(CL,wL,e=>{var{typed:t,matrix:n,isInteger:r}=e,i=eb({typed:t,matrix:n,isInteger:r});return t(`concat`,{"...any":function(e){var t=e.length-1,n=e[t];bl(n)?e[t]=n-1:xl(n)&&(e[t]=n.minus(1));try{return i.apply(null,e)}catch(e){throw Hw(e)}}})},{isTransformFunction:!0})})),EL,DL,OL,swe=e((()=>{X(),Uw(),pfe(),iL(),EL=`diff`,DL=[`typed`,`matrix`,`subtract`,`number`,`bignumber`],OL=Y(EL,DL,e=>{var{typed:t,matrix:n,subtract:r,number:i,bignumber:a}=e,o=Cb({typed:t,matrix:n,subtract:r,number:i,bignumber:a});return t(EL,{"...any":function(e){e=rL(e);try{return o.apply(null,e)}catch(e){throw Hw(e)}}})},{isTransformFunction:!0})})),kL,AL,jL,cwe=e((()=>
2633{X(),fN(),Uw(),iL(),kL=`std`,AL=[`typed`,`map`,`sqrt`,`variance`],jL=Y(kL,AL,e=>{var{typed:t,map:n,sqrt:r,variance:i}=e,a=dN({typed:t,map:n,sqrt:r,variance:i});return t(`std`,{"...any":function(e){e=rL(e);try{return a.apply(null,e)}catch(e){throw Hw(e)}}})},{isTransformFunction:!0})})),ML,NL,PL,lwe=e((()=>{X(),Uw(),zM(),iL(),ML=`sum`,NL=[`typed`,`config`,`add`,`numeric`],PL=Y(ML,NL,e=>{var{typed:t,config:n,add:r,numeric:i}=e,a=RM({typed:t,config:n,add:r,numeric:i});return t(ML,{"...any":function(e){e=rL(e);try{return a.apply(null,e)}catch(e){throw Hw(e)}}})},{isTransformFunction:!0})})),FL,IL,LL,uwe=e((()=>{X(),cN(),iL(),FL=`quantileSeq`,IL=[`typed`,`bignumber`,`add`,`subtract`,`divide`,`multiply`,`partitionSelect`,`compare`,`isInteger`,`smaller`,`smallerEq`,`larger`,`mapSlices`],LL=Y(FL,IL,e=>{var{typed:t,bignumber:n,add:r,subtract:i,divide:a,multiply:o,partitionSelect:s,compare:c,isInteger:l,smaller:u,smallerEq:d,larger:f,mapSlices:p}=e,m=sN({typed:t,bignumber:n,add:r,subtract:i,divide:a,multiply:o,partitionSelect:s,compare:c,isInteger:l,smaller:u,smallerEq:d,larger:f,mapSlices:p});return t(`quantileSeq`,{"Array | Matrix, number | BigNumber":m,"Array | Matrix, number | BigNumber, number":(e,t,n)=>m(e,t,h(n)),"Array | Matrix, number | BigNumber, boolean":m,"Array | Matrix, number | BigNumber, boolean, number":(e,t,n,r)=>m(e,t,n,h(r)),"Array | Matrix, Array | Matrix":m,"Array | Matrix, Array | Matrix, number":(e,t,n)=>m(e,t,h(n)),"Array | Matrix, Array | Matrix, boolean":m,"Array | Matrix, Array | Matrix, boolean, number":(e,t,n,r)=>m(e,t,n,h(r))});function h(e){return rL([[],e])[1]}},{isTransformFunction:!0})})),RL,zL,BL,dwe=e((()=>{Ql(),X(),Uw(),UM(),RL=`cumsum`,zL=[`typed`,`add`,`unaryPlus`],BL=Y(RL,zL,e=>{var{typed:t,add:n,unaryPlus:r}=e,i=HM({typed:t,add:n,unaryPlus:r});return t(RL,{"...any":function(e){if(e.length===2&&Ol(e[0])){var t=e[1];bl(t)?e[1]=t-1:xl(t)&&(e[1]=t.minus(1))}try{return i.apply(null,e)}catch(e){throw Hw(e)}}})},{isTransformFunction:!0})})),VL,HL,UL,fwe=e((()=>{X(),Uw(),iN(),iL(),VL=`variance`,HL=[`typed`,`add`,`subtract`,`multiply`,`divide`,`mapSlices`,`isNaN`],UL=Y(VL,HL,e=>{var{typed:t,add:n,subtract:r,multiply:i,divide:a,mapSlices:o,isNaN:s}=e,c=rN({typed:t,add:n,subtract:r,multiply:i,divide:a,mapSlices:o,isNaN:s});return t(VL,{"...any":function(e){e=rL(e);try{return c.apply(null,e)}catch(e){throw Hw(e)}}})},{isTransformFunction:!0})})),WL,GL,KL,pwe=e((()=>{Epe(),X(),Cpe(),WL=`print`,GL=[`typed`,`matrix`,`zeros`,`add`],KL=Y(WL,GL,e=>{var{typed:t,matrix:n,zeros:r,add:i}=e,a=Sx({typed:t,matrix:n,zeros:r,add:i});return t(WL,{"string, Object | Array":function(e,t){return a(o(e),t)},"string, Object | Array, number | Object":function(e,t,n){return a(o(e),t,n)}});function o(e){return e.replace(bx,e=>`$`+e.slice(1).split(`.`).map(function(e){return!isNaN(e)&&e.length>0?parseInt(e)-1:e}).join(`.`))}},{isTransformFunction:!0})})),qL,JL,YL,mwe=e((()=>{gme(),X(),Ql(),qL=`and`,JL=[`typed`,`matrix`,`zeros`,`add`,`equalScalar`,`not`,`concat`],YL=Y(qL,JL,e=>{var{typed:t,matrix:n,equalScalar:r,zeros:i,not:a,concat:o}=e,s=mS({typed:t,matrix:n,equalScalar:r,zeros:i,not:a,concat:o});function c(e,t,n){var r=e[0].compile().evaluate(n);return!Ol(r)&&!s(r,!0)?!1:s(r,e[1].compile().evaluate(n))}return c.rawArgs=!0,c},{isTransformFunction:!0})})),XL,ZL,QL,hwe=e((()=>{Ide(),X(),Ql(),XL=`or`,ZL=[`typed`,`matrix`,`equalScalar`,`DenseMatrix`,`concat`],QL=Y(XL,ZL,e=>{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:i,concat:a}=e,o=Xy({typed:t,matrix:n,equalScalar:r,DenseMatrix:i,concat:a});function s(e,t,n){var r=e[0].compile().evaluate(n);return!Ol(r)&&o(r,!1)?!0:o(r,e[1].compile().evaluate(n))}return s.rawArgs=!0,s},{isTransformFunction:!0})})),$L,eR,tR,gwe=e((()=>{Pde(),X(),Ql(),$L=`nullish`,eR=[`typed`,`matrix`,`size`,`flatten`,`deepEqual`],tR=Y($L,eR,e=>{var{typed:t,matrix:n,size:r,flatten:i,deepEqual:a}=e,o=Jy({typed:t,matrix:n,size:r,flatten:i,deepEqual:a});function s(e,t,n){var r=e[0].compile().evaluate(n);return!Ol(r)&&r!=null&&r!==void 0?r:o(r,e[1].compile().evaluate(n))}return s.rawArgs=!0,s},{isTransformFunction:!0})})),nR,rR,iR,_we=e((()=>{mde(),X(),Ql(),nR=`bitAnd`,rR=[`typed`,`matrix`,`zeros`,`add`,`equalScalar`,`not`,`concat`],iR=Y(nR,rR,e=>{var{typed:t,matrix:n,equalScalar:r,zeros:i,not:a,concat:o}=e,s=Oy({typed:t,matrix:n,equalScalar:r,zeros:i,not:a,concat:o});
2633function c(e,t,n){var r=e[0].compile().evaluate(n);if(!Ol(r)){if(isNaN(r))return NaN;if(r===0||r===!1)return 0}return s(r,e[1].compile().evaluate(n))}return c.rawArgs=!0,c},{isTransformFunction:!0})})),aR,oR,sR,vwe=e((()=>{vde(),X(),Ql(),aR=`bitOr`,oR=[`typed`,`matrix`,`equalScalar`,`DenseMatrix`,`concat`],sR=Y(aR,oR,e=>{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:i,concat:a}=e,o=My({typed:t,matrix:n,equalScalar:r,DenseMatrix:i,concat:a});function s(e,t,n){var r=e[0].compile().evaluate(n);if(!Ol(r)){if(isNaN(r))return NaN;if(r===-1)return-1;if(r===!0)return 1}return o(r,e[1].compile().evaluate(n))}return s.rawArgs=!0,s},{isTransformFunction:!0})})),cR,lR,uR,ywe=e((()=>{X(),Wp(),cR=`num`,lR=[`typed`,`fraction`],uR=Y(cR,lR,e=>{var{typed:t,fraction:n}=e;return t(cR,{Fraction:e=>e.s*e.n,BigNumber:e=>{var t=n(e);return t.s*t.n},"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),dR,fR,pR,bwe=e((()=>{X(),Wp(),dR=`den`,fR=[`typed`,`fraction`],pR=Y(dR,fR,e=>{var{typed:t,fraction:n}=e;return t(dR,{Fraction:e=>e.d,BigNumber:e=>n(e).d,"Array | Matrix":t.referToSelf(e=>t=>Bp(t,e))})})})),xwe=n({createAbs:()=>Vg,createAccessorNode:()=>Jw,createAcos:()=>cC,createAcosh:()=>uC,createAcot:()=>fC,createAcoth:()=>mC,createAcsc:()=>gC,createAcsch:()=>vC,createAdd:()=>Cw,createAddScalar:()=>Yg,createAnd:()=>mS,createAndTransform:()=>YL,createArg:()=>Ry,createArrayNode:()=>Zw,createAsec:()=>bC,createAsech:()=>SC,createAsin:()=>wC,createAsinh:()=>TC,createAssignmentNode:()=>oT,createAtan:()=>EC,createAtan2:()=>OC,createAtanh:()=>AC,createAtomicMass:()=>lI,createAvogadro:()=>uI,createBellNumbers:()=>pP,createBernoulli:()=>yN,createBigNumberClass:()=>Kd,createBigint:()=>ng,createBignumber:()=>dg,createBin:()=>hx,createBitAnd:()=>Oy,createBitAndTransform:()=>iR,createBitNot:()=>Ay,createBitOr:()=>My,createBitOrTransform:()=>sR,createBitXor:()=>Iy,createBlockNode:()=>lT,createBohrMagneton:()=>UF,createBohrRadius:()=>YF,createBoltzmann:()=>dI,createBoolean:()=>cg,createCatalan:()=>gP,createCbrt:()=>t_,createCeil:()=>v_,createChain:()=>$j,createChainClass:()=>oD,createClassicalElectronRadius:()=>XF,createClone:()=>Fp,createColumn:()=>nb,createColumnTransform:()=>II,createCombinations:()=>CN,createCombinationsWithRep:()=>DN,createCompare:()=>gS,createCompareNatural:()=>yS,createCompareText:()=>xS,createCompile:()=>aE,createComplex:()=>mg,createComplexClass:()=>rf,createComposition:()=>yP,createConcat:()=>eb,createConcatTransform:()=>TL,createConditionalNode:()=>fT,createConductanceQuantum:()=>WF,createConj:()=>By,createConstantNode:()=>wT,createCorr:()=>hN,createCos:()=>PC,createCosh:()=>IC,createCot:()=>RC,createCoth:()=>BC,createCoulomb:()=>BF,createCoulombConstant:()=>VF,createCount:()=>ib,createCreateUnit:()=>oC,createCross:()=>ob,createCsc:()=>HC,createCsch:()=>WC,createCtranspose:()=>qb,createCube:()=>x_,createCumSum:()=>HM,createCumSumTransform:()=>BL,createDeepEqual:()=>FS,createDen:()=>pR,createDenseMatrixClass:()=>Mp,createDerivative:()=>JP,createDet:()=>nM,createDeuteronMass:()=>nI,createDiag:()=>cb,createDiff:()=>Cb,createDiffTransform:()=>OL,createDistance:()=>MM,createDivide:()=>kM,createDivideScalar:()=>jx,createDot:()=>Aw,createDotDivide:()=>Kx,createDotMultiply:()=>Sy,createDotPow:()=>Wx,createE:()=>yF,createEfimovFactor:()=>cI,createEigs:()=>dM,createElectricConstant:()=>RF,createElectronMass:()=>ZF,createElementaryCharge:()=>HF,createEqual:()=>CS,createEqualScalar:()=>qh,createEqualText:()=>TS,createErf:()=>tx,createEvaluate:()=>cE,createExp:()=>w_,createExpm:()=>mM,createExpm1:()=>D_,createFactorial:()=>IN,createFalse:()=>pF,createFaraday:()=>fI,createFermiCoupling:()=>QF,createFft:()=>Zb,createFibonacciHeapClass:()=>JS,createFilter:()=>lb,createFilterTransform:()=>qI,createFineStructure:()=>$F,createFirstRadiation:()=>pI,createFix:()=>j_,createFlatten:()=>db,createFloor:()=>I_,createForEach:()=>pb,createForEachTransform:()=>XI,createFormat:()=>px,createFraction:()=>_g,createFractionClass:()=>Ef,createFreqz:()=>rF,createFunctionAssignmentNode:()=>DT,createFunctionNode:()=>$T,createGamma:()=>AN,createGasConstant:()=>hI,createGcd:()=>Ov,createGetMatrixDataType:()=>hb,createGravitationConstant:()=>PF,createGravity:()=>wI,createHartreeEnergy:()=>eI,createHasNumericValue:()=>wh,createHelp:()=>Xj,createHelpClass:()=>rD,createHex:()=>yx,createHypot:()=>Tw,createI:()=>DF,createIdentity:()=>_b,createIfft:()=>$b,createIm:()=>Hy,createImmutableDenseMatrixClass:()=>KS,createIndex:()=>Iw,createIndexClass:()=>qS,createIndexNode:()=>AT,createIndexTransform:()=>$I,createInfinity:()=>hF,createIntersect:()=>FM,createInv:()=>aM,createInverseConductanceQuantum:()=>GF,createInvmod:()=>_y,createIsBounded:()=>Ih,createIsFinite:()=>zh,createIsInteger:()=>qp,createIsNaN:()=>Nh,createIsNegative:()=>vh,createIsNumeric:()=>xh,createIsPositive:()=>Dh,createIsPrime:()=>Ox,createIsZero:()=>Ah,createKldivergence:()=>zN,createKlitzing:()=>JF,createKron:()=>yb,createLN10:()=>SF,createLN2:()=>xF,createLOG10E:()=>wF,createLOG2E:()=>CF,createLarger:()=>jS,createLargerEq:()=>NS,createLcm:()=>Fv,createLeafCount:()=>SP,createLeftShift:()=>cS,createLgamma:()=>NN,createLog:()=>Rx,createLog10:()=>Vv,createLog1p:()=>Bx,createLog2:()=>Wv,createLoschmidt:()=>mI,createLsolve:()=>Xx,createLsolveAll:()=>eS,createLup:()=>_E,createLusolve:()=>ZE,createLyap:()=>EM,createMad:()=>$M,createMagneticConstant:()=>LF,createMagneticFluxQuantum:()=>KF,createMap:()=>xb,createMapSlices:()=>Gg,createMapSlicesTransform:()=>NI,createMapTransform:()=>nL,createMatrix:()=>bg,createMatrixClass:()=>Mf,createMatrixFromColumns:()=>kg,createMatrixFromFunction:()=>Cg,createMatrixFromRows:()=>Eg,createMax:()=>US,createMaxTransform:()=>sL,createMean:()=>KM,createMeanTransform:()=>uL,createMedian:()=>XM,createMin:()=>GS,createMinTransform:()=>pL,createMod:()=>sv,createMode:()=>sx,createMolarMass:()=>SI,createMolarMassC12:()=>CI,createMolarPlanckConstant:()=>gI,createMolarVolume:()=>_I,createMultinomial:()=>HN,createMultiply:()=>Xv,createMultiplyScalar:()=>qv,createNaN:()=>gF,createNeutronMass:()=>rI,createNode:()=>Vw,createNorm:()=>Dw,createNot:()=>Ky,createNthRoot:()=>$v,createNthRoots:()=>Hx,createNuclearMagneton:()=>qF,createNull:()=>mF,createNullish:()=>Jy,createNullishTransform:()=>tR,createNum:()=>uR,createNumber:()=>$h,createNumeric:()=>kx,createObjectNode:()=>NT,createOct:()=>_x,createOnes:()=>wb,createOperatorNode:()=>RT,createOr:()=>Xy,createOrTransform:()=>
2633QL,createParenthesisNode:()=>VT,createParse:()=>nE,createParser:()=>mE,createParserClass:()=>dE,createPartitionSelect:()=>zS,createPermutations:()=>KN,createPhi:()=>bF,createPi:()=>_F,createPickRandom:()=>$N,createPinv:()=>cM,createPlanckCharge:()=>OI,createPlanckConstant:()=>FF,createPlanckLength:()=>TI,createPlanckMass:()=>EI,createPlanckTemperature:()=>kI,createPlanckTime:()=>DI,createPolynomialRoot:()=>eD,createPow:()=>Nx,createPrint:()=>Sx,createPrintTransform:()=>KL,createProd:()=>dx,createProtonMass:()=>tI,createQr:()=>bE,createQuantileSeq:()=>sN,createQuantileSeqTransform:()=>LL,createQuantumOfCirculation:()=>iI,createRandom:()=>iP,createRandomInt:()=>sP,createRange:()=>Ob,createRangeClass:()=>kf,createRangeNode:()=>WT,createRangeTransform:()=>gL,createRationalize:()=>ZP,createRe:()=>Wy,createReducedPlanckConstant:()=>IF,createRelationalNode:()=>qT,createReplacer:()=>lF,createReshape:()=>Ab,createResize:()=>jb,createResolve:()=>HP,createResultSet:()=>Wu,createReviver:()=>oF,createRightArithShift:()=>uS,createRightLogShift:()=>fS,createRotate:()=>Nb,createRotationMatrix:()=>Fb,createRound:()=>Ix,createRow:()=>Lb,createRowTransform:()=>yL,createRydberg:()=>aI,createSQRT1_2:()=>TF,createSQRT2:()=>EF,createSackurTetrode:()=>vI,createSchur:()=>CM,createSec:()=>KC,createSech:()=>JC,createSecondRadiation:()=>yI,createSetCartesian:()=>rw,createSetDifference:()=>aw,createSetDistinct:()=>sw,createSetIntersect:()=>lw,createSetIsSubset:()=>dw,createSetMultiplicity:()=>pw,createSetPowerset:()=>hw,createSetSize:()=>_w,createSetSymDifference:()=>yw,createSetUnion:()=>xw,createSign:()=>ny,createSimplify:()=>NP,createSimplifyConstant:()=>IP,createSimplifyCore:()=>zP,createSin:()=>XC,createSinh:()=>QC,createSize:()=>zb,createSlu:()=>qE,createSmaller:()=>DS,createSmallerEq:()=>kS,createSolveODE:()=>ex,createSort:()=>VS,createSpaClass:()=>YS,createSparse:()=>iC,createSparseMatrixClass:()=>Xh,createSpeedOfLight:()=>NF,createSplitUnit:()=>Mg,createSqrt:()=>ay,createSqrtm:()=>_M,createSquare:()=>cy,createSqueeze:()=>Vb,createStd:()=>dN,createStdTransform:()=>jL,createStefanBoltzmann:()=>bI,createStirlingS2:()=>uP,createString:()=>ag,createSubset:()=>Ub,createSubsetTransform:()=>SL,createSubtract:()=>dy,createSubtractScalar:()=>Qg,createSum:()=>RM,createSumTransform:()=>PL,createSylvester:()=>bM,createSymbolNode:()=>XT,createSymbolicEqual:()=>GP,createTan:()=>ew,createTanh:()=>tw,createTau:()=>vF,createThomsonCrossSection:()=>oI,createTo:()=>wx,createToBest:()=>Ex,createTrace:()=>Nw,createTranspose:()=>Gb,createTrue:()=>fF,createTypeOf:()=>Hh,createTyped:()=>Vu,createUnaryMinus:()=>Fg,createUnaryPlus:()=>Rg,createUnequal:()=>LS,createUnitClass:()=>eC,createUnitFunction:()=>nC,createUppercaseE:()=>kF,createUppercasePi:()=>OF,createUsolve:()=>Qx,createUsolveAll:()=>nS,createVacuumImpedance:()=>zF,createVariance:()=>rN,createVarianceTransform:()=>UL,createVersion:()=>AF,createWeakMixingAngle:()=>sI,createWienDisplacement:()=>xI,createXgcd:()=>my,createXor:()=>Qy,createZeros:()=>Yb,createZeta:()=>ax,createZpk2tf:()=>eF}),mR=e((()=>{_ce(),vce(),sle(),lle(),mle(),hle(),gle(),jle(),Mle(),Nle(),aue(),oue(),sue(),cue(),lue(),uue(),due(),fue(),pue(),gue(),_ue(),bue(),xue(),Sue(),Cue(),wue(),Tue(),Eue(),Due(),Oue(),kue(),Aue(),jue(),Mue(),Nue(),Pue(),Kg(),Iue(),Lue(),Rue(),zue(),Bue(),Vue(),Hue(),Uue(),L_(),Kue(),que(),Jue(),Yue(),cv(),Xue(),Zue(),Que(),$ue(),ede(),tde(),nde(),rde(),ide(),sde(),mde(),gde(),vde(),Sde(),wde(),Ede(),Ode(),Ade(),Mde(),Pde(),Ide(),Rde(),Bde(),Hde(),Wde(),Kde(),Jde(),Qde(),efe(),rfe(),afe(),sfe(),lfe(),dfe(),pfe(),gfe(),bfe(),Sfe(),Tfe(),Dfe(),kfe(),jfe(),Nfe(),Ffe(),Vfe(),Ufe(),Gfe(),qfe(),Yfe(),Zfe(),npe(),cpe(),upe(),fpe(),mpe(),gpe(),vpe(),bpe(),Spe(),Epe(),Ope(),Ape(),Mpe(),Fpe(),Lpe(),zpe(),Vpe(),Wpe(),Kpe(),Jpe(),Xpe(),Qpe(),eme(),nme(),ime(),ome(),ume(),fme(),mme(),gme(),yme(),Cme(),Tme(),Ome(),Ame(),Nme(),Ime(),zme(),Hme(),Wme(),qme(),Yme(),Zme(),$me(),the(),ihe(),che(),dhe(),mhe(),The(),Dhe(),khe(),jhe(),Nhe(),Fhe(),Lhe(),zhe(),Vhe(),Uhe(),Ghe(),qhe(),Yhe(),Qhe(),tge(),rge(),age(),sge(),lge(),dge(),pge(),hge(),_ge(),yge(),xge(),Cge(),Tge(),Dge(),Age(),Mge(),Pge(),Ige(),Rge(),Bge(),Hge(),Wge(),Kge(),Jge(),Xge(),Qge(),e_e(),n_e(),r_e(),i_e(),a_e(),o_e(),s_e(),c_e(),f_e(),p_e
2633(),m_e(),g_e(),__e(),v_e(),y_e(),b_e(),x_e(),S_e(),C_e(),w_e(),T_e(),E_e(),D_e(),O_e(),A_e(),j_e(),M_e(),N_e(),eve(),nve(),rve(),ive(),ave(),GSe(),KSe(),qSe(),JSe(),YSe(),eCe(),tCe(),nCe(),rCe(),iCe(),aCe(),oCe(),sCe(),cCe(),zM(),UM(),qM(),lCe(),uCe(),iN(),cN(),fN(),dCe(),fCe(),pCe(),mCe(),hCe(),gCe(),_Ce(),vCe(),yCe(),bCe(),xCe(),SCe(),CCe(),wCe(),TCe(),ECe(),DCe(),OCe(),ACe(),jCe(),MCe(),NCe(),PCe(),FCe(),ICe(),LCe(),RCe(),zCe(),BCe(),HCe(),UCe(),GCe(),KCe(),qCe(),JCe(),YCe(),XCe(),ewe(),twe(),nwe(),rwe(),iwe(),awe(),owe(),swe(),cwe(),lwe(),uwe(),dwe(),fwe(),pwe(),mwe(),hwe(),gwe(),_we(),vwe(),ywe(),bwe()})),hR,gR,_R,vR,yR,bR,xR,SR,CR,wR,TR,ER,DR,OR,kR,AR,jR,MR,NR,PR,FR,IR,LR,RR,zR,BR,VR,$,HR,UR,WR,GR,KR,qR,JR,YR,XR,ZR,QR,$R,ez,tz,nz,rz,iz,az,oz,sz,cz,lz,uz,dz,fz,pz,mz,hz,gz,_z,vz,yz,bz,xz,Sz,Cz,wz,Tz,Ez,Dz,Oz,kz,Az,jz,Mz,Nz,Pz,Fz,Iz,Lz,Rz,zz,Bz,Vz,Hz,Uz,Wz,Gz,Kz,qz,Jz,Yz,Xz,Zz,Qz,$z,eB,tB,nB,rB,iB,aB,oB,sB,cB,lB,uB,dB,fB,pB,mB,hB,gB,_B,vB,yB,bB,xB,SB,CB,wB,TB,EB,DB,OB,kB,AB,jB,MB,NB,PB,FB,IB,LB,RB,zB,BB,VB,HB,UB,WB,GB,KB,qB,JB,YB,XB,ZB,QB,$B,eV,tV,nV,rV,iV,aV,oV,sV,cV,lV,uV,dV,fV,pV,mV,hV,gV,_V,vV,yV,bV,xV,SV,CV,wV,TV,EV,DV,OV,kV,AV,jV,MV,NV,PV,FV,IV,LV,RV,zV,BV,VV,HV,UV,WV,GV,KV,qV,JV,YV,XV,ZV,QV,$V,eH,tH,nH,rH,iH,aH,oH,sH,cH,lH,uH,dH,fH,pH,mH,hH,gH,_H,vH,yH,bH,xH,SH,CH,wH,TH,EH,DH,OH,kH,AH,jH,MH,NH,PH,FH,IH,LH,RH,zH,BH,VH,HH,UH,WH,GH,KH,qH,JH,YH,XH,ZH,QH,$H,eU,tU,nU,rU,iU,aU,oU,sU,cU,lU,uU,dU,fU,pU,mU,hU,gU,_U,vU,yU,bU,xU,SU,CU,wU,TU,EU,DU,OU,kU,AU,jU,MU,NU,PU,FU,IU,LU,RU,zU,BU,VU,HU,UU,WU,GU,KU,qU,JU,YU,XU,ZU,QU,$U,eW=e((()=>{ou(),mR(),hR=Kd({config:J}),gR=rf({}),_R=yF({BigNumber:hR,config:J}),vR=pF({}),yR=$F({BigNumber:hR,config:J}),bR=Ef({}),xR=DF({Complex:gR}),SR=hF({BigNumber:hR,config:J}),CR=SF({BigNumber:hR,config:J}),wR=wF({BigNumber:hR,config:J}),TR=Mf({}),ER=gF({BigNumber:hR,config:J}),DR=mF({}),OR=bF({BigNumber:hR,config:J}),kR=kf({}),AR=Wu({}),jR=TF({BigNumber:hR,config:J}),MR=vI({BigNumber:hR,config:J}),NR=vF({BigNumber:hR,config:J}),PR=fF({}),FR=AF({}),IR=Mp({Matrix:TR,config:J}),LR=cI({BigNumber:hR,config:J}),RR=xF({BigNumber:hR,config:J}),zR=_F({BigNumber:hR,config:J}),BR=lF({}),VR=EF({BigNumber:hR,config:J}),$=Vu({BigNumber:hR,Complex:gR,DenseMatrix:IR,Fraction:bR}),HR=sI({BigNumber:hR,config:J}),UR=Vg({typed:$}),WR=cC({Complex:gR,config:J,typed:$}),GR=fC({BigNumber:hR,typed:$}),KR=gC({BigNumber:hR,Complex:gR,config:J,typed:$}),qR=Yg({typed:$}),JR=Ry({typed:$}),YR=SC({BigNumber:hR,Complex:gR,config:J,typed:$}),XR=TC({typed:$}),ZR=EC({typed:$}),QR=AC({Complex:gR,config:J,typed:$}),$R=ng({typed:$}),ez=Ay({typed:$}),tz=cg({typed:$}),nz=Fp({typed:$}),rz=CN({typed:$}),iz=mg({Complex:gR,typed:$}),az=By({typed:$}),oz=PC({typed:$}),sz=RC({BigNumber:hR,typed:$}),cz=HC({BigNumber:hR,typed:$}),lz=x_({typed:$}),uz=qh({config:J,typed:$}),dz=tx({typed:$}),fz=w_({typed:$}),pz=D_({Complex:gR,typed:$}),mz=lb({typed:$}),hz=db({typed:$}),gz=pb({typed:$}),_z=px({typed:$}),vz=hb({typed:$}),yz=yx({format:_z,typed:$}),bz=Hy({typed:$}),xz=Ih({typed:$}),Sz=Nh({typed:$}),Cz=xh({typed:$}),wz=Ox({typed:$}),Tz=CF({BigNumber:hR,config:J}),Ez=NN({Complex:gR,typed:$}),Dz=Vv({Complex:gR,config:J,typed:$}),Oz=Wv({Complex:gR,config:J,typed:$}),kz=xb({typed:$}),Az=sx({isNaN:Sz,isNumeric:Cz,typed:$}),jz=qv({typed:$}),Mz=Ky({typed:$}),Nz=$h({typed:$}),Pz=_x({format:_z,typed:$}),Fz=$N({config:J,typed:$}),Iz=Sx({typed:$}),Lz=iP({config:J,typed:$}),Rz=Wy({typed:$}),zz=KC({BigNumber:hR,typed:$}),Bz=ny({BigNumber:hR,Fraction:bR,complex:iz,typed:$}),Vz=XC({typed:$}),Hz=zb({typed:$}),Uz=Xh({Matrix:TR,equalScalar:uz,typed:$}),Wz=Mg({typed:$}),Gz=cy({typed:$}),Kz=ag({typed:$}),qz=Qg({typed:$}),Jz=ew({typed:$}),Yz=Ex({typed:$}),Xz=Hh({typed:$}),Zz=uC({Complex:gR,config:J,typed:$}),Qz=vC({BigNumber:hR,typed:$}),$z=bC({BigNumber:hR,Complex:gR,config:J,typed:$}),eB=dg({BigNumber:hR,typed:$}),tB=DN({typed:$}),nB=IC({typed:$}),rB=WC({BigNumber:hR,typed:$}),iB=Aw({addScalar:qR,conj:az,multiplyScalar:jz,size:Hz,typed:$}),aB=wh({isNumeric:Cz,typed:$}),oB=zh({isBounded:xz,map:kz,typed:$}),sB=vh({config:J,typed:$}),cB=Ah({equalScalar:uz,typed:$}),lB=bg({DenseMatrix:IR,Matrix:TR,SparseMatrix:Uz,typed:$}),uB=Cg({isZero:cB,matrix:lB,typed:$}),dB=Xv({addScalar:qR,dot:iB,equalScalar:uz,matrix:lB,multiplyScalar:jz,typed:$}),fB=wb({BigNumber:hR,config:J,matrix:lB,typed:$}),pB=sP({config:J,log2:Oz,typed:$}),mB=jb({config:J,matrix:lB}),hB=JC({BigNumber:hR,typed:$}),gB=QC({typed:$}),_B=iC({SparseMatrix:Uz,typed:$}),vB=ay({Complex:gR,config:J,typed:$}),yB=Vb({typed:$}),bB=tw({typed:$}),xB=Gb({matrix:lB,typed:$}),SB=my({BigNumber:hR,config:J,matrix:lB,typed:$}),CB=Yb({BigNumber:hR,config:J,matrix:lB,typed:$}),wB=mC({BigNumber:hR,Complex:gR,config:J,typed:$}),TB=wC({Complex:gR,config:J,typed:$}),EB=hx({format:_z,typed:$}),DB=BC({BigNumber:hR,typed:$}),OB=qb({conj:az,transpose:xB,typed:$}),kB=cb({DenseMatrix:IR,SparseMatrix:Uz,matrix:lB,typed:$}),AB=CS({DenseMatrix:IR,SparseMatrix:Uz,equalScalar:uz,matrix:lB,typed:$}),jB=_g({Fraction:bR,typed:$}),MB=_b({BigNumber:hR,DenseMatrix:IR,SparseMatrix:Uz,config:J,matrix:lB,typed:$}),NB=qp({equal:AB,typed:$}),PB=yb({matrix:lB,multiplyScalar:jz,typed:$}),FB=Gg({isInteger:NB,typed:$}),IB=kg({flatten:hz,matrix:lB,size:Hz,typed:$}),LB=uR({fraction:jB,typed:$}),RB=Ab({isInteger:NB,matrix:lB,typed:$}),zB=Ix({BigNumber:hR,DenseMatrix:IR,config:J,equalScalar:uz,matrix:lB,typed:$,zeros:CB}),BB=Fg({typed:$}),VB=yN({BigNumber:hR,Fraction:bR,config:J,isInteger:NB,number:Nz,typed:$}),HB=t_({BigNumber:hR,Complex:gR,Fraction:bR,config:J,isNegative:sB,matrix:lB,typed:$,unaryMinus:BB}),UB=eb({isInteger:NB,matrix:lB,typed:$}),WB=FS({equal:AB,typed:$}),GB=Sy({concat:UB,equalScalar:uz,matrix:lB,multiplyScalar:jz,typed:$}),KB=I_({DenseMatrix:IR,config:J,equalScalar:uz,matrix:lB,round:zB,typed:$,zeros:CB}),qB=Ov({BigNumber:hR,DenseMatrix:IR,concat:UB,config:J,equalScalar:uz,matrix:lB,round:zB,typed:$,zeros:CB}),JB=Dh({config:J,typed:$}),YB=jS({DenseMatrix:IR,SparseMatrix:Uz,bignumber:eB,concat:UB,config:J,matrix:lB,typed:$}),XB=Fv({concat:UB,equalScalar:uz,matrix:lB,typed:$}),ZB=cS({DenseMatrix:IR,concat:UB,equalScalar:uz,matrix:lB,typed:$,zeros:CB}),QB=sv({DenseMatrix:IR,concat:UB,config:J,equalScalar:uz,matrix:lB,round:zB,typed:$,zeros:CB}),$B=$v({BigNumber:hR,concat:UB,equalScalar:uz,matrix:lB,typed:$}),eV=Jy({deepEqual:WB,flatten:hz,matrix:lB,size:Hz,typed:$}),tV=kx({bignumber:eB,fraction:jB,number:Nz}),nV=dx({config:J,multiplyScalar:jz,numeric:tV,typed:$}),rV=uS({DenseMatrix:IR,concat:UB,equalScalar:uz,matrix:lB,typed:$,zeros:CB}),iV=DS({DenseMatrix:IR,SparseMatrix:Uz,bignumber:eB,concat:UB,config:J,matrix:lB,typed:$}),aV=dy({DenseMatrix:IR,concat:UB,equalScalar:uz,matrix:lB,subtractScalar:qz,typed:$,unaryMinus:BB}),oV=wx({concat:UB,matrix:lB,typed:$}),sV=Rg({config:J,numeric:tV,typed:$}),cV=Qy({DenseMatrix:IR,SparseMatrix:Uz,concat:UB,matrix:lB,typed:$}),lV=Cw({DenseMatrix:IR,SparseMatrix:Uz,addScalar:qR,concat:UB,equalScalar:uz,matrix:lB,typed:$}),uV=OC({BigNumber:hR,DenseMatrix:IR,concat:UB,equalScalar:uz,matrix:lB,typed:$}),dV=Oy({concat:UB,equalScalar:uz,matrix:lB,typed:$}),fV=My({DenseMatrix:IR,concat:UB,equalScalar:uz,matrix:lB,typed:$}),pV=Iy({DenseMatrix:IR,SparseMatrix:Uz,concat:UB,matrix:lB,typed:$}),mV=v_({DenseMatrix:IR,config:J,equalScalar:uz,matrix:lB,round:zB,typed:$,zeros:CB}),hV=gS({BigNumber:hR,DenseMatrix:IR,Fraction:bR,concat:UB,config:J,equalScalar:uz,matrix:lB,typed:$}),gV=xS({concat:UB,matrix:lB,typed:$}),_V=yP({addScalar:qR,combinations:rz,isInteger:NB,isNegative:sB,isPositive:JB,larger:YB,typed:$}),vV=ib({prod:nV,size:Hz,typed:$}),yV=ob({matrix:lB,multiply:dB,subtract:aV,typed:$}),bV=Cb({matrix:lB,number:Nz,subtract:aV,typed:$}),xV=jx({numeric:tV,typed:$}),SV=TS({compareText:gV,isZero:cB,typed:$}),CV=JS({larger:YB,smaller:iV}),wV=j_({Complex:gR,DenseMatrix:IR,ceil:mV,equalScalar:uz,floor:KB,matrix:lB,typed:$,zeros:CB}),TV=Tw({abs:UR,addScalar:qR,divideScalar:xV,isPositive:JB,multiplyScalar:jz,smaller:iV,sqrt:vB,typed:$}),EV=KS({DenseMatrix:IR,smaller:iV}),DV=qS({ImmutableDenseMatrix:EV,getMatrixDataType:vz}
2633),OV=FM({abs:UR,add:lV,addScalar:qR,config:J,divideScalar:xV,equalScalar:uz,flatten:hz,isNumeric:Cz,isZero:cB,matrix:lB,multiply:dB,multiplyScalar:jz,smaller:iV,subtract:aV,typed:$}),kV=_y({BigNumber:hR,add:lV,config:J,equal:AB,isInteger:NB,mod:QB,smaller:iV,typed:$,xgcd:SB}),AV=NS({DenseMatrix:IR,SparseMatrix:Uz,concat:UB,config:J,matrix:lB,typed:$}),jV=Rx({Complex:gR,config:J,divideScalar:xV,typeOf:Xz,typed:$}),MV=Xx({DenseMatrix:IR,divideScalar:xV,equalScalar:uz,matrix:lB,multiplyScalar:jz,subtractScalar:qz,typed:$}),NV=Eg({flatten:hz,matrix:lB,size:Hz,typed:$}),PV=GS({config:J,isNaN:Sz,numeric:tV,smaller:iV,typed:$}),FV=Hx({Complex:gR,config:J,divideScalar:xV,typed:$}),IV=zS({compare:hV,isNaN:Sz,isNumeric:Cz,typed:$}),LV=bE({addScalar:qR,complex:iz,conj:az,divideScalar:xV,equal:AB,identity:MB,isZero:cB,matrix:lB,multiplyScalar:jz,sign:Bz,sqrt:vB,subtractScalar:qz,typed:$,unaryMinus:BB,zeros:CB}),RV=fS({DenseMatrix:IR,concat:UB,equalScalar:uz,matrix:lB,typed:$,zeros:CB}),zV=qE({SparseMatrix:Uz,abs:UR,add:lV,divideScalar:xV,larger:YB,largerEq:AV,multiply:dB,subtract:aV,transpose:xB,typed:$}),BV=YS({FibonacciHeap:CV,addScalar:qR,equalScalar:uz}),VV=Ub({add:lV,matrix:lB,typed:$,zeros:CB}),HV=RM({add:lV,config:J,numeric:tV,typed:$}),UV=Nw({add:lV,matrix:lB,typed:$}),WV=Qx({DenseMatrix:IR,divideScalar:xV,equalScalar:uz,matrix:lB,multiplyScalar:jz,subtractScalar:qz,typed:$}),GV=eF({Complex:gR,add:lV,multiply:dB,number:Nz,typed:$}),KV=gP({addScalar:qR,combinations:rz,divideScalar:xV,isInteger:NB,isNegative:sB,multiplyScalar:jz,typed:$}),qV=yS({compare:hV,typed:$}),JV=HM({add:lV,typed:$,unaryPlus:sV}),YV=nM({divideScalar:xV,isZero:cB,matrix:lB,multiply:dB,subtractScalar:qz,typed:$,unaryMinus:BB}),XV=Kx({DenseMatrix:IR,SparseMatrix:Uz,concat:UB,divideScalar:xV,equalScalar:uz,matrix:lB,typed:$}),ZV=Iw({Index:DV,typed:$}),QV=aM({abs:UR,addScalar:qR,det:YV,divideScalar:xV,identity:MB,matrix:lB,multiply:dB,typed:$,unaryMinus:BB}),$V=Bx({Complex:gR,config:J,divideScalar:xV,log:jV,typed:$}),eH=eS({DenseMatrix:IR,divideScalar:xV,equalScalar:uz,matrix:lB,multiplyScalar:jz,subtractScalar:qz,typed:$}),tH=US({config:J,isNaN:Sz,larger:YB,numeric:tV,typed:$}),nH=Xy({DenseMatrix:IR,concat:UB,equalScalar:uz,matrix:lB,typed:$}),rH=cM({Complex:gR,add:lV,ctranspose:OB,deepEqual:WB,divideScalar:xV,dot:iB,dotDivide:XV,equal:AB,inv:QV,matrix:lB,multiply:dB,typed:$}),iH=Nx({Complex:gR,config:J,fraction:jB,identity:MB,inv:QV,matrix:lB,multiply:dB,number:Nz,typed:$}),aH=rw({DenseMatrix:IR,Index:DV,compareNatural:qV,size:Hz,subset:VV,typed:$}),oH=sw({DenseMatrix:IR,Index:DV,compareNatural:qV,size:Hz,subset:VV,typed:$}),sH=dw({Index:DV,compareNatural:qV,size:Hz,subset:VV,typed:$}),cH=hw({Index:DV,compareNatural:qV,size:Hz,subset:VV,typed:$}),lH=kS({DenseMatrix:IR,SparseMatrix:Uz,concat:UB,config:J,matrix:lB,typed:$}),uH=VS({compare:hV,compareNatural:qV,matrix:lB,typed:$}),dH=_M({abs:UR,add:lV,identity:MB,inv:QV,map:kz,max:tH,multiply:dB,size:Hz,sqrt:vB,subtract:aV,typed:$}),fH=LS({DenseMatrix:IR,SparseMatrix:Uz,concat:UB,config:J,equalScalar:uz,matrix:lB,typed:$}),pH=nS({DenseMatrix:IR,divideScalar:xV,equalScalar:uz,matrix:lB,multiplyScalar:jz,subtractScalar:qz,typed:$}),mH=mS({concat:UB,equalScalar:uz,matrix:lB,not:Mz,typed:$,zeros:CB}),hH=pR({fraction:jB,typed:$}),gH=MM({abs:UR,addScalar:qR,deepEqual:WB,divideScalar:xV,multiplyScalar:jz,sqrt:vB,subtractScalar:qz,typed:$}),_H=Wx({DenseMatrix:IR,SparseMatrix:Uz,concat:UB,equalScalar:uz,matrix:lB,pow:iH,typed:$}),vH=mM({abs:UR,add:lV,identity:MB,inv:QV,multiply:dB,typed:$}),yH=Zb({addScalar:qR,ceil:mV,conj:az,divideScalar:xV,dotDivide:XV,exp:fz,i:xR,log2:Oz,matrix:lB,multiplyScalar:jz,pow:iH,tau:NR,typed:$}),bH=AN({BigNumber:hR,Complex:gR,config:J,multiplyScalar:jz,pow:iH,typed:$}),xH=$b({conj:az,dotDivide:XV,fft:yH,typed:$}),SH=_E({DenseMatrix:IR,Spa:BV,SparseMatrix:Uz,abs:UR,addScalar:qR,divideScalar:xV,equalScalar:uz,larger:YB,matrix:lB,multiplyScalar:jz,subtractScalar:qz,typed:$,unaryMinus:BB}),CH=Ob({bignumber:eB,matrix:lB,add:lV,config:J,equal:AB,isPositive:JB,isZero:cB,larger:YB,largerEq:AV,smaller:iV,smallerEq:lH,typed:$}),wH=Lb({Index:DV,matrix:lB,range:CH,typed:$}),TH=aw({DenseMatrix:IR,Index:DV,compareNatural:qV,size:Hz,subset:VV,typed:$}),EH=pw({Index:DV,compareNatural:qV,size:Hz,subset:VV,typed:$}),DH=yw({Index:DV,concat:UB,setDifference:TH,size:Hz,subset:VV,typed:$}),OH=eC({BigNumber:hR,Complex:gR,Fraction:bR,abs:UR,addScalar:qR,config:J,divi
2633deScalar:xV,equal:AB,fix:wV,format:_z,isNumeric:Cz,multiplyScalar:jz,number:Nz,pow:iH,round:zB,subtractScalar:qz}),kH=zF({BigNumber:hR,Unit:OH,config:J}),AH=xI({BigNumber:hR,Unit:OH,config:J}),jH=lI({BigNumber:hR,Unit:OH,config:J}),MH=UF({BigNumber:hR,Unit:OH,config:J}),NH=dI({BigNumber:hR,Unit:OH,config:J}),PH=nb({Index:DV,matrix:lB,range:CH,typed:$}),FH=WF({BigNumber:hR,Unit:OH,config:J}),IH=BF({BigNumber:hR,Unit:OH,config:J}),LH=oC({Unit:OH,typed:$}),RH=nI({BigNumber:hR,Unit:OH,config:J}),zH=dM({abs:UR,add:lV,addScalar:qR,atan:ZR,bignumber:eB,column:PH,complex:iz,config:J,cos:oz,diag:kB,divideScalar:xV,dot:iB,equal:AB,flatten:hz,im:bz,inv:QV,larger:YB,matrix:lB,matrixFromColumns:IB,multiply:dB,multiplyScalar:jz,number:Nz,qr:LV,re:Rz,reshape:RB,sin:Vz,size:Hz,smaller:iV,sqrt:vB,subtract:aV,typed:$,usolve:WV,usolveAll:pH}),BH=ZF({BigNumber:hR,Unit:OH,config:J}),VH=IN({gamma:bH,typed:$}),HH=QF({BigNumber:hR,Unit:OH,config:J}),UH=hI({BigNumber:hR,Unit:OH,config:J}),WH=wI({BigNumber:hR,Unit:OH,config:J}),GH=JF({BigNumber:hR,Unit:OH,config:J}),KH=mI({BigNumber:hR,Unit:OH,config:J}),qH=LF({BigNumber:hR,Unit:OH,config:J}),JH=SI({BigNumber:hR,Unit:OH,config:J}),YH=gI({BigNumber:hR,Unit:OH,config:J}),XH=rI({BigNumber:hR,Unit:OH,config:J}),ZH=qF({BigNumber:hR,Unit:OH,config:J}),QH=KN({factorial:VH,typed:$}),$H=FF({BigNumber:hR,Unit:OH,config:J}),eU=EI({BigNumber:hR,Unit:OH,config:J}),tU=DI({BigNumber:hR,Unit:OH,config:J}),nU=tI({BigNumber:hR,Unit:OH,config:J}),rU=iI({BigNumber:hR,Unit:OH,config:J}),iU=IF({BigNumber:hR,Unit:OH,config:J}),aU=yI({BigNumber:hR,Unit:OH,config:J}),oU=_w({compareNatural:qV,typed:$}),sU=NF({BigNumber:hR,Unit:OH,config:J}),cU=bI({BigNumber:hR,Unit:OH,config:J}),lU=oI({BigNumber:hR,Unit:OH,config:J}),uU=uI({BigNumber:hR,Unit:OH,config:J}),dU=YF({BigNumber:hR,Unit:OH,config:J}),fU=VF({BigNumber:hR,Unit:OH,config:J}),pU=kM({divideScalar:xV,equalScalar:uz,inv:QV,matrix:lB,multiply:dB,typed:$}),mU=HF({BigNumber:hR,Unit:OH,config:J}),hU=fI({BigNumber:hR,Unit:OH,config:J}),gU=rF({Complex:gR,add:lV,divide:pU,matrix:lB,multiply:dB,typed:$}),_U=PF({BigNumber:hR,Unit:OH,config:J}),vU=GF({BigNumber:hR,Unit:OH,config:J}),yU=ZE({DenseMatrix:IR,lsolve:MV,lup:SH,matrix:lB,slu:zV,typed:$,usolve:WV}),bU=KF({BigNumber:hR,Unit:OH,config:J}),xU=CI({BigNumber:hR,Unit:OH,config:J}),SU=HN({add:lV,divide:pU,factorial:VH,isInteger:NB,isPositive:JB,multiply:dB,typed:$}),CU=OI({BigNumber:hR,Unit:OH,config:J}),wU=kI({BigNumber:hR,Unit:OH,config:J}),TU=sN({bignumber:eB,add:lV,compare:hV,divide:pU,isInteger:NB,larger:YB,mapSlices:FB,multiply:dB,partitionSelect:IV,smaller:iV,smallerEq:lH,subtract:aV,typed:$}),EU=aI({BigNumber:hR,Unit:OH,config:J}),DU=lw({DenseMatrix:IR,Index:DV,compareNatural:qV,size:Hz,subset:VV,typed:$}),OU=ex({abs:UR,add:lV,bignumber:eB,divide:pU,isNegative:sB,isPositive:JB,larger:YB,map:kz,matrix:lB,max:tH,multiply:dB,smaller:iV,subtract:aV,typed:$,unaryMinus:BB}),kU=uP({bignumber:eB,addScalar:qR,combinations:rz,divideScalar:xV,factorial:VH,isInteger:NB,isNegative:sB,larger:YB,multiplyScalar:jz,number:Nz,pow:iH,subtractScalar:qz,typed:$}),AU=nC({Unit:OH,typed:$}),jU=pP({addScalar:qR,isInteger:NB,isNegative:sB,stirlingS2:kU,typed:$}),MU=RF({BigNumber:hR,Unit:OH,config:J}),NU=pI({BigNumber:hR,Unit:OH,config:J}),PU=eI({BigNumber:hR,Unit:OH,config:J}),FU=zN({divide:pU,dotDivide:XV,isNumeric:Cz,log:jV,map:kz,matrix:lB,multiply:dB,sum:HV,typed:$}),IU=KM({add:lV,divide:pU,typed:$}),LU=_I({BigNumber:hR,Unit:OH,config:J}),RU=TI({BigNumber:hR,Unit:OH,config:J}),zU=xw({Index:DV,concat:UB,setIntersect:DU,setSymDifference:DH,size:Hz,subset:VV,typed:$}),BU=rN({add:lV,divide:pU,isNaN:Sz,mapSlices:FB,multiply:dB,subtract:aV,typed:$}),VU=XF({BigNumber:hR,Unit:OH,config:J}),HU=hN({add:lV,divide:pU,matrix:lB,mean:IU,multiply:dB,pow:iH,sqrt:vB,subtract:aV,sum:HV,typed:$}),UU=XM({add:lV,compare:hV,divide:pU,partitionSelect:IV,typed:$}),WU=eD({add:lV,cbrt:HB,divide:pU,equalScalar:uz,im:bz,isZero:cB,multiply:dB,re:Rz,sqrt:vB,subtract:aV,typeOf:Xz,typed:$,unaryMinus:BB}),GU=dN({map:kz,sqrt:vB,typed:$,variance:BU}
2633),KU=ax({BigNumber:hR,Complex:gR,add:lV,config:J,divide:pU,equal:AB,factorial:VH,gamma:bH,isBounded:xz,isNegative:sB,multiply:dB,pi:zR,pow:iH,sin:Vz,smallerEq:lH,subtract:aV,typed:$}),qU=$M({abs:UR,map:kz,median:UU,subtract:aV,typed:$}),JU=Dw({abs:UR,add:lV,conj:az,ctranspose:OB,eigs:zH,equalScalar:uz,larger:YB,matrix:lB,multiply:dB,pow:iH,smaller:iV,sqrt:vB,typed:$}),YU=Fb({BigNumber:hR,DenseMatrix:IR,SparseMatrix:Uz,addScalar:qR,config:J,cos:oz,matrix:lB,multiplyScalar:jz,norm:JU,sin:Vz,typed:$,unaryMinus:BB}),XU=Nb({multiply:dB,rotationMatrix:YU,typed:$}),ZU=CM({identity:MB,matrix:lB,multiply:dB,norm:JU,qr:LV,subtract:aV,typed:$}),QU=bM({abs:UR,add:lV,concat:UB,identity:MB,index:ZV,lusolve:yU,matrix:lB,matrixFromColumns:IB,multiply:dB,range:CH,schur:ZU,subset:VV,subtract:aV,transpose:xB,typed:$}),$U=EM({matrix:lB,multiply:dB,sylvester:QU,transpose:xB,typed:$})})),tW,nW,rW,iW,aW,oW,sW,cW,lW,uW,dW,fW,pW,mW,hW,gW,_W,vW,yW,bW,xW,SW,CW,wW,TW,EW,DW,OW,kW,AW,jW,MW,NW,PW,FW,IW,LW,Swe=e((()=>{Bn(),ou(),mR(),eW(),qj(),tW={},nW={},rW={},iW=Vw({mathWithTransform:nW}),aW=NT({Node:iW}),oW=RT({Node:iW}),sW=VT({Node:iW}),cW=qT({Node:iW}),lW=Zw({Node:iW}),uW=lT({Node:iW,ResultSet:AR}),dW=fT({Node:iW}),fW=WT({Node:iW}),pW=oF({classes:rW}),mW=oD({math:tW,typed:$}),hW=DT({Node:iW,typed:$}),gW=$j({Chain:mW,typed:$}),_W=wT({Node:iW,isBounded:xz}),vW=AT({Node:iW,size:Hz}),yW=Jw({Node:iW,subset:VV}),bW=oT({matrix:lB,Node:iW,subset:VV}),xW=XT({Unit:OH,Node:iW,math:tW}),SW=$T({Node:iW,SymbolNode:xW,math:tW}),CW=nE({AccessorNode:yW,ArrayNode:lW,AssignmentNode:bW,BlockNode:uW,ConditionalNode:dW,ConstantNode:_W,FunctionAssignmentNode:hW,FunctionNode:SW,IndexNode:vW,ObjectNode:aW,OperatorNode:oW,ParenthesisNode:sW,RangeNode:fW,RelationalNode:cW,SymbolNode:xW,config:J,numeric:tV,typed:$}),wW=HP({ConstantNode:_W,FunctionNode:SW,OperatorNode:oW,ParenthesisNode:sW,parse:CW,typed:$}),TW=IP({bignumber:eB,fraction:jB,AccessorNode:yW,ArrayNode:lW,ConstantNode:_W,FunctionNode:SW,IndexNode:vW,ObjectNode:aW,OperatorNode:oW,SymbolNode:xW,config:J,isBounded:xz,mathWithTransform:nW,matrix:lB,typed:$}),EW=aE({parse:CW,typed:$}),DW=cE({parse:CW,typed:$}),OW=rD({evaluate:DW}),kW=dE({evaluate:DW,parse:CW}),AW=zP({AccessorNode:yW,ArrayNode:lW,ConstantNode:_W,FunctionNode:SW,IndexNode:vW,ObjectNode:aW,OperatorNode:oW,ParenthesisNode:sW,SymbolNode:xW,add:lV,divide:pU,equal:AB,isZero:cB,multiply:dB,parse:CW,pow:iH,subtract:aV,typed:$}),jW=Xj({Help:OW,mathWithTransform:nW,typed:$}),MW=NP({AccessorNode:yW,ArrayNode:lW,ConstantNode:_W,FunctionNode:SW,IndexNode:vW,ObjectNode:aW,OperatorNode:oW,ParenthesisNode:sW,SymbolNode:xW,equal:AB,parse:CW,replacer:BR,resolve:wW,simplifyConstant:TW,simplifyCore:AW,typed:$}),NW=GP({OperatorNode:oW,parse:CW,simplify:MW,typed:$}),PW=JP({ConstantNode:_W,FunctionNode:SW,OperatorNode:oW,ParenthesisNode:sW,SymbolNode:xW,config:J,equal:AB,isZero:cB,numeric:tV,parse:CW,simplify:MW,typed:$}),FW=mE({Parser:kW,typed:$}),IW=SP({parse:CW,typed:$}),LW=ZP({bignumber:eB,fraction:jB,AccessorNode:yW,ArrayNode:lW,ConstantNode:_W,FunctionNode:SW,IndexNode:vW,ObjectNode:aW,OperatorNode:oW,ParenthesisNode:sW,SymbolNode:xW,add:lV,config:J,divide:pU,equal:AB,isZero:cB,mathWithTransform:nW,matrix:lB,multiply:dB,parse:CW,pow:iH,simplify:MW,simplifyConstant:TW,simplifyCore:AW,subtract:aV,typed:$}),zn(tW,{e:_R,false:vR,fineStructure:yR,i:xR,Infinity:SR,LN10:CR,LOG10E:wR,NaN:ER,null:DR,phi:OR,SQRT1_2:jR,sackurTetrode:MR,tau:NR,true:PR,E:_R,version:FR,efimovFactor:LR,LN2:RR,pi:zR,replacer:BR,reviver:pW,SQRT2:VR,typed:$,PI:zR,weakMixingAngle:HR,abs:UR,acos:WR,acot:GR,acsc:KR,addScalar:qR,arg:JR,asech:YR,asinh:XR,atan:ZR,atanh:QR,bigint:$R,bitNot:ez,boolean:tz,clone:nz,combinations:rz,complex:iz,conj:az,cos:oz,cot:sz,csc:cz,cube:lz,equalScalar:uz,erf:dz,exp:fz,expm1:pz,filter:mz,flatten:hz,forEach:gz,format:_z,getMatrixDataType:vz,hex:yz,im:bz,isBounded:xz,isNaN:Sz,isNumeric:Cz,isPrime:wz,LOG2E:Tz,lgamma:Ez,log10:Dz,log2:Oz,map:kz,mode:Az,multiplyScalar:jz,not:Mz,number:Nz,oct:Pz,pickRandom:Fz,print:Iz,random:Lz,re:Rz,sec:zz,sign:Bz,sin:Vz,size:Hz,splitUnit:Wz,square:Gz,string:Kz,
2633subtractScalar:qz,tan:Jz,toBest:Yz,typeOf:Xz,acosh:Zz,acsch:Qz,asec:$z,bignumber:eB,chain:gW,combinationsWithRep:tB,cosh:nB,csch:rB,dot:iB,hasNumericValue:aB,isFinite:oB,isNegative:sB,isZero:cB,matrix:lB,matrixFromFunction:uB,multiply:dB,ones:fB,randomInt:pB,resize:mB,sech:hB,sinh:gB,sparse:_B,sqrt:vB,squeeze:yB,tanh:bB,transpose:xB,xgcd:SB,zeros:CB,acoth:wB,asin:TB,bin:EB,coth:DB,ctranspose:OB,diag:kB,equal:AB,fraction:jB,identity:MB,isInteger:NB,kron:PB,mapSlices:FB,matrixFromColumns:IB,num:LB,reshape:RB,round:zB,unaryMinus:BB,bernoulli:VB,cbrt:HB,concat:UB,deepEqual:WB,dotMultiply:GB,floor:KB,gcd:qB,isPositive:JB,larger:YB,lcm:XB,leftShift:ZB,mod:QB,nthRoot:$B,nullish:eV,numeric:tV,prod:nV,rightArithShift:rV,smaller:iV,subtract:aV,to:oV,unaryPlus:sV,xor:cV,add:lV,atan2:uV,bitAnd:dV,bitOr:fV,bitXor:pV,ceil:mV,compare:hV,compareText:gV,composition:_V,count:vV,cross:yV,diff:bV,divideScalar:xV,equalText:SV,fix:wV,hypot:TV,intersect:OV,invmod:kV,largerEq:AV,log:jV,lsolve:MV,matrixFromRows:NV,min:PV,nthRoots:FV,partitionSelect:IV,qr:LV,rightLogShift:RV,slu:zV,subset:VV,sum:HV,trace:UV,usolve:WV,zpk2tf:GV,catalan:KV,compareNatural:qV,cumsum:JV,det:YV,dotDivide:XV,index:ZV,inv:QV,log1p:$V,lsolveAll:eH,max:tH,or:nH,pinv:rH,pow:iH,setCartesian:aH,setDistinct:oH,setIsSubset:sH,setPowerset:cH,smallerEq:lH,sort:uH,sqrtm:dH,unequal:fH,usolveAll:pH,and:mH,den:hH,distance:gH,dotPow:_H,expm:vH,fft:yH,gamma:bH,ifft:xH,lup:SH,range:CH,row:wH,setDifference:TH,setMultiplicity:EH,setSymDifference:DH,vacuumImpedance:kH,wienDisplacement:AH,atomicMass:jH,bohrMagneton:MH,boltzmann:NH,column:PH,conductanceQuantum:FH,coulomb:IH,createUnit:LH,deuteronMass:RH,eigs:zH,electronMass:BH,factorial:VH,fermiCoupling:HH,gasConstant:UH,gravity:WH,klitzing:GH,loschmidt:KH,magneticConstant:qH,molarMass:JH,molarPlanckConstant:YH,neutronMass:XH,nuclearMagneton:ZH,permutations:QH,planckConstant:$H,planckMass:eU,planckTime:tU,protonMass:nU,quantumOfCirculation:rU,reducedPlanckConstant:iU,secondRadiation:aU,setSize:oU,speedOfLight:sU,stefanBoltzmann:cU,thomsonCrossSection:lU,avogadro:uU,bohrRadius:dU,coulombConstant:fU,divide:pU,elementaryCharge:mU,faraday:hU,freqz:gU,gravitationConstant:_U,inverseConductanceQuantum:vU,lusolve:yU,magneticFluxQuantum:bU,molarMassC12:xU,multinomial:SU,planckCharge:CU,planckTemperature:wU,quantileSeq:TU,rydberg:EU,setIntersect:DU,solveODE:OU,stirlingS2:kU,unit:AU,bellNumbers:jU,electricConstant:MU,firstRadiation:NU,hartreeEnergy:PU,kldivergence:FU,mean:IU,molarVolume:LU,planckLength:RU,setUnion:zU,variance:BU,classicalElectronRadius:VU,corr:HU,median:UU,parse:CW,polynomialRoot:WU,resolve:wW,simplifyConstant:TW,std:GU,zeta:KU,compile:EW,evaluate:DW,mad:qU,simplifyCore:AW,help:jW,norm:JU,rotationMatrix:YU,simplify:MW,symbolicEqual:NW,derivative:PW,parser:FW,rotate:XU,leafCount:IW,rationalize:LW,schur:ZU,sylvester:QU,lyap:$U,config:J}),zn(nW,tW,{map:nL({typed:$}),filter:qI({typed:$}),forEach:XI({typed:$}),mapSlices:NI({isInteger:NB,typed:$}),or:QL({DenseMatrix:IR,concat:UB,equalScalar:uz,matrix:lB,typed:$}),and:YL({add:lV,concat:UB,equalScalar:uz,matrix:lB,not:Mz,typed:$,zeros:CB}),cumsum:BL({add:lV,typed:$,unaryPlus:sV}),max:sL({config:J,isNaN:Sz,larger:YB,numeric:tV,typed:$}),nullish:tR({deepEqual:WB,flatten:hz,matrix:lB,size:Hz,typed:$}),print:KL({add:lV,matrix:lB,typed:$,zeros:CB}),bitAnd:iR({add:lV,concat:UB,equalScalar:uz,matrix:lB,not:Mz,typed:$,zeros:CB}),concat:TL({isInteger:NB,matrix:lB,typed:$}),diff:OL({bignumber:eB,matrix:lB,number:Nz,subtract:aV,typed:$}),min:pL({config:J,isNaN:Sz,numeric:tV,smaller:iV,typed:$}),subset:SL({add:lV,matrix:lB,typed:$,zeros:CB}),bitOr:sR({DenseMatrix:IR,concat:UB,equalScalar:uz,matrix:lB,typed:$}),sum:PL({add:lV,config:J,numeric:tV,typed:$}),index:$I({Index:DV,getMatrixDataType:vz}),row:yL({Index:DV,matrix:lB,range:CH,typed:$}),column:II({Index:DV,matrix:lB,range:CH,typed:$}),mean:uL({add:lV,divide:pU,typed:$}),range:gL({bignumber:eB,matrix:lB,add:lV,config:J,equal:AB,isPositive:JB,isZero:cB,larger:YB,largerEq:AV,smaller:iV,smallerEq:lH,typed:$}),variance:UL({add:lV,divide:pU,isNaN:Sz,mapSlices:FB,multiply:dB,subtract:aV,typed:$}),quantileSeq:LL({add:lV,bignumber:eB,compare:hV,divide:pU,isInteger:NB,larger:YB,mapSlices:FB,multiply:dB,partitionSelect:IV,smaller:iV,smallerEq:lH,subtract:aV,typed:$}),std:jL({map:kz,sqrt:vB,typed:$,variance:BU})}),zn(rW,{BigNumber:hR,Complex:gR,Fraction:bR,Matrix:TR,Node:iW,ObjectNode:aW,OperatorNode:oW,ParenthesisNode:sW,Range:kR,RelationalNode:cW,ResultSet:AR,ArrayNode:lW,BlockNode:uW,ConditionalNode:dW,DenseMatrix:IR,RangeNode:fW,Chain:mW,FunctionAssignmentNode:hW,SparseMatrix:Uz,ConstantNode:_W,IndexNode:vW,FibonacciHeap:CV,ImmutableDenseMatrix:EV,Index:DV,Spa:BV,AccessorNode:yW,AssignmentNode:bW,Unit:OH,SymbolNode:xW,FunctionNode:SW,Help:OW,Parser:kW}),mW.createProxy(tW)})),Cwe=e((()=>{Ql()})),RW,wwe=e((()=>{mR(),RW=xwe})),Twe=e((()=>{mR(),wwe()})),Ewe=r(((e,t)=>{function n(){}n.prototype={on:function(e,t,n){var r=this.e||={};return(r[e]||(r[e]=[])).push({fn:t,ctx:n}),this},once:function(e,t,n){var r=this;function i(){r.off(e,i),t.apply(n,arguments)}return i._=t,this.on(e,i,n)}
2633,emit:function(e){for(var t=[].slice.call(arguments,1),n=((this.e||={})[e]||[]).slice(),r=0,i=n.length;r<i;r++)n[r].fn.apply(n[r].ctx,t);return this},off:function(e,t){var n=this.e||={},r=n[e],i=[];if(r&&t)for(var a=0,o=r.length;a<o;a++)r[a].fn!==t&&r[a].fn._!==t&&i.push(r[a]);return i.length?n[e]=i:delete n[e],this}},t.exports=n,t.exports.TinyEmitter=n}));function Dwe(e){var t=new zW.default;return e.on=t.on.bind(t),e.off=t.off.bind(t),e.once=t.once.bind(t),e.emit=t.emit.bind(t),e}var zW,Owe=e((()=>{zW=t(Ewe(),1)}));function kwe(e,t,n,r){function i(e,t){var n=arguments.length;if(n!==1&&n!==2)throw new xv(`import`,n,1,2);t||={};function r(e,n,i){if(Array.isArray(n))n.forEach(t=>r(e,t));else if(Fl(n)||d(n))for(var a in n)nu(n,a)&&r(e,n[a],a);else if(cu(n)||i!==void 0){var o=cu(n)?h(n)?n.fn+`.transform`:n.fn:i;if(nu(e,o)&&e[o]!==n&&!t.silent)throw Error(`Cannot import "`+o+`" twice`);e[o]=n}else if(!t.silent)throw TypeError(`Factory, Object, or Array expected`)}var i={};for(var o in r(i,e),i)if(nu(i,o)){var s=i[o];if(cu(s))l(s,t);else if(u(s))a(o,s,t);else if(!t.silent)throw TypeError(`Factory, Object, or Array expected`)}}function a(t,i,a){if(a.wrap&&typeof i==`function`&&(i=c(i)),f(i)&&(i=e(t,{[i.signature]:i})),e.isTypedFunction(n[t])&&e.isTypedFunction(i)){i=a.override?e(t,i.signatures):e(n[t],i),n[t]=i,delete r[t],o(t,i),n.emit(`import`,t,function(){return i});return}var s=n[t]!==void 0,l=n.Unit?.isValuelessUnit(t);if(!s&&!l||a.override){n[t]=i,delete r[t],o(t,i),n.emit(`import`,t,function(){return i});return}if(!a.silent)throw Error(`Cannot import "`+t+`": already exists`)}function o(e,t){t&&typeof t.transform==`function`?(n.expression.transform[e]=t.transform,p(e)&&(n.expression.mathWithTransform[e]=t.transform)):(delete n.expression.transform[e],p(e)&&(n.expression.mathWithTransform[e]=t))}function s(e){delete n.expression.transform[e],p(e)?n.expression.mathWithTransform[e]=n[e]:delete n.expression.mathWithTransform[e]}function c(e){var t=function(){for(var t=[],r=0,i=arguments.length;r<i;r++){var a=arguments[r];t[r]=a&&a.valueOf()}return e.apply(n,t)};return e.transform&&(t.transform=e.transform),t}function l(t,i){var a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:t.fn;if(a.includes(`.`))throw Error(`Factory name should not contain a nested path. Name: `+JSON.stringify(a));var o=h(t)?n.expression.transform:n,c=a in n.expression.transform,l=nu(o,a)?o[a]:void 0,u=function(){var r={};t.dependencies.map(dce).forEach(e=>{if(e.includes(`.`))throw Error(`Factory dependency should not contain a nested path. Name: `+JSON.stringify(e));e===`math`?r.math=n:e===`mathWithTransform`?r.mathWithTransform=n.expression.mathWithTransform:e===`classes`?r.classes=n:r[e]=n[e]});var o=t(r);if(o&&typeof o.transform==`function`)throw Error(`Transforms cannot be attached to factory functions. Please create a separate function for it with export const path = "expression.transform"`);if(l===void 0||i.override)return o;if(e.isTypedFunction(l)&&e.isTypedFunction(o))return e(l,o);if(i.silent)return l;throw Error(`Cannot import "`+a+`": already exists`)},d=t.meta?.formerly??``,f=h(t)||m(t),p=n.expression.mathWithTransform;!t.meta||t.meta.lazy!==!1?(tu(o,a,u),d&&tu(o,d,u),l&&c?(s(a),d&&s(d)):f&&(tu(p,a,()=>o[a]),d&&tu(p,d,()=>o[a]))):(o[a]=u(),d&&(o[d]=o[a]),l&&c?(s(a),d&&s(d)):f&&(tu(p,a,()=>o[a]),d&&tu(p,d,()=>o[a]))),r[a]=t,n.emit(`import`,a,u)}function u(e){return typeof e==`function`||typeof e==`number`||typeof e==`string`||typeof e==`boolean`||e===null||Tl(e)||Cl(e)||xl(e)||wl(e)||Dl(e)||Array.isArray(e)}function d(e){return typeof e==`object`&&e[Symbol.toStringTag]===`Module`}function f(e){return typeof e==`function`&&typeof e.signature==`string`}function p(e){return!nu(g,e)}function m(e){return!e.fn.includes(`.`)&&!nu(g,e.fn)&&(!e.meta||!e.meta.isClass)}function h(e){return e!==void 0&&e.meta!==void 0&&e.meta.isTransformFunction===!0||!1}var g={expression:!0,type:!0,docs:!0,error:!0,json:!0,chain:!0};return i}var Awe=e((()=>{Ql(),X(),ru(),Sv()}));function BW(e,t){var n=zn({},cl,t);if(typeof Object.create!=`function`)throw Error(`ES5 not supported by this JavaScript engine. Please load the es5-shim and es5-sham library for compatibility.`);var r=Dwe({isNumber:bl,isComplex:Cl,isBigNumber:xl,isBigInt:Sl,isFraction:wl,isUnit:Tl,isString:El,isArray:Zl,isMatrix:Dl,isCollection:Ol,isDenseMatrix:kl,isSparseMatrix:Al,isRange:jl,isIndex:Ml,isBoolean:Bse,isResultSet:Vse,isHelp:Nl,isFunction:Pl,isDate:Hse,isRegExp:Use,isObject:Fl,isMap:Il,isPartitionedMap:Wse,isObjectWrappingMap:Gse,isNull:Kse,isUndefined:qse,isAccessorNode:Ll,isArrayNode:Rl,isAssignmentNode:Jse,isBlockNode:Yse,isConditionalNode:Xse,isConstantNode:zl,isFunctionAssignmentNode:Vl,isFunctionNode:Hl,isIndexNode:Ul,isNode:Wl,isObjectNode:Gl,isOperatorNode:Kl,isParenthesisNode:ql,isRangeNode:Zse,isRelationalNode:Qse,isSymbolNode:Jl,isChain:Yl});r.config=oce(n,r.emit),r.expression={transform:{},mathWithTransform:{config:r.config}};var i=[],a=[];function o(e){if(cu(e))return e(r);var t=e[Object.keys(e)[0]];if(cu(t))return t(r);if(!ice(e))throw console.warn("Factory object with properties `type`, `name`, and `factory` expected",e),Error("Factory object with properties `type`, `name`, and `factory` expected");var s=i.indexOf(e),c;return s===-1?(c=e.math===!0?e.factory(r.type,n,o,r.typed,r):e.factory(r.type,n,o,r.typed),i.push(e),a.push(c)):c=a[s],c}var s={};function c(){var e=[...arguments];return r.typed.apply(r.typed,e)}c.isTypedFunction=VW.default.isTypedFunction;var l=kwe(c,o,r,s);return r.import=l,r.on(`config`,()=>
vendor: 23,151 bytes, line 2633
2633{Object.values(s).forEach(e=>{e&&e.meta&&e.meta.recreateOnConfigChange&&l(e,{override:!0})})}),r.create=BW.bind(null,e),r.factory=Y,r.import(Object.values(nce(e))),r.ArgumentsError=xv,r.DimensionError=Uf,r.IndexError=Gf,r}var VW,jwe=e((()=>{Bn(),VW=t(su(),1),Sv(),Wf(),Kf(),X(),Ql(),ru(),Owe(),ll(),cce(),Awe()})),Mwe=e((()=>{ou(),eW(),Swe(),Cwe(),Kf(),Wf(),Sv(),Twe(),mR(),jwe(),X()})),Nwe=e((()=>{Mwe()})),HW,UW,WW,GW,KW,qW,JW,YW,XW,ZW,QW,Pwe=e((()=>{HW=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),UW=HW((e,t)=>{var n=(function(e){var t=1e7,r=7,i=9007199254740992,a=p(i),o=`0123456789abcdefghijklmnopqrstuvwxyz`,s=typeof BigInt==`function`;function c(e,t,n,r){return typeof e>`u`?c[0]:typeof t<`u`?+t==10&&!n?ge(e):le(e,t,n,r):ge(e)}function l(e,t){this.value=e,this.sign=t,this.isSmall=!1}l.prototype=Object.create(c.prototype);function u(e){this.value=e,this.sign=e<0,this.isSmall=!0}u.prototype=Object.create(c.prototype);function d(e){this.value=e}d.prototype=Object.create(c.prototype);function f(e){return-i<e&&e<i}function p(e){return e<1e7?[e]:e<0x5af3107a4000?[e%1e7,Math.floor(e/1e7)]:[e%1e7,Math.floor(e/1e7)%1e7,Math.floor(e/0x5af3107a4000)]}function m(e){h(e);var n=e.length;if(n<4&&F(e,a)<0)switch(n){case 0:return 0;case 1:return e[0];case 2:return e[0]+e[1]*t;default:return e[0]+(e[1]+e[2]*t)*t}return e}function h(e){for(var t=e.length;e[--t]===0;);e.length=t+1}function g(e){for(var t=Array(e),n=-1;++n<e;)t[n]=0;return t}function _(e){return e>0?Math.floor(e):Math.ceil(e)}function v(e,n){var r=e.length,i=n.length,a=Array(r),o=0,s=t,c,l;for(l=0;l<i;l++)c=e[l]+n[l]+o,o=+(c>=s),a[l]=c-o*s;for(;l<r;)c=e[l]+o,o=+(c===s),a[l++]=c-o*s;return o>0&&a.push(o),a}function y(e,t){return e.length>=t.length?v(e,t):v(t,e)}function b(e,n){var r=e.length,i=Array(r),a=t,o,s;for(s=0;s<r;s++)o=e[s]-a+n,n=Math.floor(o/a),i[s]=o-n*a,n+=1;for(;n>0;)i[s++]=n%a,n=Math.floor(n/a);return i}l.prototype.add=function(e){var t=ge(e);if(this.sign!==t.sign)return this.subtract(t.negate());var n=this.value,r=t.value;return t.isSmall?new l(b(n,Math.abs(r)),this.sign):new l(y(n,r),this.sign)},l.prototype.plus=l.prototype.add,u.prototype.add=function(e){var t=ge(e),n=this.value;if(n<0!==t.sign)return this.subtract(t.negate());var r=t.value;if(t.isSmall){if(f(n+r))return new u(n+r);r=p(Math.abs(r))}return new l(b(r,Math.abs(n)),n<0)},u.prototype.plus=u.prototype.add,d.prototype.add=function(e){return new d(this.value+ge(e).value)},d.prototype.plus=d.prototype.add;function x(e,n){var r=e.length,i=n.length,a=Array(r),o=0,s=t,c,l;for(c=0;c<i;c++)l=e[c]-o-n[c],l<0?(l+=s,o=1):o=0,a[c]=l;for(c=i;c<r;c++){if(l=e[c]-o,l<0)l+=s;else{a[c++]=l;break}a[c]=l}for(;c<r;c++)a[c]=e[c];return h(a),a}function S(e,t,n){var r;return F(e,t)>=0?r=x(e,t):(r=x(t,e),n=!n),r=m(r),typeof r==`number`?(n&&(r=-r),new u(r)):new l(r,n)}function C(e,n,r){var i=e.length,a=Array(i),o=-n,s=t,c,d;for(c=0;c<i;c++)d=e[c]+o,o=Math.floor(d/s),d%=s,a[c]=d<0?d+s:d;return a=m(a),typeof a==`number`?(r&&(a=-a),new u(a)):new l(a,r)}l.prototype.subtract=function(e){var t=ge(e);if(this.sign!==t.sign)return this.add(t.negate());var n=this.value,r=t.value;return t.isSmall?C(n,Math.abs(r),this.sign):S(n,r,this.sign)},l.prototype.minus=l.prototype.subtract,u.prototype.subtract=function(e){var t=ge(e),n=this.value;if(n<0!==t.sign)return this.add(t.negate());var r=t.value;return t.isSmall?new u(n-r):C(r,Math.abs(n),n>=0)},u.prototype.minus=u.prototype.subtract,d.prototype.subtract=function(e){return new d(this.value-ge(e).value)},d.prototype.minus=d.prototype.subtract,l.prototype.negate=function(){return new l(this.value,!this.sign)},u.prototype.negate=function(){var e=this.sign,t=new u(-this.value);return t.sign=!e,t},d.prototype.negate=function(){return new d(-this.value)},l.prototype.abs=function(){return new l(this.value,!1)},u.prototype.abs=function(){return new u(Math.abs(this.value))},d.prototype.abs=function(){return new d(this.value>=0?this.value:-this.value)};function w(e,n){var r=e.length,i=n.length,a=g(r+i),o=t,s,c,l,u,d;for(l=0;l<r;++l){u=e[l];for(var f=0;f<i;++f)d=n[f],s=u*d+a[l+f],c=Math.floor(s/o),a[l+f]=s-c*o,a[l+f+1]+=c}return h(a),a}function T(e,n){var r=e.length,i=Array(r),a=t,o=0,s,c;for(c=0;c<r;c++)s=e[c]*n+o,o=Math.floor(s/a),i[c]=s-o*a;for(;o>0;)i[c++]=o%a,o=Math.floor(o/a);return i}function E(e,t){for(var n=[];t-- >0;)n.push(0);return n.concat(e)}function D(e,t){var n=Math.max(e.length,t.length);if(n<=30)return w(e,t);n=Math.ceil(n/2);var r=e.slice(n),i=e.slice(0,n),a=t.slice(n),o=t.slice(0,n),s=D(i,o),c=D(r,a),l=y(y(s,E(x(x(D(y(i,r),y(o,a)),s),c),n)),E(c,2*n));return h(l),l}function O(e,t){return-.012*e-.012*t+15e-6*e*t>0}l.prototype.multiply=function(e){var n=ge(e),r=this.value,i=n.value,a=this.sign!==n.sign,o;if(n.isSmall){if(i===0)return c[0];if(i===1)return this;if(i===-1)return this.negate();if(o=Math.abs(i),o<t)return new l(T(r,o),a);i=p(o)}return O(r.length,i.length)?new l(D(r,i),a):new l(w(r,i),a)},l.prototype.times=l.prototype.multiply;function k(e,n,r){return e<t?new l(T(n,e),r):new l(w(n,p(e)),r)}u.prototype._multiplyBySmall=function(e){return f(e.value*this.value)?new u(e.value*this.value):k(Math.abs(e.value),p(Math.abs(this.value)),this.sign!==e.sign)},l.prototype._multiplyBySmall=function(e){return e.value===0?c[0]:e.value===1?this:e.value===-1?this.negate():k(Math.abs(e.value),this.value,this.sign!==e.sign)},u.prototype.multiply=function(e){return ge(e)._multiplyBySmall(this)},u.prototype.times=u.prototype.multiply,d.prototype.multiply=function(e){return new d(this.value*ge(e).value)},d.prototype.times=d.prototype.multiply;function A(e){var n=e.length,r=g(n+n),i=t,a,o,s,c,l;for(s=0;s<n;s++){c=e[s],o=0-c*c;for(var u=s;u<n;u++)l=e[u],a=c*l*2+r[s+u]+o,o=Math.floor(a/i),r[s+u]=a-o*i;r[s+n]=o}return h(r),r}l.prototype.square=function(){return new l(A(this.value),!1)},u.prototype.square=function(){var e=this.value*this.value;return f(e)?new u(e):new l(A(p(Math.abs(this.value))),!1)},d.prototype.square=function(e){return new d(this.value*this.value)};function j(e,n){var r=e.length,i=n.length,a=t,o=g(n.length),s=n[i-1],c=Math.ceil(a/(2*s)),l=T(e,c),u=T(n,c),d,f,p,h,_,v,y;for(l.length<=r&&l.push(0),u.push(0),s=u[i-1],f=r-i;f>=0;f--){for(d=a-1,l[f+i]!==s&&(d=Math.floor((l[f+i]*a+l[f+i-1])/s)),p=0,h=0,v=u.length,_=0;_<v;_++)p+=d*u[_],y=Math.floor(p/a),h+=l[f+_]-(p-y*a),p=y,h<0?(l[f+_]=h+a,h=-1):(l[f+_]=h,h=0);for(;h!==0;){for(--d,p=0,_=0;_<v;_++)p+=l[f+_]-a+u[_],p<0?(l[f+_]=p+a,p=0):(l[f+_]=p,p=1);h+=p}o[f]=d}return l=N(l,c)[0],[m(o),m(l)]}function M(e,n){for(var r=e.length,i=n.length,a=[],o=[],s=t,c,l,u,d,f;r;){if(o.unshift(e[--r]),h(o),F(o,n)<0){a.push(0);continue}l=o.length,u=o[l-1]*s+o[l-2],d=n[i-1]*s+n[i-2],l>i&&(u=(u+1)*s),c=Math.ceil(u/d);do{if(f=T(n,c),F(f,o)<=0)break;c--}while(c);a.push(c),o=x(o,f)}return a.reverse(),[m(a),m(o)]}function N(e,n){var r=e.length,i=g(r),a=t,o,s,c,l;for(c=0,o=r-1;o>=0;--o)l=c*a+e[o],s=_(l/n),c=l-s*n,i[o]=s|0;return[i,c|0]}function P(e,n){var r,i=ge(n);if(s)return[new d(e.value/i.value),new d(e.value%i.value)];var a=e.value,o=i.value,f;if(o===0)throw Error(`Cannot divide by zero`);if(e.isSmall)return i.isSmall?[new u(_(a/o)),new u(a%o)]:[c[0],e];if(i.isSmall){if(o===1)return[e,c[0]];if(o==-1)return[e.negate(),c[0]];var h=Math.abs(o);if(h<t){r=N(a,h),f=m(r[0]);var g=r[1];return e.sign&&(g=-g),typeof f==`number`?(e.sign!==i.sign&&(f=-f),[new u(f),new u(g)]):[new l(f,e.sign!==i.sign),new u(g)]}o=p(h)}var v=F(a,o);if(v===-1)return[c[0],e];if(v===0)return[c[e.sign===i.sign?1:-1],c[0]];r=a.length+o.length<=200?j(a,o):M(a,o),f=r[0];var y=e.sign!==i.sign,b=r[1],x=e.sign;return typeof f==`number`?(y&&(f=-f),f=new u(f)):f=new l(f,y),typeof b==`number`?(x&&(b=-b),b=new u(b)):b=new l(b,x),[f,b]}l.prototype.divmod=function(e){var t=P(this,e);return{quotient:t[0],remainder:t[1]}},d.prototype.divmod=u.prototype.divmod=l.prototype.divmod,l.prototype.divide=function(e){return P(this,e)[0]},d.prototype.over=d.prototype.divide=function(e){return new d(this.value/ge(e).value)},u.prototype.over=u.prototype.divide=l.prototype.over=l.prototype.divide,l.prototype.mod=function(e){return P(this,e)[1]},d.prototype.mod=d.prototype.remainder=function(e){return new d(this.value%ge(e).value)},u.prototype.remainder=u.prototype.mod=l.prototype.remainder=l.prototype.mod,l.prototype.pow=function(e){var t=ge(e),n=this.value,r=t.value,i,a,o;if(r===0)return c[1];if(n===0)return c[0];if(n===1)return c[1];if(n===-1)return t.isEven()?c[1]:c[-1];if(t.sign)return c[0];if(!t.isSmall)throw Error(`The exponent `+t.toString()+` is too large.`);if(this.isSmall&&f(i=n**+r))return new u(_(i));for(a=this,o=c[1];r&!0&&(o=o.times(a),--r),r!==0;)r/=2,a=a.square();return o},u.prototype.pow=l.prototype.pow,d.prototype.pow=function(e){var t=ge(e),n=this.value,r=t.value,i=BigInt(0),a=BigInt(1),o=BigInt(2);if(r===i)return c[1];if(n===i)return c[0];if(n===a)return c[1];if(n===BigInt(-1))return t.isEven()?c[1]:c[-1];if(t.isNegative())return new d(i);for(var s=this,l=c[1];(r&a)===a&&(l=l.times(s),--r),r!==i;)r/=o,s=s.square();return l},l.prototype.modPow=function(e,t){if(e=ge(e),t=ge(t),t.isZero())throw Error(`Cannot take modPow with modulus 0`);var n=c[1],r=this.mod(t);for(e.isNegative()&&(e=e.multiply(c[-1]),r=r.modInv(t));e.isPositive();){if(r.isZero())return c[0];e.isOdd()&&(n=n.multiply(r).mod(t)),e=e.divide(2),r=r.square().mod(t)}return n},d.prototype.modPow=u.prototype.modPow=l.prototype.modPow;function F(e,t){if(e.length!==t.length)return e.length>t.length?1:-1;for(var n=e.length-1;n>=0;n--)if(e[n]!==t[n])return e[n]>t[n]?1:-1;return 0}l.prototype.compareAbs=function(e){var t=ge(e),n=this.value,r=t.value;return t.isSmall?1:F(n,r)},u.prototype.compareAbs=function(e){var t=ge(e),n=Math.abs(this.value),r=t.value;return t.isSmall?(r=Math.abs(r),n===r?0:n>r?1:-1):-1},d.prototype.compareAbs=function(e){var t=this.value,n=ge(e).value;return t=t>=0?t:-t,n=n>=0?n:-n,t===n?0:t>n?1:-1},l.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=ge(e),n=this.value,r=t.value;return this.sign===t.sign?t.isSmall?this.sign?-1:1:F(n,r)*(this.sign?-1:1):t.sign?1:-1},l.prototype.compareTo=l.prototype.compare,u.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=ge(e),n=this.value,r=t.value;return t.isSmall?n==r?0:n>r?1:-1:n<0===t.sign?n<0?1:-1:n<0?-1:1},u.prototype.compareTo=u.prototype.compare,d.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=this.value,n=ge(e).value;return t===n?0:t>n?1:-1},d.prototype.compareTo=d.prototype.compare,l.prototype.equals=function(e){return this.compare(e)===0},d.prototype.eq=d.prototype.equals=u.prototype.eq=u.prototype.equals=l.prototype.eq=l.prototype.equals,l.prototype.notEquals=function(e){return this.compare(e)!==0},d.prototype.neq=d.prototype.notEquals=u.prototype.neq=u.prototype.notEquals=l.prototype.neq=l.prototype.notEquals,l.prototype.greater=function(e){return this.compare(e)>0},d.prototype.gt=d.prototype.greater=u.prototype.gt=u.prototype.greater=l.prototype.gt=l.prototype.greater,l.prototype.lesser=function(e){return this.compare(e)<0},d.prototype.lt=d.prototype.lesser=u.prototype.lt=u.prototype.lesser=l.prototype.lt=l.prototype.lesser,l.prototype.greaterOrEquals=function(e){return this.compare(e)>=0},d.prototype.geq=d.prototype.greaterOrEquals=u.prototype.geq=u.prototype.greaterOrEquals=l.prototype.geq=l.prototype.greaterOrEquals,l.prototype.lesserOrEquals=function(e){return this.compare(e)<=0},d.prototype.leq=d.prototype.lesserOrEquals=u.prototype.leq=u.prototype.lesserOrEquals=l.prototype.leq=l.prototype.lesserOrEquals,l.prototype.isEven=function(){return(this.value[0]&1)==0},u.prototype.isEven=function(){return(this.value&1)==0},d.prototype.isEven=function(){return(this.value&BigInt(1))===BigInt(0)},l.prototype.isOdd=function(){return(this.value[0]&1)==1},u.prototype.isOdd=function(){return(this.value&1)==1},d.prototype.isOdd=function(){return(this.value&BigInt(1))===BigInt(1)},l.prototype.isPositive=function(){return!this.sign},u.prototype.isPositive=function(){return this.value>0},d.prototype.isPositive=u.prototype.isPositive,l.prototype.isNegative=function(){return this.sign},u.prototype.isNegative=function(){return this.value<0},d.prototype.isNegative=u.prototype.isNegative,l.prototype.isUnit=function(){return!1},u.prototype.isUnit=function(){return Math.abs(this.value)===1},d.prototype.isUnit=function(){return this.abs().value===BigInt(1)},l.prototype.isZero=function(){return!1},u.prototype.isZero=function(){return this.value===0},d.prototype.isZero=function(){return this.value===BigInt(0)},l.prototype.isDivisibleBy=function(e){var t=ge(e);return t.isZero()?!1:t.isUnit()?!0:t.compareAbs(2)===0?this.isEven():this.mod(t).isZero()},d.prototype.isDivisibleBy=u.prototype.isDivisibleBy=l.prototype.isDivisibleBy;function I(e){var t=e.abs();if(t.isUnit())return!1;if(t.equals(2)||t.equals(3)||t.equals(5))return!0;if(t.isEven()||t.isDivisibleBy(3)||t.isDivisibleBy(5))return!1;if(t.lesser(49))return!0}function L(e,t){for(var r=e.prev(),i=r,a=0,o,s,c;i.isEven();)i=i.divide(2),a++;e:for(s=0;s<t.length;s++)if(!e.lesser(t[s])&&(c=n(t[s]).modPow(i,e),!(c.isUnit()||c.equals(r)))){for(o=a-1;o!=0;o--){if(c=c.square().mod(e),c.isUnit())return!1;if(c.equals(r))continue e}return!1}return!0}l.prototype.isPrime=function(t){var r=I(this);if(r!==e)return r;var i=this.abs(),a=i.bitLength();if(a<=64)return L(i,[2,3,5,7,11,13,17,19,23,29,31,37]);for(var o=Math.log(2)*a.toJSNumber(),s=Math.ceil(t===!0?2*o**2:o),c=[],l=0;l<s;l++)c.push(n(l+2));return L(i,c)},d.prototype.isPrime=u.prototype.isPrime=l.prototype.isPrime,l.prototype.isProbablePrime=function(t,r){var i=I(this);if(i!==e)return i;for(var a=this.abs(),o=t===e?5:t,s=[],c=0;c<o;c++)s.push(n.randBetween(2,a.minus(2),r));return L(a,s)},d.prototype.isProbablePrime=u.prototype.isProbablePrime=l.prototype.isProbablePrime,l.prototype.modInv=function(e){for(var t=n.zero,r=n.one,i=ge(e),a=this.abs(),o,s,c;!a.isZero();)o=i.divide(a),s=t,c=i,t=r,i=a,r=s.subtract(o.multiply(r)),a=c.subtract(o.multiply(a));if(!i.isUnit())throw Error(this.toString()+` and `+e.toString()+` are not co-prime`);return t.compare(0)===-1&&(t=t.add(e)),this.isNegative()?t.negate():t},d.prototype.modInv=u.prototype.modInv=l.prototype.modInv,l.prototype.next=function(){var e=this.value;return this.sign?C(e,1,this.sign):new l(b(e,1),this.sign)},u.prototype.next=function(){var e=this.value;return e+1<i?new u(e+1):new l(a,!1)},d.prototype.next=function(){return new d(this.value+BigInt(1))},l.prototype.prev=function(){var e=this.value;return this.sign?new l(b(e,1),!0):C(e,1,this.sign)},u.prototype.prev=function(){var e=this.value;return e-1>-i?new u(e-1):new l(a,!0)},d.prototype.prev=function(){return new d(this.value-BigInt(1))};for(var ee=[1];2*ee[ee.length-1]<=t;)ee.push(2*ee[ee.length-1]);var R=ee.length,te=ee[R-1];function z(e){return Math.abs(e)<=t}l.prototype.shiftLeft=function(e){var t=ge(e).toJSNumber();if(!z(t))throw Error(String(t)+` is too large for shifting.`);if(t<0)return this.shiftRight(-t);var n=this;if(n.isZero())return n;for(;t>=R;)n=n.multiply(te),t-=R-1;return n.multiply(ee[t])},d.prototype.shiftLeft=u.prototype.shiftLeft=l.prototype.shiftLeft,l.prototype.shiftRight=function(e){var t,n=ge(e).toJSNumber();if(!z(n))throw Error(String(n)+` is too large for shifting.`);if(n<0)return this.shiftLeft(-n);for(var r=this;n>=R;){if(r.isZero()||r.isNegative()&&r.isUnit())return r;t=P(r,te),r=t[1].isNegative()?t[0].prev():t[0],n-=R-1}return t=P(r,ee[n]),t[1].isNegative()?t[0].prev():t[0]},d.prototype.shiftRight=u.prototype.shiftRight=l.prototype.shiftRight;function ne(e,t,r){t=ge(t);for(var i=e.isNegative(),a=t.isNegative(),o=i?e.not():e,s=a?t.not():t,c=0,l=0,u=null,d=null,f=[];!o.isZero()||!s.isZero();)u=P(o,te),c=u[1].toJSNumber(),i&&(c=te-1-c),d=P(s,te),l=d[1].toJSNumber(),a&&(l=te-1-l),o=u[0],s=d[0],f.push(r(c,l));for(var p=r(+!!i,+!!a)===0?n(0):n(-1),m=f.length-1;m>=0;--m)p=p.multiply(te).add(n(f[m]));return p}l.prototype.not=function(){return this.negate().prev()},d.prototype.not=u.prototype.not=l.prototype.not,l.prototype.and=function(e){return ne(this,e,function(e,t){return e&t})},d.prototype.and=u.prototype.and=l.prototype.and,l.prototype.or=function(e){return ne(this,e,function(e,t){return e|t})},d.prototype.or=u.prototype.or=l.prototype.or,l.prototype.xor=function(e){return ne(this,e,function(e,t){return e^t})},d.prototype.xor=u.prototype.xor=l.prototype.xor;var B=1<<30,V=(t&-t)*(t&-t)|B;function H(e){var n=e.value,r=typeof n==`number`?n|B:typeof n==`bigint`?n|BigInt(B):n[0]+n[1]*t|V;return r&-r}function re(e,t){if(t.compareTo(e)<=0){var r=re(e,t.square(t)),i=r.p,a=r.e,o=i.multiply(t);return o.compareTo(e)<=0?{p:o,e:a*2+1}:{p:i,e:a*2}}return{p:n(1),e:0}}l.prototype.bitLength=function(){var e=this;return e.compareTo(n(0))<0&&(e=e.negate().subtract(n(1))),e.compareTo(n(0))===0?n(0):n(re(e,n(2)).e).add(n(1))},d.prototype.bitLength=u.prototype.bitLength=l.prototype.bitLength;function ie(e,t){return e=ge(e),t=ge(t),e.greater(t)?e:t}function ae(e,t){return e=ge(e),t=ge(t),e.lesser(t)?e:t}function oe(e,t){if(e=ge(e).abs(),t=ge(t).abs(),e.equals(t))return e;if(e.isZero())return t;if(t.isZero())return e;for(var n=c[1],r,i;e.isEven()&&t.isEven();)r=ae(H(e),H(t)),e=e.divide(r),t=t.divide(r),n=n.multiply(r);for(;e.isEven();)e=e.divide(H(e));do{for(;t.isEven();)t=t.divide(H(t));e.greater(t)&&(i=t,t=e,e=i),t=t.subtract(e)}while(!t.isZero());return n.isUnit()?e:e.multiply(n)}function se(e,t){return e=ge(e).abs(),t=ge(t).abs(),e.divide(oe(e,t)).multiply(t)}function ce(e,n,r){e=ge(e),n=ge(n);var i=r||Math.random,a=ae(e,n),o=ie(e,n).subtract(a).add(1);if(o.isSmall)return a.add(Math.floor(i()*o));for(var s=fe(o,t).value,l=[],u=!0,d=0;d<s.length;d++){var f=u?s[d]+(d+1<s.length?s[d+1]/t:0):t,p=_(i()*f);l.push(p),p<s[d]&&(u=!1)}return a.add(c.fromArray(l,t,!1))}var le=function(e,t,n,r){n||=o,e=String(e),r||(e=e.toLowerCase(),n=n.toLowerCase());var i=e.length,a,s=Math.abs(t),c={};for(a=0;a<n.length;a++)c[n[a]]=a;for(a=0;a<i;a++){var l=e[a];if(l!==`-`&&l in c&&c[l]>=s){if(l===`1`&&s===1)continue;throw Error(l+` is not a valid digit in base `+t+`.`)}}t=ge(t);var u=[],d=e[0]===`-`;for(a=+!!d;a<e.length;a++){var l=e[a];if(l in c)u.push(ge(c[l]));else if(l===`<`){var f=a;do a++;while(e[a]!==`>`&&a<e.length);u.push(ge(e.slice(f+1,a)))}else throw Error(l+` is not a valid character`)}return ue(u,t,d)};function ue(e,t,n){var r=c[0],i=c[1],a;for(a=e.length-1;a>=0;a--)r=r.add(e[a].times(i)),i=i.times(t);return n?r.negate():r}function de(e,t){return t||=o,e<t.length?t[e]:`<`+e+`>`}function fe(e,t){if(t=n(t),t.isZero()){if(e.isZero())return{value:[0],isNegative:!1};throw Error(`Cannot convert nonzero numbers to base 0.`)}if(t.equals(-1)){if(e.isZero())return{value:[0],isNegative:!1};if(e.isNegative())return{value:[].concat.apply([],Array.apply(null,Array(-e.toJSNumber())).map(Array.prototype.valueOf,[1,0])),isNegative:!1};var r=Array.apply(null,Array(e.toJSNumber()-1)).map(Array.prototype.valueOf,[0,1]);return r.unshift([1]),{value:[].concat.apply([],r),isNegative:!1}}var i=!1;if(e.isNegative()&&t.isPositive()&&(i=!0,e=e.abs()),t.isUnit())return e.isZero()?{value:[0],isNegative:!1}:{value:Array.apply(null,Array(e.toJSNumber())).map(Number.prototype.valueOf,1),isNegative:i};for(var a=[],o=e,s;o.isNegative()||o.compareAbs(t)>=0;){s=o.divmod(t),o=s.quotient;var c=s.remainder;c.isNegative()&&(c=t.minus(c).abs(),o=o.next()),a.push(c.toJSNumber())}return a.push(o.toJSNumber()),{value:a.reverse(),isNegative:i}}function pe(e,t,n){var r=fe(e,t);return(r.isNegative?`-`:``)+r.value.map(function(e){return de(e,n)}).join(``)}l.prototype.toArray=function(e){return fe(this,e)},u.prototype.toArray=function(e){return fe(this,e)},d.prototype.toArray=function(e){return fe(this,e)},l.prototype.toString=function(t,n){if(t===e&&(t=10),t!==10||n)return pe(this,t,n);for(var r=this.value,i=r.length,a=String(r[--i]),o=`0000000`,s;--i>=0;)s=String(r[i]),a+=o.slice(s.length)+s;return(this.sign?`-`:``)+a},u.prototype.toString=function(t,n){return t===e&&(t=10),t!=10||n?pe(this,t,n):String(this.value)},d.prototype.toString=u.prototype.toString,d.prototype.toJSON=l.prototype.toJSON=u.prototype.toJSON=function(){return this.toString()},l.prototype.valueOf=function(){return parseInt(this.toString(),10)},l.prototype.toJSNumber=l.prototype.valueOf,u.prototype.valueOf=function(){return this.value},u.prototype.toJSNumber=u.prototype.valueOf,d.prototype.valueOf=d.prototype.toJSNumber=function(){return parseInt(this.toString(),10)};function me(e){if(f(+e)){var t=+e;if(t===_(t))return s?new d(BigInt(t)):new u(t);throw Error(`Invalid integer: `+e)}var n=e[0]===`-`;n&&(e=e.slice(1));var i=e.split(/e/i);if(i.length>2)throw Error(`Invalid integer: `+i.join(`e`));if(i.length===2){var a=i[1];if(a[0]===`+`&&(a=a.slice(1)),a=+a,a!==_(a)||!f(a))throw Error(`Invalid integer: `+a+` is not a valid exponent.`);var o=i[0],c=o.indexOf(`.`);if(c>=0&&(a-=o.length-c-1,o=o.slice(0,c)+o.slice(c+1)),a<0)throw Error(`Cannot include negative exponent part for integers`);o+=Array(a+1).join(`0`),e=o}if(!/^([0-9][0-9]*)$/.test(e))throw Error(`Invalid integer: `+e);if(s)return new d(BigInt(n?`-`+e:e));for(var p=[],m=e.length,g=r,v=m-g;m>0;)p.push(+e.slice(v,m)),v-=g,v<0&&(v=0),m-=g;return h(p),new l(p,n)}function he(e){if(s)return new d(BigInt(e));if(f(e)){if(e!==_(e))throw Error(e+` is not an integer.`);return new u(e)}return me(e.toString())}function ge(e){return typeof e==`number`?he(e):typeof e==`string`?me(e):typeof e==`bigint`?new d(e):e}for(var _e=0;_e<1e3;_e++)c[_e]=ge(_e),_e>0&&(c[-_e]=ge(-_e));return c.one=c[1],c.zero=c[0],c.minusOne=c[-1],c.max=ie,c.min=ae,c.gcd=oe,c.lcm=se,c.isInstance=function(e){return e instanceof l||e instanceof u||e instanceof d},c.randBetween=ce,c.fromArray=function(e,t,n){return ue(e.map(ge),ge(t||10),n)},c})();typeof t<`u`&&t.hasOwnProperty(`exports`)&&(t.exports=n),typeof define==`function`&&define.amd&&define(function(){return n})}),WW=HW((e,t)=>{(function(e){var n=9e15,r=1e9,i=`0123456789abcdef`,a=`2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058`,o=`3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823
2633066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789`,s={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-n,maxE:n,crypto:!1},c,l,u,d,f=!0,p=`[DecimalError] `,m=p+`Invalid argument: `,h=p+`Precision limit exceeded`,g=p+`crypto unavailable`,_=`[object Decimal]`,v=Math.floor,y=Math.pow,b=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,x=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,S=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,C=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,w=1e7,T=7,E=9007199254740991,D=a.length-1,O=o.length-1,k={toStringTag:_};k.absoluteValue=k.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),I(e)},k.ceil=function(){return I(new this.constructor(this),this.e+1,2)},k.clampedTo=k.clamp=function(e,t){var n,r=this,i=r.constructor;if(e=new i(e),t=new i(t),!e.s||!t.s)return new i(NaN);if(e.gt(t))throw Error(m+t);return n=r.cmp(e),n<0?e:r.cmp(t)>0?t:new i(r)},k.comparedTo=k.cmp=function(e){var t,n,r,i,a=this,o=a.d,s=(e=new a.constructor(e)).d,c=a.s,l=e.s;if(!o||!s)return!c||!l?NaN:c===l?o===s?0:!o^c<0?1:-1:c;if(!o[0]||!s[0])return o[0]?c:s[0]?-l:0;if(c!==l)return c;if(a.e!==e.e)return a.e>e.e^c<0?1:-1;for(r=o.length,i=s.length,t=0,n=r<i?r:i;t<n;++t)if(o[t]!==s[t])return o[t]>s[t]^c<0?1:-1;return r===i?0:r>i^c<0?1:-1},k.cosine=k.cos=function(){var e,t,n=this,r=n.constructor;return n.d?n.d[0]?(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+T,r.rounding=1,n=P(r,de(r,n)),r.precision=e,r.rounding=t,I(d==2||d==3?n.neg():n,e,t,!0)):new r(1):new r(NaN)},k.cubeRoot=k.cbrt=function(){var e,t,n,r,i,a,o,s,c,l,u=this,d=u.constructor;if(!u.isFinite()||u.isZero())return new d(u);for(f=!1,a=u.s*y(u.s*u,1/3),!a||Math.abs(a)==1/0?(n=A(u.d),e=u.e,(a=(e-n.length+1)%3)&&(n+=a==1||a==-2?`0`:`00`),a=y(n,1/3),e=v((e+1)/3)-(e%3==(e<0?-1:2)),a==1/0?n=`5e`+e:(n=a.toExponential(),n=n.slice(0,n.indexOf(`e`)+1)+e),r=new d(n),r.s=u.s):r=new d(a.toString()),o=(e=d.precision)+3;;)if(s=r,c=s.times(s).times(s),l=c.plus(u),r=F(l.plus(u).times(s),l.plus(c),o+2,1),A(s.d).slice(0,o)===(n=A(r.d)).slice(0,o))if(n=n.slice(o-3,o+1),n==`9999`||!i&&n==`4999`){if(!i&&(I(s,e+1,0),s.times(s).times(s).eq(u))){r=s;break}o+=4,i=1}else{(!+n||!+n.slice(1)&&n.charAt(0)==`5`)&&(I(r,e+1,1),t=!r.times(r).times(r).eq(u));break}return f=!0,I(r,e,d.rounding,t)},k.decimalPlaces=k.dp=function(){var e,t=this.d,n=NaN;if(t){if(e=t.length-1,n=(e-v(this.e/T))*T,e=t[e],e)for(;e%10==0;e/=10)n--;n<0&&(n=0)}return n},k.dividedBy=k.div=function(e){return F(this,new this.constructor(e))},k.dividedToIntegerBy=k.divToInt=function(e){var t=this,n=t.constructor;return I(F(t,new n(e),0,1,1),n.precision,n.rounding)},k.equals=k.eq=function(e){return this.cmp(e)===0},k.floor=function(){return I(new this.constructor(this),this.e+1,3)},k.greaterThan=k.gt=function(e){return this.cmp(e)>0},k.greaterThanOrEqualTo=k.gte=function(e){var t=this.cmp(e);return t==1||t===0},k.hyperbolicCosine=k.cosh=function(){var e,t,n,r,i,a=this,o=a.constructor,s=new o(1);if(!a.isFinite())return new o(a.s?1/0:NaN);if(a.isZero())return s;n=o.precision,r=o.rounding,o.precision=n+Math.max(a.e,a.sd())+4,o.rounding=1,i=a.d.length,i<32?(e=Math.ceil(i/3),t=(1/ue(4,e)).toString()):(e=16,t=`2.3283064365386962890625e-10`),a=le(o,1,a.times(t),new o(1),!0);for(var c,l=e,u=new o(8);l--;)c=a.times(a),a=s.minus(c.times(u.minus(c.times(u))));return I(a,o.precision=n,o.rounding=r,!0)},k.hyperbolicSine=k.sinh=function(){var e,t,n,r,i=this,a=i.constructor;if(!i.isFinite()||i.isZero())return new a(i);
2633if(t=a.precision,n=a.rounding,a.precision=t+Math.max(i.e,i.sd())+4,a.rounding=1,r=i.d.length,r<3)i=le(a,2,i,i,!0);else{e=1.4*Math.sqrt(r),e=e>16?16:e|0,i=i.times(1/ue(5,e)),i=le(a,2,i,i,!0);for(var o,s=new a(5),c=new a(16),l=new a(20);e--;)o=i.times(i),i=i.times(s.plus(o.times(c.times(o).plus(l))))}return a.precision=t,a.rounding=n,I(i,t,n,!0)},k.hyperbolicTangent=k.tanh=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+7,r.rounding=1,F(n.sinh(),n.cosh(),r.precision=e,r.rounding=t)):new r(n.s)},k.inverseCosine=k.acos=function(){var e=this,t=e.constructor,n=e.abs().cmp(1),r=t.precision,i=t.rounding;return n===-1?e.isZero()?te(t,r+4,i).times(.5):(t.precision=r+6,t.rounding=1,e=new t(1).minus(e).div(e.plus(1)).sqrt().atan(),t.precision=r,t.rounding=i,e.times(2)):n===0?e.isNeg()?te(t,r,i):new t(0):new t(NaN)},k.inverseHyperbolicCosine=k.acosh=function(){var e,t,n=this,r=n.constructor;return n.lte(1)?new r(n.eq(1)?0:NaN):n.isFinite()?(e=r.precision,t=r.rounding,r.precision=e+Math.max(Math.abs(n.e),n.sd())+4,r.rounding=1,f=!1,n=n.times(n).minus(1).sqrt().plus(n),f=!0,r.precision=e,r.rounding=t,n.ln()):new r(n)},k.inverseHyperbolicSine=k.asinh=function(){var e,t,n=this,r=n.constructor;return!n.isFinite()||n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+2*Math.max(Math.abs(n.e),n.sd())+6,r.rounding=1,f=!1,n=n.times(n).plus(1).sqrt().plus(n),f=!0,r.precision=e,r.rounding=t,n.ln())},k.inverseHyperbolicTangent=k.atanh=function(){var e,t,n,r,i=this,a=i.constructor;return i.isFinite()?i.e>=0?new a(i.abs().eq(1)?i.s/0:i.isZero()?i:NaN):(e=a.precision,t=a.rounding,r=i.sd(),Math.max(r,e)<2*-i.e-1?I(new a(i),e,t,!0):(a.precision=n=r-i.e,i=F(i.plus(1),new a(1).minus(i),n+e,1),a.precision=e+4,a.rounding=1,i=i.ln(),a.precision=e,a.rounding=t,i.times(.5))):new a(NaN)},k.inverseSine=k.asin=function(){var e,t,n,r,i=this,a=i.constructor;return i.isZero()?new a(i):(t=i.abs().cmp(1),n=a.precision,r=a.rounding,t===-1?(a.precision=n+6,a.rounding=1,i=i.div(new a(1).minus(i.times(i)).sqrt().plus(1)).atan(),a.precision=n,a.rounding=r,i.times(2)):t===0?(e=te(a,n+4,r).times(.5),e.s=i.s,e):new a(NaN))},k.inverseTangent=k.atan=function(){var e,t,n,r,i,a,o,s,c,l=this,u=l.constructor,d=u.precision,p=u.rounding;if(l.isFinite()){if(l.isZero())return new u(l);if(l.abs().eq(1)&&d+4<=O)return o=te(u,d+4,p).times(.25),o.s=l.s,o}else{if(!l.s)return new u(NaN);if(d+4<=O)return o=te(u,d+4,p).times(.5),o.s=l.s,o}for(u.precision=s=d+10,u.rounding=1,n=Math.min(28,s/T+2|0),e=n;e;--e)l=l.div(l.times(l).plus(1).sqrt().plus(1));for(f=!1,t=Math.ceil(s/T),r=1,c=l.times(l),o=new u(l),i=l;e!==-1;)if(i=i.times(c),a=o.minus(i.div(r+=2)),i=i.times(c),o=a.plus(i.div(r+=2)),o.d[t]!==void 0)for(e=t;o.d[e]===a.d[e]&&e--;);return n&&(o=o.times(2<<n-1)),f=!0,I(o,u.precision=d,u.rounding=p,!0)},k.isFinite=function(){return!!this.d},k.isInteger=k.isInt=function(){return!!this.d&&v(this.e/T)>this.d.length-2},k.isNaN=function(){return!this.s},k.isNegative=k.isNeg=function(){return this.s<0},k.isPositive=k.isPos=function(){return this.s>0},k.isZero=function(){return!!this.d&&this.d[0]===0},k.lessThan=k.lt=function(e){return this.cmp(e)<0},k.lessThanOrEqualTo=k.lte=function(e){return this.cmp(e)<1},k.logarithm=k.log=function(e){var t,n,r,i,a,o,s,c,l=this,u=l.constructor,d=u.precision,p=u.rounding,m=5;if(e==null)e=new u(10),t=!0;else{if(e=new u(e),n=e.d,e.s<0||!n||!n[0]||e.eq(1))return new u(NaN);t=e.eq(10)}if(n=l.d,l.s<0||!n||!n[0]||l.eq(1))return new u(n&&!n[0]?-1/0:l.s==1?n?0:1/0:NaN);if(t)if(n.length>1)a=!0;else{for(i=n[0];i%10==0;)i/=10;a=i!==1}if(f=!1,s=d+m,o=ie(l,s),r=t?R(u,s+10):ie(e,s),c=F(o,r,s,1),M(c.d,i=d,p))do if(s+=10,o=ie(l,s),r=t?R(u,s+10):ie(e,s),c=F(o,r,s,1),!a){+A(c.d).slice(i+1,i+15)+1==0x5af3107a4000&&(c=I(c,d+1,0));break}while(M(c.d,i+=10,p));return f=!0,I(c,d,p)},k.minus=k.sub=function(e){var t,n,r,i,a,o,s,c,l,u,d,p,m=this,h=m.constructor;if(e=new h(e),!m.d||!e.d)return!m.s||!e.s?e=new h(NaN):m.d?e.s=-e.s:e=new h(e.d||m.s!==e.s?m:NaN),e;if(m.s!=e.s)return e.s=-e.s,m.plus(e);
vendor: 20,767 bytes, line 2633
2633if(l=m.d,p=e.d,s=h.precision,c=h.rounding,!l[0]||!p[0]){if(p[0])e.s=-e.s;else if(l[0])e=new h(m);else return new h(c===3?-0:0);return f?I(e,s,c):e}if(n=v(e.e/T),u=v(m.e/T),l=l.slice(),a=u-n,a){for(d=a<0,d?(t=l,a=-a,o=p.length):(t=p,n=u,o=l.length),r=Math.max(Math.ceil(s/T),o)+2,a>r&&(a=r,t.length=1),t.reverse(),r=a;r--;)t.push(0);t.reverse()}else{for(r=l.length,o=p.length,d=r<o,d&&(o=r),r=0;r<o;r++)if(l[r]!=p[r]){d=l[r]<p[r];break}a=0}for(d&&(t=l,l=p,p=t,e.s=-e.s),o=l.length,r=p.length-o;r>0;--r)l[o++]=0;for(r=p.length;r>a;){if(l[--r]<p[r]){for(i=r;i&&l[--i]===0;)l[i]=w-1;--l[i],l[r]+=w}l[r]-=p[r]}for(;l[--o]===0;)l.pop();for(;l[0]===0;l.shift())--n;return l[0]?(e.d=l,e.e=ee(l,n),f?I(e,s,c):e):new h(c===3?-0:0)},k.modulo=k.mod=function(e){var t,n=this,r=n.constructor;return e=new r(e),!n.d||!e.s||e.d&&!e.d[0]?new r(NaN):!e.d||n.d&&!n.d[0]?I(new r(n),r.precision,r.rounding):(f=!1,r.modulo==9?(t=F(n,e.abs(),0,3,1),t.s*=e.s):t=F(n,e,0,r.modulo,1),t=t.times(e),f=!0,n.minus(t))},k.naturalExponential=k.exp=function(){return re(this)},k.naturalLogarithm=k.ln=function(){return ie(this)},k.negated=k.neg=function(){var e=new this.constructor(this);return e.s=-e.s,I(e)},k.plus=k.add=function(e){var t,n,r,i,a,o,s,c,l,u,d=this,p=d.constructor;if(e=new p(e),!d.d||!e.d)return!d.s||!e.s?e=new p(NaN):d.d||(e=new p(e.d||d.s===e.s?d:NaN)),e;if(d.s!=e.s)return e.s=-e.s,d.minus(e);if(l=d.d,u=e.d,s=p.precision,c=p.rounding,!l[0]||!u[0])return u[0]||(e=new p(d)),f?I(e,s,c):e;if(a=v(d.e/T),r=v(e.e/T),l=l.slice(),i=a-r,i){for(i<0?(n=l,i=-i,o=u.length):(n=u,r=a,o=l.length),a=Math.ceil(s/T),o=a>o?a+1:o+1,i>o&&(i=o,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for(o=l.length,i=u.length,o-i<0&&(i=o,n=u,u=l,l=n),t=0;i;)t=(l[--i]=l[i]+u[i]+t)/w|0,l[i]%=w;for(t&&(l.unshift(t),++r),o=l.length;l[--o]==0;)l.pop();return e.d=l,e.e=ee(l,r),f?I(e,s,c):e},k.precision=k.sd=function(e){var t,n=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(m+e);return n.d?(t=z(n.d),e&&n.e+1>t&&(t=n.e+1)):t=NaN,t},k.round=function(){var e=this,t=e.constructor;return I(new t(e),e.e+1,t.rounding)},k.sine=k.sin=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+T,r.rounding=1,n=ce(r,de(r,n)),r.precision=e,r.rounding=t,I(d>2?n.neg():n,e,t,!0)):new r(NaN)},k.squareRoot=k.sqrt=function(){var e,t,n,r,i,a,o=this,s=o.d,c=o.e,l=o.s,u=o.constructor;if(l!==1||!s||!s[0])return new u(!l||l<0&&(!s||s[0])?NaN:s?o:1/0);for(f=!1,l=Math.sqrt(+o),l==0||l==1/0?(t=A(s),(t.length+c)%2==0&&(t+=`0`),l=Math.sqrt(t),c=v((c+1)/2)-(c<0||c%2),l==1/0?t=`5e`+c:(t=l.toExponential(),t=t.slice(0,t.indexOf(`e`)+1)+c),r=new u(t)):r=new u(l.toString()),n=(c=u.precision)+3;;)if(a=r,r=a.plus(F(o,a,n+2,1)).times(.5),A(a.d).slice(0,n)===(t=A(r.d)).slice(0,n))if(t=t.slice(n-3,n+1),t==`9999`||!i&&t==`4999`){if(!i&&(I(a,c+1,0),a.times(a).eq(o))){r=a;break}n+=4,i=1}else{(!+t||!+t.slice(1)&&t.charAt(0)==`5`)&&(I(r,c+1,1),e=!r.times(r).eq(o));break}return f=!0,I(r,c,u.rounding,e)},k.tangent=k.tan=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+10,r.rounding=1,n=n.sin(),n.s=1,n=F(n,new r(1).minus(n.times(n)).sqrt(),e+10,0),r.precision=e,r.rounding=t,I(d==2||d==4?n.neg():n,e,t,!0)):new r(NaN)},k.times=k.mul=function(e){var t,n,r,i,a,o,s,c,l,u=this,d=u.constructor,p=u.d,m=(e=new d(e)).d;if(e.s*=u.s,!p||!p[0]||!m||!m[0])return new d(!e.s||p&&!p[0]&&!m||m&&!m[0]&&!p?NaN:!p||!m?e.s/0:e.s*0);for(n=v(u.e/T)+v(e.e/T),c=p.length,l=m.length,c<l&&(a=p,p=m,m=a,o=c,c=l,l=o),a=[],o=c+l,r=o;r--;)a.push(0);for(r=l;--r>=0;){for(t=0,i=c+r;i>r;)s=a[i]+m[r]*p[i-r-1]+t,a[i--]=s%w|0,t=s/w|0;a[i]=(a[i]+t)%w|0}for(;!a[--o];)a.pop();return t?++n:a.shift(),e.d=a,e.e=ee(a,n),f?I(e,d.precision,d.rounding):e},k.toBinary=function(e,t){return fe(this,2,e,t)},k.toDecimalPlaces=k.toDP=function(e,t){var n=this,i=n.constructor;return n=new i(n),e===void 0?n:(j(e,0,r),t===void 0?t=i.rounding:j(t,0,8),I(n,e+n.e+1,t))},k.toExponential=function(e,t){var n,i=this,a=i.constructor;return e===void 0?n=L(i,!0):(j(e,0,r),t===void 0?t=a.rounding:j(t,0,8),i=I(new a(i),e+1,t),n=L(i,!0,e+1)),i.isNeg()&&!i.isZero()?`-`+n:n},k.toFixed=function(e,t){var n,i,a=this,o=a.constructor;return e===void 0?n=L(a):(j(e,0,r),t===void 0?t=o.rounding:j(t,0,8),i=I(new o(a),e+a.e+1,t),n=L(i,!1,e+i.e+1)),a.isNeg()&&!a.isZero()?`-`+n:n},k.toFraction=function(e){var t,n,r,i,a,o,s,c,l,u,d,p,h=this,g=h.d,_=h.constructor;if(!g)return new _(h);if(l=n=new _(1),r=c=new _(0),t=new _(r),a=t.e=z(g)-h.e-1,o=a%T,t.d[0]=y(10,o<0?T+o:o),e==null)e=a>0?t:l;else{if(s=new _(e),!s.isInt()||s.lt(l))throw Error(m+s);e=s.gt(t)?a>0?t:l:s}for(f=!1,s=new _(A(g)),u=_.precision,_.precision=a=g.length*T*2;d=F(s,t,0,1,1),i=n.plus(d.times(r)),i.cmp(e)!=1;)n=r,r=i,i=l,l=c.plus(d.times(i)),c=i,i=t,t=s.minus(d.times(i)),s=i;return i=F(e.minus(n),r,0,1,1),c=c.plus(i.times(l)),n=n.plus(i.times(r)),c.s=l.s=h.s,p=F(l,r,a,1).minus(h).abs().cmp(F(c,n,a,1).minus(h).abs())<1?[l,r]:[c,n],_.precision=u,f=!0,p},k.toHexadecimal=k.toHex=function(e,t){return fe(this,16,e,t)},k.toNearest=function(e,t){var n=this,r=n.constructor;if(n=new r(n),e==null){if(!n.d)return n;e=new r(1),t=r.rounding}else{if(e=new r(e),t===void 0?t=r.rounding:j(t,0,8),!n.d)return e.s?n:e;if(!e.d)return e.s&&=n.s,e}return e.d[0]?(f=!1,n=F(n,e,0,t,1).times(e),f=!0,I(n)):(e.s=n.s,n=e),n},k.toNumber=function(){return+this},k.toOctal=function(e,t){return fe(this,8,e,t)},k.toPower=k.pow=function(e){var t,n,r,i,a,o,s=this,c=s.constructor,l=+(e=new c(e));if(!s.d||!e.d||!s.d[0]||!e.d[0])return new c(y(+s,l));if(s=new c(s),s.eq(1))return s;if(r=c.precision,a=c.rounding,e.eq(1))return I(s,r,a);if(t=v(e.e/T),t>=e.d.length-1&&(n=l<0?-l:l)<=E)return i=B(c,s,n,r),e.s<0?new c(1).div(i):I(i,r,a);if(o=s.s,o<0){if(t<e.d.length-1)return new c(NaN);if(!(e.d[t]&1)&&(o=1),s.e==0&&s.d[0]==1&&s.d.length==1)return s.s=o,s}return n=y(+s,l),t=n==0||!isFinite(n)?v(l*(Math.log(`0.`+A(s.d))/Math.LN10+s.e+1)):new c(n+``).e,t>c.maxE+1||t<c.minE-1?new c(t>0?o/0:0):(f=!1,c.rounding=s.s=1,n=Math.min(12,(t+``).length),i=re(e.times(ie(s,r+n)),r),i.d&&(i=I(i,r+5,1),M(i.d,r,a)&&(t=r+10,i=I(re(e.times(ie(s,t+n)),t),t+5,1),+A(i.d).slice(r+1,r+15)+1==0x5af3107a4000&&(i=I(i,r+1,0)))),i.s=o,f=!0,c.rounding=a,I(i,r,a))},k.toPrecision=function(e,t){var n,i=this,a=i.constructor;return e===void 0?n=L(i,i.e<=a.toExpNeg||i.e>=a.toExpPos):(j(e,1,r),t===void 0?t=a.rounding:j(t,0,8),i=I(new a(i),e,t),n=L(i,e<=i.e||i.e<=a.toExpNeg,e)),i.isNeg()&&!i.isZero()?`-`+n:n},k.toSignificantDigits=k.toSD=function(e,t){var n=this,i=n.constructor;return e===void 0?(e=i.precision,t=i.rounding):(j(e,1,r),t===void 0?t=i.rounding:j(t,0,8)),I(new i(n),e,t)},k.toString=function(){var e=this,t=e.constructor,n=L(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?`-`+n:n},k.truncated=k.trunc=function(){return I(new this.constructor(this),this.e+1,1)},k.valueOf=k.toJSON=function(){var e=this,t=e.constructor,n=L(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()?`-`+n:n};function A(e){var t,n,r,i=e.length-1,a=``,o=e[0];if(i>0){for(a+=o,t=1;t<i;t++)r=e[t]+``,n=T-r.length,n&&(a+=ne(n)),a+=r;o=e[t],r=o+``,n=T-r.length,n&&(a+=ne(n))}else if(o===0)return`0`;for(;o%10==0;)o/=10;return a+o}function j(e,t,n){if(e!==~~e||e<t||e>n)throw Error(m+e)}function M(e,t,n,r){var i,a,o,s;for(a=e[0];a>=10;a/=10)--t;return--t<0?(t+=T,i=0):(i=Math.ceil((t+1)/T),t%=T),a=y(10,T-t),s=e[i]%a|0,r==null?t<3?(t==0?s=s/100|0:t==1&&(s=s/10|0),o=n<4&&s==99999||n>3&&s==49999||s==5e4||s==0):o=(n<4&&s+1==a||n>3&&s+1==a/2)&&(e[i+1]/a/100|0)==y(10,t-2)-1||(s==a/2||s==0)&&(e[i+1]/a/100|0)==0:t<4?(t==0?s=s/1e3|0:t==1?s=s/100|0:t==2&&(s=s/10|0),o=(r||n<4)&&s==9999||!r&&n>3&&s==4999):o=((r||n<4)&&s+1==a||!r&&n>3&&s+1==a/2)&&(e[i+1]/a/1e3|0)==y(10,t-3)-1,o}function N(e,t,n){for(var r,a=[0],o,s=0,c=e.length;s<c;){for(o=a.length;o--;)a[o]*=t;for(a[0]+=i.indexOf(e.charAt(s++)),r=0;r<a.length;r++)a[r]>n-1&&(a[r+1]===void 0&&(a[r+1]=0),a[r+1]+=a[r]/n|0,a[r]%=n)}return a.reverse()}function P(e,t){var n,r,i;if(t.isZero())return t;r=t.d.length,r<32?(n=Math.ceil(r/3),i=(1/ue(4,n)).toString()):(n=16,i=`2.3283064365386962890625e-10`),e.precision+=n,t=le(e,1,t.times(i),new e(1));for(var a=n;a--;){var o=t.times(t);t=o.times(o).minus(o).times(8).plus(1)}return e.precision-=n,t}var F=(function(){function e(e,t,n){var r,i=0,a=e.length;for(e=e.slice();a--;)r=e[a]*t+i,e[a]=r%n|0,i=r/n|0;return i&&e.unshift(i),e}function t(e,t,n,r){var i,a;if(n!=r)a=n>r?1:-1;else for(i=a=0;i<n;i++)if(e[i]!=t[i]){a=e[i]>t[i]?1:-1;break}return a}function n(e,t,n,r){for(var i=0;n--;)e[n]-=i,i=+(e[n]<t[n]),e[n]=i*r+e[n]-t[n];for(;!e[0]&&e.length>1;)e.shift()}return function(r,i,a,o,s,c){var u,d,f,p,m,h,g,_,y,b,x,S,C,E,D,O,k,A,j,M,N=r.constructor,P=r.s==i.s?1:-1,F=r.d,L=i.d;if(!F||!F[0]||!L||!L[0])return new N(!r.s||!i.s||(F?L&&F[0]==L[0]:!L)?NaN:F&&F[0]==0||!L?P*0:P/0);for(c?(m=1,d=r.e-i.e):(c=w,m=T,d=v(r.e/m)-v(i.e/m)),j=L.length,k=F.length,y=new N(P),b=y.d=[],f=0;L[f]==(F[f]||0);f++);if(L[f]>(F[f]||0)&&d--,a==null?(E=a=N.precision,o=N.rounding):E=s?a+(r.e-i.e)+1:a,E<0)b.push(1),h=!0;else{if(E=E/m+2|0,f=0,j==1){for(p=0,L=L[0],E++;(f<k||p)&&E--;f++)D=p*c+(F[f]||0),b[f]=D/L|0,p=D%L|0;h=p||f<k}else{for(p=c/(L[0]+1)|0,p>1&&(L=e(L,p,c),F=e(F,p,c),j=L.length,k=F.length),O=j,x=F.slice(0,j),S=x.length;S<j;)x[S++]=0;M=L.slice(),M.unshift(0),A=L[0],L[1]>=c/2&&++A;do p=0,u=t(L,x,j,S),u<0?(C=x[0],j!=S&&(C=C*c+(x[1]||0)),p=C/A|0,p>1?(p>=c&&(p=c-1),g=e(L,p,c),_=g.length,S=x.length,u=t(g,x,_,S),u==1&&(p--,n(g,j<_?M:L,_,c))):(p==0&&(u=p=1),g=L.slice()),_=g.length,_<S&&g.unshift(0),n(x,g,S,c),u==-1&&(S=x.length,u=t(L,x,j,S),u<1&&(p++,n(x,j<S?M:L,S,c))),S=x.length):u===0&&(p++,x=[0]),b[f++]=p,u&&x[0]?x[S++]=F[O]||0:(x=[F[O]],S=1);while((O++<k||x[0]!==void 0)&&E--);h=x[0]!==void 0}b[0]||b.shift()}if(m==1)y.e=d,l=h;else{for(f=1,p=b[0];p>=10;p/=10)f++;y.e=f+d*m-1,I(y,s?a+y.e+1:a,o,h)}return y}})();function I(e,t,n,r){var i,a,o,s,c,l,u,d,p,m=e.constructor;e:if(t!=null){if(d=e.d,!d)return e;for(i=1,s=d[0];s>=10;s/=10)i++;if(a=t-i,a<0)a+=T,o=t,u=d[p=0],c=u/y(10,i-o-1)%10|0;else if(p=Math.ceil((a+1)/T),s=d.length,p>=s)if(r){for(;s++<=p;)d.push(0);u=c=0,i=1,a%=T,o=a-T+1}else break e;else{for(u=s=d[p],i=1;s>=10;s/=10)i++;a%=T,o=a-T+i,c=o<0?0:u/y(10,i-o-1)%10|0}if(r=r||t<0||d[p+1]!==void 0||(o<0?u:u%y(10,i-o-1)),l=n<4?(c||r)&&(n==0||n==(e.s<0?3:2)):c>5||c==5&&(n==4||r||n==6&&(a>0?o>0?u/y(10,i-o):0:d[p-1])%10&1||n==(e.s<0?8:7)),t<1||!d[0])return d.length=0,l?(t-=e.e+1,d[0]=y(10,(T-t%T)%T),e.e=-t||0):d[0]=e.e=0,e;if(a==0?(d.length=p,s=1,p--):(d.length=p+1,s=y(10,T-a),d[p]=o>0?(u/y(10,i-o)%y(10,o)|0)*s:0),l)for(;;)if(p==0){for(a=1,o=d[0];o>=10;o/=10)a++;for(o=d[0]+=s,s=1;o>=10;o/=10)s++;a!=s&&(e.e++,d[0]==w&&(d[0]=1));break}else{if(d[p]+=s,d[p]!=w)break;d[p--]=0,s=1}for(a=d.length;d[--a]===0;)d.pop()}return f&&(e.e>m.maxE?(e.d=null,e.e=NaN):e.e<m.minE&&(e.e=0,e.d=[0])),e}function L(e,t,n){if(!e.isFinite())return ae(e);var r,i=e.e,a=A(e.d),o=a.length;return t?(n&&(r=n-o)>0?a=a.charAt(0)+`.`+a.slice(1)+ne(r):o>1&&(a=a.charAt(0)+`.`+a.slice(1)),a=a+(e.e<0?`e`:`e+`)+e.e):i<0?(a=`0.`+ne(-i-1)+a,n&&(r=n-o)>0&&(a+=ne(r))):i>=o?(a+=ne(i+1-o),n&&(r=n-i-1)>0&&(a=a+`.`+ne(r))):((r=i+1)<o&&(a=a.slice(0,r)+`.`+a.slice(r)),n&&(r=n-o)>0&&(i+1===o&&(a+=`.`),a+=ne(r))),a}function ee(e,t){var n=e[0];for(t*=T;n>=10;n/=10)t++;return t}function R(e,t,n){if(t>D)throw f=!0,n&&(e.precision=n),Error(h);return I(new e(a),t,1,!0)}function te(e,t,n){if(t>O)throw Error(h);return I(new e(o),t,n,!0)}function z(e){var t=e.length-1,n=t*T+1;if(t=e[t],t){for(;t%10==0;t/=10)n--;for(t=e[0];t>=10;t/=10)n++}return n}function ne(e){for(var t=``;e--;)t+=`0`;return t}function B(e,t,n,r){var i,a=new e(1),o=Math.ceil(r/T+4);for(f=!1;;){if(n%2&&(a=a.times(t),pe(a.d,o)&&(i=!0)),n=v(n/2),n===0){n=a.d.length-1,i&&a.d[n]===0&&++a.d[n];break}t=t.times(t),pe(t.d,o)}return f=!0,a}function V(e){return e.d[e.d.length-1]&1}function H(e,t,n){for(var r,i,a=new e(t[0]),o=0;++o<t.length;){if(i=new e(t[o]),!i.s){a=i;break}r=a.cmp(i),(r===n||r===0&&a.s===n)&&(a=i)}return a}function re(e,t){var n,r,i,a,o,s,c,l=0,u=0,d=0,p=e.constructor,m=p.rounding,h=p.precision;if(!e.d||!e.d[0]||e.e>17)return new p(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:NaN);for(t==null?(f=!1,c=h):c=t,s=new p(.03125);e.e>-2;)e=e.times(s),d+=5;for(r=Math.log(y(2,d))/Math.LN10*2+5|0,c+=r,n=a=o=new p(1),p.precision=c;;){if(a=I(a.times(e),c,1),n=n.times(++u),s=o.plus(F(a,n,c,1)),A(s.d).slice(0,c)===A(o.d).slice(0,c)){for(i=d;i--;)o=I(o.times(o),c,1);if(t==null)if(l<3&&M(o.d,c-r,m,l))p.precision=c+=10,n=a=s=new p(1),u=0,l++;else return I(o,p.precision=h,m,f=!0);else return p.precision=h,o}o=s}}function ie(e,t){var n,r,i,a,o,s,c,l,u,d,p,m=1,h=10,g=e,_=g.d,v=g.constructor,y=v.rounding,b=v.precision;if(g.s<0||!_||!_[0]||!g.e&&_[0]==1&&_.length==1)return new v(_&&!_[0]?-1/0:g.s==1?_?0:g:NaN);if(t==null?(f=!1,u=b):u=t,v.precision=u+=h,n=A(_),r=n.charAt(0),Math.abs(a=g.e)<0x5543df729c000){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)g=g.times(e),n=A(g.d),r=n.charAt(0),m++;a=g.e,r>1?(g=new v(`0.`+n),a++):g=new v(r+`.`+n.slice(1))}else return l=R(v,u+2,b).times(a+``),g=ie(new v(r+`.`+n.slice(1)),u-h).plus(l),v.precision=b,t==null?I(g,b,y,f=!0):g;for(d=g,c=o=g=F(g.minus(1),g.plus(1),u,1),p=I(g.times(g),u,1),i=3;;){if(o=I(o.times(p),u,1),l=c.plus(F(o,new v(i),u,1)),A(l.d).slice(0,u)===A(c.d).slice(0,u))if(c=c.times(2),a!==0&&(c=c.plus(R(v,u+2,b).times(a+``))),c=F(c,new v(m),u,1),t==null)if(M(c.d,u-h,y,s))v.precision=u+=h,l=o=g=F(d.minus(1),d.plus(1),u,1),p=I(g.times(g),u,1),i=s=1;else return I(c,v.precision=b,y,f=!0);else return v.precision=b,c;c=l,i+=2}}function ae(e){return String(e.s*e.s/0)}function oe(e,t){var n,r,i;for((n=t.indexOf(`.`))>-1&&(t=t.replace(`.`,``)),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;t.charCodeAt(r)===48;r++);for(i=t.length;t.charCodeAt(i-1)===48;--i);if(t=t.slice(r,i),t){if(i-=r,e.e=n=n-r-1,e.d=[],r=(n+1)%T,n<0&&(r+=T),r<i){for(r&&e.d.push(+t.slice(0,r)),i-=T;r<i;)e.d.push(+t.slice(r,r+=T));t=t.slice(r),r=T-t.length}else r-=i;for(;r--;)t+=`0`;e.d.push(+t),f&&(e.e>e.constructor.maxE?(e.d=null,e.e=NaN):e.e<e.constructor.minE&&(e.e=0,e.d=[0]))}else e.e=0,e.d=[0];return e}function se(e,t){var n,r,i,a,o,s,l,u,d;if(t.indexOf(`_`)>-1){if(t=t.replace(/(\d)_(?=\d)/g,`$1`),C.test(t))return oe(e,t)}else if(t===`Infinity`||t===`NaN`)return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(x.test(t))n=16,t=t.toLowerCase();else if(b.test(t))n=2;else if(S.test(t))n=8;else throw Error(m+t);for(a=t.search(/p/i),a>0?(l=+t.slice(a+1),t=t.substring(2,a)):t=t.slice(2),a=t.indexOf(`.`),o=a>=0,r=e.constructor,o&&(t=t.replace(`.`,``),s=t.length,a=s-a,i=B(r,new r(n),a,a*2)),u=N(t,n,w),d=u.length-1,a=d;u[a]===0;--a)u.pop();return a<0?new r(e.s*0):(e.e=ee(u,d),e.d=u,f=!1,o&&(e=F(e,i,s*4)),l&&(e=e.times(Math.abs(l)<54?y(2,l):c.pow(2,l))),f=!0,e)}function ce(e,t){var n,r=t.d.length;if(r<3)return t.isZero()?t:le(e,2,t,t);n=1.4*Math.sqrt(r),n=n>16?16:n|0,t=t.times(1/ue(5,n)),t=le(e,2,t,t);for(var i,a=new e(5),o=new e(16),s=new e(20);n--;)i=t.times(t),t=t.times(a.plus(i.times(o.times(i).minus(s))));return t}function le(e,t,n,r,i){var a,o,s,c,l=1,u=e.precision,d=Math.ceil(u/T);for(f=!1,c=n.times(n),s=new e(r);;){if(o=F(s.times(c),new e(t++*t++),u,1),s=i?r.plus(o):r.minus(o),r=F(o.times(c),new e(t++*t++),u,1),o=s.plus(r),o.d[d]!==void 0){for(a=d;o.d[a]===s.d[a]&&a--;);if(a==-1)break}a=s,s=r,r=o,o=a,l++}return f=!0,o.d.length=d+1,o}function ue(e,t){for(var n=e;--t;)n*=e;return n}function de(e,t){var n,r=t.s<0,i=te(e,e.precision,1),a=i.times(.5);if(t=t.abs(),t.lte(a))return d=r?4:1,t;if(n=t.divToInt(i),n.isZero())d=r?3:2;else{if(t=t.minus(n.times(i)),t.lte(a))return d=V(n)?r?2:3:r?4:1,t;d=V(n)?r?1:4:r?3:2}return t.minus(i).abs()}function fe(e,t,n,a){var o,s,c,u,d,f,p,m,h,g=e.constructor,_=n!==void 0;if(_?(j(n,1,r),a===void 0?a=g.rounding:j(a,0,8)):(n=g.precision,a=g.rounding),!e.isFinite())p=ae(e);else{for(p=L(e),c=p.indexOf(`.`),_?(o=2,t==16?n=n*4-3:t==8&&(n=n*3-2)):o=t,c>=0&&(p=p.replace(`.`,``),h=new g(1),h.e=p.length-c,h.d=N(L(h),10,o),h.e=h.d.length),m=N(p,10,o),s=d=m.length;m[--d]==0;)m.pop();if(!m[0])p=_?`0p+0`:`0`;else{if(c<0?s--:(e=new g(e),e.d=m,e.e=s,e=F(e,h,n,a,0,o),m=e.d,s=e.e,f=l),c=m[n],u=o/2,f||=m[n+1]!==void 0,f=a<4?(c!==void 0||f)&&(a===0||a===(e.s<0?3:2)):c>u||c===u&&(a===4||f||a===6&&m[n-1]&1||a===(e.s<0?8:7)),m.length=n,f)for(;++m[--n]>o-1;)m[n]=0,n||(++s,m.unshift(1));for(d=m.length;!m[d-1];--d);for(c=0,p=``;c<d;c++)p+=i.charAt(m[c]);if(_){if(d>1)if(t==16||t==8){for(c=t==16?4:3,--d;d%c;d++)p+=`0`;for(m=N(p,o,t),d=m.length;!m[d-1];--d);for(c=1,p=`1.`;c<d;c++)p+=i.charAt(m[c])}else p=p.charAt(0)+`.`+p.slice(1);p=p+(s<0?`p`:`p+`)+s}else if(s<0){for(;++s;)p=`0`+p;p=`0.`+p}else if(++s>d)for(s-=d;s--;)p+=`0`;else s<d&&(p=p.slice(0,s)+`.`+p.slice(s))}p=(t==16?`0x`:t==2?`0b`:t==8?`0o`:``)+p}return e.s<0?`-`+p:p}function pe(e,t){if(e.length>t)return e.length=t,!0}function me(e){return new this(e).abs()}function he(e){return new this(e).acos()}function ge(e){return new this(e).acosh()}function _e(e,t){return new this(e).plus(t)}function ve(e){return new this(e).asin()}function ye(e){return new this(e).asinh()}function be(e){return new this(e).atan()}function xe(e){return new this(e).atanh()}function Se(e,t){e=new this(e),t=new this(t);var n,r=this.precision,i=this.rounding,a=r+4;return!e.s||!t.s?n=new this(NaN):!e.d&&!t.d?(n=te(this,a,1).times(t.s>0?.25:.75),n.s=e.s):!t.d||e.isZero()?(n=t.s<0?te(this,r,i):new this(0),n.s=e.s):!e.d||t.isZero()?(n=te(this,a,1).times(.5),n.s=e.s):t.s<0?(this.precision=a,this.rounding=1,n=this.atan(F(e,t,a,1)),t=te(this,a,1),this.precision=r,this.rounding=i,n=e.s<0?n.minus(t):n.plus(t)):n=this.atan(F(e,t,a,1)),n}function Ce(e){return new this(e).cbrt()}function we(e){return I(e=new this(e),e.e+1,2)}function Te(e,t,n){return new this(e).clamp(t,n)}function Ee(e){if(!e||typeof e!=`object`)throw Error(p+`Object expected`);var t,i,a,o=e.defaults===!0,c=[`precision`,1,r,`rounding`,0,8,`toExpNeg`,-n,0,`toExpPos`,0,n,`maxE`,0,n,`minE`,-n,0,`modulo`,0,9];for(t=0;t<c.length;t+=3)if(i=c[t],o&&(this[i]=s[i]),(a=e[i])!==void 0)if(v(a)===a&&a>=c[t+1]&&a<=c[t+2])this[i]=a;else throw Error(m+i+`: `+a);if(i=`crypto`,o&&(this[i]=s[i]),(a=e[i])!==void 0)if(a===!0||a===!1||a===0||a===1)if(a)if(typeof crypto<`u`&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[i]=!0;else throw Error(g);else this[i]=!1;else throw Error(m+i+`: `+a);return this}function De(e){return new this(e).cos()}function Oe(e){return new this(e).cosh()}function ke(e){var t,n,r;function i(e){var t,n,r,a=this;if(!(a instanceof i))return new i(e);if(a.constructor=i,Pe(e)){a.s=e.s,f?!e.d||e.e>i.maxE?(a.e=NaN,a.d=null):e.e<i.minE?(a.e=0,a.d=[0]):(a.e=e.e,a.d=e.d.slice()):(a.e=e.e,a.d=e.d?e.d.slice():e.d);return}if(r=typeof e,r===`number`){if(e===0){a.s=1/e<0?-1:1,a.e=0,a.d=[0];return}if(e<0?(e=-e,a.s=-1):a.s=1,e===~~e&&e<1e7){for(t=0,n=e;n>=10;n/=10)t++;f?t>i.maxE?(a.e=NaN,a.d=null):t<i.minE?(a.e=0,a.d=[0]):(a.e=t,a.d=[e]):(a.e=t,a.d=[e]);return}if(e*0!=0){e||(a.s=NaN),a.e=NaN,a.d=null;return}return oe(a,e.toString())}if(r===`string`)return(n=e.charCodeAt(0))===45?(e=e.slice(1),a.s=-1):(n===43&&(e=e.slice(1)),a.s=1),C.test(e)?oe(a,e):se(a,e);if(r===`bigint`)return e<0?(e=-e,a.s=-1):a.s=1,oe(a,e.toString());throw Error(m+e)}if(i.prototype=k,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.EUCLID=9,i.config=i.set=Ee,i.clone=ke,i.isDecimal=Pe,i.abs=me,i.acos=he,i.acosh=ge,i.add=_e,i.asin=ve,i.asinh=ye,i.atan=be,i.atanh=xe,i.atan2=Se,i.cbrt=Ce,i.ceil=we,i.clamp=Te,i.cos=De,i.cosh=Oe,i.div=Ae,i.exp=je,i.floor=Me,i.hypot=Ne,i.ln=Fe,i.log=Ie,i.log10=Re,i.log2=Le,i.max=ze,i.min=Be,i.mod=Ve,i.mul=He,i.pow=Ue,i.random=We,i.round=Ge,i.sign=Ke,i.sin=qe,i.sinh=Je,i.sqrt=Ye,i.sub=Xe,i.sum=Ze,i.tan=Qe,i.tanh=$e,i.trunc=et,e===void 0&&(e={}),e&&e.defaults!==!0)for(r=[`precision`,`rounding`,`toExpNeg`,`toExpPos`,`maxE`,`minE`,`modulo`,`crypto`],t=0;t<r.length;)e.hasOwnProperty(n=r[t++])||(e[n]=this[n]);return i.config(e),i}function Ae(e,t){return new this(e).div(t)}function je(e){return new this(e).exp()}function Me(e){return I(e=new this(e),e.e+1,3)}function Ne(){var e,t,n=new this(0);for(f=!1,e=0;e<arguments.length;)if(t=new this(arguments[e++]),t.d)n.d&&(n=n.plus(t.times(t)));else{if(t.s)return f=!0,new this(1/0);n=t}return f=!0,n.sqrt()}function Pe(e){return e instanceof c||e&&e.toStringTag===_||!1}function Fe(e){return new this(e).ln()}function Ie(e,t){return new this(e).log(t)}function Le(e){return new this(e).log(2)}function Re(e){return new this(e).log(10)}function ze(){return H(this,arguments,-1)}
2633function Be(){return H(this,arguments,1)}function Ve(e,t){return new this(e).mod(t)}function He(e,t){return new this(e).mul(t)}function Ue(e,t){return new this(e).pow(t)}function We(e){var t,n,i,a,o=0,s=new this(1),c=[];if(e===void 0?e=this.precision:j(e,1,r),i=Math.ceil(e/T),this.crypto)if(crypto.getRandomValues)for(t=crypto.getRandomValues(new Uint32Array(i));o<i;)a=t[o],a>=429e7?t[o]=crypto.getRandomValues(new Uint32Array(1))[0]:c[o++]=a%1e7;else if(crypto.randomBytes){for(t=crypto.randomBytes(i*=4);o<i;)a=t[o]+(t[o+1]<<8)+(t[o+2]<<16)+((t[o+3]&127)<<24),a>=214e7?crypto.randomBytes(4).copy(t,o):(c.push(a%1e7),o+=4);o=i/4}else throw Error(g);else for(;o<i;)c[o++]=Math.random()*1e7|0;for(i=c[--o],e%=T,i&&e&&(a=y(10,T-e),c[o]=(i/a|0)*a);c[o]===0;o--)c.pop();if(o<0)n=0,c=[0];else{for(n=-1;c[0]===0;n-=T)c.shift();for(i=1,a=c[0];a>=10;a/=10)i++;i<T&&(n-=T-i)}return s.e=n,s.d=c,s}function Ge(e){return I(e=new this(e),e.e+1,this.rounding)}function Ke(e){return e=new this(e),e.d?e.d[0]?e.s:0*e.s:e.s||NaN}function qe(e){return new this(e).sin()}function Je(e){return new this(e).sinh()}function Ye(e){return new this(e).sqrt()}function Xe(e,t){return new this(e).sub(t)}function Ze(){var e=0,t=arguments,n=new this(t[e]);for(f=!1;n.s&&++e<t.length;)n=n.plus(t[e]);return f=!0,I(n,this.precision,this.rounding)}function Qe(e){return new this(e).tan()}function $e(e){return new this(e).tanh()}function et(e){return I(e=new this(e),e.e+1,1)}c=ke(s),c.prototype.constructor=c,c.default=c.Decimal=c,a=new c(a),o=new c(o),typeof define==`function`&&define.amd?define(function(){return c}):typeof t<`u`&&t.exports?(typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`&&(k[Symbol.for(`nodejs.util.inspect.custom`)]=k.toString,k[Symbol.toStringTag]=`Decimal`),t.exports=c):(e||=typeof self<`u`&&self&&self.self==self?self:window,u=e.Decimal,c.noConflict=function(){return e.Decimal=u,c},e.Decimal=c)})(e)}),GW=HW((e,t)=>{var n=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997,1009,1013,1019,1021,1031,1033,1039,1049,1051,1061,1063,1069,1087,1091,1093,1097,1103,1109,1117,1123,1129,1151,1153,1163,1171,1181,1187,1193,1201,1213,1217,1223,1229,1231,1237,1249,1259,1277,1279,1283,1289,1291,1297,1301,1303,1307,1319,1321,1327,1361,1367,1373,1381,1399,1409,1423,1427,1429,1433,1439,1447,1451,1453,1459,1471,1481,1483,1487,1489,1493,1499,1511,1523,1531,1543,1549,1553,1559,1567,1571,1579,1583,1597,1601,1607,1609,1613,1619,1621,1627,1637,1657,1663,1667,1669,1693,1697,1699,1709,1721,1723,1733,1741,1747,1753,1759,1777,1783,1787,1789,1801,1811,1823,1831,1847,1861,1867,1871,1873,1877,1879,1889,1901,1907,1913,1931,1933,1949,1951,1973,1979,1987,1993,1997,1999,2003,2011,2017,2027,2029,2039,2053,2063,2069,2081,2083],r={};for(let e of n)r[e]=!0;typeof t<`u`&&(t.exports={PRIMES:n,PRIMES_SET:r,LONG_PI:`3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196`,LONG_E:`2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901`,BIG_LOG_CACHE:`-253631954333118718762629409109262279926288908775918712466601196032/39970093576053625963957478139049824030906352922262642968060706375.0.24553090145869607172412918483124184864289170814122579923404694986469653261608528681589949629750677407356463601998534945057511664951799678336/35422621391945757431676178435630229283255250779216421054188228659061954317501699707236864189383591478024245495110561124597124995986978302375.369017335340917140706044240090243368728616279239227943871048759140274862131699550043150713059889196223917527172547/335894053932612728969975338549993764554481173661218585876475837409922537622385232776657791604345125227005476864000.24606853025626737903121303930100462245506322607985779603220820323211395607931699126390918477501325805513849611930008427268176602460462988972957593458726734897129954728102144/17750092415977639787139561330326170936321452137635322313122938207611787444311735251389066106937796085669460151963285086542745859461943369606018450213014148175716400146484375.399073568781976806715759409052286641738926636328983929439450824555613704676637191564699164303012247386095942144825603522401740680808466858044/247958349743620302021733249049411604982786755454514947379317600613433680222511897950658049325685140346169718465773927872179874971908848116625.1468102989495846944084741146947295378041808701256909016224309866143294556551407470861354311593351276612463858816796714569499021375899793849136855085849133702029337910502448189055357182595424959360/81936387930928630349721752737546312040473909826020027952078895077745890043830735673808293058603246260121580263632099364800
26337907724899611296693997216938989854861043298494990214825163523387600982777.5896704855274661767824574093605344871722790278354431422729640950821239030785642943033153793245906863203822369276271050164634206965056233097479117980782641839669/3030306850569309344013726745100070601277982132543905537366562638553198167007159067544789592089960911065181606283478843359856123992707598685058297067179343872000.76631772943534985713873427262830314617912556928476573358548256872141516989538374761909611879922349479420014771499018155447198112155515453671128814488139633810493264352294560043912066253026059140653027326566801398784/36852092933388988649396042883218509607503204211148493545892849595498822817623842579026942621098851631842754395231561679671400197056377380063233740202370686144673585955581403046886083948450136247134308381940165804875.3159076083816399509754948610929467278257473888282947311280653574634802580912280940686954763313882823327077171624015737719617373932318151594325834524000275847475866299387913048/1437757485694188822758304467756419845842037623148461107362957994816554782989250555362514354661961482939226272309026092009962414616417412938087494467254146002233028411865234375.22266067259907364984531611601870291368272674573653403965630628996687370994139884833897773468149149664829922302484782423514167405397665098388400450149078982462318781750661005833037235183394221496186539779712428265837926417581952/9670030144664428565128962309657100138096047028794689249320859276197340398920725569428532293373676415359965773460364494998334259893079003125373872108770534788283842907318071170285038777091588292539102269617376180390982915567375.14604654564989239958569331443385369522850975185358647132770022716433280072271007767111036877803328768910274400515590151934676819262085211828028638417329558229123989556376108454497813055/6090614019162516693013973409650613208227889078878781039105047015752493519149314227721984436973374032279421344818329285207124280297611253861173835238379831004010748379874393292231671808.1901241885407696031217292877862925220917660047127261026827869027159993239567933534052663335498281439239753018507182016153657409777749792228538380379703411298411623469292891476969894084838876001545818141543890273256985768690847587711270930688/765116019778838839812655402103512685695769161212360553099732689795578904762091216998790589926057819838537805856579109910198553330075924857419395160755642371550113347465300208422126945265887065434116781678702741657275181694851670325469434625.139459806786604751793737926146840623607010208216289543036026206208962059593900745886202214788747453279179283344350478734275973878932538430194363355795823581315329311220701640235653288975569812161436/54371368534412517053056101353618694718215711767266376573138772968257303578467926450212293233332401067673270853953399269852376592855992724934941173346260129257754416412476202526978443681584633116375.1045669091124493070709683241190022970908640501171378776604126771144008324358233819560649021940145166254659028524319517244711645162132513416238958170819347361185944945680269442845829390112062101255500836072082817820950448463314034677353723256969344/396228259004446234921310936915931611736815598535963504660076315228798989932959459406702091180060429080345146735173591749448509810270759531977278642135591672189002006272326131885315743181289970885337574780897529347356567086535505950450897216796875.9912919238915437302006264477931031611447467070103973106567538528951878797932559935860738745374437522819124347510590800370471910492338584284092534264608801221235029062881964101996762011296996851893455828946521/3660537472668264151218961634689665210933936249986285290553357254224360417386515311493310199319523687171757653216994741150377508234317025158302057758196429623723072084157928224798322861732880034847243894784000.9263710175433181746575186369318246002919895649622127410824041370079225200282403368319370743363303164313395723904510539050157032684710468364067204876434546848634842333436957245275217583248805993142227630297924119330553308466662488683624783307023014909360640/3341177182697517248552428837661919299725031035849865632511882688786226888137634168024976033652753689210700218163621739078534353578510364301481093730054725078138658805025014615651043313990684347632166030359086885561104034510990826655289288319840595753002771.5116082230713622171832327542439052727465114322479570603905499496221224653983960598946033081212909066917137546065542953865612718836914393275681318667667521726785633638189373998191090501201427906618075889744489190209584/1805752553736060443820406101277706970767657006346276183748749630179442318063568286372320188433843729960294965366346522303898609655762491623098453269916163621089005711823488749297418113474056676109581110715068124438875.246569125619713282434448566970352231845414317018379160824176638351574938993535464763890962336882760882398479702237564384291290459961036068916857265499633061660562532011248501476114401629839742058389195725393702000011860799793778295606988057303225493814005789533570432/85307063020836305797178273029353623060860009152114361453434032434699636078115114412588719432277441055049132559782203988387794711585368296817222565434951256788867244687081233632650953850383220864394261763844194948389861147622944651546912394593164406926489862036343375.133672026303452911046163998480860917119290576658330909785707604886881155606725822685088929236266583416708668502760907677019598002175122453170574729028452721476464728566191464897928696630979863154661704374206171469014225143/45398130975270785045482567762871405072140548998125471025451666500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.6041693953360002800224091673336562508913199995987479264605216252220579740134601435770085920869376641180763419907442721705887169884230643795126568815123647603047739799302562095542459344811429882053086550900803768964612193941424128649976704727183797495759082741166938351872/2016766992122395667828553277997478570503475626107286343497917705446132017125079612756035254750822860815515899557855166824523851779156336235294914777307802256439645525835223691751931866188957324792276149549076500784191791380803500156
2633776088683900346065830066370370083309875.705868391597244582764749229356331441978820024796066870551110486625729826111158236686696326058778874201639006234449557592353247542995871491078308187261304930042019640830629526023972693107193897009168955674240659026247094657679060/231848642748474339277532000336338632910990823562381469441716922006107433404523316252618490265927265734670539384485699132080062215196462178933963957679882342083893417545858074378754089719547920901917516016346211301054206383643383.101832160604157943093944673541651013907278188571533075311673249923948856034633446617630054761681006062910980371900782781226979391765818325065031889334563981235894369036439929651260587335544056975715076598739977065390678221999918899003881778449092038750712969437519295878491018112/32944277910571666002449086492515464541550138004002141571670657643770713783329063548790202120805341989608877739811787937782240802963962520261844114327432160788193314874913687387269408387417806176202979244637915812905426565263196954203487934225589622864145960079736633434831996625.10655703119271468913597640479490594180964700448340778168715956712130636958373270202484276402718566314881119559090842449610957974112230306343486091910217340665146602598568991520563987490686996746558858366002301982443029430290679385551/3398412687366638541233365137084722368200311117891192348532156645374786104142009695796409107380345795998400850838706661851176885183144928701608654514812261697598380070746520197171576610572921007069104300695592751543563472456384512000.1903039332876763837419920240543738799531131775028971323439870868730321221615515008394327723508670975623498588291298064320786970626232668956372004004897872810230178526101184611242511193415796638694370503100219710864543168952682617801833318493436174387568067811938490953495819438108686336/598806534367503338307287246320963280558134937382149405305466709787179429317914803617527827862441615350396864359976273212272586892074799651088317544101755361439294687323233086696182687664637422796995789967075271448560870681210580691574924544896656175563265378514188341796398162841796875.525573915563826130963525826191411949262846916750432019596028344808298471293378917508549164993368392834023782480702893643486699787870059946429810070222126260200026332874480239090370088123833491499400991181659445914352500247596757005142623368/163278727324937389095822405034435687776345799835442022795533783889356344755225815267819508608559076191292900367982490827396869405536484846115955581043091229202052407483776587687967125885665493681707461345895999542381476164157058393971431375.9263815657177858787273494705338516861045771674838057329170239610953039987023429736752079544014780707408666628475997291124805562998227296677616204140605356257712022384368492575381355563976330347792504605666631512343447560301417325154003481040250148561839861837778597346623630046623751094400/2843321709948499955095590862256744532227698001408929142548057792217790532624003190447363578048562448168721539177458065482170148482375585867230123873178100117094533143052886527452665480614620123764036974180917207421482431983407742154634391264619615289225747664532332469783301704643254076601.407959339726114455622180187758753007349209016396248763075759257357925636039752474207685682218422721827857994768023399625060206708378433960993946156803948655098667156937949174400873748557248801874735834957795040139401560494087476967548060208243867/123780218751812156744401121690996305978134694678934447237402511116731459214498784497436358160964198336874043702652746834763131444030185151143987331404604087778514863973633941401826334750268416015224906056576641018962863645043976537664227639296000.2547676391598917379516698439971914695230548782904479778605691338364453606537643088857116141939170899135026552016969320061900926954008522781162186995856580955090548471448276736878300717869625651893741316530109438876067419826217901657017506157997588944233677467357220316084583383623602865379325184/764562034757392298786420374672266498815021229519853724850874576419885380830752931701831256959159800764672605004880389358601658343203513177084389490286723240185146570925957286083025676875197029662038213216541352875570101363668917766225709569356861275434470568767077844675593176178611021135573625.186545352286463730559933346565311535598243666022232037054735807289501173444103692309735768703898330430135399033529355360391658728987379385732098960609744313878477967971557204207043802935782878745271859468248704012618254203101767841517569443555143252/55399179641621656233589820996143825959365789093262978988289445625153099592463372579496245442338653053662134699646413817866770218574795378644415019944304868289119443774932782235638737888469746745621382139263856603239588594078668393194675445556640625.664884440164786473344854955309049113269357314957985265728106924238588705533437169796551912202931185746193155801905841712503407258166135075966280435780812714252670362202091663287095423712596462690753468682634261029392794173636943978404002804413009590005984736612421172979101972556772005594499779860608/195485517776407145286424460448995460754674039560651791192647586550615878988380153730602665795647187884543361218962125172808792176382956599256188706636727418572541254480798303566840010217729386905041217793614214518363859058348249961790104618910877813067510758225302884815410347238200133693756493703875.2614957283934314904315471338485451166053664494383241929385424599389309215073267052860464009981063483440201193771607520572077231889699858482582363845275452280606276949653970992719332472370351170732899676316967244504534154616036371979031399425846100527685/76149366443274908931266548077349629
26330658029971027686543404885407644062485746072719559288231362060149626237939029641098328278650939665665969011529293869562636656650999759724704272743235210867676873525147820749560155294022488994426729939894753293900972032.124843380518493746761140367283007507854364503961156704095198010255465940085534099747297600085903814014415830785663764373057896014399822131175202342399536439284123918855893825207202244831315575594886675813256448846863723093240955901916229136393454605455444105444987028391748121054399538064686074523506176/36022228212051654395480210378626648518430280334458144892889271272122662467638331091863215146548048144675657239846337165813938424387499358852301016926312083940212100001220180762189978024821166744964908871443681332664798940660421469519997746775275873085770018269706847741064037876137315001228315806659875.827992369063043155578730871896750570951766628472810506926098505028264552046829097082095665194000002802661600196840639204300804225352337632259980703832713031790922485730615305441309917696044954289187837653933158950774246017223571461858939407386087081525130831392/23680593282368653499115339386928853036801157466585922670427968556
26337723830696754821658770176385138917722808377962346690757191122309876922069867472518117628639913077442806147910884267694879089753138429767401700283014143248445966474839193628309668702223994071394625.17347276886878323736540051321582548724378497839789943634071026331001588645519865992773157565595886250230140452154269197770615097377486013097979087647774513500701793885978192218455687078883766086309728287172567466406449372659680040183273634701092561727514713494914793425407149186041796935055187281744386432/4919325621804683623339606849970832094714371903709195539440424738973575902329797546592497378000858196173718145883783709223158260700365224756081275272021856393735663399552166737690038832550853145831185979094979556715294990257315369124065787473707136464772247917156232366320267601622617803514003753662109375.137984231830526866236186357461458917020538108058615632801298091031540729111527734872044790487396302545910108285921421417358113055522725197998483383380192391312304647004240060970929072498293210057120617332323445379424867965764749534125081131327565507524502163460761/38810445792642817561168950890315210470940006613819790543653745327778579787694809782601777514116858514049585074667085399925278459138508514838268321349069481334967221455722811414399738756151414906092225265355449011152267068726417045644222323488445626292574879744000.746567120547823334914136339633766098626636643449144032626270358619125402826113269699709721071135471625588981126637674402048519990010499180844665151971356149292818375448504122545400227696621572263621729512461528550588108384619064912224884465737417596190735966915167530332762203074440688676123756162572829692160/208334337057923929636884170505570363171441147899816815785150954417598643614152856767186132467069365605496210036171429712485182162940460120834349006784956522600679357307849981862006710239311750261522832996877712350330290831638640913932265004107623954913155144975252743257846945609734368518424172846119306643431.64649371728330695076928013661001819989330953381731372450140483779536126948957993261299287753791770622512248630224724990234903928056275080682537641377393210728546364176267034339221558641084730052304770498929958838997239635790469536857863963589118888238069738647239076/17903951498200212327802847425913723358452100686246224008745414214690047078122925247086521362329833307849817944645647750649290248110509395628305970523384831671737569872597295947593410067364379687588919135621621162007748635920864926867870502568935739725312687094047375.2454918942158003099688922026016393688092399295166304634317616773083386087532869193458590448918958337530406410803840837646465522656670050113548208618655070231274778592766244282964463702354872753657766121825196898916725498553882689210280080206627916046484942827487726300822318764058084323314109595329304407466188383616/674880185931325925966586583820010578979699141814417326552629206140252348822939845006845669570885271576698771404162512001549922909048916000017837898649100825976232784446638776021483802989797501705685620612986771521390439936066527738682396560462899753657942715306792783283782238662155922082005591512296007820682995125.74018558041066162916454010680594042518462756234254788158141115244349044958441521749277686851928706433556285971088455226217644009628399441967508838553345152310730562224910795446341601049647392069373970101491741830623078126344928804029524181578945586663110848142571149861/20204153620006780689923328634586091101021423979622170579036140596085566172775051595588438592742563923428900864000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.2127032036758045513335690185608563023954009095206088224487365541995326714285119384743928987635752931664240752323937321097955456543854943206092931247498833001499955456190701695430459583885125382086777607021670447795321669948733328973350279846928613949120929250312666393359442423066212311060931469017737106028339882830848/576612418511902928757340062840968526862381326698309578771238715462180282212422302261044980131594522407066369222998903808960617461164985318633518680304995784614308979881735537678182134128319596636920719106506829571072447362052319438091347699720147003209417806230149598345068078717948025207635448205253184540936478445125.35289653975561083576641954928762116897061274899517309102784750384002335187117263273488751066569234386120759866204372398611196356888479036949053282301027789530999737306501029700128744408015642211359442183943916106790666114870974212159410284751571905275610921784716184508440/9503006066880728386808143045924119024212377150217533250562188228062174064693375135306438120385877320162710918716613546077156389583384656340709638430674364232343609717735574035535102953482366914421205216675248471695111720986346092738728929878538430662191272737183832556131.102633551023964794485575491065909467125458972250222581133681080524371507544152979467328048718122409841060527545925136196267751819689935599599321090571687632103850847605493223603751038996548520557330016046032671961857623066292962260173840972332108111505971231021442896036760967107060309991355545554631003681544611731245475968/27459658121882266328752886605529964804078316737648012166874496015808620265471203512606463219297059547428855195782384236337998738233668399173746663289852416697917397644234441300570212555870401420579737973722145663287124151049692290432756231390864184491891697469874600345958989433125942336757049639797225309327019275689074625.10034393558388390065766795008210457368713365491566387292163814915435906649268119060550511145023450790393353937124495488860451123302412204483570913557762460385297770427946219119911920640306914453207097103853766023934602534502476962159682750262143380527529536498215384467975023/2667919902603322771586358077760621955455470781865624844984169443739075976572061827709528710108877015489050369589117491611045518221354793418884447632063538994046714401229510497599783726376490260140723032102883617341970952663947646017489439179953454964374887388652792446976000.248528145263843375390386172800048509380966183384567983242213959113927668429802237067505890436957693495616107089384741585283620097982859345081736730899912519273262934785992235852866637878831878448348444611412764161078458068549719800733237024285525816723480868704742804077255242682077291713092790250511567621735004237450946304/65676865669148624809340872151906045781446981664561196686217551358486802274698228825404698950974939545099727242259547145392352658637333562345477931951890984276718673618736565926663528625796412420753961231404680876558659735251469326707567479071881966875336951133475135427640218972722939427821842173216282390058040618896484375.7805448718805635696495809414501206964843262114470109146341305656318015059743127114324245035489577134938579856003956861881125856595981500593426840968087618241785931128978516340812066502964561231235073012672356530509663384739132686548934288703179479011016719045530855033205271
2633548/2050525178024039744126592505352202216905491833360272553169520915020715464206141942151086176509423406413311520838568324134077402841030113427309725873344806030836314500267104070131451720947531994814710189000076651895520222646974590481497382830325485174899169093049299764813276375.3355325071293197839434119105039673324264765809771192815982246040415580387729382404624613875653005261578877047405365032178619450963731719777167015959920645055600439987161800547901539269321100559393048973255388860193948274255340335876890491746900991668165565729269698196233805991206691196045182214641935483083662356666996922240/876402579119117579582569839757462461050855174353108858954282915644790659429341853404829661899850841645529640454766173209897510988090318303454542547519850473808789222552969933222203420847859171250332350076509996295844203965564448154484566493395403967626596213792922784509892086361572955175655987334882030766001799867659814117.218871061991045868372866381545267589365410350294028138778572466235486397478028823720846191998825628156716190463263492304639890659254282445466806224943413446008645087186307985343574807361972238230520975439736199291019544576443791916302825193643774360055545186783819367378492631806297/56849560726416896431557940314760680962653658127458002233782028041537121216487790008085876994020812492987733987414743604239935223783349870516284048368761617736127892160849065895223288023531930411718807065209903593668117085505482007061969339237404945180379460053180570404846043136000.5008685108365226931582937964451700746853986170633433728409171904803795018146152804690759530990140552460596075588463394200510044617816085275660078502126507209302951286606953039953843685800941558212440519542602092919776366067720586295390886070120828199562643208637974347390938772070049344991272621102622931576339988103674070876518912/1293888539680354282541277646947380627241979967611883341823378331667976045287311988103163380651334828012840330710760757271860219584371109472132211215957402251594055009937397184768184517621978947384029376766290498101728971145633139541827544539988344772578184316843734267915665730981857376872622787627370859411909330227080697966353375.15388340113525711660227566446101909585796746979396093776960989868457211684028149502578116456785221720682202816140911944661051001675127262774824593420825587319436537346311831003212424497488485098543512314062112948777572038731823948224734505930748371522309451168088057190162878224801232/3954220582960831691377435160890656173654063611768428458807273708040518769541211737927975894584024448193835165167801976423275767590502552964407494549049777006346189436817215329891530811451811864579644894987864267389290848598289794977382504890216219362031324635609053075313568115234375.5099039333987561374222193551155323470675617979816941646196895589439391685938046865391119484510329634015275893520725135141878751153360264368353595348921951280561029028912953500944814771064409611917475818956659775131751121312316084465321917769679881052144364834485866477379437705913911371481828140817759401117780199246301705600020671104/1303503600297679371136943454060319958680553228879031326679449263682048703103464872914972900105569835004878963701599765030590097739639045890060548760692125546754294514068052902543220382104483822438283040090444827980927544440984823535260277595466339403795403200720622852069244768910603820007632395190204569927612348189089161551951106625.4902837141334073026145827027361937996261324349722726869116185158777439337041263482852376194988371853413467559557923410949898048139830183335197992754748294810838187068126867611615800383834975563313220497573778480109264178673389149671194149749735833378557143135481387904961537942569904075/1247045310545991266291285730016853118981099516935251861146038369985109288084420528171217942065832292739130145780833406014673689119563698528225048800794718789218267628507713621235056538202070171596177775095071513194885568843375526804796016261173388452184505503341132236719484809714335744.38114743522716832107917466438257616720476488812538316101658139632867788464381862291240727309611460187159930652186486096300862388591521625093237019662273764387591494074792574929490381910446287947994150655077877204446864004067956087975012773988833339521775463977233068498404144221045837190392670308437391686081418318624745039402145439223552/9647001083383999453668111809775451078976046488746916070976218645431946648087171586252172936600115032316383427265217993193444199863138429602138841976586190525451324093772097241349417938578878934577091671046050326087898259692917931230974174799815198493279413438192301437068820185757869608523761456160341754512329264442115351926967120404125.5736950552252257270088037307675189064907049959291776176462756468845557079609866254819441016227084154159888447400287180275544526623589579335261
263373824325955904005404113684003841990198157072540659184995738719040024647370869010473254071681533880576462368600901824622431045529064651675640055917092/144509482511118816399089096021290587489594541280398871255876563615464628718527634679330291741479135415168539765887291789615790513527330600394937614433502341116068305347468133950204152174094704092402978083370792135432486240914953928188835819767755172666693219213868545854371103120604946200875.23876960329653589647925126180903391687666378233201794403339630995420215267415575142266707357255726330536094448314199602616026935251126469221925945960901748679919435908556550271504767784553484434363646489174587463466333864577705745452492395785557425904735048180164697040313528831173448025400634629163795223739061661461986923675833880378496/5986312408594306954013526197465608559068621248896320652512228238115589875514604632230098997609482248000888567135685167138762172475788060284232459813998201719590208742091697294562538265829954186149162974972471533202880368317237508987477069872431064075005305838801862900501819963793062041081601844759452202282545840716920793056488037109375.58168289917567723171226992383559866214094157894992327555495441698028867727845766488121900626912848698952863438654895252811583144479300382761129433911280049009362667380001406579175563745824368613319103673817094498117944856004415812877213722455299491145649879676787079744410765053845551958756701/14517067289347903655500020160671113450349743650636953726251191692074385521975132268313263723831804150872238173602847065423463131917373356798750100313145228608894881457107689499956903046984443545789053438946050974567665049237414588435796381674590098629779384355275820782532479708807512981504000.728621890568281859295409481422447012528302594365693410763821707074444799793690738137592101239862736313347273167450056625929591960610208335290882047413011571781161008296084630072829079783328937418641417642857196346026366370059522990813537731394823630207433267854616768658990289454635793326766697884798538576055949457122067828153655416688640/181030730759516991863708593747964787874073354051675597050399087612142539517308720603687322924426591889179726492403913356461908748733972707460063017057809060190437917851790767968877215795679844983288935075688219234885360839984681619084834228226744165610073685719017596630302462070188937998558312507638434329299017584329479516410907786681093.86855946923438322218622470067224691860808273886184997065663554841573982963995340977083049132518812923329423480393306918856650577072525633920456721265953575424233701929892019410099166322511413146891121248381648145391642571638857576890568882512129960291171866772665863159474602604647289052079991768/21485753507365901947528588896402264670781310878547726104482740647554738151100954835784115119035980523529677083504495839730499664052882400915208251594384038810917282207449860876251558307288700200910747338758723324686939379138206117634546981163355060740270734146780942696291669461182599512320099625.2158989152301022938148680102142188531448821359505188055264665167313418619665693092337665573150374231484840948447637297247277576415460889296724813940128955070240137590073233263168835678714131062764247434144994737610229909964847568491446606012581370840699582055341626266533733744293929658949697805855362114229666626620766245630122333733703618176/531794915405164005613733454597931482878479882704956110685223892325074211694837836221759995948610212818642789132749082430059593652854659130217225506942675608692701447738732031302987802196501895840510235161825501235133794449421919927396142470196961877376701957829921152848178076410141813926924749057304222282687697297216661687583257901415465125.139432548574396829074586704387656697097760057897628994548358619815052936481650396157428747411173567801047221928593253479330480454469358220685854351236980383914223693722868233819483137401339800304943891968050399345430243790898955416907228948287367356990263740207046902209563417267686591994743547621/34201151688775214071963206765436083445901621442002061707492082843232231754829227303539041286301398668437202547003300396162741375435703188500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.11008517174872833286150985180322584448162884832099344969609291070844193524816852920942383850580217443209402836100467940651581092350600329145627967515818684442171571156446321228596914355704205623857871497315955269266498229823278800717909321269179839084452384509142712677235552103459737790674103994445173074670347080506698168482564009465276165824768/2689223396936080856855299215659204161946704205931885125148201643087176556822542895325191478283706585400237901215485150928036895428721912118467760766508162631903585126377676412573187912443878232521444786090510891599171741773242011017926658231638022943018461086517502584854390836347781674626615709751386455292026775663545470794167629144456268750125.16108638074211260588800537540680707641986073914251424878121255234668558067988171568946079848860335948991834525552515669040163026131919804987340113244760738846884911038097907756220945883750502673899084880578229601870882631165510396775126850307838505063922101682333806284668762825609556049426829531780/3919363961344261777100658318137884299575193089462944554282218278496298610828757650104922583359642384253066896538203596057302203635134833545580869871333892935330950583664400555463557735723364497947986885146043017010159347046389604172186788902608216894094289769850517098027486468084407618748895626853.34420755849180279597302103726180110022640946692592540634353734157479505420320000324260530767186132260970572450489530034440214259559325114511265075416512316229177952140217732655405289808326341696986755141965043719344169685611217958619102774617224847284122901023774956887687026904767714958090256282893003000752947427857703259704682455375442735857024/8342030311716679826889917494957593165464748884572298173556257652389845294530325764837124998293398445804458613956489096007564811101361266196542129764287084823604897187311540561857741285793447174119667215803837719660675298308873496219385226998078648428368061868944322478384684509466965129972030932418920415308276430355882329457342937549162000252625.345888075261020004071220843714060353763382280664960929903544964118831237876694384053904571498830068831026644303797377762345709976595360421502594656308937649239978525713471393570536680412814805076323426256584504251728507416368609420882442293831684681071553766603478479006495757222912500012444787804577811/83505703731469734628961395063481893801938371516752417759131774530720075262459158384433785006689548434701904106312038822969658455364219435022841597243178757423598248565463985786213156556523685666430799283870548238467817226915680747412191245046634279766450629886904716776719219698922088211154187845632000.1061717830619177527082296723099890392273896386613997004874669053445943252046748251883532634529759169500795452576392700472771365240996842610207274128102329096619028487369622001737128463631016494371635687841733644339636164570819431573829173533941056258744442930643735587780907310433371453992062647737259587563398111688659657406089003293576961475848704/255359631537215747979895955806995352799574790340218399351168178555478073997876110889483456972687438702262017800167048243754141722496276537685853311434069991222324039005160057724073156957530106623908696241268268096879569794431919729620178375212905203484165745866913773304319069321426245521467122472046370356725530914587807274074293673038482666015625.274122944106300296738399632684955400761495830361663966466225652918683099779465438024846903286816813856490888796372134557295699980528187779624865098445756013563535339056233912394908544185885547842235097677765325396255649207317018754967666450708249125316192200151505568416495274671679500594656671785202496/65687592621976546250581560102201535533608158256953087745856906437400149205693427285162333502528793675585022025602144243543064185647792948495372442630333800126269123531636800213405254045262127593759539706750242430153456891792533267948231185296091297979933562727112487057234422009426868531651634706262125.7842680480716516803148821198697967237136721860017131244266974996267074742248599085253569637183007740566941125452215834642683053334607896723447140851344501084122965014242091312411884985569341166545074688756440728922408743841592658677792796881188604773469108807869960161395759837407978596679911066586626885830991556090978327508459276025943279064965688960/1872528612245648675720382138045071131304652050696842872529163720558126655075937845539792108048310219395746259570506175902206215101518698490144716531697689534559827422735649881381597761684154409796315455445459537515308174919488497154409643876490472215352056502193150125644288086294418253309947229151074464928874881827227706992859640236086417889990541889.5300824422251242070074569186825929119848111723012841627275830216301188228660779008353049
2633603527567784119877706984722171178137272986345560485784907345500893648715341273841147320288851034078863843374665850852481747000237834238703248634174397792745914847774297223176674917912406659831206869442510948965571661/1261140476013707338477604677428573831791396352814802149994640617701773078174882455512668089072441176857892331468691160991310474734143842336092636848492066592397892638052212250229129355009939118431643425836944282456647571558383755315238500832868535816144280088644939696339160092963629012001958205063168000.2220223718762215584659309059880106334425515875615107369399767892051551634000614327272260081056973863669004224981561870246078120862256383581012183852291444462730018546753183156982897386563561418424093883164027305254176874653780425452987066512563140531367766900610414277825262239199580925879453806414860409441845631158680721091621460775043562065815179617536/526383206607841251253861841374779803798480623722760367843070466043030228662340154304405180907941079883976168609082254331465595267209149963786388600028701073430773581228212441424400748220833542964971495005714483235359479470452593264280645360131482713147116366500300066771223383007216182988263355451923333319170174755334598973202740108032097242475554128875.521891797109626296684891455959263713257353500867652268541535940159815152120871142196535233326890353914761242025931373491906127275561002910157909306979093246574207104081108188995072105948138299097848175016082947174156278439986705241571619793059501724269644447572323501261424770743329858038040685313621446524/123310256826873923765604825413207481739886340225713108649758575106598510022338480189649787216845041382860899099250547657534972156328080736149239332330143771138115695598493059325064119176038137294863053148618656356436332991079150723235214278848602671333076219529535123842212129829931654967367649078369140625.66086044538329677372986118727999622900471937619891337714357792768200341519193500393739322894033303245376225584865369486696276607060432449792893028061817203932068085863800494054274423512956136695211796751845295921015953538329385253280866669403169919614982155350899648626481405781514434761541281229159396787287553493046927448595964103589100429722948913403008/15562137339474350565671240515273666798063901504051979980452491653975250630723677279081058884163396938548780856293034775459223871281049026140999055923743471466471830572672766633086347312178711643724485955576579988182546105048041649947277672869613992334541438784737993706482731696809943027528882927942967419447250586964258807454003775693567366165507144866375.335377615394100148751647837967017467711612297170079949298328061159559939969228226474615711044891085626519877634842694983669611974807129333052471799687426665556738316626171408219730853872410792831871526174987402129691897433888027072807302411474690613948951673562473758814664346259109886876538510453475290967835/78715592752271462306588358880337347638000605031000575876214116610339827495261512281635361568951675037834544811575026718101166562072917855004822606752296233435017284127594847656529606648345533195437635894948829857913798336356647286032372695130461573940500785137424365840081503133157308796505622439791698116608.20090879701618729602554170716780970848925039917987945471322994867171660307998603515745066411687983450400412739285577269751603921163835619296822801840348319742203974023505186187060251544248644338412667631232247108675504629538319425769464277309915502144443973397371136256151336255138506001292355330875114245901820438821732843540725116728866301271466614762497024/4700223519410528857298732096729483544820841497820611795617923063440946097326817340637303431283005509904481323205480729806879570430868897342398783028649633951362398196137429076844504529051072393709154483678349272930361110568616112723747726853614661953537957117231900032044221535502745676310313569997665352252492568100075191900969170979460298189170486601502625.2904778979985524171206573028445379872240558084236464200857594814631031581387804621371822074061289363372523364167184697785570324832815972970658633551879143187709707164796663015180877412717910872234647704536817108676736661804878068078543241390828229923424191204586313620612539678930999769543756218765870513049986792/677408099044823641581658869221044375312077929976719183424865834811543737800956896926637625166844372424044003929341361734886232742770909683021563822987505236295727478159938135467975522336774471915167606673489722102077041330652185811196423400701795791669780695158730756241178262962515917389382302757366325768069625.312701558093297518638852247324543972922309690020049538323540653197355306249962546954530618514496003459776464550725124007605397470540038512895403394258486818041902844512534626637311353377750883799544037400580849496754604459098263222978175354006041803382013226671390625002692854934175630953658996313609017326841249302966431085
263351710704785906431324876072470231424/7269578038000504017073007978844992319987411732848567116655821196644382777088703228960020894756722675887473977480537577509061256138261063926845643360849217556370868752909531088361229374467207196928745673402380473721018157327193509586295879051411183657185176812738231456253321187419224704301236205478184115996135940848503487199394612616742961108684539794921875.432538822079707760382094121020421735679118830363764570640789368235407853152380328891350816400541189148550353337874309885334920995713154225799660601389784410911658967499100610376065640785585342035058364676314084595283850213942576431310823836792440218271879354669291052589804956435743500204185107215929849054782893113/100246574739326291035824954677502591279343311051719151327066341370995390423713403739043396503785261917771859220535505691760472395306543276314938287868734009582906895763073519374099272340577921671298878837400921045252035507925021904954445172372479744465666760762909731237634082051855588025732494461939980856983552000.1914333673689206389116942789116917579088664511118582610293383428712902211612554212779880638065888518488492298586641997844141510832940409501694726851666478650414191249534733087933879981733561565249818572204932715347752949087800778646065986244657260832234479202201129845117955957242616947361016603702640821256099895469088229339240402478576285854783063612307200/442333801076281757298117784528962837115323835962460661601905131618341609371649347131724700192551574625400701487125984359494804828935577124602622582550626336986871791407398609915208114339012374456785705161994343348351473385887949809051796407340988735853810174589261300681030826392672282630613354461927208579993042968520650313621522933214063366558703422757071.5704691626402072213006354545292364761246893919997531024861408248746241619817955824682639582830486790618668221530365426203424888737658778881721063941495350237419723855000515747725926735319471480027293210991869255971365522170749568996651406002311020883635577590045650037569906001924971041810547543163363976464780729932/1314240362076792592671773873754757443276256223533339004339330559325754574023619698171225777585408160438834449576526997055649849875516310105297894855264038450585295422343454458568152668980131977005808840141079502436391909349182185596381509091427752151860204235071122788499996991078935216686010888734471173124487937875.451219364084386208718456142329444023337343409261545444643031014769484085278440612677813682892926852469540118625738238137458321112005189595703619178533263706811689687213128887082197330137502064260105387500552856851972124172206996205919556553246133218441769325133725631665593372188755090094541462474970525820334385058333756591222492801647110594428922046641945259392/103648250172203340865458115839764297558925693061798169434516001775068769911768281084188883278842546791612199025413573394167639925287068809631958006622842716869211374513136766899877504136929177267362862319748507372147243911522667591375015611312165464514308451222180272935398828092646393830572838772085366567154646425598388620105539619174837489536378605144891769625.1591076564577634575701791393842535460875733974464805197283632670013516183281542903377750304419996681222758401497321278555686661981435637461350320471258386388843198706277657208526372100698700615835733712519332548607115875288787602084336341594576426630670911478276101702119972195558314357975365863803265163991961173/364433108410193393847203348728981296285742202617988970384277162225847256295865554341611171460436362780497179090329831885853324392923449579538286804729856000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.5307507148709435807261229345132535134848030343901300324623409721698217134932866488937772986386501538026693956121121771089740095760486362654754229904633476234090792827930433598453200536551779789049352131005222659995845427680686677324963223653949277037520711609343166926627713758990384011274777087968799793410506391884872456420041494598273703914689586637995139580794368/1212244290381524115082005575105703496583315188540177702780216570265159923654197746388568151706509243638302707511238539845531608313334248788980188054651601536067740709977678222790481348003085034888244447626347312094586389347535167903408519024105748523384932942441843118813819781347089702286481924493361058339731949844620763272778960860509570622673048786968660129650125.3046577098843580578619955603029073328361298436129791931304665777036152915858575282362742008136721284817899542475666054101957899858138590963789072530710775790433466847100422875906866496318804986202089528198912098377828580031852152997907433335176267300286466072997014023120087988748396598176622765923059385876855303940720/693911859077752895978833241338902695755528613729508555938416419864772385336777924892434701804078893822446727762077537955240605927550548046309823051841326355655848406646248595628715185413852040295631448250459076043816328082561248420925930431777502622148019371383254316636979070731427737764160145097293260938978413488819.155310926743873343426312607182060072939030765297630534544899230213054714482456829198485999782086944271490229412707980997432528653509945301574794242118433868747172279224118534460563400440670015323324602117517342201640016853927923976796453577048995243600967202462466681112804476672348206491490513419336308575442086511015101999847896197546900512764233674747415844045184/35278162986589659300679088538176070649273991865663041616088851923111175518405117391134863644540911005782372831496121355954470744169969774540892096320978686548284501139861783292226140413769665461494668479430833892857992401391262903582109993838728281915806394747833588629467613308837196269424421131934859079260185052081536487462257809987002198437182539441349474426375.46729591025621874782758519074451728476386657576036360734358719976400940301493939192083339293779149127132651616972817165172116269307276487158069293114860391502484125554406945249728802484128756924044633825692779783425628292959170597009935305429239702926898931975023598456207165067568919757902764815108751735753431153581849/10585868084079030838651390738371141142245086465033459640458366146849314274285871375459898014414833295804139979016362796357043372316321872357817727821559232353993714062535883074661734509440994664726425399880995133711038483607773782532430879196405793694658185175583691180757783597895616920432527125993118171361116684288000.3736372348124144720852190769710129461145889011598636925228657393934132828633132357232883470466940330848177425542748100211498184494252714616379450272611850068867816250209867530921278645286769418080018709947826876461419654782341309127709703626401211996255743831998918894661053669189312375159058718767082163156988766821194002596331826150321864927832618126580509732359424/844176851007504003627016945212023239308348428094023437269532743221937069345682900884618378849283002998220513307273333096775669556093005637615012750733216460458689282791632437851364674879152695438589692227159038555722539345972833161146108367329370564838671791241431125003401861887477969954740544092178721327724620450947646209914621007186497081420384347438812255859375.1258774755828991281578968023382624723772927642002016270484090409043454336040857926581316994594109169123354553321469500848146015719851609220423736153365139804086413284787598253618361769125996755159571523632747129480387254164008968993734442164892486441152227433281625391753702577143985047832519062595123255569172968685060844/283659859661671181526547833415653453506477950678651675193210969173130116121017723360258249430884213011988678011357458727603413521688184521573094783291496368005697481333739504490647194454695504722542014845706216224432373442438242355188461951883454664693262684873988061018976711201351382163527093784753398257094429403691625.84932063355292829988908961192574710493098897148701473172754949846455626381329456661808566365329266898990829247446356970454502007127269708487563279536825277374133681167235811080298134899629580318813382668399644553111080625918213250223197440426147821225593304993621451053135332451997633132772608233430131400186571793929377129211228689703376067763625568623535588709576320/19089978133324852910950469658566458037096027722326716800113107848115231563787455584278193954518442601810776347091253561956877155673550458955562102935555510392954425196165785410319126098393353878286400877305164869548380670204577544630353859009177051698096136470072137579698473017257397949994722015089768745013713383769765609613514021200888647472804720456494757423299627.802638881530832431828249604040579750916118423833791608589560402449036920165704012070349537114920882938466635598602387718300074733476150548724726460209016834416094317724261857969955414000155807312852092720310159572547644569797512233899495300028159721348599816083166712365215075728968005941610056018023633235372936903015771583/1799511973861190797324386174079215350651405030434291743946056529138799824860516277606521974841425474470005081894551264938682295656472843327355524625255984651920735587933359130054592669770861043596210226919310024880527275975134134923935256602729001613756
263377499228252863529934576881596384036401784035248649026076581302370304000.25208742399375362881099811032135575360109715964024747212026245529087599633280142314962581193303683759605084995818253124445773115574470717199218828756449187055537877478033129862600982068782249943150019637186466260707552416433010545437321814115233841687700051830170191107127799355485920046505591193770164750886037885397478191534797655616745528343172318318678405576430544896/5637713398995569614196397857525646325234056219513202928587580534159596897880731043336790273040813044077153051260989730372846713618900145444802234629922717464041261370803598799826604841654608724727320798324006129524610666235998113655193642594744544226880944882342204407750193512869672849910003246504052298022468012594459974209940607450480609190841893267203392880360823875.732332637178584560220688900268566130246820235956768724845747830959547501950765063982943061181526237061809052444110437930100210105274824607344902764184151030827266142225894655531497849161692760385938786736436977268616029862577293984376170905024712952813234949508186306774257035535805330366742322777611063402455261391021097128/163377988152179636922409938163005948596822656868040662831003991395905185823836089887990201522673196719628247106777881741843786365701135555917263285268753605514812568258179391272113405920369587922702002732667842511108732068683407168090725712401954314293193572654347237716691784386690948494003094992876867763698101043701171875.22391374854299462107923583267570593886002658786775211597896252879708753450794332301142909715845151746786016535157797023153041007263258732991465037648536702217273897876864351559736449481285518249846264600935543582562018874574655740660800634883403597181876364712521253650744197321080655028374602772696770227741610874399454362583980465225235674816785988164157351243193265401728/4983275997188967758382167867656806681565521964135131710678447245984239733544941881418957694612909599261843693554043504855207170782744518943778096768859337980470219783210191765678908537645270392500777411134164918803949155037581108678968701961544979451081836872425574123683574475790997414488641534074873248802450108535183413970057319247033379016606809226547805269752123746375.21252344995592269775107236774689012760750850598567799560343535731251766780016530978663079386453430272698006977668063208502408607227544322945446079708000304179073184745623740466334127867464883762843346619853325415963062181018736410570113171387891518398846617197097407612852037905687899800932343156979591740310928257766081697645/4718515378484509142377558412184183991357747235892194234377932213613746008373918923611236346330189287336493794499188640380975364991548794341177060325509698404571318037298112293926833877103554546466055612498927474225619680186119313129604319096374924037870803554153458104225741255753314955115645304948564151765516183663634546688.76703085666560609319365659209445044957052359500745196718269665234646121134787807938680787341023203786904308047981099228357850016602203539979246579454229078497537148799349353250167621935384193502383187510928609818011142642954550330069991570983902841318203794113898871515702445720207144863877026526025447819537396146822201819435536435835285098485990260677737192230985069824/16989892821104122916312992616665764943723222199277412857053896319814438961475117951904867066845412639236790762432996309717924037467863024360211163971190006272168845197000304328480920483651558672879967350982199768255256753110375467976246339260326422891913564151453729285191351273342206198366624882195135056176502724912849575385576554208844814085228696838834665339811027625.40153831166521391225489894857551838468150576827129133168972859441122728710165233865309084872159583787083130713473702296122465319276461991457173085312407612757280915853584698420083436946976844240063731333638150599017886937783470942007376523947840104246927580254612991191040951001539641947153847776050138532219595746056076776809812/8873576113581065493273519627544307418139908640325227196912114520903505426722086265723900326735989771660987609604507503750212298754414472822477243293638486047313990878348820573874809636084574108909615044524663712495422565151340037564156235745628465172219286664653343193162657374410926171153516871765680561505768223
2633660055617934625.200736374277835272485186523480177159453030082779872429648449412313247640312479214261681899286513818912991945046297334418102711629933437654377760028476767482162031641781499114859553677502002901248124750539270235098492377826240319766677856465093871367817683734079621359186477306173620331748496369122143019303740252461824523590096923561928354020960176605008889579578495073283712/44259440065125442964014453739391594153290923937737136823355312892557975399035370631521014554980129291582486968083228888083079118116286312583989433037097397252506140224404130371160608365777625538148303917306340620019882928744151294738308047800711028158277500317134537540772759486365658024194428796846364486187105343266398338060080611643110071184992193593643605709075927734375.488459049325494693259159444507437983381645757291858092983371672334043029615965882574409808932509285079401239403272414271652617474184321852388397021836909585659327974611273820676128650810907598106588433939541654215766888212287311943387232664417347883717203611092450971786083806323404432266197250919880225892099146722474124874256523/107455855466267410923480140898552598306699341366032095904938430084768624148829473848763761936703072253841751966906142283640379336131083461646777390874405323298406517250231389493084918065243079819898691146841695350589992171102939046740169198394671965069747042621265775948217054519855346617967866614303497258042439052681849864192000.8430374068596413768975326329313648683222744787097373111477788794692418932056901235174019333392845529821722488982447683794746518712070635063397464904489452840169472596494433874412726723065560358405027764015273789053064830528919091414531400589850704395887250756457780868677553068164933299802944396576360356896758745030955907258232257358056931680617626606715393885378887657377280/1850480358582748412767893656294669486390769246349349706200869446679212812264400876685764762211659843658541567071977813110496329850010288179702589501255367345935389050373021591572539260951149696801665953123597521983257852207280970577287472932167362521740230973547070264273850381896786822127290397075758780174083415923482640313277341120938690594859118603017930500014640169211239.58273615882491925540881784328370957720539797010816130007322211512070634295154626813477498607761260613353633996451797686143131893884559909668805628269959901044961666535533876340116728982072626875010391195372759135469446048394835148654407846242721443845351855234347422256700864370273092971804207514736924787577569355949601385705517152/12763172138328432984573837529764902730448666594097466544652830703737195804747682450548488162227364538052585484418491914323658215406327363805353540266048943197822838925184942600367647278764952826664684839953902567694832690683467635727409976388280092262839126779730168889686628630302519063225007497707028600865624133968363921915016625.2685278694947152969468407055109959900160804835228466214479525891103128459065131221736713585038130737099067040196326815283171857977706979990467444622550497565521863441617001097354649972660183038850033950647594754644997436624623325003537308428828750008305464174443210079059253920383411910911594636045517662796811001285984447671371943267419151220518726940455756833040934506414133888/586864816044968996825907488721678304211296267371936463272955488077666796280028127333229453342355554450708284934221461946991556216095213627059047984199091625921432110913096253352065238765240063555347292393427726758010888546427415276046238297382474708612526770055488323003698641493939145624184943388159614111350839555141202024991876221874110644879676602924730506882384603409121625.27700345710264347957758638741952394530538598225904772664391173119594616680996031886665218221392453628824570256438960349220263575741495285780845399187013582169907518462437966962923592601721119258663490655013419675469864809004562272799012227293974254329929404036071055528766397079743200179924243479370594973626764330855493789112414191/6040997839051213541001279276287478343874107660287651711609067205111574718442229224212245187655300348484144001298428958025052162253854676210451657425437588244676589965820312500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.80160269787574270953020489212619791839643207793889009503234879683494928396231769167082355143564723274576166638869430572977442020236299319718643894871736539109822173538266278165276591962215927816541165548699380129014840956895931285215480350321259054359835472320394089646764361802445068798451796525897304221529850133401768027469126408090577121172238802281079916258951770135485696/1744495708493645555507487672180824131165166880209182858991131025370951722671588072294826797756038143630715234282130452507365137976314428167891104727638923171386039279497545351810705556876500948697301734147956015479234088878033702948164604623396792328946814129369923681519655381937382828039848896666599409287768086064326691486183763932260776180474025692042951843435383987828087
26335.2352816897072623416220002134476921108405735955266703519252095150412419264317091785317803024028565851487861978477208755211589867803009700996828082850796103789009194767813611798769297617674631277847910238088040257037678126316866517601388289837575778165301828137259948173292658462765645645868094197736382683775415645307647043205988394700/510973411316690313485681833991645423802776865720580280058344111363363091616558230182669376841383375321912553771027107891991318313938505988903735114191313214327683449514676737796942389784957658395806951715454372568523597420866050825822028817422805046287798054682484158011143949412956697442991898914560191411624040490122951328364833797.6403295584873165688372907494046202150046769667837790834896334486679541887567517050446119511695248926941383207478170182650927368177009669717288184903306689332746127845953193587519575304974203099873732502605739219028995266139383163062837007982999189114810534856227848568800302527760100163350814120545587074865568436789021082619398126713943637898657861949091545516403987546145915409024/1387794272010111535893205703999712437783041553900341112488641528986385462810448493444968969845352401058333929711237978223214186693177251566069419805757440174840170213159651962686467523533938145629444468366235554597245713128812532716616087753947246800626006504878203666972651384731498770435755225220796872155249202960801768048854869001310722927230237083418017482134588865244642658875.82993247683514419570466529457059660634483860665557779709153549045427987672829778520201315148149878525274005978368939092115193636113741972236218502664881450367443614971109677363668874484696543982239492409231870942414193419634675024621942196087473557914167832058111113476295926250739099284241826553737074679953551191767148712684157318697/17950946423927357725787689855263532224005643859095168852729513034456208872420513601894508438640531171097082516559962755244698695622824386001219435651555513795509616906355363573638916895074349491513539093024980575852693293474288638209680085037286354050958859425647536735341886663074581909148323105020337857959651624760873736590065664000.584891611376763781852144397260140844977346305541197362434227194779766612939978629636198589818106137319267243431810481928639442343946346034433828599323416877248326356345631611148749005937144684862502198147087702668524450709118588741606955966569427636630159793409544653944608958808602551061186799401212712216156799273254257486955348236914237644151956226336750212957092204830385441792/126256710861549838395499078249922986417488985866522660521294610280820007499099176190820291214370699289977888813109514854178180265382471972583921477022411657285850911270389720508719377071949050253246021921916685716353393018411683757067093259101151481189635423399611625009617884983318141463140199839724797412514785751549277231259345923662499623640886881048572831787168979644775390625.4743054867460856425399742072925732465660626340183690464743217147109403130730445842673866624947360862438925194786600531200056131309608642363389833474026007798643235346104937733349791667694862514383520689594596660275306247615314272223660862212527346572811422915223417783887717426641317921972456913534338708745549252254865615725859881457906376/1021840037832289788284691535543138164288462770384961802287250236519983887262771944174557087207566030730743075334169628971336358708580124427857321953981475719503574867471090607795242192417162791762511940848493176847925838738242153177311649130718886794249673254183907621449520415060660496225939963471753122766421338241291756892571824984344625.3784664074155769467702999785016514468281913375341134899878893061325465790589101335015569840325786070795267055386681356241209412947116340524588831510768864231937929260236754881829005065056310226407358204278658699999612596866156294195316867934035877283950841910726224355461522065773816109849107487214275801829843762482082803559183694631856772777313673086715631547326400170962722842240/813783281473223559981291694175087508812520505931454895884442580280342455516154674683217348039336712901850738745276445107477919518905155156380620466135946654952837573797479076027688866326359448543065305071605591497778941561986579230698384305536224430794233462949056326864499827444363206162251104552740175503996670997705423888382328014210171324376593090187604268086334796245552762333.1946671258536842642381655747294621776070051525209940130115769153666368932042152311477746728678182920842238801763565726086459485050237860693394471644023999467670017470376746609892484192072297938254898880354014176373253875722410186683852253828299669530022166361304397631667133689128358365296701757782382475692465977794960109690362462330857/417774039698408581013003883929127512062321623871486379101498968145670269174833505080260389860863417408848209525427705249526516766731427603641806256289098209429110794311660844125377702016056984573671024035213045475132134896835814746425864304907974005950155657789157496389234919107772201305672421982198984613601511388413381215220924416000.328578487723377153600821813410631465225159589727320893988991729306688663770697528156625398176929288628930496338036815910669579019719633124832162035588583242320537435554101841406566009219059042888412893352417446437227440076869427577701706713564212185163005644118869496869980925214424591264870388237079776503547314587137721633918824664946974571838634860386893404364499977966899068777016064/70382695927096628347637455030970644630942872888311870124896575877585692281624151103204551947776906510366521972834357031777287506848887607457751667816514216907338309372900327919413372044625602555866294337672022362865161523684052940126509854895320132828009551012639156341878073682501185688461720664801829933689280752623773789373199210473995823367199793407048741191786377993390965297664875.2617201476921368517857942326432090876874414269689140439151907982631768946799200744678055980827789859579196832718849393046147656447672531861353456343821196812881882023188898815179947651274
2633131166835133965629115749368441605680383605331300030886676081418867305170012032824011912531673468215561506423833911621270680104083533917562622600478548/559567121085534865189976875600841717161617153776904752351231210970240323460800785728739412474960421770806162360125774000625035522428160837855944215417821324758873127567654244465281354654299068546570789547691342609793050301258532586131013585959164719533123826201937801986942606844854123769532447570107525081084531848318874835968017578125.636225736038986537559880265988431731529837451289737542395494683393492040808565905376235074534207026537145408562785279823547657299565440309510931336394031904920056464959974743525662459433889398003683078967642651812081450227654478095420306880762753401111260630654049389197602389949892636943971690212484981672010398108426002137114819838399222096538921225458913266993881960732663394566024064/135776510176793971074115131648637508758953050390591773574951317807919051619690313331192027871176160424663811116849856489187562728496099757910540362703888937768555824513740118941387831822900198029266206334350448626733139136083404404120210893986654422850183837974770675600952078956326317698998103770833069712616832650406225828969036781514645731022616236082175582937900731419575337473384125.266695771933124633677367149389643417608461366874310588884377151539325854547826373711099517873721616543570605935954334944030816383858485296542260152894035979141266909050267414072982042090341712035518685997484257326212454742816979806460287972757626105526907510197321350895873473656215941034605746494172316089636216915825022339855304925515685/56811706665210352283362623728191218698295056176625217939528332247537278605113496147630185544004654583441448319260578659922931798845493756189402805173037491645434052737405379674607517658118427614090338938517963215812444779184193933749520313676564187507594274551791388039139409235056119788261689087831209441779870873305232021728002651979776.3511806683161697708497547617957719390189982761002154386881580160856792742952365159764830433511949678304281539875366378131195670004345568047690216126001067194904446295336734931691743477531830892015690816210752795806120303198745685394015161323982229908105397857791180342330098240702332072396030780386362735967021055250450666535422528637737695053315137238368787607412459874094164027214953984/746741569878639983491390741637813989978804202898438708743258000150996080386381281307609038830698579358879333079215327202911977568726258527646560497079622703052765164031089590965199628534477381843079892123440214378949632707668935001371616475282883095939750704292616758568964786737752325652839226013335092148777788733453702438432279149298482004122593243860829060557386699231448957232420125.499543951252504651717279461487337168721376180441322735807713499521878076780205427598086756686061009718016175215146305489885835839673419698751530207404115002383180054704927695269921072232395828258826213554806570423602966743337801741633869267620843626804016742412046844770601322513184123515405692795346790813502805238635003099976693786012816/106032986203682550514602969462803214831559442358811656484036951559991322084935692953211120289352600484987931812632505499612220494311324679562152078883141464406938524087376964935494245010636163705698220308243980789514815579319533341929989455211613890905485981353837321342730307819060825125980500975023479813757024395422041501208805339176375.8540849722242122835873311629952985285477986765819584558233324868363310302206006773828897816547299245727087876984857726652932481899766510637403577175623031467933486823994040576431755172220921921877192006685053572215922347418846423419683723609799729359551828522978186208983138345476801247634773975311405913274552616037005854836040162212761099347518242200807692224460514057530656658616850816/1809694575992816440924165741094996511361288430727981159314194000585536832192004274726651828760263522962868944612215633976203596150606503849595633388319338251977160257979846235995654357082321611719654136058257458753105122024859078420173515189641515736029725847315662215778251370398007468665986604529263071981040014321717598469319370651877296085250322599247141397427185438573360443115234375.51377057693118720457387330519321684810411289582445982078756989158447711080414032055843805733348558621949380554029375294451303430269197115810494758213980833379214402452992657502777067850631862453239349835215260705131864911194740832694498014048717871429797341104227759557199716944554347879767916801106279081864127192611546757627038037780244683/10867246748205139797826516105458406878398263495890048637741584969144406206902037615496936724683237700974333817527350121106320991054058406504571347680049945745432432384570515723033245430148177097144850158758462968940525568041926860856763884474605057056550146491001458649244094211354153171337463406192651150028767064600270112838159624568832000.2517199821548153657910904242290029026229621935918771922146425373057248090467388430999870036608278542449661971830076845113363443421757278612394167195431759807908413353743377586893872930828548256216510734912027450642648789925142482023713336937258932978503310551945630359646777080073329099268529064437120002567758664419443374110941824106727218341795100740316967386497091058915066147604481280/531524260324016969370728057738851340792702640911631807178654723224511108065633433027773388768889035083734041289308124943130099580765995149865288328550751289346866467755881013217287175392101334538392596956248952430438673292186779006015549928829953979591250274457658042926539541422697852390294886719770034058916886894408015624288115732154492554105512936468520265305162358665491880968652687.937159485027553069020805864547349554547661693803137696125140510201297417077233061462068930061915381468160677500445535971818609631674361074587732183297
2633775728389124966713749450996643183965795829780345678634356741756033039293590264355732129789110416943789326482663579413229893878422643110852069225671783017610387570935863228248464396615988222968188/197552642195166614912991396771845374656891854357948006221100585931656016640982345159207601253599235265353060942313995345483862152489766993442419668492877390774016299878943454249209917002169480134131612530977452579520564400124908392339263545911443803619972765231094502745980083350567509014991735227390978850048088378721210219321877150756855372125.5119346675109082499980756672052066247676641510661024682574296075659671743397880591881419516307292610449161239233139088348510165442597278965718490070997173182184417648987611422446347235659085092530927312760229499083348217392125906851921500360553758600756698605047197529446594606336369425040236883171542367713951500007600355406492128741649090501989105696576697387613035366083536629358444229248/1077349190930018641197987339365056771667455373500846354778079878558146320193384166982231171317419356136237346389570422332278447217033773023556383420372685049620361481309067017697564760747047839930422553324681218253359586320952896352245366885171583221864112040038531116947187482413031483309534553461613717398523132176948321964066833901215878133594739833910960843185464241840039390204295097875.58469980853327028628854378052548435225264353747414624620847476036979290604604988637469977624105451959796142112200285366199247075503424204044884512269071061176877225315884188402954249683107639777479663275428465242905314418930053869461904934138752031124685541853599407727446896558064252696813370692668496452783003306386669962110734257851955001481/12284458784412533668960387046583440199646081362484321078872891438551639470826582933879934711861551014258493898870867541349962531447724393381011633785884743889445407749238183080941846528000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.632694338036291086868292541736272151517212971647680989553388199374739841494700315711180961760384484042159533979873604395621016272772109619401112452105475906812313548587880899058905419220497456502543971131226430775692744506047039958551641270070996110661036371362526401525207493270590999387476275629412687473362310414634469788979236895300129227082421021999210841384596617452097273320509348159488/132710874087075221626157136110978536488168313127228703025408943153782802265472978945703742152954881438058373686972477195846162708986982742647038014147903817539418442869011995988024638278746664230046452545499722614320284478925059527086663455478374200352375121910000967044366831275681254530914306064535110528723482282501358749001657608122307686482720926189537227492041135055090784059994118192625.2022422468242151190347511883185841333968390991430363660248687284021524206079162212007263606819387821055183192871951076644707111802972354128011904720586729919826758651167984507804867954970064938022106484656560866447290934136610214175516487579122328055482392137619829739560923807880779865442016530712986750711199998190148885726144596663143651240/423528009127070458603837580844559347493775236970253513203186912091140251858605354218715508091394564000304400858761758838182654201653901408046974668599216804223721114331085507752600832390227068985693006017591304916519540245902645712532993889000048992026931475754508248265356181099817467608863068068953756055334213584649136541490530849577363647.150542201776735231618709653388506394887777837646651406023174643241783006776019388336318216053045300417086929061565868663031237502137150880313922488106751241006715449458736723129545400133450376339156062387859536289694727635468338235084533552501618659272047966040838509286942825414463511175531001410923014751124732748099355476332649458471135027773371541572374016038525336728276024676601778299264/31475618522527975728853391146702172347290819252268551219771201846701658848754300838383637247014705706066050673096278897933831272607774110183488615338021656923433335661890414740664480671162459271850877855521869741833030384682549648626038314686632195158507693321505500888988183270276134667071014075017317692121986144742473139078857816578133693776368882596780120407949076129685719314703426278875.162664351499283182546788129866259011542529017155637405328005084357078048074065548349602626724265307733005745244338982661090506394708170105916177679714664432754153795772811389612700051002336719842784098507498286260450939289109123759859710248621544296008356071415713931721102824434964336667980062728653562369697289761913925215639430496443820411811651/33956433298509232632327667206936379248172049619640091186698677954874297837764235300806836350019565970550533206216590639008637925266405524715041372407701947953283803854153876844320283735281209725651036513491246238622967031979233265136280687995181375582844780830517825595245506321879177965868747546127685256867456319112247572348416655367667187712000.27228583713734183629451808889147559240254570554044667607519238865891084165382075658707675405673276615039702916443152954157535195508033284355580742761569101934821088036084480297442018005972653124248838420021440899368869744141698556359295489470499243402799483082406238128875386939389123336303631993557844565927960009744780823166462314116039469622216263221278402673028225214534859076857413557466368/5675134787340359276387085910732530678163604187009567576895331134521132071092293139167824957253050637085885426100206370974479279292804959049999647539684766632278449357893560561608633329561385765035738071726214510832066885156767060324427330401967034889966727638276371320401053302413136551142103678412692111973028587922399670456670380189570979581674699102934733563330382821732200682163238525390625.1340937726818688387636018677960518622106989311577445614347061615417831160296369500704524022869612973331444242000788110133157689786976834913297544087249593601420972111789552905846168933014570399562460789075871112224533723259660967481288525220689577290386781169316008987012566216235876842757183233207943071523447855623001920854571597886491163165150556/279054368814522483241446594911968519760869180429079780837994812436395792594449929617293503975169489945136244602350941695478861584261665582123038340824700224583170270427163469762789603657025958695551448477050958557681299495041994050951692916032501884523150972841782658389836059236040091605838583126400660344344601879969354053137568588338096589095875.8910951660339249479517731530773509037034977353457185453617569046885132434552771722727442649095007828468878374139001808825741829728375370140505088133244952288239619141544661695065318568074863317054989982620944602245967155400712702259180443238473885690297281525960618905625084639870407113029712510345262279507055197024677292523214467306898573956604928730377318210588837126450942086527893437954864000/1851573255256476362977604759655284263358595254392797078730401113550522214182030016660458780180636930591149034499142464357511158868625309442843792189394292787657774627425816694628839987456477799348874853555586931850788645677998004186437300173080088839930384424797706381282430208961565555953254145002318893188197561315855286173276564036402546798318351229978103276843822345004757661005876638005274037.84997663352987536417038496128111159210386455419431137931308301989414462311135708114322046234708053448098538629166672456703651524480738219822858469100454933583774404032968304328859365484249897913676382909050450855222567147661842184538302991526635974158862033287154321908483007506326807469239745851379559259262425675035790574846229470041596801343087041/17634687575122715507915388096857069366146981156897230620371714518707518105157483283253374797127075689236298114335734874553183291806268149747826050838089931351158483980735336772879045027213982661634865556129548356487722537193914986994283729746578044621115589195066212043187229606921062007047940293972381121200723292297716621231320254309060321476608000.1648849257486312935416274009474520589799750757877252390543329851029437452988499485179026845292068377957697884739052491455807688429630524210823560524122596610276957537756142278585091315141096146341773982302888007751632401090642472506538817998043326415693840862261701364114923327286462650797963969289743571514890723145251583881752876340628073395708716735192690808352188867334842743895738955762067968/34158041190296214052954762226738183442526489322644765872365412092054916641611484973158855257862604159784700294610545981223097990048013542378771782569795515219352672402989082961584531476
26335605770060975538542976523177976182401820926854406945392167140347444433885786340415437006775075196031433365827874254477351374236932624514469241634422312990555534789607377023339236417434574755566856489013828206625.4899626659231633406569362199187192352933567344960498139854460545644210119722856870634652562532083546344965166340063297647520613455037240144734014575196764021102614748218834054157165781057405100578668000290493431869797883155764963238760612333048336953434663867580862692267574574465371615023999531030446250351305046572267686566999209229202587258144318592/1013522377571209303732207048597964555261512342860326827024786500686692475697570284120359840724596444209277948648863014479460188496587721578075151793081823795161404110811480269106846359964436993190293615381593756076515012514100289406862487971220020752628653845345780766244842386136740768474703009091552043945843632199999007070800871588289737701416015625.362903847358088423032098939589019598036593525722040887883164115981767777873860799955715587436566233010543937498922435963385091400670303956612881974450548904906949032005878241638546734597308786514086678561900713741746905742866635779432216761799371793260025549698865319760786921444505323758235164807966277024031605673481480590193724980659448692487108892154809490199414370023696404259691299614147712/74959603173756091922435708504751461448318819548943586676159545028063979695880930926805574951275602951047845904770828900645717477098988124553474616764040938121171776556999069351772286262529729056288451037717198273521810585868307402693261479298923209587143468206907278220909447483738730657438961435587752873879244136801168836767273934997417156543866722171766794171623224855358640156858606843576125.8521348154958613550574095745596657249924328336262127244827955886474742319277424381360677655239017583606851483318951440691757875270001283229585075137091617073509041644097526047127618954293881264113694362598157456878784814696577083997902588926421675843291157049153701100218784481406086810264243143337016042301806376864424632290226377881206765051896745/1757584673254145109614914862134217345456065873908262753169404848658913774363650863904627183104777337461445063704655164325930891269843669860409763569362863600932267319335889540453302785099532688264425988677082044905948179153286276609910158854349711054144968131934713419772852663860893241364433872853338630216232313607969790083448433666334742108176384.1802461420562646993856730082999823508145602238125054717836501201545920604020389361370931345491160549787411668288359013059160331370751496329806488246135100776263777863399096485894306306621852596694700845918608199329091852956315870664531614358379176680326508877329862713333336188556181470928613423972314983964578645688876556351433429494008513812136152576866650152623510296911708111085518974142728903424/371238439252064016214448115231139360835481920731625321084601566992497057371416121407293286027832357816257507287295719261141426130159269433199862002841433235955835172774430690352481806933860390015899973299268361513643524088242973968537595085600335021120523852420135081643310663869327371821064862449426404044951571585406092523478861879148545678639697679215289523234342337347529225543852787599016265125.88795280670112240977945082069219541902481768504536167808816453021962616596410396813316064685579412429940019071114917828928080181638058444302439626425155946562362550070187433083541414569447612195370911498321149367969974762244140788494955146280201020345849385865084095189982291190135293114489407801749533448443222584092575861096946605418438181411489276/18262596223069549313969288693970246663726147886364354584825624311486557881239003216971630599389642752648815377795018130449384513824927138566203714891090017787258920529990523519479383032564209629983810866231367438270859421572641494420831435563580050954867101292568399107965982704216434467243223964964535464624988344342084084237484262612100980519602625.752911409358158070688133336918078236438086521781731735123294741731669530734909563155732092406099003582749182967246236657021875488130304108082404134004381196925042617909108654109138702993903561036987511410396567636331465803949049946947888490287210013788802287247422993384874670368649616782837096233384279817294778916419067404863458318451722971117669642134894906235066332205740872938406767767019265664/154635332883086377656813458754577288834216641577439356891585125701020579768315520324293435008561626926046988056302745604248220408154454267643222328696606367409715369481567213640103076112146615938180089303294709009813772509602954514391675152597458428326644988225555987883250642389550531163153338541870029415077982539614784206119074702022117790679351778993541426110436276530890609137713909149169921875.15286089077439918584953144558775765002061832952090847117286473868694909713791678395221438112006475047633028543501632631679316850512797978594476229228325228403849089079675681042224057234415951253954044235099139983386056610384489202589484570852048157272551098909455253037561994944665563291526597323199530997923272894119350512727802414680772513760081360291/3135161418037836259442831302977219750614726139657718770206960776514822107155928800694375522572523712277389679035632531727155957120566617736817225541673148354829212969778664144907503411589126111888917929495106029890532891919001138770210977012708107496187227751496980000137223047079127096028939624830654227758737339725345681745847598
2633157538483308068864000.17723482381737693269787076798246423310802126092500438681864673375704464394105734049099094818738115345706100191580982712146882034618103161268453808819471603805345990162762722549964406042295355916458624836894291267553138041035528315839108252422478610879301656207772491548742981990469454529537049123948604931661837539943536878260665617524824604291547373872716194154198824107266275716083848262625068958720/3630091565725887087605600771358216927099748013831912080380983545872077197366172619225751217619097657405660172801849926220948413919823038425519006413005998509677472226729295278652284861834178791332630676772284971762683579047508016687969040658592436230062049051143001484384767836353233324570686249824980508520186643477313941054900197268584495128610811273834192099099592687485176400539748616360799518357.39160514032490258389003214587901781721548011632821053230881239001436341012396166857515197251499460842954863342641015306304854226194551189224721257664420778416733889030680295206179109679627522113592373938602737416822981698362363553492610842201005420727750505681358595340127099855823746410663750133019743170700888375554918213182862789028531284364877435896/8009919337434786244380818390213546866794958389603666737562053423775386173149395943310276429895991903753441584557917565343673605019989336264748588735390182130334278887642569515202100870042209261561001627386525182096090194076839370589780431326097965428311786635366819094633651297179987340498215947144870164066409654464551017761658775207392803825996394875.18188388167811476762477659006849121912679763597132233588170406666718758511478154418948855160838212151370453213943784067796172102916618102024199200086478021533171984254799008541948973652219533819511807681148179806051835318645591102296256347927018942348574774821478499092054497390790734798143983945096982240517058861467440217558586822663985584775920517755909444876443211404222400335500608733284461685888/3715278241795087610941547133490827711133909145414878217965273061493740719983191775105550559905283733134189195190321643965858771461560130864714477448011225816210219450040558581571206711791272284197614810026220745160693898421068168630870850392739817340370146186703867097982858560347971281142766235850971837330222970900661653800041795020382847588362774677568059355238174402415384788280852059532958121625.46353430636874284402376008361176880938798775506236714098123916668545331718677407145199311191108199195405139575147933283523305343027297808443653460575141799729554209181454676876263582758919969948546918471128299522715691694855904535448703118221685887195383025133924852224568922999317583667985459047407473419196367812949579858081181660610155317911318937349/9455890179897829052705408931064120820559254220394152447502395298827357144081378513080398823188243663943177539817982481713456798757563952162598464929784370305696420245648035222083207596797327498500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.13607414211126412689435920170832779523235279308039712294681570127241403406455725064605210473923965685858012114332021572088551127762628892611459785625407107300355287623761046438724706918300976102581928643740596336865698485838431972050267114940079353996100620311097561405192365496385584164725035842307146351211183443267583872067352881387294766804298681841402861626441205037637282007810811602289501477350144/2772205947240095684743358245950494400934136973845543049938212403703005150954425087866758842625041409060217562878157900197951382737615822655863548356735553650755342108183641353142157728364469706919993519071329069805875834057743793434164720370026073143626055293058601124362130539040404491770346043977106988100969901297669523170508321703496903672333781306743488573086901583022550356345156457496396749797875.2326435009331569050713150072691440177163325960290489438731274227546260157478848557491319596785400988682443623774078991085184304530667352432461113053671980271791261560910928526116322000724149296483393397578925768175500205489045374780341846511956738931575480179195055330403466639967763003068375946662779712397174206186692821378045232584784890168279288684098
26330/4733430508316851445525799359992627142007028326865116523033957869609125212251136452396410236930025876982265915963089597825393317909648054808274488356887197933393799241941120691826916741647173843634076299630884655997401370400734954098249519111198509015387869462198674657171808841005212058822254513429836457539629035675822719720295352508916898476137111981397.538960934807826161927564251064896730663918579817797131801326848839524373936888402762331254883505157846659830555799909822861853145306547699817986010353774500545305596630924815657016569444824389893996399550343022444937690798126189162954188680257730893424775303801562327757655350002001080811866451425665301674688928515041429654624970707803336800125648742168380676815769457467038849213225206824671025803392/109517448833211208909213522579666376007937648875042608355810687327424621469323788799169718267715808580775296460944943658428295481347915131091297305260674731651980547668762317138753250458639043477453950774629862540017034566407286963562574188172753764978963685535201028286359818524519980885827473904574840285411260037264057197155527809916623487144493019982419606308144576939532055057697567269576800542875.24451481554350251656598350124163983489544445991992661049829014268366250968046589127810466483349378560701491445658725080497078590986743512397927747885285095846398852574219367580068049729894667374214861939897557930527646930793431512683750733092448862551580494245486308114129295467976874843852138144539250235632985676953662288536669286915983261820949386845806781/4962240683851186225340479316959605207278948397833849899236383273145853045488131674290332609876751222112917095096150531825255611911377071887145019702433883343849119017643117746273523770961304609989779231048095665388209125939879595509516490230961558353074751312876252070889983946768175488341370453053495319823381943793679003096504200440997908071027962806272000.166591964685609920525429719961758335887941461052357297159523350448241484106515158310298216150030768812873781356326923214637847449893575074813991141092681107583183275003570804134461187213143832123628701876041315736048451374824101256980832991214945762266748755723551899001458245164317581617731332466039757786839492869211248064662857987111284518155462148044812626055842061283907063784492325693994911811072/3376594346685975634723173728576851624074971426456441081483996601149023359800622724639692359406948849636899485
26337718734549787000213944990695920130591750377483911116845697231074543526982580529937081378303555262933800375576494067959129682770065443667091668104132884375840812635624862495548888467575848428463895756394050252457592540570490061561616914443009224917652440212112452400106121785938739776611328125.142464729519206642943985715465196065680101634264787375740459792619754842396453535646509170066091478069799080172299369994438836484938378991283020978342879057271045033903518255546705211647900945143546293360496661466657600494787228476009216508124736254967761901224547269496682078470378676865981855568197705507111970901389105723589666709580851611656838285777566736/28839643075889294346635430272525349651555039807615358795334663734940126053968249608601725991946342449660829847322517564370606746964714098508298705743689729306507554363954348780144675937510900983622836770223945538844314468550644543502501484521561567788992156632892028591678742014134130878101553633195551605796158103033794695984958987367799607407626319024034625.380457154857422076784416625436182734840012277442496600178664323821064977485271288502806124740204295811759917468598315932331219906040253463960961995849761235911145436552991677050565022181516596464968316292789048809559129516930574340710998611088996508613850407294743457197519091160170604426002924022923388338999324182261954685794522778833029950214443271526469607532589775916381786492089432407550224137344640/76922142291839859196033215395526448408989799722090330866256930898223012427332209054699494033511478050536463051459450844520020426942553107946282832072826069342120835351421637970462054707566481086202287686453371483126873188020538661871147778312986131920021929455276187425940666580158173676284545586944833678819622895550345083175685846944633982680908505900099388037050135210936852210263717185637166725605577.79999800708369666670693340813609265988600461251844239982904928629083975986385235816587497657678297663151298709076884516168798694292862559083730259839524968813932151813233366175091317046758260934357096757322369138747731224414176608247605314668045838769433811781490030635374856042786947109101585097035794969502111354126773165391577217071956928171336060247633607/16154850265413610119312596299635391433380319311682208755390341659152160578366244774029302281068833963848811596545791104919556346810193385001196395489740571188884873246131813864782581356887110499639544662322008824704830818136660544673293865921754569356583698951612797219776290835161780326945625621758204931298948625885081325268123344406261740843197232316416000.26517014004241498798848003208133111307300592620947908933072661812816683085261359696887064436611747292468717739609776825664344064024535028242737616786238200200498291226984541942836459188328346609549239724653950302145388877472274074665166631509490297630344351573245265440164082334092997307729007429218385933622623935704482371360985836659823269511115937443161532987660855490906546130131716829909388620539153152/53482575295300735242809892575770508780332394868856647773409471024170778756282385017917113368034185036160429228802188602666115955944000202061925995599251695890233392952560845799665332608612495296701418546329652314685334487093634771204372774776681731499582679566544118223
263360053335695956270719680086524322530514249891157439878407417971839744392044064720476417844056346174795601710447583861127956455406902139625.71197348290771978405602732839537012310626009318133570890482364371056186523989330157966045289127980687764218363064941391483781008265266963537623770685390148810455244349859354857421474277963009857011653865476081389968122418691934354122230780300833008753686234433642072919923583176333668289998661499146617277981691372057042930131717336250309680764289256080895092/14342680993892886303954853579883363225921109635079605392320944523109187641283117181461662846411912306480691901515655220490850586434947504504317080144378185989596578890875561336496479576651516902048606328604696610314441229321219627021610788398730173161473456954861916116391687748151443335513249810808309201830214153565966339609616397865465842187404632568359375.342401018754023891059352629509715357053454506037284788725127073168445189422181540408896452651232759821766616850264122591225331120588918865882061344322996688880669665450231982002597398732201789017495427566260651180470635467002453249479483900268320570004293679361696197905823690145326531180324429318916092471863347575533714871355651558610515931373080997536792242278529575700808878786732127630024064418468916608/68894647682461956089382461406499759613691148650738957016015844830333168307020284281532026442272618372290646283794122772122665531108484704223311663270836645399554940741928358317884620420886609705267248656765357348477857852684140561714900614303731786621656041881975328169543884661780531057279582784036689401206706069028229798913082362331334839997133771880514515972024899408556517159759907883793675672065360125.190286571838805495686895463752492174798162827967490343625540320679760700551286395956241059969689020885714190883323266375067607282890063444652926151862650426323339187596278760962390404656342309737428214493422028545912504503974763216230927196187743439226243880933947417760147785405444976177822143722569696182520826218120595298059020305548681823408268556482981325/38242608291912408815838081993045123864617058390583394828737640036167893859507494091864963383596867701436244007905770284939991912884465101575490548813894148831966132970730263562113961685364216989999844961688441914455435934703797359360780356482629495214859917249465567846934284121032247250332634283689409883499295469118485912489058982596725212975311140618764288.15345379701153714436938289567639102307887273898834051456693981514956329731572600026866162286097662958712922836383881840211072389867463987895894067288699955858337488812343674818565432780224654423872618380928462939482247900055572079914753652915184313685270722583926261499687728814560680092231526501970431280783177357735398580700300402036873780385926225005561766822479878280891130232036389707452005183370152749056/3080426623087819678602049171756961824196425548529619576972793653585089380165862889092832375934535464160425580449193072125955685099151500755278763306599307218302635233595329082702148677300945556130106197481236122437978375963261172524503625593066102601042060541617791008722569799735202779005407381267021641545644264334109052258081225159748043792288699674153722046659880085850980843460715080965607434114275256125.36443601662144279337033484452272105547257065463167427418525882851507989449375452076227652634440476502702584889057376829320548464677623038648843251719168810701744338735202853412651160681259533015293997501525430222870696235141468274274064390273214484922080219643095978640300874086585386991338440415203863901714217818222666715642467237183267303214471854472286478344/7307237990148312451155090506264642657872224684879860008436735430879314349554023096366846856470375025555139219961666754780864835035902856314981482268319886395881809659368275720375576152008289949085453326722156553603358879420820012964006978808113307340321824660484441618487292138631579616351777191144073820686595597986548374588839763719082323114663844043046087375.1575294930860663922843149113097927168024893739962464327016763741314068438447271326302129681931564068796631337571133444163024224071270063174829664848259482066723104251718808936762938249028582992557822551950212098797718627418782376027133576209718376784834456568694813577764300
2633716139817031545408608110880973380162736536313173329973171844528083756524804574267826691156368696436273087171467254161930265910972517504/315498546654512047637461608750018349421492986465373840347519942494904200733840189483934245529561231604050629653992944140351106887747105945984325466452136415067807666316202346895657914393512001212656936450425268507235863153258769360296536050028695266363553141327896064944506216017933135251875087069031098099192325817395958019524956320840925176589616439477134480262100237057953933117460110224783420562744140625.7692057599553133417225997786980128299372439542315125030077404519679450372805989755158000864378924877036225189784045171045139667691524763609840822628706422918926410377185494048355128046783294954373197082851501927410350313585640237550107070936498164597231431242858771457898152684298047446530220873884022213114819556822050178579707210264243087257050468000092842761/1538814487241112760739561704846381585063002784795057066438330325566843108114787083741788078680861495340026117682606689156065008672344707615420501964123121620401073675430690541617930520947170306763541251152854304975131871537939618684186766168376514664494488691311397307418298556185724993104760692216619178358268934740746932420562664234738576394742559349407744000.15190836470550557926140012263310230378455340797095100474720776113765300081463960235506950799869073894127884189857505951314428810423734978025409205413789025720642609035117121385453856877706229778165533034683130064865256448444765902482146676668197546098809055341050873494446231793312407516463576380102073171090898973046611572020564659042146465345334273595086941562425006763960197801018796906114925005810069684480/3035556598829526968124942916297025416522606357010637652635799096498208643970273828496655227572100159414352020909846298817521082538898702393916708804775798552206401718323929157863173504795127180177622667376867235806208021329981136637175570409791442328468473111768140746895005561471574356889047981458002257872092408771959478275534098789982899056118498417649167444480913552548249005268380838457505944462494874581.2923754549090941424546974281011770689534961442264350984393235983189168024079617848190236639328676436485460311093391982825027512234467853098757486086492333410753919927528867817406389678461354257841007722472106464785557179844602277350411593959136520732862935740433163383885526249897183805981219416420390137516812715245569037561966929572448247077578419534651990827044/583599691615378545100950777601104007812792435102945248411439102112424251478512952087517463400054567832353967731887062349496616445419782499817548928078665212077449420216892583997505908858360011413290038645573504472422610780073975450391707084016931661068694024023083417126286468909117254531307085545768412513447197205482285022417611018126886491416133665625891075125.441922815213568908489589193556560586318864326425397702047965372289295962228254658331201274291697626694859414786292266008476137667843874780506886929181835469302142365772763129838217316953835831059616268288399119642314758261677639945004547833810080700127847214666763863338091523753898362699222880772298183760217731228628442782431573977490761665091005756534420789258276075174436091798475838370152192077494553263232/88113527373573049332749294663402406454524640221866407165839162576979477138694653404281889227416977618913249275712917582743426231744980461918772793673202077716234026090308791893409200158969108910565467273725064769890443408324386897017825489615600787634985397885230455168591240328585041836771921929567914891379235573982442311269392541694564675053636078990836491104116280492254795616055818375774141667319774630875.91197133767962483852278456285591810579974783077874307589555559715577599604626819245000672929518645004771085106770784762994476973842713035791487204122653245797126906189270204029735872508462106527240320932458036231707311992868347221176460407003487373754014365881209649632547685657666691589606571865740595829983849941049450471212387808617247938941417000965198123059467/18163679611214677813643455199979098261849405189805364986036911945012016248297645596270602508015864371788974684317239728239847888960155365342460843559658233069613218442910226128113196984801126248862273503232000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.73339
26336724434554481470656964167233690851279923085197144879644750437402627936723531635898542414136943003236478432848965516925891956615111678444586384493883113385335463639674699443808084827715994137410743992130712903997815471369201406683862985677774155704267039224546352414417632475628136460919900347977754644214725932476856018335195927604771408949980634142255497812566866795799230501026066145434755838336990365184/145912495644159810313026420025053989609942265686388630266226856650796088768164358961644113076809511566125145395699271530802891523741636707532676065833327082092521989958971154798465784847092870457944857590623097781956884297103961713362268264159015928554707158239398721416218953003215109202771651993622244788505649098445109438104466256408060944298437033058380804126574878377874459371251056800895394904459469832875.167606423853658713615749101123336326908381619586838606922565378505211386185130407423587264776519589295420758009764678759213587906216543160801059029133457062067529468464636376639307690657945597847080706144898920305379653754920571797771178341550808041652360635584401789901525709166172283390177673009483341826911179861584213314395893323035527116283758445038413646757280/33310364848744488727470761889861069993071965180756187311178124887286133554324042422503263994717993129539448310743598138364172889305532401505890384806078790034557049074169245078416704866867380089103064821732673967120808611636618526737138435792818828990403374766228037003927569643972203993263329403469747342204808360947840103843317533210523853631711601450617095736473.22466735478643771803624909352181817912387732117378538284107485621001246177152644141853604633676939694208131243081227668237716194316732125445041260568403752325416203858329469477774720998849334961751541191761521224644520742691981372782009394826739249604257098248751626957528543558542443122470657230835176462612530464044652140581367666271771882198747182114685116336512604038833327707163107207664705120728068987996560512/4460342260599110071819142535903990817893424192972341872394014748315090430999224107274777695306032783105944721337053156074851240201179902835353097683269298594190456286888326067932777720561181760369783486872666974623910515795208353605697065447942804414120030678603538761538385793829787734830129764152263691296719726909633580318897787729004972323599773548689272008712427926734258913271101899780538635213826239542884125.1972862002066252798837977155272535342727415329632252213508267781390870646909686724955861608046325765650407340102472833428905279473185818898693854344138403744757857928883601637909604082588338869612221777263582365745419719805587946558326048087138197694016224613118304623864709183681172362693106460535117459192992832969130895829916210933710820035479169562970982784580861/391262854245936198649509275719624152305206807261382621390946060636032376057385723427601113233050260359684153963520782285097664628279596618521963444574543409076428660874564026651742234728997339844161514273669735686516761239076529088145208958938384732800586298943281728435207452253170935715239392534815683367114290676180839217919539381651841151674859715992309727232000.25408691426286653276004556426513401767718328640048945917745783225459709487487356095164164652218100925888847689099153320777389381851598236046402124684511968385325107497047025485302333503075085562533472482645023963717347867696861885363417595298751490212495932766872748125111115039311507374363000062513977436921772096443948159289707996749061007112458126301618769295162649600673247799961118662602756889448152517364992/5033870770817104909025512331238419776407331281944565644457345507262881100618908405924951559853352841154730802006750688581603270849880756026262217651685813584900300357685874044482329601894134443542753690048962260914642678445058891387041919581376195543193199307524572671344323361282633828144708683536721118910549933336800461248338059209853766305058943888965279863852107507075916981165164543199352920055389404296875.616565940481577765011174617619124841631603944267256178093555235591208387588894068005162766513720546626399308168923904625210748051788652328072241494243040185611373035059619136712559505023703153194815611268503291295059648269772663939137446253437248541496631852986499688052678961495116210133458596866684413931188348798244969797973846568160999564540652111599082181871436/122025682149627484528651507368051367620578469392233875493556828623437869650284356703295836998178256875766319508797903923638967073687991229708051285605187358616531926112736402511567721889845693991963610192161413692928378708223712791930113386840109729368772998347036090902364801014045328348830748307179590755723160142468563977011700764517880467116766150322736003147125.979882056834583241477188686550561625289337025747787132773853690143359657519481397575561812727394470125172272246774578404543257210124412718725081536309818383310896102958167337333430555168671327992395916735022711297435263157670501117734412587691271084981140167017421900852550822579410636184333142944411060788723653596377015359036101170054828623669169047118551010102258802465554033173968468183492058271365801755986560/193732066620504775981759812703028757608600125742477178751189607602983198559778039141192492589734277739017909889924488699372940787977794555519474807920198944109549023547259912324279741006975129518191081373554817584214941629021088206977532599055014150433581544599721903881284581257812850697423350805715586436114842183295730680490110793225514602133304729484547181740290534056445482186430729398701311563285494964645419.1138059441890428903336718712159907364975959482163004276901676063186939296217569849990951930955270849692775077813359573394435924934540269310629731801376134549169322946310756738187834128956671195358413024062230774111935109203207768898525882417078119314003162592087920755572050993355843681931139257303484526223461840939880759908449181135029327442039666513325916729112853/224777393704985303260433439401503507705148576727364388720387174977154204629336985298082893443205223017966145098064861566754244624732671470935725326043491911142467178027013112527668183783450932992534517827863293825061296257420183
2633669383719043873666284378647952385401303733274771042385666436214517205678674213118374889121542369996042313879258622144464565403138392064000.614262617634904509410555695398092190166323289787703954329113412647342230855826568873946233136303566178604275296873234926652080462259552775254755109931312516616838091852915397846984381183732773411263828600108443070778861986849272794442105107285234729077818614332155890946804257724112143631642663084660012362691100872465148864413343598067567142977134846266425075195546265101720326272502009234689388355365794889444257557504/121200854655310345878069155190734381476914416893031941761756379148622591310152793328910334357724762079139509813381997287954319983165971628429295803162563856219211627796200599196263868781937234015821367575512548522790158101892507996780675863234181700253545912643548466256938936835469646114659598727592390628209362096738343417775009361678599075671154405137663077798419897932404104579113056038271753988669813988076515476125.106893445531995430131837569895703697604978445859412739331042151546083234373443601923983714252801103551874986033841637079479794895452077803182698291822629713500021995241940133037200268381793282318691568234728329378829301282121562652452936297422136961147432559766896143081059518238234777055931999714973999553456547746825617168005650221542417216291412324174772893635832/21070287546583154895102927029203125577385528350171457634203261197137238923923245382493868134869009844094435068284335909266152042903157700510534904847257436666980671067329084409346149729385625108233234542133838924281113454526471855573271066865534480974484196644173270141056470857666632902827625475719738076524047736123182255306429677688129231682978570461273193359375.1112742798776748551928744983308584493817112400536084744850969025063360679785378789764875076529575583792571198510306186417773101346425704969671256564494135750783642910394213727189639661184379341961737135764570942961692159177189753139209638929302928699705042832922774012622017270172331722295881412111812933593370743210214549038212395941675257558442878012136484052827439007483777859391215222647499741572327725689840850048/219121905514652575155579185322367175400669386131891843382447432851122462422992147756333729893028362013318264155489537138133372703295804002840920402482110260590055749843170064921843460498824128274420925357547023876488939786863662801268798987685503391058250902634999352652063668663245829496836853509616873246554292796823779397317819134891873583857621623143253788854530146303641400986028503534408870194989478421253057625.983995170259637497940121707857673268620603982844439610076334749792119502557380361624096960070148627663305171311646851566811683351232268240169848810658089698606409195744471343416197434926513684882439596141368794175162315633192028977211909698595778839497844847281262559899914504080092844816319298286511436690429175757804604673752838786852277255064434365401871903307643705/193579499709739777577893639665643417521924510242119561765932078835121983190401762561436208758210519231103767232899529457440602166918701550386152070813526760823513884391055054076485295945972185402977095815609448651316824455250005505410192101148149284756928250258632031981439345164037318129987999546683113483700660879431801728391911161900686707231543216283304182063038464.3069101307683
26336380319652884848585431917439358375118437035944950498156836885409110087616602043242747413728866747975631727566613593257623099549583001362246649928075859944695060947434885707102684568632559339383409378997568182445019183928058902445738702610436187907199482604867148445903921474846103586253320950728989228898324829144701782792767763794895137313050381112872972806712570559942583906619373159053654481250809168128/6031936190594376585238407905469035598668211679521553144958053099463931217856780171872253258738635531385711702176347575597387389685526098889278278029314982721284691198967204664771178761416891317672705719303088746953644978471289001577698554025410820041497108311270431130911021653860874238212040640737171103823631718483572464361276703378587106311153455557896527384426327053165214814954154328483257657424873929502112904625.33633002641218571027682690377239300567277297301791434890431645909447040830457253186262970747405514897340315490970846553666201190386457221846694126637998462873786334837901001833771510353365825087187582807843940479192544772559118293851131234910638705258664901225494129023244916125545283621607920983287799648992632814461828998517949449887522866259724675318233522060729654796/6603800575190864815125307817934327053530311915572323544225173935830559756077637251538096164499112411672913910767032482188570876526606118068929913515497400397562722669603861813453418621246538114872330536044519242663538662076583511078523573320035084744399535581216815034837553165853576616422592790103728141443697362408727056813977234078214386771115586436985105038873998875.9090550743395453237608373761422705922989356346696677314277463900103283296889488490217663400349361962695279888433677856471792856853109469433355422802663947305503479561493033851081993247556828544308258821557994512133708656174864544457143793106703578476914924328960109390350040954158797845288786321215010324565010420734044059968931558099077932776525974187717655105951506223649947806568984848883258144616897526257038550656/1783219994432430133950472014582130883873515063182143523712063859964133099770763874744121895885645346884371273930727450069430704145915261127061538288702855011220545530326588799412076879985026006593893648911637986337776174555198865379578424838210466703683642106934154603710587408512357351455891557594977191641529451749437270208258072920514602243985184744955476557012910446023911358037761232253615162335336208343505859375.396226087129511787616470716244996965529391571019620342657409150252952330537366537352182763477820160355931003174946109480036915624974500187179367618457008802667089004678925595775249725629495848146669773574395699032785024522882892752987825063933573399691764866816284097232869198405981830106568826923407996367321353003569052419999880089180418759265274331299787468134974811/77651132902382550540201641628906752945078964002822585000619340261128555048628863996784740469908853602590877726845475670110127527874088625214912598995012971630852593597027649154487264595100300180591016581254965295280089902497540043916128232871685159131211213497239568483141031137909208031392464815187505714066235868748950184065923236670418822911614780061752905170944000.1288523130900767412477856952035690867153496584747510253984686336382980221603917538996138294311274357713893956725672062832264871415025750136690143411884111580335458539824573239771267043414225271729141508235839982033182605445173050590151912297720800168687369852280323356691345317649445843078291369394324862039143247087442309135074453265658730028145500871559458519282433012494054724678302957276371418936282902434203225600/252284450515080370603949213084529993395050575951188044032908270470514999880554862449223347761507020354321422785760279154913310488296485989979706208254206974075438570521939826124860483842758137231373182496438568202110337751291106165654945352183167578675508602832478752400011567482434301614269579368882858973850914513870297071866544875650189106576672289734326492492059816669288907018095832842249738081022227281715919357.559506782175368748187145067236900803925823792088293851453005882621173124590368101213652371965740365119375069053747415415684193092607523211636912074219215053809881814859129515591479780669511533619258835199715146655774919418434080807837587396115955105126806762961292429904380132116986984435528307613054828929294602185927322238461491059740342387266084431988727321711184308176/109446188216864405154936682374609448082436347600301765944233278303643744736544109262794383069197271409398615846380701459882784547857821831816863216080069944818453908760476475874319791512782445408136169878207358663250499628002971644430164185578966399908622640732411885568638054229180673755690889471388585521113862492432946110902070139679164884208988489955874131206343597375.365842109776085256207829452385781129402656684569922320812625438296958174120084800064669048017227033185969596458778213306152397766619692644694641677223213185977626940193107608138827771259334379895020377700759789774994800008933137569543592829220611543060189849601828342989023692876182148818363689293009174358168826340010491728715549904988196347316703985894355217235339548078187164176255405596310602921647203428200269666176/71497266937783826306774367225149833789788300609530680399994804704196212252148324552193149332755057982662844988588678159610516634667597707204818296457616315484973288944637139939912166034691155272078609876888919170894915224022982785138928008133003473320018151370486895637936102520353951511525996197267572355782608352075229547764732602557133494648237258900273354364050662921889937355682486287799239363976556848320046933875.59378684894605773397070783936113244261297966863668546282887298999811950599772732377979382620766180662159460666220894896896564357533604962977968843474062092083279165837424210591042655271577974272394203253875965589611493384384257117088518521598379301169916060951350650621757237206805037261878212424267780312614942173870651684587166691539909068452932891649554575072205080763/11593916877920131260484148322810317629326850763057953025674154928920977965095141485536566217873796019006709247938019404840440511433467040918770165456925609124166970862430104329357419669175323763143377917913760028500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.4407066298424020751379267977324052680159151993343415652
263318443748798479563505125605478061664327658137598204192554352688830679475840386882350034150077506804799859586772904929402683276898098601814091430598259347980573084686932949502809068565420937301632494387691284902026088950093888426872222813857928092871267130505744095697172494119689779474840037266295586359244899477781345249657455186847452249040895151288114085352974933708544/85971876318334010542313048056773419567285701852816309711738644074302467763075671531248793080425349570584102078764464196653843973936119037322000695949209283327606280423406302517302874806092835694196353778161663338667091195199032831587897410329509487165187753418615356836636352319310103639079123698118997500068644500893282438137614420288839230827096109835206605385673197123994357393257304049093683934224826006704198171592304125.13220371178312284248107863849287558696210741535280184003301555188086761767176560823174196915070378763091889333203635784037294769747641959860810039816533609140662043493962707445564057197150603226797446933532133956054671103942520142568674339411250001585991743608723150284270101326419464088290151483823061613403673956918458456165552482913079283537536214967294211244361353060/2576683013797055224377707713704899315377379548630511095136568220145808780162671473907260623503552385384482723173913562423316997528913651044277418227616447815609873991028073011738113927961824632868956802271260292075825561646156680740323686126811928372672670917332613490241615850953660246271541592056143611581223295045062157404996958100136358649109693659623847024011265147.1538372578072246705266078247950089219881197139399081643650271348770110178217959856819170325400476655944115553238940541695152110949081675985299189913515975242840473616169775880272489805123124548256666658584129873597192213080038937409046114908719298170078476325423466734429870048697383304265342125425087105698152643145531760853127801123272389134514333752173173161562273487752064850461823726948588221913540799816489566883798912/299566102446745552813544808169323270315327122249327394279467999308669285416179486075255023523726449428151807672528368606071047812907935426406886253284580296349349558797128593446316786243666290649442956134448480598303527795996222703837663605600624271807461605295956674925277658331760000117761013381199880905748188151556184620779667670278558839116983636972680749836497346863752662521197700717702790359162307617024566689271625.281696937222363685333688097915539146272117417024070728031063821781398985795813333650547982965341298894634762289669256129805545549280355643122501181852136332529515756074502902204877664395456278205770206019663082511098956468724829475220996427130295010430751942126263620206886404244432409164651524408198286831329682605959881993845189585640874220032515465014097345759490750307207/54806274927935495596891312029173862473687610099325998583092091915101265393157631244775387832621032230434007486602816972765210205596482942091518459849775458089575743699797096697542306049628939919466378189656065461708686421130956996965004776108499273871055615413566043083634090083096967567965373203683231171594922347812966905149873265654962896456451681332216735396249206784000.228506238533410805238253122961471637501498406104430046727793420497895852412513560203475440156216063574654372726194215013407325207763369075250819386897086702757125418327084312933061738392406321003231853349865003322697360659712771167066453430309997639548320673279964210730701373707765051246595806673865646607841876463608039111252607452843372970797479959213447237540830563469297144446069689149549515457318899981763489792/44418759813188470246596822974281932219088697005123285598909329328419879212164564561558656547678211265529803086702843380128457744445765859393426675396393053094588240457569380155526179040891009717323059641035189017918495485630657360525410506453554255734005459614858972904374739673834145083512160883402151636664208253116362089211658645312778404886460203600762546810897889629330022309705583438699250109493732452392578125.2396110297187570506257836426251930521245117960980667897194680897478996322590925380310917400763581787981992131769075961259393685331523600287377841990678117113566991100720996059187144934569703045966210306282348527729533806882408323961336166190162075154579344185244957673138372347997134388801085788353482276257401005734929059700346687783400772331280644647089520646562669857652648/465370154262863030800729180763091967573522779260407615567563274096037297593764955820626213827962697601334935773802201919483657310282236100250543992334865461800976838791035335861420892967699843608855185710753433852279737724446294443337363478679601049432404435672469098850676302728116369979460222148206944323730586138
2633087862719386327396334468302608499235112520318322763857676375.1188272888075247520453568790651819187486389546755745961952033150576243575862120569399808467067800830890874391487822723879717525264875722720416173276963170672622214121308038530968291758445510982186014289745026439477197148445087614813262170975056866881909056450023324743409114115141145340480846088869807540798073417035168139476153897066325127540609756310068558610112731607522096096821938163134080426356894899245575410494080/230586762395914863625709048789913840511134004337945700368117795195769576856434588144361459740833007125516905017415184787078710001969815416281381427387949263792200577791644278234661952852149216540491852757174842146376788280677956350901082838474705227642420261641783722891948710833898248566893322144435457967452449965772543077421407816225704952270697016152452032506898311260979594550143344971416786595888053149375287120733.1072184299258468249004114536023934869518152618369895613271618698908405514630154819453979477077738526673716264830106745031385951736108376866253955319711026042389282009348594845497252059906901748860111986811345742998968284077119165082435598381810306691078037018432766116865792677955520465319184311529667642995217214507658693259694586107847099911341219913576038605872218680562047/207882129535607118520818565811162643811811563516006836924341123976848022970024793004700710992938987476728640943834012473687892481059618823520721737479364352887178017866425027953255856440099446112508663603319745066750522936408781591578321031173620445865113295407603090322283539974563690157418931060565698315406021569491751612761888641141446406531645379264720684248398299136000.158094023904374464057702010126993231151433474361820266584020400101533651587072432728050776506672527718975042616651177034635188178967462982926261516748842073587981953038445977514446838733557926696939591069712397947055261777416704028506441173540338327591514650398349069348381309688677335132100441905603664282735310299686268721634369502296867409514777359935022301425165750780988231639828675424239931533849896744198012747670272/30626384366513923671063955469537776291182594080083494737341604579575446319190916924682809546024369330706012653799783122328775875399363759308193432327358837772825609356553955350401725689682838701996446404559005896479618311357573203081153855961484398360670837599853294627153740224543175497655414585918231215639906924313779933211774291565425360415684556655021031131349317390382320286092667852173815259422737956767922154798375.12216278924286401897470540169822542417611356797676160128176706721343511598951866107858729405615631246003458062949723290192242594609994613705183460814797527214549142043573863947658832694800184691222426521703728394203722420336773310908687071670107794543022567943478843065246011544888390757810534211554666736239506503613750756246364621509359804902243487113673014588325806249988332/2364584127734680580481708368927921125934330000162935118371174269642831409084634375654239735054363928748162229294829526339927907778510530444646754603322373712788147193691037688552857183116332292048731726305451516954679277320777955342295564000586923227775208580772868590742136150431152495718132142742153643081187691849828217592954519485869135930755646768375299870967864990234375.578939195017447864385837341975558679292903716580114421030538728778491606282153588930983966100514147976321305616196463174070345884292672842497715966933722088536619333912687108737657068701352918582656105418491672377271304970407730786932913490869797471081081431072836814581099271832696990064828717287258860166842791984158634684078346453202928137987930328826212011774670396356151265781053547412633310327737900786639842674288716416/111966291649651600701875186827360807558960817589719096407887999108024557254221008849510152469119211567152616745769256123968832250104006560061907741567034087109512483357851919402017950812795426393415409198268246337542639470834168040295134130657073201020340432236723824670803498949071870597039309004562024033656488150406105175401372709011082725359382691270659245312133919518760328422827067578306005644825927050994860723405473375.8041514821545833865350873212853873042112343327573364523948780030849543753072688526717886590013028227714585965095216381829914996539132359247488639692828
2633639170075726301411777307168737667077730792892326979446426349813642680537699905651125068091362135055902152994216233622733424128982011248923051410141033146604688083721413402395290842738021365861670415833356403364696759583009635/1553937833499559104910551811592138833189892464446761247731330672284191313590708439680460540329836344767557599746234213006493842842879398684745864919973051635127080738612248150108793397855113122368507483429209127035263504194847798809612278864438287815470711036548695032421148125849669175729331459149833945183228413961985381338162155596008680906676498435954178226973272371625984.12059659399309169167301353842123191409306995788633965680414620302285606896146667751472818541537183787935352700725982053536032930866708413010971856856768384974849695774437178790890015242323873769697407411558706626105140596160049735605389301414460825674631122462760014451298494875244754354054447697502521388381253293175367558014453865905104467382184997528879171136492277222127399012368677604910497789360212571238146627048080568400384/2328494054002703067219004484782931471919751585969487160602269605916676223315055450845942763690581877771159615428854802721943114463834992106300185328876910271612375509166975628540839858771078495267566008071532876816826751069408153323840515037497664871689085370699991860738368371510578076683395101062439493831773194498579620513073693022191702398601471237166387045790480861932005012807234071429628725981935147069738988682858417182625.683009426705008850682549700382901603742691705123356866338951397347368059105140826655486518416578697931244347554322654428162554903861783227680935341690740579867651545205562690172425016836559678937794312287639193745517811234257062356826622207475918293015140472942579713388671782202262396642735640315948612572908444501108579457520714632371056288874351015666995549139003946314085696/131769214246522869780429817236150406548549044658474416909806179734873399109656411633488099249198882165279745627038984487365589625562901914030850178330133080409420340227179447548044572594184601425691821617928130423410997853384425373999967759499571890326740433081063424903098252502791477854302204200941376983295622430177445507316706609802292121282957519571162158620971952084486375.1418116259749091420309271913909337143756589314597557128553117870573928055109322864794169592355058370891251425125187770724828108988587888087023982451205475980371440423992838481547236638456717520835668859093413956339261802305597694403381021863258753441889536361061407579332570493634254542013337999844407181346815549594836374497512447969751514466481466717590255369810506813543577735080228718660747940956248427356785784199073569408/273368882980516556922532339653303822104510203916024760371844491705599093435133738774975538364241630079468712981056336655766117378160822393876348755370711942273876284944422610974149712212944211513462921649872232656449940987552227525504529710373144228818606127541937831103642415534318303187393593236209298242574677293352798419428712873685798636474667204083938875672934235816396371477146089168375198141802684403955936431884765625.546411077581845999248238069684194831621691193366466972898628141511422317954477211865167402284211971296286346492698354214043840080181702652132835681239302798339667835439189275457116051279366194551632712819028177402221815140045210690908631767786711675029194359998826252332434573121740830827417293557234891406021102083555472155479148332697839972702631641910213821827820374586459319/105246945889799140338072754365901705544530661781295362563214285953881890233987516230568663143342952799036341701952267011236663118111226623815975847494372076420199418712941018288738590264475520229651370015377608638075866459684692488079223686296541020897904588347083045723167762682959422858996673894180805702299907478685374065593161226849447131100462022089783265346597553176576000.2398330640958841474772606439916070050977544535580605737383995160447105736276950196885906408317628083110923322157113892928963237845914017845444295040924101784423382681801754191301860383927129006953354739240926643562987838836997453985855576402628166875869041032631651591871962852884189548538272285387092843044669499688035134181859376665409767886188304314888753894905317929877238322615838524354191263502347881033855441181420399360/461588070868590122892265681879734295007029130965626060552783760068897000195207878227714842617470320231527222074701444349530952699708435668339712860464533455345665068841333232359698449088497137068713309811942968433868609329301082001752
2633617420002377892756821532220676085014874112083615054550278903960627185675459015343606391094523511117705747842645927349130302549554534056269331809016770715819934970200483161548527932617036185253.6041015879424725383006424536130409209607854044642113747266098198777011981328765528361630516108680392500990580908509403483891763219659726090675140672989657743882183951954294745396417829943469201306594018454995862321821016087416840247422350906412007336103086620396467456181771583200365740253389107968122850063607085957109965406634738740996318415514360956028575560979203447735121436/1161752799109428422288020947061281540989708937450568100764830251908850596717606701047413407636907934320789870175907792017513896999208892282137299070761467096211814586909598705615312819596495636017728313513520193786266452836805291464826226833593878504804389728477191170027729963773716267868284479768397603444919008915279522376004326398403851684761808785381609370767169521034383625.13240077436443988749179508462267267187169441948722358165090554769250505713747934643200804819418670147225695324432684266924694524337920816452346599774452681831320005286326986675907899608537972384924882996757503264622991355949039882526389342174307168805166215838138277557052303430492669193939212362638263582899713198716541723383138016564027766560215944409353427176135895982596327685665844815618402881202645610620284792793420780517248/2544223084468158291883698813309541801455311468982232546872485444308211415529998472787377800559884210837213042932180479090277285630234238711851480232520137856848809986631784843528381778520727465146661792797924458540957133423665746229799675650290296217658444899605236550972043549278128087645211909479009099766619355677984218929672461506691980442071860591767266913041147587815452007726513853820116629482732060593116624596368806566625.1953999166296955830935495158735359200362904181792947794529339487489730042568305997099959302322956898299616194932283060554261566410988618045107398092345476532371402134206635235570281738377188438407703089325315446371127042537576093536896282955524842632708645655481028161471313608974238110718242273935956977555610147714316158486553633871312187084618154014921190595222799283957140353/375191165084882521037046014569185165885459082629136124177286500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000`.split(`.`)})}),KW=HW((e,t)=>{var n=typeof globalThis.nerdamerBigInt>`u`?UW():globalThis.nerdamerBigInt,r=typeof globalThis.nerdamerBigDecimal>`u`?WW():globalThis.nerdamerBigDecimal;r.set({precision:250});var i=typeof globalThis.nerdamerConstants>`u`?GW():globalThis.nerdamerConstants,a={},o=[],s={},c=[],l=[],u=[],d={Settings:null,Math2:null},f={ext:{bigInt:n,bigDec:r,PRIMES:i.PRIMES,PRIMES_SET:i.PRIMES_SET,LONG_PI:i.LONG_PI,LONG_E:i.LONG_E,BIG_LOG_CACHE:i.BIG_LOG_CACHE},groups:{N:1,P:2,S:3,EX:4,FN:5,PL:6,CB:7,CP:8},fnNames:{SQRT:`sqrt`,ABS:`abs`,FACTORIAL:`factorial`,DOUBLEFACTORIAL:`dfactorial`,PARENTHESIS:`parens`,LOG:`log`,CONST_HASH:`#`},get settings(){return d.Settings},state:{get EXPRESSIONS(){return o},get VARS(){return s},CONSTANTS:{},get RESERVED(){return c},get WARNINGS(){return l},get USER_FUNCTIONS(){return u},get CUSTOM_OPERATORS(){return a}},classes:{Frac:null,Fraction:null,NerdamerSymbol:null,Vector:null,Matrix:null,Expression:null,Collection:null,NerdamerSet:null,Scientific:null,Parser:null,LaTeX:null,Math2:null,Build:null},utils:{get isSymbol(){return W},get isVector(){return hn},get isMatrix(){return gn},get isExpression(){return _n},get isNumericSymbol(){return Me},get isFraction(){return wn},get isArray(){return z},get isInt(){return fe},get text(){return Hn},get variables(){return yn},get scientificToDecimal(){return Se},get err(){return Ht},get block(){return $t},get evaluate(){return en},get reserveNames(){return Ie},get nround(){return ge},get remove(){return ye},get _setFunction(){return Ln},get _clearFunctions(){return zn},symfunction:null,callfunction:null},exceptions:null,parser:null,core:null,libExports:null,version:`1.1.16`},p={N:f.groups.N,P:f.groups.P,S:f.groups.S,EX:f.groups.EX,FN:f.groups.FN,PL:f.groups.PL,CB:f.groups.CB,CP:f.groups.CP};Math.sign||=function(e){return e=Number(e),e===0||isNaN(e)?e:e>0?1:-1},Math.cosh||=function(e){let t=Math.exp(e);return(t+1/t)/2},Math.sech||=function(e){return 1/Math.cosh(e)},Math.csch||=function(e){return 1/Math.sinh(e)},Math.coth||=function(e){return 1/Math.tanh(e)},Math.sinh||=function(e){let t=Math.exp(e);return(t-1/t)/2},Math.tanh||=function(e){if(e===1/0)return 1;if(e===-1/0)return-1;let t=Math.exp(2*e);return(t-1)/(t+1)},Math.asinh||=function(e){return e===-1/0?e:Math.log(e+Math.sqrt(e*e+1))},Math.acosh||=function(e){return Math.log(e+Math.sqrt(e*e-1))},Math.atanh||=function(e){return Math.log((1+e)/(1-e))/2},Math.trunc||=function(e){return isNaN(e)?NaN:e>0?Math.floor(e):Math.ceil(e)};function m(e){return/\d+\.?\d*e[+-]*\d+/iu.test(e)}var h={convert(e,t){let n=Number(e),r;if(n===0)r=[0,1];else if(Math.abs(n)<1e-6||Math.abs(n)>0x56bc75e2d63100000){let e=this.quickConversion(n);if(e[1]<=0x2386f26fc10000){let t=Math.abs(n),i=n/t;r=this.fullConversion(t.toFixed(`${e[1]}`.length-1)),r[0]*=i}else r=e}else r=this.fullConversion(n);return r},quickConversion(e){let t=function(e){typeof e!=`string`&&(e=e.toString());let t=``,n=e.charAt(0);return n===`-`?(e=e.substr(1,e.length),t=`-`):n===`+`&&(e=e.substr(1,e.length)),{sign:t,value:e}};function n(e){m(e)&&(e=Se(e));let n=t(e),r=n.value.split(`.`),i;i=r.length===1?r[0]:r[0]+r[1];let a=r[1]?r[1].length:0,o=`1${`0`.repeat(a)}`;return i!==`0`&&(i=i.replace(/^0+/u,``)),[n.sign+i,o]}return n(e)},fullConversion(e){let t=Number(e),n=Math.abs(t)>1e10?1e-16:1e-30,r=!1,i=0,a=1,o=1,s=0,c=0,l=t,u,d;for(;!r;){c++;let e;if(Math.abs(l)>1e10){let t=Math.round(l);e=Math.abs(l-t)/Math.abs(t)<1e-14?t:Math.floor(l)}else e=Math.floor(l);u=i+e*o,d=a+e*s;let f=l-e;f<n&&(r=!0),l=1/f,i=o,a=s,o=u,s=d,(Math.abs(u/d-t)<n||c>30)&&(r=!0)}return[u,d]}};f.classes.Fraction=h;function g(e){let t=function(t){this.name=e,this.message=t===void 0?``:t;let n=Error(this.message);n.name=this.name,this.stack=n.stack};return t.prototype=Object.create(Error.prototype),t}var _=g(`DivisionByZero`),v=g(`ParseError`),y=g(`UndefinedError`),b=g(`OutOfFunctionDomainError`),x=g(`MaximumIterationsReached`),S=g(`NerdamerTypeError`),C=g(`ParityError`),w=g(`OperatorError`),T=g(`OutOfRangeError`),E=g(`DimensionError`),D=g(`InvalidVariableNameError`),O=g(`ValueLimitExceededError`),k=g(`NerdamerValueError`),A=g(`SolveError`),j=g(`InfiniteLoopError`),M=g(`UnexpectedTokenError`);f.exceptions={DivisionByZero:_,ParseError:v,OutOfFunctionDomainError:b,UndefinedError:y,MaximumIterationsReached:x,NerdamerTypeError:S,ParityError:C,OperatorError:w,OutOfRangeError:T,DimensionError:E,InvalidVariableNameError:D,V
2633alueLimitExceededError:O,NerdamerValueError:k,SolveError:A,InfiniteLoopError:j,UnexpectedTokenError:M};var N={get bigInt(){return f.ext.bigInt},get bigDec(){return f.ext.bigDec},get isInt(){return f.utils.isInt},get scientificToDecimal(){return f.utils.scientificToDecimal},get DivisionByZero(){return _},get Settings(){return f.settings},get Fraction(){return h}},P=class e{num;den;constructor(t){if(t instanceof e)return t;if(t===void 0)return this;try{if(N.isInt(t))try{this.num=N.bigInt(t),this.den=N.bigInt(1)}catch(n){if(n.message===`timeout`)throw n;return e.simple(t)}else{let e=t instanceof N.bigDec?N.Fraction.quickConversion(t):N.Fraction.convert(t);this.num=new N.bigInt(e[0]),this.den=new N.bigInt(e[1])}}catch(n){if(n.message===`timeout`)throw n;return e.simple(t)}}static create(t){if(t instanceof e)return t;t=t.toString();let n=t.charAt(0)===`-`;n&&(t=t.substr(1,t.length-1));let r=new e(t);return n&&r.negate(),r}static isFrac(t){return t instanceof e}static quick(t,n){let r=new e;return r.num=new N.bigInt(t),r.den=new N.bigInt(n),r}static simple(t){let n=String(N.scientificToDecimal(t)).split(`.`),r=n.join(``),i=`1`,a=(n[1]||``).length;for(let e=0;e<a;e++)i+=`0`;return e.quick(r,i).simplify()}multiply(e){if(this.isOne())return e.clone();if(e.isOne())return this.clone();let t=this.clone();return t.num=t.num.multiply(e.num),t.den=t.den.multiply(e.den),t.simplify()}divide(e){if(e.equals(0))throw new N.DivisionByZero(`Division by zero not allowed!`);return this.clone().multiply(e.clone().invert()).simplify()}subtract(e){return this.clone().add(e.clone().neg())}sub(e){return this.subtract(e)}neg(){return this.num=this.num.multiply(-1),this}add(e){let t=this.den,n=e.den,r=this.clone(),i=r.num,a=e.num;return t.equals(n)?r.num=i.add(a):(r.num=i.multiply(n).add(a.multiply(t)),r.den=t.multiply(n)),r.simplify()}mod(e){let t=this.clone(),n=e.clone();return t.num=t.num.multiply(n.den),t.den=t.den.multiply(n.den),n.num=n.num.multiply(this.den),n.den=n.den.multiply(this.den),t.num=t.num.mod(n.num),t.simplify()}simplify(){let e=N.bigInt.gcd(this.num,this.den);return this.num=this.num.divide(e),this.den=this.den.divide(e),this}clone(){let t=new e;return t.num=new N.bigInt(this.num),t.den=new N.bigInt(this.den),t}decimal(e){let t=this.num.isNegative()?`-`:``;if(this.num.equals(this.den))return`1`;e||=N.Settings.PRECISION,e+=2;let n=[],r=this.num.abs(),i=this.den,a;for(a=0;a<e;a++){let e=r.divide(i),t=r.subtract(e.multiply(i));if(n.push(e),t.equals(0))break;r=t.times(10)}let o=n.shift();if(n.length===0)return t+o.toString();if(a===e){let e=[];for(let t=0;t<2;t++)e.unshift(n.pop());n.push(Math.round(Number(e.join(`.`))))}return t+`${o.toString()}.${n.join(``)}`}toDecimal(e){return e||=N.Settings.PRECISION,e?this.decimal(e):this.num.valueOf()/this.den.valueOf()}qcompare(e){return[this.num.multiply(e.den),e.num.multiply(this.den)]}equals(t){isNaN(t)||(t=new e(t));let n=this.qcompare(t);return n[0].equals(n[1])}absEquals(t){isNaN(t)||(t=new e(t));let n=this.qcompare(t);return n[0].abs().equals(n[1])}greaterThan(t){isNaN(t)||(t=new e(t));let n=this.qcompare(t);return n[0].gt(n[1])}gt(e){return this.greaterThan(e)}gte(e){return this.greaterThan(e)||this.equals(e)}lte(e){return this.lessThan(e)||this.equals(e)}lessThan(t){isNaN(t)||(t=new e(t));let n=this.qcompare(t);return n[0].lt(n[1])}lt(e){return this.lessThan(e)}isInteger(){return this.den.equals(1)}negate(){return this.num=this.num.multiply(-1),this}invert(){let e=this.den;if(!this.num.equals(0)){let t=this.num.isNegative();this.den=this.num.abs(),this.num=e,t&&(this.num=this.num.multiply(-1))}return this}isOne(){return this.num.equals(1)&&this.den.equals(1)}sign(){return this.num.isNegative()?-1:1}abs(){return this.num=this.num.abs(),this}gcd(t){return e.quick(N.bigInt.gcd(t.num,this.num),N.bigInt.lcm(t.den,this.den))}toString(){return this.den.equals(1)?this.num.toString():`${this.num.toString()}/${this.den.toString()}`}valueOf(){return N.Settings.USE_BIG?new N.bigDec(this.num.toString()).div(new N.bigDec(this.den.toString())):this.num.valueOf()/this.den.valueOf()}isNegative(){return this.toDecimal()<0}contains(t){let n=typeof t==`number`?new e(t):t;return this.mod(n).equals(0)}};f.classes.Frac=P;var F={get isVector(){return f.utils.isVector},get Vector(){return f.classes.Vector},get remove(){return ye}},I=class e{elements=[];constructor(e,...t){if(typeof e>`u`)return;let n=e;if(F.isVector(e)||(n=F.Vector.fromArray([e,...t])),n){let{elements:e}=n;for(let t=0,n=e.length;t<n;t++)this.add(e[t])}}static fromArray(t){let n=new e;for(let e of t)n.add(e);return n}add(e){this.contains(e)||this.elements.push(e.clone())}contains(e){for(let t=0;t<this.elements.length;t++){let n=this.elements[t];if(e.equals(n))return!0}return!1}each(t){let{elements:n}=this,r=new e;for(let e=0,i=n.length;e<i;e++){let i=n[e];t.call(this,i,r,e)}return r}clone(){let t=new e;return this.each(e=>{t.add(e.clone())}),t}union(e){let t=this.clone();return e.each(e=>{t.add(e)}),t}difference(e){let t=this.clone();return e.each(e=>{t.remove(e)}),t}remove(e){for(let t=0,n=this.elements.length;t<n;t++)if(this.elements[t].equals(e))return F.remove(this.elements,t),!0;return!1}intersection(t){let n=new e,r=this;return t.each(e=>{r.contains(e)&&n.add(e)}),n}intersects(e){return this.intersection(e).elements.length>0}isSubset(e){let{elements:t}=e;for(let e=0,n=t.length;e<n;e++)if(!this.contains(t[e]))return!1;return!0}toString(){return`{${this.elements.join(`,`)}}`}};f.classes.NerdamerSet=I;var L={get _(){return f.parser},get block(){return f.utils.block}},ee=class e{elements=[];constructor(e){e&&this.elements.push(e)}static create(t){return new e(t)}append(e){this.elements.push(e)}getItems(){return this.elements}toString(){return L._.prettyPrint(this.elements)}dimensions(){return this.elements.length}text(e){return`(${this.elements.map(t=>t.text(e)).join(`,`)})`}clone(){let t=e.create();return t.elements=this.elements.map(e=>e.clone()),t}expand(e){return this.elements=this.elements.map(t=>L._.expand(t,e)),this}evaluate(e){return this.elements=this.elements.map(t=>L._.evaluate(t,e)),this}map(e){let t=this.clone();return t.elements=t.elements.map((t,n)=>e(t,n+1)),t}add(e){return L.block(`SAFE`,()=>{let t=e.elements;return this.elements.length===t.length?this.map((e,n)=>L._.add(e,t[n-1])):null},void 0,this)}subtract(e){return L.block(`SAFE`,()=>{let t=e.elements;return this.elements.length===t.length?this.map((e,n)=>L._.subtract(e,t[n-1])):null},void 0,this)}};f.classes.Collection=ee;var R={get Settings(){return f.settings},get nround(){return f.utils.nround}},te=class e{sign;coeff;exponent;wholes;dec;decp;constructor(t){t=String(typeof t>`u`?0:t),t.startsWith(`-`)?(this.sign=-1,t=t.substr(1,t.length)):this.sign=1,e.isScientific(t)?this.fromScientific(t):this.convert(t)}static isScientific(e){return m(e)}static leadingZeroes(e){let t=e.match(/^(?<zeros>0*).*$/u);return t?t[1]:``}static removeLeadingZeroes(e){let t=e.match(/^0*(?<rest>.*)$/u);return t?t[1]:``}static removeTrailingZeroes(e){let t=e.match(/0*$/u);return t?e.substring(0,e.length-t[0].length):``}static round(e,t){let n=String(R.nround(e,t)),r=t-(n.includes(`.`)?n.split(`.`).pop():``).length;return r>0&&(n.includes(`.`)||(n+=`.`),n+=Array(r+1).join(`0`)),n}fromScientific(e){let t=String(e).toLowerCase().split(`e`);this.coeff=t[0],this.exponent=Number(t[1]);let n=this.coeff.split(`.`);this.wholes=n[0]||``,this.dec=n[1]||``;let{dec:r}=this;return this.decp=r===`0`?0:r.length,this}convert(t){let n=t.split(`.`),r=n[0]||``,i=n[1]||``;r=e.removeLeadingZeroes(r),i=e.removeTrailingZeroes(i);let a=r.length,o=r+i,s=e.leadingZeroes(o).length;this.exponent=a-(s+1);let c=e.removeLeadingZeroes(o);this.coeff=`${c.charAt(0)}.${e.removeTrailingZeroes(c.substr(1,c.length))||`0`}`;let l=this.coeff.split(`.`)[1]||``;return this.decp=l===`0`?0:l.length,this.dec=i,this.wholes=r,this}
2633round(e){let t=this.copy();if(e=Number(e),e===0)t.coeff=t.coeff.charAt(0);else{let n=this.coeff.substring(0,e+1),r=this.coeff.substring(e+1,e+3),i=Number(r.charAt(0));Number(r.charAt(1))>4&&i++,t.coeff=n+i}return t}copy(){let t=new e(0);return t.coeff=this.coeff,t.exponent=this.exponent,t.sign=this.sign,t}toString(t){let n;if(R.Settings.SCIENTIFIC_IGNORE_ZERO_EXPONENTS&&this.exponent===0&&this.decp<t)n=this.decp===0&&this.wholes!==void 0?this.wholes:this.coeff;else{let r=typeof t>`u`?this.coeff:e.round(this.coeff,Math.min(t,this.decp||1)),i=this.exponent;r.startsWith(`10.`)&&(r=typeof t>`u`?r.replace(/^10\./u,`1.0`):e.round(r.replace(/^10\./u,`1.0`),Math.min(t,this.decp||1)),i=Number(i)+1),n=this.exponent===0?r:`${r}e${i}`}return(this.sign===-1?`-`:``)+n}};f.classes.Scientific=te;function z(e){return Array.isArray(e)}function ne(e){return`(${e})`}function B(e,t){return e<0==t<0}function V(...e){return e.shift().replace(/\{(?<idx>\d+)\}/gu,(t,n)=>{let r=e[n];return typeof r==`function`?r():r})}function H(e,t,n){let r=[];n||=1;for(let i=e;i<=t;i++)r.push(i*n);return r}function re(e){return e?String(e):``}function ie(e,t,n,r){return e.substr(0,t)+r+e.substr(n,e.length)}function ae(e){return e!==void 0&&e.custom}function oe(e){return Math.max.apply(void 0,e)}function se(e){return Math.min.apply(void 0,e)}function ce(e){return Number(e)%2==0}function le(e){return 1/(e%1)%2==0}function ue(e){let t=e.length,n=[];for(let r=0;r<t;r++){let t=e[r];n.indexOf(t)===-1&&n.push(t)}return n}function de(e){return[].slice.call(e)}function fe(e){return typeof e==`number`?Number.isInteger(e):typeof e<`u`&&/^[-+]?\d+e?\+?\d*$/gimu.test(e.toString())}function pe(e,t){if(e.sort(),t.sort(),e.length===t.length){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}return!1}function me(e){let t=[],n=e.length;for(let r=0;r<n;r++)t[r]=e[r].clone();return t}function he(e){return/^\d+\.?\d*$/u.test(String(e))}function ge(e,t=14){return fe(e)?Number(e)>=Number.MAX_VALUE?e.toString():Number(e):Math.round(e*10**t)/10**t}function _e(e,t){t||=20;let n=[],r,i,a;n.push(e[0]);for(let o=0;o<e.length-1;o++){r=e[o],i=e[o+1]-r,a=i/t;for(let e=0;e<t;e++)r+=a,n.push(r)}return n}function ve(e,t){if(z(e)){let n=e.length;for(let r=0;r<n;r++)t.call(e,r)}else for(let n in e)Object.hasOwn(e,n)&&t.call(e,n)}function ye(e,t){let n;return z(e)?n=e.splice(t,1)[0]:(n=e[t],delete e[t]),n}function be(e,t){let n={};return n[e]=t,n}function xe(e){for(let t=0;t<e.length;t++)if(!he(e[t]))return!1;return!0}function Se(e){let t=Math.sign(e),n=Math.abs(e);if(/\d+\.?\d*e[+-]*\d+/iu.test(String(n))){let e=String(n).toLowerCase().split(`e`),t=e.pop(),r=Math.abs(Number(t)),i=Math.sign(Number(t)),a=e[0].split(`.`);if(i===-1)r-=a[0].length,n=r<0?`${a[0].slice(0,r)}.${a[0].slice(r)}${a.length===2?a[1]:``}`:`0.${Array(r+1).join(`0`)}${a.join(``)}`;else{let e=a[1];e&&(r-=e.length),n=r<0?`${a[0]+e.slice(0,r)}.${e.slice(r)}`:a.join(``)+Array(r+1).join(`0`)}}return t<0?`-${n}`:String(n)}function Ce(e){let t=e[0];for(let n=1,r=e.length;n<r;n++)if(!e[n].equals(t))return!1;return!0}function we(e,t){typeof t!=`function`&&(t=function(e,t){return e===t});let n=[];for(;e.length;){let r=e[0];if(e.length===1){n.push(r);break}let i=[];n.push(r);for(let n=1;n<e.length;n++){let a=e[n];t(r,a)||i.push(a)}e=i}return n}function Te(e,t){let n=e.length,r=[];for(let n=0;n<e.length;n++)r.push([e[n],t[n]]);r.sort((e,t)=>Number(e[0])-Number(t[0]));let i=[],a=[];for(let e=0;e<n;e++)i.push(r[e][0]),a.push(r[e][1]);return[i,a]}function Ee(e){return e instanceof ee}function De(e){return e instanceof I}function Oe(e,t,n){let r=Object.keys(e)[0];return t?r:n?{key:r,obj:e[r]}:e[r]}var{keys:ke}=Object,Ae={get N(){return f.groups.N},get P(){return f.groups.P},get S(){return f.groups.S},get EX(){return f.groups.EX},get FN(){return f.groups.FN},get PL(){return f.groups.PL},get CB(){return f.groups.CB},get CP(){return f.groups.CP}},je={get _(){return f.parser},get N(){return f.groups.N},get P(){return f.groups.P},get S(){return f.groups.S},get EX(){return f.groups.EX},get FN(){return f.groups.FN},get PL(){return f.groups.PL},get CB(){return f.groups.CB},get CP(){return f.groups.CP},get SQRT(){return f.fnNames.SQRT},get ABS(){return f.fnNames.ABS},get FACTORIAL(){return f.fnNames.FACTORIAL},get DOUBLEFACTORIAL(){return f.fnNames.DOUBLEFACTORIAL},get PARENTHESIS(){return f.fnNames.PARENTHESIS},get bigDec(){return f.ext.bigDec},get PRIMES(){return f.ext.PRIMES},get VARS(){return f.state.VARS}};function Me(e){return e.group===Ae.N||e.group===Ae.P}function Ne(e){return e.group===Ae.S&&e.multiplier.equals(1)&&e.power.equals(1)}function Pe(e){for(let t=0;t<e.length;t++)if(e[t].group!==Ae.N)return!1;return!0}var Fe={get RESERVED(){return f.state.RESERVED}};function Ie(e){let t=function(e){Fe.RESERVED.indexOf(e)===-1&&Fe.RESERVED.push(e)};typeof e==`string`?t(e):ve(e,e=>{t(e)})}function Le(e){let t=Fe.RESERVED.indexOf(e);t!==-1&&(Fe.RESERVED[t]=void 0)}var Re={get ALLOW_CHARS(){return f.settings?.ALLOW_CHARS??[]},VALIDATION_REGEX:/^[a-z_][a-z\d_]*$/iu};
2633function ze(e,t=`variable`){if(Re.ALLOW_CHARS.indexOf(e)===-1&&!Re.VALIDATION_REGEX.test(e))throw new D(`${e} is not a valid ${t} name`)}function Be(e){return Fe.RESERVED.indexOf(e)!==-1}var Ve={get WARNINGS(){return f.state.WARNINGS},get SHOW_WARNINGS(){return!(f.settings?.SILENCE_WARNINGS??!0)}};function He(e){Ve.WARNINGS.push(e),Ve.SHOW_WARNINGS&&console&&console.warn&&console.warn(e)}function Ue(){return Ve.WARNINGS}var We={get EXPRESSIONS(){return f.state.EXPRESSIONS}};function Ge(){return We.EXPRESSIONS.length}var Ke={get Settings(){return f.settings}};function qe(e){return Ke.Settings[e]}function Je(e){try{return ze(e),Fe.RESERVED.indexOf(e)===-1}catch(e){if(e.message===`timeout`)throw e;return!1}}function Ye(e){return e?Fe.RESERVED:Fe.RESERVED.join(`, `)}var Xe={get _version(){return f.version},get C(){return f.core}};function Ze(e){if(e)try{return Xe.C[e].version}catch(t){if(t.message===`timeout`)throw t;return`No module named ${e} found!`}return f.version}function Qe(){return Xe.C}var $e={get functions(){return f.parser?.functions}};function et(){return ke($e.functions)}var tt={get CONSTANTS(){return f.parser?.CONSTANTS}};function nt(e){return String(tt.CONSTANTS[e])}var rt={get VARS(){return f.state.VARS}};function it(e){return rt.VARS[e]}function at(e,t){e||=`text`;let n={};if(e===`object`)n=rt.VARS;else for(let r in rt.VARS)Object.hasOwn(rt.VARS,r)&&(e===`latex`?n[r]=rt.VARS[r].latex(t):e===`text`&&(n[r]=rt.VARS[r].text(t)));return n}var ot={get _(){return f.parser},get C(){return f.core}};function st(e,t){return ot._.toTeX(e,t)}function ct(e){return ot._.getOperator(e)}function lt(e,t){ot._.aliasOperator(e,t)}function ut(e,t,n){ot._.setOperator(e,t,n)}function dt(e,t){ot._.peekers[e]&&ot._.peekers[e].push(t)}function ft(e,t){let n=ot._.peekers[e];if(n){let e=n.indexOf(t);e!==-1&&ye(n,e)}}function pt(e){let t=ot._.toRPN(ot._.tokenize(e));return ot._.tree(t)}function mt(e){return String(e).split(`;`).map(e=>ot._.parse(e))}function ht(e){return ot._.toRPN(ot._.tokenize(e))}function gt(e,t){return`<div class="tree">
2634    <ul>
2635        <li>
2636${pt(e).toHTML(3,t)}
2637        </li>
2638    </ul>
2639</div>`}function _t(e,t,n){let r=ot._.functions[e],i=typeof n>`u`?r[1]:n;ot._.functions[e]=[t(r[0],ot.C),i]}var vt={get EXPRESSIONS(){return f.state.EXPRESSIONS},get USER_FUNCTIONS(){return f.state.USER_FUNCTIONS},get LaTeX(){return f.classes.LaTeX},get text(){return f.utils.text},get functions(){return f.parser?.functions??{}},get Math2(){return f.classes.Math2},get _(){return f.parser},get Expression(){return f.classes.Expression}};function yt(e,t,n){let r=e?{}:[];for(let i=0;i<vt.EXPRESSIONS.length;i++){let a=t?vt.LaTeX.latex(vt.EXPRESSIONS[i],n):vt.text(vt.EXPRESSIONS[i],n);e?r[i+1]=a:r.push(a)}return r}function bt(e,t){let n=e?{}:[];for(let r=0;r<vt.USER_FUNCTIONS.length;r++){let i,a,o=vt.USER_FUNCTIONS[r],s=vt.functions[o][2];if(s)({params:i,body:a}=s);else{let e=vt.Math2[o].toString();[,i]=/\((?<params>.*?)\)/u.exec(e),i=i.split(`,`).map(e=>e.trim()),a=`{JavaScript}`}let c=`${o}(${i.join(`, `)})=${a}`,l=vt.text(c,t);e?n[r+1]=l:n.push(l)}return n}function xt(e){e=e.replace(/_(?<char>[A-Za-z0-9])/gu,(...e)=>`${e[0]} `),e=e.replace(/\^(?<char>[A-Za-z0-9])/gu,(...e)=>`^{${e[1]}}`),e=e.replace(/(?<cmd>\\[A-Za-z]+)(?<digit>\d)/gu,(...e)=>`${e[1]}{${e[2]}}`),e=e.replace(/(?<cmd>\\[A-Za-z]+\{.*?\})(?<digit>\d)/gu,(...e)=>`${e[1]}{${e[2]}}`);let t=vt.LaTeX.parse(vt._.tokenize(e));return new vt.Expression(vt._.parse(t))}var St={get libExports(){return f.libExports},get VARS(){return f.state.VARS},get _clearFunctions(){return f.utils._clearFunctions},get _initConstants(){return f.parser?.initConstants??(()=>{})},get clear(){return Ft}};function Ct(){for(let e in St.VARS)Object.hasOwn(St.VARS,e)&&delete St.VARS[e];return St.libExports}function wt(){return St._clearFunctions(),St.libExports}function Tt(){return St.libExports}function Et(){return St.clear(`all`),St.libExports}function Dt(e){return e.call(St.libExports),St.libExports}var Ot={get libExports(){return f.libExports},get CONSTANTS(){return f.state.CONSTANTS}};function kt(e,t){if(ze(e),!Be(e))if(t===`delete`||t===``)delete Ot.CONSTANTS[e];else{if(isNaN(t))throw new S(`Constant must be a number!`);Ot.CONSTANTS[e]=t}return Ot.libExports}var At={get libExports(){return f.libExports},get VARS(){return f.state.VARS},get CONSTANTS(){return f.state.CONSTANTS},get parse(){let{parser:e}=f;return e?.parse?.bind(e)??(()=>null)},get isSymbol(){return f.utils.isSymbol}};function jt(e,t){return ze(e),e in At.CONSTANTS&&Ht(`Cannot set value for constant ${e}`),t===`delete`||t===``?delete At.VARS[e]:At.VARS[e]=At.isSymbol(t)?t:At.parse(t),At.libExports}var Mt={get libExports(){return f.libExports},get _setFunction(){return f.utils._setFunction}};function Nt(e,t,n){if(!Mt._setFunction(e,t,n))throw Error(`Failed to set function!`);return Mt.libExports}var Pt={get libExports(){return f.libExports},get EXPRESSIONS(){return f.state.EXPRESSIONS}};function Ft(e,t=!1){if(e===`all`)Pt.EXPRESSIONS.length=0;else if(e===`last`)Pt.EXPRESSIONS.pop();else if(e===`first`)Pt.EXPRESSIONS.shift();else{let n=e?e-1:Pt.EXPRESSIONS.length;t===!0?Pt.EXPRESSIONS[n]=void 0:ye(Pt.EXPRESSIONS,n)}return Pt.libExports}var It={get libExports(){return f.libExports},get Settings(){return f.settings},get functions(){return f.parser?.functions??{}}};function Lt(e){let t=It.libExports.getCore();if(z(e))for(let t=0;t<e.length;t++)e&&Lt(e[t]);
2639else if(e&&It.Settings.exclude.indexOf(e.name)===-1){if(e.dependencies){for(let n=0;n<e.dependencies.length;n++)if(!t[e.dependencies[n]])throw Error(V(`{0} requires {1} to be loaded!`,e.name,e.dependencies[n]))}let n=e.parent,r=e.build.call(t);if(n){t[n]||(t[e.parent]={});let i=n===`nerdamer`?It.libExports:t[n];i[e.name]=r}e.visible&&(It.functions[e.name]=[r,e.numargs])}}var Rt={get bigDec(){return f.ext.bigDec},get Settings(){return f.settings},get functions(){return f.parser?.functions??{}},get symfunction(){return f.utils.symfunction},get NerdamerSymbol(){return f.classes.NerdamerSymbol}};function zt(e,t){if(typeof e==`object`&&e){let t=e;for(let e in t)Object.hasOwn(t,e)&&zt(e,t[e])}[`SAFE`].indexOf(e)!==-1&&Ht(`Cannot modify setting: ${e}`),e===`PRECISION`?(Rt.bigDec.set({precision:t}),Rt.Settings.PRECISION=t,t>21&&zt(`USE_BIG`,!0)):e===`USE_LN`&&t===!0?(Rt.Settings.LOG=`LN`,Rt.Settings.LOG10=`log`,Rt.functions.log=Rt.Settings.LOG_FNS.log10,Rt.functions.log[0]=function(e){return e.isConstant()?new Rt.NerdamerSymbol(Math.log10(e)):Rt.symfunction(Rt.Settings.LOG10,[e])},Rt.functions.LN=Rt.Settings.LOG_FNS.log,delete Rt.functions.log10):Rt.Settings[e]=t}var Bt={get libExports(){return f.libExports},get functions(){return f.parser?.functions??{}},get parse(){let{parser:e}=f;return e?.parse?.bind(e)??(()=>null)},get callfunction(){return f.utils.callfunction},get Expression(){return f.classes.Expression}};function Vt(e=!1){let t=function(e){return function(...t){for(let e=0;e<t.length;e++)t[e]=Bt.parse(t[e]);return new Bt.Expression($t(`PARSE2NUMBER`,()=>Bt.callfunction(e,t)))}};for(let n in Bt.functions)(!(n in Bt.libExports)||e)&&(Bt.libExports[n]=t(n))}var eee={get suppress_errors(){return f.settings?.suppress_errors??!1}};function Ht(e,t=void 0){if(!eee.suppress_errors)throw t?new t(e):Error(e)}var Ut={get PRIMES_SET(){return f.ext.PRIMES_SET}};function Wt(e){if(e in Ut.PRIMES_SET)return!0;let t=Math.floor(Math.sqrt(e));for(let n=2;n<=t;n++)if(e%n===0)return!1;return!0}var Gt={starttime:0,timeout:0,get TIMEOUT(){return f.settings?.TIMEOUT??800}};function Kt(){Gt.starttime=Date.now(),Gt.timeout=Gt.TIMEOUT}function qt(){Gt.starttime=0}function Jt(){if(Gt.starttime!==0&&Date.now()>Gt.starttime+Gt.timeout)throw Error(`timeout`)}var Yt={get PRIMES(){return f.ext.PRIMES},get PRIMES_SET(){return f.ext.PRIMES_SET}};function Xt(e){if(Jt(),Wt(e))return[e];let t=e,n=1,r=[];for(;n<t;){Jt();let i=e/n,a=Math.floor(i);if(i-a<=2220446049250313e-31&&n>1){if(Wt(n)&&(Yt.PRIMES_SET[n]||(Yt.PRIMES.push(n),Yt.PRIMES_SET[n]=!0),r.push(n)),Wt(a)){r.push(a);break}t=a}n++}return r.sort((e,t)=>e-t)}function Zt(e){let t=Yt.PRIMES[Yt.PRIMES.length-1]||2;for(let n=t;n<e;n++)Wt(n)&&Yt.PRIMES.push(n),Yt.PRIMES_SET[n]=!0}var Qt={get Settings(){return f.settings}};function $t(e,t,n=void 0,r=void 0){let i=Qt.Settings[e];Qt.Settings[e]=n===void 0?!0:!!n;let a=t.call(r);return Qt.Settings[e]=i,a}function en(e,t=void 0){return $t(`PARSE2NUMBER`,()=>je._.parse(e,t),!0)}var tn={get EXPRESSIONS(){return f.state.EXPRESSIONS},get Settings(){return f.settings},get LaTeX(){return f.classes.LaTeX},get text(){return f.utils.text},get variables(){return f.utils.variables},get isVector(){return f.utils.isVector},get isSymbol(){return f.utils.isSymbol},get isExpression(){return f.utils.isExpression},get isNumericSymbol(){return f.utils.isNumericSymbol},get isFraction(){return f.utils.isFraction},get isArray(){return f.utils.isArray},get _(){return f.parser},get Build(){return f.classes.Build}},nn=class e{symbol;constructor(e){this.symbol=e}static getExpression(t,n=void 0){(t===`last`||!t)&&(t=tn.EXPRESSIONS.length),t===`first`&&(t=1);let r=Number(t)-1,i=tn.EXPRESSIONS[r];return i&&new e(i.symbol)}text(e=`decimals`,t=void 0){t||=tn.Settings.EXPRESSION_DECP;let n=this.symbol;return n.text_?n.text_(e):tn.text(this.symbol,e,void 0,t)}latex(e){return this.symbol.latex?this.symbol.latex(e):tn.LaTeX.latex(this.symbol,e)}valueOf(){return this.symbol.valueOf()}evaluate(...t){if(tn.isVector(this.symbol)&&this.symbol.dimensions()===0)return this;let n=t[0],r,i=1;typeof n==`string`?r=n.charAt(0)===`%`?e.getExpression(n.substr(1)).text():n:n instanceof e||tn.isSymbol(n)?r=n.text():(r=this.symbol.text(),i--);let a=t[i]||{};return new e($t(`PARSE2NUMBER`,()=>tn._.parse(r,a),!0))}buildFunction(e){return tn.Build.build(this.symbol,e)}isNumber(){return tn.isNumericSymbol(this.symbol)}isInfinity(){return Math.abs(this.symbol.multiplier.valueOf())===1/0}isImaginary(){return en(tn._.parse(this.symbol)).isImaginary()}variables(){return tn.variables(this.symbol)}toString(){try{return tn.isArray(this.symbol)?`[${this.symbol.toString()}]`:this.symbol.toString()}catch(e){if(e.message===`timeout`)throw e;return``}}toDecimal(e){tn.Settings.precision=e;let t=tn.text(this.symbol,`decimals`);return tn.Settings.precision=void 0,t}isFraction(){return tn.isFraction(this.symbol)}isPolynomial(){return this.symbol.isPoly()}sub(t,n){return new e(this.symbol.sub(tn._.parse(t),tn._.parse(n)))}operation(t,n){let r;return r=tn.isExpression(n)?n.symbol:tn.isSymbol(n)?n:tn._.parse(n),new e(tn._[t](this.symbol.clone(),r.clone()))}add(e){return this.operation(`add`,e)}subtract(e){return this.operation(`subtract`,e)}multiply(e){return this.operation(`multiply`,e)}divide(e){return this.operation(`divide`,e)}pow(e){return this.operation(`pow`,e)}expand(){return new e(tn._.expand(this.symbol))}each(e,t){if(this.symbol.each)this.symbol.each(e,t);else if(tn.isArray(this.symbol))for(let t=0;t<this.symbol.length;t++)e.call(this.symbol,this.symbol[t],t);else e.call(this.symbol)}eq(e){tn.isSymbol(e)||(e=tn._.parse(e));try{return tn._.subtract(this.symbol.clone(),e).equals(0)}catch(e){if(e.message===`timeout`)throw e;return!1}}lt(e){tn.isSymbol(e)||(e=tn._.parse(e));try{return en(tn._.subtract(this.symbol.clone(),e)).lessThan(0)}catch(e){if(e.message===`timeout`)throw e;return!1}}
2639gt(e){tn.isSymbol(e)||(e=tn._.parse(e));try{return en(tn._.subtract(this.symbol.clone(),e)).greaterThan(0)}catch(e){if(e.message===`timeout`)throw e;return!1}}gte(e){return this.gt(e)||this.eq(e)}lte(e){return this.lt(e)||this.eq(e)}numerator(){return new e(this.symbol.getNum())}denominator(){return new e(this.symbol.getDenom())}hasFunction(e){return this.symbol.containsFunction(e)}contains(e){return this.symbol.contains(e)}toTeX(e){return this.latex(e)}};f.classes.Expression=nn;var rn={get _(){return f.parser},get Settings(){return f.settings},get LaTeX(){return f.classes.LaTeX},get NerdamerSymbol(){return f.classes.NerdamerSymbol}},an=class e{multiplier;elements;rowVector;custom=!0;constructor(e,...t){this.multiplier=new P(1),hn(e)?this.elements=e.elements?.slice(0)??[]:z(e)?this.elements=e.slice(0):gn(e)?e.elements.length===1?(this.elements=[...e.elements[0]],this.rowVector=!0):e.elements.length>1&&Array.isArray(e.elements[0])&&e.elements[0].length===1&&(this.elements=e.elements.map(e=>e[0]),this.rowVector=!1):typeof e>`u`?this.elements=[]:this.elements=[e,...t]}static arrayPrefill(e,t){let n=[];t||=0;for(let r=0;r<e;r++)n[r]=t;return n}static fromArray(t){let n=new e;return n.elements=t,n}static fromSet(t){return e.fromArray(t.elements)}e(e){return e<1||e>this.elements.length?null:this.elements[e-1]}set(e,t){W(t)?this.elements[e]=t:this.elements[e]=new rn.NerdamerSymbol(t)}dimensions(){return this.elements.length}modulus(){return $t(`SAFE`,()=>rn._.pow(this.dot(this.clone()),new rn.NerdamerSymbol(.5)),void 0,this)}eql(e){let t=this.elements.length,n=e.elements||e;if(t!==n.length)return!1;do if(Math.abs(rn._.subtract(this.elements[t-1],n[t-1]).valueOf())>rn.Settings.PRECISION)return!1;while(--t);return!0}clone(){let t=new e,n=this.elements.length;for(let e=0;e<n;e++)t.elements.push(this.elements[e].clone());return t.rowVector=this.rowVector,t}expand(e){return this.elements=this.elements.map(t=>rn._.expand(t,e)),this}map(t){let n=[];return this.each((e,r)=>{n.push(t(e,r))}),new e(n)}each(e){let t=this.elements.length,n=t,r;do r=n-t,e(this.elements[r],r+1);while(--t)}toUnitVector(){return $t(`SAFE`,()=>{let e=this.modulus();return e.valueOf()===0?this.clone():this.map(t=>rn._.divide(t,e))},void 0,this)}angleFrom(e){return $t(`SAFE`,()=>{let t=e.elements||e;if(this.elements.length!==t.length)return null;let n=new rn.NerdamerSymbol(0),r=new rn.NerdamerSymbol(0),i=new rn.NerdamerSymbol(0);this.each((e,a)=>{n=rn._.add(n,rn._.multiply(e,t[a-1])),r=rn._.add(r,rn._.multiply(e,e)),i=rn._.add(i,rn._.multiply(t[a-1],t[a-1]))}),r=rn._.pow(r,new rn.NerdamerSymbol(.5)),i=rn._.pow(i,new rn.NerdamerSymbol(.5));let a=rn._.multiply(r,i);if(a.valueOf()===0)return null;let o=rn._.divide(n,a),s=o.valueOf();return s<-1&&(o=-1),s>1&&(o=1),new rn.NerdamerSymbol(Math.acos(o))},void 0,this)}isParallelTo(e){let t=this.angleFrom(e).valueOf();return t===null?null:t<=rn.Settings.PRECISION}isAntiparallelTo(e){let t=this.angleFrom(e).valueOf();return t===null?null:Math.abs(t-Math.PI)<=rn.Settings.PRECISION}isPerpendicularTo(e){let t=this.dot(e);return t===null?null:Math.abs(t)<=rn.Settings.PRECISION}add(e){return $t(`SAFE`,()=>{let t=e.elements||e;return this.elements.length===t.length?this.map((e,n)=>rn._.add(e,t[n-1])):null},void 0,this)}subtract(e){return $t(`SAFE`,()=>{let t=e.elements||e;return this.elements.length===t.length?this.map((e,n)=>rn._.subtract(e,t[n-1])):null},void 0,this)}multiply(e){return this.map(t=>rn._.multiply(t.clone(),e.clone()))}x(e){return this.multiply(e)}dot(e){return $t(`SAFE`,()=>{let t=e.elements||e,n=new rn.NerdamerSymbol(0),r=this.elements.length;if(r!==t.length)return null;do n=rn._.add(n,rn._.multiply(this.elements[r-1],t[r-1]));while(--r);return n},void 0,this)}cross(t){let n=t.elements||t;if(this.elements.length!==3||n.length!==3)return null;let r=this.rowVector&&t.rowVector,i=this.elements;return $t(`SAFE`,()=>{let t=new e([rn._.subtract(rn._.multiply(i[1],n[2]),rn._.multiply(i[2],n[1])),rn._.subtract(rn._.multiply(i[2],n[0]),rn._.multiply(i[0],n[2])),rn._.subtract(rn._.multiply(i[0],n[1]),rn._.multiply(i[1],n[0]))]);return t.rowVector=r,t},void 0,this)}toUnitMultiplier(){return this}max(){let e=0,t=this.elements.length,n=t,r;do{r=n-t;let i=this.elements[r],a=i.valueOf(),o=typeof e==`number`?e:e.valueOf();Math.abs(a)>Math.abs(o)&&(e=i)}while(--t);return e}magnitude(){let e=new rn.NerdamerSymbol(0);return this.each(t=>{e=rn._.add(e,rn._.pow(t,new rn.NerdamerSymbol(2)))}),rn._.sqrt(e)}indexOf(e){let t=null,n=this.elements.length,r=n,i;do i=r-n,t===null&&this.elements[i].valueOf()===e.valueOf()&&(t=i+1);while(--n);return t}text_(e,t){let n=Hn(this,t);return(this.rowVector?`[`:``)+n+(this.rowVector?`]`:``)}text(e,t){let n=Hn(this,t);return(this.rowVector?`[`:``)+n+(this.rowVector?`]`:``)}toString(){return this.text()}latex(e){let t=[];for(let n=0;n<this.elements.length;n++)t.push(rn.LaTeX.latex(this.elements[n],e));return`[${t.join(`, `)}]`}};f.classes.Vector=an;var on={get _(){return f.parser},get LaTeX(){return f.classes.LaTeX},get NerdamerSymbol(){return f.classes.NerdamerSymbol}},sn=class e{multiplier;elements;custom=!0;constructor(...e){this.multiplier=new P(1);let t=e,n=t.length,r,i=[];if(gn(t))for(r=0;r<n;r++)i.push(t[r].slice(0));else{let e,a,o;for(r=0;r<n;r++)e=t[r],hn(e)&&(e=e.elements),z(e)||(e=[e]),o=e.length,a&&a!==o&&Ht(`Unable to create Matrix. Row dimensions do not match!`),i.push(e),a=o}this.elements=i}static identity(t){let n=new e;for(let e=0;e<t;e++){n.elements.push([]);for(let r=0;r<t;r++)n.set(e,r,e===r?new on.NerdamerSymbol(1):new on.NerdamerSymbol(0))}return n}static fromArray(t){return new e(...t)}static zeroMatrix(t,n){let r=new e;for(let e=0;e<t;e++)r.elements.push(an.arrayPrefill(n,new on.NerdamerSymbol(0)));return r}get(e,t){if(this.elements[e])return this.elements[e][t]}map(t,n){let r=new e;return this.each((e,i,a)=>{r.set(i,a,t.call(r,e),n)}),r}set(e,t,n,r){this.elements[e]||=[],r||W(n)?this.elements[e][t]=n:this.elements[e][t]=new on.NerdamerSymbol(n)}cols(){return this.elements[0].length}rows(){return this.elements.length}row(e){return!e||e>this.cols()?[]:this.elements[e-1]}col(e){let t=this.rows(),n=[];if(e>this.cols()||!e)return n;for(let r=0;r<t;r++)n.push(this.elements[r][e-1]);return n}eachElement(e){let t=this.rows(),n=this.cols(),r,i;for(r=0;r<t;r++)for(i=0;i<n;i++)e.call(this,this.elements[r][i],r,i)}each(e){this.eachElement(e)}
2639determinant(){if(!this.isSquare())return null;let e=this.toRightTriangular(),t=e.elements[0][0],n=e.elements.length-1,r=n,i;do i=r-n+1,t=on._.multiply(t,e.elements[i][i]);while(--n);return t}isSquare(){return this.elements.length===this.elements[0].length}isSingular(){let e=this.determinant();return this.isSquare()&&e!==null&&e.multiplier.equals(0)}augment(e){let t=this.rows();t!==e.rows()&&Ht(`Cannot augment matrix. Rows don't match.`);for(let n=0;n<t;n++)this.elements[n]=this.elements[n].concat(e.elements[n]);return this}clone(){let t=this.rows(),n=this.cols(),r=new e;for(let e=0;e<t;e++){r.elements[e]=[];for(let t=0;t<n;t++){let n=this.elements[e][t];r.elements[e][t]=W(n)?n.clone():n}}return r}toUnitMultiplier(){return this}expand(e){return this.eachElement(t=>on._.expand(t,e)),this}evaluate(e){return this.eachElement(t=>on._.evaluate(t,e)),this}invert(){return this.isSquare()||Ht(`Matrix is not square!`),$t(`SAFE`,()=>{let t=this.elements.length,n=t,r,i,a=e.identity(t),o=this.augment(a).toRightTriangular(),s,c=o.elements[0].length,l,u,d,f=[],p;do{r=t-1,u=[],s=c,f[r]=[],d=o.elements[r][r];do l=c-s,p=on._.divide(o.elements[r][l],d.clone()),u.push(p),l>=n&&f[r].push(p);while(--s);for(o.elements[r]=u,i=0;i<r;i++){u=[],s=c;do l=c-s,u.push(on._.subtract(o.elements[i][l].clone(),on._.multiply(o.elements[r][l].clone(),o.elements[i][r].clone())));while(--s);o.elements[i]=u}}while(--t);return e.fromArray(f)},void 0,this)}toRightTriangular(){return $t(`SAFE`,()=>{let e=this.clone(),t,n,r,i=this.elements.length,a=i,o,s,c=this.elements[0].length,l;do{if(o=a-i,n=e.elements[o][o],n.valueOf()===0){for(let n=o+1;n<a;n++)if(r=e.elements[n][o],r&&r.valueOf()!==0){t=[],s=c;do l=c-s,t.push(on._.add(e.elements[o][l].clone(),e.elements[n][l].clone()));while(--s);e.elements[o]=t;break}}if(n=e.elements[o][o],n.valueOf()!==0)for(let n=o+1;n<a;n++){let r=on._.divide(e.elements[n][o].clone(),e.elements[o][o].clone());t=[],s=c;do l=c-s,t.push(l<=o?new on.NerdamerSymbol(0):on._.subtract(e.elements[n][l].clone(),on._.multiply(e.elements[o][l].clone(),r.clone())));while(--s);e.elements[n]=t}}while(--i);return e},void 0,this)}transpose(){let t=this.elements.length,n=this.elements[0].length,r=new e,i=n,a,o,s;do{a=n-i,r.elements[a]=[],o=t;do s=t-o,r.elements[a][s]=this.elements[s][a].clone();while(--o)}while(--i);return r}canMultiplyFromLeft(e){let t=gn(e)?e.elements.length:e.length;return this.elements[0].length===t}sameSize(e){return this.rows()===e.rows()&&this.cols()===e.cols()}multiply(t){return $t(`SAFE`,()=>{let n=t.elements||t;if(!this.canMultiplyFromLeft(n))return null;let r=this.elements.length,i=r,a,o,s=n[0].length,c,l=this.elements[0].length,u=[],d,f,p;do{a=i-r,u[a]=[],o=s;do{c=s-o,d=new on.NerdamerSymbol(0),f=l;do p=l-f,d=on._.add(d,on._.multiply(this.elements[a][p],n[p][c]));while(--f);u[a][c]=d}while(--o)}while(--r);return e.fromArray(u)},void 0,this)}add(t,n){let r=new e;return this.sameSize(t)&&this.eachElement((e,i,a)=>{let o=on._.add(e.clone(),t.elements[i][a].clone());n&&(o=n.call(r,o,e,t.elements[i][a])),r.set(i,a,o)}),r}subtract(t,n){let r=new e;return this.sameSize(t)&&this.eachElement((e,i,a)=>{let o=on._.subtract(e.clone(),t.elements[i][a].clone());n&&(o=n.call(r,o,e,t.elements[i][a])),r.set(i,a,o)}),r}negate(){return this.each(e=>e.negate()),this}toVector(){if(this.rows()===1||this.cols()===1){let e=new an;return e.elements=this.elements.flat(),e}return this}toString(e,t){let n=this.rows(),r=[];e=e===void 0?`
2640`:e;for(let e=0;e<n;e++)r.push(`[${this.elements[e].map(e=>{let n=t?e.multiplier.toDecimal():e.toString();return e===void 0?``:n}).join(`,`)}]`);return`matrix${ne(r.join(`,`))}`}text(){return`matrix(${this.elements.map(e=>`[${e.join(`,`)}]`)})`}latex(e){let t=this.cols(),{elements:n}=this;return V(`\\begin{vmatrix}{0}\\end{vmatrix}`,()=>{let r=[];for(let i in n){if(!Object.hasOwn(n,i))continue;let a=[];for(let r=0;r<t;r++)a.push(on.LaTeX.latex(n[i][r],e));r.push(a.join(` & `))}return r.join(` \\cr `)})}};f.classes.Matrix=sn;var cn={get _(){return f.parser},get N(){return f.groups.N},get P(){return f.groups.P},get S(){return f.groups.S},get EX(){return f.groups.EX},get FN(){return f.groups.FN},get CB(){return f.groups.CB},get Math2(){return d.Math2},get NerdamerSymbol(){return f.classes.NerdamerSymbol}}
2640,ln={dependencies:{},reformat:{},initDependencies(){let{Math2:e}=cn;this.dependencies={_rename:{"Math2.factorial":`factorial`},factorial:{"Math2.gamma":e.gamma},gamma_incomplete:{"Math2.factorial":e.factorial},Li:{"Math2.Ei":e.Ei,"Math2.bigLog":e.bigLog,Frac:P},Ci:{"Math2.factorial":e.factorial},Ei:{"Math2.factorial":e.factorial},Si:{"Math2.factorial":e.factorial},Shi:{"Math2.factorial":e.factorial},Chi:{isInt:fe,nround:ge,"Math2.num_integrate":e.num_integrate},factor:{"Math2.ifactor":e.ifactor,NerdamerSymbol:cn.NerdamerSymbol},num_integrate:{"Math2.simpson":e.simpson,nround:ge},fib:{even:ce}},this.reformat={diff(t,n){let r=t.args[1].toString(),i=`let f = ${ln.build(t.args[0].toString(),[r])};`,a=e.diff.toString();return!a.startsWith(`function`)&&!a.startsWith(`(`)&&!a.startsWith(`async`)&&(a=`function ${a}`),n[1]+=`let diff = ${a};`,n[1]+=i,[`diff(f)(${r})`,n]}}},getProperName(e){return{continuedFraction:`continuedFraction`}[e]||e},compileDependencies(e,t){let n=ln.dependencies[e],r=t&&t[1]?t[1]:``,i=t&&t[0]?t[0]:{};for(let e in n){if(typeof n[e]==`object`)continue;let t=e.split(`.`),a=n[e];if(typeof a==`function`){let e=a.toString();!e.startsWith(`function`)&&!e.startsWith(`(`)&&!e.startsWith(`async`)&&(e=`function ${e}`),a=e}r+=`let ${t.length>1?t[1]:t[0]}=${a};`,i[e]=t.pop()}return[i,r]},getArgsDeps(e,t){let{args:n}=e,r=t,i=function(e){e.group===cn.FN&&(r=ln.compileDependencies(e.fname,r))};for(let t=0;t<n.length;t++)e.args[t].each(i);return r},build(e,t){let{_:n,FN:r,N:i,S:a,P:o,EX:s,CB:c,NerdamerSymbol:l}=cn;e=$t(`PARSE2NUMBER`,()=>n.parse(e),!0);let u=yn(e),d=[],f=[{},``],p=function(e,t){e.fname===``&&(e=l.unwrapPARENS(e)),t||=[];let u=[],{group:m}=e,h=``,g=function(n){let r=n===c?`*`:`+`,i=[];for(let n in e.symbols){if(!Object.hasOwn(e.symbols,n))continue;let r=e.symbols[n],a=p(r,t)[0];r.isComposite()&&(a=ne(a)),i.push(a)}let a=i.join(r);return a=a&&!e.multiplier.equals(1)?ne(a):a,a},_=function(n){let r;if(n in Math)r=`Math.${n}`;else{if(n=ln.getProperName(n),d.indexOf(n)===-1){let e=cn.Math2[n].toString();!e.startsWith(`function`)&&!e.startsWith(`(`)&&!e.startsWith(`async`)&&(e=`function ${e}`),t.push(`let ${n} = ${e}; `),d.push(n)}r=n}return r+=ne(e.args.map(e=>p(e,t)[0]).join(`,`)),r};m===i?u.push(e.multiplier.toDecimal()):e.multiplier.equals(-1)?h=`-`:e.multiplier.equals(1)||u.push(e.multiplier.toDecimal());let v;if(m===a||m===o)v=e.value;else if(m===r)if(f=ln.compileDependencies(e.fname,f),f=ln.getArgsDeps(e,f),ln.reformat[e.fname]){let t=ln.reformat[e.fname](e,f);f=t[1],v=t[0]}else v=_(e.fname);else if(m===s){let t=e.previousGroup;t===i||t===a?v=e.value:t===r?(v=_(e.fname),f=ln.compileDependencies(e.fname,f),f=ln.getArgsDeps(e,f)):v=g(e.previousGroup)}else v=g(e.group);if(e.group!==i&&!e.power.equals(1)){let r=p(n.parse(e.power));t.push(r[1]),v=`Math.pow${ne(`${v},${r[0]}`)}`}return v&&u.push(h+v),[u.join(`*`),t.join(``).replace(/\n+\s+/gu,` `)]};t&&(u=t);let m=p(e);for(let e in f[0]){if(!Object.hasOwn(f[0],e))continue;let t=f[0][e];m[1]=m[1].replace(e,t),f[1]=f[1].replace(e,t)}return Function(...u,`${(f[1]||``)+m[1]} return ${m[0]};`)}};f.classes.Build=ln;var un={get _(){return f.parser},get Settings(){return f.settings},get SQRT(){return f.fnNames.SQRT},get ABS(){return f.fnNames.ABS},get PARENTHESIS(){return f.fnNames.PARENTHESIS},get FACTORIAL(){return f.fnNames.FACTORIAL},get DOUBLEFACTORIAL(){return f.fnNames.DOUBLEFACTORIAL},get N(){return f.groups.N},get P(){return f.groups.P},get S(){return f.groups.S},get EX(){return f.groups.EX},get FN(){return f.groups.FN},get CB(){return f.groups.CB},get CP(){return f.groups.CP},get Parser(){return f.classes.Parser}},dn={parser:null,space:`~`,dot:` \\cdot `,latex(e,t){let{_:n,P:r,CB:i}=un;if(e&&typeof e==`object`&&`clone`in e&&typeof e.clone==`function`&&(e=e.clone()),e instanceof n.classes.Collection&&(e=e.elements),z(e)){let r=[];for(let i=0;i<e.length;i++){let a=e[i];W(a)||(a=n.parse(a)),r.push(this.latex(a,t))}return this.brackets(r.join(`, `),`square`)}if(gn(e)){let n=`\\begin{pmatrix}
2641`;for(let r=0;r<e.elements.length;r++){let i=[],a=e.elements[r];for(let e=0;e<a.length;e++)i.push(this.latex(a[e],t));n+=i.join(` & `),r<e.elements.length-1&&(n+=`\\\\
2642`)}return n+=`\\end{pmatrix}`,n}if(hn(e)){let n=`\\left[`;for(let r=0;r<e.elements.length;r++)n+=`${this.latex(e.elements[r],t)} ${r===e.elements.length-1?``:`,\\,`}`;return n+=`\\right]`,n}if(De(e)){let n=`\\{`;for(let r=0;r<e.elements.length;r++)n+=`${this.latex(e.elements[r],t)} ${r===e.elements.length-1?``:`,\\,`}`;return n+=`\\}`,n}e=e.clone();let a=t===`decimal`||t===`decimals`,{power:o}=e,s=Dn(o),c=e.multiplier.lessThan(0);if(e.group===r&&a){let t=Number(e.value),n=Number(e.power.toDecimal()),r=Number(e.multiplier.toDecimal());return String(r*t**n)}e.multiplier=e.multiplier.abs();let l;l=a?[String(e.multiplier.toDecimal()),``]:[e.multiplier.num,e.multiplier.den];let u=this.value(e,s,t,c),d;s&&o.negate(),a?(d=W(o)?dn.latex(o,t):String(o.toDecimal()),String(d)===`1`&&(d=``)):d=W(o)?this.latex(o,t):this.formatFrac(o,!0);let f=[``,``],p=+!!s;return f[p]=d,((c?`-`:``)+this.set(l,u,f,e.group===i)).replace(/\+-/giu,`-`)},greek:{alpha:`\\alpha`,beta:`\\beta`,gamma:`\\gamma`,delta:`\\delta`,epsilon:`\\epsilon`,zeta:`\\zeta`,eta:`\\eta`,theta:`\\theta`,iota:`\\iota`,kappa:`\\kappa`,lambda:`\\lambda`,mu:`\\mu`,nu:`\\nu`,xi:`\\xi`,omnikron:`\\omnikron`,pi:`\\pi`,rho:`\\rho`,sigma:`\\sigma`,tau:`\\tau`,upsilon:`\\upsilon`,phi:`\\phi`,chi:`\\chi`,psi:`\\psi`,omega:`\\omega`,Gamma:`\\Gamma`,Delta:`\\Delta`,Epsilon:`\\Epsilon`,Theta:`\\Theta`,Lambda:`\\Lambda`,Xi:`\\Xi`,Pi:`\\Pi`,Sigma:`\\Sigma`,Phi:`\\Phi`,Psi:`\\Psi`,Omega:`\\Omega`},symbols:{arccos:`\\arccos`,cos:`\\cos`,csc:`\\csc`,exp:`\\exp`,ker:`\\ker`,limsup:`\\limsup`,min:`\\min`,sinh:`\\sinh`,arcsin:`\\arcsin`,cosh:`\\cosh`,deg:`\\deg`,gcd:`\\gcd`,lg:`\\lg`,ln:`\\ln`,Pr:`\\Pr`,sqrt:`\\sqrt`,sup:`\\sup`,arctan:`\\arctan`,cot:`\\cot`,det:`\\det`,hom:`\\hom`,lim:`\\lim`,log:`\\log`,LN:`\\LN`,sec:`\\sec`,tan:`\\tan`,arg:`\\arg`,coth:`\\coth`,dim:`\\dim`,
2642inf:`\\inf`,liminf:`\\liminf`,max:`\\max`,sin:`\\sin`,tanh:`\\tanh`},value(e,t,n,r){let{SQRT:i,ABS:a,PARENTHESIS:o,FACTORIAL:s,DOUBLEFACTORIAL:c,FN:l,S:u,P:d,N:f,CB:p,CP:m,EX:h}=un,{group:g}=e,{previousGroup:_}=e,v=[``,``],y=+!!t;if(e.isInfinity)v[y]=`\\infty`;else if(g===u||g===d||_===u||_===d||_===f){let t=this.formatSubscripts(e.value);t.replace&&(t=t.replace(/(?<prefix>.+)_$/u,`$1\\_`));let n=String(t).split(`_`),r=this.greek[n[0]];r&&(n[0]=r,t=n.join(`_`));let i=this.symbols[n[0]];i&&(n[0]=i,t=n.join(`_`)),v[y]=t}else if(g===l||_===l){let t=[],{fname:r}=e;for(let r=0;r<e.args.length;r++){let i=e.args[r],a;a=typeof i==`string`?i:this.latex(i,n),t.push(a)}if(r===i)v[y]=`\\sqrt${this.braces(t.join(`,`))}`;else if(r===a)v[y]=this.brackets(t.join(`,`),`abs`);else if(r===o)v[y]=this.brackets(t.join(`,`),`parens`);else if(r===`limit`)v[y]=` \\lim\\limits_{${t[1]} \\to ${t[2]}} ${t[0]}`;else if(r===`integrate`)v[y]=`\\int${this.braces(t[0])}${this.braces(`d${t[1]}`)}`;else if(r===`defint`)v[y]=`\\int\\limits_${this.braces(t[1])}^${this.braces(t[2])} ${t[0]} d${t[3]}`;else if(r===s||r===c){let n=e.args[0];n.power.equals(1)&&(n.isComposite()||n.isCombination())&&(t[0]=this.brackets(t[0])),v[y]=t[0]+(r===s?`!`:`!!`)}else if(r===`floor`)v[y]=`\\left \\lfloor${this.braces(t[0])}\\right \\rfloor`;else if(r===`ceil`)v[y]=`\\left \\lceil${this.braces(t[0])}\\right \\rceil`;else if(r===un.Settings.LOG&&t.length>1)v[y]=`\\mathrm${this.braces(un.Settings.LOG)}_${this.braces(t[1])}${this.brackets(t[0])}`;else if(r===un.Settings.LOG10)v[y]=`\\mathrm${this.braces(un.Settings.LOG)}_${this.braces(`10`)}${this.brackets(t[0])}`;else if(r===un.Settings.LOG2)v[y]=`\\mathrm${this.braces(un.Settings.LOG)}_${this.braces(`2`)}${this.brackets(t[0])}`;else if(r===un.Settings.LOG1P)v[y]=`\\ln${this.brackets(`1 + ${t[0]}`)}`;else if(r===`sum`){let e=t[0],n=t[1],r=t[2],i=t[3];v[y]=`\\sum\\limits_{${this.braces(n)}=${this.braces(r)}}^${this.braces(i)} ${this.braces(e)}`}else if(r===`product`){let e=t[0],n=t[1],r=t[2],i=t[3];v[y]=`\\prod\\limits_{${this.braces(n)}=${this.braces(r)}}^${this.braces(i)} ${this.braces(e)}`}else if(r===`nthroot`)v[y]=`\\sqrt[${t[1]}]${this.braces(t[0])}`;else if(r===`mod`)v[y]=`${t[0]} \\bmod ${t[1]}`;else if(r===`realpart`)v[y]=`\\operatorname{Re}${this.brackets(t[0])}`;else if(r===`imagpart`)v[y]=`\\operatorname{Im}${this.brackets(t[0])}`;else{let n=r===``?``:`\\mathrm${this.braces(r.replace(/_/gu,`\\_`))}`;e.isConversion?v[y]=n+this.brackets(t.join(``),`parens`):v[y]=n+this.brackets(t.join(`,`),`parens`)}}else if(e.isComposite()){let t=e.collectSymbols().sort(g===m||_===m?(e,t)=>t.group-e.group:(e,t)=>{let n=W(e.power)?-1:Number(e.power);return(W(t.power)?-1:Number(t.power))-n}),i=[],a=t.length;for(let e=0;e<a;e++)i.push(dn.latex(t[e],n));let o=i.join(`+`),s=e;v[y]=!(s.isLinear()&&s.multiplier.equals(1))||r?this.brackets(o,`parens`):o}else if(g===p||_===h||_===p){g===p&&e.distributeExponent();let t=[],r=[],i=[],a=[],o=0,s=0,c=function(e,t,n){if(n>1&&t.length>0){let n=t.length;for(let r=0;r<n;r++){let n=t[r],i=e[n];/^\\left\(.+\\right\)\^\{.+\}$/gu.test(i)||/^\\left\(.+\\right\)$/gu.test(i)||(e[n]=dn.brackets(i,`parens`))}}return e};e.each(c=>{let l=Dn(c.power),u;l?(u=dn.latex(c.invert(),n),s++,c.isComposite()&&(!e.multiplier.den.equals(1)&&Math.abs(Number(c.power))===1&&(u=dn.brackets(u,`parens`)),i.push(t.length)),t.push(u)):(u=dn.latex(c,n),o++,c.isComposite()&&(!e.multiplier.num.equals(1)&&Math.abs(Number(c.power))===1&&(u=dn.brackets(u,`parens`)),a.push(r.length)),r.push(u))}),c(r,a,o),v[0]=r.join(this.dot),c(t,i,s),v[1]=t.join(this.dot)}return v},set(e,t,n,r){let i=function(e){return/^\\left\(.+\\right\)$/u.test(e)};n&&=this.formatP(n);let a;r&&(a=n[0],n[0]=``),t=this.merge(t,n);let o=e[0],s=e[1],c=t[0],l=t[1];c&&Number(o)===1&&(o=``),Number(s)===1&&(s=``);let u=this.join(o,c,i(c)?``:this.dot),d=this.join(s,l,i(l)?``:this.dot);if(u&&d){let e=this.frac(u,d);return r&&a&&(e=this.brackets(e)+a),e}return u},merge(e,t){let n=[];for(let r=0;r<2;r++)n[r]=e[r]+t[r];return n},join(e,t,n){return!e&&!t?``:e&&!t?e:t&&!e?t:e+n+t},formatSubscripts(e){let t=e.toString().split(`_`),n=``;for(;t.length>1;)t.length>0&&(n=`_${this.braces(t.pop()+n)}`);return t[0]+n},formatP(e){for(let t=0;t<2;t++){let n=e[t];n&&(e[t]=`^${this.braces(n)}`)}return e},formatFrac(e,t){let n=e.num.toString(),r=e.den.toString();return t&&n===`1`&&r===`1`?``:r===`1`?n:this.frac(n,r)},frac(e,t){return`\\frac${this.braces(e)}${this.braces(t)}`},braces(e){return`{${e}}`},brackets(e,t){t||=`parens`;let n={parens:[`(`,`)`],square:[`[`,`]`],brace:[`{`,`}`],abs:[`|`,`|`],angle:[`\\langle`,`\\rangle`]}[t];return`\\left${n[0]}${e}\\right${n[1]}`},filterTokens(e){let t=[];z(e)&&(t.type=e.type);let n=[`\\`,`left`,`right`,`big`,`Big`,`large`,`Large`];for(let r=0,i=e.length;r<i;r++){let i=e[r],a=e[r+1];i.value===`\\`&&a.value===`\\`?t.push(i):z(i)?t.push(dn.filterTokens(i)):n.indexOf(i.value)===-1&&t.push(i)}return t},parse(e){let{SQRT:t}=un,n,r,i=``,a=this.filterTokens(e),o={cdot:``,times:``,infty:`Infinity`},s=function(e){return a[typeof e>`u`?++n:n+=e]},c=function(){return dn.parse(s())},l=function(e){return e in o?o[e]:e===`*`&&a[n+1].value===`&`?(s(2),`,`):e===`&`?(s(),`,`):e===`\\`?`],[`:e};for(n=0,r=a.length;n<r;n++){let e=a[n];if(e.value===`frac`){let e=c(),t=c();i+=`${e}/${t}`}else if(e.value in dn.symbols)if(e.value===t&&a[n+1].type===`vector`&&a[n+2].type===`NerdamerSet`){let e=c(),t=c();i+=`${t}^${ne(`1/${e}`)}`}else i+=e.value+c();else if(e.value===`int`){let e=c();n++;let t=s().value;t=l(t.substring(1,t.length)),i+=`integrate${ne(`${e},${t}`)}`}else if(e.value===`int_`){let e=c();n++;let t=s().value;t===void 0&&(n--,t=c());let r=c(),a=s().value;a===`,`&&(a=s().value),a===`differentialD`&&(n++,a=s().value),a===`mathrm`&&(n++,a=s().value),i+=`defint${ne(`${r},${e},${t},${a}`)}`}else if(e.value&&e.value.startsWith(`int_`)){let t=e.value.replace(`int_`,``);n++;let r=s().value;r===void 0&&(n--,r=c());let a=c(),o=s().value;o===`,`&&(o=s().value),o===`differentialD`&&(n++,o=s().value),o===`mathrm`&&(n++,o=s().value),i+=`defint${ne(`${a},${t},${r},${o}`)}`}else if(e.value===`mathrm`){let e=a[++n][0].value;i+=e+c()}else if(e.value===`sum_`||e.value===`prod_`){let t=e.value===`sum_`?`sum`:`product`,r=s();n++;let a=c(),o=c();i+=t+ne([o,l(r[0]),l(r[2]),l(a)].join(`,`))}else if(e.value===`lim_`){let e=s();i+=`limit${ne([c(),l(e[0]),l(e[2])].join(`,`))}`}else if(e.value===`begin`){let e=s();Array.isArray(e)&&e[0].value===`matrix`&&(i+=`matrix([`)}else if(e.value===`end`){let e=s();Array.isArray(e)&&e[0].value===`matrix`&&(i+=`])`)}else Array.isArray(e)?i+=l(dn.parse(e)):i+=l(e.value.toString())}return ne(i)},initParser(){let e=un.Parser,t=[`classes`,`setOperator`,`getOperators`,`getBrackets`,`tokenize`,`toRPN`,`tree`,`units`],n=new e;for(let e in n)t.indexOf(e)===-1&&delete n[e];n.setOperator({precedence:8,operator:`\\`,action:`slash`,prefix:!0,postfix:!1,leftAssoc:!0,operation(e){return e}}),n.setOperator({precedence:8,operator:`\\,`,action:`slash_comma`,prefix:!0,postfix:!1,leftAssoc:!0,operation(e){return e}});let r=n.getBrackets();r[`{`].maps_to=void 0,this.parser=n}};f.classes.LaTeX=dn;var fn={get LONG_PI(){return f.ext.LONG_PI},get LONG_E(){return f.ext.LONG_E}},U={callPeekers:!1,init_primes:1e3,exclude:[],suppress_errors:!1,PARSE2NUMBER:!1,SAFE:!1,IMAGINARY:`i`,FUNCTION_MODULES:[Math],ALLOW_CHARS:[`π`],USE_MULTICHARACTER_VARS:!0,POWER_OPERATOR:`^`,FUNCTION_REGEX:/^\s*(?<fnName>[a-z_][a-z0-9_]*)\((?<fnArgs>[a-z0-9_,\s]*)\)\s*:?=\s*(?<fnBody>.+)\s*$/iu,VALIDATION_REGEX:/^[a-z_αAβBγΓδΔϵEζZηHθΘιIκKλΛμMνNξΞoOπΠρPσΣτTυϒϕΦχXψΨωΩ∞][0-9a-z_αAβBγΓδΔϵEζZηHθΘιIκKλΛμMνNξΞoOπΠρPσΣτTυϒϕΦχXψΨωΩ]*$/iu,IMPLIED_MULTIPLICATION_REGEX:/(?<coeff>[+\-/*]*[0-9]+)(?<vars>[a-z_αAβBγΓδΔϵEζZηHθΘιIκKλΛμMνNξΞoOπΠρPσΣτTυϒϕΦχXψΨωΩ]+[+\-/*]*)/giu,ALIASES:{π:`pi`,"∞":`Infinity`},POSITIVE_MULTIPLIERS:!1,CACHE:{},SILENCE_WARNINGS:!1,PRECISION:21,EXPRESSION_DECP:19,DEFAULT_DECP:16,VECTOR:`vector`,PARENTHESIS:`parens`,SQRT:`sqrt`,ABS:`abs`,FACTORIAL:`factorial`,DOUBLEFACTORIAL:`dfactorial`,get LONG_PI(){return fn.LONG_PI},get LONG_E(){return fn.LONG_E},PI:Math.PI,E:Math.E,LOG:`log`,LOG_LATEX:`log`,LOG10:`log10`,LOG10_LATEX:`log_{10}`,LOG2:`log2`,LOG2_LATEX:`log_{2}`,LOG1P:`log1p`,LOG1P_LATEX:`ln\\left( 1 + {0} \\right)`,MAX_EXP:2e5,SCIENTIFIC_MAX_DECIMAL_PLACES:14,SCIENTIFIC_IGNORE_ZERO_EXPONENTS:!0,SCIENTIFIC_SWITCH_FROM_DECIMALS_MIN_EXPONENT:7,TIMEOUT:800,initCache(){this.CACHE.roots={};for(let e=2;e<=40;e++)for(let t=2;t<=40;t++){let r=n(e).pow(t);this.CACHE.roots[`${r}-${t}`]=e}}};U.CONST_HASH=f.fnNames.CONST_HASH,U.initCache(),d.Settings=U;var pn={get bigInt(){return f.ext.bigInt},get BIG_LOG_CACHE(){return f.ext.BIG_LOG_CACHE},get PRIMES(){return f.ext.PRIMES},get NerdamerSymbol(){return f.classes.NerdamerSymbol},get CB(){return f.groups.CB},get P(){return f.groups.P}},mn={csc(e){return 1/Math.sin(e)},sec(e){return 1/Math.cos(e)},cot(e){return 1/Math.tan(e)},acsc(e){return Math.asin(1/e)},asec(e){return Math.acos(1/e)},acot(e){return Math.PI/2-Math.atan(e)},erf(e){let t=1/(1+.5*Math.abs(e)),n=1-t*Math.exp(-e*e-1.26551223+t*(1.00002368+t*(.37409196+t*(.09678418+t*(-.18628806+t*(.27886807+t*(-1.13520398+t*(1.48851587+t*(-.82215223+t*.17087277)))))))));return e>=0?n:-n},diff(e){return function(t){return(e(t+.001)-e(t-.001))/.002}},median(...e){e.sort((e,t)=>
2642e-t);let t=Math.floor(e.length/2);return e.length%2?e[t]:(e[t-1]+e[t])/2},fromContinued(e){let t=e.fractions.slice(),n=1/t.pop();for(let e=0,r=t.length;e<r;e++)n=1/(t.pop()+n);return e.sign*(e.whole+n)},continuedFraction(e,t){t||=20;let n=Math.sign(e),r=Math.abs(e),i=Math.floor(r),a=r-i,o=0,s=!1,c,l,u={whole:i,sign:n,fractions:[]};for(;!s&&a!==0&&(c=1/a,l=Math.floor(c),!(l>1e7&&mn.fromContinued(u)-e<=2**-52));)u.fractions.push(l),a=c-l,(a<=1e-14||o>=t-1)&&(s=!0),o++;let d=u.fractions.length-1;return u.fractions[d]===1&&(u.fractions.pop(),u.fractions[--d]++),u},bigpow(e,t){e instanceof P||(e=P.create(e)),t instanceof P||(t=P.create(t));let n=new P(0);if(t.isInteger())n.num=e.num.pow(t.toString()),n.den=e.den.pow(t.toString());else{let r=P.create(e.num**t.num),i=P.create(e.den**t.num);n.num=mn.nthroot(r,t.den.toString()),n.den=mn.nthroot(i,t.den)}return n},gamma(e){let t=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,1.5056327351493116e-7];if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*mn.gamma(1-e));--e;let n=t[0];for(let r=1;r<9;r++)n+=t[r]/(e+r);let r=e+7+.5;return Math.sqrt(2*Math.PI)*r**(e+.5)*Math.exp(-r)*n},bigfactorial(e){let t=new pn.bigInt(1);for(let n=2;n<=e;n++)t=t.times(n);return new P(t)},bigLog(e){let t=pn.BIG_LOG_CACHE;if(t[e])return P.quick.apply(null,t[e].split(`/`));e=new P(e);let n=new P(0),r=e.subtract(new P(1)),i=e.add(new P(1));for(let e=0;e<80;e++){let t=new P(2*e+1),a=mn.bigpow(r.divide(i),t),o=t.clone().invert().multiply(a);n=n.add(o)}return n.multiply(new P(2))},factorial(e){let t=e%1==0;if(t&&e<0)return NaN;if(!t)return mn.gamma(e+1);let n=1;for(let t=2;t<=e;t++)n*=t;return n},dfactorial(e){let t=new P(1);if(fe(e)){let n=e%2==0,r=n?e/2:(e+1)/2;if(n)for(let e=1;e<=r;e++)t=t.multiply(new P(2).multiply(new P(e)));else for(let e=1;e<=r;e++)t=t.multiply(new P(2).multiply(new P(e)).subtract(new P(1)))}else t=2**((1+2*e-Math.cos(Math.PI*e))/4)*Math.PI**((Math.cos(Math.PI*e)-1)/4)*mn.gamma(1+e/2);return t},GCD(...e){let t=ue(e.map(e=>Math.abs(e))).sort(),n=Math.abs(t.shift()),r=t.length;for(;r-- >0;){let e=Math.abs(t.shift());for(;;){if(n%=e,n===0){n=e;break}if(e%=n,e===0)break}}return n},QGCD(...e){let t=e[0];for(let n=1;n<e.length;n++){let r=e[n],i=t.isNegative()&&r.isNegative()?-1:1;t=r.gcd(t),i<0&&t.negate()}return t},LCM(e,t){return e*t/mn.GCD(e,t)},pow(e,t){return e<0&&Math.abs(t)<1?1/t%2==0?NaN:-(Math.abs(e)**t):e**t},factor(e){e=Number(e);let t=Math.sign(e);e=Math.abs(e);let n=mn.ifactor(e),r=new pn.NerdamerSymbol;r.symbols={},r.group=pn.CB;for(let e in n){if(!Object.hasOwn(n,e))continue;let t=new pn.NerdamerSymbol(1);t.group=pn.P,t.value=e,t.power=new pn.NerdamerSymbol(n[e]),r.symbols[e]=t}return r.updateHash(),e===1&&(r=new pn.NerdamerSymbol(e)),t<0&&r.negate(),r},sfactor(e,t){t||={};let n=Math.floor(Math.sqrt(e)),{PRIMES:r}=pn;n>r[r.length-1]&&e<1e6&&Zt(n);let i=r.length;for(let n=0;n<i;n++){let i=r[n];for(;e%i===0;)e/=i,t[i]=(t[i]||0)+1}return e>1&&(t[e]=1),t},ifactor(e){let{bigInt:t}=pn,n=new t(e),r=new t(String(e));if(r.equals(0))return{0:1};let i=r.isNegative()?-1:1;r=r.abs();let a={};if(r.lt(`65536`))a=mn.sfactor(r,a);else{let e=function(e){e.isPrime()?a[e]=(a[e]||0)+1:a=mn.sfactor(e,a)};try{let n={value:0},i=function(e,n,r){let a=new t(e),o=2,s=new t(e),c=new t(1);for(;c.equals(1);){for(let e=0;e<=o&&c.equals(1);e++){if(r.value++>1e3)throw Error(`stopping`);s=s.pow(2).add(1).mod(n),c=t.gcd(s.minus(a).abs(),n)}o*=2,a=s}return c.equals(n)?i(e+1,n,r):c};for(;!r.abs().equals(1);)if(r.isPrime()){e(r);break}else{let t=i(2,r,n);e(t),r=r.divide(t)}}catch(t){if(t.message===`timeout`)throw t;a={},e(n)}}if(i===-1){let e=se(ke(a).map(Number));a[`-${e}`]=a[e],delete a[e]}return a},boxfactor(e,t){t||=200;let n,r,i=Math.floor(5/12*e),a=0,o=!1;for(;n=Math.floor(e/i),r=e%i,r!==0;){if(o)return[e,1];i=Math.max(r,i-r),a++,o=a>t}return[n,i,a]},fib(e){let t=Math.sign(e);e=Math.abs(e),t=ce(e)?t:Math.abs(t);let n=0,r=1,i=1;for(let t=2;t<=e;t++)i=n+r,n=r,r=i;return i*t},mod(e,t){return e%t},integer_part(e){return Math.sign(e)*Math.floor(Math.abs(e))},simpson(e,t,n,r){let i=function(e,t,n){let r=e(t),i=1e-12;return isNaN(r)&&(r=e(n===1?t+i:t-i)),r};r||=1e-4;let a=Math.abs(Math.floor((n-t)/r));a%2!=0&&a++;let o=(n-t)/a,s=i(e,t,1),c=!1,l=t+o,u,d;for(let t=1;t<a;t++)u=c?2:4,d=u*i(e,l,1),s+=d,c=!c,l+=o;return(s+i(e,l,2))*(o/3)},num_integrate(e,t,n,r,i){if(i<0)throw Error(`max depth cannot be negative`);function a(e,t,n,r,i,o,s,c,l,u,d){if(d.nanEncountered)return NaN;let f=n-t,p=e(t+f*.25),m=e(n-f*.25);if(isNaN(p)){d.nanEncountered=!0;return}if(isNaN(m)){d.nanEncountered=!0;return}let h=f*(r+4*p+i)/12,g=f*(i+4*m+o)/12,_=h+g,v=(_-s)/15;if(d.maxDepthCount>1e3*l)return;if(u>l)return d.maxDepthCount++,_+v;if(Math.abs(v)<c)return _+v;let y=t+f*.5,b=a(e,t,y,r,p,i,h,c*.5,l,u+1,d);if(isNaN(b))return d.nanEncountered=!0,NaN;let x=a(e,y,n,i,m,o,g,c*.5,l,u+1,d);return isNaN(x)?(d.nanEncountered=!0,NaN):b+x}function o(e,t,n,r,i){let o={maxDepthCount:0,nanEncountered:!1};r===void 0&&(r=1e-9),i===void 0&&(i=45);let s=e(t),c=e(.5*(t+n)),l=e(n),u=a(e,t,n,s,c,l,(s+4*c+l)*(n-t)/6,r,i,1,o);if(o.maxDepthCount>0&&He(`integrate-adaptive-simpson: Warning: maximum recursion depth (${i}) reached ${o.maxDepthCount} times`),o.nanEncountered)throw Error(`Function does not converge over interval!`);return u}let s;try{s=o(e,t,n,r,i)}catch(r){if(r.message===`timeout`)throw r;return mn.simpson(e,t,n)}return ge(s,12)},Ci(e){let t=0;for(let n=1;n<20;n++){let r=2*n;t+=(-1)**n*e**r/(r*mn.factorial(r))}return Math.log(e)+.5772156649015329+t},Si(e){let t=0;for(let n=0;n<20;n++){let r=2*n;t+=(-1)**n*e**(r+1)/((r+1)*mn.factorial(r+1))}return t},Ei(e){if(Number(e)===0)return-1/0;let t=0;for(let n=1;n<30;n++)t+=e**n/(n*mn.factorial(n));return .5772156649015329+Math.abs(Math.log(e))+t},Shi(e){let t=0,n,r;for(let i=0;i<30;i++)n=2*i,r=n+1,t+=e**r/(r*r*mn.factorial(n));return t},Chi(e){return Math.log(e)+.5772156649015329+mn.num_integrate(function(e){return(Math.cosh(e)-1)/e},.002,e,.001)},Li(e){return mn.Ei(mn.bigLog(e))},gamma_incomplete(e,t){let n=e-1,r=0,i=t||0;for(let e=0;e<n;e++)r+=i**e/mn.factorial(e);return mn.factorial(n)*Math.exp(-i)*r},step(e){return e>0?1:e<0?0:.5},rect(e){let t=Math.abs(e);return t===.5?t:t>.5?0:1},sinc(e){return e.equals(0)?1:Math.sin(e)/e},tri(e){return e=Math.abs(e),e>=1?0:1-e},nthroot(e,t){if(e instanceof P||(e=new P(e.toString())),t instanceof P||(t=new P(t.toString())),t.equals(1))return e;let n=e.divide(new P(2)),r=new P(1e-15),i,a,o,s=t.clone().invert(),c=t.subtract(new P(1));
2642do{let t=mn.bigpow(n,c),r=s.multiply(e.divide(t).subtract(n)).toDecimal(25);if(i=P.create(r),o)break;n=n.add(i),r=i.toDecimal(),o=a?a===r:!1,a=r}while(i.abs().gte(r));return n},sqrt(e){e instanceof P||(e=new P(e));let t,n,r,i,a=0,o=!1,s=new P(1e-20);t=e.divide(new P(2));do{if(a>1e3)throw Error(`Unable to calculate square root for ${e}`);t=t.add(e.divide(t)).divide(new P(2)),t=new P(t.decimal(30)),n=e.subtract(t.multiply(t)),i=r?r.equals(n):!1,(n.clone().abs().lessThan(s)||i)&&(o=!0),r=n,a++}while(!o);return t}};U.FUNCTION_MODULES.push(mn),Ie(mn),d.Math2=mn;function W(e){return e instanceof f.classes.NerdamerSymbol}function hn(e){return e instanceof an}function gn(e){return e instanceof sn}function _n(e){return e instanceof nn}var vn={get EX(){return f.groups.EX},get CP(){return f.groups.CP},get CB(){return f.groups.CB},get S(){return f.groups.S},get PL(){return f.groups.PL},get FN(){return f.groups.FN}};function yn(e,t=null,n=null){if(n||={c:[],add(e){this.c.indexOf(e)===-1&&isNaN(e)&&this.c.push(e)}},W(e)){let{group:r}=e,i=e.previousGroup;if(r===vn.EX&&yn(e.power,t,n),r===vn.CP||r===vn.CB||i===vn.CP||i===vn.CB)for(let r in e.symbols)Object.hasOwn(e.symbols,r)&&yn(e.symbols[r],t,n);else if(r===vn.S||i===vn.S)e.value===`e`||e.value===`pi`||e.value===U.IMAGINARY||n.add(e.value);else if(r===vn.PL||i===vn.PL)yn(Oe(e.symbols),t,n);else if(r===vn.EX)isNaN(Number(e.value))||n.add(e.value),yn(e.power,t,n);else if(r===vn.FN&&!t&&e.args)for(let r=0;r<e.args.length;r++)yn(e.args[r],t,n)}return n.c.sort()}function bn(e,t,n){let r=[];e.each(e=>{let n,i;e.contains(t)?(n=e.stripVar(t),i=je._.divide(e.clone(),n.clone()).power.toDecimal()):(n=e,i=0);let a=r[i];r[i]=a?je._.add(a,n):n},!0);for(let e=0;e<r.length;e++)r[e]||=new f.classes.NerdamerSymbol(0);return r}var xn={get _(){return f.parser},get FN(){return f.groups.FN},get P(){return f.groups.P},get N(){return f.groups.N},get NerdamerSymbol(){return f.classes.NerdamerSymbol}};function Sn(e){let t,n,r;if(e.group===xn.FN&&e.fname===``?(t=xn.NerdamerSymbol.unwrapPARENS(xn._.parse(e).toLinear()),n=xn._.parse(e.power)):e.group===xn.P&&(t=xn._.parse(e.value),n=xn._.parse(e.power)),t&&n&&t.group===xn.N&&n.group===xn.N&&t.multiplier.isNegative()){r=[];let i=xn.NerdamerSymbol.toPolarFormArray(en(e))[0],a=xn._.arg(t),o=n.multiplier.den.toString(),s=n.multiplier.num.toString();for(let e=0;e<Number(o);e++){let t=en(xn._.parse(V(`(({0})+2*pi*({1}))/({2})`,a,e,o))).multiplier.toDecimal();r.push(en(xn._.parse(V(`(({0})^({1})*(cos({3})+({2})*sin({3})))^({4})`,i,o,U.IMAGINARY,t,s))))}return an.fromArray(r)}if(e.isConstant(!0,!0)){let t=e.sign(),n=en(e.abs()),i=xn._.sqrt(n);r=[i.clone(),i.negate()],t<0&&(r=r.map(e=>xn._.multiply(e,xn.NerdamerSymbol.imaginary())))}else r=[xn._.parse(e)];return an.fromArray(r)}function Cn(e,t,n){let r={},i;for(let e=0;e<n.length;e++)r[n[e]]=new f.classes.NerdamerSymbol(Math.floor(Math.random()*5)+1);return $t(`PARSE2NUMBER`,()=>{i=je._.parse(e,r).equals(je._.parse(t,r))}),i}function wn(e){return W(e)?wn(e.multiplier.toDecimal()):Number(e)%1!=0}function Tn(e,t){let n=new f.classes.NerdamerSymbol(0);for(let t=0;t<e.length;t++){let r=e[t];n=je._.add(n,W(r)?r:je._.parse(r))}return t?Number(n):n}function En(e){for(let t=0;t<e.length;t++)if(!(e[t].isPi()||e[t].isE())&&!e[t].isConstant(!0))return!1;return!0}function tee(e,t){t||=e.length;for(let n=0;n<t;n++)e[n]||(e[n]=new f.classes.NerdamerSymbol(0));return e}function Dn(e){return W(e)?e.multiplier.lessThan(0):typeof e==`object`&&`lessThan`in e?e.lessThan(0):e<0}var On={get _(){return f.parser},get S(){return f.groups.S},get FN(){return f.groups.FN},get EX(){return f.groups.EX},get ABS(){return f.fnNames.ABS}};function kn(e,t){e=On._.expand(e),t||={};let n=function(e,n){t[e]||=new f.classes.NerdamerSymbol(0),t[e]=On._.add(t[e],n.clone())};return e.each(e=>{e.isConstant(`all`)?n(`constants`,e):e.group===On.S?n(e.value,e):e.group===On.FN&&(e.fname===On.ABS||e.fname===``)?kn(e.args[0]):e.group===On.EX||e.group===On.FN||n(yn(e).join(` `),e)}),t}var An={get _(){return f.parser},get CP(){return f.groups.CP}};function jn(e,t,n){t=String(t);let r,i;
2642if(e.group===An.CP){let n=An._.expand(e.clone()).stripVar(t);r=An._.subtract(e.clone(),n.clone()),i=n}else r=e.clone();let a=r.stripVar(t),o=An._.divide(r.clone(),a.clone());return i||=new f.classes.NerdamerSymbol(0),n?{a,x:o,ax:r,b:i}:[a,o,r,i]}function Mn(e,t,n){(t.isComposite()&&!e.isComposite()||t.isLinear()&&!e.isLinear())&&([e,t]=[t,e]);let r=new f.classes.NerdamerSymbol(0);return e.isLinear()?e.each(e=>{if(t.isComposite())t.isLinear()?t.each(t=>{let i=je._.multiply(je._.parse(e),je._.parse(t)),a=je._.expand(je._.parse(i),n);r=je._.add(r,a)},!0):r=je._.add(r,je._.multiply(e,je._.parse(t)));else{let i=je._.multiply(je._.parse(e),je._.parse(t));r=je._.add(r,je._.expand(i,n))}},!0):r=je._.multiply(e,t),r}function Nn(e){if(z(e)){let t=new an([]);for(let n=0;n<e.length;n++)t.elements.push(Nn(e[n]));return t}return W(e)?e:je._.parse(e)}function Pn(e){let t=yn(e[0],null,null);for(let n=1,r=e.length;n<r;n++)t=t.concat(yn(e[n]));return t=ue(t).sort(),t}function Fn(e){let t=`u`,n=0,r=yn(e);for(;!(Fe.RESERVED.indexOf(t)===-1&&r.indexOf(t)===-1);)t=`u`+ n++;for(let e=0,n=Fe.RESERVED.length;e<=n;e++)if(!Fe.RESERVED[e]){Fe.RESERVED[e]=t;break}return t}var In={get _(){return f.parser},get C(){return f.core},get USER_FUNCTIONS(){return f.state.USER_FUNCTIONS}};function Ln(e,t,n){if(!t){let r=typeof e;if(r===`string`){let r=e;if(!/:?=/u.test(r))return!1;let i=U.FUNCTION_REGEX.exec(r);if(!i)return!1;let[,a,o,s]=i;e=a,t=o.split(`,`).map(e=>e.trim()),n=s}else if(r===`function`){let t=e,n=t.name;return ze(n),Be(n)?!1:(In.C.Math2[n]=t,In._.functions[n]=[void 0,t.length],In.USER_FUNCTIONS.includes(n)||In.USER_FUNCTIONS.push(n),!0)}else return!1}return e=e.trim(),ze(e),Be(e)?!1:(t||=yn(In._.parse(n)),t=t.map(e=>e.trim()),In._.functions[e]=[In._.mappedFunction,t.length,{name:e,params:t,body:n}],In.USER_FUNCTIONS.includes(e)||In.USER_FUNCTIONS.push(e),!0)}var Rn={get _(){return f.parser},get C(){return f.core},get USER_FUNCTIONS(){return f.state.USER_FUNCTIONS}};function zn(){for(let e of Rn.USER_FUNCTIONS)delete Rn.C.Math2[e],delete Rn._.functions[e]}function Bn(){let e={};for(let t in je._.functions)Object.hasOwn(je._.functions,t)&&(e[t]=je._.functions[t][0]);return e}var Vn={get bigInt(){return f.ext.bigInt},get isSymbol(){return f.utils.isSymbol},get isVector(){return f.utils.isVector},get N(){return f.groups.N},get P(){return f.groups.P},get S(){return f.groups.S},get FN(){return f.groups.FN},get PL(){return f.groups.PL},get CB(){return f.groups.CB},get CP(){return f.groups.CP},get EX(){return f.groups.EX},get CUSTOM_OPERATORS(){return f.state.CUSTOM_OPERATORS}};function Hn(e,t=void 0,n=void 0,r=void 0){let i=t===`hash`,a,o=i?void 0:t,s=o===`decimal`||o===`decimals`||o===`decimals_or_scientific`;o===`decimals_or_scientific`&&typeof r>`u`&&(r=U.DEFAULT_DECP);function c(e,n){switch(t){case`decimals`:case`decimal`:return a||=function(e){return!1},n?e.toDecimal(n):e.valueOf();case`recurring`:{a||=function(e){return e.indexOf(`'`)!==-1};let t=e.toString(),n=/^-?\d+(?:\/\d+)?$/u.exec(t);if(n.length===0)return t;let r=n[0].split(`/`),i=!1,o=Number(r[0]);o<0&&(o=-o,i=!0);let s=Number(r[1]);s||=1;let c=Math.floor(o/s),l=10*(o-c*s);for(c=`${c.toString()}.`;l&&l<s;)l*=10,c+=`0`;let u=``,d=[],f=0;for(;;){if(typeof d[l]<`u`){let e=u.slice(0,d[l]),t=u.slice(d[l]),n=`${c+e}'${t}'`;return(i?`-`:``)+n.replace(`'0'`,``).replace(/\.$/u,``)}let e=Math.floor(l/s),t=l-e*s;d[l]=f,u+=e.toString(),f+=1,l=10*t}}case`mixed`:{a||=function(e){return e.indexOf(`/`)!==-1};let t=e.toString(),n=/^-?\d+(?:\/\d+)?$/u.exec(t);if(n.length===0)return t;let r=n[0].split(`/`),i=new Vn.bigInt(r[0]),o=new Vn.bigInt(r[1]);o.equals(0)&&(o=new Vn.bigInt(1));let s=i.divmod(o),{quotient:c}=s,{remainder:l}=s,u=r[0][0]===`-`||c.equals(0)||l.equals(0)?``:`+`;return(c.equals(0)?``:c.toString())+u+(l.equals(0)?``:`${l.toString()}/${r[1]}`)}case`scientific`:return a||=function(e){return!1},new te(e.valueOf()).toString(U.SCIENTIFIC_MAX_DECIMAL_PLACES);case`decimals_or_scientific`:{a||=function(e){return!1};let t=e.valueOf(),r=new te(t);return Math.abs(r.exponent)>=U.SCIENTIFIC_SWITCH_FROM_DECIMALS_MIN_EXPONENT?r.toString(U.SCIENTIFIC_MAX_DECIMAL_PLACES):n?e.toDecimal(n):t}default:return a||=function(e){return e.indexOf(`/`)!==-1},e.toString()}}if(Vn.isSymbol(e)){let l=``,u=``,d=``,f=e.group||n,{value:p}=e;if(!i){let t=c(e.multiplier);
2642String(t)===`-1`&&String(e.multiplier)===`-1`&&(d=`-`,t=`1`),String(t)!==`1`&&(l=t);let n=e.power?c(e.power):``;String(n)!==`1`&&(u=W(n)?Hn(n,o):n)}switch(f){case Vn.N:{l=``;let t;t=o===`decimals_or_scientific`?c(e.multiplier,r):r&&s?e.multiplier.toDecimal(r):c(e.multiplier),p=String(e.multiplier)===`-1`?`1`:t,u=``;break}case Vn.PL:p=e.collectSymbols().map(e=>{let t=Hn(e,o,n,r);return t===`0`&&(t=``),t}).sort().join(`+`).replace(/\+-/gu,`-`);break;case Vn.CP:p=e.collectSymbols().map(e=>{let t=Hn(e,o,n,r);return t===`0`&&(t=``),t}).sort().join(`+`).replace(/\+-/gu,`-`);break;case Vn.CB:p=e.collectSymbols(e=>{let t=e.group;return(t===Vn.PL||t===Vn.CP)&&e.power.equals(1)&&e.multiplier.equals(1)?ne(Hn(e,o)):Hn(e,o)}).join(`*`);break;case Vn.EX:{let t=e.previousGroup,n=e.power.group;t===Vn.PL&&(p=e.collectSymbols(Hn,o).join(`+`).replace(`+-`,`-`)),!(t===Vn.N||t===Vn.S||t===Vn.FN)&&!i&&(p=ne(p)),(n===Vn.CP||n===Vn.CB||n===Vn.PL||e.power.multiplier.toString()!==`1`)&&u&&(u=ne(u));break}}if(f===Vn.FN&&(p=e.fname+ne(e.args.map(e=>Hn(e,o)).join(`,`))),f===Vn.FN&&e.fname in Vn.CUSTOM_OPERATORS){let t=Hn(e.args[0]),n=Hn(e.args[1]);e.args[0].isComposite()&&(t=ne(t)),e.args[1].isComposite()&&(n=ne(n)),p=t+Vn.CUSTOM_OPERATORS[e.fname]+n}let m=typeof a==`function`?a(u):!1;if(u&&f!==Vn.EX&&m&&(u=ne(u)),((f===Vn.CP||f===Vn.PL)&&(l&&String(l)!==`1`||d===`-`)||(f===Vn.CB||f===Vn.CP||f===Vn.PL)&&u&&String(u)!==`1`||!i&&f===Vn.P&&String(p)===`-1`||e.fname===U.PARENTHESIS)&&(p=ne(p)),r&&(t===`decimal`||(t===`decimals`||t===`decimals_or_scientific`)&&l))if(l.toString().includes(`e`)){if(t!==`decimals_or_scientific`){let e=Number(l),t=e.toExponential(),n=e.toPrecision(r);l=t.length<n.length?t:n}}else l=ge(Number(l),r);let h=d+l,g=typeof a==`function`?a(l):!1;if(l&&g&&(h=ne(h)),Number(u)<0&&(u=ne(u)),l&&(h=`${h}*`),u){if(p===`e`&&U.E_TO_EXP)return`${h}exp${ne(u)}`;u=U.POWER_OPERATOR+u}f===Vn.EX&&p.charAt(0)===`-`&&(p=ne(p));let _=h+p;return e.parens&&(_=ne(_)),_+u}if(Vn.isVector(e)){let n=e.elements.length,r=[];for(let i=0;i<n;i++)r.push(e.elements[i].text(t));return`[${r.join(`,`)}]`}try{return e.toString()}catch(e){if(e.message===`timeout`)throw e;return``}}var G={get bigDec(){return f.ext.bigDec},get bigInt(){return f.ext.bigInt},get _(){return f.parser},get N(){return f.groups.N},get P(){return f.groups.P},get S(){return f.groups.S},get FN(){return f.groups.FN},get PL(){return f.groups.PL},get CB(){return f.groups.CB},get CP(){return f.groups.CP},get EX(){return f.groups.EX},get CONST_HASH(){return f.fnNames.CONST_HASH},get isSymbol(){return f.utils.isSymbol},get text(){return f.utils.text},get variables(){return f.utils.variables},get SQRT(){return f.fnNames.SQRT},get PARENTHESIS(){return f.fnNames.PARENTHESIS}},K=class e{group;value;multiplier;power;args=void 0;fname=void 0;isImgSymbol=void 0;imaginary=void 0;isInfinity=void 0;constructor(e){Jt();let t=e===`Infinity`;typeof e==`object`&&e&&e instanceof G.bigDec&&(e=e.toString());let n=String(e);/^(?<sign>-?\+?\d+)\.?\d*e?-?\+?\d*/iu.test(n)||typeof e==`object`&&e&&e instanceof G.bigDec?(this.group=G.N,this.value=G.CONST_HASH,this.multiplier=new P(e)):(this.group=G.S,ze(e),this.value=e,this.multiplier=new P(1),this.imaginary=e===U.IMAGINARY,this.isInfinity=t),this.power=new P(1)}static imaginary(){let t=new e(U.IMAGINARY);return t.imaginary=!0,t}static infinity(t=void 0){let n=new e(`Infinity`);return t===-1&&n.negate(),n}static shell(t,n){let r=new e(n);return r.group=t,r.symbols={},r.length=0,r}static unwrapSQRT(e,t){let n=e.power;if(e.fname===U.SQRT&&(e.isLinear()||t)){let r=e.args[0].clone();r.power=r.power.multiply(new P(1/2)),r.multiplier=r.multiplier.multiply(e.multiplier),e=r,t&&(e.power=n.multiply(new P(1/2)))}return e}static hyp(t,n){t||=new e(0),n||=new e(0);let{_:r}=G;return r.sqrt(r.add(r.pow(t.clone(),new e(2)),r.pow(n.clone(),new e(2))))}static toPolarFormArray(t){let n=t.realpart(),r=t.imagpart();return[e.hyp(n,r),n.equals(0)?G._.parse(`pi/2`):G._.trig.atan(G._.divide(r,n))]}static unwrapPARENS(t){if(t.fname===``){let n=t.args[0];return n.power=n.power.multiply(t.power),n.multiplier=n.multiplier.multiply(t.multiplier),t.fname===``?e.unwrapPARENS(n):n}return t}static create(e,t){t=t===void 0?1:t;let{_:n}=G;return n.parse(`(${e})^(${t})`)}pushMinus(){let{_:e}=G,t=this;if((this.group===G.CB||this.group===G.CP||this.group===G.PL)&&this.multiplier.lessThan(0)&&!ce(this.power)){t=this.clone();let n=t.multiplier.clone();n.negate(),t.toUnitMultiplier();for(let e in t.symbols)if(Object.hasOwn(t.symbols,e)&&(t.symbols[e]=t.symbols[e].clone().negate(),t.group===G.CB))break;t.length>0&&t.each(e=>
2642e.pushMinus()),t=e.parse(t),t=e.multiply(e.parse(n),t)}return t}getNth(e){let{_:t}=G,n=t.parse(String(e)),r=en(t.pow(t.parse(this.multiplier),n.clone().invert())),i=t.parse(ge(r));return en(t.pow(i,n.clone())).equals(t.parse(this.multiplier))?i:r}isToNth(e){let{_:t}=G,n=fe(this.getNth(e).multiplier.toDecimal()),r;return this.group===G.CB?(r=!0,this.each(t=>{t.isToNth(e)||(r=!1)})):r=this.group===G.N?!0:fe(t.divide(t.parse(this.power),t.parse(e))),n&&r}isSquare(){return this.isToNth(2)}isCube(){return this.isToNth(3)}isSimple(){return this.power.equals(1)&&this.multiplier.equals(1)}powSimp(){let{_:t}=G;if(this.group===G.CB){let n=[],r=this.multiplier.sign();if(this.each(e=>{let t=e.power;G.isSymbol(t)||t.equals(1)||n.push(t)}),n.length===0)return this.clone();let i=new P(se(n)),a=this.multiplier.clone().abs(),o=mn.ifactor(a.valueOf()),s=new P(1),c=new P(1);for(let e in o){if(!Object.hasOwn(o,e))continue;let n=new P(o[e]);n.lessThan(i)||(n=n.divide(i).subtract(new P(1)),c=c.multiply(new P(e))),s=s.multiply(t.parse(`${ne(e)}^${ne(n)}`).multiplier)}let l=new e(c);this.each(e=>{e=e.clone(),e.power=e.power.divide(i),l=t.multiply(l,e)});let u=t.symfunction(G.PARENTHESIS,[l]);return u.power=i,u.multiplier=r<0?s.negate():s,u}return this.clone()}equals(t){let n;return n=G.isSymbol(t)?t:new e(t),this.value===n.value&&this.power.equals(n.power)&&this.multiplier.equals(n.multiplier)&&this.group===n.group}abs(){let e=this.clone();return e.multiplier.abs(),e}gt(t){G.isSymbol(t)||(t=new e(t));let n=t;return this.isConstant()&&n.isConstant()&&this.multiplier.greaterThan(n.multiplier)}gte(t){G.isSymbol(t)||(t=new e(t));let n=t;return this.equals(n)||this.isConstant()&&n.isConstant()&&this.multiplier.greaterThan(n.multiplier)}lt(t){G.isSymbol(t)||(t=new e(t));let n=t;return this.isConstant()&&n.isConstant()&&this.multiplier.lessThan(n.multiplier)}lte(t){G.isSymbol(t)||(t=new e(t));let n=t;return this.equals(n)||this.isConstant()&&n.isConstant()&&this.multiplier.lessThan(n.multiplier)}isPoly(e=!1){let t=this.group,n=this.power;if(!fe(n)||Number(n)<0)return!1;if(t===G.N||t===G.S||this.isConstant(!0))return!0;let r=G.variables(this);if(t===G.CB&&r.length===1){let e=r[0];if(!e)return!0;for(let t in this.symbols){if(!Object.hasOwn(this.symbols,t))continue;let n=this.symbols[t];if(n.group===G.FN&&!n.args[0].isConstant()||!n.contains(e)&&!n.isConstant(!0))return!1}return!0}if(this.isComposite()||t===G.CB&&e){if(!e&&r.length>1)return!1;for(let t in this.symbols)if(!this.symbols[t].isPoly(e))return!1;return!0}return!1}stripVar(t,n=!1){let{_:r}=G,i;return(this.group===G.PL||this.group===G.S)&&this.value===t?i=new e(n?0:this.multiplier):this.group===G.CB&&this.isLinear()?(i=new e(1),this.each(e=>{e.contains(t,!0)||(i=r.multiply(i,e.clone()))}),i.multiplier=i.multiplier.multiply(this.multiplier)):this.group===G.CP&&!this.isLinear()?i=new e(this.multiplier):this.group===G.CP&&this.isLinear()?(i=new e(0),this.each(e=>{if(!e.contains(t)){let t=e.clone();t.multiplier=t.multiplier.multiply(this.multiplier),i=r.add(i,t)}}),i.equals(0)&&(i=new e(this.multiplier))):i=this.group===G.EX&&this.power.contains(t,!0)||this.group===G.FN&&this.contains(t)?new e(this.multiplier):this.clone(),i}toArray(t,n){let{_:r}=G;n||={arr:[],add(e,t){let n=this.arr[t];this.arr[t]=n?r.add(n,e):e}};let i=this.group;if(i===G.S&&this.contains(t))n.add(new e(this.multiplier),this.power);else if(i===G.CB){let e=this.stripVar(t),i=r.divide(this.clone(),e.clone()),a=i.isConstant()?0:i.power;n.add(e,a)}else if(i===G.PL&&this.value===t)this.each((e,r)=>{n.add(e.stripVar(t),r)});else if(i===G.CP)this.each(e=>{e.toArray(t,n)});else{if(this.contains(t))throw new S(`Cannot convert to array! Exiting`);n.add(this.clone(),0)}n=n.arr;for(let t=0;t<n.length;t++)n[t]||=new e(0);return n}hasFunc(e){let t=this.group===G.FN||this.group===G.EX;if(t&&!e||t&&this.contains(e))return!0;if(this.symbols){for(let t in this.symbols)if(this.symbols[t].hasFunc(e))return!0}return!1}sub(t,n){let{_:r}=G;t=G.isSymbol(t)?t.clone():r.parse(t),n=G.isSymbol(n)?n.clone():r.parse(n),(t.group===G.N||t.group===G.P)&&Ht(`Cannot substitute a number. Must be a variable`);let i=!1,a=t.multiplier.equals(1),o=this.multiplier.clone(),s;if(this.value===t.value&&(this.group!==G.PL&&t.group!==G.PL||this.group===G.PL&&t.group===G.PL))(a||t.multiplier.equals(this.multiplier))&&(t.isLinear()?s=n:t.power.equals(this.power)&&(s=n,i=!0),t.multiplier.equals(this.multiplier)&&(o=new P(1)));else if(this.group===G.CB||this.previousGroup===G.CB)s=new e(1),this.each(e=>{let i=r.parse(e.sub(t,n));s=r.multiply(s,i)});else if(this.isComposite()){let i=this.clone();if(t.isComposite()&&i.isComposite()&&i.isLinear()&&t.isLinear()){let e=function(t,n){for(let r in t.symbols){if(!Object.hasOwn(t.symbols,r))continue;let i=t.symbols[r];if(i.isComposite()&&e(i,n)||i.equals(n))return!0}return!1};for(let n in t.symbols)if(Object.hasOwn(t.symbols,n)&&!e(i,t.symbols[n]))return i.clone();s=r.add(r.subtract(i.clone(),t),n)}else s=new e(0),i.each(e=>{s=r.add(s,e.sub(t,n))})}else if(this.group===G.EX)s=r.parse(this.value).sub(t,n);else if(this.group===G.FN){let e=[];for(let i=0;i<this.args.length;i++){let a=this.args[i];G.isSymbol(a)||(a=r.parse(a)),e.push(a.sub(t,n))}s=r.symfunction(this.fname,e)}if(s){if(!i){let e=this.group===G.EX?this.power.sub(t,n):r.parse(this.power);s=r.pow(s,e)}return s.multiplier=s.multiplier.multiply(o),s}return this.clone()}isMonomial(){if(this.group===G.S)return!0;
2642if(this.group===G.CB){for(let e in this.symbols)if(this.symbols[e].group!==G.S)return!1}else return!1;return!0}isPi(){return this.group===G.S&&this.value===`pi`}sign(){return this.multiplier.sign()}isE(){return this.value===`e`}isSQRT(){return this.fname===G.SQRT}isConstant(e,t){if(t&&this.group===G.CB){for(let e in this.symbols)if(this.symbols[e].isConstant(!0))return!0}if(e===`functions`&&this.isComposite()){let n=!0;return this.each(r=>{r.isConstant(e,t)||(n=!1)},!0),n}if(e===`all`&&(this.isPi()||this.isE()))return!0;if(e&&this.group===G.FN){for(let t=0;t<this.args.length;t++)if(!this.args[t].isConstant(e))return!1;return!0}return e?Me(this):this.value===G.CONST_HASH}isImaginary(){if(this.imaginary)return!0;if(this.symbols){for(let e in this.symbols)if(this.symbols[e].isImaginary())return!0}return!1}realpart(){let{_:t}=G;if(this.isConstant())return this.clone();if(this.imaginary)return new e(0);if(this.isComposite()){let n=new e(0);return this.each(e=>{n=t.add(n,e.realpart())}),n}return this.isImaginary()?new e(0):this.clone()}imagpart(){let{_:t}=G;if(this.group===G.S&&this.isImaginary()){let t=this;return this.power.isNegative()&&(t=this.clone(),t.power.negate(),t.multiplier.negate()),new e(t.multiplier)}if(this.isComposite()){let n=new e(0);return this.each(e=>{n=t.add(n,e.imagpart())}),n}return this.group===G.CB?this.stripVar(U.IMAGINARY):new e(0)}isInteger(){return this.isConstant()&&this.multiplier.isInteger()}isLinear(e){if(e){if(this.isConstant()||!this.contains(e,!0))return!0;if(this.group===G.S)return this.value===e?this.power.equals(1):!0;if(this.isComposite()&&this.power.equals(1)){for(let t in this.symbols)if(!this.symbols[t].isLinear(e))return!1;return!0}return this.group===G.CB?this.symbols[e]?this.symbols[e].isLinear(e):!0:!1}return this.power.equals(1)}containsFunction(e){if(typeof e==`string`&&(e=[e]),this.group===G.FN&&e.indexOf(this.fname)!==-1)return!0;if(this.symbols){for(let t in this.symbols)if(this.symbols[t].containsFunction(e))return!0}return!1}multiplyPower(t){let{_:n}=G;if(this.group===G.N&&this.multiplier.equals(1))return this;let r=this.power;if(this.group!==G.EX&&G.isSymbol(t)&&t.group===G.N){let e=t.multiplier;this.group===G.N&&!e.isInteger()&&this.convert(G.P),this.power=r.equals(1)?e.clone():r.multiply(e),this.group===G.P&&fe(this.power)&&(this.value=String(Number(this.value)**Number(this.power)),this.toLinear(),this.convert(G.N))}else{this.group!==G.EX&&(r=new e(r),this.convert(G.EX));let i=n.multiply(r,t);this.power=i}return this}setPower(e,t=!1){if(this.group===G.N&&this.multiplier.equals(1))return this;if(this.group===G.EX&&!G.isSymbol(e))this.group=this.previousGroup,delete this.previousGroup,this.group===G.N?(this.multiplier=new P(this.value),this.value=G.CONST_HASH):this.power=e;else{let n=!1;G.isSymbol(e)&&(e.group===G.N?e=e.multiplier:n=!0);let r=n?G.EX:G.P;this.power=e,this.group===G.N&&r&&this.convert(r,t)}return this}isInverse(){return this.group===G.EX?this.power.multiplier.lessThan(0):Number(this.power)<0}clone(t=void 0){let n=this,r=t||new e(0),i=[`value`,`group`,`length`,`previousGroup`,`imaginary`,`fname`,`args`,`isInfinity`,`scientific`],a=i.length,o;if(n.symbols){r.symbols={};for(let e in n.symbols)Object.hasOwn(n.symbols,e)&&(r.symbols[e]=n.symbols[e].clone())}for(o=0;o<a;o++)n[i[o]]!==void 0&&(r[i[o]]=n[i[o]]);r.power=n.power.clone(),r.multiplier=n.multiplier.clone();let s=n,c=r;return s.isConversion&&(c.isConversion=s.isConversion),s.isUnit&&(c.isUnit=s.isUnit),r}toUnitMultiplier(e=!1){return this.multiplier.num=new G.bigInt(this.multiplier.num.isNegative()&&e?-1:1),this.multiplier.den=new G.bigInt(1),this}toLinear(){return this.power.equals(1)||this.setPower(new P(1)),this}each(e,t=!1){if(this.symbols)for(let n in this.symbols){if(!Object.hasOwn(this.symbols,n))continue;let r=this.symbols[n];if(r.group===G.PL&&t)for(let t in r.symbols)Object.hasOwn(r.symbols,t)&&e.call(n,r.symbols[t],t);else e.call(this,r,n)}else e.call(this,this,this.value)}valueOf(){return this.group===G.N?this.multiplier.valueOf():this.power.equals(0)?1:this.multiplier.equals(0)?0:G.text(this,`decimals`)}contains(e,t=!1){e=String(e);let n=this.group;if(this.value===e)return!0;
2642if(this.symbols){for(let n in this.symbols)if(this.symbols[n].contains(e,t))return!0}if(n===G.FN||this.previousGroup===G.FN){for(let n=0;n<this.args.length;n++)if(this.args[n].contains(e,t))return!0}return n===G.EX&&(t&&this.power.contains(e,t)||this.value===e)?!0:this.value===e}negate(){return this.multiplier.negate(),(this.group===G.CP||this.group===G.PL)&&this.distributeMultiplier(),this}invert(e=!1,t=!1){return e||(this.multiplier=this.multiplier.invert()),G.isSymbol(this.power)?this.power.negate():this.group===G.CB&&t?this.each(e=>e.invert()):this.power&&this.group!==G.N&&this.power.negate(),this}distributeMultiplier(e=!1){let t=e?this.power.absEquals(1):this.power.equals(1);if(this.symbols&&t&&this.group!==G.CB&&!this.multiplier.equals(1)){for(let e in this.symbols){if(!Object.hasOwn(this.symbols,e))continue;let t=this.symbols[e];t.multiplier=t.multiplier.multiply(this.multiplier),t.distributeMultiplier()}this.toUnitMultiplier()}return this}distributeExponent(){let{_:t}=G;if(!this.power.equals(1)){let n=this.power;for(let r in this.symbols){if(!Object.hasOwn(this.symbols,r))continue;let i=this.symbols[r];i.group===G.EX?i.power=t.multiply(i.power,new e(n)):G.isSymbol(this.symbols[r].power)?this.symbols[r].power=t.multiply(this.symbols[r].power,new e(n)):this.symbols[r].power=this.symbols[r].power.multiply(n)}this.toLinear()}return this}convert(t,n=void 0){if(t>G.FN){let e=this.clone();this.symbols={},t===G.CB?e.toUnitMultiplier():this.toUnitMultiplier(),this.group===G.FN&&(e.args=this.args,delete this.args,delete this.fname),this.isImgSymbol&&delete this.isImgSymbol,this.toLinear(),this.symbols[e.keyForGroup(t)]=e,this.group=t,this.length=1}else if(t===G.EX)this.group===G.N&&this.multiplier.equals(1)||(this.group!==G.EX&&(this.previousGroup=this.group),this.group===G.N?(this.value=this.multiplier.num.toString(),this.toUnitMultiplier()):this.value=G.text(this,`hash`),this.group=G.EX);else if(t===G.N){let t=this.multiplier.toDecimal();this.symbols&&=void 0,new e(this.group===G.P?Number(t)*Number(this.value)**Number(this.power):t).clone(this)}else t===G.P&&this.group===G.N&&(this.value=n?this.multiplier.num.toString():String(Math.abs(Number(this.multiplier.num.toString()))),this.toUnitMultiplier(!n),this.group=G.P);return this}insert(t,n){let{_:r}=G;if(G.isSymbol(t)||Ht(`Object ${t} is not of type NerdamerSymbol!`),this.symbols){let{group:i}=this;if(i>G.FN){let a=t.keyForGroup(i),o=a in this.symbols?this.symbols[a]:!1;if(n===`add`){let e=a;o?(this.symbols[e]=r.add(o,t),this.symbols[e].multiplier.equals(0)&&(delete this.symbols[e],this.length--,this.length===0&&(this.convert(G.N),this.multiplier=new P(0)))):(this.symbols[a]=t,this.length++)}else t.group===G.P&&fe(t.power)&&t.convert(G.N),t.group===G.EX?(t.parens=t.multiplier.lessThan(0),this.multiplier=this.multiplier.multiply(t.multiplier.clone().abs()),t.toUnitMultiplier(!0)):(this.multiplier=this.multiplier.multiply(t.multiplier),t.toUnitMultiplier()),o&&(t=r.multiply(ye(this.symbols,a),t),t.isConstant()&&(this.multiplier=this.multiplier.multiply(t.multiplier),t=new e(1)),this.length--),t.isOne(!0)?t.multiplier.lessThan(0)&&this.negate():(this.symbols[a]=t,this.length++);this.length===0&&this.convert(G.N),(this.group===G.CP||this.group===G.CB)&&this.updateHash()}}return this}attach(e){if(z(e)){for(let t=0;t<e.length;t++)this.insert(e[t],`add`);return this}return this.insert(e,`add`)}combine(e){if(z(e)){for(let t=0;t<e.length;t++)this.insert(e[t],`multiply`);return this}return this.insert(e,`multiply`)}updateHash(){if(this.group!==G.N)if(this.group===G.FN){let e=``,{args:t}=this,n=this.fname===G.PARENTHESIS;for(let n=0;n<t.length;n++)e+=(n===0?``:`,`)+G.text(t[n]);let r=n?``:this.fname;this.value=r+(n?e:ne(e))}else this.group===G.S||this.group===G.PL||(this.value=G.text(this,`hash`))}keyForGroup(e){let t=this.group,n;if(t===G.N)n=this.value;
2642else if(t===G.S||t===G.P)n=e===G.PL?this.power.toDecimal():this.value;else if(t===G.FN)n=e===G.PL?this.power.toDecimal():G.text(this,`hash`);else{if(t===G.PL)return n=e===G.CB?G.text(this,`hash`):e===G.CP?this.power.equals(1)?this.value:ne(G.text(this,`hash`))+U.POWER_OPERATOR+this.power.toDecimal():e===G.PL?this.power.toString():this.value,n;t===G.CP?(e===G.CP&&(n=G.text(this,`hash`)),n=e===G.PL?this.power.toDecimal():this.value):t===G.CB?n=e===G.PL?this.power.toDecimal():G.text(this,`hash`):t===G.EX&&(n=e===G.PL?G.text(this.power):G.text(this,`hash`))}return n}collectSymbols(e,t,n,r){let i=[];if(this.symbols)for(let n in this.symbols){if(!Object.hasOwn(this.symbols,n))continue;let a=this.symbols[n];r&&(a.group===G.PL||a.group===G.CP)?i=i.concat(a.collectSymbols()):i.push(e?e(a,t):a)}else i.push(this);return n===null&&(n=void 0),i.sort(n)}collectSummandSymbols(e,t,n,r){let i=[];if(!this.symbols||this.group===G.CB)i.push(this);else for(let n in this.symbols){if(!Object.hasOwn(this.symbols,n))continue;let a=this.symbols[n];r&&(a.group===G.PL||a.group===G.CP)?i=i.concat(a.collectSymbols()):i.push(e?e(a,t):a)}return n===null&&(n=void 0),i.sort(n)}latex(e){return dn.latex(this,e)}text(e=void 0){return G.text(this,e)}isOne(e=!1){let t=e?`absEquals`:`equals`;return this.group===G.N?this.multiplier[t](1):this.power.equals(0)}isComposite(){let e=this.group,t=this.previousGroup;return e===G.CP||e===G.PL||t===G.PL||t===G.CP}isCombination(){let e=this.group,t=this.previousGroup;return e===G.CB||t===G.CB}lessThan(e){return this.multiplier.lessThan(e)}greaterThan(t){return G.isSymbol(t)||(t=new e(t)),!this.isConstant(!0)||!t.isConstant(!0)?!1:this.multiplier.greaterThan(t.multiplier)}getDenom(){let{_:e}=G,t,n;if(n=this.clone(),this.group===G.CB&&this.power.lessThan(0)&&(n=e.expand(n)),n.power.lessThan(0)||n.group===G.EX&&n.power.multiplier.lessThan(0)){let r=e.parse(n.multiplier.den);t=n.toUnitMultiplier(),t.power.negate(),t=e.multiply(r,t)}else if(n.group===G.CB){t=e.parse(n.multiplier.den);for(let r in n.symbols){if(!Object.hasOwn(n.symbols,r))continue;let i=n.symbols[r];(Number(i.power)<0||i.group===G.EX&&i.power.multiplier.lessThan(0))&&(t=e.multiply(t,n.symbols[r].clone().invert()))}}else t=e.parse(n.multiplier.den);return t}getNum(){let{_:e}=G,t,n;return n=this.clone(),n.group===G.CB&&n.power.lessThan(0)&&(n=e.expand(n)),n.power.greaterThan(0)&&n.group!==G.CB||n.group===G.EX&&n.power.multiplier.greaterThan(0)?t=e.multiply(e.parse(n.multiplier.num),n.toUnitMultiplier()):n.group===G.CB?(t=e.parse(n.multiplier.num),n.each(n=>{(Number(n.power)>0||n.group===G.EX&&n.power.multiplier.greaterThan(0))&&(t=e.multiply(t,n.clone()))})):t=e.parse(n.multiplier.num),t}toString(){return this.text()}};f.classes.NerdamerSymbol=K;var Un=class{constructor(){let{N:e,P:t,S:n,EX:i,FN:a,PL:o,CB:s,CP:c}=je,{SQRT:l,ABS:u,FACTORIAL:d,DOUBLEFACTORIAL:f,PARENTHESIS:p}=je,{bigDec:m,PRIMES:h,VARS:g}=je,x=this,S=x,T={},D={names:[],actions:[]};class O{upper;lower;constructor(e,t){this.upper=e,this.lower=t}isConstant(){let e=this.upper,t=this.lower;return e.isConstant()&&t.isConstant()}text(){return`${Hn(this.upper)}:${Hn(this.lower)}`}}class A{static OPERATOR=`OPERATOR`;static VARIABLE_OR_LITERAL=`VARIABLE_OR_LITERAL`;static FUNCTION=`FUNCTION`;static UNIT=`UNIT`;static KEYWORD=`KEYWORD`;static MAX_PRECEDENCE=999;constructor(e,t,n){if(this.type=t,this.value=e,n!==void 0&&(this.column=n+1),t===A.OPERATOR){let t=L[e];for(let e in t)Object.hasOwn(t,e)&&(this[e]=t[e])}else t===A.FUNCTION&&(this.precedence=A.MAX_PRECEDENCE,this.leftAssoc=!1)}toString(){return this.is_prefix?`\`${this.value}`:this.value}}this.classes={Collection:ee,Slice:O,Token:A};let j={prec:void 0,cos(e,t){let n=S.parse(String(Math.cos(e)*Math.cosh(t))),r=S.parse(String(Math.sin(e)*Math.sinh(t)));return S.subtract(n,S.multiply(r,K.imaginary()))},sin(e,t){let n=S.parse(String(Math.sin(e)*Math.cosh(t))),r=S.parse(String(Math.cos(e)*Math.sinh(t)));return S.subtract(n,S.multiply(r,K.imaginary()))},tan(e,t){let n=S.parse(String(Math.sin(2*e)/(Math.cos(2*e)+Math.cosh(2*t)))),r=S.parse(String(Math.sinh(2*t)/(Math.cos(2*e)+Math.cosh(2*t))));return S.add(n,S.multiply(r,K.imaginary()))},sec(e,t){let n=this.removeDen(this.cos(e,t));return S.subtract(n[0],S.multiply(n[1],K.imaginary()))},csc(e,t){let n=this.removeDen(this.sin(e,t));return S.add(n[0],S.multiply(n[1],K.imaginary()))},cot(e,t){let n=this.removeDen(this.tan(e,t));return S.subtract(n[0],S.multiply(n[1],K.imaginary()))},acos(e,t){let n=this.fromArray([e,t]),r=S.pow(n.clone(),new K(2)),i=S.expand(r),a=S.multiply(Fe(S.subtract(new K(1),i)),K.imaginary()),o=Qe(S.expand(S.add(n.clone(),a)));return S.expand(S.multiply(K.imaginary().negate(),o))},asin(e,t){return S.subtract(S.parse(`pi/2`),this.acos(e,t))},atan(e,t){if(e.equals(0)&&(t.equals(1)||t.equals(-1)))return S.parse(`${K.infinity()}*${U.IMAGINARY}*${t}`);
2642let n=j.fromArray([e,t]),r=S.expand(S.multiply(K.imaginary(),n.clone())),i=Qe(S.expand(S.subtract(new K(1),r.clone()))),a=Qe(S.expand(S.add(new K(1),r.clone())));return S.expand(S.multiply(S.divide(K.imaginary(),new K(2)),S.subtract(i,a)))},asec(e,t){let n=this.removeDen([e,t]);return n[1].negate(),this.acos(...n)},acsc(e,t){let n=this.removeDen([e,t]);return n[1].negate(),this.asin(...n)},acot(e,t){let n=this.removeDen([e,t]);return n[1].negate(),this.atan(...n)},cosh(e,t){let n=S.parse(String(Math.cosh(e)*Math.cos(t))),r=S.parse(String(Math.sinh(e)*Math.sin(t)));return S.add(n,S.multiply(r,K.imaginary()))},sinh(e,t){let n=S.parse(String(Math.sinh(e)*Math.cos(t))),r=S.parse(String(Math.cosh(e)*Math.sin(t)));return S.add(n,S.multiply(r,K.imaginary()))},tanh(e,t){let n=S.parse(String(Math.sinh(2*e)/(Math.cos(2*t)+Math.cosh(2*e)))),r=S.parse(String(Math.sin(2*t)/(Math.cos(2*t)+Math.cosh(2*e))));return S.subtract(n,S.multiply(r,K.imaginary()))},sech(e,t){let n=this.removeDen(this.cosh(e,t));return S.subtract(n[0],S.multiply(n[1],K.imaginary()))},csch(e,t){let n=this.removeDen(this.sinh(e,t));return S.subtract(n[0],S.multiply(n[1],K.imaginary()))},coth(e,t){let n=this.removeDen(this.tanh(e,t));return S.add(n[0],S.multiply(n[1],K.imaginary()))},acosh(e,t){let n=this.fromArray([e,t]),r=Fe(S.add(n.clone(),new K(1))),i=Fe(S.subtract(n.clone(),new K(1)));return S.expand(Qe(S.add(n,S.expand(S.multiply(r,i)))))},asinh(e,t){let n=this.fromArray([e,t]),r=Fe(S.add(new K(1),S.expand(S.pow(n.clone(),new K(2)))));return S.expand(Qe(S.add(n,r)))},atanh(e,t){let n=this.fromArray([e,t]),r=Qe(S.add(n.clone(),new K(1))),i=Qe(S.subtract(new K(1),n));return S.expand(S.divide(S.subtract(r,i),new K(2)))},asech(e,t){let n=this.removeDen([e,t]);return n[1].negate(),this.acosh(...n)},acsch(e,t){let n=this.removeDen([e,t]);return n[1].negate(),this.asinh(...n)},acoth(e,t){let n=this.removeDen([e,t]);return n[1].negate(),this.atanh(...n)},sqrt(e){let t=e.realpart(),n=e.imagpart(),r=K.hyp(t,n),i=S.add(t.clone(),r),a=Fe(S.multiply(new K(2),i.clone()));return S.add(S.divide(i.clone(),a.clone()),S.multiply(S.divide(n,a),K.imaginary()))},log(e,t){let n=Qe(K.hyp(e,t)),r=U.USE_BIG?new K(m.atan2(t.multiplier.toDecimal(),e.multiplier.toDecimal())):Math.atan2(t,e),i=S.parse(r);return S.add(n,S.multiply(K.imaginary(),i))},erf(e,t){return S.symfunction(`erf`,[e])},removeDen(e){let t,n;z(e)?(t=e[0],n=e[1]):(t=e.realpart(),n=e.imagpart());let r=t**2+n**2;return[S.parse(String(t/r)),S.parse(String(n/r))]},fromArray(e){return S.add(e[0],S.multiply(K.imaginary(),e[1]))},evaluate(e,t){let n,r,i=e.power.sign();if(e.power=e.power.abs(),e.power.greaterThan(1)&&(e=S.expand(e)),i<0){let t=this.removeDen(e);n=t[0],r=t[1]}else n=e.realpart(),r=e.imagpart();return n.isConstant(`all`)&&r.isConstant(`all`)?this[t](n,r):S.symfunction(t,[e])}},N=this.trig={cos(e){if(e.equals(`pi`)&&e.multiplier.den.equals(2))return new K(0);if(U.PARSE2NUMBER){if(e.equals(new K(U.PI/2)))return new K(0);if(e.isConstant())return U.USE_BIG?new K(m.cos(e.multiplier.toDecimal())):new K(Math.cos(e.valueOf()));if(e.isImaginary())return j.evaluate(e,`cos`)}if(e.equals(0))return new K(1);let t,n=!1,r=et(e.multiplier.toDecimal()),i=e.multiplier.abs();if(e.multiplier=i,e.isPi()&&e.isLinear())if(fe(i))t=new K(ce(i)?1:-1);else{Number(i.num);let r=Number(i.den);r===2?t=new K(0):r===3?(t=S.parse(`1/2`),n=!0):r===4?(t=S.parse(`1/sqrt(2)`),n=!0):r===6?(t=S.parse(`sqrt(3)/2`),n=!0):t=S.symfunction(`cos`,[e])}return n&&(r===2||r===3)&&t.negate(),t||=S.symfunction(`cos`,[e]),t},sin(e){if(U.PARSE2NUMBER){if(e.isConstant())return Number(e.multiplier.toDecimal())%Math.PI===0?new K(0):U.USE_BIG?new K(m.sin(e.multiplier.toDecimal())):new K(Math.sin(e.valueOf()));if(e.isImaginary())return j.evaluate(e,`sin`)}if(e.equals(0))return new K(0);let t,n=!1,r=et(e.multiplier.toDecimal()),i=e.multiplier.sign(),a=e.multiplier.abs();if(e.multiplier=a,e.equals(`pi`))t=new K(0);else if(e.isPi()&&e.isLinear())if(fe(a))t=new K(0);else{a.num;let r=a.den;r.equals(2)?(t=new K(1),n=!0):r.equals(3)?(t=S.parse(`sqrt(3)/2`),n=!0):r.equals(4)?(t=S.parse(`1/sqrt(2)`),n=!0):r.equals(6)?(t=S.parse(`1/2`),n=!0):t=S.multiply(new K(i),S.symfunction(`sin`,[e]))}return t||=S.multiply(new K(i),S.symfunction(`sin`,[e])),n&&(r===3||r===4)&&t.negate(),t},tan(e){if(U.PARSE2NUMBER){if(Number(e.multiplier.toDecimal())%Math.PI===0&&e.isLinear())return new K(0);if(e.isConstant())return U.USE_BIG?new K(m.tan(e.multiplier.toDecimal())):new K(Math.tan(e.valueOf()));if(e.isImaginary())return j.evaluate(e,`tan`)}let t,n=!1,r=et(e.multiplier.toDecimal()),i=e.multiplier;if(e.multiplier=i,e.isPi()&&e.isLinear())if(fe(i))t=new K(0);else{i.num;let r=i.den;if(r.equals(2))throw new y(`tan is undefined for ${e.toString()}`);r.equals(3)?(t=S.parse(`sqrt(3)`),n=!0):r.equals(4)?(t=new K(1),n=!0):r.equals(6)?(t=S.parse(`1/sqrt(3)`),n=!0):t=S.symfunction(`tan`,[e])}return t||=S.symfunction(`tan`,[e]),n&&(r===2||r===4)&&t.negate(),t},sec(e){if(U.PARSE2NUMBER)return e.isConstant()?U.USE_BIG?new K(new m(1).dividedBy(m.cos(e.multiplier.toDecimal()))):new K(mn.sec(e.valueOf())):e.isImaginary()?j.evaluate(e,`sec`):S.parse(V(`1/cos({0})`,e));let t,n=!1,r=et(e.multiplier.toDecimal()),i=e.multiplier.abs();if(e.multiplier=i,e.isPi()&&e.isLinear())if(fe(i))t=new K(ce(i)?1:-1);else{i.num;let r=i.den;if(r.equals(2))throw new y(`sec is undefined for ${e.toString()}`);r.equals(3)?(t=new K(2),n=!0):r.equals(4)?(t=S.parse(`sqrt(2)`),n=!0):r.equals(6)?(t=S.parse(`2/sqrt(3)`),n=!0):t=S.symfunction(`sec`,[e])}return n&&(r===2||r===3)&&t.negate(),t||=S.symfunction(`sec`,[e]),t},csc(e){if(U.PARSE2NUMBER)return e.isConstant()?U.USE_BIG?new K(new m(1).dividedBy(m.sin(e.multiplier.toDecimal()))):new K(mn.csc(e.valueOf())):e.isImaginary()?j.evaluate(e,`csc`):S.parse(V(`1/sin({0})`,e));let t,n=!1,r=et(e.multiplier.toDecimal()),i=e.multiplier.sign(),a=e.multiplier.abs();if(e.multiplier=a,e.isPi()&&e.isLinear()){if(fe(a))throw new y(`csc is undefined for ${e.toString()}`);{a.num;let r=a.den;r.equals(2)?(t=new K(1),n=!0):r.equals(3)?(t=S.parse(`2/sqrt(3)`),n=!0):r.equals(4)?(t=S.parse(`sqrt(2)`),n=!0):r.equals(6)?(t=ne
2642w K(2),n=!0):t=S.multiply(new K(i),S.symfunction(`csc`,[e]))}}return t||=S.multiply(new K(i),S.symfunction(`csc`,[e])),n&&(r===3||r===4)&&t.negate(),t},cot(e){if(U.PARSE2NUMBER)return Number(e.multiplier.toDecimal())%(Math.PI/2)==0?new K(0):e.isConstant()?U.USE_BIG?new K(new m(1).dividedBy(m.tan(e.multiplier.toDecimal()))):new K(mn.cot(e.valueOf())):e.isImaginary()?j.evaluate(e,`cot`):S.parse(V(`1/tan({0})`,e));let t,n=!1,r=et(e.multiplier.toDecimal()),i=e.multiplier;if(e.multiplier=i,e.isPi()&&e.isLinear()){if(fe(i))throw new y(`cot is undefined for ${e.toString()}`);{i.num;let r=i.den;r.equals(2)?t=new K(0):r.equals(3)?(t=S.parse(`1/sqrt(3)`),n=!0):r.equals(4)?(t=new K(1),n=!0):r.equals(6)?(t=S.parse(`sqrt(3)`),n=!0):t=S.symfunction(`cot`,[e])}}return t||=S.symfunction(`cot`,[e]),n&&(r===2||r===4)&&t.negate(),t},acos(e){if(U.PARSE2NUMBER){if(e.isConstant())return e.gt(1)||e.lt(-1)?it(en(`pi/2-asin(${e.toString()})`)):U.USE_BIG?new K(m.acos(e.multiplier.toDecimal())):new K(Math.acos(e.valueOf()));if(e.isImaginary())return j.evaluate(e,`acos`)}return S.symfunction(`acos`,[e])},asin(e){if(U.PARSE2NUMBER){if(e.isConstant()){if(e.gt(1)||e.lt(-1)){let t=U.IMAGINARY,n=e.multiplier.toDecimal();return it(en(`${t}*log(sqrt(1-${n}^2)-${t}*${n})`))}return U.USE_BIG?new K(m.asin(e.multiplier.toDecimal())):new K(Math.asin(e.valueOf()))}if(e.isImaginary())return j.evaluate(e,`asin`)}return S.symfunction(`asin`,[e])},atan(e){let t;if(e.equals(0))t=new K(0);else{if(U.PARSE2NUMBER)return e.isConstant()?U.USE_BIG?new K(m.atan(e.multiplier.toDecimal())):new K(Math.atan(e.valueOf())):e.isImaginary()?j.evaluate(e,`atan`):S.symfunction(`atan`,[e]);t=e.equals(-1)?S.parse(`-pi/4`):S.symfunction(`atan`,[e])}return t},asec(e){if(U.PARSE2NUMBER){if(e.equals(0))throw new b(`Input is out of the domain of sec!`);if(e.isConstant())return N.acos(e.invert());if(e.isImaginary())return j.evaluate(e,`asec`)}return S.symfunction(`asec`,[e])},acsc(e){if(U.PARSE2NUMBER){if(e.isConstant())return N.asin(e.invert());if(e.isImaginary())return j.evaluate(e,`acsc`)}return S.symfunction(`acsc`,[e])},acot(e){if(U.PARSE2NUMBER){if(e.isConstant())return S.add(S.parse(`pi/2`),N.atan(e).negate());if(e.isImaginary())return j.evaluate(e,`acot`)}return S.symfunction(`acot`,[e])},atan2(e,t){if(e.equals(0)&&t.equals(0))throw new y(`atan2 is undefined for 0, 0`);return U.PARSE2NUMBER&&e.isConstant()&&t.isConstant()?new K(Math.atan2(e,t)):S.symfunction(`atan2`,[e,t])}},F=this.trigh={cosh(e){if(U.PARSE2NUMBER){if(e.isConstant())return new K(Math.cosh(e.valueOf()));if(e.isImaginary())return j.evaluate(e,`cosh`)}return S.symfunction(`cosh`,[e])},sinh(e){if(U.PARSE2NUMBER){if(e.isConstant())return new K(Math.sinh(e.valueOf()));if(e.isImaginary())return j.evaluate(e,`sinh`)}return S.symfunction(`sinh`,[e])},tanh(e){if(U.PARSE2NUMBER){if(e.isConstant())return new K(Math.tanh(e.valueOf()));if(e.isImaginary())return j.evaluate(e,`tanh`)}return S.symfunction(`tanh`,[e])},sech(e){return U.PARSE2NUMBER?e.isConstant()?new K(Math.sech(e.valueOf())):e.isImaginary()?j.evaluate(e,`sech`):S.parse(V(`1/cosh({0})`,e)):S.symfunction(`sech`,[e])},csch(e){return U.PARSE2NUMBER?e.isConstant()?new K(Math.csch(e.valueOf())):e.isImaginary()?j.evaluate(e,`csch`):S.parse(V(`1/sinh({0})`,e)):S.symfunction(`csch`,[e])},coth(e){return U.PARSE2NUMBER?e.isConstant()?new K(Math.coth(e.valueOf())):e.isImaginary()?j.evaluate(e,`coth`):S.parse(V(`1/tanh({0})`,e)):S.symfunction(`coth`,[e])},acosh(e){let t;return t=U.PARSE2NUMBER&&e.isImaginary()?j.evaluate(e,`acosh`):U.PARSE2NUMBER?en(S.parse(V(`${U.LOG}(({0})+sqrt(({0})^2-1))`,e.toString()))):S.symfunction(`acosh`,[e]),t},asinh(e){let t;return t=U.PARSE2NUMBER&&e.isImaginary()?j.evaluate(e,`asinh`):U.PARSE2NUMBER?en(S.parse(V(`${U.LOG}(({0})+sqrt(({0})^2+1))`,e.toString()))):S.symfunction(`asinh`,[e]),t},atanh(e){let t;return t=U.PARSE2NUMBER&&e.isImaginary()?j.evaluate(e,`atanh`):U.PARSE2NUMBER?en(S.parse(V(`(1/2)*${U.LOG}((1+({0}))/(1-({0})))`,e.toString()))):S.symfunction(`atanh`,[e]),t},asech(e){let t;return t=U.PARSE2NUMBER&&e.isImaginary()?j.evaluate(e,`asech`):U.PARSE2NUMBER?en(Qe(S.add(e.clone().invert(),Fe(S.subtract(S.pow(e,new K(-2)),new K(1)))))):S.symfunction(`asech`,[e]),t},acsch(e){let t;return t=U.PARSE2NUMBER&&e.isImaginary()?j.evaluate(e,`acsch`):U.PARSE2NUMBER?en(S.parse(V(`${U.LOG}((1+sqrt(1+({0})^2))/({0}))`,e.toString()))):S.symfunction(`acsch`,[e]),t},acoth(e){let t;if(U.PARSE2NUMBER&&e.isImaginary())t=j.evaluate(e,`acoth`);else if(U.PARSE2NUMBER)if(e.equals(1))t=K.infinity();else{let n=Qe(S.divide(S.add(e.clone(),new K(1)),S.subtract(e.clone(),new K(1))));t=en(S.divide(n,new K(2)))}else t=S.symfunction(`acoth`,[e]);return t}};this.units={};let L={"\\":{precedence:8,operator:`\\`,action:`slash`,prefix:!0,postfix:!1,leftAssoc:!0,operation(e){return e}},"!!":{precedence:7,operator:`!!`,action:`dfactorial`,prefix:!1,postfix:!0,leftAssoc:!0,operation(e){return S.symfunction(U.DOUBLEFACTORIAL,[e])}},"!":{precedence:7,operator:`!`,action:`factorial`,prefix:!1,postfix:!0,leftAssoc:!0,operation(e){return de(e)}},"^":{precedence:6,operator:`^`,action:`pow`,prefix:!1,postfix:!1,leftAssoc:!0},"**":{precedence:6,operator:`**`,action:`pow`,prefix:!1,postfix:!1,leftAssoc:!0},"%":{precedence:4,operator:`%`,action:`percent`,prefix:!1,postfix:!0,leftAssoc:!0,overloaded:!0,overloadAction:`mod`,overloadLeftAssoc:!1,operation(e){return S.divide(e,new K(100))}},"*":{precedence:4,operator:`*`,action:`multiply`,prefix:!1,postfix:!1,leftAssoc:!1},"/":{precedence:4,operator:`/`,action:`divide`,prefix:!1,postfix:!1,leftAssoc:!1},"+":{precedence:3,operator:`+`,action:`add`,prefix:!0,postfix:!1,leftAssoc:!1,operation(e){return e}},plus:{precedence:3,operator:`plus`,action:`add`,prefix:!0,postfix:!1,leftAssoc:!1,operation(e){return e}},"-":{precedence:3,operator:`-`,action:`subtract`,prefix:!0,postfix:!1,leftAssoc:!1,operation(e){return e.negate()}},"=":{precedence:2,operator:`=`,action:`equals`,prefix:!1,postfix:!1,leftAssoc:!1},"==":{precedence:1,operator:`==`,action:`eq`,prefix:!1,postfix:!1,leftAssoc:!1},"<":{precedence:1,operator:`<`,action:`lt`,prefix:!1,postfix:!1,leftAssoc:!1},"<=":{precedence:1,operator:`<=`,action:`lte`,prefix:!1,postfix:!1,leftAssoc:!1},">":{precedence:1,operator:`>`,action:`gt`,prefix:!1,postfix:!1,leftAssoc:!1},"=>":{precedence:1,operator:`=>`,action:`gte`,prefix:!1,postfix:!1,leftAssoc:!1},",":{precedence:0,operator:`,`,action:`comma`,prefix:!1,postfix:!1,leftAssoc:!1},":":{precedence:0,operator:`,`,action:`assign`,prefix:!1,postfix:!1,leftAssoc:!1,vectorFn:`slice`},":=":{precedence:0,operator:`,`,action:`functionAssign`,prefix:!1,postfix:!1,leftAssoc:!0}},R={"(":{type:`round`,id:1,is_open:!0,is_close:!1},")":{type:`round`,id:2,is_open:!1,is_close:!0},"[":{type:`square`,id:3,is_open:!0,is_close:!1,maps_to:`vector`},"]":{type:`square`,id:4,is_open:!1,is_close:!0},"{":{type:`curly`,id:5,is_open:!0,is_close:!1,maps_to:`NerdamerSet`},"}":{type:`curly`,id:6,is_open:!1,is_close:!0}},te=this.functions={cos:[N.cos,1],sin:[N.sin,1],tan:[N.tan,1],sec:[N.sec,1],csc:[N.csc,1],cot:[N.cot,1],acos:[N.acos,1],asin:[N.asin,1],atan:[N.atan,1],arccos:[N.acos,1],arcsin:[N.asin,1],arctan:[N.atan,1],asec:[N.asec,1],acsc:[N.acsc,1],acot:[N.acot,1],atan2:[N.atan2,2],acoth:[F.acoth,1],asech:[F.asech,1],acsch:[F.acsch,1],sinh:[F.sinh,1],cosh:[F.cosh,1],tanh:[F.tanh,1],asinh:[F.asinh,1],sech:[F.sech,1],csch:[F.csch,1],coth:[F.coth,1],acosh:[F.acosh,1],atanh:[F.atanh,1],log10:[void 0,1],log2:[void 0,1],log1p:[void 0,1],exp:[xe,1],radians:[Te,1],degrees:[ke,1],min:[Ye,-1],max:[Je,-1],erf:[void 0,1],floor:[void 0,1],ceil:[void 0,1],trunc:[void 0,1],Si:[void 0,1],step:[void 0,1],rect:[void 0,1],sinc:[be,1],tri:[void 0,1],sign:[Xe,1],Ci:[void 0,1],Ei:[void 0,1],Shi:[void 0,1],Chi:[void 0,1],Li:[void 0,1],fib:[void 0,1],fact:[de,1],factorial:[de,1],continuedFraction:[pe,[1,2]],dfactorial:[void 0,1],gamma_incomplete:[void 0,[1,2]],roun
2642d:[$e,[1,2]],scientific:[Le,[1,2]],mod:[me,2],pfactor:[ze,1],vector:[ht,-1],matrix:[gt,-1],NerdamerSet:[_t,-1],imatrix:[at,-1],parens:[se,-1],sqrt:[Fe,1],cbrt:[Ie,1],nthroot:[Re,2],log:[Qe,[1,2]],expand:[rt,1],abs:[ue,1],invert:[Ct,1],determinant:[vt,1],size:[yt,1],transpose:[St,1],dot:[bt,2],cross:[xt,2],vecget:[ot,2],vecset:[ct,3],vectrim:[st,[1,2]],matget:[lt,3],matset:[mt,4],matgetrow:[ut,2],matsetrow:[dt,3],matgetcol:[ft,2],matsetcol:[pt,3],rationalize:[Ae,1],IF:[_e,3],isIn:[ve,2],realpart:[Be,1],imagpart:[Ve,1],conjugate:[Ue,1],arg:[We,1],polarform:[Ge,1],rectform:[Ke,1],sort:[Ze,[1,2]],integer_part:[void 0,1],union:[wt,2],contains:[Et,2],intersection:[Tt,2],difference:[Dt,2],intersects:[Ot,2],isSubset:[kt,2],primes:[At,2],print:[jt,-1]};this.error=Ht;let ne=function(e){let t=U.FUNCTION_MODULES,n=t.length;for(let r=0;r<n;r++){let n=t[r];if(e in n)return n[e]}return Ht(`The function ${e} is undefined!`)};this.override=function(e,t){T[e]||=[],T[e].push(this[e]),this[e]=t},this.restore=function(e){this[e]&&=T[e].pop()},this.extend=function(e,t,n){let r=this;if(typeof this[e]==`function`&&typeof t==`function`){let i=this[e];this[e]=function(e,a){return W(e)&&W(a)&&!n?i.call(r,e,a):t.call(r,e,a,i)}}},this.symfunction=function(e,t){let n=new K(e);return n.group=a,typeof t==`object`&&(t=[].slice.call(t)),n.args=t,n.fname=e===p?``:e,n.updateHash(),n},this.callfunction=function(e,t,n=void 0){let r=te[e];r||Ht(`Nerdamer currently does not support the function ${e}`);let i=r[1]||n,a=r[0],o;if(t instanceof Array||(t=t===void 0?[]:[t]),i!==-1){let n=z(i),r=n?i[0]:i,a=n?i[1]:i,o=t.length,s=`${e} requires a {0} of {1} arguments. {2} provided!`;o<r&&Ht(V(s,`minimum`,r,o)),o>a&&Ht(V(s,`maximum`,a,o))}let s=Pe(t);return a?o=a.apply(r[2],t):(a=ne(e),o=U.PARSE2NUMBER&&s?tt(a.apply(a,t)):S.symfunction(e,t)),o},this.operator_filter_regex=(function(){let e=`^\\${Object.keys(L).filter(e=>e.length===1).join(`\\`)}`;return RegExp(`([${e}])\\s+([${e}])`)})(),this.setOperator=function(e,t=void 0,n=void 0){let r=e.operator;if(L[r]=e,t&&(this[e.action]=t),x[r]=e.operation,!e.action&&!(e.prefix||e.postif)&&(e.action=r),n===`over`||n===`under`){let{precedence:t}=e;for(let e in L){if(!Object.hasOwn(L,e))continue;let r=L[e];(n===`over`?r.precedence>=t:r.precedence>t)&&r.precedence++}}},this.getOperator=function(e){return L[e]},this.aliasOperator=function(e,t){let n={},r=L[e];for(let e in r)Object.hasOwn(r,e)&&(n[e]=r[e]);n.operator=t,this.setOperator(n)},this.getOperators=function(){return L},this.getBrackets=function(){return R};let B=function(e,t){e=String(e);for(let n=0;n<D.actions.length;n++)e=D.actions[n].call(t,e);for(e=e.replace(/\s+/gu,` `),/e/giu.test(e)&&(e=e.replace(/-+\d+\.?\d*e\+?-?\d+/giu,e=>Se(e)),e=e.replace(/(?<![A-Za-z])\d+\.?\d*e\+?-?\d+/giu,e=>Se(e))),e=e.replace(U.IMPLIED_MULTIPLICATION_REGEX,(e,t,n,r,i)=>{let a=i.charAt(r),o=``,s=`*`;return a.match(/[+\-/*]/u)||(o=i.charAt(r-1)),o.match(/[a-z]/iu)&&(s=``),t+s+n}).replace(/(?<varname>[a-z0-9_]+)/giu,(e,t)=>U.USE_MULTICHARACTER_VARS===!1&&!(t in te)&&isNaN(t)?t.split(``).join(`*`):t).replace(/\)\(/gu,`)*(`)||`0`;;){let t=e;if(e=e.replace(/(?<prefix>[a-z0-9_]+)(?<open>\()|(?<close>\))(?<suffix>[a-z0-9]+)/giu,(e,t,n,r,i)=>{let a=t||r,o=n||i;return a in te?a+o:`${a}*${o}`}),t===e)break}return e};this.initConstants=function(){this.CONSTANTS={E:new K(U.E),PI:new K(U.PI)}},this.prettyPrint=function(e){if(Array.isArray(e)){let t=e,n=t.map(e=>S.prettyPrint(e)).join(`, `);return t.type===`vector`?`vector<${n}>`:`(${n})`}return e.toString()},this.peekers={pre_operator:[],post_operator:[],pre_function:[],post_function:[]},this.callPeekers=function(e,...t){if(U.callPeekers){let n=this.peekers[e],r=t.map(re);for(let e=0;e<n.length;e++)n[e].apply(null,r)}},this.tokenize=function(e){e=String(e),e=e.trim().replace(/\s+/gu,` `);for(let t in R){if(!Object.hasOwn(R,t))continue;let n=RegExp(R[t].is_close?`\\s+\\${t}`:`\\${t}\\s+`,`gu`);e=e.replace(n,t)}let t=0,n=e.length,r=0,i=[],a=[i],o=a[0],s=0,c=[],l=!1,u,d=function(e=void 0,t=void 0){let n=[];e!==void 0&&(n.type=e),n.column=t,a.push(n),o.push(n),o=n,s++},f=function(){a.pop(),o=a[--s]},p=function(n){n=n===void 0?t:n;let r=n+1;for(;e.charAt(r++)in L;);return e.substring(n,r-1)},m=function(e){let n=t-e.length,r=[],i=e.charAt(0),a=e.length,o;for(o=1;o<a;o++){let t=e.charAt(o),a=i+t;a in L?i=a:(r.push(new A(i,A.OPERATOR,n+o)),i=t)}return r.push(new A(i,A.OPERATOR,n+o)),r},h=function(t,n=void 0){n===void 0&&(n=e.substring(r,t)),n in S.units?o.push(new A(n,A.UNIT,r)):n!==``&&o.push(new A(n,A.VARIABLE_OR_LITERAL,r))},g=function(e){o.push(new A(e,A.FUNCTION,r))},_=function(e){r=e+1},v=function(){r=r+u.length-2,t=r-1};for(;t<n;t++){let n=e.charAt(t);if(n in L){h(t);let e=o[0]&&he(o[0])&&n===`*`;l&&r<t&&!(n===`,`||e)&&(l=!1,f()),_(t+1),u=p(t),v(),o.push(...m(u))}else if(n in R){let i=R[n];if(i.is_open){c.push([i,r]);let n=e.substring(r,t);n in te?g(n):n!==``&&o.push(new A(n,A.VARIABLE_OR_LITERAL,r)),d(i.maps_to,t)}else if(i.is_close){let e=c.pop();if(e){if(e[0].id!==i.id-1)throw new C(`Parity error`)}else throw new C(`Missing open bracket for bracket at: ${t+1}`);h(t),f()}_(t)}else if(n===` `){let n=e.substring(r,t),i=e.charAt(t+1);if(l){if(n in L)o.push(new A(n,A.OPERATOR,t));else{h(void 0,n),f();let e=i in L;(e&&L[i].value===`-`||!e)&&o.push(new A(`*`,A.OPERATOR,t))}l=!1}else{let a=e.substring(r,t);a in te?(l=!0,g(a),d()):a in L?o.push(new A(a,A.OPERATOR,t)):(h(void 0,a),i=e.charAt(t+1),n!==``&&i!==``&&!(n in L)&&!(i in L)&&o.push(new A(`*`,A.OPERATOR,t)))}_(t)}}if(c.length)throw new C(`Missing closed bracket for bracket at ${c.pop()[1]+1}`);return h(t),i},this.toRPN=function(e){let t=e.type,n=e.length,r,i,a=[],o=[],s=[],c=function(e,t){for(;e.length;)t.push(e.pop())};for(r=0;r<n;r++){let t=e[r];if(t.type!==A.OPERATOR)break;if(!t.prefix)throw new w(`Not a prefix operator`);t.is_prefix=!0,o.push(t)}for(;r<n;r++){if(i=e[r],i.type===A.OPERATOR){let n=i;if(n.overloaded){let t=e[r+1];t&&t.type===A.VARIABLE_OR_LITERAL&&(n.postfix=!1,n.action=n.overloadAction,n.leftAssoc=n.overloadLeftAssoc)}for(;o.length;){let e=o[o.length-1];if(!(e.precedence>n.precedence||!n.leftAssoc&&e.precedence===n.precedence))break;a.push(o.pop())}if((t===`vector`||t===`set`)&&`vectorFn`in n&&(n.action=n.vectorFn),n.postfix){let t=e[r-1];if(t){if(t.type===A.OPERATOR&&!t.postfix)throw new w(`Unexpected prefix operator '${t.value}'! at ${t.column}`)}else throw new w(`Unexpected prefix operator '${i.value}'! at ${i.column}`)}else{let t;do{let n=e[r+1];if(t=n?n.type===A.OPERATOR:!1,t){if(!n.prefix)throw new w(`A prefix operator was expected at ${n.column}`);n.is_prefix=!0,s.push(n),r++}}while(t)}for(n.is_prefix?s.push(n):o.push(n);s.length&&(n.leftAssoc||!n.leftAssoc&&s[s.length-1].precedence>=n.precedence);)o.push(s.pop())}
2642else if(i.type===A.VARIABLE_OR_LITERAL){a.length===0&&c(s,o),a.push(i);let e=o[o.length-1];(!e||!e.leftAssoc)&&c(s,a)}else i.type===A.FUNCTION?o.push(i):i.type===A.UNIT&&a.push(i);if(Array.isArray(i)){let e=i;a.push(this.toRPN(i)),e.type&&a.push(new A(e.type,A.FUNCTION,e.column))}}return c(o,a),c(s,a),a},this.parseRPN=function(e,t){try{t||={};for(let e in t)Object.hasOwn(t,e)&&(t[e]=S.parse(t[e],{}));U.PARSE2NUMBER&&(`e`in t||(t.e=new K(U.E)),`pi`in t||(t.pi=new K(U.PI)));let n=[],r;for(let i=0,a=e.length;i<a;i++)if(r=e[i],Array.isArray(r)&&(r=this.parseRPN(r,t)),r)if(r.type===A.OPERATOR)if(r.is_prefix||r.postfix)n.push(r.operation(n.pop()));else{let e=n.pop(),t=n.pop();if(typeof t>`u`)throw new w(`${r} is not a valid postfix operator at ${r.column}`);let i=r.action===`comma`;t instanceof I&&!i&&(t=an.fromSet(t)),e instanceof I&&!i&&(e=an.fromSet(e)),this.callPeekers(`pre_operator`,t,e,r);let a=S[r.action](t,e);this.callPeekers(`post_operator`,a,t,e,r),n.push(a)}else if(r.type===A.FUNCTION){let t=n.pop(),{parent:a}=t;t instanceof ee||(t=ee.create(t));let o=r.value,s=t.getItems();this.callPeekers(`pre_function`,o,s);let c=S.callfunction(o,s);this.callPeekers(`post_function`,c,o,s),n[n.length-1];let l=e[i+1];l&&l.type===A.OPERATOR&&l.value,a&&(c.parent=a),n.push(c)}else{let e,i=r.value;if(i in U.ALIASES)r=S.parse(U.ALIASES[r]);else if(r.type===A.VARIABLE_OR_LITERAL)r=new K(i);else if(r.type===A.UNIT){let e=new K(i);e.isUnit=!0,r=e}i in S.CONSTANTS?(e=r,r=new K(S.CONSTANTS[i])):i in t&&i!==t[i].toString()?(e=r,r=t[i].clone()):i in g&&(e=r,r=g[i].clone()),e&&(r.subbed=e),n.push(r)}let i=n[0];if([`undefined`,`string`,`number`].indexOf(typeof i)!==-1)throw new M(`Unexpected token!`);return i}catch(e){if(e.message===`timeout`||e instanceof TypeError||e instanceof ReferenceError||e instanceof RangeError)throw e;[b].forEach(t=>{if(e instanceof t){let n=e.column;throw new t(`${e.message}${n?`: ${n}`:``}`)}});let t=e.column;throw new v(`${e.message}${t?`: ${t}`:``}`)}};class H{constructor(e){this.type=e.type,this.value=e.value,this.left=e.left,this.right=e.right}toString(){let e=this.left?`${this.left.toString()}---`:``,t=this.right?`---${this.right.toString()}`:``;return`${e}(${this.value})${t}`}toHTML(e,t){e||=0,t=typeof t>`u`?4:t;let n=function(e){return` `.repeat(t*e)},r=``,i=this.left?`${n(e+1)}<li>
2643${this.left.toHTML(e+2,t)}${n(e+1)}</li> 
2644`:``,a=this.right?`${n(e+1)}<li>
2645${this.right.toHTML(e+2,t)}${n(e+1)}</li>
2646`:``;return r=`${n(e)}<div class="${this.type.toLowerCase()}"><span>${this.value}</span></div>${n(e)}
2647`,(i||a)&&(r+=`${n(e)}<ul>
2648${i}${a}${n(e)}</ul>
2649`),r}}this.tree=function(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(Array.isArray(r)){r=this.tree(r),t.push(r);continue}if(r.type===A.OPERATOR)if(r.is_prefix||r.postfix){let e=r.is_prefix?`left`:`right`,n=t.pop();r=new H(r),r[e]=n,t.push(r)}else r=new H(r),r.right=t.pop(),r.left=t.pop(),t.push(r);else if(r.type===A.FUNCTION){r=new H(r);let e=t.pop();if(r.right=e,r.value===`object`){let e=t[t.length-1];if(e){for(;e.right;)e=e.right;e.right=r;continue}}t.push(r)}else t.push(new H(r))}return t[0]},this.parse=function(e,t){e=B(e,this),t||={};let n=this.tokenize(e),r=this.toRPN(n);return this.parseRPN(r,t)},this.toObject=function(e){return function e(t){let n=[];for(let r=0,i=t.length;r<i;r++){let i=t[r],a=i.value;if(i.type===A.VARIABLE_OR_LITERAL)n.push(new K(a));else if(i.type===A.FUNCTION){r++;let i=S.symfunction(a,e(t[r]));i.isConversion=!0,n.push(i)}else i.type===A.OPERATOR?n.push(a):n.push(e(i))}return n}(S.tokenize(e))};let ie=function(e){let t=0,n=[[]];for(let r=0,i=e.length;r<i;r++)e[r]===`,`?(t++,n[t]=[]):n[t].push(e[r]);return n},ae=function(e){return e.replace(/^\\left\((?<inner>.+)\\right\)$/gu,(e,t)=>t||e)},oe=function(e){let t=[];for(;e.length;){let n=e.shift(),r=e[0],i=z(r),a=r===`-`;if(n===`^`&&(r===`+`?e.shift():i&&r[0]===`+`&&r.shift(),i&&r.length===1&&e.unshift(e.shift()[0])),n===`^`&&(i&&r[0]===`-`||a)){let a=t.pop(),o=t[t.length-1],s=`1`;o===`*`?(t.pop(),s=t.pop()):z(o)&&(s=t.pop()),t.push(s,`/`,a,n),i?r.shift():e.shift(),i&&r.length===1&&t.push(e.shift()[0])}else t.push(n)}return t};this.toTeX=function(e,t){t||={};let n=t.decimals===!0?`decimals`:void 0,r=typeof e==`string`?this.toObject(e):e,i=[],o=typeof t.cdot>
2649`u`?`\\cdot`:t.cdot;if(r=oe(r),z(r)){let e=[],t,n;for(let i=0;i<r.length;i++)t=r[i],r[i+1]===`^`?(n=r[i+2],e.push(`${dn.braces(this.toTeX([t]))}^${dn.braces(this.toTeX([n]))}`),i+=2):e.push(t);r=e}for(let e=0,t=r.length;e<t;e++){let t=r[e];if(t===`*`&&(t=o),W(t))if(t.group===a){let{fname:e}=t,r;if(e===l)r=`\\sqrt${dn.braces(this.toTeX(t.args))}`;else if(e===u)r=dn.brackets(this.toTeX(t.args),`abs`);else if(e===p)r=dn.brackets(this.toTeX(t.args),`parens`);else if(e===U.LOG)r=`\\${U.LOG_LATEX}\\left( ${this.toTeX(t.args)}\\right)`;else if(e===U.LOG10)r=`\\${U.LOG10_LATEX}\\left( ${this.toTeX(t.args)}\\right)`;else if(e===U.LOG2)r=`\\${U.LOG2_LATEX}\\left( ${this.toTeX(t.args)}\\right)`;else if(e===U.LOG1P)r=`\\${V(U.LOG1P_LATEX,this.toTeX(t.args))}`;else if(e===`integrate`){let e=ie(t.args);r=`\\int ${dn.braces(this.toTeX(e[0]))}\\, d${this.toTeX(e[1])}`}else if(e===`defint`){let e=ie(t.args),n=dn.braces(this.toTeX(e[0])),i=this.toTeX(e[3]);r=`\\int\\limits_{${this.toTeX(e[1])}}^{${this.toTeX(e[2])}} ${n}\\, d${i}`}else if(e===`diff`){let e=ie(t.args),n=``,i=dn.braces(this.toTeX(e[0]));if(e.length===1){let t=[];for(let n=0;n<e[0].length;n++)e[0][n].group===3&&t.push(e[0][n].value);t.sort(),n=t.length>0?`\\frac{d}{d ${t[0]}}`:`\\frac{d}{d x}`}else n=e.length===2?`\\frac{d}{d ${e[1]}}`:`\\frac{d^{${e[2]}}}{d ${this.toTeX(e[1])}^{${e[2]}}}`;r=`${n}\\left(${i}\\right)`}else if(e===`sum`||e===`product`){let n=[[],[],[],[]],i=0;for(let e=0;e<t.args.length;e++){if(t.args[e]===`,`){i++;continue}n[i].push(t.args[e])}r=(e===`sum`?`\\sum_`:`\\prod_`)+dn.braces(`${this.toTeX(n[1])} = ${this.toTeX(n[2])}`),r+=`^${dn.braces(this.toTeX(n[3]))}${dn.braces(this.toTeX(n[0]))}`}else if(e===`limit`){let e=this.toTeX.bind(this),n=S,i=ie(t.args).map(t=>Array.isArray(t)?n.toTeX(t.join(``)):e(String(t)));r=`\\lim_${dn.braces(`${i[1]}\\to ${i[2]}`)} ${dn.braces(i[0])}`}else r=e===d||e===f?this.toTeX(t.args)+(e===d?`!`:`!!`):dn.latex(t,n);i.push(r)}else i.push(dn.latex(t,n));else z(t)?i.push(dn.brackets(this.toTeX(t))):t===`/`?i.push(dn.frac(ae(i.pop()),ae(this.toTeX([r[++e]])))):i.push(t)}return i.join(` `)};function se(e){return U.PARSE2NUMBER?e:S.symfunction(`parens`,[e])}function ue(e){if(e.isInfinity)return K.infinity();if(e.multiplier.lessThan(0)&&e.multiplier.negate(),e.isImaginary()){let t=e.realpart(),n=e.imagpart();if(t.isConstant()&&n.isConstant())return Fe(S.add(S.pow(t,new K(2)),S.pow(n,new K(2))))}else if(Me(e)||ce(e.power)||Ne(e)&&typeof e.value==`string`&&e.value.startsWith(`baseunit_`))return e;if(e.isComposite()){let t=[];e.each(e=>{t.push(e.multiplier)}),mn.QGCD.apply(null,t).lessThan(0)&&(e.multiplier=e.multiplier.multiply(new P(-1)),e.distributeMultiplier())}let t=S.parse(e.multiplier);return e.toUnitMultiplier(),S.multiply(t,S.symfunction(u,[e]))}function de(e){let t;if(hn(e)){let t=new an;return e.each((e,n)=>{t.set(n-1,de(e))}),t}if(gn(e)){let t=new sn;return e.each((e,n,r)=>{t.set(n,r,de(e))}),t}if(U.PARSE2NUMBER&&e.isConstant())return t=fe(e)?mn.bigfactorial(e):mn.gamma(e.multiplier.add(new P(1)).toDecimal()),t=tt(t),t;if(e.isConstant()&&e.getDenom().equals(2)){let t=e.getNum(),n,r,i;e.multiplier.isNegative()?(i=S.subtract(t.negate(),new K(1)).multiplier.divide(new P(2)),n=S.pow(new K(-4),new K(i)).multiplier.multiply(mn.bigfactorial(i)),r=mn.bigfactorial(new P(2).multiply(i))):(i=S.add(t,new K(1)).multiplier.divide(new P(2)),n=mn.bigfactorial(new P(2).multiply(i)),r=S.pow(new K(4),new K(i)).multiplier.multiply(mn.bigfactorial(i)));let a=n.divide(r);return S.multiply(S.parse(`sqrt(pi)`),new K(a))}return S.symfunction(d,[e])}function pe(e,t){let n=en(e);if(n.isConstant()){let e=mn.continuedFraction(n,t),r=an.fromArray(e.fractions.map(e=>new K(e)));return an.fromArray([new K(e.sign),new K(e.whole),r])}return S.symfunction(`continuedFraction`,[e,t])}function me(e,t){if(e.isConstant()&&t.isConstant()){let n=new K(1);return n.multiplier=n.multiplier.multiply(e.multiplier.mod(t.multiplier)),n}return fe(S.divide(e.clone(),t.clone()))?new K(0):S.symfunction(`mod`,[e,t])}function _e(e,t,n){return typeof e!=`boolean`&&Me(e)&&(e=!!Number(e)),e?t:n}function ve(e,t){if(gn(e)){for(let n=0,r=e.rows();n<r;n++)for(let r=0,i=e.cols();r<i;r++)if(e.elements[n][r].equals(t))return new K(1)}else if(e.elements){for(let n=0,r=e.elements.length;n<r;n++)if(e.elements[n].equals(t))return new K(1)}return new K(0)}function be(e){return U.PARSE2NUMBER?e.isConstant()?new K(mn.sinc(e)):S.parse(V(`sin({0})/({0})`,e)):S.symfunction(`sinc`,[e])}function xe(e){return e.fname===U.LOG&&e.isLinear()?S.pow(e.args[0],K.create(e.multiplier.toString())):S.parse(V(`e^({0})`,e))}function Te(e){return S.parse(V(`({0})*pi/180`,e))}function ke(e){return S.parse(V(`({0})*180/pi`,e))}function Ae(e){if(e.isComposite()){let t=new K(0),n,r,i,a,o,s,c,l;return e.each(e=>{n=e.getNum(),r=e.getDenom(),i=t.getNum(),a=t.getDenom(),o=S.multiply(r,i),s=S.multiply(n,a),c=S.expand(S.add(o,s)),l=S.multiply(a,r),t=S.divide(c,l)},!0),t}return e}function Fe(e){W(e)||(e=S.parse(e));let t=S.symfunction(`sqrt`,[e]);if(e.group===i)return S.symfunction(l,[e]);e.fname===``&&e.power.equals(1)&&(e=e.args[0]);let r=e.multiplier.sign()<0;if(U.PARSE2NUMBER){if(e.isConstant()&&!r)return new K(m.sqrt(e.multiplier.toDecimal()));if(e.isImaginary())return j.sqrt(e);if(e.group===n)return S.symfunction(`sqrt`,[e])}let a,o,c=e.isConstant();if(e.group===s&&e.isLinear()){let t=Fe(new K(e.multiplier));for(let n in e.symbols){if(!Object.hasOwn(e.symbols,n))continue;let r=e.symbols[n];t=S.multiply(t,Fe(r))}o=t}else if(e.fname===l){let t=e.args[0],n=e.multiplier;t.setPower(e.power.multiply(new P(.25))),o=t,n.equals(1)||(o=S.multiply(Fe(S.parse(n)),o))}else if(!e.power.isInteger())e.setPower(e.power.multiply(new P(.5))),o=e;else if(Number(e.multiplier)<0&&e.group===n){let t=S.parse(e.multiplier).negate(),n=S.parse(e).toUnitMultiplier().negate();o=S.multiply(S.symfunction(U.SQRT,[n]),Fe(t))}else{let t=e.power.sign();e.power=e.power.abs(),c&&e.multiplier.lessThan(0)&&(a=K.imaginary(),e.multiplier=e.multiplier.abs());let n=Number(e.multiplier.toDecimal()),r=Math.sqrt(Math.abs(n)),i;if(fe(r))i=new K(r);else if(fe(n)){let e=mn.ifactor(n),t=1;for(let r in e){if(!Object.hasOwn(e,r))continue;let i=e[r],a=i-i%2;if(a){let e=Number(r)**a;t*=Number(r)**(a/2),n/=e}}i=S.multiply(S.symfunction(l,[new K(n)]),new K(t))}
2649else{let t=[new K(e.multiplier.num),new K(e.multiplier.den)],n=[new K(1),new K(1)],r=[new K(1),new K(1)],a=S;for(let e=0;e<2;e++){let i=t[e];ze(i).each(t=>{t=K.unwrapPARENS(t);let i=t.clone().toLinear(),o=Number(t.power),s=o%2,c=(o-s)/2;n[e]=a.multiply(n[e],a.pow(i,new K(c))),r[e]=a.multiply(r[e],Fe(a.pow(i,new K(s))))})}i=S.divide(S.multiply(n[0],r[0]),S.multiply(n[1],r[1]))}e=e.toUnitMultiplier(!0),o=e.isOne()?e:ce(e.power.toString())?S.pow(e.clone(),new K(.5)):S.symfunction(l,[e]),t<0&&o.power.negate(),i&&(o=S.multiply(i,o)),a&&(o=S.multiply(a,o))}return Dn&&U.PARSE2NUMBER&&o.text()!==t.text()?S.parse(o):o}function Ie(e){if(!e.isConstant(!0)){let t,n=Number(e.power)/3,r=S.pow(S.parse(e.multiplier),new K(1/3)),i=e.toUnitMultiplier();return fe(n)?t=S.pow(i.toLinear(),S.parse(String(n))):i.group===s?(t=new K(1),i.each(e=>{t=S.multiply(t,Ie(e))})):t=S.symfunction(`cbrt`,[i]),S.multiply(r,t)}return Re(e,new K(3))}function Le(e,t){return e.scientific=t||10,e}function Re(t,n,r=void 0,i=void 0){if(n=en(S.parse(n)),n.equals(0))throw new y(`Unable to calculate nthroots of zero`);if(Number(t)<0&&ce(n))throw Error(`Cannot calculate nthroot of negative number for even powers`);if(!t.isConstant(!0)){let e=[t,n];return typeof r<`u`&&e.push(new K(r)),typeof i<`u`&&e.push(new K(+!!i)),S.symfunction(`nthroot`,e)}t.group!==e&&(t=en(t)),typeof i>`u`&&(i=!0),r||=25;let a=t.sign(),o,s;if(a<0&&(t=ue(t)),fe(t)&&n.isConstant())return s=Number(t)<0x10000000000000000?P.create(Number(t)**(1/Number(n))):mn.nthroot(t,n),o=i?new K(s):new K(s.toDecimal(r)),S.multiply(new K(a),o)}function ze(e){if(e.greaterThan(9999999999998891e26)||e.equals(-1))return e;if(e.equals(Math.PI))return new K(Math.PI);e=en(e.clone());let t;if(e.isConstant()){t=new K(1);let n=e.toString();if(fe(n)){let e=mn.ifactor(n);for(let n in e){if(!Object.hasOwn(e,n))continue;let r=e[n];t=S.multiply(t,S.symfunction(`parens`,[new K(n).setPower(new P(r))]))}}else{let n=ze(new K(e.multiplier.num)),r=ze(new K(e.multiplier.den));t=S.multiply(S.symfunction(`parens`,[n]),S.symfunction(`parens`,[r]).invert())}}else t=S.symfunction(`pfactor`,[e]);return t}function Be(e){return e.realpart()}function Ve(e){return e.imagpart()}function Ue(e){let t=e.realpart(),n=e.imagpart();return S.add(t,S.multiply(n.negate(),K.imaginary()))}function We(e){let t=e.realpart(),n=e.imagpart();return t.isConstant()&&n.isConstant()?n.equals(0)&&t.equals(1)?S.parse(`0`):n.equals(1)&&t.equals(0)?S.parse(`pi/2`):n.equals(0)&&t.equals(-1)?S.parse(`pi`):n.equals(-1)&&t.equals(0)?S.parse(`-pi/2`):n.equals(1)&&t.equals(1)?S.parse(`pi/4`):n.equals(1)&&t.equals(-1)?S.parse(`pi*3/4`):n.equals(-1)&&t.equals(1)?S.parse(`-pi/4`):n.equals(-1)&&t.equals(-1)?S.parse(`-pi*3/4`):new K(Math.atan2(Number(n),Number(t))):S.symfunction(`atan2`,[n,t])}function Ge(e){let t=K.toPolarFormArray(e),n=t[1],r=t[0],i=S.parse(V(`e^({0}*({1}))`,U.IMAGINARY,n));return S.multiply(r,i)}function Ke(e){let t=e.clone();try{let n=jn(e,`e`,!0),r=G.isSymbol(n.x.power)?n.x.power:S.parse(n.x.power),i=S.divide(r,K.imaginary()),a=en(N.tan(i));S.pow(n.a,new K(2));let o=a.getDenom(),s=a.getNum();return K.hyp(s,o).equals(n.a)?S.add(o,S.multiply(K.imaginary(),s)):t}catch(e){if(e.message===`timeout`)throw e;return t}}function qe(e,t){t.forEach(e=>{e.numVal=en(e).multiplier});let n,r,i;for(;;){if(n=t.length,n<2)return t[0];r=t.pop(),i=t[n-2],(e===`min`?r.numVal<i.numVal:r.numVal>i.numVal)&&(t.pop(),t.push(r))}}function Je(...e){return Ce(e)?e[0]:Pe(e)?new K(Math.max.apply(null,e)):U.SYMBOLIC_MIN_MAX&&En(e)?qe(`max`,e):S.symfunction(`max`,e)}function Ye(...e){return Ce(e)?e[0]:Pe(e)?new K(Math.min.apply(null,e)):U.SYMBOLIC_MIN_MAX&&En(e)?qe(`min`,e):S.symfunction(`min`,e)}function Xe(e){return e.isConstant(!0)?new K(Math.sign(en(e))):S.symfunction(`sign`,[e])}function Ze(t,r){r=r?r.toString():`asc`;let i=function(t){return t.group===e?t.multiplier:t.group===a?t.fname===``?i(t.args[0]):t.fname:t.group===n?t.power:t.value};return new an((hn(t)?t.elements:t.collectSymbols()).sort((e,t)=>{let n=i(e),a=i(t);return r===`desc`?a-n:n-a}))}function Qe(e,t=void 0){let n=e,r=t===void 0?void 0:t;if(n.equals(1))return new K(0);let o;if(n.fname===l&&n.multiplier.equals(1))return o=S.divide(Qe(n.args[0]),new K(2)),n.power.sign()<0&&o.negate(),o;if(n.equals(0))throw new y(`${U.LOG}(0) is undefined!`);if(n.isImaginary())return j.evaluate(n,U.LOG);
2649if(n.isConstant()&&typeof r<`u`&&r.isConstant())o=new K(Math.log(n)/Math.log(r));else if(n.group===i&&n.power.multiplier.lessThan(0)||n.power.toString()===`-1`)n.power.negate(),o=Qe(n).negate();else if(n.value===`e`&&n.multiplier.equals(1)){let e=n.power;o=W(e)?e:new K(e)}else if(n.group===a&&n.fname===`exp`){let e=n.args[0];o=n.multiplier.equals(1)?S.multiply(e,new K(n.power)):S.symfunction(U.LOG,[n])}else if(U.PARSE2NUMBER&&Me(n)){let e=S.parse(n),t;e.multiplier.lessThan(0)&&(e.negate(),t=S.multiply(new K(Math.PI),new K(`i`))),o=new K(Math.log(e.multiplier.toDecimal())),t&&(o=S.add(o,t))}else{let e;!n.power.equals(1)&&!n.contains(`e`)&&n.multiplier.isOne()&&(e=n.group===i?n.power:new K(n.power),n.toLinear());let t=typeof r>`u`?[n]:[n,r];o=t.length>1&&Ce(t)?new K(1):S.symfunction(U.LOG,t),e&&(o=S.multiply(e,o))}return o}function $e(e,t){typeof t==`number`&&(t=new K(t));let n=t&&t.isConstant()||typeof t>`u`;if(e.isConstant()&&n){let n,r,i;n=e,t&&t.lessThan(0)&&(t=ue(t),r=Number(e).toExponential().toString().split(`e`),n=r[0],i=r[1]);let a=new K(ge(Number(n),Number(t)||0));return S.multiply(a,S.pow(new K(10),new K(i||0)))}let r=[e];return typeof t<`u`&&r.push(t),S.symfunction(`round`,r)}function et(e){let t=Number(e)%2,n;return t<0&&(t=2+t),n=t>=0&&t<=.5?1:t>.5&&t<=1?2:t>1&&t<=1.5?3:4,n}function tt(e){if(!isFinite(e)){let t=Math.sign(e),n=new K(String(Math.abs(e)));return n.multiplier=n.multiplier.multiply(new P(t)),n}if(W(e))return e;if(typeof e==`number`)try{e=P.simple(e)}catch(t){if(t.message===`timeout`)throw t;e=new P(e)}let t=new K(0);return t.multiplier=e,t}function nt(e){let t=e.group,n;if(t===c){let t=e.getNum(),r=e.getDenom()||new K(1),i=Number(e.power),a=new K(1);if(Math.abs(i)===1){r.each(e=>{e.group===s?a=S.multiply(a,nt(e.getDenom())):e.power.lessThan(0)&&(a=S.multiply(a,nt(e.clone().toUnitMultiplier())))});let e=new K(0);r.each(t=>{e=S.add(S.divide(t,a.clone()),e)}),a.invert();let i;t.isComposite()?(i=new K(0),t.each(e=>{i=S.add(S.multiply(nt(e),a.clone()),i)})):i=S.multiply(a,t),n=S.divide(i,e)}}else t===s?(n=new K(1),e.each(e=>{n=S.multiply(n,S.clean(e))})):t===a&&e.args.length===1&&e.args[0].isConstant()&&(n=$t(`PARSE2NUMBER`,()=>S.parse(e),!0));return n||=e,n}function rt(e,t){return t||={expand_denominator:!0,expand_functions:!0},it(e,t)}function it(r,i){if(Array.isArray(r))return r.map(e=>it(e,i));if(`expand`in r&&typeof r.expand==`function`)return r.expand(i);let l=r;if(i||={},l.group===a&&l.fname===``){let e=it(l.args[0],i),t=it(S.pow(e,S.parse(l.power)),i);return S.multiply(S.parse(l.multiplier),t).distributeMultiplier()}if([e,t,n].indexOf(l.group)!==-1)return l;let u=l.clone();try{let e=l.multiplier.toString(),t=Number(l.power),n=l;if(l.isComposite()&&fe(l.power)&&t>0){let r=t-1,a=new K(0);l.each(e=>{a=S.add(a,it(S.parse(e),i))});let o=S.parse(a);for(let e=0;e<r;e++)o=Mn(o,a,i);n=S.multiply(S.parse(e),o).distributeMultiplier()}else if(l.group===a&&i.expand_functions===!0){let e=[];l.args.forEach(t=>{e.push(it(t,i))}),n=S.pow(S.symfunction(l.fname,e),S.parse(l.power)),n=S.multiply(n,S.parse(l.multiplier))}else if(l.isComposite()&&fe(l.power)&&t<0&&i.expand_denominator===!0)n=it(l.invert(),i),n.invert();else if(l.group===s){let r=function(e){switch(e.group){case c:return 0;case o:return 1;case s:return 2;case a:return 3;default:return 4}},u=l.collectSymbols().sort((e,t)=>r(t)-r(e)).map(e=>it(S.pow(e,S.parse(String(t))),i)),d=u.pop();d.isComposite()&&d.isLinear()?(u.forEach(e=>{d=Mn(d,e,i)}),d.isComposite()?(Number(d.power)>1&&(d=it(S.pow(d,S.parse(d.power)),i)),n=S.multiply(S.parse(e),d).distributeMultiplier()):n=d):(n=d,u.forEach(e=>{n=S.multiply(n,e)}),n=S.multiply(n,S.parse(e)).distributeMultiplier()),n.group===s&&(n=S.parse(n))}else n=l;return n}catch(e){if(e.message===`timeout`)throw e;return u}}function at(e){return sn.identity(e)}function ot(e,t){return t.isConstant()&&fe(t)?e.elements[Number(t)]:S.symfunction(`vecget`,[e,t])}function st(e,t){return t=typeof t>`u`?1e-14:t,e=e.clone(),t=Number(t),e.elements.sort((e,t)=>t.group-e.group),e.elements=we(e.elements,(e,n)=>Number(S.subtract(en(e),en(n)).abs())<=t),e}function ct(e,t,n){return t.isConstant?(e.elements[Number(t)]=n,e):S.symfunction(`vecset`,[e,t,n])}function lt(e,t,n){return t.isConstant()&&n.isConstant()?e.elements[Number(t)][Number(n)]:S.symfunction(`matget`,[e,t,n])}function ut(e,t){return t.isConstant()?an.fromArray(e.elements[Number(t)]):S.symfunction(`matgetrow`,[e,t])}function dt(e,t,n){if(!t.isConstant())return S.symfunction(`matsetrow`,[e,t,n]);if(e.elements[Number(t)].length!==n.elements.length)throw new E(`Matr
2649ix row must match row dimensions!`);let r=e.clone();return r.elements[Number(t)]=n.clone().elements,r}function ft(e,t){if(!t.isConstant())return S.symfunction(`matgetcol`,[e,t]);let n=Number(t),r=sn.fromArray([]);return e.each((e,t,i)=>{i===n&&r.elements.push([e.clone()])}),r}function pt(e,t,n){if(!t.isConstant())return S.symfunction(`matsetcol`,[e,t,n]);let r=Number(t);if(e.rows()!==n.elements.length)throw new E(`Matrix column length must match number of rows!`);return n.each(((t,n)=>{e.set(n-1,r,t.elements[0].clone())})),e}function mt(e,t,n,r){return e.elements[t][n]=r,e}function ht(...e){return new an(e)}function gt(...e){return sn.fromArray(e)}function _t(...e){return I.fromArray(e)}function vt(e){return gn(e)?e.determinant():e}function yt(e){let t;return gn(e)?t=[new K(e.cols()),new K(e.rows())]:hn(e)||De(e)?t=new K(e.elements.length):Ht(`size expects a matrix or a vector`),t}function bt(e,t){return gn(e)&&(e=new an(e)),gn(t)&&(t=new an(t)),hn(e)&&hn(t)?e.dot(t):S.multiply(e.clone(),t.clone())}function xt(e,t){return gn(e)&&(e=new an(e)),gn(t)&&(t=new an(t)),hn(e)&&hn(t)?e.cross(t):S.multiply(e.clone(),t.clone())}function St(e){return gn(e)?e.transpose():Ht(`function transpose expects a matrix`)}function Ct(e){return gn(e)?e.invert():Ht(`invert expects a matrix`)}function wt(e,t){return e.union(t)}function Tt(e,t){return e.intersection(t)}function Et(e,t){return e.contains(t)}function Dt(e,t){return e.difference(t)}function Ot(e,t){return new K(Number(e.intersects(t)))}function kt(e,t){return new K(Number(e.isSubset(t)))}function At(e,t){t??=e;let n=h.slice(e,t).map(e=>new K(e));return n.length===1?n[0]:n.length===0?new K(0):new an(n)}function jt(...e){e.forEach(e=>{console.log(e.toString())})}function Mt(e){if(!W(e.power)&&e.power.absEquals(.5)){let n=e.power.sign(),r=Fe(e.group===t?new K(e.value):e.toLinear());return n<0&&r.invert(),r}return e}function Nt(e){if(e.group===t){let t=e.value,n=Xt(t)[0];if(!n)return He(`Unable to compute prime factors. This should not happen. Please review and report.`),e;let r=new P(Math.log(t)/Math.log(n)).multiply(e.power);if(r.den>e.power.den)return e;e=fe(r)?new K(n**Number(r)):new K(n).setPower(r)}return e}this.expand=it,this.round=$e,this.clean=nt,this.sqrt=Fe,this.cbrt=Ie,this.abs=ue,this.log=Qe,this.rationalize=Ae,this.nthroot=Re,this.arg=We,this.conjugate=Ue,this.imagpart=Ve,this.realpart=Be,this.getFunction=function(e){return te[e][0]},this.addPreprocessor=function(e,t,n,r){let{names:i}=D,{actions:a}=D;if(typeof t!=`function`)throw Error(`Incorrect parameters. Function expected!`);n?r?(i.splice(n,0,e),a.splice(n,0,t)):(i[n]=e,a[n]=t):(i.push(e),a.push(t))},this.getPreprocessors=function(){let e={};for(let t=0,n=D.names.length;t<n;t++){let n=D.names[t];e[n]={order:t,action:D.actions[t]}}return e},this.removePreprocessor=function(e,t){let n=D.names.indexOf(e);t?(ye(D.names,n),ye(D.actions,n)):(D.names[n]=void 0,D.actions[n]=void 0)},this.mappedFunction=function(...e){let t={},{params:n}=this;for(let r=0;r<n.length;r++)t[n[r]]=String(e[r]);return S.parse(this.body,t)},this.add=function(r,u){let d=W(r),f=W(u);if(d&&f){let d=r,f=u;if(d.unit||f.unit)return S.Unit.add(d,f);if(d.isInfinity||f.isInfinity){let e=d.multiplier.lessThan(0),t=f.multiplier.lessThan(0);if(d.isInfinity&&f.isInfinity&&e!==t)throw new y(`(${d})+(${f}) is not defined!`);let n=K.infinity();return t&&n.negate(),n}if(d.isComposite()&&d.isLinear()&&f.isComposite()&&f.isLinear()&&(d.distributeMultiplier(),f.distributeMultiplier(),f.length>d.length&&d.group===f.group&&([d,f]=[f,d])),d.multiplier.equals(0))return f;if(f.multiplier.equals(0))return d;if(d.isConstant()&&f.isConstant()&&U.PARSE2NUMBER)return new K(d.multiplier.add(f.multiplier).toDecimal(U.PRECISION));let p=d.group,m=f.group,h=d.power.toString(),g=f.power.toString();if(p<m||p===m&&Number(h)>Number(g)&&Number(g)>0)return this.add(f,d);if(p===s&&m===o&&d.value===f.value){let e=d;d=f,f=e,p=d.group,m=f.group,h=d.power.toString(),g=f.power.toString()}let _=h===g,v=d.value,b=f.value,x=d.isComposite(),C=f.isComposite(),w,T,E;if(x&&(w=Hn(d,`hash`)),C&&(T=Hn(f,`hash`)),p===c&&m===c&&f.isLinear()&&!d.isLinear()&&w!==T)return this.add(f,d);p===o&&m===o&&(v=w,b=T);let D=p===t&&m===e,O=d.value===f.multiplier.toString(),k=v===b||w===T&&w!==void 0||D&&O;if(k&&_&&p===m)if(D&&(f=f.convert(t)),p===o&&(m===n||m===t))d.distributeMultiplier(),E=d.attach(f);else if(E=d,d.multiplier.isOne()&&f.multiplier.isOne()&&p===c&&d.isLinear()&&f.isLinear())for(let e in f.symbols){if(!Object.hasOwn(f.symbols,e))continue;let t=f.symbols[e];E.attach(t)}else E.multiplier=E.multiplier.add(f.multiplier);else if(k&&p!==o)p===c&&m===o?(f.insert(d,`add`),E=f):(E=K.shell(o).attach([d,f]),E.value=p===o?w:v);else if(x&&d.isLinear()){let e=p===m,t=p===o&&m===o;if(t&&(e=d.value===f.value),d.distributeMultiplier(),f.isComposite()&&f.isLinear()&&e){f.distributeMultiplier();for(let e in f.symbols){if(!Object.hasOwn(f.symbols,e))continue;let t=f.symbols[e];d.attach(t)}E=d}else t&&d.value!==T||p===o&&!k?(E=K.shell(c).attach([d,f]),E.updateHash()):E=d.attach(f)}else{if(p===a&&d.fname===l&&m!==i&&f.power.equals(.5)){let e=f.multiplier.clone();f=Fe(f.toUnitMultiplier().toLinear()),f.multiplier=e}d.length===2&&f.length===2&&ce(d.power)&&ce(f.power)?E=S.add(it(d),it(f)):(E=K.shell(c).attach([d,f]),E.updateHash())}E.multiplier.equals(0)&&(E=new K(0));let A=E;if(A.length===1){let e=A.multiplier,t=Oe(A.symbols);return t.multiplier=t.multiplier.multiply(e),t}return E}if(f&&!d){let e=r;r=u,u=e;let t=f;f=d,d=t}let p=gn(u);if(d&&p){let e=new sn;u.eachElement((t,n,i)=>{e.set(n,i,S.add(r.clone(),t))}),u=e}else if(gn(r)&&p)u=r.add(u);else if(d&&hn(u)){let e=u;e.each((t,n)=>{n--,e.elements[n]=S.add(r.clone(),e.elements[n])})}else if(hn(r)&&hn(u)){let e=r,t=u;t.each((n,r)=>{r--,t.elements[r]=S.add(e.elements[r],t.elements[r])})}else{if(hn(r)&&gn(u))return S.add(u,r);if(gn(r)&&hn(u)){if(u.elements.length===r.rows()){let e=new sn,t=r.cols();return u.each((n,i)=>{let a=[];if(hn(n))for(let e=0;e<t;e++)a.push(S.add(r.elements[i-1][e].clone(),n.elements[e].clone()));else for(let e=0;e<t;e++)a.push(S.add(r.elements[i-1][e].clone(),n.clone()));e.elements.push(a)}),e}Ht(`Dimensions must match!`)}}return u},this.subtract=function(e,t){let n=W(e),r=W(t);if(n&&r){let n=e,r=t;return n.unit||r.unit?S.Unit.subtract(n,r):this.add(n,r.negate())}if(r&&hn(e))t=e.map(e=>S.subtract(e,t.clone()));else if(n&&hn(t))t=t.map(t=>S.subtract(e.clone(),t));else if(hn(e)&&hn(t)||Ee(e)&&Ee(t))e.dimensions()===t.dimensions()?t=e.subtract(t):S.error(`Unable to subtract vectors/collections. Dimensions do not match.`);else if(gn(e)&&hn(t)){if(t.elements.length===e.rows()){let n=new sn,r=e.cols();return t.each((t,i)=>{let a=[];for(let n=0;n<r;n++)a.push(S.subtract(e.elements[i-1][n].clone(),t.clone()));n.elements.push(a)}),n}Ht(`Dimensions must match!`)}else if(hn(e)&&gn(t)){let n=t.clone().negate();return S.add(n,e)}else if(gn(e)&&gn(t))t=e.subtract(t);else if(gn(e)&&r){let n=new sn;e.each((e,r,i)=>{n.set(r,i,S.subtract(e,t.clone()))}),t=n}else if(n&&gn(t)){let n=new sn;t.each((t,r,i)=>{n.set(r,i,S.subtract(e.clone(),t))}),t=n}return t},this.multiply=function(r,u){let f=W(r),p=W(u);if(f&&u instanceof ee)return u.elements.push(r),u;if(f&&p){let f=r,p=u;if(p.isUnit){let e=f.clone();return f.unit=p,e}if(f.unit||p.unit)return S.Unit.multiply(f,p);
2649if(f.isInfinity||p.isInfinity){if(f.equals(0)||p.equals(0))throw new y(`${f}*${p} is undefined!`);if(p.power.lessThan(0)){if(!f.isInfinity)return new K(0);throw new y(`Infinity/Infinity is not defined!`)}let e=f.multiplier.multiply(p.multiplier).sign(),t=K.infinity();if(f.isConstant()||p.isConstant()||f.isInfinity&&p.isInfinity)return e<0&&t.negate(),t}if(f.multiplier.equals(0)||p.multiplier.equals(0))return new K(0);if(f.isOne())return p.clone();if(p.isOne())return f.clone();if(f.isConstant()&&p.isConstant()&&U.PARSE2NUMBER){let e,t=f.multiplier.num.abs().toString().length-f.multiplier.den.toString().length,n=p.multiplier.num.abs().toString().length-p.multiplier.den.toString().length,r=U.PRECISION-5;if(t<-r||t>r||n<-r||n>r){let t=new m(String(f.multiplier.num)),n=new m(String(f.multiplier.den)),r=new m(String(p.multiplier.num)),i=new m(String(p.multiplier.den));e=new K(t.times(r).dividedBy(n).dividedBy(i).toFixed())}else{let t=new m(f.multiplier.toDecimal()),n=new m(p.multiplier.toDecimal());e=new K(t.times(n).toFixed())}return e}if(p.group>f.group&&p.group!==c)return this.multiply(p,f);if(f.group===s&&p.group===o&&f.value===p.value){let e=f;f=p,p=e}let h=f.group,g=p.group,_=p.multiplier.num,v=p.multiplier.den;if(h===a&&f.fname===l&&!p.isConstant()&&f.args[0].value===p.value&&!f.args[0].multiplier.lessThan(0)){let e=f.power,t=S.parse(f.multiplier);f=S.multiply(t,f.args[0].clone()),f.setPower(new P(.5).multiply(e)),h=f.group}else h===a&&f.fname===l&&f.multiplier.equals(1)&&f.power.equals(-1)&&p.isConstant()&&f.args[0].equals(p)&&(f=S.symfunction(l,[p.clone()]),p=new K(1));let b=f.value,x=p.value,C=new P(f.sign()),w=h===t&&g===e&&p.multiplier.equals(f.value),T=w?new P(1).multiply(f.multiplier).abs():f.multiplier.multiply(p.multiplier).abs(),E=f.clone().toUnitMultiplier();if(p=p.clone().toUnitMultiplier(!0),h===a&&g===a){let e=f.args[0].clone(),t=p.args[0].clone();if(f.fname===l&&p.fname===l&&f.isLinear()&&p.isLinear()){let n=S.divide(e,t).invert();n.gt(1)&&fe(n)&&(E=S.multiply(f.args[0].clone(),Fe(n.clone())),p=new K(1))}else if(f.fname===d&&p.fname===d&&!e.isConstant()&&!t.isConstant()&&Number(p.power)<0){let n=S.subtract(e.clone(),t.clone());if(n.isConstant()){let r=new K(1);if(Number(n)<0){for(let t=0,i=Math.abs(Number(n));t<=i;t++){let n=S.add(e.clone(),new K(t));r=S.multiply(r,n)}E=S.multiply(S.pow(e,new K(f.power)),S.pow(r,new K(p.power))),p=new K(1)}else{for(let e=0,i=Math.abs(Number(n));e<=i;e++){let n=S.add(t.clone(),new K(e));r=S.multiply(r,n)}E=S.multiply(S.pow(r,new K(f.power)),S.pow(t,new K(p.power))),p=new K(1)}}}}if(b===x&&h===o&&h===g&&(b=f.text(`hash`),x=p.text(`hash`)),g===i&&p.previousGroup===o&&h===o&&(b=Hn(f,`hash`,i)),(b===x||w)&&!(h===o&&(g===n||g===t||g===a))&&!(h===o&&g===s)){let t=f.power,n=p.power,r=W(t),a=W(n),s=r||a;h===o&&g!==o&&p.previousGroup!==o&&t.equals(1)?(E=new K(0),f.each(e=>{E=S.add(E,S.multiply(e,p.clone()))},!0)):(s?E.power=S.add(W(t)?t:new K(t),W(n)?n:new K(n)):h===e?E.power=t:E.power=t.add(n),E.power.equals(0)&&(E=E.convert(e)),s&&E.convert(i),f.imaginary&&p.imaginary&&ce(Number(E.power)%2)&&(E=new K(1),T.negate()),E.group!==i&&E.previousGroup&&(E.previousGroup=void 0),E.multiplier=E.multiplier.multiply(p.multiplier))}else if(h===s&&f.isLinear())if(g===s&&p.distributeExponent(),g===s&&p.isLinear()){for(let e in p.symbols){if(!Object.hasOwn(p.symbols,e))continue;let t=p.symbols[e];E=E.combine(t)}E.multiplier=E.multiplier.multiply(p.multiplier)}else E.combine(p);else if(h===e)E=p.clone().toUnitMultiplier(!0);else if(h===s)E.distributeExponent(),E.combine(p);else if(!p.isOne()){let e=p.multiplier.clone();p.toUnitMultiplier(),E=K.shell(s).combine([E,p]),E.multiplier=E.multiplier.multiply(e)}if(E.group===t){let e=Math.log(Number(E.value)),t=Math.log(Number(_))/e,n=Math.log(Number(v))/e,r=Number(T.num)/Number(_),i=Number(T.den)/Number(v);t!==0&&fe(t)&&fe(r)&&(E.power=E.power.add(new P(t)),T.num=T.num.divide(_)),n!==0&&fe(n)&&fe(i)&&(E.power=E.power.subtract(new P(n)),T.den=T.den.divide(v))}if(E.length===1){let e=E.multiplier;E=Oe(E.symbols),E.multiplier=E.multiplier.multiply(e)}if(ce(E.power.toString())&&E.fname===l){C=C.multiply(new P(E.sign())
2649);let e=E.power;E=E.args[0],E=S.multiply(new K(T),S.pow(E,new K(e.divide(new P(2))))),C.lessThan(0)&&E.negate()}else E.multiplier=E.multiplier.multiply(T).multiply(C),E.group===c&&E.isImaginary()&&E.distributeMultiplier();return E.group===t&&fe(E.power.toDecimal())&&(E=E.convert(e)),E}if(p&&!f){let e=r;r=u,u=e;let t=p;p=f,f=t}let h=gn(u),g=gn(r);if(f&&h){let e=new sn;u.eachElement((t,n,i)=>{e.set(n,i,S.multiply(r.clone(),t))}),u=e}else if(g&&h){let e=r,t=u,n=e.rows()===1||e.cols()===1,i=t.rows()===1||t.cols()===1;if(n&&i){let n=new an(e.rows()===1?e.elements[0]:e.elements.map(e=>e[0])),r=new an(t.rows()===1?t.elements[0]:t.elements.map(e=>e[0]));if(n.elements.length===r.elements.length)return n.dot(r);Ht(`Dimensions must match!`)}else{let n=e.multiply(t);n?u=n:Ht(`Dimensions must match!`)}}else if(f&&hn(u)){let e=u;e.each((t,n)=>{n--,e.elements[n]=S.multiply(r.clone(),e.elements[n])})}else if(hn(r)&&hn(u)){let e=r,t=u;if(e.elements.length===t.elements.length)return e.dot(t);Ht(`Dimensions must match!`)}else{if(hn(r)&&gn(u))return this.multiply(u,r);if(gn(r)&&hn(u)){let e=r,t=u;if(t.elements.length===e.cols()){let n=e.rows(),r=[];for(let i=0;i<n;i++){let n=new an(e.elements[i]);r.push(n.dot(t))}return new an(r)}Ht(`Dimensions must match!`)}}return u},this.divide=function(e,t){let n=W(e),r=W(t);if(n&&r){let n=e,r=t;if(n.unit||r.unit)return S.Unit.divide(n,r);let i;if(r.equals(0))throw new _(`Division by zero not allowed!`);return n.isConstant()&&r.isConstant()?(i=n.clone(),i.multiplier=i.multiplier.divide(r.multiplier)):(r.invert(),i=S.multiply(n,r)),i}let i=hn(e),a=hn(t);if(n&&a)t=t.map(t=>S.divide(e.clone(),t));else if(i&&r)t=e.map(e=>S.divide(e,t.clone()));else if(i&&a){let n=e;n.dimensions()===t.dimensions()?t=t.map((e,t)=>S.divide(n.elements[--t],e)):S.error(`Cannot divide vectors. Dimensions do not match!`)}else{let i=gn(e),o=gn(t);if(i&&r){let n=new sn;e.eachElement((e,r,i)=>{n.set(r,i,S.divide(e,t.clone()))}),t=n}else if(n&&o){let n=new sn;t.eachElement((t,r,i)=>{n.set(r,i,S.divide(e.clone(),t))}),t=n}else if(i&&o){let n=new sn,r=e,i=t;r.rows()===i.rows()&&r.cols()===i.cols()?(r.eachElement((e,t,r)=>{n.set(t,r,S.divide(e,i.elements[t][r]))}),t=n):S.error(`Dimensions do not match!`)}else if(i&&a){let n=e,r=t;if(n.cols()===r.dimensions()){let e=new sn;n.eachElement((t,n,i)=>{e.set(n,i,S.divide(t,r.elements[n].clone()))}),t=e}else S.error(`Unable to divide matrix by vector.`)}}return t},this.pow=function(t,n){let o=W(t),c=W(n);if(o&&c){let o=t,c=n;if(o.unit||c.unit)return S.Unit.pow(o,c);if(o.group===a&&o.fname===u&&ce(c)){let e=o.multiplier.clone(),t=S.pow(o.args[0],c);return t.multiplier=e,t}if(o.isInfinity||c.isInfinity){if(o.isInfinity&&c.isInfinity)throw new y(`(${o})^(${c}) is undefined!`);if(o.isConstant()&&c.isInfinity){if(o.equals(0)){if(c.lessThan(0))throw new y(`0^Infinity is undefined!`);return new K(0)}if(o.equals(1))throw new y(`1^${c.toString()} is undefined!`);if(c.lessThan(0))return new K(0);if(!o.lessThan(0))return K.infinity()}if(o.isInfinity&&c.isConstant()){if(c.equals(0))throw new y(`${o}^0 is undefined!`);return c.lessThan(0)?new K(0):S.multiply(K.infinity(),S.pow(new K(o.sign()),c.clone()))}}let d=o.equals(0),f=c.equals(0);if(d&&f)throw new y(`0^0 is undefined!`);if(d&&c.isConstant()&&c.multiplier.greaterThan(0))return new K(0);if(f)return new K(1);let h=c.isConstant(),g=o.isConstant(),_=c.isInteger(),v=o.multiplier,b=o.clone();if(g&&h&&o.equals(0)&&c.lessThan(0))throw new y(`Division by zero is not allowed!`);if(U.PARSE2NUMBER&&g&&h&&o.sign()<0&&le(c)){let e=Math.PI*Number(c.multiplier.toDecimal()),t=new K(Math.cos(e)),n=S.multiply(K.imaginary(),new K(Math.sin(e)));return S.add(t,n)}if(U.PARSE2NUMBER&&o.isImaginary()&&h&&fe(c)&&!c.lessThan(0)){let e,t,n,i,a,s=o.realpart(),l=o.imagpart();if(s.isConstant(`all`)&&l.isConstant(`all`))return a=U.USE_BIG?r.atan2(l.multiplier.toDecimal(),s.multiplier.toDecimal()).times(c.toString()):Math.atan2(Number(l.multiplier.toDecimal()),Number(s.multiplier.toDecimal()))*Number(c.multiplier.toDecimal()),t=new K(a),e=S.pow(K.hyp(s,l),c),n=S.multiply(e.clone(),S.trig.cos(t.clone())),i=S.multiply(e,S.trig.sin(t)),S.add(n,S.multiply(K.imaginary(),i))}b.toUnitMultiplier();let x;if(b.group===a&&b.fname===l&&!h){let e=b.args[0];e.multiplyPower(new K(.5)),e.multiplier.multiply(b.multiplier),e.multiplyPower(c),b=e}else x=v.sign(),le(c)&&x<0&&(b.negate(),b=S.symfunction(p,[b]),b.negate()),b.multiplyPower(c);let C,w;if(g&&h&&U.PARSE2NUMBER){let e;x<0&&(o.negate(),e=c.multiplier.den.equals(2)?new K(U.IMAGINARY):fe(c.multiplier)?ce(c.multiplier)?new K(1):new K(-1):ce(c.multiplier.den)?S.pow(S.symfunction(p,[new K(x)]),c.clone()):new K(x**c.multiplier.num));let t=Number(o.multiplier.toDecimal())**Number(c.multiplier.toDecimal());if(t!==0||o.multiplier.equals(0))b=new K(t);else{let e=new m(o.multiplier.toDecimal()),t=new m(c.multiplier.toDecimal());b=new K(e.pow(t).toFixed())}e&&(b=S.multiply(b,e))}else if(_&&!v.equals(1)){if(c.abs().gt(U.MAX_EXP))return c.sign()<0?new K(0):K.infinity();let e=c.multiplier.toDecimal(),t=Math.sign(Number(e)),n=Math.abs(Number(e)),r=new P(1);r.num=v.num.pow(Number(n)),r.den=v.den.pow(Number(n)),t<0&&r.invert(),b.multiplier=b.multiplier.multiply(r)}else{let t=o.sign();if(c.isConstant()&&o.isConstant()&&!c.multiplier.den.equals(1)&&t<0)if(c.multiplier.den.equals(2)){let e=new K(U.IMAGINARY);o.negate(),c.lessThan(0)&&(e.negate(),c.negate()),b=S.multiply(S.pow(o,c),e)}else{let e=o.clone();e.multiplier.negate(),b=S.pow(S.symfunction(p,[new K(x)]),c.clone());let t=S.pow(new K(e.multiplier.num),c.clone()),n=S.pow(new K(e.multiplier.den),c.clone()),r=S.divide(t,n);b=S.multiply(b,r)}else if(U.PARSE2NUMBER&&c.isImaginary()){let e=c.realpart(),t=c.imagpart(),n=o.clone().toLinear(),r=S.pow(n.clone(),e),i=Qe(n.clone()),a=N.cos(S.multiply(t.clone(),i)),s=S.multiply(N.sin(S.multiply(t,Qe(n))),K.imaginary());b=S.multiply(r,S.add(a,s)),b=S.expand(S.parse(b))}else{let r=o.group===e&&t<0;
2649if(C=Mt(new K(r?Number(v.num):Math.abs(Number(v.num))).setPower(c.clone())),w=Mt(new K(Number(v.den)).setPower(c.clone()).invert()),o.imaginary)if(_){let e=Math.sign(c),t=ue(c)%4;b=new K(ce(t)?-1:U.IMAGINARY),(t===0||e<0&&t===1||e>0&&t===3)&&b.negate()}else{let e=n.multiplier.multiply(P.quick(1,2)),t=(-1)**e.num;b=ce(e.den)?new K(-1).setPower(e,!0):new K(t)}if(t<0&&!r&&b.negate(),h&&o.group!==i){let e=ce(c.multiplier.den),t=ce(o.power),n=b.power.toDecimal(),r=ce(n);if(e&&t&&!r){if(n===`1`||n===`1`)typeof b.value==`string`&&b.value.startsWith(`baseunit_`)||(b=S.symfunction(u,[b]));else if(fe(n))b=S.multiply(S.symfunction(u,[b.clone().toLinear()]),b.clone().setPower(new P(Number(n)-1)));else{let e=b.power;b=S.symfunction(u,[b.toLinear()]).setPower(e)}U.POSITIVE_MULTIPLIERS&&b.fname===u&&(b=b.args[0])}}if(c.equals(2)&&b.group===s){let e=new K(1);b.each(t=>{e=S.multiply(e,S.pow(t,c))}),b=e}}}if(b=Mt(b),C&&w&&(b=S.multiply(b,Nt(S.multiply(C,w)))),b.fname===l){let e=b.group===i;if(ce(e?b.power.multiplier.toString():b.power.toString())){let t=e?S.divide(b.power,new K(2)):new K(b.power.divide(new P(2))),n=b.multiplier;b=S.pow(b.args[0],t),b.multiplier=b.multiplier.multiply(n)}}else if(!U.IGNORE_E&&b.isE()&&b.group===i&&b.power.contains(`pi`)&&b.power.contains(U.IMAGINARY)&&c.group===s){let e=c.stripVar(U.IMAGINARY);b=S.add(N.cos(e),S.multiply(K.imaginary(),N.sin(e)))}return b}if(hn(t)&&c)t=t.map(e=>S.pow(e,n.clone()));else if(gn(t)&&c){let e=new sn;t.eachElement((t,r,i)=>{e.set(r,i,S.pow(t,n.clone()))}),t=e}else if(o&&gn(n)){let e=new sn;n.eachElement((n,r,i)=>{e.set(r,i,S.pow(t.clone(),n))}),t=e}return t},this.comma=function(e,t){return e instanceof ee||(e=ee.create(e)),e.append(t),e},this.mod=function(e,t){return me(e,t)},this.slice=function(e,t){return new O(e,t)},this.equals=function(e,t){return e.group!==n&&!e.isLinear()&&Ht(`Cannot set equality for ${e.toString()}`),g[e.value]=t.clone(),t},this.percent=function(e){return S.divide(e,new K(100))},this.assign=function(e,t){if(e instanceof ee&&t instanceof ee)return e.elements.map((e,n)=>S.assign(e,t.elements[n])),an.fromArray(t.elements);if(e.parent){let n=e.parent;return n.elements[n.getter]=t,delete n.getter,n}if(e.group!==n)throw new k(`Cannot complete operation. Incorrect LH value for ${e}`);return g[e.value]=t,t},this.functionAssign=function(e,t){return Ln(e.elements.pop(),e.elements,t)};let Pt=function(e){return new K(+(e===!0))};this.eq=function(e,t){return Pt(e.equals(t))},this.gt=function(e,t){return Pt(e.gt(t))},this.gte=function(e,t){return Pt(e.gte(t))},this.lt=function(e,t){return Pt(e.lt(t))},this.lte=function(e,t){return Pt(e.lte(t))},this.factorial=function(e){return this.symfunction(d,[e])},this.dfactorial=function(e){return this.symfunction(f,[e])}}},Wn={allSame:Ce,allNumeric:xe,arguments2Array:de,armTimeout:Kt,arrayAddSlices:_e,arrayClone:me,arrayMax:oe,arrayMin:se,arrayEqual:pe,arrayUnique:ue,err:Ht,arrayGetVariables:Pn,arraySum:Tn,block:$t,checkTimeout:Jt,clearU:Le,comboSort:Te,compare:Cn,convertToVector:Nn,customError:g,customType:ae,decompose_fn:jn,disarmTimeout:qt,each:ve,evaluate:en,even:ce,evenFraction:le,fillHoles:tee,firstObject:Oe,format:V,generatePrimes:Zt,getCoeffs:bn,getU:Fn,importFunctions:Bn,inBrackets:ne,isArray:z,isCollection:Ee,isExpression:_n,isFraction:wn,isInt:fe,isMatrix:gn,isNegative:Dn,isNumericSymbol:Me,isPrime:Wt,isReserved:Be,isSet:De,isSymbol:W,isVariableSymbol:Ne,isVector:hn,keys:ke,knownVariable:be,nroots:Sn,remove:ye,reserveNames:Ie,range:H,round:ge,sameSign:B,scientificToDecimal:Se,separate:kn,stringReplace:ie,text:Hn,validateName:ze,variables:yn,warn:He};function Gn(){return(function(e,t,n,r){Kt();try{let i=f.parser,a=f.state.EXPRESSIONS,o=!1;if((typeof e==`string`||typeof e==`function`)&&Ln(e))return f.libExports;typeof e==`object`&&e&&e instanceof nn&&(e=e.toString()),typeof e==`object`&&e&&`text`in e&&typeof e.text==`function`&&(e=e.text()),z(n)||(n=typeof n>`u`?[]:[n]),n.forEach(t=>{if(t===`numer`){o=!0;return}let n=i.functions[t];n&&n[1]===1&&(e=`${t}(${e})`)});let s=new nn($t(`PARSE2NUMBER`,()=>i.parse(e,t),o||U.PARSE2NUMBER));return r?a[r-1]=s:a.push(s),s}finally{qt()}})}
2649function Kn(){return{groups:p,NerdamerSymbol:K,Expression:nn,Collection:ee,Frac:P,Vector:an,Matrix:sn,NerdamerSet:I,Math2:mn,LaTeX:dn,Build:ln,Utils:Wn,PARSER:f.parser,Settings:U,bigInt:n,bigDec:r,exceptions:f.exceptions,Solve:{},Calculus:{},Algebra:{},Extra:{}}}function qn(){let e=f.parser;Ie(e.CONSTANTS),Ie(e.functions),e.initConstants(),e.error||=Ht,U.LOG_FNS={log:e.functions.log,log10:e.functions.log10}}function Jn(e){e.rpn=ht,e.convertToLaTeX=st,e.convertFromLaTeX=xt,e.version=Ze,e.getWarnings=Ue,e.setConstant=kt,e.getConstant=nt,e.clearConstants=Tt,e.setFunction=Nt,e.clearFunctions=wt,e.getCore=Qe,e.getExpression=e.getEquation=nn.getExpression,e.reserved=Ye,e.clear=Ft,e.flush=Et,e.expressions=yt,e.functions=bt,e.register=Lt,e.validateName=ze,e.validVarName=Je,e.supported=et,e.numEquations=e.numExpressions=Ge,e.setVar=jt,e.getVar=it,e.clearVars=Ct,e.load=Dt,e.getVars=at,e.set=zt,e.get=qe,e.updateAPI=Vt,e.replaceFunction=_t,e.setOperator=ut,e.getOperator=ct,e.aliasOperator=lt,e.tree=pt,e.htmlTree=gt,e.addPeeker=dt,e.removePeeker=ft,e.parse=mt}var nee=(function(){let e=new Un;f.parser=e,f.classes.Parser=Un,dn.initParser(),ln.initDependencies(),qn();let t=Kn();f.core=t,f.classes.Math2=t.Math2,f.utils.symfunction=e.symfunction.bind(e),f.utils.callfunction=e.callfunction.bind(e),f.state.CONSTANTS=e.CONSTANTS;let n=Gn();return f.libExports=n,Jn(n),n.updateAPI(),n})();typeof t<`u`&&(t.exports=nee)}),qW=HW((e,t)=>{var n=typeof globalThis<`u`&&globalThis.nerdamer?globalThis.nerdamer:void 0;typeof t<`u`&&n===void 0&&(n=KW(),JW()),(function(){let e=n.getCore(),t=e.PARSER,{Frac:r}=e,{Settings:i}=e,{isSymbol:a}=e.Utils,{FN:o}=e.groups,{NerdamerSymbol:s}=e,{text:c}=e.Utils,{inBrackets:l}=e.Utils,{isInt:u}=e.Utils,{format:d}=e.Utils,{even:f}=e.Utils,{evaluate:p}=e.Utils,{N:m}=e.groups,{S:h}=e.groups,{PL:g}=e.groups,{CP:_}=e.groups,{CB:v}=e.groups,{EX:y}=e.groups,{P:b}=e.groups,{LOG:x}=i,S=`sqrt`,C=`asin`,w=`acos`,T=`atan`,E=`asec`,D=`acsc`,O=`acot`,k=`sinh`,A=`cosh`,j=`tanh`,M=`csch`,N=`sech`,P=`coth`,F=`asech`,I=`acsch`,L=`acoth`;function ee(e){return a(e.power)&&(e.power.group===h||e.power.group===v)}function R(e){this.message=e||``}R.prototype=Error(),s.prototype.hasIntegral=function(){return this.containsFunction(`integrate`)},s.prototype.fnTransform=function(){if(this.group!==o)return this;let e,n=this.args[0],r=new s(this.multiplier),i=this.clone().toUnitMultiplier();if(this.isLinear())switch(this.fname){case k:e=t.parse(d(`(e^({0})-e^(-({0})))/2`,n));break;case A:e=t.parse(d(`(e^({0})+e^(-({0})))/2`,n));break;case j:e=t.parse(d(`(e^({0})-e^(-({0})))/(e^({0})+e^(-({0})))`,n));break;case`tan`:e=t.parse(d(`sin({0})/cos({0})`,n));break;case`csc`:e=t.parse(d(`1/sin({0})`,n));break;case`sec`:e=t.parse(d(`1/cos({0})`,n));break;default:e=i}else if(this.power.equals(2))switch(this.fname){case`sin`:e=t.parse(d(`1/2-cos(2*({0}))/2`,n));break;case`cos`:e=t.parse(d(`1/2+cos(2*({0}))/2`,n));break;case`tan`:e=t.parse(d(`sin({0})^2/cos({0})^2`,n));break;case A:e=t.parse(d(`1/2+cosh(2*({0}))/2`,n));break;case k:e=t.parse(d(`-1/2+cosh(2*({0}))/2`,n));break;case j:e=t.parse(d(`(1+cosh(2*({0})))/(-1+cosh(2*({0})))`,n));break;case`sec`:e=t.parse(d(`(1-cos(2*({0})))/(1+cos(2*({0})))+1`,n));break;default:e=i}else if(this.fname===`sec`)e=t.parse(d(`1/cos({0})^({1})`,this.args[0],this.power));else if(this.fname===`csc`)e=t.parse(d(`1/sin({0})^({1})`,this.args[0],this.power));else if(this.fname===`tan`)e=this.power.lessThan(0)?t.parse(d(`cos({0})^(-({1}))/sin({0})^({1})`,this.args[0],this.power.negate())):t.parse(d(`sin({0})^({1})/cos({0})^({1})`,this.args[0],this.power));else if(this.fname===`sin`&&this.power.lessThan(0))e=t.parse(d(`csc({0})^(-({1}))`,this.args[0],this.power.negate()));else if(this.fname===`cos`&&this.power.lessThan(0))e=t.parse(d(`sec({0})^(-({1}))`,this.args[0],this.power.negate()));else if(this.fname===`sin`&&this.power.equals(3))e=t.parse(d(`(3*sin({0})-sin(3*({0})))/4`,this.args[0]));else if(this.fname===`cos`&&this.power.equals(3))e=t.parse(d(`(cos(3*({0}))+3*cos({0}))/4`,this.args[0]));else if((this.fname===`cos`||this.fname===`sin`)&&f(this.power)){let n=this.power/2,r=this.clone().toLinear(),i=t.pow(r,t.parse(2)),a=t.expand(t.pow(i.fnTransform(),t.parse(n)));e=new s(0),a.each(n=>{let r=n.fnTransform();e=t.add(e,r)},!0)}else e=i;return t.multiply(e,r)},s.prototype.hasTrig=function(){if(this.isConstant(!0)||this.group===h)return!1;if(this.fname&&(e.Utils.inTrig(this.fname)||e.Utils.inInverseTrig(this.fname)))return!0;
2649if(this.symbols){for(let e in this.symbols)if(this.symbols[e].hasTrig())return!0}return!1},e.Expression.prototype.hasIntegral=function(){return this.symbol.hasIntegral()},e.Utils.toCommonDenominator=function(n){if(n.isComposite()&&n.isLinear()){let r=new s(n.multiplier),i=new s(1),a=new s(0);return n.each(e=>{i=t.multiply(i,e.getDenom())},!0),n.each(e=>{let n=e.getNum(),r=e.getDenom(),o=t.multiply(n,t.divide(i.clone(),r));a=t.add(a,o)}),t.multiply(r,e.Algebra.divide(t.expand(a),t.expand(i)))}return n},e.Utils.inInverseTrig=function(e){return[C,w,T,D,E,O].indexOf(e)!==-1},e.Utils.inTrig=function(e){return[`cos`,`sin`,`tan`,`sec`,`csc`,`cot`].indexOf(e)!==-1},e.Utils.inHtrig=function(e){return[k,A,j,I,F,L].indexOf(e)!==-1},e.Matrix.jacobian=function(t,n){let r=new e.Matrix;return n||=e.Utils.arrayGetVariables(t),n.forEach((n,i)=>{t.forEach((t,a)=>{let o=e.Calculus.diff(t.clone(),n);r.set(a,i,o)})}),r},e.Matrix.prototype.max=function(){let e=new s(0);return this.each(t=>{let n=t.abs();n.gt(e)&&(e=n)}),e},e.Matrix.cMatrix=function(n,r){let i=new e.Matr
2649ix;return r.forEach((e,r)=>{i.set(r,0,t.parse(n))}),i};let te=e.Utils.allFunctions=function(e){for(let t=0,n=e.length;t<n;t++)if(e[t].group!==o)return!1;return!0},z=e.Utils.cosAsinBtranform=function(e,n){let r=e.args[0],i=n.args[0];return t.parse(d(`(sin(({0})+({1}))-sin(({0})-({1})))/2`,r,i))},ne=e.Utils.cosAsinAtranform=function(e,n){if(Number(n.power)!==1)return t.multiply(e,n);let r=e.args[0];return t.parse(d(`(sin(2*({0})))/2`,r))},B=e.Utils.cosAsinBtranform=function(e,n){let r=e.args[0],i=n.args[0];return t.parse(d(`(cos(({0})+({1}))-cos(({0})-({1})))/2`,r,i))},V=e.Utils.trigTransform=function(e){let n={},r,i,a=new s(1);for(let s=0,c=e.length;s<c;s++)if(r=e[s],r.group===o){let{fname:e}=r;e===`cos`&&n.sin?(i=n.sin.args[0].toString()===r.args[0].toString()?ne(r,n.sin):z(r,n.sin),delete n.sin,a=t.multiply(a,i)):e===`sin`&&n.cos?(i=n.cos.args[0].toString()===r.args[0].toString()?ne(r,n.cos):z(r,n.cos),delete n.cos,a=t.multiply(a,i)):e===`sin`&&n.sin?(n.sin.args[0].toString()===r.args[0].toString()?(i=t.multiply(r,n.sin),delete n.sin):(i=B(r,n.sin),delete n.sin),a=i):n[e]=r}else a=t.multiply(a,r);for(let e in n)Object.hasOwn(n,e)&&(a=t.multiply(a,n[e]));return a};e.Settings.integration_depth=10,e.Settings.max_lim_depth=10;let H=e.Calculus={version:`1.4.6`,sum(n,r,i,a){if(r.group!==e.groups.S)throw new e.exceptions.NerdamerTypeError(`Index must be symbol. ${c(r)} provided`);let o=r.value,l;if(e.Utils.isNumericSymbol(i)&&e.Utils.isNumericSymbol(a)){let r=Number(a)-Number(i)<200?``:`PARSE2NUMBER`,c=Number(i),u=Number(a);l=e.Utils.block(r,()=>{let r=n.text(),i={"~":!0},a=new e.NerdamerSymbol(0);for(let e=c;e<=u;e++){i[o]=new s(e);let n=t.parse(r,i);a=t.add(a,n)}return a})}else l=t.symfunction(`sum`,[n,new s(o),i,a]);return l},product(n,r,i,a){if(r.group!==e.groups.S)throw new e.exceptions.NerdamerTypeError(`Index must be symbol. ${c(r)} provided`);let o=r.value,l;if(e.Utils.isNumericSymbol(i)&&e.Utils.isNumericSymbol(a)){let r=Number(a)-Number(i)<200?``:`PARSE2NUMBER`;l=e.Utils.block(r,()=>{let r=Number(i),c=Number(a.multiplier),l=n.text(),u={},d=new e.NerdamerSymbol(1);for(let e=r;e<=c;e++)u[o]=new s(e),d=t.multiply(d,t.parse(l,u));return d})}else l=t.symfunction(`product`,[n,new s(o),i,a]);return l},diff(n,u,f){if(e.Utils.isVector(n)){let t=new e.Vector([]);return n.each(e=>{t.elements.push(H.diff(e,u,f))}),t}if(e.Utils.isMatrix(n)){let t=new e.Matrix;return n.each((e,n,r)=>{t.set(n,r,H.diff(e,u,f))}),t}let p=n;if(p.LHS&&p.RHS)return new e.Equation(H.diff(p.LHS.clone(),u,f),H.diff(p.RHS.clone(),u,f));let k=a(u)?u.text():u;if(f=a(f)?f.multiplier.toDecimal():f||1,k===void 0&&(k=e.Utils.variables(n)[0]),p.group===o&&p.fname===S){let e=p.args[0],i=p.power.clone();(e.group!==m||e.group!==b)&&(e.power=a(e.power)?t.multiply(t.multiply(e.power,new s(1/2)),new s(i)):e.power.multiply(new r(.5)).multiply(i),e.multiplier=e.multiplier.multiply(p.multiplier)),n=e}if(n.group===o&&!a(n.power)){let e=ee(t.parse(n)),r=H.diff(n.args[0].clone(),k);n=t.multiply(e,r)}else n=ee(n);return f>1&&(f--,n=H.diff(n,u,f)),n;function A(e){return(e.value===k||e.contains(k,!0))&&(e.multiplier=e.multiplier.multiply(e.power),e.power=e.power.subtract(new r(1)),e.power.equals(0)&&(e=new s(e.multiplier))),e}function ee(e){let n=e.group,f,p;if(n===m||n===h&&e.value!==k||n===b)e=new s(0);else if(n===h)e=A(e);else if(n===v){let n=e.multiplier.clone();e.toUnitMultiplier();let r=t.multiply(te(e),A(e));return r.multiplier=r.multiplier.multiply(n),r}else if(n===o&&e.power.equals(1)){let n=e.multiplier.clone();switch(e.toUnitMultiplier(),e.fname){case x:p=e.clone(),e=e.args[0].clone(),e.power=e.power.negate(),e.multiplier=p.multiplier.divide(e.multiplier);break;case`cos`:e.fname=`sin`,e.multiplier.negate();break;case`sin`:e.fname=`cos`;break;case`tan`:e.fname=`sec`,e.power=new r(2);break;case`sec`:e=R(e,`tan`);break;case`csc`:e=R(e,`-cot`);break;case`cot`:e.fname=`csc`,e.multiplier.negate(),e.power=new r(2);break;case C:e=t.parse(`(sqrt(1-(${c(e.args[0])})^2))^(-1)`);break;case w:e=t.parse(`-(sqrt(1-(${c(e.args[0])})^2))^(-1)`);break;case T:e=t.parse(`(1+(${c(e.args[0])})^2)^(-1)`);break;case`abs`:f=e.args[0].clone(),f.toUnitMultiplier(),e=t.parse(`${l(c(e.args[0]))}/abs${l(c(f))}`);break;case`parens`:e=new s(1);break;case`cosh`:e.fname=`sinh`;break;case`sinh`:e.fname=`cosh`;break;case j:e.fname=N,e.power=new r(2);break;case N:e=R(e,`-tanh`);break;case M:{let n=String(e.args[0]);e=t.parse(`-coth(${n})*csch(${n})`);break}case P:{let n=String(e.args[0]);e=t.parse(`-csch(${n})^2`);break}case`asinh`:e=t.parse(`(sqrt(1+(${c(e.args[0])})^2))^(-1)`);break;case`acosh`:e=t.parse(`(sqrt(-1+(${c(e.args[0])})^2))^(-1)`);break;case`atanh`:e=t.parse(`(1-(${c(e.args[0])})^2)^(-1)`);break;case F:{let n=String(e.args[0]);e=t.parse(`-1/(sqrt(1/(${n})^2-1)*(${n})^2)`);break}case L:e=t.parse(`-1/((${e.args[0]})^2-1)`);break;case I:{let n=String(e.args[0]);e=t.parse(`-1/(sqrt(1/(${n})^2+1)*(${n})^2)`);break}case E:{let n=String(e.args[0]);e=t.parse(`1/(sqrt(1-1/(${n})^2)*(${n})^2)`);break}case D:{let n=String(e.args[0]);e=t.parse(`-1/(sqrt(1-1/(${n})^2)*(${n})^2)`);break}case O:e=t.parse(`-1/((${e.args[0]})^2+1)`);break;case`S`:{let n=String(e.args[0]);e=t.parse(`sin((pi*(${n})^2)/2)`);break}case`C`:{let n=String(e.args[0]);e=t.parse(`cos((pi*(${n})^2)/2)`);break}case`Si`:{let n=e.args[0];e=t.parse(`sin(${n})/(${n})`);break}case`Shi`:{let n=e.args[0];e=t.parse(`sinh(${n})/(${n})`);break}case`Ci`:{let n=e.args[0];e=t.parse(`cos(${n})/(${n})`);break}case`Chi`:{let n=e.args[0];e=t.parse(`cosh(${n})/(${n})`);break}case`Ei`:{let n=e.args[0];e=t.parse(`e^(${n})/(${n})`);break}case`Li`:{let n=e.args[0];e=t.parse(`1/${i.LOG}(${n})`);break}case`erf`:e=t.parse(`(2*e^(-(${e.args[0]})^2))/sqrt(pi)`);break;
2649case`atan2`:{let n=String(e.args[0]),r=String(e.args[1]);e=t.parse(`(${r})/((${r})^2+(${n})^2)`);break}case`sign`:e=new s(0);break;case`sinc`:e=t.parse(d(`(({0})*cos({0})-sin({0}))*({0})^(-2)`,e.args[0]));break;case i.LOG10:e=t.parse(`1/((${e.args[0]})*${i.LOG}(10))`);break;default:e=t.symfunction(`diff`,[e,u])}e.multiplier=e.multiplier.multiply(n)}else if(n===y||n===o&&a(e.power)){let r;r=n===y?e.value:n===o&&e.contains(k)?e.fname+l(c(e.args[0])):e.value+l(c(e.args[0])),f=H.diff(t.multiply(t.parse(x+l(r)),e.power.clone()),k),e=t.multiply(e,f)}else if(n===o&&!e.power.equals(1))f=e.clone(),f.toLinear(),f.toUnitMultiplier(),e=t.multiply(A(e.clone()),ee(f));else if(n===_||n===g){let n=e.clone(),r=new s(0);for(let n in e.symbols)Object.hasOwn(e.symbols,n)&&(r=t.add(r,H.diff(e.symbols[n].clone(),k)));e=t.multiply(A(n),r)}return e.updateHash(),e}function R(e,n,r){return t.multiply(e,t.parse(n+l(r||c(e.args[0]))))}function te(e){let n=e.collectSymbols(),r=new s(0),i=n.length;for(let e=0;e<i;e++){let a=H.diff(n[e].clone(),k);for(let r=0;r<i;r++)e!==r&&(a=t.multiply(a,n[r].clone()));r=t.add(r,a)}return r}},integration:{u_substitution(n,r){let i=`__u__`;function c(e,n,i){let a=H.diff(n,r),o=i?i(e,n):t.divide(e.clone(),a);return o.contains(r,!0)?null:o}function l(e,n){let r=H.integrate(t.symfunction(e,[new s(i)]),i,0);return r=r.sub(new s(i),n),r.updateHash(),r}let u=n[0].clone(),d=n[1].clone(),f=u.group,p=d.group,m;if(f===o&&p!==o){let e=u.args[0];if(m=c(d,e.clone()),m)return t.multiply(m,l(u.fname,e));if(m=c(d,u),m)return H.integration.poly_integrate(u)}else if(p===o&&f!==o){let e=d.args[0];if(m=c(u,e.clone()),m)return t.multiply(m,l(d.fname,e))}else if(f===o&&p===o){if(m=c(u.clone(),d.clone()),m||(m=c(d.clone(),u.clone()),m))return t.multiply(H.integration.poly_integrate(d),m)}else if(f===y&&p!==y){let e=u.power;if(m=c(d,a(e)?e.clone():new s(e)),!m){let n=H.integration.decompose_arg(a(e)?e.clone():new s(e),r),o=H.diff(n[2].clone(),r),c=H.integration.decompose_arg(o.clone(),r);if(t.multiply(n[1],c[1]).power.equals(d.power)){let e=t.divide(n[0].clone(),c[0].clone()),r=t.multiply(e.clone(),t.pow(new s(u.value),t.multiply(n[0],new s(i))));return r=t.multiply(r,new s(i)),H.integration.by_parts(r,i,0,{}).sub(i,n[1].clone())}}let n=H.integrate(u.sub(e.clone(),new s(i)),i,0);return t.multiply(n.sub(new s(i),e),m)}else if(p===y&&f!==y){let e=d.power;m=c(u,e.clone());let n=H.integrate(d.sub(e,new s(i)),i,0);return t.multiply(n.sub(new s(i),e),m)}else if(u.isComposite()||d.isComposite()){let n=function(n,i){let a=H.diff(i,r),o=e.Algebra.Factor.factorInner(n),s=e.Algebra.Factor.factorInner(a);return t.divide(o,s)},i=u.isComposite()?u.clone().toLinear():u.clone(),a=d.isComposite()?d.clone().toLinear():d.clone();if(m=c(i.clone(),a.clone(),n),m)return t.multiply(H.integration.poly_integrate(d),m);if(m=c(a.clone(),i.clone(),n),m)return t.multiply(H.integration.poly_integrate(u),m)}},poly_integrate(e){let n=e.power.toString(),r=e.multiplier.toDecimal(),i=e.toUnitMultiplier().toLinear();return Number(n)===-1?t.multiply(new s(r),t.symfunction(x,[i])):t.parse(d(`({0})*({1})^(({2})+1)/(({2})+1)`,r,i,n))},stop(t){throw t||=`Unable to compute integral!`,e.Utils.warn(t),new R(t)},partial_fraction(n,r,i,o){a(r)||(r=t.parse(r));let c;c=new s(0);let l=e.Algebra.PartFrac.partfrac(n,r);return l.group===v&&l.isLinear()?(l.each(e=>{e.isLinear()||H.integration.stop()}),l.each(e=>{c=t.add(c,H.integrate(e,r,i,o))})):c=t.add(c,H.integrate(l,r,i,o)),c},get_udv(n){let r=[[],[],[],[],[]],i=function(t){let n=t.group;if(n===o){let{fname:n}=t;e.Utils.inTrig(n)||e.Utils.inHtrig(n)?r[3].push(t):e.Utils.inInverseTrig(n)?r[1].push(t):n===x?r[0].push(t):H.integration.stop()}else n===h||t.isComposite()&&t.isLinear()||n===v&&t.isLinear()?r[2].push(t):n===y||t.isComposite()&&!t.isLinear()?r[4].push(t):H.integration.stop()};n.group===v?n.each(e=>{i(s.unwrapSQRT(e,!0))}):i(n);let a,c=new s(1);for(let e=0;e<5;e++){let i=r[e],o,l=i.length;if(l>0){if(l>1){o=new s(1);for(let e=0;e<l;e++)o=t.multiply(o,i[e].clone())}else o=i[0].clone();a?c=t.multiply(c,o):(a=o,a.multiplier=a.multiplier.multiply(n.multiplier))}}return[a,c]},trig_sub(n,r,i,a,o,s){o||=H.integration.decompose_arg(n.clone().toLinear(),r),o[3],o[2];let c=o[0],u=o[1];if(u.power.equals(2)&&c.greaterThan(0)){let r=e.Utils.getU(n),o=t.parse(`tan`+l(r)),s=t.parse(`${`sec`+l(r)}^2`),c=t.multiply(n.sub(u,o),s),d=H.integrate(c,r,i,a).sub(o,u);return e.Utils.clearU(o),d}},by_parts(n,r,i,a){a.previous||=[];let o,c=H.integration.get_udv(n),l=c[0],u=c[1],d=s.unwrapSQRT(t.expand(H.diff(l.clone(),r)),!0),f=d.clone().stripVar(r);d=t.divide(d,f.clone());
2649let p=H.integrate(u.clone(),r,i||0),m=t.multiply(p.clone(),d),h=m.toString();if(a.previous.indexOf(h)!==-1&&e.Utils.inTrig(l.fname)&&u.isE())return a.is_cyclic=!0,new s(1);a.previous.push(h);let g=t.multiply(l,p),_=m.multiplier.clone();m.toUnitMultiplier();let v=t.multiply(H.integrate(m.clone(),r,i,a),f);if(v.multiplier=v.multiplier.multiply(_),o=t.subtract(g,v),a.is_cyclic&&(a.previous.pop(),a.previous.length===0)){o=t.expand(o);let e=new s(0);o.each(n=>{n.contains(r)||(e=t.add(e,n.clone()))}),o=t.divide(t.subtract(o,e.clone()),t.subtract(new s(1),e))}return o},decompose_arg:e.Utils.decompose_fn},integrate(n,c,p,m){if(e.Utils.isVector(n)){let t=new e.Vector([]);return n.each(e=>{t.elements.push(H.integrate(e,c))}),t}if(!c){let t=e.Utils.variables(n);t.length===1&&(c=t[0]),c||=`x`}return isNaN(parseFloat(c))||t.error(`variable expected but received ${c}`),n.isConstant(!0)?t.multiply(n.clone(),t.parse(c)):(m||={},e.Utils.block(`PARSE2NUMBER`,()=>{p||=0;let b=a(c)?c.toString():c,z=s.unwrapSQRT(n.clone(),!0),ne=z.group,B;try{if(++p>e.Settings.integration_depth&&H.integration.stop(`Maximum depth reached. Exiting!`),!z.contains(b,!0))B=t.multiply(z.clone(),t.parse(b));else if(ne===h)B=H.integration.poly_integrate(z,b,p);else if(ne===y)if(z.previousGroup===o&&!(z.fname===`sqrt`||z.fname===i.PARENTHESIS)&&H.integration.stop(),z.contains(b)&&z.previousGroup!==o)z.power.contains(b)?H.integration.stop():(H.diff(z.clone().toLinear(),b).contains(b)&&H.integration.stop(),B=H.integration.poly_integrate(z));else{let e=H.diff(z.power.clone(),b);if(e.contains(b)){let n=e.stripVar(b),i=t.divide(e.clone(),n.clone());if(i.group===h&&i.isLinear())return n.multiplier=n.multiplier.divide(new r(2)),t.parse(d(`({2})*(sqrt(pi)*erf(sqrt(-{0})*{1}))/(2*sqrt(-{0}))`,n,b,z.multiplier));H.integration.stop()}if(z.isE())if(e.isLinear())B=z;else if(e.isE()&&a(e.power)&&e.power.group===h&&e.power.power.equals(1)){let e=a(z.power)?z.power:new s(z.power);B=t.multiply(t.symfunction(`Ei`,[e.clone()]),e)}else H.integration.stop();else{let e=t.symfunction(x,[t.parse(z.value)]);B=t.divide(z,e)}B=t.divide(B,e)}else if(z.isComposite()&&z.isLinear()){let e=t.parse(z.multiplier);z.toUnitMultiplier(),B=new s(0),z.each(e=>{B=t.add(B,H.integrate(e,b,p))}),B=t.multiply(e,B)}else if(ne===_)if(z.power.greaterThan(1)&&(z=t.expand(z)),z.power.equals(1))B=new s(0),z.each(e=>{B=t.add(B,H.integrate(e,b,p))},!0);else{let n=Number(z.power),r=z.multiplier.clone();z.toUnitMultiplier();let i=z.clone().toLinear(),a=H.integration.decompose_arg(i,b),o=a[3],c=a[2],d=a[0],f=a[1];if(n===-1&&f.group!==g&&f.power.equals(2)){let e=u(o)?Number(o)>0:!0;if(f.group===h&&f.power.equals(2)&&e){let e=function(e){let n=new s(1);return e.each(e=>{n=t.multiply(n,e.fname===`abs`?e.args[0]:e)}),n},n=d.clone(),r=o.clone();n=t.pow(n,new s(1/2)),r=t.pow(r,new s(1/2));let i=t.multiply(e(r),e(n)),a=t.symfunction(T,[t.divide(t.multiply(d,f.toLinear()),i.clone())]);B=t.divide(a,i)}else if(f.group===h&&f.isLinear())B=t.divide(H.integration.poly_integrate(z),d);else if(f.power.equals(4)){let e=l,n=t.parse(`${S+e(String(d))}*${b}^2`),r=t.parse(`${S+e(`2`)}*${e(String(d))}^${e(`1/4`)}*${e(String(o))}^${e(`1/4`)}*${b}`),i=t.parse(S+e(String(o))),a=t.add(t.add(n.clone(),r.clone()),i.clone()),s=t.add(t.subtract(n,r),i),c=t.parse(`${S+e(`2`)}*${e(String(o))}^${e(`3/4`)}`),u=t.parse(`${S+e(String(o))}*${e(String(o))}^${e(`1/4`)}*${b}`),f=t.parse(`2*${e(String(o))}*${S}${e(`2`)}*${e(String(o))}^${e(`1/4`)}`),h=t.divide(t.subtract(c.clone(),u.clone()),t.multiply(f.clone(),s)),g=t.divide(t.add(c,u),t.multiply(f,a.clone()));B=t.add(H.integrate(h,b,p,m),H.integrate(g,b,p,m))}else B=H.integration.partial_fraction(z,b,p)}else if(n===-1/2)if(f.group===h&&f.power.equals(2))if(c.multiplier.lessThan(0)&&!o.multiplier.lessThan(0))if(d.negate(),o.isConstant()&&d.isConstant()){let e=t.symfunction(S,[d.clone()]),n=t.symfunction(S,[t.multiply(d.clone(),o)]);B=t.divide(t.symfunction(C,[t.divide(c.toLinear(),n)]),e)}else{let e=t.symfunction(S,[d]),n=t.multiply(e.clone(),f.clone().toLinear());B=t.divide(t.symfunction(T,[t.divide(n,t.symfunction(S,[i.clone()]))]),e)}else H.integration.stop();else H.integration.stop();else if(n===1/2&&f.power.equals(2)&&d.greaterThan(0))H.integration.stop();else if(f.isLinear()&&f.group!==g)B=t.divide(H.integration.poly_integrate(z),d);else if(f.power.equals(2)&&d.greaterThan(0)){let n=t.parse(S+l(d)),r=t.parse(S+l(o)),i=t.multiply(n.clone(),r.clone()).invert(),a=t.pow(o,new s(z.power.toDecimal())),c=e.Utils.getU(z),u=t.multiply(i,f.clone().toLinear()),p=t.symfunction(T,[u]),m=(Math.abs(Number(z.power))-1)*2,h=H.integrate(t.parse(`${`cos`+l(c)}^${m}`));return e.Utils.clearU(c),t.multiply(h.sub(c,p),a)}else if(z.group!==v&&!z.power.lessThan(0))B=H.integration.by_parts(z,b,p,m);else{let n=z.clone().toLinear(),r=e.Algebra.Factor.factorInner(n).toString()!==n.toString();if(e.Algebra.degree(n,t.parse(b)).equals(2)&&!r)try{let r=e.Algebra.sqComplete(n,b),i=e.Utils.getU(n),a=r.f.sub(r.a,i),o=t.pow(a,t.parse(z.power));B=H.integrate(o,i).sub(i,r.a)}catch(e){if(e.message===`timeout`)throw e;H.integration.stop()}else B=H.integration.partial_fraction(z,b,p,m)}B.multiplier=B.multiplier.multiply(r)}else if(ne===o){let n=z.args[0],a=z.multiplier.clone();z.toUnitMultiplier();
2649let o=H.integration.decompose_arg(n,b),c=o[0],f=o[1],{fname:g}=z;if(g===x||g===C||g===w||g===T&&f.isLinear()){let r=z.power.toString();if(u(r)&&(p-=Number(r)),n.isComposite()){let i=e.Utils.getU(z),o=t.pow(t.parse(x+l(i)),new s(r)),c=H.diff(n,b),u=t.multiply(o,c),d=H.integrate(u,i,p,m);B=t.multiply(t.parse(a),d.sub(i,n))}else B=t.multiply(t.parse(a),H.integration.by_parts(z,b,p,m))}else if(g===`tan`&&z.power.lessThan(0)){let e=z.clone();return e.power.negate(),e.fname=`cot`,t.multiply(t.parse(a),H.integrate(e,b,p))}else{if(!c.contains(b,!0)&&z.isLinear())if(g===`abs`){let i=t.divide(n.clone(),c.clone());if(i.group===h&&!i.power.lessThan(0))if(e.Utils.even(i.power))B=H.integrate(n,b,p);else{let e=H.integrate(i,b,p);e.power=e.power.subtract(new r(1)),B=t.multiply(t.multiply(t.symfunction(`abs`,[i.toLinear()]),e),c)}else H.integration.stop()}else{let e=z.args[0].group,r=H.integration.decompose_arg(n,b);switch((!(e===_||e===h||e===v)||!r[1].power.equals(1)||n.hasFunc(``))&&H.integration.stop(),g){case`cos`:B=t.symfunction(`sin`,[n]);break;case`sin`:B=t.symfunction(`cos`,[n]),B.negate();break;case`tan`:B=t.parse(d(`${i.LOG}(sec({0}))`,n));break;case`sec`:B=t.parse(d(`${i.LOG}(tan({0})+sec({0}))`,n));break;case`csc`:B=t.parse(d(`-${i.LOG}(csc({0})+cot({0}))`,n));break;case`cot`:B=t.parse(d(`${i.LOG}(sin({0}))`,n));break;case k:B=t.symfunction(A,[n]);break;case A:B=t.symfunction(k,[n]);break;case j:B=t.parse(d(`${i.LOG}(cosh({0}))`,n));break;case E:B=H.integration.by_parts(z,b,p,m);break;case D:B=H.integration.by_parts(z,b,p,m);break;case O:B=H.integration.by_parts(z,b,p,m);break;case F:B=H.integration.by_parts(z,b,p,m);break;case I:B=H.integration.by_parts(z,b,p,m);break;case L:B=H.integration.by_parts(z,b,p,m);break;case N:B=t.parse(d(`atan(sinh({0}))`,n));break;case M:B=t.parse(d(`${i.LOG}(tanh(({0})/2))`,n));break;case P:B=t.parse(d(`${i.LOG}(sinh({0}))`,n));break;case`exp`:B=H.integrate(t.parse(d(`e^({0})`,n)),b,p);break;case`S`:{let e=z.args[0].clone(),n=H.integration.decompose_arg(e,b);n[1];let r=n[0],i=n[3];B=t.parse(d(`(cos((1/2)*pi*(({1})+({0})*({2}))^2)+pi*(({1})+({0})*({2}))*S(({1})+({0})*({2})))/(({0})*pi)`,r,i,f));break}case`C`:{let e=z.args[0].clone(),n=H.integration.decompose_arg(e,b),r=n[1],i=n[0],a=n[3];B=t.parse(d(`(pi*(({1})+({0})*({2}))*C(({1})+({0})*({2}))-sin((1/2)*pi*(({1})+({0})*({2}))^2))/(({0})*pi)`,i,a,r));break}case`erf`:{let e=z.args[0].clone(),n=H.integration.decompose_arg(e,b),r=n[1],i=n[0];B=t.parse(d(`e^(-(({2}))^2)/(({0})*sqrt(pi))+(1/({0})+({1}))*erf(({2}))`,i,r,e));break}case`sign`:B=t.multiply(z.clone(),n.clone());break;default:H.integration.stop()}B=t.divide(B,c)}else if(f.isLinear())if(g===`cos`||g===`sin`){let e=Number(z.power);if(e<0)z.fname=g===`sin`?`csc`:`sec`,z.invert().updateHash(),B=H.integrate(z,b,p);else{z.args[0];let i=z.clone(),a=z.clone(),o=new s((e-1)/e),l=t.multiply(c.clone(),new s(e)).invert();i.power=i.power.subtract(new r(1)),a.power=a.power.subtract(new r(2));let u=t.symfunction(g===`cos`?`sin`:`cos`,[n.clone()]);g===`sin`&&u.negate(),B=t.add(t.multiply(t.multiply(l,i),u),t.multiply(o,H.integrate(t.parse(a),b,p)))}}else if(g===`tan`||g===`cot`){if(z.args[0].isLinear(b)){let e=z.power.subtract(new r(1)).toString(),i=z.clone().toUnitMultiplier(),a=t.parse(d(`${g===`cot`?`-`:``}1/({2}*{0})*{3}({1})^({0})`,e,n,c,g));i.power=i.power.subtract(new r(2)),i.power.equals(0)&&(i=t.parse(i)),B=t.subtract(a,H.integrate(i,b,p))}}else if(g===`sec`||g===`csc`){let e=z.power.subtract(new r(1)).toString(),i=z.power.subtract(new r(2)).toString(),a=g===`sec`?`tan`:`cot`,o=z.clone().toUnitMultiplier(),l=d(`${g===`csc`?`-`:``}1/({0}*{1})*{4}({3})^({2})*{5}({3})`,c,e,i,n,g,a),u=t.parse(l);o.power=o.power.subtract(new r(2)),o.power.equals(0)&&(o=t.parse(o)),B=t.add(u,t.multiply(new s(Number(i)/Number(e)),H.integrate(o,b,p)))}else (g===A||g===k)&&z.power.equals(2)?B=H.integrate(z.fnTransform(),b,p):H.integration.stop();else H.integration.stop();B.multiplier=B.multiplier.multiply(a)}}else if(ne===g)B=H.integration.partial_fraction(z,b,p);else if(ne===v){z.getDenom().group===h&&(z=t.expand(z));let n=z.stripVar(b),i=t.divide(z.clone(),n.clone());if(n.contains(b)&&(i=t.multiply(i,n),n=new s(1)),i.group===v){let a=i.collectSymbols().sort((e,t)=>
2649e.group===t.group?Number(e.power)===Number(t.power)?e<t?1:-1:Number(t.power)-Number(e.power):t.group-e.group).map(e=>{let n=s.unwrapSQRT(e,!0);return n.fname===`exp`?t.parse(d(`({1})*e^({0})`,n.args[0],n.multiplier)):n}),c=a.length;if(Number(z.power)<0){if(c===2)return H.integrate(t.expand(z),b,p,m)}else if(c===2){try{B=H.integration.u_substitution(a,b)}catch(e){if(e.message===`timeout`)throw e}if(!B){let i=a[0].group,c=a[1].group,l=a[0],w=a[1],T=l.fname,E=w.fname;if(z=t.multiply(l.clone(),w.clone()),i===o&&c===o)if(T===x||E===x)B=H.integration.by_parts(z.clone(),b,p,m);else{a.sort((e,t)=>t.fname>e.fname?1:-1);let r=l.args[0];(!r.isLinear()||!(r.group===_||r.group===v||r.group===h))&&H.integration.stop();let i=H.integration.decompose_arg(r,b),o=i[1],c=i[0];o.isLinear()||H.integration.stop();let u=w.args[0];if(r.equals(u))if(T===`sin`&&E===`cos`||T===`cos`&&E===`sin`)if(l.power.lessThan(0)&&H.integration.stop(),T===`sin`&&l.power.add(w.power).equals(0))l.fname=`tan`,l.updateHash(),B=H.integrate(l,b,p);else if(f(l.power)&&E===`cos`&&w.power.lessThan(0)){let e=Number(l.power)/2,n=t.parse(d(`(1-cos({0})^2)^({1})`,l.args[0],e));B=H.integrate(t.expand(t.multiply(n,w.clone())),b,p,m)}else if(f(l.power)&&E===`sin`&&w.power.lessThan(0)){let e=Number(l.power)/2,n=t.parse(d(`(1-sin({0})^2)^({1})`,l.args[0],e));B=H.integrate(t.expand(t.multiply(n,w.clone())),b,p,m)}else{let i=e.Utils.even(l.power),a=e.Utils.even(w.power);if(B=new s(0),!i||!a){let n,a;i?(n=l,a=w):(n=w,a=l);let o=n.fname===`cos`?-1:1,c=(Number(a.power)-1)/2,u=t.parse(`(1-${n.fname}${e.Utils.inBrackets(r.toString())}^2)^${c}`);t.expand(t.multiply(new s(o),t.multiply(n.clone(),u))).each(e=>{B=t.add(B,H.integration.poly_integrate(e.clone()))})}else{let e=function(e){let n=e.power/2,r;return r=e.fname===`cos`?`((1/2)+(cos(2*(${e.args[0]}))/2))^${n}`:`((1/2)-(cos(2*(${e.args[0]}))/2))^${n}`,t.parse(r)},r=e(l),i=e(w),a=t.multiply(r,i);return t.expand(a).each(e=>{B=t.add(B,H.integrate(e,b,p))}),t.multiply(B,n)}}else if(T===`sec`&&E===`tan`&&o.isLinear()&&w.isLinear())B=t.parse(d(`sec({0})^({1})/({1})`,l.args[0],l.power));else if(T===`tan`&&E===`sec`&&o.isLinear())if(l.isLinear()&&w.isLinear())B=t.divide(t.symfunction(`sec`,[r.clone()]),c);else if(f(l.power)){let e=Number(l.power)/2,n=t.parse(d(`(sec({0})^2-1)^({1})`,l.args[0],e));B=H.integrate(t.expand(t.multiply(n,w)),b,p)}else H.integration.stop();else if(T===`sec`&&E===`cos`)l.fname=`cos`,l.invert().updateHash(),B=H.integrate(t.multiply(l,w),b,p);else if(T===`sin`&&E===`csc`)w.fname=`sin`,w.invert().updateHash(),B=H.integrate(t.multiply(l,w),b,p);else if(T===`tan`&&(E===`cos`||E===`sin`)&&w.power.lessThan(0)){let e=t.multiply(l.fnTransform(),w);B=H.integrate(t.expand(e),b,p)}else{let e=t.multiply(l.fnTransform(),w.fnTransform());B=H.integrate(t.expand(e),b,p)}else if((T===`sin`||T===`cos`)&&(E===`sin`||E===`cos`))if(l.isLinear()&&w.isLinear())if(l.args[0].isLinear()&&w.args[0].isLinear()){let e,n;E===`sin`?(e=l.args[0],n=w.args[0]):(n=l.args[0],e=w.args[0]);let r=t.parse(d(`(sin(({1})+({0}))+sin(({1})-({0})))/2`,e.toString(),n.toString()));B=H.integrate(r,b,p)}else{let e=V(a);B=H.integrate(t.expand(e),b,p)}else{let e=new s(1);a.forEach(n=>{let r=n.fnTransform();e=t.multiply(e,r)});let n=t.expand(e);B=H.integrate(n,b,p),B.hasIntegral()&&(B=H.integrate(V(e.collectSymbols()),b,p))}else H.integration.stop()}else if(i===o&&c===h){let e=l.isLinear();if(l.fname===`cos`&&e&&w.power.equals(-1))B=t.symfunction(`Ci`,[l.args[0]]);else if(l.fname===`cos`&&w.power.equals(-1))B=H.integrate(t.multiply(l.fnTransform(),w.clone()),b,p);else if(l.fname===A&&e&&w.power.equals(-1))B=t.symfunction(`Chi`,[l.args[0]]);else if(l.fname===A&&w.power.equals(-1))B=H.integrate(t.multiply(l.fnTransform(),w.clone()),b,p);else if(l.fname===`sin`&&e&&w.power.equals(-1))B=t.symfunction(`Si`,[l.args[0]]);else if(l.fname===`sin`&&w.power.equals(-1))B=H.integrate(t.multiply(l.fnTransform(),w.clone()),b,p);else if(l.fname===k&&e&&w.power.equals(-1))B=t.symfunction(`Shi`,[l.args[0]]);else if(l.fname===k&&w.power.equals(-1))B=H.integrate(t.multiply(l.fnTransform(),w.clone()),b,p);else if(l.fname===x&&w.power.equals(-1))B=H.integration.poly_integrate(l,b,p);else if(l.fname===`erf`){if(w.power.equals(1)){let e=H.integration.decompose_arg(l.args[0],b),n=e[0],r=e[1],i=l.args[0].toString();B=t.parse(d(`(e^(-(({2}))^2)*(sqrt(pi)*e^((({2}))^2)*(2*({0})^2*({1})^2-3)*erf(({2}))+2*({0})*({1})-2))/(4*sqrt(pi)*({0})^2)`,n,r,i))}}else B=H.integration.by_parts(z,b,p,m)}else if(i===y&&c===h){let e=T===x?H.integration.decompose_arg(l.args[0],b)[1]:null;B=l.isE()&&ee(l)&&w.power.equals(-1)?t.symfunction(`Ei`,[l.power.clone()]):T===x&&e.value===w.value?H.integration.poly_integrate(l):H.integration.by_parts(z,b,p,m)}else if(i===g&&c===h){if(w.value===l.value&&l.power.equals(-1)){let n=Math.min.apply(null,e.Utils.keys(l.symbols)),i=Math.min(n,Number(w.power)),a=w.clone();a.power=new r(i),w=t.divide(w,a.clone());let o=new s(0);l.each(e=>{o=t.add(o,t.divide(e.clone(),a.clone()))}),o.multiplier=l.multiplier,z=t.divide(w,o)}else z=t.expand(z);B=H.integration.partial_fraction(z,b,p)}else if(i===_&&c===h){let r=l.clone().toLinear(),i=e.Algebra.degree(r,t.parse(b)).equals(1);if(l.power.equals(-1/2)){let n=H.integration.decompose_arg(l.clone().toLinear(),b),r=n[0].negate(),i=n[1],a=n[3],o=Number(l.power),c=Number(w.power);
2649if(u(c)&&e.Utils.even(c)&&i.power.equals(2)){let e=t.divide(t.multiply(t.pow(a.clone(),new s(2)),t.symfunction(S,[t.divide(a.clone(),r.clone())])),t.pow(r.clone(),new s(2)));e=t.multiply(e,t.symfunction(S,[a]).invert());let n=t.parse(`sin(u)`);n.power=n.power.multiply(w.power);let i=H.integrate(n,`u`,p),o=t.parse(`${C}(${S}(${r}/${a})*${b})`);B=t.multiply(e,i.sub(new s(`u`),o))}else if(o===-1/2){let e=function(e,n){let r=t.parse(H.integrate(e,b,p,m).sub(b,d(n,b)));if(!r.hasIntegral())return r};c===-1?B=e(t.expand(t.expand(t.pow(t.multiply(l.invert(),w.invert()),new s(2)))).invert(),`sqrt(1-1/({0})^2)`):c===-2&&(B=e(t.sqrt(t.expand(t.divide(t.pow(z,new s(2)).invert(),t.pow(new s(b),new s(2))).negate())).invert(),`sqrt(1-1/({0})^2)`))}}else if(l.power.equals(-1)&&w.isLinear()&&i)B=H.integration.partial_fraction(z,b,p);else if(!l.power.lessThan(0)&&u(l.power)){let e=t.expand(l);B=new s(0),e.each(e=>{e.group===g?e.each(e=>{B=t.add(B,H.integrate(t.multiply(w.clone(),e),b,p))}):B=t.add(B,H.integrate(t.multiply(w.clone(),e),b,p))})}else if(l.power.lessThan(-2))B=H.integration.by_parts(z,b,p,m);else if(l.power.lessThan(0)&&w.power.greaterThan(1)){let n=H.integration.decompose_arg(l.clone().toLinear(),b);n[0].negate();let r=n[1],i=n[3],a=l.clone().toLinear();if(r.group!==g&&r.isLinear()){let e=Number(w.power),n=new s(`_u_`),r=t.expand(t.divide(t.pow(t.subtract(n.clone(),i.clone()),new s(e)),n.clone())),o={};o._u_=a;let c=t.parse(r,o);B=H.integrate(c,b,0)}else if(w.power.greaterThan(r.power)||w.power.equals(r.power)){let n=new e.Algebra.Classes.Factors;l=e.Algebra.Factor.coeffFactor(l.invert(),n);let r=e.Algebra.divide(w,l);r.group===v?B=H.integration.by_parts(z,b,p,m):(B=new s(0),r.each(e=>{B=t.add(B,H.integrate(e,b,p))}),n.each(e=>{B=t.divide(B,e)}),B=t.expand(B))}else B=H.integration.partial_fraction(z,b,p)}else if(l.power.den.equals(2)){let e=H.integration.decompose_arg(l.clone().toLinear(),b),r=e[3],i=e[1],a=e[0];if(e[2],i.power.equals(2)&&a.lessThan(0)){r.equals(1)||(n=t.multiply(n,t.pow(r,new s(2))));let e=b,i=t.divide(t.pow(a.clone().negate(),new s(1/2)),t.pow(r,new s(1/2))),o=t.symfunction(`cos`,[new s(e)]),c=t.pow(t.symfunction(`cos`,[new s(e)]),new s(Number(l.power.num))),u=t.pow(t.symfunction(`sin`,[new s(e)]),new s(Number(w.power))),d=t.multiply(t.multiply(c,o),u);B=H.integrate(d,e,p).sub(e,t.symfunction(C,[t.multiply(new s(b),i)]))}else B=H.integration.partial_fraction(z,b,p,m)}else i&&(B=H.integration.partial_fraction(z,b,p))}else if(l.isComposite()&&w.isComposite())if(B=new s(0),l.power.greaterThan(0)&&w.power.greaterThan(0))t.expand(z).each(e=>{B=t.add(B,H.integrate(e,b,p))},!0);else{let e=Number(l.power),n=Number(w.power);if(e<0&&n>0){let e=l;l=w,w=e}e===-1&&n===-1?B=H.integration.partial_fraction(z,b,p):l.each(e=>{let n=t.multiply(e,w.clone()),r=H.integrate(n,b,p);B=t.add(B,r)})}else if(i===_&&a[0].power.greaterThan(0))l=t.expand(l),B=new s(0),l.each(e=>{B=t.add(B,H.integrate(t.multiply(e,w.clone()),b,p))},!0);else if(i===o&&c===y&&e.Utils.inHtrig(l.fname))l=l.fnTransform(),B=H.integrate(t.expand(t.multiply(l,w)),b,p);else if(i===o&&c===_||c===o&&i===_){if(c===o&&i===_){let e=l;l=w,w=e}let n,r,a,u,d=s.unwrapSQRT(H.diff(l.clone(),b),!0),f=s.unwrapSQRT(w,!0);if(d.power.equals(f.power)){if(n=new s(Number(w.power)),a=d.clone().toLinear(),u=w.clone().toLinear(),r=e.Algebra.divide(a.toLinear(),u),r.isConstant()){let e=t.pow(r,n.negate());B=t.multiply(e,H.integration.poly_integrate(l.clone()))}}else B=H.integration.by_parts(z,b,p,m)}else{let e=l.clone().toLinear(),n=w.clone().toLinear();B=i===y&&c===y&&l.power.contains(b)&&w.power.contains(b)&&!e.contains(b)&&!n.contains(b)?t.parse(d(`(({0})^(({2})*({4}))*({1})^(({3})*({4})))/(log(({0})^({2}))+log(({1})^({3})))`,e.toString(),n.toString(),l.power.multiplier.toString(),w.power.multiplier.toString(),b)):H.integration.by_parts(z,b,p,m)}}}else if(c===3&&(a[2].group===h&&a[2].power.lessThan(2)||a[0].group===_)){let e=a[0];if(e.group===_){e.power.greaterThan(1)&&(e=t.expand(e));let n=t.multiply(a[1],a[2]);B=new s(0),e.each(e=>{let r=t.multiply(e,n.clone()),i=H.integrate(r,b,p);B=t.add(B,i)},!0)}else B=H.integration.by_parts(z,b,p,m)}
2649else if(te(a)){let e=new s(1);for(let n=0,r=a.length;n<r;n++)e=t.multiply(e,a[n].fnTransform());e=t.expand(e),B=H.integrate(e,b,p)}else{let e=V(a);B=H.integrate(t.expand(e),b,p)}}else{if(i.equals(1))return H.integrate(t.expand(z),b,p);i.clone().toLinear().isPoly(!0)&&e.Utils.variables(i).length>1&&(i=e.Algebra.Factor.factorInner(i)),B=H.integrate(i,b,p)}B=t.multiply(B,n)}if(B)return B}catch(t){if(t.message===`timeout`||!(t instanceof R||t instanceof e.exceptions.DivisionByZero))throw t}let re=a(c)?c.toString():c;return t.symfunction(`integrate`,[n,new s(re)])},!1))},defint(n,r,i,a){a||=`x`;let o=function(e,n,r){try{return t.parse(e,n)}catch(t){if(t.message===`timeout`)throw t;return H.Limit.limit(e,a,r)}},c=e.Utils.variables(n),l=n.hasTrig(),u,d;if(c.length===1&&!a&&(a=c[0]),l||(d=H.integrate(n,a)),!l&&!d.hasIntegral()){let e={},n={};e[a]=i,n[a]=r;let s=o(d,e,i),c=o(d,n,r);u=t.subtract(s,c)}else if(c.length===1&&r.isConstant()&&i.isConstant()){let t=e.Build.build(n);u=new s(e.Math2.num_integrate(t,Number(r),Number(i)))}else u=t.symfunction(`defint`,[n,r,i,new s(a)]);return u},Limit:{interval(e,n){return t.parse(d(`[{0}, {1}]`,e,n))},diverges(){return H.Limit.interval(`-Infinity`,`Infinity`)},divide(n,r,a,o,c){if(c++>i.max_lim_depth)return;n.clone();let l=r.clone();if(r.fname===`abs`){let e=n.sign(),i=o.sign();if(o.isInfinity)return t.multiply(new s(e),new s(i));if(o.equals(0)){let e=t.parse(n.multiplier),i=t.parse(r.multiplier);return t.divide(t.multiply(e,H.Limit.interval(`-1`,`1`)),i)}return H.Limit.diverges()}let u=function(t){if(e.Utils.isVector(t)){let e=t;for(let t=0;t<e.elements.length;t++)if(!e.elements[t].isInfinity)return!1;return!0}return t.isInfinity},d=function(t,n){return e.Utils.isVector(t)?!1:t.equals(n)},f,m=0,h,g,_;do if(h=p(H.Limit.limit(n.clone(),a,o,c)),g=p(H.Limit.limit(r.clone(),a,o,c)),_=u(h)&&u(g)||d(h,0)&&d(g,0),_){let e=H.diff(n.clone(),a),i=H.diff(r.clone(),a),o=t.divide(e,i);n=o.getNum(),r=o.getDenom()}while(_&&++m<i.max_lim_depth);if(m>=i.max_lim_depth)return;let v=g.equals(0);return Number(l.power),f=o.isConstant(!0)&&v?s.infinity(h.lessThan(0)?-1:void 0):v?H.Limit.diverges():t.divide(h,g),f},rewriteToLog(e){let n=e.power.clone();return e.toLinear(),t.pow(new s(`e`),t.multiply(n,t.symfunction(`${i.LOG}`,[e])))},getSubbed(e,t,n){let r;e.group===y&&(e=H.Limit.rewriteToLog(e));try{r=e.sub(t,n)}catch(t){if(t.message===`timeout`)throw t;r=e}return r},isInterval(t){return e.Utils.isVector(t)},isConvergent(e){return!(H.Limit.isInterval(e)&&e.elements[0].isInfinity&&e.elements[1].isInfinity||e.containsFunction(`limit`))},limit(n,r,c,l){if(n.isLinear()&&n.isComposite()){let e=new s(0);return n.each(n=>{e=t.add(e,H.Limit.limit(n,r,c,l))},!0),e}if(n=e.Algebra.Simplify.simplify(n),l||=1,l++>i.max_lim_depth)return;let u=t.parse(n.multiplier);n.toUnitMultiplier();let f;try{if(n.isConstant(!0))f=n;else{let m={};m[r]=c;try{let e=t.parse(n.sub(r,c),m);(e.isConstant(!0)||e.isInfinity)&&(f=e)}catch(e){if(e.message===`timeout`)throw e}if(!f){let g=n.getNum(),_=n.getDenom();if(_.isConstant(!0)){if(n.group===y){let i=n.clone().toLinear();n.power.clone();let o=i.getNum(),u=i.getDenom(),p=e.Utils.decompose_fn(u,r,!0);if(o.group===h&&o.multiplier.isOne()&&p.ax.group===h&&p.b.isConstant(!0)&&p.a.isOne()&&p.b.isConstant(!0))f=t.parse(d(`(1/e^({0}))`,p.b));else{let e=H.Limit.rewriteToLog(n.clone()),i=e.power.clone(),o=e.clone().toLinear(),u=H.Limit.limit(o,r,c,l),d=a(i)?i:new s(i),p=H.Limit.limit(d,r,c,l);f=t.pow(u,p)}}else if(n.group===o&&n.args.length===1){let a,o=H.Limit.limit(n.args[0],r,c,l);if(e.Utils.isVector(o))return f=o.map(e=>{let i=n.clone();return i.args[0]=e,H.Limit.limit(t.symfunction(n.fname,[e]),r,c,l)}),t.multiply(u,f);let d;if(o.isConstant(!0)){d=t.symfunction(n.fname,[o]);try{p(d),a=!0}catch(e){if(e.message===`timeout`)throw e;a=!1}}if(a)f=d;else if(H.Limit.isConvergent(o)){if(n.fname===x)switch(o.toString()){case`0`:f=s.infinity().negate();break;case`Infinity`:f=s.infinity();break;case`-Infinity`:f=s.infinity();break}else if((n.fname===`cos`||n.fname===`sin`)&&c.isInfinity)f=H.Limit.interval(-1,1);else if(n.fname===`tan`){let e=n.args[0],t=e.getNum(),r=e.getDenom(),i=t.toUnitMultiplier();(c.isInfinity||i.equals(`pi`)&&r.equals(2))&&(f=H.Limit.diverges())}else if(n.fname===i.FACTORIAL&&o.isInfinity)return s.infinity()}}else if(n.group===h){if(Number(n.power)>0)return t.parse(n,m);f=e.Utils.even(n.power)?s.infinity():H.Limit.diverges()}else if(n.group===v){let e,i,a=n.collectSymbols().sort((e,t)=>
2649e.group-t.group),o=a.pop();for(e=p(H.Limit.limit(o,r,c,l));a.length;){let n=a.pop();i=p(H.Limit.limit(n,r,c,l)),e.isInfinity||!H.Limit.isConvergent(e)&&i.equals(0)||e.equals(0)&&H.Limit.isConvergent(i)?(n.containsFunction(x)&&(n=[o,o=n][0]),n.invert(),e=e.isInfinity&&i.isInfinity?s.infinity():H.Limit.divide(o,n,r,c,l)):(e=t.multiply(e,i),o=t.multiply(o,n))}f=e}else if(n.isComposite()){let e;n.isLinear()||(n=t.expand(n)),f=new s(0);let a=n.collectSymbols().sort((e,t)=>t.group-e.group),u=[],d=new s(0);for(let e=0,n=a.length;e<n;e++){let n=a[e].clone();n.group===o||n.group===v&&n.hasFunc(``)?d=t.add(d,n):u.push(n)}u.unshift(d),u.length!==1&&(a=u);for(let o=0,s=a.length;o<s;o++){let s=a[o];try{e=H.Limit.limit(s,r,c,l)}catch(t){if(t.message===`timeout`)throw t;e=H.Limit.diverges()}try{f=t.add(f,e)}catch(e){if(e.message===`timeout`)throw e;if(l++>i.max_lim_depth)return;f=H.Limit.limit(H.diff(n,r),r,c,l)}}}}else f=H.Limit.divide(g,_,r,c,l)}}f||=t.symfunction(`limit`,[n,new s(r),c])}catch(e){if(e.message===`timeout`)throw e;f=t.symfunction(`limit`,[n,new s(r),c])}return t.multiply(u,f)}},Fresnel:{S(e){return e.isConstant(!0)?H.defint(t.parse(`sin(pi*x^2/2)`),new s(0),e,`x`):t.symfunction(`S`,[e])},C(e){return e.isConstant(!0)?H.defint(t.parse(`cos(pi*x^2/2)`),new s(0),e,`x`):t.symfunction(`C`,[e])}}};n.register([{name:`diff`,visible:!0,numargs:[1,3],build(){return H.diff}},{name:`sum`,visible:!0,numargs:4,build(){return H.sum}},{name:`product`,visible:!0,numargs:4,build(){return H.product}},{name:`integrate`,visible:!0,numargs:[1,2],build(){return H.integrate}},{name:`defint`,visible:!0,numargs:[3,4],build(){return H.defint}},{name:`S`,visible:!0,numargs:1,build(){return H.Fresnel.S}},{name:`C`,visible:!0,numargs:1,build(){return H.Fresnel.C}},{name:`limit`,visible:!0,numargs:[3,4],build(){return H.Limit.limit}}]),n.updateAPI()})()}),JW=HW((e,t)=>{var n=typeof globalThis<`u`&&globalThis.nerdamer?globalThis.nerdamer:void 0;typeof t<`u`&&n===void 0&&(n=KW(),qW()),(function(){let e=n.getCore(),t=e.PARSER,{N:r,P:i,S:a,EX:o,FN:s,PL:c,CP:l,CB:u}=e.groups,{keys:d,even:f,variables:p,format:m,round:h,isInt:g}=e.Utils,{Frac:_,NerdamerSymbol:v,Vector:y,Expression:b}=e,{CONST_HASH:x}=e.Settings,S=e.Utils.importFunctions();e.Utils.evaluate;function C(n,r,i){if(this.coeffs=[],this.variable=``,e.Utils.isSymbol(n))this.parse(n),this.variable||=r||``;else if(typeof n==`number`&&!isNaN(n)){if(i||=0,r===void 0)throw new e.exceptions.InvalidVariableNameError(`Polynomial expects a variable name when creating using order`);this.coeffs=[],this.coeffs[i]=new _(n),this.fill(n)}else typeof n==`string`&&this.parse(t.parse(n))}C.fromArray=function(t,n){if(typeof n>`u`)throw new e.exceptions.InvalidVariableNameError(`A variable name must be specified when creating polynomial from array`);let r=new C;return r.coeffs=t,r.variable=n,r},C.fit=function(e,t,n,r,i,a){let o=Array(i+1),s=n-t;o[0]=t,o[i]=e,s-=e*r**i;for(let e=i-1;e>0;e--){let t=r**e,n=s/t,i=Math.sign(n)*Math.floor(Math.abs(n));s-=i*t,o[e]=i}if(s!==0)return null;for(let e=0;e<o.length;e++)o[e]=new _(o[e]);return C.fromArray(o,a)},C.prototype={parse(n,i){if(this.variable=p(n)[0],!n.isPoly())throw new e.exceptions.NerdamerTypeError(`Polynomial Expected! Received ${e.Utils.text(n)}`);if(i||=[],n.power.absEquals(1)||(n=t.expand(n)),n.group===e.groups.N)i[0]=n.multiplier;else if(n.group===e.groups.S)i[Number(n.power.toDecimal())]=n.multiplier;else for(let t in n.symbols){if(!Object.hasOwn(n.symbols,t))continue;let a=n.symbols[t],o=a.power;if(e.Utils.isSymbol(o))throw new e.exceptions.NerdamerTypeError(`power cannot be a NerdamerSymbol`);let s=a.group===r?0:Number(o.toDecimal());a.symbols?this.parse(a,i):i[s]=a.multiplier}this.coeffs=i,this.fill()},fill(e){e=Number(e)||0;let t=this.coeffs.length;for(let n=0;n<t;n++)this.coeffs[n]===void 0&&(this.coeffs[n]=new _(e));return this},trim(){let e=this.coeffs.length;for(;e--;){let t=this.coeffs[e],n=t.equals(0);if(t&&n){if(e===0)break;this.coeffs.pop()}else break}return this},modP(e){let t=this.coeffs.length;for(let n=0;n<t;n++){let r=this.coeffs[n],i;if(r.lessThan(0)){let a;for(i=n;i<t;i++)if(this.coeffs[i].greaterThan(0)){a=this.coeffs[i];break}if(a){for(;i>n;i--)this.coeffs[i]=this.coeffs[i].subtract(new _(1)),this.coeffs[i-1]=this.coeffs[i-1].add(new _(e));r=this.coeffs[n]}}let a=r.mod(new _(e)),o=r.subtract(a).divide(new _(e));if(!o.equals(0)){let e=n+1,t=this.coeffs[e]||new _(0);t=t.add(o),this.coeffs[e]=t,this.coeffs[n]=a}}return this},add(e){let t=Math.max(this.coeffs.length,e.coeffs.length);for(let n=0;n<t;n++){let t=this.coeffs[n]||new _(0),r=e.coeffs[n]||new _(0);this.coeffs[n]=t.add(r)}return this},subtract(e){let t=Math.max(this.coeffs.length,e.coeffs.length);for(let n=0;n<t;n++){let t=this.coeffs[n]||new _(0),r=e.coeffs[n]||new _(0);this.coeffs[n]=t.subtract(r)}return this},divide(t){let{variable:n}=this,r=e.Utils.arrayClone(this.coeffs),i=e.Utils.arrayClone(t.coeffs),a=r.length,o=i.length-1,s=[];for(let e=0;e<a;e++){let t=a-(e+1),n=t-o,c=r[t].divide(i[o]);if(n<0)break;s[n]=c;for(let e=0;e<=o;e++)r[e+n]=r[e+n].subtract(i[e].multiply(c))}let c=C.fromArray(r,n||`x`).trim();return[C.fromArray(s,n||`x`),c]},multiply(e){let t=this.coeffs.length,n=e.coeffs.length,r=[];for(let i=0;i<t;i++){let t=this.coeffs[i];for(let a=0;a<n;a++){let n=i+a,o=e.coeffs[a];r[n]=(r[n]||new _(0)).add(t.multiply(o))}}return this.coeffs=r,this},isZero(){let e=this.coeffs.length;for(let t=0;t<e;t++)if(!this.coeffs[t].equals(0))return!1;return!0},sub(e){let t=new _(0),n=this.coeffs.length;for(let r=0;r<n;r++){let n=this.coeffs[r];n.equals(0)||(t=t.add(n.multiply(new _(e**r))))}return t},clone(){let e=new C;return e.coeffs=this.coeffs.slice(),e.variable=this.variable,e},deg(){return this.trim(),this.coeffs.length-1},lc(){return this.coeffs[this.deg()].clone()},monic(){let e=this.lc(),t=this.coeffs.length;for(let n=0;n<t;n++)this.coeffs[n]=this.coeffs[n].divide(e);return this},gcd(t){let n=this.coeffs.length-1,r=t.coeffs.length-1,i;if(n<r)return t.gcd(this);let a=this;for(;!t.isZero();){let e=t.clone();a=a.clone(),i=a.divide(e),t=i[1],a=e}let o=e.Math2.QGCD.apply(null,a.coeffs);if(!o.equals(1)){let e=a.coeffs.length;for(let t=0;t<e;t++)a.coeffs[t]=a.coeffs[t].divide(o)}return a},diff(){let e=[],t=this.coeffs.length;for(let n=1;n<t;n++)e.push(this.coeffs[n].multiply(new _(n)));return this.coeffs=e,this},integrate(){let e=[new _(0)],t=this.coeffs.length;for(let n=0;n<t;n++){let t=new _(n+1);e[n+1]=this.coeffs[n].divide(t)}return this.coeffs=e,this},gcf(t){let n=function(e){for(let t=0;t<e.length;t++)if(!e[t].equals(0))return t},r=[];for(let e=0;e<this.coeffs.length;e++){let t=this.coeffs[e];!t.equals(0)&&r.indexOf(t)===-1&&r.push(t)}let i=[e.Math2.QGCD.apply(void 0,r),n(this.coeffs)||0];if(t){let e=[];e[i[1]-1]=i[0],i=C.fromArray(e,this.variable).fill()}return i},quad(e){let t=[];if(this.coeffs.length>3)throw Error(`Cannot calculate quadratic order of ${this.coeffs.length-1}`);if(this.coeffs.length===0)throw Error(`Polynomial array has no terms`);let n=this.coeffs[2]?Number(this.coeffs[2].toDecimal()):0,r=this.coeffs[1]?Number(this.coeffs[1].toDecimal()):0,i=Number(this.coeffs[0].toDecimal()),a=r*r-4*n*i;return a<0&&!e||(t[0]=(-r+Math.sqrt(a))/(2*n),t[1]=(-r-Math.sqrt(a))/(2*n)),t},squareFree(){let e=this.clone(),t=1,n=e.clone().diff(),r=e.clone().gcd(n),i=e.divide(r)[0],a=C.fromArray([new _(1)],e.variable);for(;!r.equalsNumber(1);){let e=i.gcd(r),n=i.divide(e)[0];if(!n.equalsNumber(1)&&t>1){let e=n.clone();for(let r=1;r<t;r++)e.multiply(n.clone());n=e}a=a.multiply(n),t++,i=e,r=r.divide(e)[0]}return[a,i,t]},toSymbol(){let n=this.coeffs.length,{variable:r}=this;if(n===0)return new v(0);if(!r)throw new e.exceptions.NerdamerTypeError(`Polynomial.toSymbol requires a variable. Constants should not be converted to Polynomial.`);let i=[];for(let e=0;e<n;e++){let t=this.coeffs[e];t.equals(0)||i.push(`${t}*${r}^${e}`)}return i.length===0?new v(0):t.parse(i.join(`+`))},equalsNumber(e){return this.trim(),this.coeffs.length===1&&this.coeffs[0].toDecimal()===String(e)},toString(){return this.toSymbol().toString()}}
2649,v.prototype.coeffs=function(e,n){n&&!this.isPoly(!0)&&t.error(`Polynomial expected when requesting coefficients with order`),e||=[];let r=this.clone().distributeMultiplier();if(r.isComposite())for(let t in r.symbols){if(!Object.hasOwn(r.symbols,t))continue;let i=r.symbols[t];i.isComposite()?i.clone().distributeMultiplier().coeffs(e,n):n?e[i.isConstant()?0:Number(i.power.toDecimal())]=i.multiplier:e.push(i.multiplier)}else if(n)e[r.isConstant(!0)?0:Number(r.power.toDecimal())]=r.multiplier;else if(r.group===u&&r.isImaginary()){let n=new v(r.multiplier);r.each(e=>{(e.isConstant(!0)||e.imaginary)&&(n=t.multiply(n,e))}),e.push(n)}else e.push(r.multiplier);if(n)for(let t=0;t<e.length;t++)e[t]===void 0&&(e[t]=new v(0));return e},v.prototype.tBase=function(e){if(typeof e>`u`)throw Error(`NerdamerSymbol.tBase requires a map object!`);let t=[],n=this.collectSymbols(null,null,null,!0),r=n.length;for(let i=0;i<r;i++){let r=n[i],a=r.group,o=new T(r.multiplier,[],e);if(a===u)for(let t in r.symbols){if(!Object.hasOwn(r.symbols,t))continue;let n=r.symbols[t];o.terms[e[t]]=n.power}else o.terms[e[r.value]]=r.power;t.push(o.fill()),o.updateCount()}return t},v.prototype.altVar=function(e){let t=this.multiplier.toString(),n=this.power.toString();return(t===`1`?``:`${t}*`)+e+(n===`1`?``:`^${n}`)},v.prototype.sameVars=function(e){if(!(this.symbols||this.group===e.group))return!1;for(let t in this.symbols){if(!Object.hasOwn(this.symbols,t))continue;let n=this.symbols[t],r=e.symbols[t];if(!r||n.value!==r.value)return!1}return!0},v.prototype.groupTerms=function(n){n=String(n);let r,i,a,o=[];return this.each(s=>{if(s.group===c){a=s.groupTerms(n);for(let e=0;e<a.length;e++){let t=a[e];t&&(o[e]=t)}}else r=e.Utils.decompose_fn(s,n,!0),i=r.x.value===n?Number(r.x.power):0,o[i]=t.add(o[i]||new v(0),r.a)}),o},v.prototype.collectFactors=function(){let e=[];return this.group===u?this.each(t=>{e.push(t.clone())}):e.push(this.clone()),e};function w(){this.factors={},this.length=0,this.preAdd=void 0,this.pFactor=void 0}w.prototype.getNumberSymbolics=function(){let e=0;return this.each(t=>{t.isConstant(!0)||e++}),e},w.prototype.add=function(n){if(n.equals(0))return this;if(n.equals(-1)&&this.length>0){let n=e.Utils.firstObject(this.factors,null,!0),r=t.symfunction(e.Settings.PARENTHESIS,[n.obj]).negate();return delete this.factors[n.key],this.add(r),this.length--,this}if(n.group===u){let e=this;n.multiplier.equals(1)||e.add(new v(n.multiplier)),n.each(t=>{e.add(t)})}else{this.preAdd&&(n=this.preAdd(n)),this.pFactor&&(n=t.pow(n,new v(this.pFactor)));let e=n.isConstant();if(e&&n.equals(1))return this;let r=e?n.value:n.text();r in this.factors?(this.factors[r]=t.multiply(this.factors[r],n),this.factors[r].equals(1)&&(delete this.factors[r],this.length--)):(this.factors[r]=n,this.length++)}return this},w.prototype.toSymbol=function(){let n=new v(1),r=Object.values(this.factors).sort((e,t)=>e.group>t.group?1:-1);for(let i=0,a=r.length;i<a;i++){let a=r[i],o=a.power.equals(1)&&a.fname!==``?t.symfunction(e.Settings.PARENTHESIS,[a]):a;n=t.multiply(n,o)}return n.fname===``&&(n=v.unwrapPARENS(n)),n},w.prototype.merge=function(e){for(let n in e)n in this.factors?this.factors[n]=t.multiply(this.factors[n],e[n]):this.factors[n]=e[n];return this},w.prototype.each=function(t){for(let n in this.factors){if(!Object.hasOwn(this.factors,n))continue;let r=this.factors[n];r.fname===e.Settings.PARENTHESIS&&r.isLinear()&&(r=r.args[0]),t.call(this,r,n)}return this},w.prototype.count=function(){return d(this.factors).length},w.prototype.clean=function(){try{let t=e.Settings.CONST_HASH;this.factors[t].lessThan(0)&&(this.factors[t].equals(-1)?delete this.factors[t]:this.factors[t].negate(),this.each(e=>{e.negate()}))}catch(e){if(e.message===`timeout`)throw e}},w.prototype.toString=function(){return this.toSymbol().toString()};function T(e,t,n){this.terms=t||[],this.coeff=e,this.map=n,this.sum=new _(0),this.image=void 0,this.revMap=void 0,this.count=void 0}T.prototype.updateCount=function(){this.count||=0;for(let e=0;e<this.terms.length;e++)this.terms[e].equals(0)||this.count++;return this},T.prototype.getVars=function(){let e=[];for(let t=0;t<this.terms.length;t++){let n=this.terms[t];this.getRevMap(),!n.equals(0)&&this.revMap&&e.push(this.revMap[t])}return e.join(` `)},T.prototype.len=function(){return typeof this.count>`u`&&this.updateCount(),this.count||0},T.prototype.toSymbol=function(e){e||=this.getRevMap();let n=new v(this.coeff);for(let r=0;r<this.terms.length;r++){let i=e[r],a=this.terms[r];if(a.equals(0)||i===x)continue;let o=new v(i);o.power=a,n=t.multiply(n,o)}return n},T.prototype.getRevMap=function(){if(this.revMap)return this.revMap;let e={};if(this.map)for(let t in this.map)Object.hasOwn(this.map,t)&&(e[this.map[t]]=t);return this.revMap=e,e},T.prototype.generateImage=function(){return this.image=this.terms.join(` `),this},T.prototype.getImg=function(){return this.image||this.generateImage(),this.image||``},T.prototype.fill=function(){let e=this.map?this.map.length:0;for(let t=0;t<e;t++)typeof this.terms[t]>`u`?this.terms[t]=new _(0):this.sum=this.sum.add(this.terms[t]);return this}
2649,T.prototype.divide=function(e){let t=this.coeff.divide(e.coeff),n=this.terms.length,r=new T(t,[],this.map);for(let t=0;t<n;t++)r.terms[t]=this.terms[t].subtract(e.terms[t]),r.sum=r.sum.add(r.terms[t]);return r},T.prototype.multiply=function(e){let t=this.coeff.multiply(e.coeff),n=this.terms.length,r=new T(t,[],this.map);for(let t=0;t<n;t++)r.terms[t]=this.terms[t].add(e.terms[t]),r.sum=r.sum.add(r.terms[t]);return r},T.prototype.isZero=function(){return this.coeff.equals(0)},T.prototype.toString=function(){return`{ coeff: ${this.coeff.toString()}, terms: [${this.terms.join(`,`)}]: sum: ${this.sum.toString()}, count: ${this.count}}`},e.Utils.toMapObj=function(e){let t=0,n={length:0};for(let r=0;r<e.length;r++){let i=e[r];typeof n[i]>`u`&&(n[i]=t,t++)}return n.length=t,n},e.Utils.filledArray=function(e,t,n){let r=[];for(;t--;)r[t]=n?new n(e):e;return r},e.Utils.arrSum=function(e){let t=0,n=e.length;for(let r=0;r<n;r++)t+=e[r];return t},e.Utils.haveIntersection=function(e,t){return t.length>e.length&&([e,t]=[t,e]),e.some(e=>t.indexOf(e)>-1)},e.Utils.subFunctions=function(t,n){n||={};let r=[],i=new Set(p(t));return t.each(t=>{if(t.group===s||t.previousGroup===s){let a=e.Utils.text(t,`hash`),o=n[a];if(o)r.push(t.altVar(o));else{let e=0,o;do o=t.fname+d(n).length+(e>0?String(e):``),e++;while(i.has(o));n[a]=o,r.push(t.altVar(o))}}else t.group===u||t.group===c||t.group===l?r.push(e.Utils.subFunctions(t,n)):r.push(t.text())}),t.group===l||t.group===c?t.altVar(e.Utils.inBrackets(r.join(`+`))):t.group===u?t.altVar(e.Utils.inBrackets(r.join(`*`))):t.text()},e.Utils.getFunctionsSubs=function(e){let n={};for(let r in e)Object.hasOwn(e,r)&&(n[e[r]]=t.parse(r));return n};let E=e.Algebra={version:`1.4.6`,proots(n,r){r||=7;let i=[],o=function(e,t,n){let r=s(e,t,n).concat(i);for(let e=0;e<0;e++)r.unshift(0);return r};if(e.Utils.isSymbol(n)&&n.isPoly()){let r=n;if(r.distributeMultiplier(),r.group===c){let n=e.Utils.arrayMin(d(r.symbols)),a=r.symbols[n].clone().toUnitMultiplier();r=t.expand(t.divide(r,a)),i.push(0)}if(r.group===e.groups.S)return[`0`];if(r.group===e.groups.PL){let t=d(r.symbols),n=e.Utils.arrayMin(t);r=e.PARSER.divide(r,e.PARSER.parse(`${r.value}^${n}`))}let s=d(r.symbols).sort().pop(),l=r.group===e.groups.PL?r.symbols:r.symbols[s||``],u=l.group,f=u===a?[l.power.toDecimal()]:d(l.symbols),p=[],m=e.Utils.arrayMax(f);for(let e=1;e<=m;e++){let t=0;f.indexOf(`${e}`)!==-1&&(t=u===a?l.multiplier:l.symbols[e].multiplier),p.unshift(t)}return p.push(n.symbols[x].multiplier),r.group===a&&(p[0]=r.multiplier),o(p,f,m)}if(e.Utils.isArray(n)){let e=n,t=[],r=[],i=0;for(let n=0;n<e.length;n++){let a=e[n][0],o=e[n][1],s=o-i-1;for(let e=0;e<s;e++)t.unshift(0);t.unshift(a),o!==0&&r.push(o),i=o}return o(t,r,Math.max.apply(void 0,r))}throw new e.exceptions.NerdamerTypeError(`Cannot calculate roots. NerdamerSymbol must be a polynomial!`);function s(t,n,i){let a,o=t.slice(0);if(t.unshift(i),i>100)throw new e.exceptions.ValueLimitExceededError(`This utility accepts polynomials of degree up to 100. `);let s=[],c={};for(c.Degree=i,a=0;a<i;a++)s.push(0);let l=s.slice(0);function u(e,t,n,r,i,a){i[0]=a.b=r[0],i[1]=a.a=-(t*a.b)+r[1];for(let o=2;o<e;o++)i[o]=-(t*a.a+n*a.b)+r[o],a.b=a.a,a.a=i[o]}function d(e,t,n,r,i,a,o,s,c){let l={},d=3;return l.b=l.a=0,u(t,o,s,a,c,l),i.c=l.a,i.d=l.b,Math.abs(i.c)<=100*e*Math.abs(a[t-1])&&Math.abs(i.d)<=100*e*Math.abs(a[t-2])||(i.h=s*r,Math.abs(i.d)>=Math.abs(i.c)?(d=2,i.e=n/i.d,i.f=i.c/i.d,i.g=o*r,i.a3=i.e*(i.g+n)+i.h*(r/i.d),i.a1=-n+i.f*r,i.a7=i.h+(i.f+o)*n):(d=1,i.e=n/i.c,i.f=i.d/i.c,i.g=i.e*o,i.a3=i.e*n+(i.g+i.h/i.c)*r,i.a1=-(n*(i.d/i.c))+r,i.a7=i.g*i.d+i.h*i.f+n)),d}function f(e,t,n,r,i,a,o,s,c){if(n===3){o[1]=o[0]=0;for(let e=2;e<t;e++)o[e]=s[e-2];return}let l=n===1?i:r;if(Math.abs(a.a1)>10*e*Math.abs(l)){a.a7/=a.a1,a.a3/=a.a1,o[0]=c[0],o[1]=-(c[0]*a.a7)+c[1];for(let e=2;e<t;e++)o[e]=-(c[e-1]*a.a7)+s[e-2]*a.a3+c[e]}else{o[0]=0,o[1]=-(c[0]*a.a7);for(let e=2;e<t;e++)o[e]=-(c[e-1]*a.a7)+s[e-2]*a.a3}}function p(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g){let _,v,y,b,x,S,C,w,T;t.b=t.a=0,e===3||(e===2?(_=(n+u)*l+d,v=(l+f)*s+p*c):(_=n+f*o+d*l,v=s+(f+p*l)*c),y=-(m[h-1]/g[h]),b=-(m[h-2]+y*g[h-1])/g[h],x=p*b*r,S=y*a,C=y*y*i,w=-(S+C)+x,T=-w+v+y*_,T!==0&&(t.a=-((f*(C+S)+p*(y*r+b*a))/T)+f,t.b=p*(1+w/T)))}function m(e,t,n,r){let i,a;if(r.sr=r.si=r.lr=r.li=0,e===0){r.sr=t===0?r.sr:-(n/t);return}if(n===0){r.lr=-(t/e);return}let o=t/2;Math.abs(o)<Math.abs(n)?(a=n>
2649=0?e:-e,a=-a+o/Math.abs(n)*o,i=Math.sqrt(Math.abs(a))*Math.sqrt(Math.abs(n))):(a=-(e/o*(n/o))+1,i=Math.sqrt(Math.abs(a))*Math.abs(o)),a>=0?(i=o>=0?-i:i,r.lr=(-o+i)/e,r.sr=r.lr===0?r.sr:n/r.lr/e):(r.lr=r.sr=-(o/e),r.si=Math.abs(i/e),r.li=-r.si)}function g(e,t,n,r,i,a,o,s,c,l,h,g){let _={},v,y,b,x=0,S,C,w,T,E,D,O,k=0,A,j=0;n.NZ=0,C=r,T=i;do{if(_.li=_.lr=_.si=_.sr=0,m(1,C,T,_),n.szr=_.sr,n.szi=_.si,n.lzr=_.lr,n.lzi=_.li,Math.abs(Math.abs(n.szr)-Math.abs(n.lzr))>.01*Math.abs(n.lzr))break;for(u(o,C,T,c,a,s),y=Math.abs(-(n.szr*s.b)+s.a)+Math.abs(n.szi*s.b),D=Math.sqrt(Math.abs(T)),v=2*Math.abs(a[0]),S=-(n.szr*s.b),O=1;O<t;O++)v=v*D+Math.abs(a[O]);if(v=v*D+Math.abs(S+s.a),v=(9*v+2*Math.abs(S)-7*(Math.abs(s.a+S)+D*Math.abs(s.b)))*e,y<=20*v){n.NZ=2;break}if(k++,k>20)break;if(k>=2&&x<=.01&&y>=b&&!j){for(x=Math.sqrt(x<e?e:x),C-=C*x,T+=T*x,u(o,C,T,c,a,s),O=0;O<5;O++)A=d(e,t,s.a,s.b,h,g,C,T,l),f(e,t,A,s.a,s.b,h,g,l,a);j=1,k=0}b=y,A=d(e,t,s.a,s.b,h,g,C,T,l),f(e,t,A,s.a,s.b,h,g,l,a),A=d(e,t,s.a,s.b,h,g,C,T,l),p(A,s,s.a,h.a1,h.a3,h.a7,s.b,h.c,h.d,h.f,h.g,h.h,C,T,g,t,c),w=s.a,E=s.b,E!==0&&(x=Math.abs((-T+E)/E),C=w,T=E)}while(E!==0)}function _(e,t,n,r,i,a,o,s,c){let l,u,d,f,p,m,h,g,_,v,y,b=r-1;for(t.NZ=y=_=0,h=n.a;;){for(m=i[0],o[0]=m,v=1;v<a;v++)o[v]=m=m*h+i[v];for(d=Math.abs(m),f=Math.abs(h),l=.5*Math.abs(o[0]),v=1;v<a;v++)l=l*f+Math.abs(o[v]);if(d<=20*e*(2*l-d)){t.NZ=1,t.szr=h,t.szi=0;break}if(y++,y>10)break;if(y>=2&&Math.abs(g)<=.001*Math.abs(-g+h)&&d>p){_=1,t.a=h;break}for(p=d,c[0]=u=s[0],v=1;v<r;v++)c[v]=u=u*h+s[v];if(Math.abs(u)>Math.abs(s[b])*10*e)for(g=-(m/u),s[0]=o[0],v=1;v<r;v++)s[v]=g*c[v-1]+o[v];else for(s[0]=0,v=1;v<r;v++)s[v]=c[v-1];for(u=s[0],v=1;v<r;v++)u=u*h+s[v];g=Math.abs(u)>Math.abs(s[b])*10*e?-(m/u):0,h+=g}return _}function v(e,t,n,r,i,a,o,s,c,l,m,h){let v={},y={},b=Array(t),x=Array(t),S,C,w,T,E,D,O,k,A,j,M,N,P,F,I,L,ee,R,te,z=1,ne,B,V,H,re,ie;for(h.NZ=0,T=w=.25,E=r,k=i,v.b=v.a=0,u(c,m,i,s,l,v),S=v.a,C=v.b,y.h=y.g=y.f=y.e=y.d=y.c=y.a7=y.a3=y.a1=0,H=d(e,o,S,C,y,a,m,i,b),ne=0;ne<n;ne++){if(R=1,f(e,o,H,S,C,y,a,b,l),H=d(e,o,S,C,y,a,m,i,b),p(H,v,S,y.a1,y.a3,y.a7,C,y.c,y.d,y.f,y.g,y.h,m,i,a,o,s),I=v.a,ee=L=v.b,j=a[o-1]===0?0:-(s[o]/a[o-1]),M=P=1,ne!==0&&H!==3&&(P=ee===0?P:Math.abs((ee-k)/ee),M=j===0?M:Math.abs((j-E)/j),F=P<O?P*O:1,N=M<D?M*D:1,re=+(F<T),B=+(N<w),B||re)){for(te=0;te<o;te++)x[te]=a[te];for(A=j,V=ie=0;;){if(!(R&&(R=0)==0&&B&&(!re||N<F))){if(g(e,o,h,I,L,l,c,v,s,b,y,a),S=v.a,C=v.b,h.NZ>0)return;if(z=ie=1,T*=.25,V||!B)z=0;else for(te=0;te<o;te++)a[te]=x[te]}if(z!==0){if(v.a=A,z=_(e,h,v,o,s,c,l,a,b),A=v.a,h.NZ>0)return;if(V=1,w*=.25,z!==0){I=-(A+A),L=A*A;continue}}for(te=0;te<o;te++)a[te]=x[te];if(!re||ie)break}u(c,m,i,s,l,v),S=v.a,C=v.b,H=d(e,o,S,C,y,a,m,i,b)}k=ee,E=j,O=P,D=M}}function y(e,t,n,r){let i=e.Degree,o=Math.PI/180,s=Math.LN2,c=e.Degree+1,l=Array(c),u=Array(c),d=Array(c),f=Array(c),p={},h={},g,_,y,b,x,S,C,w,T,E,D,O,k,A,j,M,N,P,F,I,L,ee,R,te;O=1;do _=O,O/=2,k=1+O;while(k>1);let z=Number.MIN_VALUE/_,ne=Math.cos(94*o),B=Math.sin(94*o),V=Math.sqrt(.5),H=-V;for(h.NZ=F=0,h.szr=h.szi=h.lzr=h.lzi=0;t[i]===0;)n[F]=r[F]=0,i--,F++;for(R=i+1;i>=1;){if(i<=2){i<2?(n[e.Degree-1]=-(t[1]/t[0]),r[e.Degree-1]=0):(p.li=p.lr=p.si=p.sr=0,m(t[0],t[1],t[2],p),n[e.Degree-2]=p.sr,r[e.Degree-2]=p.si,n[e.Degree-1]=p.lr,r[e.Degree-1]=p.li);break}for(C=0,w=Number.MAX_VALUE,a=0;a<R;a++)E=Math.abs(t[a]),E>C&&(C=E),E!==0&&E<w&&(w=E);if(T=z/w,(T<=1&&C>=10||T>1&&Number.MAX_VALUE/T>=C)&&(T=T===0?Number.MIN_VALUE:T,L=Math.floor(Math.log(T)/s+.5),x=2**L,x!==1))for(a=0;a<R;a++)t[a]*=x;for(let e=0;e<R;e++)u[e]=Math.abs(t[e]);u[i]=-u[i],ee=i-1,E=Math.exp((Math.log(-u[i])-Math.log(u[0]))/i),u[ee]!==0&&(D=-u[i]/u[ee],E=D<E?D:E),D=E;do{E=D,D=.1*E,S=u[0];for(let e=1;e<R;e++)S=S*D+u[e]}while(S>0);b=E;do{y=S=u[0];for(let e=1;e<i;e++)S=E*S+u[e],y=E*y+S;S=E*S+u[i],b=S/y,E-=b}while(Math.abs(b/E)>.005);g=E;for(let e=1;e<i;e++)l[e]=(i-e)*t[e]/i;for(l[0]=t[0],O=t[i],k=t[ee],te=+(l[ee]===0),I=0;I<5;I++)if(A=l[ee],te){for(let e=0;e<ee;e++)F=ee-e,l[F]=l[F-1];l[0]=0,te=+(l[ee]===0)}else{M=-O/A;for(let e=0;e<ee;e++)F=ee-e,l[F]=M*l[F-1]+t[F];l[0]=t[0],te=+(Math.abs(l[ee])<=Math.abs(k)*_*10)}for(let e=0;e<i;e++)f[e]=l[e];for(I=1;I<=20;I++)if(P=-(B*H)+ne*V,H=B*V+ne*H,V=P,j=g*V,N=-(2*j),v(_,c,20*I,j,g,l,i,t,R,d,N,h),h.NZ===0)for(let e=0;e<i;e++)l[e]=f[e];else{F=e.Degree-i,n[F]=h.szr,r[F]=h.szi,R-=h.NZ,i=R-1;for(let e=0;e<R;e++)t[e]=d[e];h.NZ===1||(n[F+1]=h.lzr,r[F+1]=h.lzi);break}if(I>20){e.Degree-=i;break}}}y(c,o,l,s);let b=s.length,x=[];for(a=0;a<b;a++){let e=h(s[a],r+8),t=h(Number(l[a]),r+8);t=r-String(t).length>2?t:Number(l[a]);let n=Number(e)<0?`-`:``,i=t,o=e;t===0&&(i=``),e===0&&(o=``),o=Math.abs(Number(e))===1?`${n}i`:e?`${e}*i`:``,x[a]=(i&&o?`${i}+${o}`:String(i)+String(o)).replace(/\+-/gu,`-`)}return x}},roots(n){if(n.isConstant(!0,!0))return e.Utils.nroots(n);let r=E.proots(n).map(e=>t.parse(e));return e.Vector.fromArray(r)},froot(t,n,r){return function(n){let i=r||e.Build.build(e.Calculus.diff(t.clone())),a=t instanceof Function?t:e.Build.build(t),o=!1,s=0;for(;!o;){let e=n-a(n)/i(n),t=Math.abs(e)-Math.abs(n),r=Math.abs(t);n=e,r<1e-12?o=!0:s>1e4&&(n=null,o=!0),s++}return n}(Number(n))},quad(e,n,r){let i=function(e,n,r,i){return t.parse(`-(${n}+${i}*sqrt((${n})^2-4*(${e})*(${r})))/(2*${e})`)};return[i(e,n,r,1),i(e,n,r,-1)]},sumProd(e,t){return E.quad(String(-t),String(e),`-1`).map(e=>e.invert())},coeffs(n,r,i){n=t.expand(n),i||=[new v(0)];let a=p(n);
2649r===void 0&&a.length===1&&(r=a[0]),r=String(r),n.group===o&&n.contains(r,!0)&&t.error(`Unable to get coefficients using expression ${n.toString()}`),a=p(n);let s=n.contains(`pi`)||n.contains(`e`)||n.containsFunction(`sqrt`);if(a.length===1&&a[0]===r&&!n.isImaginary()&&!s){let e=new C(n).coeffs.map(e=>new v(e));for(let n=0,r=e.length;n<r;n++){let r=e[n],a=i[n];a&&(r=t.add(a,r)),i[n]=r}}else if(a.length===1&&a[0]===r&&!n.isImaginary()&&s&&n.group===l){let a=e.Utils.getCoeffs(n,r);for(let e=0,n=a.length;e<n;e++){let n=a[e],r=i[e];r&&(n=t.add(r,n)),i[e]=n}}else if(r||t.error(`Polynomial contains more than one variable. Please specify which variable is to be used!`),a.indexOf(r)===-1)i[0]=t.add(n,i[0]);else{i||=[new v(0)];let e;if(n.group===u){let a=n.symbols[r];a||t.error(`Expression is not a polynomial!`);let o=Number(a.power);e=t.divide(n.clone(),a.clone()),(e.contains(r,!0)||o<0||!g(o))&&t.error(`Expression is not a polynomial!`);let s=i[o];s&&(e=t.add(s,e)),i[o]=e}else n.group===l&&n.each(e=>{E.coeffs(e.clone(),r,i)},!0)}for(let e=0,t=i.length;e<t;e++)typeof i[e]>`u`&&(i[e]=new v(0));return i},polyPowers(t,n,i){i||=[];let o=t.group;if(o===c&&n===t.value)i=i.concat(d(t.symbols));else if(o===l)for(let e in t.symbols){if(!Object.hasOwn(t.symbols,e))continue;let o=t.symbols[e],s=o.group,d=o.value;if(s===a&&n===d)i.push(o.power);else if(s===c||s===l)i=E.polyPowers(o,n,i);else if(s===u&&o.contains(n)){let e=o.symbols[n];e&&i.push(e.power)}else (s===r||n!==d)&&i.push(0)}else if(o===u&&t.contains(n)){let r=e.Utils.decompose_fn(t,n,!0);i.push(r.x.power)}return e.Utils.arrayUnique(i).sort()},Factor:{split(e){let n=new v(1),r=new v(1);return E.Factor.factorInner(e,new w).each(e=>{let i=t.parse(e);e.isConstant(!0)?n=t.multiply(n,i):r=t.multiply(r,i)}),[n,r]},mix(e,t){let n=d(e),r=n.length,i=[];for(let a=0;a<r;a++){let r=Number(n[a]),o=e[n[a]],s=i.length;for(let e=0;e<s;e++){let n=i[e]*r;i.push(n),t&&i.push(-n)}for(let e=1;e<=o;e++)i.push(r**e)}return i},common(n,r){try{if(n.group===l){let i=t.expand(n.clone(),{expand_denominator:!0}),a=e=>e.length||1,o=i.collectSymbols(null,null,(e,t)=>a(t)-a(e)),s={},c=[];for(let e=0;e<o.length;e++){let t=o[e];c.push(t.multiplier.clone()),t.each(e=>{let t=Number(e.power);if(isNaN(t))throw Error(`exiting`);e.value in s?(t<s[e.value][0]&&(s[e.value][0]=t),s[e.value][1].push(e)):s[e.value]=[t,[e]]})}let l=new v(1);for(let e in s)s[e][1].length===o.length&&(l=t.multiply(l,t.pow(new v(e),new v(s[e][0]))));let u=e.Math2.QGCD.apply(null,c);if(!u.equals(1)){r.add(new v(u));for(let e=0;e<o.length;e++)o[e].multiplier=o[e].multiplier.divide(u)}if(!l.equals(1)){r.add(l),n=new v(0);for(let e=0;e<o.length;e++)n=t.add(n,t.divide(o[e],l.clone()))}}}catch(e){if(e.message===`timeout`)throw e}return n},zeroes(n,r){let i=function(){throw new e.exceptions.ValueLimitExceededError(`Exiting`)};try{let a,o,s;n=t.expand(n.clone());let c=n.toString(),u=p(n);o=new v(0);let d=[],f=[];for(let e=0,n=u.length;e<u.length;e++){let r={};for(let t=0;t<n;t++)e!==t&&(r[u[t]]=0);a=t.parse(c,r);let o=a.power;g(o)||i(),d.push(a),f.push(a.power)}if(e.Utils.allSame(f)){let t=n.length,r=d.length,i=Math.round((Math.sqrt(8*t-1)-3)/2);s=r===2?new _(Number(f[0])/(t-1)):r===3&&i!==0?new _(Number(f[0])/i):e.Math2.QGCD.apply(null,f)}else s=e.Math2.QGCD.apply(null,f);if(!g(s))return n;for(let e=0;e<d.length;e++){let r=d[e],i=r.power.clone().divide(s),a=Number(i);if((Number(r.multiplier.num)<0||Number(r.multiplier.den)<0)&&a%2==0)return n;r.multiplier=new _(Number(r.multiplier)**(1/a)),r.power=s.clone(),o=t.add(o,r)}if(o.group!==l)return n;for(;;){let e=E.div(n.clone(),o.clone());if(e[1].equals(0)){if(n=e[0],r.add(o.clone()),n.equals(1))break}else break}}catch(e){if(e.message===`timeout`)throw e}return n},factor(t,n){e.Utils.checkTimeout();let r=n?{...n.factors}:null,i=n?n.length:0;try{let e=E.Factor.factorInner(t,n);return e=e.pushMinus(),e}catch(e){if(e.message===`timeout`)throw e;return n&&r&&(n.factors=r,n.length=i),t}},factorInner(n,r){if(e.Utils.checkTimeout(),n.isConstant()&&n.isInteger())return e.Math2.factor(Number(n.multiplier));let i=t.parse(n);if(i.isConstant())return i.isInteger()?e.Math2.factor(Number(i.multiplier)):n;
2649if(i.equals(0)||i.equals(1))return i;let a=E.Factor._factor(i,r);if(a.equals(n)||a.equals(0)||a.equals(1))return a;if(a.group===u){let e=new v(1),n=t.parse(a.power),r=t.parse(a.multiplier);a.toUnitMultiplier(),a.multiplier.lessThan(0)&&(e.negate(),a.negate()),a.each(n=>{let i=t.parse(E.Factor._factor(n));if(r=t.multiply(r,v.create(i.multiplier.toString())),i.toUnitMultiplier(),i.group===u){let n=new v(1);i.each(e=>{let i=t.parse(E.Factor._factor(e));i.group===u&&(r=t.multiply(r,v.create(i.multiplier.toString())),i.toUnitMultiplier()),n=t.multiply(n,i)}),n=t.pow(n,new v(i.power.toString())),e=t.multiply(e,n)}else e=t.multiply(e,i)});let i=t.pow(e,n);a=t.multiply(r,i)}return a},quadFactor(n,r){if(n.isPoly()&&E.degree(n).equals(2)){let i=e.Utils.variables(n)[0],a=E.coeffs(n,i);if(a.length<3)return n;let o=E.Factor._factor(a[2].clone());if(o.group===u){let s=o.collectSymbols();if(s.length>2)return n;let c=t.multiply(t.parse(a[0]),t.parse(s[0])),l=t.parse(a[1]).negate(),u=t.parse(s[1]),d=E.quad(u,l,c).filter(t=>e.Utils.isInt(t));if(d.length===1){let o=d[0],c=t.divide(a[0],t.parse(o));e.Utils.isInt(c)&&(r.add(t.parse(m(`({0})*({1})+({2})`,String(s[1]),i,String(c)))),r.add(t.parse(m(`({0})*({1})+({2})`,String(s[0]),i,o))),n=new v(1))}}}return n},cubeFactor(e,n){if(e.isComposite()){let r=e.collectSymbols();if(r.length===2){let i=r[0].sign(),a=r[0].clone().abs(),o=r[1].sign(),s=r[1].clone().abs();if(a.isCube()&&s.isCube()){i<o&&([i,o]=[o,i],[a,s]=[s,a]);let r=t.parse(a.getNth(3)),c=t.parse(s.getNth(3)),l=t.multiply(t.expand(t.pow(a.clone().toUnitMultiplier(),t.parse(`1/3`))),r),u=t.multiply(t.expand(t.pow(s.clone().toUnitMultiplier(),t.parse(`1/3`))),c);i===1&&o===-1?(n.add(t.parse(m(`(({0})-({1}))`,String(l),String(u)))),n.add(t.parse(m(`(({0})^2+({0})*({1})+({1})^2)`,String(l),String(u)))),e=new v(1)):i===1&&o===1&&(n.add(t.parse(m(`(({0})+({1}))`,String(l),String(u)))),n.add(t.parse(m(`(({0})^2-({0})*({1})+({1})^2)`,String(l),String(u)))),e=new v(1))}}}return e},_factor(n,r){if(e.Utils.checkTimeout(),n.group,n.group===s){let e=n.args[0];if(e.group===a&&e.isSimple())return n}else if(n.group===a&&n.isSimple())return n;if(n.group===l){n.distributeMultiplier(!0);let e=new v(0);n.each(n=>{(n.group===l&&n.power.greaterThan(1)||n.group===u)&&(n=t.expand(n)),e=t.add(e,n)}),e.power=n.power,n=e}n.group===s&&n.fname!==`sqrt`&&(n=e.Utils.evaluate(n));let i=n.clone();try{if(n.group===u){t.parse(n.power);let e=E.Simplify.strip(n.getDenom()),r=E.Simplify.strip(n.getNum()),i=e.pop(),a=r.pop();if(a.equals(n))return n;let o=E.Factor.factorInner(a),s=E.Factor.factorInner(i),c=E.Simplify.unstrip(r,o),l=E.Simplify.unstrip(e,s);return t.divide(c,l)}if(n.group===a)return n;if(n.isConstant())return n.equals(1)||n.equals(0)||!n.isInteger()?n.clone():e.Math2.factor(Number(n.multiplier));let o=n.power.clone();if(g(o)&&!(o.lessThan(0)&&n.group===s)){let s=o.sign();n.toLinear(),r||=new w;let c={};n=t.parse(e.Utils.subFunctions(n,c)),d(c).length>0&&(r.preAdd=function(n){return t.parse(n,e.Utils.getFunctionsSubs(c))}),n.isLinear()||(r.pFactor=n.power.toString(),n.toLinear());let l=p(n);n.isImaginary()&&l.push(e.Settings.IMAGINARY);let u=l.length>1;if(u){let r=!0,i=!0;if(n.each(e=>{e.group!==a&&(r=!1),e.multiplier.equals(1)||(i=!1)}),r&&i)return t.pow(t.parse(n,e.Utils.getFunctionsSubs(c)),t.parse(o))}let m=new w;n=E.Factor.coeffFactor(n,m),m.each(e=>{f(Number(o))&&e.lessThan(0)&&e.negate(),s<0&&e.invert(),r.add(e)});let h=new w;if(n=E.Factor.powerFactor(n,h),h.each(e=>{s<0&&e.invert(),r.add(e)}),u)n=E.Factor.cubeFactor(n,r),n=E.Factor.mfactor(n,r),r.each(e=>{s<0&&e.power.negate()});else{let e=l[0];n=E.Factor.squareFree(n,r,e);let a=new w;n=E.Factor.trialAndError(n,a,e);let s=a.toSymbol();if(s.equals(i))return s;for(let e in a.factors){if(!Object.hasOwn(a.factors,e))continue;let n=a.factors[e];r.add(t.pow(n,t.parse(o)))}n.equals(i)&&(n=E.Factor.quadFactor(n,r))}n=t.parse(n,e.Utils.getFunctionsSubs(c));let g=r.length===1;r.add(t.pow(n,t.parse(o)));let _=r.toSymbol();return g&&n.equals(1)&&_.isLinear()&&(_=t.pow(_,t.parse(o))),_}return n}catch(e){if(e?.message===`timeout`)throw e;return i}},reduce(e,n){if(e.group===l&&e.length===2){let r=e.collectSymbols().sort((e,t)=>
2649Number(t.multiplier)-Number(e.multiplier));if(r[0].power.equals(r[1].power)){let e=t.parse(r[0].power),i=r[0].clone().toLinear(),a=r[1].clone().toLinear();n.add(t.add(i.clone(),a.clone())),a.negate();let o=Number(e),s=new v(0);for(let n=1;n<=o;n++){let r=t.pow(i.clone(),t.subtract(e.clone(),new v(n))),o=t.pow(a.clone(),t.subtract(new v(n),new v(1)));s=t.add(s,t.multiply(r,o))}return s}}return e},squareFree(e,t,n){if(e.isConstant()||e.group===a||!e.isPoly())return e;let r=new C(e,n).squareFree(),i=r[2];if(i!==1){let e=r[1].toSymbol();return e.power=e.power.multiply(new _(i)),t.add(E.Factor.factorInner(e)),E.Factor.squareFree(r[0].toSymbol(),t)}return e},powerFactor(n,r){if(n.group!==c||n.previousGroup===o)return n;let i=d(n.symbols);if(!e.Utils.allNumeric(i))return n;let a=e.Utils.arrayMin(i),s=new v(0),l=t.parse(`${n.value}^${a}`);return n.each(e=>{e=t.divide(e,l.clone()),s=t.add(s,e)}),r.add(l),s},coeffFactor(t,n){if(t.isComposite()){let r=e.Math2.QGCD.apply(null,t.coeffs());if(r.equals(1)){let e=function(e){let t;return e.group===u?(t=0,e.each(e=>{t+=e.power})):t=Number(e.power),t},r=t.collectSymbols(null,null,null,!0).sort((e,t)=>e.isConstant(!0)?1:Number(t.power)-Number(e.power)),i=r[0];(e(i)>e(r[1])||r[1].isConstant(!0))&&i.multiplier.lessThan(0)&&(n.add(new v(-1)),t.each(e=>{e.negate()},!0))}else t.each(e=>{e.isComposite()?e.each(e=>{e.multiplier=e.multiplier.divide(r)}):e.multiplier=e.multiplier.divide(r)}),t.updateHash();n&&n.add(new v(r))}return t},trialAndError(t,n,r){let i=t.clone();try{let i=[];if(t.isConstant()||t.group===a||!t.isPoly())return t;let o=new C(t,r),s=o.coeffs[0],c=e.Math2.ifactor(Number(s)),l=E.proots(t);for(let t=0;t<l.length;t++){let n=l[t],r=1;if(!isNaN(Number(n))){for(let t in c){if(!Object.hasOwn(c,t))continue;let i=e.Utils.round(Math.log(Number(t))/Math.log(Math.abs(Number(n))),8);if(g(i)){n=t,r=Number(i);break}}let t=new _(Number(n)),a=[new _(Number(t.num)).negate()];a[r]=new _(Number(t.den));let s=C.fromArray(a,o.variable).fill(),l=o.divide(s);l[1].equalsNumber(0)&&(o=l[0],i.push(s.toSymbol()))}}return o.equalsNumber(1)||(o=E.Factor.search(o,n)),i.forEach(e=>{n.add(e)}),o.toSymbol()}catch(e){if(e.message===`timeout`)throw e;return i}},search(t,n,r){r||=10;let i=t.variable,a=function(e,a,o,s){let c=C.fit(e,a,o,r,s,i);if(c&&c.coeffs.length>1){let e=t.divide(c);if(e[1].equalsNumber(0))return n.add(c.toSymbol()),[e[0],c]}return null},o=t.coeffs[0],s=e.Math2.ifactor(Number(o)),c=t.lc(),l=e.Math2.ifactor(Number(c)),u=t.sub(r),d=e.Math2.ifactor(u),f=E.Factor.mix(d,u<0),p=Math.ceil(t.coeffs.length/2),m=c.lessThan(0),h=o.lessThan(0);for(l[1]=1,s[1]=1;p--;)for(let i in l)if(Object.hasOwn(l,i)){for(let o in s)if(Object.hasOwn(s,o))for(let s=0;s<f.length;s++){let c=a(Number(i),Number(o),f[s],p);if(c)return t=c[0],e.Utils.isPrime(t.sub(r))||(t=E.Factor.search(t,n)),t;c||(m&&h?c=a(-Number(i),-Number(o),f[s],p):m?c=a(-Number(i),Number(o),f[s],p):h&&(c=a(Number(i),-Number(o),f[s],p)))}}return t},mSqfrFactor(t,n){if(t.group!==s){let r=p(t).reverse();for(let i=0;i<r.length;i++){let a=!1;do{if(r[i]===t.value){n.add(t),t=new v(1);continue}let o=e.Calculus.diff(t,r[i]),s=E.Factor.coeffFactor(o);if(s.equals(0)||s.equals(1)||s.equals(-1))break;let c=!0;s.isConstant()&&t.isComposite()&&t.each(e=>{Number(e.multiplier)%Number(s.multiplier)!==0&&(c=!1)},!0);let l;if(c){let e=t.clone();if(l=E.divWithCheck(t,s.clone()),a=l[1].equals(0),t.equals(l[0])&&l[1].equals(0)){t=e;break}if(l[0].isConstant()){n.add(l[0]);break}}else a=!1;a&&(n.add(l[0]),t=s)}while(a)}}return t},sqdiff(n,r){if(n.isConstant(`all`))return n;try{let i=function(t){return e.Utils.block(`POSITIVE_MULTIPLIERS`,()=>v.unwrapPARENS(S.sqrt(S.abs(t))),!0)},o=e.Utils.separate(n.clone());if(!o)return n;let s=[];for(let e in o)e!==`constants`&&s.push(o[e]);if(s.sort((e,t)=>Number(t.power)-Number(e.power)),s.length===2){let e,c;if(e=s.pop(),c=s.pop(),f(Number(e.power))&&f(Number(c.power))&&e.sign()===c.sign()&&e.group===a&&c.group===a)throw Error(`Unable to factor`);if(e.isComposite()&&c.power.equals(2)&&e.sign()!==c.sign()){c=i(c);let a=E.Factor.factorInner(t.add(e,o.constants));a.power.equals(2)&&(a.toLinear(),r.add(t.subtract(a.clone(),c.clone())),r.add(t.add(a,c)),n=new v(1))}else if(e=e.powSimp(),c=c.powSimp(),(e.group===a||e.fname===``)&&e.power.equals(2)&&(c.group===a||c.fname===``)&&c.power.equals(2)&&!o.constants){if(e.multiplier.lessThan(0)){let t=c;c=e,e=t}e.multiplier.greaterThan(0)&&(e=i(e),c=i(c)),r.add(t.subtract(e.clone(),c.clone())),r.add(t.add(e,c)),n=new v(1)}}}catch(e){if(e.message===`timeout`)throw e}return n},mfactor(n,r){if(n.group===s)if(n.fname===`sqrt`){let r=new w,i=E.Factor.common(n.args[0].clone(),r);i=E.Factor.coeffFactor(i,null),n=t.multiply(t.symfunction(`sqrt`,[i]),t.parse(n.multiplier)),r.each(r=>{n=t.multiply(n,t.parse(e.Utils.format(`sqrt({0})`,String(r))))})}else r.add(n),n=new v(1);else{n=E.Factor.mSqfrFactor(n,r);let e=p(n),i=n.collectSymbols().map(e=>v.unwrapSQRT(e)),a={},o={},s=e.length,c=i.length;for(let n=0;n<s;n++){let r=e[n];a[r]=new v(0);for(let e=0;e<c;e++){let n=i[e];if(n.contains(r)){let e=n.value===r?n.power.toDecimal():n.symbols[r].power.toDecimal();(!o[r]||e<o[r])&&(o[r]=e),a[r]=t.add(a[r],n.clone())}}}for(let e in a){if(!Object.hasOwn(a,e))continue;let i=t.parse(`${e}^${o[e]}`),s=t.divide(a[e],i),c=t.expand(s);if(c.equals(1)||c.equals(-1))break;let l=E.div(n.clone(),c);if(l[0].equals(0))break;if(l[1].equals(0)){let e=!1;if(l[0].each(t=>{g(t.multiplier)||(e=!0)}),e){l[1]=t.expand(t.multiply(l[1],c));break}}let u=g(c)&&c.lessThan(0);if(l[1].equals(0)&&!u){let e=E.divWithCheck(n.clone(),l[0].clone()),t=e[0];if(t.equals(0)||(n=e[1],t.equals(-1)&&!n.equals(0)))return n;let i=l[0];if(n.equals(i)){let e=E.Factor.reduce(i,r);return n.equals(e)?e:E.Factor.mfactor(e,r)}return r.add(i),n.equals(0)?t:t.isConstant(`all`)?(r.add(t),t):(n=E.Factor.mfactor(t,r),n)}}}
2649return n=E.Factor.sqdiff(n,r),n=E.Factor.zeroes(n,r),n}},allLinear(e){let t=e.length;for(let n=0;n<t;n++)if(!E.isLinear(e[n]))return!1;return!0},isLinear(e){let t=!1,n=e.group;if(n===c||n===l){t=!0;for(let n in e.symbols){if(!Object.hasOwn(e.symbols,n))continue;let i=e.symbols[n],a=i.group;if((a===s||a===o)&&(t=!1),a===u)t=p(i).length===1;else if(a===c||a===l)t=E.isLinear(i);else if(i.group!==r&&i.power.toString()!==`1`){t=!1;break}}}else n===a&&e.power===1&&(t=!0);return t},gcd(...n){let r;if(r=n.length===1&&n[0]instanceof e.Vector?n[0].elements:n,r.length===0)return new v(1);if(r.length===1)return r[0];let i=[],a=!1;for(let t=0;t<r.length;t++){let n=r[t];if(n.group===s&&n.fname===`gcd`)r=r.concat(n.args),r.splice(t,1);else{let t=p(n);if(e.Utils.haveIntersection(t,i)){a=!0;break}else i=i.concat(t)}}if(a||i.length===0){if(r.every(e=>e.getDenom().equals(1))){let e=r[0];for(let t=1;t<r.length;t++)e=E.gcd_(r[t],e);return e}return t.divide(E.gcd.apply(null,r.map(e=>e.getNum())),E.lcm.apply(null,r.map(e=>e.getDenom())))}return t.symfunction(`gcd`,r)},gcd_(n,r){if((n.group===s||n.group===i)&&(n=e.Utils.block(`PARSE2NUMBER`,()=>t.parse(n))),(r.group===s||r.group===i)&&(r=e.Utils.block(`PARSE2NUMBER`,()=>t.parse(r))),r.group===s&&(r=e.Utils.block(`PARSE2NUMBER`,()=>t.parse(r))),n.isConstant()&&r.isConstant())return new v(e.Math2.QGCD(new _(Number(n)),new _(Number(r))));let a=t.multiply(n.getDenom()||new v(1),r.getDenom()||new v(1)).invert();if(n=t.multiply(n.clone(),a.clone()),r=t.multiply(r.clone(),a.clone()),n=t.expand(n),r=t.expand(r),n.group===u||r.group===u){let e=t.divide(n.clone(),r.clone()),i=t.multiply(r.clone(),e.getDenom().invert());if(!i.equals(1))return i}if(n.group===o||r.group===o){let i=new v(e.Math2.QGCD(n.multiplier,r.multiplier)),a=E.gcd_(n.value===x?new v(1):t.parse(n.value),r.value===x?new v(1):t.parse(r.value)),o=E.gcd_(t.parse(n.power),t.parse(r.power));return t.multiply(i,t.pow(a,o))}if(n.length<r.length){let e=n;n=r,r=e}let c=p(n),l=p(r);if(c.length===1&&l.length===0||c.length===0&&l.length===1){let t=c.length===1?n:r,i=c.length===0?n:r;return i.equals(0)?t:new v(e.Math2.QGCD(t.multiplier,i.multiplier))}if(c.length===l.length&&c.length===1&&c[0]===l[0]){let e=new C(n),i=new C(r);return t.divide(e.gcd(i).toSymbol(),a)}let d=[];n.each(e=>{d.push(e.multiplier)}),r.each(e=>{d.push(e.multiplier)});let f;for(;!r.equals(0);){let i=r.clone();if(n=n.clone(),f=E.div(n,i),r=f[1],f[0].equals(0))return t.divide(new v(e.Math2.QGCD(n.multiplier,r.multiplier)),a);n=i}let m=e.Math2.QGCD.apply(void 0,d);return m.equals(1)||n.each(e=>{e.multiplier=e.multiplier.divide(m)}),n.equals(1)&&!n.isConstant()&&!r.isConstant()?t.divide(t.symfunction(`gcd`,[n,r]),a):t.divide(n,a)},lcm(...n){let r;n.length===1?n[0]instanceof e.Vector?r=n[0].elements:t.error(`lcm expects either 1 vector or 2 or more arguments`):r=n;let i=r.reduce((e,n)=>t.multiply(e,n.clone()),new v(1)),a=(function(e,t){t=Number(t);let n=[],r,i,a,o=2**e.length;for(i=t;i<o;i++){r=[],a=e.length-1;do i&1<<a&&r.push(e[a]);while(a--);r.length===t&&n.push(r)}return n})(r,r.length-1).map(e=>e.reduce((e,n)=>t.multiply(e,n.clone()),new v(1))),o;return o=r.every(t=>e.Utils.isVariableSymbol(t))?t.symfunction(`gcd`,e.Utils.arrayUnique(a)):E.gcd.apply(null,a),t.divide(i,o)},divide(e,n){let r,i=E.Factor.factorInner(e.clone());r=i.getDenom(),r.isConstant(`all`)?r=new v(1):e=t.expand(v.unwrapPARENS(t.multiply(i,r.clone())));let a=E.div(e,n),o=t.divide(a[1],n);return t.divide(t.add(a[0],o),r)},divWithCheck(e,n){let r=[new v(0),e.clone()],i=E.div(e,n),a=e.clone(),o=t.multiply(i[0].clone(),n.clone());o=t.add(o,i[1].clone());let s=t.subtract(a,o);return s=t.expand(s),s.equals(0)?i:r},div(n,r){let i=[new v(0),n.clone()];try{if(r.isConstant(`all`))return n.each(e=>{e.multiplier=e.multiplier.divide(r.multiplier)}),[n,new v(0)];if(n=t.expand(n),r=t.expand(r),n.group===a&&r.group===l){let i=n.value,a=e.Utils.decompose_fn(r.clone(),i,!0);if(n.isLinear()&&a.x&&a.x.isLinear()&&r.isLinear()){let e=v.create(n.multiplier);return[t.divide(e.clone(),a.a.clone()),t.divide(t.multiply(e,a.b),a.a).negate()]}}if(n.group===a&&r.group===a){let e=t.divide(n.clone(),r.clone());return e.isConstant()?[e,new v(0)]:[new v(0),n.clone()]}let i=n.hasFunc(),o=r.hasFunc(),s=!1,c;if(i||o){s=!0;let i={};n=t.parse(e.Utils.subFunctions(n,i)),r=t.parse(e.Utils.subFunctions(r,i)),c=e.Utils.getFunctionsSubs(i)}let u=e.Utils.arrayUnique(p(n).concat(p(r))),d,f,m;if((n.isImaginary()||r.isImaginary())&&u.push(e.Settings.IMAGINARY),u.length===1){let e=new C(n).divide(new C(r));d=e[0].toSymbol(),f=e[1].toSymbol()}else{u.push(x);let i=function(e){let n=new v(0);for(let r=0;r<e.length;r++){let i=e[r].toSymbol();n=t.add(n,i)}return n}
2649,a=function(e,t){let n=Math.max.apply(null,e.terms),r=0,i;if(!t){for(let t=0;t<e.terms.length;t++)if(e.terms[t].equals(n)&&(i=t,r++),r>1)return}if(t){for(let t=0;t<e.terms.length;t++)if(e.terms[t].equals(n)){i=t;break}}return[n,i,e]},o=e.Utils.toMapObj(u),s=function(e,t){return t.sum.subtract(e.sum)},c=n.tBase(o).sort(s),l=r.tBase(o).sort(s),p=function(e,t){t||=0;let n=e[t],r=e.length;if(!n)return;let i=a(n);for(let o=t+1;o<r;o++){let t=e[o],r=n.sum.equals(t.sum);if(!r&&i)break;if(r){let e,r,a,o,s=n.terms.length;for(let i=0;i<s;i++){let s=n.terms[i],c=t.terms[i];(typeof e>`u`||s.greaterThan(e))&&(e=s,a=i),(typeof r>`u`||c.greaterThan(r))&&(r=c,o=i)}let c=e.subtract(t.terms[a]),l=r.subtract(n.terms[o]);if(l>c){i=[r,o,t];break}if(c>l){i=[e,a,n];break}}else if(i=a(t),i)break;i=a(t)}if(!i)return a(e[0],!0);let o,s;for(let e=0;e<l.length;e++){let t=l[e].terms;if(s=i[1],s===t.length-1)return;if(o=t[s],!o.equals(0))break}return o.equals(0)?p(e,++t):i},h=function(e,t){if(!e||!t)return!1;for(let n=0;n<e.terms.length;n++)if(e.terms[n].lessThan(t.terms[n]))return!1;return!0},g=p(h(c[0],l[0])&&c[0].count>l[0].count?l:c),y=[];if(g){let t=g[1],n=function(e,t){return e[0].sum.equals(t[0].sum)?e.length>=t.length:!0},r=function(e,t,n){let r=[];for(let t=0;t<e.length;t++){let n=e[t];for(let e=0;e<n.terms.length;e++){let i=r[e],a=n.terms[e];t===0?r[e]=a:i&&!i.equals(a)&&(r[e]=void 0)}}for(let e=0;e<r.length;e++){let t=r[e];if(t&&!t.equals(0))return e}return n},i=function(e,n){let r=e.len(),i=n.len(),a=n.terms[t],o=e.terms[t];return i>r&&a.greaterThan(o)?i-r:a.subtract(o)};t=r(c,l,t),c.sort(i),l.sort(i);let a=l[0],o=c[0];if(m=new T(new _(1),[],o.map),a.sum.greaterThan(o.sum)&&o.len()>1)for(let e=0;e<o.terms.length;e++){let t=a.terms[e].subtract(o.terms[e]);if(t.equals(0))m.terms[e]=new _(0);else{let n=t.add(new _(1));m.terms[e]=t;for(let t=0;t<c.length;t++)c[t].terms[e]=c[t].terms[e].add(n)}}let s=h(c[0],l[0]),u=0;for(;s&&n(c,l);){if(u++>200)throw new e.exceptions.InfiniteLoopError(`Unable to compute!`);let t=c[0].divide(l[0]);y.push(t),c.shift();for(let n=1;n<l.length;n++){let r=l[n].multiply(t).generateImage(),a=c.length;a===0&&(r.coeff=r.coeff.neg(),c.push(r),c.sort(i));for(let t=0;t<a;t++){let n=c[t];if(n.getImg()===r.getImg()){n.coeff=n.coeff.subtract(r.coeff),n.coeff.equals(0)&&(e.Utils.remove(c,t),t--);break}t===a-1&&(r.coeff=r.coeff.neg(),c.push(r),c.sort(i))}}if(s=h(c[0],l[0]),!s&&c.length>=l.length){for(let t=1;t<c.length;t++)if(s=h(c[t],l[0]),s){c.unshift(e.Utils.remove(c,t));break}}}}d=i(y),f=i(c),typeof m<`u`&&(m=m.toSymbol(),d=t.divide(d,m.clone()),f=t.divide(f,m))}return s&&(d=t.parse(d.text(),c),f=t.parse(f.text(),c)),[d,f]}catch(e){if(e.message===`timeout`)throw e;return i}},line(n,r,i){e.Utils.isArray(n)&&(n=e.Utils.convertToVector(n)),e.Utils.isArray(r)&&(r=e.Utils.convertToVector(r));let a=t.parse(i||`x`);(!e.Utils.isVector(n)||!e.Utils.isVector(r))&&t.error(`Line expects a vector! Received "${n}" & "${r}"`);let o=n,s=r,c=t.subtract(s.e(1).clone(),o.e(1).clone()),l=t.subtract(s.e(2).clone(),o.e(2).clone()),u=t.divide(l,c),d=t.multiply(a,u.clone()),f=t.multiply(o.e(1).clone(),u);return t.add(t.subtract(d,f),o.e(2).clone())},PartFrac:{createTemplate(e,n,r,i){e=E.Factor.factorInner(e),e.each((t,n)=>{if(t.group===s&&t.fname===``&&t.args[0].group===a){let r=t.args[0];e.symbols?(delete e.symbols[n],e.symbols[r.value]=r):e=t.args[0]}});let o,c,l,u=n.collectFactors?.()||[],d=[],f=[],p=new v(1);for(let n=0;n<u.length;n++){let a=v.unwrapPARENS(u[n]);if(a.power.greaterThan(1)){c=Number(a.power),o=a.clone().toLinear(),l=Number(E.degree(o,i));for(let n=0;n<c;n++){let i=t.pow(o.clone(),new v(n+1));r.push(i.clone());let a=t.divide(e.clone(),i.clone());f.push(l),d.push(a)}}else{l=Number(E.degree(a,i)),r.push(a);let n=t.divide(e.clone(),a.clone());n=t.expand(v.unwrapPARENS(n)),f.push(l),d.push(n)}}return r=r.map(e=>t.multiply(e,p.clone())),[r,d,f]},partfrac(n,r,i){let a=p(n);r||=t.parse(a[0]);try{let a,o,s,c=t.expand(n.getNum()),l=t.expand(n.getDenom().toUnitMultiplier());c.multiplier=n.multiplier;let u=r.value;if(a=c.groupTerms(u),Number(E.degree(c,r))>=Number(E.degree(l,r))?(o=E.div(c.clone(),t.expand(l.clone())),s=o[0],c=o[1],a=c.groupTerms(u)):s=new v(0),Number(E.degree(l,r))===1){let e=t.divide(c,l);return i?[s,e]:t.add(s,e)}let d=E.Factor.factorInner(l),f=E.PartFrac.createTemplate(l.clone(),d,[],r),p=f[0],m=f[1],h=f[2],g=[a.length],_=[],y=[],b=[],x,S;m.forEach((e,n)=>{x=p[n],S=h[n];for(let n=0;n<S;n++){y.push(x.clone());let r=v.create(u,n),i=t.expand(t.multiply(e,r.clone())).groupTerms(u),a=i.length;g.push(a),_.push(i),b.push(r.clone())}});
2649let C=e.Utils.arrayMax(g),w=new e.Matrix(e.Utils.fillHoles(a,C)).transpose(),T=new e.Matrix;for(let t=0;t<_.length;t++)T.elements.push(e.Utils.fillHoles(_[t],C));let D=t.multiply(T.transpose().invert(),w);if(i){let e=[s];return D.each((n,r)=>{let i=t.multiply(b[r],t.divide(n,y[r]));e.push(i)}),e}let O=s;return D.each((e,n)=>{let r=t.multiply(b[n],t.divide(e,y[n]));O=t.add(O,r)}),O}catch(e){if(e.message===`timeout`)throw e;try{if(n.isComposite()){let e={};n.each(n=>{let r=n.getDenom(),i=n.getNum(),a=e[r];e[r]=a?t.add(a,i):i});let r=new v(0);for(let n in e)Object.hasOwn(e,n)&&(r=t.add(r,t.divide(e[n],t.parse(n))));n=r}}catch(e){if(e.message===`timeout`)throw e}}return n}},degree(n,r,i){if(i||={nd:[],sd:[],depth:0},!r){let e=p(n);if(e.length>1)throw Error(`You must specify the variable for multivariate polynomials!`);if(e.length===0)return new v(0);r=t.parse(e[0])}let s=n.group;n.isComposite()?(n=n.clone(),n.distributeExponent(),n.each(e=>{i.depth++,E.degree(e,r,i),i.depth--})):n.group===u?n.each(e=>{i.depth++,E.degree(e,r,i),i.depth++}):s===o&&n.value===r.value?i.sd.push(n.power.clone()):s===a&&n.value===r.value?i.nd.push(t.parse(n.power)):i.nd.push(new v(0));let c=i.nd.length>0?e.Utils.arrayMax(i.nd):void 0;return i.depth===0&&i.sd.length>0?(c!==void 0&&i.sd.unshift(t.parse(c)),t.symfunction(`max`,i.sd)):t.parse(c??0)},sqComplete(n,r,i){e.Utils.isSymbol(r)||(r=t.parse(r));let a=function(t){throw t||=`Stopping`,new e.exceptions.ValueLimitExceededError(t)};n.isPoly(!0)||a(`Must be a polynomial!`);let o=e.Utils.inBrackets;n=n.clone();let s=e.Algebra.degree(n,r);s.equals(2)||a(`Cannot complete square for degree ${s.text()}`);let c=e.Algebra.coeffs(n,r),l=c[2],u=c[1].sign(),d=t.divide(c[1],new v(2)),f=t.pow(d.clone(),new v(2)),p=S.sqrt(l),m=t.divide(S.sqrt(f),p.clone()),h=t.subtract(c[0],t.pow(m.clone(),new v(2)));if(i)return[l,d,h];let g=t.parse(o(`${p.clone()}*${r}${u<0?`-`:`+`}${m}`));return{a:g,c:h,f:t.add(t.pow(g.clone(),new v(2)),h.clone())}},Simplify:{strip(e){let n=t.parse(e.multiplier);e.toUnitMultiplier();let r=t.parse(e.power);return e.toLinear(),[n,r,e]},unstrip(e,n){let r=e[0],i=e[1];return t.multiply(r,t.pow(n,i))},complexSimp(e,n){let r=e.realpart(),i=e.imagpart(),a=n.realpart(),o=n.imagpart(),s=t.multiply(r.clone(),a.clone()),c=t.multiply(i.clone(),o.clone()),l=t.multiply(a.clone(),i),u=t.multiply(r,o.clone()),d=t.add(t.pow(a,new v(2)),t.pow(o,new v(2)));return t.divide(t.add(t.add(s,c),t.multiply(t.subtract(l,u),v.imaginary())),d)},trigSimp(n){let r=!0,i=0;for(;r&&n.containsFunction([`cos`,`sin`,`tan`]);){i++,r=!1,n=n.clone();let a=E.Simplify.strip(n);n=a.pop();let o=n.clone();if(n.group===l){let e=new v(0);n.each(n=>{let r=E.Simplify.trigSimp(n.fnTransform());e=t.add(e,r)},!0),o=t.pow(t.multiply(new v(n.multiplier),e),new v(n.power)),r=o.text()!==n.text()}else if(n.group===u){let i=n.getNum(),a=n.getDenom();if(i.fname===`sin`&&a.fname===`cos`&&i.args[0].equals(a.args[0])&&i.power.equals(a.power))o=t.parse(e.Utils.format(`(({1})/({0}))*tan({2})^({3})`,a.multiplier,i.multiplier,i.args[0],i.power)),r=!0;else if(i.fname===`tan`&&a.fname===`sin`&&i.args[0].equals(a.args[0])&&i.power.equals(a.power))o=t.parse(e.Utils.format(`(({1})/({0}))*cos({2})^(-({3}))`,a.multiplier,i.multiplier,i.args[0],i.power)),r=!0;else{let n=new v(1),i={workDone:r};o.each(r=>{if(r.fname===`tan`)r=t.parse(e.Utils.format(`({0})*sin({1})^({2})/cos({1})^({2})`,r.multiplier,E.Simplify._simplify(r.args[0]),r.power)),i.workDone=!0;else if(r.containsFunction([`cos`,`sin`,`tan`])){let e=E.Simplify.trigSimp(r);r.equals(e)||(r=e,i.workDone=!0)}n=t.multiply(n,r)}),r=i.workDone,o=n}}else if((n.fname===`cos`||n.fname===`sin`)&&n.args[0].group===l){let i=0,a=new v(0),s=t.parse(`pi/2`);if(n.args[0].each(n=>{let r=t.divide(n.clone(),s.clone());r=E.Simplify._simplify(r),r=e.Utils.evaluate(r),g(r)?i+=r.multiplier.num.toJSNumber():a=t.add(a,n)}),i){i+=+(n.fname===`cos`),i%=4,i+=i<0?4:0;let s=e.Utils.format([`sin({0})`,`cos({0})`,`-sin({0})`,`-cos({0})`][i],String(a));o=t.parse(s),r=!0}else if(Object.keys(n.args[0].symbols).length>1){let i=n.args[0].clone(),a=Object.values(i.symbols),s=a[0],c=a.slice(1).map(e=>`(${e.text()})`).join(`+`),l;l=n.fname===`sin`?e.Utils.format(`sin({0})cos({1})+sin({1})cos({0})`,s,c):e.Utils.format(`cos({0})cos({1})-sin({1})sin({0})`,s,c),o=t.parse(l),r=!0}}else if((n.fname===`cos`||n.fname===`sin`)&&n.args[0].multiplier.sign()===-1){let i=n.args[0].clone().negate(),a=e.Utils.format(`${n.fname}({0})`,i);n.fname===`sin`&&(a=`-${a}`),o=t.parse(a),r=!0}if(n.fname===`sin`&&n.args[0].multiplier.equals(2)&&!n.args[0].equals(2)){let i=n.args[0].clone().toUnitMultiplier(),a=e.Utils.format(`2sin({0})cos({0})`,i);o=t.parse(a),r=!0}if(o=E.Simplify.unstrip(a,o).distributeMultiplier(),n=o,i>10)break}return n},logArgSimp(n,r){if(r.value===`1`||r.value===`1`)return new v(0);let i=new v(0),a=r.multiplier.clone();if(r.toUnitMultiplier(),!a.equals(1)){let r=e.Utils.format(`({0}({1}))`,n,a);i=t.add(i,t.parse(r))}if(r.group===u)r.each(r=>{r=r.clone();let a=r.power.clone();E.Simplify.strip(r);let o=e.Utils.format(`(({1})*{0}({2}))`,n,a,r);i=t.add(i,t.parse(o))});else{let a=r.clone(),o=a.power.clone();E.Simplify.strip(a);let s=e.Utils.format(`(({1})*{0}({2}))`,n,o,a);i=t.add(i,t.parse(s))}return i},logSimp(e){if(e.group===s&&(e.fname===`log`||e.fname===`log10`)){e.clone();let n=E.Simplify.strip(e);e=n.pop();
2649let r=e.args[0].clone(),i=r.getNum().clone(),a=r.getDenom().clone(),o=e.fname,s=E.Simplify.logArgSimp(o,i);if(!a.equals(1)){let e=E.Simplify.logArgSimp(o,a);s=t.subtract(s,e)}s=E.Simplify.unstrip(n,s).distributeMultiplier(),e=s}else if(e.containsFunction([`log`,`log10`]))for(let t in e.symbols){if(!Object.hasOwn(e.symbols,t))continue;let n=e.symbols[t];e.symbols[t]=E.Simplify.logSimp(n)}return e},_sqrtCompression(e,n,r){let i=E.Simplify.strip(e),o=e=>e.fname===`abs`,s=e=>e.args[0],c=e=>o(e)?s(e):null,l=e=>e.type===a&&e.value.startsWith(`baseunit_`),u=(e,t)=>{let n=s(t);return n.equals(c(e))||n.equals(e)&&l(e)?[t,null]:[null,t]},d,f=!1,p=(e,t)=>{for(let n=0;n<e.length;n++){let r=e[n];if(r.isSQRT()){for(let e=0;e<t.length;e++){let n=t[e];if([n,r]=u(n,r),n!==null){t[e]=n,d=!0,f=!0;break}}e[n]=r,e=e.filter(e=>e),t=t.filter(e=>e)}}return[e,t]},m=n.collectFactors(),h=r.collectFactors();do d=!1,[m,h]=p(m,h),[h,m]=p(h,m);while(d);return f&&(e=m.reduce((e,n)=>e=t.multiply(e,n),new v(1)),e=h.reduce((e,n)=>e=t.divide(e,n),e)),e=E.Simplify.unstrip(i,e),e},fracSimp(e){let n=e.getDenom(),r=e.getNum();if(r.isImaginary()&&n.isImaginary()&&(e=E.Simplify.complexSimp(r,n)),e.isComposite()){e.power.gt(1)&&(e=t.expand(e));let i=e.collectSymbols(),a,o,s,c,l,u,d,f,p,m,h;for(o=i.pop();i.length;)s=i.pop(),c=t.parse(o.getDenom()),l=t.parse(s.getDenom()),u=o.getNum(),d=s.getNum(),h=t.multiply(c.clone(),l.clone()),p=t.multiply(u,l),m=t.multiply(d,c),f=t.add(p,m),o=t.divide(f,h);return n=t.expand(o.getDenom()),r=t.expand(o.getNum()),a=r.isImaginary()&&n.isImaginary()?E.Simplify.complexSimp(r,n):t.divide(r,n),a.equals(e)?e:E.Simplify._simplify(a)}return e=E.Simplify._sqrtCompression(e,r,n),e=E.Simplify.simpleFracSimp(e),e},simpleFracSimp(e){let n=e.getDenom(),r=e.getNum(),i;return n=t.expand(n),r=t.expand(r),i=r.isImaginary()&&n.isImaginary()?E.Simplify.complexSimp(r,n):t.divide(r,n),i.equals(e)?e:i},ratSimp(e){if(e.group===u){let n=e.getDenom(),r=e.getNum().distributeMultiplier(),i=E.Simplify.fracSimp(n),a=E.Simplify.fracSimp(r);e=t.divide(a,i)}return e},sqrtSimp(e,n){let i,a=!1,o=e.clone();try{if(e.isSQRT()){let n=e.multiplier.clone(),o=e.args[0].clone(),s=E.Factor.factorInner(o),c=t.parse(s.multiplier),l=c.sign();i=new v(1);let d;if(s.group===u){let e=new v(1);s.each(n=>{if(n=t.parse(n),n.group===r){let r=t.sqrt(n.clone());g(r)?i=t.multiply(i,r):e=t.multiply(e,n)}else e=t.multiply(e,n)});let n=t.multiply(e,t.parse(l));d=t.sqrt(n.clone()),d.isImaginary()&&(d=t.sqrt(t.expand(n.clone())))}else d=s.clone().toUnitMultiplier(),d=t.multiply(d,new v(l)),d=t.sqrt(d);i=t.multiply(i,d),i=t.pow(i,t.parse(e.power)),i=t.multiply(i,t.sqrt(c.abs())),i=t.multiply(i,t.parse(n)),a=!0}else e.isComposite()&&e.isLinear()?(i=new v(0),e.each(e=>{i=t.add(i,E.Simplify.sqrtSimp(e))},!0),i=t.pow(i,t.parse(e.power)),i=t.multiply(i,t.parse(e.multiplier)),a=!0):e.group===u&&(i=new v(1),e.each(e=>{let n=E.Simplify.sqrtSimp(e);i=t.multiply(i,n)}),i=t.pow(i,t.parse(e.power)),i=t.multiply(i,t.parse(e.multiplier)),a=!0);return a||i&&!g(i)&&(i=null),i||=t.parse(e),i}catch(e){if(e.message===`timeout`)throw e;return o}},patternSub(t){let n={},r=function(e){let t=!1;return e.each(e=>{e.group===l?t=!0:e.symbols&&(t=r(e))}),t},i=function(a){a.each(a=>{if(!(!a.symbols&&a.group!==s)){if(r(a))i(a);else if(!n[a.value]){let r=e.Utils.getU(t);n[a.value]=r,t=t.sub(a.value,r)}}},!0)};return i(t),[t,n]},simplify(e){if(e.simplify)return e.simplify();let n=E.Simplify._simplify(e);return n=n.pushMinus(),n=t.parse(n),n},_simplify(n){let r=E.Simplify.strip(n.clone());if(n=r.pop(),n=E.Simplify.fracSimp(n),n.isConstant()||n.group===e.groups.S)return r.push(n),E.Simplify.unstrip(r,n);let i=n.clone();if(i=E.Simplify.sqrtSimp(i,r),i=E.Simplify.trigSimp(i),i=E.Simplify.logSimp(i),i=E.Simplify.ratSimp(i),i=E.Factor.factorInner(i),i.group===e.groups.CP&&i.isLinear()){let e=i.multiplier.clone();i.toUnitMultiplier();let n=new v(0);return i.each(e=>{let r=E.Simplify._simplify(e);n=t.add(n,r)}),i=n,i=t.multiply(i,new v(e)),i.multiplier.equals(-1)&&i.distributeMultiplier(),i=E.Simplify.unstrip(r,i),i}return i=E.Simplify.unstrip(r,i),i}},Classes:{Polynomial:C,Factors:w,MVTerm:T}};e.Expression.prototype.simplify=function(){e.Utils.armTimeout();try{let t;if(typeof this.symbol.LHS>`u`)t=new e.Expression(E.Simplify.simplify(this.symbol));else{let e=this.symbol.clone();e.LHS=E.Simplify.simplify(e.LHS),e.RHS=E.Simplify.simplify(e.RHS),t=e}return t}catch(e){if(e.message===`timeout`)throw e;return this}finally{e.Utils.disarmTimeout()}},e.Collection.prototype.simplify=function(){return this.elements=this.elements.map(e=>E.Simplify.simplify(e)),this},e.Matrix.prototype.simplify=function(){return this.elements=this.elements.map(e=>e.map(e=>E.Simplify.simplify(e))),this},n.useAlgebraDiv=function(){E.divideFn=t.divide;let n=0;t.divide=function t(r,i){n++;let a;return a=n===1?e.Algebra.divide(r,i):t(r,i),n=0,a}
2649},n.useParserDiv=function(){E.divideFn&&(t.divide=E.divideFn),delete E.divideFn},n.register([{name:`factor`,visible:!0,numargs:1,build(){return E.Factor.factor}},{name:`simplify`,visible:!0,numargs:1,build(){return E.Simplify.simplify}},{name:`gcd`,visible:!0,numargs:[1],build(){return E.gcd}},{name:`lcm`,visible:!0,numargs:[1],build(){return E.lcm}},{name:`roots`,visible:!0,numargs:-1,build(){return E.roots}},{name:`divide`,visible:!0,numargs:2,build(){return E.divide}},{name:`div`,visible:!0,numargs:2,build(){return E.div}},{name:`partfrac`,visible:!0,numargs:[1,2],build(){return E.PartFrac.partfrac}},{name:`deg`,visible:!0,numargs:[1,2],build(){return E.degree}},{name:`coeffs`,visible:!0,numargs:[1,2],build(){return function(...t){let n=E.coeffs(t[0],t[1]);return new e.Vector(n)}}}]),n.coeffs=function(...t){let n=e.PARSER;for(let r=0;r<t.length;r++)typeof t[r]==`string`?t[r]=n.parse(t[r]):t[r]&&t[r].symbol?t[r]=t[r].symbol.clone():e.Utils.isSymbol(t[r])&&(t[r]=t[r].clone());let r=E.coeffs(t[0],t[1]);return new e.Expression(new e.Vector(r))},n.register([{name:`line`,visible:!0,numargs:[2,3],build(){return E.line}},{name:`sqcomp`,visible:!0,numargs:[1,2],build(){return function(e,t){try{return t||=p(e)[0],E.sqComplete(e.clone(),t).f}catch(t){if(t.message===`timeout`)throw t;return e}}}}]),n.updateAPI()})()}),YW=HW((e,t)=>{var n=typeof globalThis<`u`&&globalThis.nerdamer?globalThis.nerdamer:void 0;typeof t<`u`&&n===void 0&&(n=KW(),qW(),JW()),(function(){let e=n.getCore(),t=e.PARSER,r=e.Algebra,i=e.Calculus,{integration:a}=i,{decompose_arg:o}=a,{Factor:s,Simplify:c,Classes:l}=r,{evaluate:u,remove:d,format:f,knownVariable:p,isSymbol:m,variables:h,range:g}=e.Utils,{build:_}=e.Build,{NerdamerSymbol:v}=e,{S:y,PL:b,CB:x,CP:S,FN:C}=e.groups,{Settings:w}=e,{isArray:T}=e.Utils;e.Settings.SOLVE_RADIUS=1e3,e.Settings.ROOTS_PER_SIDE=10,e.Settings.make_pi_conversions=!1,e.Settings.STEP_SIZE=.1,e.Settings.EPSILON=2e-13,e.Settings.MAX_NEWTON_ITERATIONS=200,e.Settings.NEWTON_EPSILON=2e-15,e.Settings.MAX_NON_LINEAR_TRIES=12,e.Settings.NON_LINEAR_JUMP_AT=50,e.Settings.NON_LINEAR_JUMP_SIZE=100,e.Settings.NON_LINEAR_START=.01,e.Settings.NEWTON_SLICES=200,e.Settings.SOLUTION_PROXIMITY=1e-14,e.Settings.FILTER_SOLUTIONS=!0,e.Settings.MAX_SOLVE_DEPTH=10,e.Settings.ZERO_EPSILON=1e-9,e.Settings.MAX_BISECTION_ITER=2e3,e.Settings.BI_SECTION_EPSILON=1e-12,e.NerdamerSymbol.prototype.hasTrig=function(){return this.containsFunction([`cos`,`sin`,`tan`,`cot`,`csc`,`sec`])},e.NerdamerSymbol.prototype.hasNegativeTerms=function(){if(this.isComposite())for(let e in this.symbols){if(!Object.hasOwn(this.symbols,e))continue;let t=this.symbols[e];if(t.group===b&&t.hasNegativeTerms()||this.symbols[e].power.lessThan(0))return!0}return!1};function E(t,n){if(n.isConstant()&&t.isConstant()&&!t.equals(n)||t.equals(e.Settings.IMAGINARY)&&n.isConstant(!0)||n.equals(e.Settings.IMAGINARY)&&t.isConstant(!0))throw new e.exceptions.NerdamerValueError(`${t.toString()} does not equal ${n.toString()}`);this.LHS=t,this.RHS=n}E.prototype={toString(){return`${this.LHS.toString()}=${this.RHS.toString()}`},text(e){return`${this.LHS.text(e)}=${this.RHS.text(e)}`},toLHS(e){e=!!e;let n=this.removeDenom(),r=n.LHS,i=n.RHS;r.isConstant(!0)&&!i.isConstant(!0)&&([r,i]=[i,r]);let a=t.subtract(r,i),o=e?t.expand(a):a;return o=new E(o,new v(0)).removeDenom().LHS,o},removeDenom(){let e=this.LHS.clone(),n=this.RHS.clone(),r=t.multiply(e.getDenom(),n.getDenom());if(e=t.expand(t.multiply(e,r.clone())),n=t.expand(t.multiply(n,r)),n.group===S&&n.group!==S){let t=e;e=n,n=t}if(e.group===x){let r=new v(e.multiplier),i=n.clone();e.each(e=>{e.power.lessThan(0)?i=t.divide(i,e):r=t.multiply(r,e)}),e=r,n=i}else if(e.group===S)for(let r in e.symbols){if(!Object.hasOwn(e.symbols,r))continue;let i=e.symbols[r];if(i.group===x)for(let r in i.symbols){if(!Object.hasOwn(i.symbols,r))continue;let a=i.symbols[r];if(a.power.lessThan(0))return new E(t.expand(t.multiply(a.clone().toLinear(),e)),t.expand(t.multiply(a.clone().toLinear(),n)))}}return new E(e,n)},clone(){return new E(this.LHS.clone(),this.RHS.clone())},sub(e,t){let n=this.clone();return n.LHS=n.LHS.sub(e.clone(),t.clone()),n.RHS=n.RHS.sub(e.clone(),t.clone()),n},isZero(){return e.Utils.evaluate(this.toLHS()).equals(0)},latex(e){return[this.LHS.latex(e),this.RHS.latex(e)].join(`=`)}},t.equals=function(e,t){return new E(e,t)},(function(){let e=t.functions.simplify[0];t.functions.simplify[0]=function(t){return t instanceof E?(t.LHS=e(t.LHS),t.RHS=e(t.RHS),t):e(t)}})(),e.Expression.prototype.equals=function(t){return t instanceof e.Expression&&(t=t.
2649symbol),new E(this.symbol,t)},e.Expression.prototype.solveFor=function(n){e.Utils.armTimeout();try{let{symbol:r}=this;if(this.symbol instanceof E){if(this.symbol.LHS.isConstant()&&this.symbol.RHS.equals(n))return[new e.Expression(this.symbol.LHS)];if(this.symbol.RHS.isConstant()&&this.symbol.LHS.equals(n))return[new e.Expression(this.symbol.RHS)]}return j(r,n).map(n=>(n=c.simplify(t.parse(n)),new e.Expression(n)))}finally{e.Utils.disarmTimeout()}},e.Expression.prototype.expand=function(){if(this.symbol instanceof E){let n=this.symbol.clone();return n.RHS=t.expand(n.RHS),n.LHS=t.expand(n.LHS),new e.Expression(n)}return new e.Expression(t.expand(this.symbol))},e.Expression.prototype.variables=function(){return this.symbol instanceof E?e.Utils.arrayUnique(e.Utils.variables(this.symbol.LHS).concat(e.Utils.variables(this.symbol.RHS))):e.Utils.variables(this.symbol)};let D=function(e,n){return t.equals(e,n)};e.Equation=E;let O=e.Utils.checkAll=function(e,t){for(let n=0;n<e.length;n++)if(t(e[n]))return!1;return!0},k=e.Solve={version:`2.0.3`,solutions:[],solve(t,n){let r=w.PARSE2NUMBER;w.PARSE2NUMBER=!1;let i=j(t,String(n));return w.PARSE2NUMBER=r,new e.Vector(i)},toLHS(e,n){if(m(e))return e;if(!(e instanceof E)){let n=e.split(`=`);n[1]||=`0`,e=new E(t.parse(n[0]),t.parse(n[1]))}return e.toLHS(n)},solveCircle(n,i){let a=i.map(e=>t.parse(e)),o=[],s=[];for(let t=0;t<n.length;t++){let i=[];for(let e=0;e<a.length;e++)i.push(Number(r.degree(n[t],a[e])));i.push(e.Utils.arraySum(i,!0)),o.push(i)}let c=n[0],l=n[1];if(o[0][2]>o[1][2]&&([l,c]=[c,l],[o[1],o[0]]=[o[0],o[1]]),o[0][0]===1&&o[0][2]===2&&o[1][0]===2&&o[1][2]===4){let e=i[0],n=i[1],r=j(t.parse(l,p(e,j(t.parse(c),e)[0])),n).map(e=>e.toString()),a=[j(t.parse(c,p(n,r[0])))[0].toString()];if(r[1]&&a.push(j(t.parse(c,p(n,r[1])))[0].toString()),w.SOLUTIONS_AS_OBJECT){let t={};t[e]=a,t[n]=r,s=t}else r.unshift(n),a.unshift(e),s=[a,r]}return s},solveNonLinearSystem(n,r,i){if(r<0)return[];i=typeof i>`u`?e.Settings.NON_LINEAR_START:i;let a=e.Settings.MAX_NON_LINEAR_TRIES,o=Math.floor(a/2);r=typeof r>`u`?a:r;let s=e.Settings.NON_LINEAR_JUMP_AT,c=e.Settings.NON_LINEAR_JUMP_SIZE,l=!0,u=function(e,t){return e.map((e,n)=>Number(t.get(n,0)))},d=e.Utils.arrayGetVariables(n),f=e.Matrix.jacobian(n,d,e=>_(e,d),!0),p=e.Settings.MAX_NEWTON_ITERATIONS,m,h,g,v,y,b,x,S,C=n.map(e=>_(e,d)),w=f.map(e=>_(e,d),!0);v=e.Matrix.cMatrix(0,d);let T=e.Matrix.cMatrix(i,d);g=0;do{if(g>p){l=!1;break}m=u(d,T),x=T.clone();let a=m,f=T;C.forEach((e,t)=>{f.set(t,0,e(...a))});let _=new e.Matrix;if(w.each((e,t,n)=>{let r=e(...a);_.set(t,n,r)}),_=_.invert(),h=t.multiply(_,T).negate(),S=h.subtract(v,e=>t.parse(Number(e))),v=x.add(h,e=>t.parse(Number(e))),T=v,g>=s&&Number(y)>1){r===o&&(i=0);let e=r>o?1:-1,t=r%Math.floor(o)+1;return i+=e*t*c,k.solveNonLinearSystem(n,--r,i)}if(b=y,g++,y=S.max(),Number(y)===Number(b))break}while(Number(y)>=2**-52);return l?k.systemSolutions(T,d,!0,t=>e.Utils.round(Number(t),14)):[]},systemSolutions(n,r,i,a){if(e.Settings.SOLUTIONS_AS_OBJECT){let e={};return n.each((n,o)=>{let s=(i?t.expand(n):n).valueOf();a&&(s=a.call(n,s)),e[r[o]]=s}),e}let o=[];return n.each((e,n)=>{let s=(i?t.expand(e):e).valueOf();a&&(s=a.call(e,s)),o.push([r[n],s])}),o},solveSystemBySubstitution(t){let n=h(t[0]),r=h(t[1]);return t.length===2&&n.length===2&&e.Utils.arrayEqual(n,r)?k.solveCircle(t,n):[]},solveSystem(i,a){for(let e=0;e<i.length;e++)i[e]=k.toLHS(i[e]);
2649let s=i.length,c=new e.Matrix,l=new e.Matrix,u=!1,f;if(typeof a>`u`){if(!r.allLinear(i))try{return k.solveNonLinearSystem(i)}catch(t){if(t.message===`timeout`)throw t;if(t instanceof e.exceptions.DivisionByZero)return k.solveSystemBySubstitution(i)}if(f=e.Utils.arrayGetVariables(i),f.length===1){let e=0,t,n;do n=i[e].clone(),e>0&&(n=n.sub(f[0],t[0])),t=j(n,f[0]);while(++e<i.length);let r;return w.SOLUTIONS_AS_OBJECT?(r={},r[f[0]]=t):r=t.length===0?t:[f[0],t],r}if(f.length<i.length){let e=[],n=i.length;for(let r=0;r<n-1;r++)e.push(t.parse(i[r]));let r={},a=k.solveSystem(e,f);if(Array.isArray(a))a.forEach(e=>{Array.isArray(e[1])||(r[e[0]]=e[1])});else for(let e of Object.keys(a)){let t=a[e];Array.isArray(t)||(r[e]=t)}let o=!0;for(let e=n-1;e<n;e++)t.parse(i[e],r).equals(0)||(o=!1);if(o)return a}for(let e=0;e<f.length;e++)n.setVar(f[e],`delete`);for(let t=0;t<s;t++){let n=i[t];for(let r=0;r<f.length;r++){let i=f[r],a=[];n.each(e=>{e.contains(i)&&(a=a.concat(e.coeffs()))});let o=e.Utils.arraySum(a);c.set(t,r,o)}let r=n.clone();f.forEach(e=>{r=r.stripVar(e,!0)}),l.set(t,0,r.negate())}}else{f=a,u=!0;for(let n=0;n<s;n++){l.set(n,0,new v(0));let r=t.expand(i[n]).collectSummandSymbols();for(let i=0;i<a.length;i++){c.set(n,i,new v(0));let s=a[i];for(let l=0;l<r.length;l++){let u=r[l],f=!1;for(let t=0;t<a.length;t++)u.contains(a[t])&&(f&&e.Utils.err(`Multiple variables found for term ${u}`),f=!0);if(u.contains(s)){let e=o(d(r,l),s);l--,c.set(n,i,t.add(c.get(n,i),e[0]))}}}for(let e=0;e<r.length;e++)l.set(n,0,t.add(l.get(n,0),r[e]))}}if(f.length!==i.length||c.determinant().equals(0))throw new e.exceptions.SolveError(`System does not have a distinct solution`);c=c.invert();let p=c.multiply(l);return e.Utils.isArray(a)&&p.each(e=>e.negate()),k.systemSolutions(p,f,u)},quad(e,n,r){let i=t.subtract(t.pow(n.clone(),new v(2)),t.multiply(t.multiply(r.clone(),e.clone()),new v(4)));i=t.expand(i);let a=t.pow(i,new v(.5)),o=t.parse(t.multiply(new v(2),r.clone()));return[t.parse(f(`(-({0})+({1}))/({2})`,n,a,o)),t.parse(f(`(-({0})-({1}))/({2})`,n,a,o))]},cubic(e,n,r,i){let a=i.text(),o=r.text(),s=n.text(),c=`(-(${o})^3/(27*(${a})^3)+(${o})*(${s})/(6*(${a})^2)-(${e.text()})/(2*(${a})))`,l=`((${s})/(3*(${a}))-(${o})^2/(9*(${a})^2))`,u=`((${c})+sqrt((${c})^2+(${l})^3))^(1/3)+((${c})-sqrt((${c})^2+(${l})^3))^(1/3)-(${`(${o})/(3*(${a}))`})`,d=`1/2+sqrt(3)/2*i`;return[t.parse(u),t.parse(`(${u})(${d})`),t.parse(`(${u})(${d})^2`)]},quartic(n,r,i,a,o){let s={};e.Utils.arrayUnique(h(o).concat(h(a)).concat(h(i)).concat(h(r)).concat(h(n))).forEach(e=>{s[e]=1});let c=o.toString(),l=a.toString(),u=i.toString(),d=r.toString(),p=n.toString(),m=t.parse(f(`(8*({0})*({2})-3*({1})^2)/(8*({0})^2)`,c,l,u)).toString(),g=t.parse(f(`(({1})^3-4*({0})*({1})*({2})+8*({0})^2*({3}))/(8*({0})^3)`,c,l,u,d)).toString(),_=t.parse(f(`12*({0})*({4})-3*({1})*({3})+({2})^2`,c,l,u,d,p)).toString(),v=t.parse(f(`2*({2})^3-9*({1})*({2})*({3})+27*({1})^2*({4})+27*({0})*({3})^2-72*({0})*({2})*({4})`,c,l,u,d,p)).toString(),y=t.parse(f(`((({1})+(({1})^2-4*({0})^3)^(1/2))/2)^(1/3)`,_,v)).toString(),b=t.parse(f(`(1/2)*(-(2/3)*({1})+(1/(3*({0}))*(({2})+(({3})/({2})))))^(1/2)`,c,m,y,_)).toString();return[t.parse(f(`-(({1})/(4*({0})))-({4})+(1/2)*sqrt(-4*({4})^2-2*({2})+(({3})/({4})))`,c,l,m,g,b)),t.parse(f(`-(({1})/(4*({0})))-({4})-(1/2)*sqrt(-4*({4})^2-2*({2})+(({3})/({4})))`,c,l,m,g,b)),t.parse(f(`-(({1})/(4*({0})))+({4})+(1/2)*sqrt(-4*({4})^2-2*({2})-(({3})/({4})))`,c,l,m,g,b)),t.parse(f(`-(({1})/(4*({0})))+({4})-(1/2)*sqrt(-4*({4})^2-2*({2})-(({3})/({4})))`,c,l,m,g,b))]},divideAndConquer(e,t){let n=[],r=s.factorInner(e);return r.group===x&&r.each(e=>{e=v.unwrapPARENS(e),n=n.concat(j(e,t))}),n},csolve(n,r){return e.Utils.block(`IGNORE_E`,()=>{let i,a,o,s,c,l,u=[],d=e.Utils.decompose_fn(n,r,!0);if(d.x.group===y){i=t.parse(d.x.power),a=Number(i),o=t.pow(t.divide(d.b.negate(),d.a),i.invert()),s=v.toPolarFormArray(o),c=s[0],s[1],l=c.toString(),i.toString();let n,r,p;for(let o=0;o<a;o++)n=o,p=f(`({0})*e^(2*{1}*pi*{2}*{3})`,l,n,i,e.Settings.IMAGINARY),r=t.parse(p),u.push(r)}return u},!0)},getPoints(t,n,r){n||=.01;let i=[],a=_(t);a(0);
2649let o=e.Settings.ROOTS_PER_SIDE,s=o;i.push(0),i.push(0),i.push(0),t.each(t=>{t.containsFunction(e.Settings.LOG)&&i.push(.1)});let c=g(-e.Settings.SOLVE_RADIUS,0,n),l=g(0,e.Settings.SOLVE_RADIUS,n),u=function(e,t){let n,r,o,s=[],c=e[0],l=Math.sign(a(c));for(let i=0,c=e.length;i<c&&s.length<t;i++)n=e[i],r=a(n),o=Math.sign(r),!isNaN(o)&&(o!==l&&(s.push(n),s.push(e[i-1])),l=o);i=i.concat(s)};if(u(c,s),u(l,o),r){let t=e.Settings.SOLVE_RADIUS;u([t,t*t],1),u([-t*t,-t],1)}return i},bisection(t,n){let r=t-1,i=t+1;if(Math.sign(n(r))!==Math.sign(n(i))){let t=0,a,o;do{if(a=Math.abs(i-r),t++>e.Settings.MAX_BISECTION_ITER||isNaN(a))return;o=(r+i)/2,n(r)*n(o)>0?r=o:i=o}while(a>=w.EPSILON);let s=(r+i)/2,c=n(s);return!isNaN(c)&&Math.abs(c)<=e.Settings.BI_SECTION_EPSILON?e.Utils.round(s,13):void 0}},bSearch(e,t,n){let r=n(e),i=n(t);if(Math.sign(r)===Math.sign(i)||isNaN(r)||isNaN(i))return;let a=0;do{let o=(e+t)/2;if(Math.sign(r)===Math.sign(n(o))){if(o===e)break;e=o,r=n(e)}else{if(o===t)break;t=o,i=n(t)}a++}while(e!==t&&a<80);if(!(!isFinite(n(e))||!isFinite(n(t))))return e},Newton(t,n,r,i){let a=e.Settings.MAX_NEWTON_ITERATIONS,o=0,s=t,c,l,u;do{let e=n(s);if(s===0&&e===0){c=0;break}if(o++,o>a)return;let t=r(s);if(isNaN(t)||isNaN(e))return;if(t===0)c+=u;else{if(!isFinite(e)||!isFinite(t)||Math.abs(e)>1e25)return k.bSearch(i,s,n);c=s-e/t}if(u=c-s,u===0&&!isFinite(t))return;l=Math.abs(u),s=c}while(l>w.NEWTON_EPSILON);return c},rewrite(n,r,i){if(r||=new v(0),n.isComposite()&&n.isLinear()){let a=[],o=[];n.each(e=>{e=e.clone(),e.fname===`sqrt`&&e.contains(i)?a.push(e):o.push(e)},!0),a.length===1&&(r=t.expand(t.pow(t.subtract(r,e.Utils.arraySum(o)),new v(2))),n=t.expand(t.pow(v.unwrapSQRT(a[0]),new v(2))))}else n=v.unwrapSQRT(t.expand(n));let a=0,o=n.length;if(n.group===S&&n.contains(i)&&n.isLinear()){n.distributeMultiplier();let e=new v(0);return n.each(n=>{n.contains(i)?(a++,e=t.add(e,n.clone())):r=t.subtract(r,n.clone())}),n=e,a===o?[n,r]:k.rewrite(n,r,i)}if(n.group===x&&n.contains(i)&&n.isLinear()){if(n.multiplier.lessThan(0)&&(n.multiplier=n.multiplier.multiply(new e.Frac(-1)),r.multiplier=r.multiplier.multiply(new e.Frac(-1))),r.equals(0))return new v(0);let a=new v(1);return n.each(e=>{e.contains(i)?a=t.multiply(a,e.clone()):r=t.divide(r,e.clone())}),n=a,k.rewrite(n,r,i)}if(!n.isLinear()&&n.contains(i)){let e=t.parse(n.power.clone().invert());return n=t.pow(n,e.clone()),r=t.pow(t.expand(r),e.clone()),k.rewrite(n,r,i)}return n.group===C||n.group===y||n.group,[n,r]},sqrtSolve(e,n){let r=new v(0),i=new v(0);if(e.isComposite()&&(e.each(e=>{e.fname===`sqrt`&&e.contains(n)?r=t.add(r,e.clone()):i=t.add(i,e.clone())}),!r.equals(0))){let a=j(t.expand(t.multiply(t.parse(e.multiplier),t.subtract(t.pow(i,new v(2)),t.pow(r,new v(2))))),n);return a=a.filter(t=>{if(t.isImaginary())return!0;let r={};return r[n]=t,!!u(e,r).equals(0)}),a}}},A=function(e,t,n,r){let i=e.toString(),a=i.match(/(?<![a-z])abs/gu);if(!a||a.length>2||e.LHS.group!==C&&e.RHS.group!==C)return null;let o=e.constructor(i.replace(/(?<![a-z])abs/u,``)),s=e.constructor(i.replace(/(?<![a-z])abs/u,`(-1)`)),c=j(o,t,null,n,r);return[j(s,t,null,n,r),c]};function j(n,a,c,d,f){if(d||=0,d++>w.MAX_SOLVE_DEPTH)return c;c||=[];let p={},h={};h[a]=0;let g=function(n,r){let i=m(n);if(!(n===void 0||typeof n==`number`&&isNaN(n))){if(T(n))n.forEach(e=>{g(e)});else if(n.valueOf()!==`null`){if(typeof e.Settings.PRE_ADD_SOLUTION==`function`&&(n=e.Settings.PRE_ADD_SOLUTION(n)),i||(n=t.parse(n)),e.Settings.make_pi_conversions&&r){let e=t.divide(n.clone(),new v(Math.PI)),r=e.multiplier,i=Math.abs(Number(r.num)),a=Math.abs(Number(r.den));i<10&&a<10&&(n=t.multiply(e,new v(`pi`)))}let a=n.toString();p[a]||c.push(n),p[a]=!0}}};if(n instanceof E){let e=A(n,a,d,f);if(e)return g(e),c;if(n.isZero())return[new v(0)];if(n.LHS.equals(a)&&!n.RHS.contains(a,!0))return[n.RHS];if(n.RHS.equals(a)&&!n.LHS.contains(a,!0))return[n.LHS]}if(n instanceof e.Vector&&(n=n.elements),T(n))return k.solveSystem(n,a);if(a||=`x`,m(n)&&u(n.getDenom(),h).equals(0)===!0)return c;if(n.group===y&&n.contains(a)){try{let e={};e[a]=0,u(f,e),g(new v(0))}catch(e){if(e.message===`timeout`)throw e}return c}if(n.group===x){let e=n.getNum();if(e.group===x){let t=String(a);return e.each(e=>{e.contains(t)&&j(e,a,c,d,n)}),c}return j(e,a,c,d,f)}n.group===C&&n.fname===`sqrt`&&(n=t.pow(v.unwrapSQRT(n),new v(2)));let D=(e.Utils.isSymbol(n)?n:k.toLHS(n,!1)).getNum(),M=e.Utils.variables(D),N=M.length;if(e.Utils.isInt(D.power)&&Number(D.power)>1&&(D=t.parse(D).toLinear()),(D.group===y||D.group===x)&&D.contains(a))return[new v(0)];let P={},F,I=function(n){n=t.expand(n,{expand_denominator:!0,expand_functions:!0});let r=n.clone();if(n.symbols)for(let i in n.symbols){if(!Object.hasOwn(n.symbols,i))continue;let s=n.symbols[i],c=s.getDenom();if(!c.isConstant(!0)&&n.isComposite()){let e=new v(0);return n.each(n=>{e=t.add(e,t.multiply(n,c.clone()))}),I(t.multiply(t.parse(n.multiplier),e))}let l=o(s,a),u=l[1].fname===e.Settings.SQRT,d=v.unwrapSQRT(l[1]),f=d.power.clone();if(!m(f)&&!f.equals(1/2)){if(Number(f.den)>1){if(u)return n=t.subtract(n,s.clone()),n=t.add(n,t.multiply(l[0].clone(),d)),I(n);let e=P[Number(f.den)];P[Number(f.den)]=e?e++:1}else if(f.sign()===-1){let e=t.parse(`${a}^${Math.abs(Number(f))}`),r=n;return r.each((n,i)=>{n.contains(a)&&(r.symbols[i]=t.multiply(n,e.clone()))}),P={},I(t.parse(r))}else if(s.group===b){let n=e.Utils.arrayMin(e.Utils.keys(s.symbols).map(Number));if(n<0){let e=t.parse(`${a}^${Math.abs(n)}`),i=new v(0);return r.each(n=>{i=t.add(i,t.multiply(n.clone(),e.clone()))},!0),i}}}}return n},L=function(e){let n=new v(0),r=new v(0);return e.each(e=>{e.contains(a,!0)?n=t.add(n,e.clone()):r=t.subtract(r,e.clone())}),[n,r]};if(k.inverseFunctionSolve=function(e,n,r){let i=o(n.args[0],a);
2649if(i[1].group===y)return t.divide(t.symfunction(e,[t.divide(r,t.parse(n.multiplier))]),i[0])},D=I(D),D.equals(0))return[D];let ee=e.Utils.keys(P);if(ee.length===1&&(F=ee[0],D.each((n,r)=>{if(n.contains(a)){let i=o(n,a),s=i[1],c=s.power;c.den.gt(1)&&(s.power=c.multiply(new e.Frac(F)),D.symbols[r]=t.multiply(s,i[0]))}}),D=t.parse(D)),g(k.sqrtSolve(D,a)),N===1)if(D.isPoly(!0)){let i=new l.Factors;if(s.factorInner(D,i),i.getNumberSymbolics()>1)for(let e in i.factors)Object.hasOwn(i.factors,e)&&g(j(i.factors[e],a));else{let i=e.Utils.getCoeffs(D,a),o=i.length-1,c=!1;if(M[0]===a){if(O(i,t=>t.group!==e.groups.N)){let t=e.Algebra.proots(D);O(t,t=>!e.Utils.isInt(t))&&(c=!0,t.forEach(e=>{g(new v(e))}))}if(!c)if(n=t.parse(n),n instanceof e.Equation&&(n=n.toLHS()),o===1)g(t.divide(i[0],i[1].negate()));else if(o===2)g(t.expand(k.quad.apply(void 0,i)));else if(o===3){let e=[];s.factorInner(n),e=[],e.length>0?g(e):g(k.cubic.apply(void 0,i))}else r.proots(D).map(g)}}}else{let t=D.hasTrig(),n=k.getPoints(D,.1),r=k.getPoints(D,.05),a=k.getPoints(D,.01,!0),o=e.Utils.arrayUnique(n.concat(r).concat(a)).sort((e,t)=>e-t),s,l,u,d=_(D.clone()),f=[];for(s=0;s<o.length;s++){if(l=o[s],u=k.bisection(l,d),typeof u>`u`){f.push(l);continue}g(u,t)}o=f;let p=_(i.diff(D.clone())),m=o[0];for(s=0;s<o.length;s++)l=o[s],g(k.Newton(l,d,p,m),t),m=l;c.sort((e,t)=>{let n=e.text(`decimals`),r=t.text(`decimals`),i=Number(n),a=Number(r);return isNaN(i)&&isNaN(a)?n.localeCompare(r):isNaN(i)&&!isNaN(a)?-1:!isNaN(i)&&isNaN(a)?1:i-a}),c=c.map(e=>e.isConstant()?new v(Number(Number(e).toPrecision(15))):e),c=c.filter((e,t,n)=>{let r=Number(Number(e).toPrecision(15)),i=Number(n[t-1]);return t===0||isNaN(r)||isNaN(i)?!0:Math.abs(r-i)>=w.EPSILON})}else if(!D.hasFunc(a)&&D.isComposite())try{let n=s.factorInner(D.clone()),r=t.expand(t.parse(n)),i=t.expand(D.clone()),o=t.subtract(r,i),l=!0;if(o.equals(0)||(l=!1),l&&n.group===x)n.each(e=>{g(j(e,a))});else{let r=e.Utils.getCoeffs(D,a);switch(r.length-1){case 0:{let n=L(D),r=n[0],i=n[1];if(r.group===e.groups.EX){let n=e.Settings.LOG,a=`${n}((${i})/(${r.multiplier}))/(${n}(${r.value})*${r.power.multiplier})`;g(t.parse(a))}break}case 1:g(t.divide(r[0],r[1].negate()));break;case 2:g(k.quad.apply(void 0,r));break;case 3:g(k.cubic.apply(void 0,r));break;case 4:g(k.quartic.apply(void 0,r));break;default:g(k.csolve(D,a)),c.length===0&&g(k.divideAndConquer(D,a))}c.length===0&&g(j(n,a,c,d))}}catch(e){if(e.message===`timeout`)throw e}else try{let n=k.rewrite(D,null,a),r=n[0],i=n[1];if(r.group===C)if(r.fname===`abs`)r.args[0].toString()===a&&g([i.clone(),i.negate()]);else if(r.fname===`sin`)g(k.inverseFunctionSolve(`asin`,r,i));else if(r.fname===`cos`)g(k.inverseFunctionSolve(`acos`,r,i));else if(r.fname===`tan`)g(k.inverseFunctionSolve(`atan`,r,i));else if(r.fname===e.Settings.LOG){let e=o(r.args[0],a),n=e[1];n.group===y&&(i=t.divide(t.subtract(t.pow(r.args.length>1?r.args[1]:new v(`e`),t.divide(i,t.parse(r.multiplier))),e[3]),e[0]),g(j(new E(n,i).toLHS(),a)))}else g(t.subtract(r,i));else{let e=new E(r,i).toLHS();if(e.equals(D))throw Error(`Stopping. No stop condition exists`);g(j(e,a))}}catch(n){if(n.message===`timeout`)throw n;if(D.group===x)g(0);else if(D.group===S){let n=L(D),r=n[0],i=n[1];if(r.group===e.groups.EX&&r.value===a){let e=r.power.clone().invert();g(t.pow(i,e))}}}if(F&&(c=c.map(e=>t.pow(e,new v(F)))),m(n)){let e={};c=c.filter(t=>{try{return e[a]=t,Number(u(n,e)),!0}catch(e){if(e.message===`timeout`)throw e;return!1}})}return c}n.register([{name:`solveEquations`,parent:`nerdamer`,numargs:-1,visible:!0,build(){return j}},{name:`solve`,parent:`Solve`,numargs:2,visible:!0,build(){return e.Solve.solve}},{name:`setEquation`,parent:`Solve`,numargs:2,visible:!0,build(){return D}}]),n.updateAPI()})()}),XW=HW((e,t)=>{var n=typeof globalThis<`u`&&globalThis.nerdamer?globalThis.nerdamer:void 0;typeof t<`u`&&n===void 0&&(n=KW(),qW(),JW()),(function(){let e=n.getCore(),t=e.PARSER,{NerdamerSymbol:r,Vector:i,Algebra:a,Calculus:o}=e,{format:s,isVector:c,isArray:l,isSymbol:u}=e.Utils,{S:d,EX:f,CP:p,PL:m,CB:h,FN:g}=e.groups;e.Settings.Laplace_integration_depth=40;function _(e){return u(e.power)&&(e.power.group===d||e.power.group===h)}r.prototype.findFunction=function(e){if(this.group===g&&this.fname===e)return this.clone();let t;if(this.symbols){for(let n in this.symbols)if(Object.hasOwn(this.symbols,n)&&(t=this.symbols[n].findFunction(e),t))break}return t};let v=e.Extra={version:`1.4.2`,LaPlace:{transform(n,i,a){n=n.clone(),i=i.toString(),n=r.unwrapSQRT(n,!0);let c,l=n.stripVar(i),u=n.group;if(n=t.divide(n,l.clone()),n.isConstant()||!n.contains(i,!0))c=t.parse(s(`({0})/({1})`,n,a));else if(u===d&&e.Utils.isInt(n.power)){let e=String(n.power);c=t.parse(s(`factorial({0})/({1})^({0}+1)`,e,a))}else if(n.group===d&&n.power.equals(1/2))c=t.parse(s(`sqrt(pi)/(2*({0})^(3/2))`,a));else if(n.isComposite())c=new r(0),n.each(e=>{c=t.add(c,v.LaPlace.transform(e,i,a))},!0);else if(n.isE()&&_(n)){let e=n.power.stripVar(i);c=t.parse(s(`1/(({1})-({0}))`,e,a))}else if(n.group===g&&[`sin`,`cos`,`sinh`,`cosh`].indexOf(n.fname)!==-1&&(n.args[0].group===d||n.args[0].group===h)){let e=n.args[0].stripVar(i);switch(n.fname){case`sin`:c=t.parse(s(`({0})/(({1})^2+({0})^2)`,e,a));break;case`cos`:c=t.parse(s(`({1})/(({1})^2+({0})^2)`,e,a));break;case`sinh`:c=t.parse(s(`({0})/(({1})^2-({0})^2)`,e,a));break;case`cosh`:c=t.parse(s(`({1})/(({1})^2-({0})^2)`,e,a));break}}else{let s=e.Settings.integration_depth<e.Settings.Laplace_integration_depth,l;s&&(l=e.Settings.integration_depth,e.Settings.integration_depth=e.Settings.Laplace_integration_depth),e.Utils.block(`PARSE2NUMBER`,()=>{let e=i,s=n.sub(i,e),l=t.parse(`e^(-${a}*${e})*${s}`);if(c=o.integrate(l,e),c.hasIntegral?.()){c=t.symfunction(`laplace`,[n,t.parse(String(i)),t.parse(String(a))]);return}
2649c=c.sub(i,0),c=t.expand(t.multiply(c,new r(-1))),c=c.sub(e,i)},!1),c=e.Utils.block(`PARSE2NUMBER`,()=>t.parse(c),!0),s&&(e.Settings.integration_depth=l)}return t.multiply(c,l)},inverse(n,i,o){let c=n.clone();return e.Utils.block(`POSITIVE_MULTIPLIERS`,()=>{let l;if(n.group===h&&(n=a.PartFrac.partfrac(t.expand(n),i)),n.group===d||n.group===h||n.isComposite()){let c,u,f,g,_,y,b,x,S=n.multiplier.clone();n.toUnitMultiplier();let C=n.getNum(),w=n.getDenom().toUnitMultiplier();w.group===p||w.group===m?(u=w.power.clone(),w.toLinear()):u=new e.Frac(1);let T=i.toString(),E=e.Utils.decompose_fn(w,T,!0);e.Utils.decompose_fn(t.expand(C.clone()),T,!0),C.multiplier=C.multiplier.multiply(S);let D=function(){l=t.multiply(l,C),l.multiplier=l.multiplier.multiply(n.multiplier),l=t.divide(l,E.a)};if((w.group===d||w.group===h)&&E.x.value===T&&E.b.equals(0)&&e.Utils.isInt(E.x.power))c=E.x.power-1,x=e.Math2.factorial(c),l=t.divide(t.pow(t.parse(String(o)),new r(c)),new r(x)),D();else if(w.group===p&&u.equals(1)){if(E.x.group===e.groups.PL&&a.degree(w).equals(2)){let n=a.sqComplete(w,T),r=e.Utils.getU(w);f=e.Utils.decompose_fn(n.a,T,!0).b;let i=v.LaPlace.inverse(t.parse(`1/((${r})^2+(${n.c}))`),r,String(o));l=t.multiply(i,t.parse(`(${S})*e^(-(${f})*(${o}))`))}else if(E.x.isLinear()&&!C.contains(T))o=t.divide(t.parse(String(o)),E.a.clone()),c=u-1,x=c===0||c===1?`1`:`(${u}-1)!`,l=t.parse(s(`(({0})^({3}-1)*e^(-(({2})*({0}))/({1})))/(({4})*({1})^({3}))`,o,E.a,E.b,u,x)),D();else if(E.x.group===d&&E.x.power.equals(2))if(C.contains(T)){if(f=new r(1),C.group===h){let e=new r(1);C.each(n=>{n.contains(T)?e=t.multiply(e,n):f=t.multiply(f,n)}),C=e}b=e.Utils.decompose_fn(C,T,!0);let n=b.a,i=b.b,a=n.containsFunction(`sin`),c=n.containsFunction(`cos`),u=i.containsFunction(`cos`),d=i.containsFunction(`sin`);if(b.x.value===T&&b.x.isLinear()&&!(a&&u||c||d))l=t.parse(s(`(({1})*cos((sqrt(({2})*({3}))*({0}))/({2})))/({2})`,o,b.a,E.a,E.b));else if(a&&u){let e=n.findFunction?.(`sin`),r=i.findFunction?.(`cos`);if(e?.args?.[0].equals(r?.args?.[0])&&!e?.args?.[0].contains(T)){g=t.divide(i,r.toUnitMultiplier()).toString();let a=e.args[0].toString();_=E.b;let c=t.divide(n,e.toUnitMultiplier());y=`(({1})*({2})*cos({3})*sin(sqrt({4})*({0})))/sqrt({4})+({1})*sin({3})*({5})*cos(sqrt({4})*({0}))`,l=t.parse(s(y,o,f,g,a,_,c))}}}else l=t.parse(s(`(({1})*sin((sqrt(({2})*({3}))*({0}))/({2})))/sqrt(({2})*({3}))`,o,C,E.a,E.b))}else if(E.x.power.num&&E.x.power.num.equals(3)&&E.x.power.den.equals(2)&&C.contains(`sqrt(pi)`)&&!C.contains(T)&&C.isLinear())g=t.divide(C.clone(),t.parse(`sqrt(pi)`)),l=t.parse(s(`(2*({2})*sqrt({0}))/({1})`,o,E.a,g,C));else if(u.equals(2)&&E.x.power.equals(2))if(C.contains(T))if(b=e.Utils.decompose_fn(t.expand(C.clone()),T,!0),b.x.isComposite()){let n=[],i=C.collectSymbols(t=>{t=r.unwrapPARENS(t);let n=e.Utils.decompose_fn(t,T,!0);return n.symbol=t,n}).sort((e,t)=>{let n=e.x.value===T?e.x.power:0;return(t.x.value===T?t.x.power:0)-n});f=new r(-1);for(let e=0;e<i.length;e++){let r=i[e];r.x.value===T?n.push(r):f=t.multiply(f,r.symbol)}n[0].x.power.equals(2)&&n[1].x.power.equals(1)&&n[1].b.equals(0)&&!n[0].b.equals(0)&&(g=n[0].a.negate(),y=`-(({1})*({2})*({5})*({0})*sin((sqrt(({4})*({5}))*({0}))/({4})))/(2*({4})^2*sqrt(({4})*({5})))-(({1})*({3})*({0})*sin((sqrt(({4})*({5}))*({0}))/({4})))/(2*({4})*sqrt(({4})*({5})))+(({1})*({2})*cos((sqrt(({4})*({5}))*({0}))/({4})))/({4})^2`,l=t.parse(s(y,o,f,g,n[0].b,E.a,E.b)))}else b.x.isLinear()?(f=t.divide(b.a,new r(2)),y=`(({1})*({0})*sin((sqrt(({2})*({3}))*({0}))/({2})))/(({2})*sqrt(({2})*({3})))`,l=t.parse(s(y,o,f,E.a,E.b))):b.x.power.equals(2)&&(b.b.equals(0)?(f=t.divide(b.a,new r(2)),y=`(({1})*sin((sqrt(({2})*({3}))*({0}))/({2})))/(({2})*sqrt(({2})*({3})))+(({1})*({0})*cos((sqrt(({2})*({3}))*({0}))/({2})))/({2})^2`,l=t.parse(s(y,o,f,E.a,E.b))):(f=t.divide(b.a,new r(2)),_=b.b.negate(),y=`-((({2})*({4})-2*({1})*({3}))*sin((sqrt(({2})*({3}))*({0}))/({2})))/(2*({2})*({3})*sqrt(({2})*({3})))+(({4})*({0})*cos((sqrt(({2})*({3}))*({0}))/({2})))/(2*({2})*({3}))+(({1})*({0})*cos((sqrt(({2})*({3}))*({0}))/({2})))/({2})^2`,l=t.parse(s(y,o,f,E.a,E.b,_))));else f=t.divide(C,new r(2)),y=`(({1})*sin((sqrt(({2})*({3}))*({0}))/({2})))/(({3})*sqrt(({2})*({3})))-(({1})*({0})*cos((sqrt(({2})*({3}))*({0}))/({2})))/(({2})*({3}))`,l=t.parse(s(y,o,f,E.a,E.b));else n.isComposite()&&(u.equals(2)&&E.x.group===d?l=t.parse(`(${S})*(${o})*e^(-(${E.b})*(${o}))`):(l=new r(0),n=a.PartFrac.partfrac(t.expand(n),i),n.each(e=>{l=t.add(l,v.LaPlace.inverse(e,i,o))},!0)))}return l||=t.symfunction(`ilt`,[c,t.parse(String(i)),t.parse(String(o))]),l},!0)}},Statistics:{frequencyMap(e){let t={};for(let n=0,r=e.length;n<r;n++){let r=e[n].toString();t[r]||=0,t[r]++}return t},sort(e){return e.sort((e,n)=>((!e.isConstant()||!n.isConstant())&&t.error(`Unable to sort! All values must be numeric`),e.multiplier.subtract(n.multiplier)))},count(e){return new r(e.length)},sum(e,n){let i=new r(0);for(let a=0,o=e.length;a<o;a++){let o=e[a].clone();i=n?t.add(t.pow(t.subtract(o,n.clone()),new r(2)),i):t.add(o,i)}return i},mean(...e){return c(e[0])?v.Statistics.mean(...e[0].elements):t.divide(v.Statistics.sum(e),v.Statistics.count(e))},median(...n){let r;if(c(n[0]))return v.Statistics.median(...n[0].elements);try{let t=v.Statistics.sort(n),i=n.length;if(e.Utils.even(i)){let e=i/2;
2649r=v.Statistics.mean(t[e-1],t[e])}else r=t[Math.floor(i/2)]}catch(e){if(e.message===`timeout`)throw e;r=t.symfunction(`median`,n)}return r},mode(...n){let r;if(c(n[0]))return v.Statistics.mode(...n[0].elements);let i=v.Statistics.frequencyMap(n);if(e.Utils.keys(i).length===1)r=n[0];else{let n={};for(let e in i){if(!Object.hasOwn(i,e))continue;let t=i[e];if(t in n){let r=n[t];l(r)?r.push(e):n[t]=[e,n[t]]}else n[t]=e}let a=e.Utils.keys(n).map(e=>Number(e)),o=n[Math.max.apply(null,a)];r=l(o)?t.symfunction(`mode`,o.sort().map(e=>t.parse(e))):t.parse(o)}return r},gVariance(e,n){let r=v.Statistics.mean(...n),i=v.Statistics.sum(n,r);return t.multiply(e,i)},variance(...e){if(c(e[0]))return v.Statistics.variance(...e[0].elements);let n=t.divide(new r(1),v.Statistics.count(e));return v.Statistics.gVariance(n,e)},sampleVariance(...e){if(c(e[0]))return v.Statistics.sampleVariance(...e[0].elements);let n=t.divide(new r(1),t.subtract(v.Statistics.count(e),new r(1)));return v.Statistics.gVariance(n,e)},standardDeviation(...e){return c(e[0])?v.Statistics.standardDeviation(...e[0].elements):t.pow(v.Statistics.variance(...e),new r(1/2))},sampleStandardDeviation(...e){return c(e[0])?v.Statistics.sampleStandardDeviation(...e[0].elements):t.pow(v.Statistics.sampleVariance(...e),new r(1/2))},zScore(e,n,r){return t.divide(t.subtract(e,n),r)}},Units:{table:{foot:`12 inch`,meter:`100 cm`,decimeter:`10 cm`}}};n.register([{name:`laplace`,visible:!0,numargs:3,build(){return v.LaPlace.transform}},{name:`ilt`,visible:!0,numargs:3,build(){return v.LaPlace.inverse}},{name:`mean`,visible:!0,numargs:-1,build(){return v.Statistics.mean}},{name:`median`,visible:!0,numargs:-1,build(){return v.Statistics.median}},{name:`mode`,visible:!0,numargs:-1,build(){return v.Statistics.mode}},{name:`smpvar`,visible:!0,numargs:-1,build(){return v.Statistics.sampleVariance}},{name:`variance`,visible:!0,numargs:-1,build(){return v.Statistics.variance}},{name:`smpstdev`,visible:!0,numargs:-1,build(){return v.Statistics.sampleStandardDeviation}},{name:`stdev`,visible:!0,numargs:-1,build(){return v.Statistics.standardDeviation}},{name:`zscore`,visible:!0,numargs:3,build(){return v.Statistics.zScore}}]),n.updateAPI()})(),typeof t<`u`&&(t.exports=n)}),ZW=KW(),JW(),qW(),YW(),XW(),QW=ZW})),$W,eG,tG=e((()=>{$W=`lobe-calculator`,eG={base:`base`,calculate:`calculate`,defintegrate:`defintegrate`,differentiate:`differentiate`,evaluate:`evaluate`,execute:`execute`,integrate:`integrate`,limit:`limit`,solve:`solve`,sort:`sort`}})),nG,rG,iG,aG=e((()=>{Ne(),Mse(),Nwe(),Pwe(),tG(),nG=BW(RW),rG=class extends ye{identifier=$W;apiEnum=eG;evaluateMathExpression(e,t={}){try{return nG.parse(e).compile().evaluate(t)}catch(e){throw Error(`Failed to evaluate expression: ${e instanceof Error?e.message:`Unknown error`}`)}}formatResult(e,t){return typeof e==`number`?t===void 0?e.toString():e.toFixed(t):typeof e==`bigint`?e.toString():typeof e==`string`?e:nG.format(e,{precision:t||10})}convertNumber(e,t,n){let r=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ`.slice(0,t),i=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ`.slice(0,n),a=sl(r),o=sl(i),s=String(e).trim().toUpperCase(),c=s.indexOf(`.`);c!==-1&&(s=s.slice(0,Math.max(0,c)));let l=a.decodeBigInt(s);return o.encodeBigInt(l)}calculate=async e=>{try{let t=this.evaluateMathExpression(e.expression);if(t===void 0)return{content:`Cannot evaluate expression: "${e.expression}"`,error:{message:`Expression resulted in undefined`,type:`ValidationError`},success:!1};let n=this.formatResult(t,e.precision);return{content:n,state:{expression:e.expression,precision:e.precision,result:n},success:!0}}catch(e){let t=e;return{content:`Calculation error: ${t.message}`,error:{message:t.message,type:`CalculationError`},success:!1}}};evaluate=async e=>{try{let t=e.variables||{},n=this.evaluateMathExpression(e.expression,t);if(n===void 0)return{content:`Cannot evaluate expression: "${e.expression}"`,error:{message:`Expression resulted in undefined`,type:`ValidationError`},success:!1};let r=this.formatResult(n,e.precision);return{content:r,state:{expression:e.expression,precision:e.precision,result:r,variables:t},success:!0}}catch(e){let t=e;return{content:`Expression evaluation error: ${t.message}`,error:{message:t.message,type:`CalculationError`},success:!1}}};sort=async e=>{try{let{numbers:t,mode:n,precision:r,reverse:i}
2649=e;if(t.length<2)return{content:`At least 2 numbers are required for comparison`,error:{message:`Insufficient numbers for comparison`,type:`ValidationError`},success:!1};let a=t.map(e=>{let t=typeof e==`string`?parseFloat(e):e;if(isNaN(t))throw Error(`Invalid number: ${e}`);return t}),o=[...a].sort((e,t)=>i?t-e:e-t),s=e=>r===void 0?e.toString():e.toFixed(r),c=o.map(s),l=s(Math.max(...a)),u=s(Math.min(...a)),d;switch(n){case`largest`:d=l;break;case`smallest`:d=u;break;default:d=c}return{content:JSON.stringify(d),state:{largest:l,mode:n,originalNumbers:t,precision:r,result:d,reverse:i,smallest:u,sorted:c},success:!0}}catch(e){let t=e;return{content:`Comparison error: ${t.message}`,error:{message:t.message,type:`ComparisonError`},success:!1}}};base=async e=>{try{let{number:t,fromBase:n,toBase:r}=e;if(n<2||n>36||r<2||r>36)throw Error(`Base must be between 2 and 36`);let i=this.convertNumber(t,n,r);return{content:i,state:{convertedNumber:i,decimalValue:parseInt(String(t),n),originalBase:n,originalNumber:t,targetBase:r},success:!0}}catch(e){let t=e,n=t.message;return(t.message?.includes(`Cannot convert`)||t.message?.includes(`Invalid digit`))&&(n=`Invalid digit`),{content:`Base conversion error: ${n}`,error:{message:n,type:`ConversionError`},success:!1}}};solve=async e=>{try{let{equation:t,variable:n}=e,r;if(t.length===1){let e=n&&n.length>0?n[0]:`x`,i=QW.solve(t[0],e).toString();if(i===`[]`)return{content:`No solution found for the given equation`,error:{message:`No solution found`,type:`SolveError`},success:!1};r=i}else{let e;if(n&&n.length>0)e=n;else{let n=new Set;for(let e of t){let t=QW(e).variables();for(let e of t)e!==``&&n.add(e)}e=Array.from(n),e.length===0&&(e=[`x`])}let i=QW.solveEquations(t,e).toString().split(`,`),a={};for(let e=0;e<i.length;e+=2)e+1<i.length&&(a[i[e]]=i[e+1]);r=JSON.stringify(a,null,2)}return{content:r,state:{equation:t,result:r,variable:n},success:!0}}catch(e){let t=e;return{content:`Equation solver error: ${t.message}`,error:{message:t.message,type:`SolveError`},success:!1}}};differentiate=async e=>{try{let{expression:t,variable:n}=e,r=QW(`diff(${t}, ${n})`).toString();return{content:r,state:{expression:t,result:r,variable:n},success:!0}}catch(e){let t=e;return{content:`Differentiation error: ${t.message}`,error:{message:t.message,type:`DifferentiationError`},success:!1}}};integrate=async e=>{try{let{expression:t,variable:n}=e,r=QW(`integrate(${t}, ${n})`).toString();return{content:r,state:{expression:t,result:r,variable:n},success:!0}}catch(e){let t=e;return{content:`Integration error: ${t.message}`,error:{message:t.message,type:`IntegrationError`},success:!1}}};defintegrate=async e=>{try{let{expression:t,variable:n,lowerBound:r,upperBound:i}=e,a=QW(`integrate(${t}, ${n})`),o=QW(`${a.evaluate({[n]:i})} - ${a.evaluate({[n]:r})}`).toString();return{content:o,state:{expression:t,lowerBound:r,result:o,upperBound:i,variable:n},success:!0}}catch(e){let t=e;return{content:`Definite integration error: ${t.message}`,error:{message:t.message,type:`DefintegrationError`},success:!1}}};execute=async e=>{try{let{expression:t}=e,n=QW(t).toString();return{content:n,state:{expression:t,result:n},success:!0}}catch(e){let t=e;return{content:`Nerdamer execution error: ${t.message}`,error:{message:t.message,type:`NerdamerError`},success:!1}}};limit=async e=>{try{let{expression:t,variable:n,point:r}=e,i;i=r===void 0?`limit(${t}, ${n})`:`limit(${t}, ${n}, ${r})`;let a=QW(i).toString();return{content:a,state:{expression:t,point:r,result:a,variable:n},success:!0}}catch(e){let t=e;return{content:`Limit computation error: ${t.message}`,error:{message:t.message,type:`LimitError`},success:!1}}};getApiNames(){return Object.values(this.apiEnum)}hasApi(e){return Object.values(this.apiEnum).includes(e)}},iG=new rG})),Fwe=e((()=>{aG()})),oG,sG=e((()=>{oG=`You have access to a Calculator tool powered by mathjs and nerdamer, capable of comprehensive mathematical computations, base conversions, and symbolic equation solving.
2650
2651<core_capabilities>
26521. **calculate**: Direct math expressions and unit conversions
26532. **evaluate**: Complex expressions with variable substitution
26543. **sort**: Sort numbers (ascending/descending/largest/smallest)
26554. **base**: Convert between number bases (2-36)
26565. **solve**: Algebraic equations and systems of equations
26576. **differentiate**: Derivatives of mathematical expressions
26587. **integrate**: Indefinite integrals
26598. **defintegrate**: Definite integrals over specified intervals
26609. **execute**: Generic nerdamer expressions for symbolic math
266110. **limit**: Limits of expressions
2662</core_capabilities>
2663
2664<tool_selection>
2665- **calculate**: Best for simple calculations, functions, matrices, complex numbers, unit conversions
2666   - Examples: "2 + 3 * 4", "sqrt(16)", "sin(30 deg)", "5 cm to inch", "25 degC to degF"
2667   - Uses mathjs syntax exclusively
2668
2669- **evaluate**: Best for expressions with variables
2670   - Provide variables object: {"x": 5, "y": 3}
2671   - Example: Expression "x^2 + 2*x + 1" with x=5
2672
2673- **base**: Best for base conversions
2674   - Requires numeric bases (2-36)
2675   - Supports string or number inputs
2676   - Example: Convert "1010" from base 2 to base 10
2677
2678- **sort**: Best for sorting numbers
2679   - Parameters: numbers (array), mode (optional: "largest"|"smallest"|default), reverse (optional)
2680   - Returns sorted array or single value if mode specified
2681   - Example: sort({"numbers": [3.14, 2.718, 1.618], "mode": "largest"}) → "3.14"
2682
2683- **solve**: Best for equations and systems
2684   - CRITICAL: equation MUST be array (even for single)
2685   - variable is optional - auto-detects if omitted
2686   - Single: {"equation": ["x^2 - 5*x + 6 = 0"], "variable": ["x"]} → [2, 3]
2687   - System: {"equation": ["2*x+y=5", "x-y=1"], "variable": ["x", "y"]} → {"x": "2", "y": "1"}
2688   - Supports: linear, quadratic, cubic, polynomial, systems
2689
2690- **differentiate**: Best for computing derivatives
2691   - Parameters: expression, variable
2692   - Example: {"expression": "x^3", "variable": "x"} → "3*x^2"
2693
2694- **integrate**: Best for computing indefinite integrals
2695   - Parameters: expression, variable
2696   - Example: {"expression": "x^3", "variable": "x"} → "(1/4)*x^4"
2697
2698- **defintegrate**: Best for computing definite integrals over intervals
2699   - Parameters: expression, variable, lowerBound, upperBound
2700   - Example: {"expression": "x^2", "variable": "x", "lowerBound": 0, "upperBound": 1} → "1/3"
2701   - Supports numeric bounds and special values like "infinity", "-infinity", "pi"
2702
2703- **execute**: Best for generic nerdamer symbolic math expressions
2704   - Parameters: expression (any valid nerdamer expression)
2705   - Examples: {"expression": "expand((x+1)^2)"} → "x^2+2*x+1"
2706             {"expression": "factor(x^2-1)"} → "(x-1)*(x+1)"
2707             {"expression": "partfrac(1/(x^2-1))"} → "1/2/(x-1)-1/2/(x+1)"
2708             {"expression": "toTeX(x^2+2*x+1)"} → "x^{2}+2x+1"
2709             {"expression": "simplify(x^2+2*x-x)"} → "x^2+x"
2710
2711- **limit**: Best for computing limits
2712   - Parameters: expression, variable, point (optional: value or "infinity")
2713   - Example: {"expression": "sin(x)/x", "variable": "x", "point": "0"} → "1"
2714</tool_selection>
2715
2716<mathjs_syntax>
2717**Units** - Use these formats:
2718- Temperature: "25 degC to degF" (NOT °C/°F)
2719- Length: "5 cm to inch"
2720- Weight: "1 kg to lb"
2721- Speed: "100 km/h to mph"
2722- Volume: "1 liter to gallon"
2723
2724**Functions** - Follow mathjs names:
2725- Trig: sin(x), cos(x), tan(x) - use "deg" for degrees: sin(30 deg)
2726- Constants: pi, e, tau, phi
2727- Logs: log(x), log10(x), log2(x)
2728- Exp: exp(x), pow(x,y), sqrt(x)
2729
2730**Complex Numbers**:
2731- Imaginary unit: i
2732- Examples: sqrt(-1), 3+4i, complex(3,4)
2733
2734**Equations**:
2735- Power: x^2, x^3
2736- Multiplication: 2*x (explicit * required)
2737- Equality: x^2 - 5*x + 6 = 0
2738</mathjs_syntax>
2739
2740<response_format>
2741- Return results directly, no original input
2742- Unit conversions: include units
2743- Equations: array (single) or object (systems)
2744- Calculus: symbolic expression result
2745</response_format>
2746
2747<critical_rules>
27481. Use mathjs syntax for ALL calculations
27492. For solve: equation MUST be array (even for single)
27503. Temperature: use "degC"/"degF", not °C/°F
27514. Angles: use "deg" suffix for degrees
27525. Base conversions: use numeric bases (2, not "binary")
27536. For limits at specific values, specify point parameter
2754</critical_rules>
2755
2756<error_handling>
2757- Invalid expressions: explain specific error
2758- Missing variables: operation fails
2759- Base errors: verify bases 2-36 and valid digits
2760- Equation errors: may have no/infinite solutions or need more equations
2761- Calculus errors: expression too complex or unsupported
2762</error_handling>
2763`})),cG,lG=e((()=>{sG(),tG(),cG={api:[{description:`Calculate result of a mathematical expression.`,name:eG.calculate,parameters:{additionalProperties:!1,properties:{expression:{description:`Mathematical expression to calculate (e.g., "2 + 3 * 4", "sqrt(16)", "sin(30 deg)", "det([[1,2],[3,4]])", "5 cm to inch")`,type:`string`},precision:{description:`Number of decimal places for result (optional, defaults to 10)`,maximum:20,minimum:0,type:`number`}},required:[`expression`],type:`object`}},{description:`Evaluate a complex mathematical expression with variable support.`,name:eG.evaluate,parameters:{additionalProperties:!1,properties:{expression:{description:`Mathematical expression to evaluate (e.g., "x^2 + 2*x + 1", "det([[a,b],[c,d]])", "sqrt(a^2 + b^2)")`,type:`string`},precision:{description:`Number of decimal places for result (optional, defaults to 10)`,maximum:20,minimum:0,type:`number`},variables:{description:`Key-value pairs of variables to substitute in expression (e.g., {"x": 5, "r": 3})`,type:`object`}},required:[`expression`],type:`object`}},{description:`Sort multiple numbers with flexible output options (sorted array, largest value, or smallest value).`,name:eG.sort,parameters:{additionalProperties:!1,properties:{mode:{description:`Optional mode: "largest" returns only largest value; "smallest" returns only smallest value; if not specified, returns sorted array`,enum:[`largest`,`smallest`],type:`string`},numbers:{description:`Array of numbers to compare (e.g., ["3.14", "2.718", "1.618"] or [3.14, 2.718, 
27631.618])`,items:{type:[`string`,`number`]},minItems:2,type:`array`},precision:{description:`Number of decimal places for comparison results (optional, defaults to 10)`,maximum:20,minimum:0,type:`number`},reverse:{description:`Sort order: false (default) sorts ascending (smallest to largest); true sorts descending (largest to smallest)`,type:`boolean`}},required:[`numbers`],type:`object`}},{description:`Convert numbers between different number bases.`,name:eG.base,parameters:{additionalProperties:!1,properties:{fromBase:{description:`Source base of the input number (numeric value between 2-36)`,maximum:36,minimum:2,type:`number`},number:{description:`The number to convert (string or number, e.g., "1010", 1010, "77", "255", "FF", "Z")`,type:[`string`,`number`]},toBase:{description:`Target base for conversion (numeric value between 2-36)`,maximum:36,minimum:2,type:`number`}},required:[`number`,`fromBase`,`toBase`],type:`object`}},{description:`Differentiate a mathematical expression with respect to a variable.`,name:eG.differentiate,parameters:{additionalProperties:!1,properties:{expression:{description:`Mathematical expression to differentiate (e.g., "x^2", "sin(x)", "x^3 + 2*x + 1")`,type:`string`},variable:{description:`Variable to differentiate with respect to (e.g., "x", "y", "t")`,type:`string`}},required:[`expression`,`variable`],type:`object`}},{description:`Compute definite integral of a mathematical expression with respect to a variable over a given interval.`,name:eG.defintegrate,parameters:{additionalProperties:!1,properties:{expression:{description:`Mathematical expression to integrate (e.g., "x^2", "sin(x)", "exp(x)")`,type:`string`},lowerBound:{description:`Lower bound of integration (can be number, "0", "-infinity", etc.)`,oneOf:[{type:`string`},{type:`number`}]},upperBound:{description:`Upper bound of integration (can be number, "pi", "infinity", etc.)`,oneOf:[{type:`string`},{type:`number`}]},variable:{description:`Variable to integrate with respect to (e.g., "x", "y", "t")`,type:`string`}},required:[`expression`,`variable`,`lowerBound`,`upperBound`],type:`object`}},{description:`Integrate a mathematical expression with respect to a variable (indefinite integral).`,name:eG.integrate,parameters:{additionalProperties:!1,properties:{expression:{description:`Mathematical expression to integrate (e.g., "x^2", "sin(x)", "exp(x)")`,type:`string`},variable:{description:`Variable to integrate with respect to (e.g., "x", "y", "t")`,type:`string`}},required:[`expression`,`variable`],type:`object`}},{description:`Execute a generic nerdamer expression for symbolic math computations.`,name:eG.execute,parameters:{additionalProperties:!1,properties:{expression:{description:`Nerdamer expression to execute (e.g., "expand((x+1)^2)", "factor(x^2-1)", "partfrac(1/(x^2-1))")`,type:`string`}},required:[`expression`],type:`object`}},{description:`Compute the limit of a mathematical expression.`,name:eG.limit,parameters:{additionalProperties:!1,properties:{expression:{description:`Mathematical expression to compute limit for (e.g., "sin(x)/x", "x^2", "exp(-x)")`,type:`string`},point:{description:`Point at which to evaluate the limit (optional). If not specified, computes the limit as variable approaches the expression. Can be a specific value or "infinity" (e.g., "0", "1", "infinity")`,oneOf:[{type:`string`},{type:`number`}]},variable:{description:`Variable to compute limit with respect to (e.g., "x", "y", "t")`,type:`string`}},required:[`expression`,`variable`],type:`object`}},{description:`Solve algebraic equations or systems of equations symbolically.`,name:eG.solve,parameters:{additionalProperties:!1,properties:{equation:{description:`The equation(s) to solve. Single equation (e.g., ["x^2 + 2*x + 1 = 0"]) or system of equations (e.g., ["2*x+y=5", "x-y=1"])`,items:{type:`string`},type:`array`},variable:{description:`Variable(s) to solve for. For single equation: array with one variable (optional, defaults to ["x"], e.g., ["x"]). For system of equations: array of variables (e.g., ["x", "y"])`,items:{type:`string`},type:`array`}},required:[`equation`],type:`object`}}],identifier:$W,meta:{avatar:`🧮`,description:`Perform mathematical calculations, solve equations, and work with symbolic expressions`,readme:`Advanced mathematical calculator supporting basic arithmetic, algebraic equations, calculus operations, and symbolic math. Includes base conversion, equation solving, differentiation, integration, and more.`,title:`Calculator`},systemRole:oG,type:`builtin`}})),uG=e((()=>{Fwe(),lG(),sG(),tG()})),dG,fG=e((()=>{Hne(),dG=class{async listFiles(e){try{let t=await this.callService(`listLocalFiles`,e);if(!t.success)return this.errorOutput(t,{files:[],totalCount:0});let n=t.result?.files||[],r=t.result?.totalCount,i={files:n,totalCount:r};return{content:Lne({directory:e.directoryPath,files:n.map(e=>({isDirectory:e.isDirectory,name:e.name})),sortBy:e.sortBy,sortOrder:e.sortOrder,totalCount:r}),state:i,success:!0}}catch(e){return this.handleError(e)}}async readFile(e){try{let t=await this.callService(`readLocalFile`,e);if(!t.success)return this.errorOutput(t,{content:``,endLine:e.endLine,path:e.path,startLine:e.startLine});let n=t.result||{};if(n.isImage&&n.imageUrl){let t=n.filename||e.path,r=n.content||`[Image: ${t}]`;return{content:r,state:{content:r,filename:t,fileType:n.fileType,images:[{fileId:n.imageFileId,mediaType:n.fileType||`image/png`,url:n.imageUrl}],path:e.path},success:!0}}let r=n.content||``,i={charCount:n.charCount??r.length,content:r,endLine:e.endLine,fileType:n.fileType,filename:n.filename,loc:n.loc,path:e.path,startLine:e.startLine,totalCharCount:n.totalCharCount,totalLines:n.totalLineCount??n.totalLines};return{content:qne({content:r,lineRange:e.startLine!==void 0&&e.endLine!==void 0?[e.startLine,e.endLine]:void 0,path:e.path}),state:i,success:!0}}catch(e){return this.handleError(e)}}async writeFile(e){try{let t=await this.callService(`writeLocalFile`,e);if(!t.success)return this.errorOutput(t,{path:e.path,success:!1});let n={bytesWritten:t.result?.bytesWritten,path:e.path,success:!0};return{content:Wne({path:e.path,success:!0}),state:n,success:!0}}catch(e){return this.handleError(e)}}async editFile(e){try{let t=await this.callService(`editLocalFile`,e);if(!t.success)return this.errorOutput(t,{path:e.path,replacements:0});let n={diffText:t.result?.diffText,linesAdded:t.result?.linesAdded,linesDeleted:t.result?.linesDeleted,path:e.path,replacements:t.result?.replacements||0};return{content:Kne({filePath:e.path,linesAdded:n.linesAdded,linesDeleted:n.linesDeleted,replacements:n.replacements}),state:n,success:!0}}catch(e){return this.handleError(e)}}async searchFiles(e){try{let t=await this.callService(`searchLocalFiles`,e);if(!t.success)return this.errorOutput(t,{results:[],totalCount:0});let n=t.result?.results||t.result,r=Array.isArray(n)?n:[],i={results:r,totalCount:t.result?.totalCount||r.length};return{content:Bne(r.map(e=>({path:e.path}))),state:i,success:!0}}catch(e){return this.handleError(e)}}async moveFiles(e){try{let t=await this.callService(`moveLocalFiles`,e);if(!t.success)return this.errorOutput(t,{results:[],successCount:0,totalCount:e.operations.length});let n=t.result?.results||t.result,r=Array.isArray(n)?n:[],i={results:r,successCount:t.result?.successCount??r.filter(e=>e.success).length,totalCount:e.operations.length};return{content:Gne(r),state:i,success:!0}}catch(e){return this.handleError(e)}}async renameFile(e){try{let t=await this.callService(`renameLocalFile`,e);if(!t.success){let n=t.error?.message||t.result?.error;return{content:Rne({error:n,newName:e.newName,oldPath:e.oldPath,success:!1}),state:{error:n,newPath:``,oldPath:e.oldPath,success:!1},success:!0}}let n={error:t.result?.error,newPath:t.result?.newPath||``,oldPath:e.oldPath,success:!0};return{content:Rne({error:t.result?.error,newName:e.newName,oldPath:e.oldPath,success:!0}),state:n,success:!0}}catch(e){return this.handleError(e)}}async runCommand(e){try{let t=await this.callService(`runCommand`,e);if(!t.success)return this.errorOutput(t,{error:t.error?.message,exitCode:t.result?.exitCode??t.result?.exit_code,isBackgroun
2763d:e.background||!1,stderr:t.result?.stderr,stdout:t.result?.stdout,success:!1});let n=t.result||{},r=typeof n.success==`boolean`?n.success:t.success,i=n.outputFiles??n.output_files,a={commandId:n.commandId||n.shell_id,error:n.error,exitCode:n.exitCode??n.exit_code,isBackground:e.background||!1,output:n.output,outputFiles:i,stderr:n.stderr,stdout:n.stdout,success:r};return{content:Fne({error:n.error,exitCode:n.exitCode??n.exit_code,outputFiles:i,shellId:n.commandId||n.shell_id,stderr:n.stderr,stdout:n.stdout||n.output,success:r}),state:a,success:!0}}catch(e){return this.handleError(e)}}async getCommandOutput(e){try{let t=await this.callService(`getCommandOutput`,e);if(!t.success)return this.errorOutput(t,{error:t.error?.message,success:!1});let n=t.result||{},r=typeof n.success==`boolean`?n.success:t.success,i=n.outputFiles??n.output_files,a={durationMs:n.durationMs??n.duration_ms,error:n.error,exitCode:n.exitCode??n.exit_code,outputFiles:i,running:n.running??!1,stderr:n.stderr,stdout:n.stdout,success:r};return{content:Ine({durationMs:n.durationMs??n.duration_ms,error:n.error,exitCode:n.exitCode??n.exit_code,output:n.newOutput||n.output,outputFiles:i,stderr:n.stderr,stdout:n.stdout,success:r}),state:a,success:!0}}catch(e){return this.handleError(e)}}async killCommand(e){try{let t=await this.callService(`killCommand`,e);if(!t.success)return this.errorOutput(t,{commandId:e.commandId,error:t.error?.message,success:!1});let n=typeof t.result?.success==`boolean`?t.result.success:t.success,r={commandId:e.commandId,error:t.result?.error,success:n};return{content:Vne({error:t.result?.error,shellId:e.commandId,success:n}),state:r,success:!0}}catch(e){return this.handleError(e)}}async grepContent(e){try{let t=await this.callService(`grepContent`,e);if(!t.success)return this.errorOutput(t,{matches:[],pattern:e.pattern,totalMatches:0});let n=t.result||{},r=n.matches||[],i=n.totalMatches??n.total_matches??0,a={matches:r,pattern:e.pattern,totalMatches:i};return{content:zne({matches:r,totalMatches:i}),state:a,success:!0}}catch(e){return this.handleError(e)}}async globFiles(e){try{let t=await this.callService(`globLocalFiles`,e);if(!t.success)return this.errorOutput(t,{files:[],pattern:e.pattern,totalCount:0});let n=t.result?.files||[],r=t.result?.totalCount??t.result?.total_files??n.length,i={files:n,pattern:e.pattern,totalCount:r};return{content:Une({files:n,totalFiles:r}),state:i,success:!0}}catch(e){return this.handleError(e)}}handleError(e){return{content:e instanceof Error?e.message:String(e),error:e,success:!1}}errorOutput(e,t){return{content:e.error?.message||(e.error===void 0?void 0:JSON.stringify(e.error))||(typeof t?.stderr==`string`?t.stderr:void 0)||(typeof t?.error==`string`?t.error:void 0)||`[UNKNOWN_EXEC_ERROR] Tool execution failed`,state:t,success:!0}}}})),pG,mG,Iwe=e((()=>{fG(),Pe(),pG={editLocalFile:`editLocalFile`,getCommandOutput:`getCommandOutput`,globLocalFiles:`globFiles`,grepContent:`grepContent`,killCommand:`killCommand`,listLocalFiles:`listLocalFiles`,moveLocalFiles:`moveLocalFiles`,readLocalFile:`readLocalFile`,renameLocalFile:`renameLocalFile`,runCommand:`runCommand`,searchLocalFiles:`searchLocalFiles`,writeLocalFile:`writeFile`},mG=class extends dG{service;constructor(e){super(),this.service=e}async callService(e,t){let n=pG[e];if(!n)return{error:{message:`Unknown tool: ${e}`},result:null,success:!1};let r=this.denormalizeParams(e,t),i=this.service[n],a=await i(r);return this.normalizeResult(e,a)}denormalizeParams(e,t){switch(e){case`editLocalFile`:return{file_path:t.path,new_string:t.replace,old_string:t.search,replace_all:t.all};case`listLocalFiles`:return{limit:t.limit,path:t.directoryPath,sortBy:t.sortBy,sortOrder:t.sortOrder};case`moveLocalFiles`:return{items:t.operations?.map(e=>({newPath:e.destination,oldPath:e.source}))};case`renameLocalFile`:return{newName:t.newName,path:t.oldPath};case`getCommandOutput`:return{filter:t.filter,shell_id:t.commandId,timeout:t.timeout};case`killCommand`:return{shell_id:t.commandId};case`readLocalFile`:{let e=t.startLine!==void 0||t.endLine!==void 0?[t.startLine??0,t.endLine??200]:void 0;return{fullContent:t.fullContent,loc:e,path:t.path}}case`globLocalFiles`:return{limit:t.limit,pattern:t.pattern,scope:t.directory};case`grepContent`:return{...t,cwd:t.cwd??t.directory??t.path??t.scope};default:return t}}async readFiles(e){try{let{formatMultipleFiles:t}=await Ge(async()=>{let{formatMultipleFiles:e}=await import(`./fileSystem-DmAwavrR.js`).then(e=>(e.n(),e.t));return{formatMultipleFiles:e}},__vite__mapDeps([7,1])),n=await this.service.readLocalFiles(e);return{content:t(n),state:{filesContent:n},success:!0}}catch(e){return this.handleError(e)}}normalizeResult(e,t){switch(e){case`runCommand`:return{result:{error:t.error,exitCode:t.exit_code,output:t.output,commandId:t.shell_id,durationMs:t.duration_ms,outputFiles:t.output_files,stderr:t.stderr,stdout:t.stdout,success:t.success},success:t.success};case`getCommandOutput`:return{result:{durationMs:t.duration_ms,exitCode:t.exit_code,error:t.error,outputFiles:t.output_files,stderr:t.stderr,stdout:t.stdout,success:t.success},success:t.success};case`killCommand`:return{result:{error:t.error,success:t.success},success:t.success};case`grepContent`:return{error:t.error?{message:String(t.error)}:void 0,result:{matches:t.matches,totalMatches:t.total_matches},success:t.success};case`globLocalFiles`:return{error:t.error?{message:String(t.error)}:void 0,result:{files:t.files,totalCount:t.total_files},success:t.success};case`listLocalFiles`:return{result:{files:t.files,totalCount:t.totalCount},success:!0};case`readLocalFile`:return{result:{charCount:t.charCount,content:t.content,fileType:t.fileType,filename:t.filename,imageFileId:t.imageFileId,imageUrl:t.imageUrl,isImage:t.isImage,loc:t.loc,totalCharCount:t.totalCharCount,totalLineCount:t.totalLineCount},success:!0};case`writeLocalFile`:return{result:{bytesWritten:t.bytesWritten,success:t.success},success:t.success??!0};case`editLocalFile`:return{error:t.error?{message:String(t.error)}:void 0,result:{diffText:t.diffText,error:t.error,linesAdded:t.linesAdded,linesDeleted:t.linesDeleted,replacements:t.replacements},success:t.success};case`searchLocalFiles`:{let e=Array.isArray(t)?t:[];return{result:{results:e,totalCount:e.length},success:!0}}case`moveLocalFiles`:{let e=Array.isArray(t)?t:[];return{result:{results:e,successCount:e.filter(e=>e.success).length},success:!0}}case`renameLocalFile`:return{result:{error:t.error,newPath:t.newPath,success:t.success},success:t.success};default:return{result:t,success:!0}}}}})),hG=e((()=>{fG(),Iwe()})),gG,_G=e((()=>{hG(),gG=class extends dG{sandboxService;constructor(e){super(),this.sandboxService=e}async callService(e,t){return this.sandboxService.callTool(e,t)}async executeCode(e){try{let t=e.language||`python`,n=await this.callService(`executeCode`,{code:e.code,language:t}),r={error:n.result?.error,exitCode:n.result?.exitCode,language:t,output:n.result?.output,stderr:n.result?.stderr,success:n.success||!1};return n.success?{content:JSON.stringify(n.result),state:r,success:!0}:{content:n.error?.message||JSON.stringify(n.error),state:r,success:!0}}catch(e){return console.error(`executeCode error`,e),this.handleError(e)}}async exportFile(e){try{let t=e.path.split(`/`).pop()||`exported_file`,n=await this.sandboxService.exportAndUploadFile(e.path,t),r={downloadUrl:n.success&&n.url?n.url:``,fileId:n.fileId,filename:n.filename,mimeType:n.mimeType,path:e.path,size:n.size,success:n.success};return n.success?{content:`File exported successfully.\n\nFilename: ${t}\nDownload URL: ${n.url}`,state:r,success:!0}:{content:JSON.stringify({error:n.error?.message||`Failed to export file from sandbox`,filename:t,success:!1}),state:r,success:!0}}catch(e){return this.handleError(e)}}}})),vG,yG,bG,xG,SG,CG,wG=e((()=>{vG=`/mnt/data`,yG=e=>e.filter(e=>e.size==null||e.size<=104857600).slice(0,50),bG=e=>{if(typeof e!=`number`||!Number.isFinite(e)||e<=0)return``;let t=[`B`,`KB`,`MB`,`GB`],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return` (${r===0?n:Math.round(n*10)/10}${t[r]})`},xG=e=>{let t=[...e.split(/[/\\]/).pop()??``].filter(e=>{let t=e.codePointAt(0)??0;return t>31&&t!==127}).join(``).trim();return t.length>0?t:`file`},SG=e=>`${vG}/${xG(e)}`,CG=e=>{if(!e||e.length===0)return``;let t=new Set,n=[];for(let r of yG(e)){if(!r?.name)continue;let e=SG(r.name);t.has(e)||(t.add(e),n.push(`- ${e}${bG(r.size)}`))}return n.length===0?``:[`These user-uploaded files are pre-loaded and ready to use:`,...n].join(`
2764`)}})),TG,EG=e((()=>{wG(),TG=`You have access to a Cloud Sandbox that provides a secure, isolated environment for executing code and file operations. This sandbox runs on AWS Bedrock AgentC
2764ore and is completely separate from the user's local system.
2765
2766
2767<sandbox_environment>
2768**Important:** This is a CLOUD SANDBOX environment, NOT the user's local file system.
2769- Files created here are temporary and session-specific
2770- Each conversation topic has its own isolated session
2771- Sessions may expire after inactivity; files will be recreated if needed
2772- The sandbox has its own isolated file system starting at the root directory
2773- Commands will time out after 120 seconds by default
2774- **Default shell is /bin/sh** (typically dash or ash), NOT bash. The \`source\` command may not work as expected. If you need bash-specific features or \`source\`, wrap your command with bash: \`bash -c "source ~/.creds/env && your_command"\`
2775
2776**Credential Injection Locations:**
2777- Environment-based credentials (oauth, kv-env, kv-header) are written to \`~/.creds/env\`
2778- File-based credentials are extracted to \`~/.creds/files/{key}/{filename}\`
2779</sandbox_environment>
2780
2781
2782<uploaded_files>
2783Files the user uploaded in this conversation (attachments and session files) are automatically synced into \`${vG}\` when your sandbox session starts. If the user refers to a file they shared, look there first — do NOT ask them to re-upload. Run \`listFiles\` on \`${vG}\` to see everything that is available.
2784{{sandbox_uploaded_files}}
2785</uploaded_files>
2786
2787
2788<preinstalled_software>
2789**IMPORTANT: Prefer Pre-installed Software**
2790The sandbox comes with pre-installed software and libraries. **Always prioritize using these pre-installed tools** when they can solve the user's problem, rather than installing additional packages.
2791
2792**Base Image:** lobehubbot/python-node:latest (Debian-based)
2793
2794**Programming Languages & Runtimes:**
2795- Python (with pip)
2796- Node.js (with npm)
2797- Bun
2798- Bash/Shell
2799
2800**Package Managers:**
2801- pip (Python)
2802- npm / pnpm (Node.js)
2803
2804**System Tools (apt):**
2805- curl, wget, unzip, jq - Common utilities
2806- build-essential - gcc/g++/make compilation toolchain
2807- FFmpeg - Audio/video processing
2808- LibreOffice - Office document processing
2809- Pandoc - Document format conversion
2810- poppler-utils - PDF tools (pdftotext, pdftoppm, etc.)
2811- GitHub CLI (gh)
2812
2813**JS/TS Tools:**
2814- marp-cli - Markdown to PPT/PDF presentation
2815- Chromium (installed via Playwright, also used by marp-cli)
2816- Playwright - Browser automation
2817
2818**Python Libraries (Pre-installed):**
2819- Data Science/ML: numpy, pandas, scipy, scikit-learn
2820- Visualization: matplotlib, plotly
2821- Data Processing: pyyaml, toml, python-dotenv, Pillow, opencv-python-headless
2822- File Processing: openpyxl, xlrd, python-docx, PyPDF2, reportlab
2823- Async: aiofiles, anyio
2824- Testing: pytest
2825- Server: fastapi, uvicorn, pydantic
2826
2827**Fonts:**
2828- Noto Sans CJK - Chinese/Japanese/Korean sans-serif font
2829- Noto Serif CJK - Chinese/Japanese/Korean serif font
2830
2831**NOT Available (do not attempt to use):**
2832- Tesseract (OCR) - Not installed
2833- Puppeteer - Not installed, use Playwright instead
2834- mermaid-cli - Not installed
2835- seaborn - Not installed
2836
2837**Installation Guidelines:**
2838- Only install additional packages when pre-installed software cannot fulfill the requirement
2839- When Python libraries are already available, use them directly without pip install
2840- For document generation, prioritize LibreOffice and Pandoc before Python libraries
2841</preinstalled_software>
2842
2843
2844<core_capabilities>
2845You have access to the following tools for interacting with the cloud sandbox:
2846
2847
2848**File Operations:**
28491.  **listFiles**: Lists files and directories in a specified path within the sandbox.
28502.  **readFile**: Reads the content of a specified file, optionally within a line range.
28513.  **writeFile**: Write content to a specific file. Creates parent directories if needed.
28524.  **editFile**: Performs exact string replacements in files. Must read the file first before editing.
28535.  **moveFiles**: Moves or renames files and directories. To rename, keep the same directory and change the filename in \`newPath\`.
28546.  **exportFile**: Export a file from the sandbox to allow user download.
2855
2856
2857**Code Execution:**
28587.  **executeCode**: Execute code directly in the sandbox. Supports Python (default), JavaScript, and TypeScript.
2859
2860**Shell Commands:**
28618.  **runCommand**: Execute shell commands with timeout control. Supports background execution.
28629.  **getCommandOutput**: Retrieve output from running background commands.
286310. **killCommand**: Terminate a running background shell command by its ID.
2864
2865
2866**Search & Find:**
286711. **searchFiles**: Search for files based on keywords and criteria.
286812. **grepContent**: Search for content within files using regex patterns.
286913. **globFiles**: Find files matching glob patterns (e.g., "**/*.js").
2870</core_capabilities>
2871
2872
2873<workflow>
28741. Understand the user's request regarding code execution or file operations.
28752. Select the appropriate tool(s) for the task.
28763. Execute operations in the sandbox environment.
28774. Present results clearly, noting that files exist in the cloud sandbox.
28785. **Export files by default** - see export_policy below for when to export vs skip.
2879</workflow>
2880
2881
2882<export_policy>
2883**CRITICAL: Default Export Behavior**
2884
2885**Core Principle: Export by Default**
2886When code execution produces any output files (documents, images, data, etc.), you SHOULD automatically export them using \`exportFile\` unless the user explicitly indicates they don't need the file.
2887
2888**When to Export (DEFAULT - most cases):**
2889- User asks to "create/make/generate/write/build" something
2890- User asks to "export/download/save" something
2891- User asks to "convert/transform" files
2892- User asks to "process/analyze" data and expects output files
2893- User asks to "draw/plot/visualize" something (export the chart/image)
2894- User provides data and expects a result file
2895- Any task that produces a meaningful output file the user would want
2896
2897**Trigger Phrases that REQUIRE export:**
2898- English: "create", "make", "generate", "export", "download", "save", "convert", "help me [verb] a [file]", "I need/want a [file]"
2899- Chinese: "创建", "生成", "制作", "导出", "下载", "保存", "转换", "帮我做/写/画", "我要/需要一个"
2900
2901**When NOT to Export (exceptions only):**
2902- User explicitly says "just run it" / "帮我跑一下" / "run this" / "execute only"
2903- User says "don't export" / "不用导出" / "just check" / "只是看看"
2904- User only asks to "read", "view", "check", or "debug" without expecting output files
2905- Temporary/intermediate files (cache, temp data, __pycache__, etc.)
2906- Configuration files meant to stay in sandbox (.env, config.json for sandbox use)
2907- User is iterating/debugging and hasn't finalized the result yet
2908
2909**Execution Pattern:**
29101. Execute the requested operation
29112. If output files are produced → **call exportFile immediately**
29123. Present download links prominently in the response
29134. Confirm what was created and exported
2914
2915**Example Response Format:**
2916✅ Successfully created [filename]
2917📥 Download link: [export URL]
2918📄 File details: [size, format, brief description]
2919
2920**Export File Types (common outputs):**
2921- Documents: PDF, DOCX, XLSX, PPTX, TXT, MD, CSV, ODT, ODS, ODP
2922- Images: PNG, JPG, JPEG, SVG, GIF
2923- Code files: PY, JS, HTML, CSS, JSON, XML, YAML
2924- Archives: ZIP, TAR, GZ
2925- Data files: CSV, JSON, XML, PARQUET
2926</export_policy>
2927
2928
2929<tool_usage_guidelines>
2930- For listing directory contents: Use 'listFiles' with the target directory path.
2931- For reading a file: Use 'readFile' with the file path. Optionally specify startLine/endLine for partial reads.
2932- For writing files: Use 'writeFile' with the file path and content. Set createDirectories: true if needed.
2933- For editing files: Use 'editFile'. Always read the file first to verify content before editing.
2934- For executing code directly: Use 'executeCode' with the code and optional language (python/javascript/typescript). This is preferred over runCommand for simple code execution.
2935- For running shell commands: Use 'runCommand' to execute shell commands like \`pip install package\` or complex shell operations.
2936- For background tasks: Set background: true in runCommand, then use getCommandOutput to check progress.
2937- For searching files: Use 'searchFiles' for filename search, 'grepContent' for content search, 'globFiles' for pattern matching.
2938- For exporting files: Use 'exportFile' with the file path to generate a download URL for the user. **Export by default when any output files are produced - only skip when user explicitly asks to just run/check something.**
2939</tool_usage_guidelines>
2940
2941
2942<python_guidelines>
2943When executing Python code:
2944
2945
2946**Using Pre-installed Libraries:**
2947- **Always check if required libraries are pre-installed** (see preinstalled_software section)
2948- Data Science/ML: numpy, pandas, scipy, scikit-learn, matplotlib, plotly are already available
2949- Data Processing: pyyaml, toml, python-dotenv, Pillow, opencv-python-headless are already available
2950- File Processing: openpyxl, xlrd, python-docx, PyPDF2, reportlab are already available
2951- **Skip pip install** for pre-installed libraries - use them directly
2952- Only use \`pip install\` for libraries NOT in the pre-installed list
2953
2954
2955**Visualization with Matplotlib:**
2956- matplotlib 3.10.8 is pre-installed - use directly without installation
2957- Never use seaborn library
2958- Give each chart its own distinct plot (no subplots)
2959- Never set specific colors unless explicitly asked by the user
2960- Save plots to files using \`plt.savefig('output.png')\` then **automatically export for user download**
2961
2962
2963**Generating Document Files:**
2964You MUST use the following libraries for each supported file format:
2965- **PDF**: Use \`reportlab\` (pre-installed) - prioritize \`reportlab.platypus\` over canvas for text content
2966- **DOCX**: Use \`python-docx\` (pre-installed)
2967- **XLSX**: Use \`openpyxl\` (pre-installed)
2968- **PPTX**: Use \`python-pptx\` (requires pip install)
2969- **CSV**: Use \`pandas\` (pre-installed)
2970- **ODS/ODT/ODP**: Use \`odfpy\` (requires pip install)
2971
2972For libraries NOT pre-installed: Install with \`pip install <package-name>\` before use.
2973**After successful generation, automatically export the document file.**
2974
2975
2976**Chinese Text in PDFs:**
2977When generating PDFs with Chinese text, you MUST:
29781. Register the Chinese font: \`pdfmetrics.registerFont(TTFont('STSong', 'STSong.ttf'))\`
29792. Apply the 'STSong' font style to all text elements containing Chinese characters
2980</python_guidelines>
2981
2982
2983<session_behavior>
2984- Your sandbox session is automatically managed per conversation topic
2985- If a session expires, it will be automatically recreated
2986- Files from previous sessions may not persist; recreate them as needed
2987- The sessionExpiredAndRecreated flag in responses indicates if this occurred
2988</session_behavior>
2989
2990
2991<security_considerations>
2992- This sandbox is isolated from the user's local system for security
2993- Confirm with the user before performing destructive operations
2994- Be cautious with shell commands that have significant side effects
2995- The sandbox has resource limits (CPU, memory, execution time)
2996</security_considerations>
2997
2998
2999<response_format>
3000- When showing file paths, clarify they are in the cloud sandbox
3001- When displaying file contents, format code appropriately with syntax highlighting
3002- When showing command output, preserve formatting and line breaks
3003- Always indicate success/failure status clearly
3004- **When files are auto-exported per the rules, prominently display download links with clear labels**
3005- Use visual indicators (✅ 📥 📄) to make exported files stand out
3006</response_format>
3007`})),DG,OG=e((()=>{DG={editFile:`editFile`,executeCode:`executeCode`,exportFile:`exportFile`,getCommandOutput:`getCommandOutput`,globFiles:`globFiles`,grepContent:`grepContent`,killCommand:`killCommand`,listFiles:`listFiles`,moveFiles:`moveFiles`,readFile:`readFile`,runCommand:`runCommand`,searchFiles:`searchFiles`,writeFile:`writeFile`}})),Lwe=e((()=>{})),Rwe=e((()=>{})),zwe=e((()=>{})),kG=e((()=>{OG(),Lwe(),Rwe(),zwe()})),AG,jG,MG=e((()=>{EG(),kG(),AG=`lobe-cloud-sandbox`,jG={api:[{description:`Execute code directly in the sandbox environment. Supports Python, JavaScript, and TypeScript. Returns execution output, errors, and exit code.`,humanIntervention:`required`,name:DG.executeCode,parameters:{properties:{description:{description:`A brief description of what this code does (required for user understanding)`,type:`string`},language:{description:`Programming language: python (default), javascript, or typescript`,enum:[`python`,`javascript`,`typescript`],type:`string`},code:{description:`The code to execute`,type:`string`}},required:[`description`,`language`,`code`],type:`object`}},{description:`List files and folders in a specified directory. Input should be a path. Output is a JSON array of file/folder names.`,name:DG.listFiles,parameters:{properties:{directoryPath:{description:`The directory path to list`,type:`string`}},required:[`directoryPath`],type:`object`}},{description:`Read the content of a specific file. Input should be the file path. Output is the file content as a string.`,name:DG.readFile,parameters:{properties:{endLine:{description:`End line number (1-based, inclusive)`,type:`number`},path:{description:`The file path to read`,type:`string`},startLine:{description:`Start line number (1-based)`,type:`number`}},required:[`path`],type:`object`}},{description:`Search for files within the sandbox based on keywords and filter options.`,name:DG.searchFiles,parameters:{properties:{directory:{description:`Directory to search in`,type:`string`},fileType:{description:`File type/extension filter`,type:`string`},keyword:{description:`Filename keyword filter`,type:`string`},modifiedAfter:{description:`Modified time lower bound (ISO date string)`,type:`string`},modifiedBefore:{description:`Modified time upper bound (ISO date string)`,type:`string`}},required:[`directory`],type:`object`}},{description:`Moves or renames multiple files/directories. Input is an array of operations with source and destination paths.`,humanIntervention:`required`,name:DG.moveFiles,parameters:{properties:{operations:{description:`A list of move operations to perform.`,items:{properties:{destination:{description:`The target path for the file/directory.`,type:`string`},source:{description:`The current path of the file/directory to move.`,type:`string`}},required:[`source`,`destination`],type:`object`},type:`array`}},required:[`operations`],type:`object`}},{description:`Write content to a specific file. Input should be the file path and content. Overwrites existing file or creates a new one.`,humanIntervention:`required`,name:DG.writeFile,parameters:{properties:{content:{description:`The content to write`,type:`string`},createDirectories:{description:`Whether to create parent directories if they do not exist`,type:`boolean`},path:{description:`The file path to write to`,type:`string`}},required:[`path`,`content`],type:`object`}},{description:`Perform exact string replacements in files. Must read the file first before editing.`,humanIntervention:`required`,name:DG.editFile,parameters:{properties:{all:{description:`Replace all occurrences (default: false)`,type:`boolean`},path:{description:`The absolute path to the file to modify`,type:`string`},replace:{description:`The text to replace with (must differ from search)`,type:`string`},search:{description:`The exact text to search for`,type:`string`}},required:[`path`,`search`,`replace`],type:`object`}},{defaultTimeoutMs:12e4,description:`Execute a shell command and return its output. Supports both synchronous and background execution with timeout control.`,humanIntervention:`required`,name:DG.runCommand,parameters:{properties:{description:{description:`A brief description of what this code does (required for user understanding)`,type:`string`},background:{description:`Set to true to run command in background and return commandId`,type:`boolean`},command:{description:`The shell command to execute`,type:`string`},timeout:{description:`Timeout in milliseconds (default: 120000ms)`,type:`number`}},required:[`description`,`command`],type:`object`}},{description:`Retrieve output from a running or completed background shell command. Returns only new output since the last check.`,name:DG.getCommandOutput,parameters:{properties:{commandId:{description:`The ID of the background command to retrieve output from`,type:`string`}},required:[`commandId`],type:`object`}},{description:`Kill a running background shell command by its ID.`,name:DG.killCommand,parameters:{properties:{commandId:{description:`The ID of the background command to kill`,type:`string`}},required:[`commandId`],type:`object`}},{description:`Search for content within files using regex patterns. Supports various output modes and filtering options.`,name:DG.grepContent,parameters:{properties:{directory:{description:`Directory to search in`,type:`string`},filePattern:{description:`File name pattern filter (e.g., "*.ts")`,type:`string`}
3007,pattern:{description:`The regex pattern to search for`,type:`string`},recursive:{description:`Whether to search recursively (default: true)`,type:`boolean`}},required:[`pattern`,`directory`],type:`object`}},{description:`Find files matching glob patterns. Supports standard glob syntax like "**/*.js" or "src/**/*.ts".`,name:DG.globFiles,parameters:{properties:{directory:{description:`The base directory to search in (defaults to current working directory)`,type:`string`},pattern:{description:`The glob pattern to match files against (e.g. "**/*.js", "*.{ts,tsx}")`,type:`string`}},required:[`pattern`],type:`object`}},{description:`Export a file from the sandbox to cloud storage. The file will be uploaded to a pre-signed URL and can be downloaded by the user.`,name:DG.exportFile,parameters:{properties:{path:{description:`The path of the file in the sandbox to export (e.g., "./output/result.csv")`,type:`string`}},required:[`path`],type:`object`}}],identifier:AG,meta:{avatar:`💻`,description:`Execute code, run commands, and manage files in a secure cloud environment`,readme:`Execute Python, JavaScript, and TypeScript code in an isolated cloud environment. Run shell commands, manage files, search content with regex, and export results securely.`,title:`Cloud Sandbox`},systemRole:TG,type:`builtin`}})),NG=e((()=>{_G(),MG(),EG(),kG(),wG()})),PG,FG,IG,LG=e((()=>{PG={connectComposioService:`connectComposioService`,initiateOAuthConnect:`initiateOAuthConnect`,injectCredsToSandbox:`injectCredsToSandbox`,saveCreds:`saveCreds`},FG=[`github`,`linear`,`microsoft`,`notion`,`twitter`],IG=FG.join(`, `)})),Bwe=e((()=>{Wt(),LG()})),RG,zG,BG,VG,HG,UG,WG,Vwe=e((()=>{RG=e=>{let t={file:[],"kv-env":[],"kv-header":[],oauth:[]};for(let n of e)t[n.type].push(n);return t},zG=e=>{let t=e.description?` - ${e.description}`:``,n=e.ownerType===`user`?` [shared by ${e.ownerDisplayName??`a workspace member`}]`:e.ownerType===`organization`?` [workspace credential]`:``;return`  - ${e.name} (key: ${e.key})${t}${n}`},BG=e=>{if(e.length===0)return`No credentials configured yet. Guide the user to set up credentials when needed.`;let t=RG(e),n=[];return t[`kv-env`].length>0&&n.push(`**Environment Variables:**\n${t[`kv-env`].map(zG).join(`
3008`)}`),t[`kv-header`].length>0&&n.push(`**HTTP Headers:**\n${t[`kv-header`].map(zG).join(`
3009`)}`),t.oauth.length>0&&n.push(`**OAuth Connections:**\n${t.oauth.map(zG).join(`
3010`)}`),t.file.length>0&&n.push(`**File Credentials:**\n${t.file.map(zG).join(`
3011`)}`),n.join(`
3012
3013`)},VG=(e,t)=>{let n=BG(t.creds);return e.replaceAll(`{{CREDS_LIST}}`,n).replaceAll(`{{SETTINGS_URL}}`,t.settingsUrl)},HG=(e,t)=>e.filter(e=>!t.has(e.identifier)),UG=(e,t,n)=>e.filter(e=>!t.has(e.identifier)&&!n.has(e.identifier)).map(e=>({identifier:e.identifier,name:e.label})),WG=(e,t)=>{if(e.length===0&&t.length===0)return``;let n=[];if(e.length>0){let t=e.map(e=>`  - ${e.name} (identifier: ${e.identifier}) — Authorized via Composio OAuth. Use ${e.identifier} tools directly.`).join(`
3014`);n.push(`**Connected Composio Services (authorized, use tools directly):**\n${t}`)}if(t.length>0){let e=t.map(e=>`  - ${e.name} (identifier: ${e.identifier}) — Use \`connectComposioService\` to connect.`).join(`
3015`);n.push(`**Available Composio Services (not yet connected):**\n${e}`)}return n.join(`
3016
3017`)}})),GG,KG=e((()=>{GG=`You have access to a LobeHub Credentials Tool. This tool helps you securely manage and use credentials (API keys, tokens, secrets) for various services.
3018
3019<session_context>
3020Current user: {{username}}
3021Session date: {{session_date}}
3022Sandbox mode: {{sandbox_enabled}}
3023</session_context>
3024
3025<available_credentials>
3026{{CREDS_LIST}}
3027</available_credentials>
3028
3029<credential_types>
3030- **kv-env**: Environment variable credentials (API keys, tokens). Injected as environment variables.
3031- **kv-header**: HTTP header credentials. Injected as request headers.
3032- **oauth**: OAuth-based authentication. Provides secure access to third-party services.
3033- **file**: File-based credentials (certificates, key files).
3034</credential_types>
3035
3036<core_responsibilities>
30371. **Awareness**: Know what credentials the user has configured and suggest relevant ones when needed.
30382. **Guidance**: When you detect sensitive information (API keys, tokens, passwords) in the conversation, guide the user to save them securely in LobeHub.
30393. **Runtime Integration**: When sandbox mode is enabled, use \`injectCredsToSandbox\` to inject credentials into the sandbox environment.
30404. **Ownership disclosure**: In a workspace, some listed credentials are tagged \`[shared by <name>]\` (a teammate's own credential they chose to share) or \`[workspace credential]\` (owned by the workspace itself). Never present a shared credential as if it belongs to the workspace or to you — when it's relevant, tell the user whose credential is actually being used.
3041</core_responsibilities>
3042
3043<tooling>
3044- **initiateOAuthConnect**: Start OAuth authorization flow for third-party services. Returns an authorization URL for the user to click.
3045- **injectCredsToSandbox**: Inject credentials into the sandbox environment. Only available when s
3045andbox mode is enabled.
3046- **saveCreds**: Save new credentials securely. Use when user wants to store sensitive information.
3047  - Parameters: \`key\` (unique identifier, lowercase with hyphens), \`name\` (display name), \`type\` ("kv-env" or "kv-header"), \`values\` (object of key-value pairs, NOT a string), \`description\` (optional)
3048  - Example: \`saveCreds({ key: "openai", name: "OpenAI API Key", type: "kv-env", values: { "OPENAI_API_KEY": "sk-xxx" } })\`
3049  - For multiple env vars: \`saveCreds({ key: "my-config", name: "My Config", type: "kv-env", values: { "APP_URL": "http://localhost:3000", "DB_URL": "postgres://..." } })\`
3050  - IMPORTANT: \`values\` must be a JSON object (Record<string, string>), NOT a raw string. Each environment variable should be a separate key-value pair in the object.
3051</tooling>
3052
3053<oauth_providers>
3054LobeHub provides built-in OAuth integrations for the following services:
3055- **github**: GitHub repository and code management. Connect to access repositories, create issues, manage pull requests.
3056- **linear**: Linear issue tracking and project management. Connect to create/manage issues, track projects.
3057- **microsoft**: Microsoft Outlook Calendar. Connect to view/create calendar events, manage meetings.
3058- **notion**: Notion workspace and knowledge management. Connect to create pages, search content, update databases, and organize workspace knowledge.
3059- **twitter**: X (Twitter) social media. Connect to post tweets, manage timeline, engage with audience.
3060
3061When a user mentions they want to use one of these services, use \`initiateOAuthConnect\` to provide them with an authorization link. After they authorize, the credential will be automatically saved and available for use.
3062</oauth_providers>
3063
3064<security_guidelines>
3065- **Never display credential values** in your responses. Refer to credentials by their key or name only.
3066- **Prompt for saving**: When you see users share sensitive information like API keys or tokens, suggest:
3067  "I noticed you shared a sensitive credential. Would you like me to save it securely in LobeHub? This way you can reuse it without sharing it again."
3068- **Explain the benefit**: Let users know that saved credentials are encrypted and can be easily reused across conversations.
3069</security_guidelines>
3070
3071<credential_saving_triggers>
3072Proactively suggest saving credentials when you detect:
3073- API keys (e.g., "sk-...", "api_...", patterns like "OPENAI_API_KEY=...")
3074- Access tokens or bearer tokens
3075- Secret keys or private keys
3076- Database connection strings with passwords
3077- OAuth client secrets
3078- Any explicitly labeled secrets or passwords
3079
3080When suggesting to save, always:
30811. Explain that the credential will be encrypted and stored securely
30822. Ask the user for a meaningful name and optional description
30833. Use the \`saveCreds\` tool to store it with \`values\` as a JSON object (e.g., \`{ "API_KEY": "sk-xxx" }\`), NOT a raw string
3084</credential_saving_triggers>
3085
3086<sandbox_integration>
3087**Only applies when sandbox mode is enabled (current value: {{sandbox_enabled}}).**
3088
3089When sandbox mode is enabled and you need to run code that requires credentials:
30901. Check if the required credential is in the available credentials list
30912. Use \`injectCredsToSandbox\` to inject the credential before running code
30923. The credential will be available as an environment variable or file in the sandbox
30934. Never pass credential values directly in code - always use environment variables or file paths
3094
3095**Important Notes:**
3096- \`executeCode\` runs in an isolated process that may NOT have access to injected environment variables. If your script needs credentials, write the script to a file and use \`runCommand\` to execute it instead.
3097
3098**Credential Storage Locations:**
3099- **Environment-based credentials** (oauth, kv-env, kv-header): Written to \`~/.creds/env\` file
3100- **File-based credentials** (file): Extracted to \`~/.creds/files/\` directory
3101
3102**Environment Variable Naming:**
3103- **oauth**: \`{{KEY}}_ACCESS_TOKEN\` (e.g., \`GITHUB_ACCESS_TOKEN\`)
3104- **kv-env**: Each key-value pair becomes an environment variable as defined (e.g., \`OPENAI_API_KEY\`)
3105- **kv-header**: \`{{KEY}}_{{HEADER_NAME}}\` format (e.g., \`GITHUB_AUTH_HEADER_AUTHORIZATION\`)
3106
3107**File Credential Usage:**
3108- File credentials are extracted to \`~/.creds/files/{key}/{filename}\`
3109- Example: A credential with key \`gcp-service-account\` and file \`credentials.json\` → \`~/.creds/files/gcp-service-account/credentials.json\`
3110- Use the file path directly in your code (e.g., \`GOOGLE_APPLICATION_CREDENTIALS=~/.creds/files/gcp-service-account/credentials.json\`)
3111</sandbox_integration>
3112
3113<composio_integrations>
3114{{COMPOSIO_SERVICES_LIST}}
3115</composio_integrations>
3116
3117<composio_guidelines>
3118- **Composio integrations** are OAuth connections managed by the C
3118omposio platform for third-party services (e.g., Gmail, Google Calendar, Slack).
3119- For **connected** Composio services: Use the corresponding tools directly. Do NOT ask users for API keys, tokens, or credentials — the authorization is already handled by Composio.
3120- For **available but not connected** services: Use \`connectComposioService\` to initiate the OAuth connection flow via Composio.
3121- Composio credentials **CANNOT** be injected via \`injectCredsToSandbox\` — they are tool-only authorizations managed externally by Composio.
3122- If a user asks about a service that matches a connected Composio integration, always prefer using the Composio tools over asking the user for manual credentials.
3123</composio_guidelines>
3124
3125<response_expectations>
3126- When credentials are relevant, mention which ones are available and how they can be used.
3127- When accessing credentials, briefly explain why access is needed.
3128- When guiding users to save credentials, be helpful but not pushy.
3129- Keep credential-related discussions concise and security-focused.
3130</response_expectations>`})),qG,JG,YG=e((()=>{KG(),LG(),qG=`lobe-creds`,JG={api:[{description:`Connect a Composio integration service via OAuth. Use this to authorize access to third-party services managed by the Composio platform (e.g., Gmail, Google Calendar, Slack). Check the available Composio services in the credentials context before calling this.`,name:PG.connectComposioService,parameters:{additionalProperties:!1,properties:{service:{description:`The Composio service identifier to connect (e.g., "gmail", "google-calendar"). See the available Composio services list in the credentials context.`,type:`string`}},required:[`service`],type:`object`}},{description:`Initiate OAuth connection flow for a LobeHub Skill provider (e.g., GitHub, Linear, Microsoft Outlook, Notion, Twitter/X). Returns an authorization URL that the user must click to authorize. After authorization, the credential will be automatically saved.`,name:PG.initiateOAuthConnect,parameters:{additionalProperties:!1,properties:{provider:{description:`The OAuth provider ID. Available providers: ${IG}`,enum:[...FG],type:`string`}},required:[`provider`],type:`object`}},{description:`Inject credentials into the sandbox environment as environment variables. Only available when sandbox mode is enabled — do NOT call this on desktop/local.`,name:PG.injectCredsToSandbox,parameters:{additionalProperties:!1,properties:{keys:{description:`Array of credential keys to inject into the sandbox`,items:{type:`string`},type:`array`}},required:[`keys`],type:`object`}},{description:`Save a new credential securely. Use this when the user wants to store sensitive information like API keys, tokens, or secrets. The credential will be encrypted and stored securely.`,name:PG.saveCreds,parameters:{additionalProperties:!1,properties:{description:{description:`Optional description explaining what this credential is used for`,type:`string`},key:{description:`Unique identifier key for the credential (e.g., "openai", "github-token"). Use lowercase with hyphens.`,pattern:`^[a-z][a-z0-9-]*$`,type:`string`},name:{description:`Human-readable display name for the credential`,type:`string`},type:{description:`The type of credential being saved`,enum:[`kv-env`,`kv-header`],type:`string`},values:{additionalProperties:{type:`string`},description:`Key-value pairs of the credential. For kv-env, the key should be the environment variable name (e.g., {"OPENAI_API_KEY": "sk-..."})`,type:`object`}},required:[`key`,`name`,`type`,`values`],type:`object`}}],identifier:qG,meta:{avatar:`🔐`,description:`Manage user credentials for authentication, environment variable injection, and API verification. Use this tool when tasks require API keys, OAuth tokens, or secrets - such as calling third-party APIs, authenticating with external services, or injecting credentials into sandbox environments.`,title:`Credentials`},systemRole:GG,type:`builtin`}})),XG=e((()=>{Bwe(),Vwe(),YG(),KG(),LG()})),ZG,QG=e((()=>{ZG=`You have access to a Knowledge Base tool with comprehensive capabilities for browsing files, searching knowledge, and managing knowledge bases.
3131
3132<important_file_behavior>
3133**Most user files live in the resource library, NOT in knowledge bases.**
3134When a user uploads files (images, PDFs, documents, etc.), they go into the resource library by default. Most users never manually organize files into knowledge bases. Therefore:
3135- When the user says "find my file", "look for that PDF", "check my uploads", "我的文件", or references ANY file — **always use listFiles first**.
3136- Only use listKnowledgeBases / searchKnowledgeBase when the user explicitly mentions "knowledge base", "知识库", or wants semantic search over organized collections.
3137- If listFiles doesn't find the file, then fall back to searching knowledge bases.
3138</important_file_behavior>
3139
3140<core_capabilities>
3141**File Browsing (start here for most file requests):**
31421. List and search files in the resource library (listFiles) — **default for finding user files**
31432. Get detailed metadata of a specific file (getFileDetail)
3144
3145**Knowledge Base Discovery & Search:**
31463. List all knowledge bases (listKnowledgeBases)
31474. View a knowledge base's details and files (viewKnowledgeBase)
31485. Semantic vector search across knowledge bases (searchKnowledgeBase)
31496. Read full file content (readKnowledge)
3150
3151**Knowledge Base Management:**
31527. Create a new knowledge base (createKnowledgeBase)
31538. Delete a knowledge base (deleteKnowledgeBase)
31549. Create a document in a knowledge base (createDocument)
315510. Add existing files to a knowledge base (addFiles)
315611. Remove files from a knowledge base (removeFiles)
3157</core_capabilities>
3158
3159<workflow>
3160**When the user asks about files (most common):**
31611. Use listFiles to find files — filter by category (images/documents/audios/videos) or search by name
31622. Use getFileDetail to inspect a specific file's metadata
31633. Use readKnowledge to read the file content if needed
31644. If the file should be added to a knowledge base for semantic search, use addFiles
3165
3166**For knowledge base semantic search (user explicitly requests it):**
31671. Use listKnowledgeBases to see what's available
31682. Use viewKnowledgeBase to browse a specific knowledge base's contents
31693. Use searchKnowledgeBase to find relevant files via semantic search
31704. Use readKnowledge to get full content from the most relevant files
31715. Synthesize and cite sources
3172
3173**For knowledge base management:**
31741. Use listKnowledgeBases to check existing knowledge bases
31752. Use createKnowledgeBase to create a new one if needed
31763. Use createDocument to add text/markdown content directly
31774. Use addFiles/removeFiles to manage file associations
3178</workflow>
3179
3180<tool_selection_guidelines>
3181**File browsing (use first for most file requests):**
3182- **listFiles**: **Primary tool for finding user files.** Browse the resource library where most user-uploaded files live. Supports category filter (images, documents, audios, videos, websites), search by name, and pagination. Use this whenever the user asks about their files.
3183- **getFileDetail**: Get detailed metadata of a specific file by ID. Works for any file regardless of knowledge base association.
3184
3185**Knowledge base search (use when user explicitly asks for KB or semantic search):**
3186- **listKnowledgeBases**: Discover available knowledge bases. Returns name, description, and ID for each.
3187- **viewKnowledgeBase**: See all files/documents in a specific knowledge base. Provides file IDs, types, and sizes.
3188- **searchKnowledgeBase**: Search across knowledge base content. Returns two result types:
3189  - \`<files>\` — uploaded files matched by semantic vector search at chunk-level (file_* IDs). Resolve pronouns to concrete entities (BAD: "What does it do?" → GOOD: "What does the authentication system do?").
3190  - \`<documents>\` — inline notes/documents (created via createDocument) matched by full-text BM25 search at document-level (docs_* IDs). Works well with literal keyword queries.
3191  - Adjust topK (5-100, default: 15) per result type.
3192- **readKnowledge**: Read complete content by ID. Accepts both file IDs (file_*) for uploaded files and document IDs (docs_*) for inline documents. Use the IDs returned by searchKnowledgeBase or viewKnowledgeBase.
3193
3194**Knowledge base management:**
3195- **createKnowledgeBase**: Create a new knowledge base with a name and optional description.
3196- **deleteKnowledgeBase**: Permanently remove a knowledge base. Use with caution.
3197- **createDocument**: Add text/markdown notes directly to a knowledge base without file upload.
3198- **addFiles**: Associate existing files (by ID) with a knowledge base. Use to organize resource library files into knowledge bases.
3199- **removeFiles**: Dissociate files from a knowledge base (files are not deleted, only unlinked).
3200</tool_selection_guidelines>
3201
3202<search_strategy_guidelines>
3203- **Coreference Resolution**: Always resolve pronouns and references to concrete entities before searching
3204  - Replace "it", "that", "this", "them" with the actual entity names
3205  - Use full names instead of abbreviations when first searching
3206  - Include relevant context in the query itself
3207- Formulate clear and specific search queries
3208- For broad topics, start with a general query then refine if needed
3209- You can perform multiple searches with different queries if needed
3210- Review relevance scores and excerpts to select the most pertinent files
3211</search_strategy_guidelines>
3212
3213<reading_strategy_guidelines>
3214- Read only the most relevant files to avoid information overload
3215- Prioritize files with higher relevance scores
3216- If search results show many relevant files, read them in batches
3217</reading_strategy_guidelines>
3218
3219<citation_requirements>
3220- Always cite source files when providing information
3221- Reference file names clearly in your response
3222- Help users understand which knowledge base files support your answers
3223</citation_requirements>
3224
3225<best_practices>
3226- When the user mentions any file, always try listFiles first — most files live in the resource library
3227- Only use listKnowledgeBases or searchKnowledgeBase when the user explicitly wants knowledge base features
3228- Use searchKnowledgeBase for targeted information retrieval
3229- Don't read files blindly — review search results first
3230- When creating documents, use clear titles and well-structured content
3231- Maintain accuracy — only cite information actually present in the files
3232</best_practices>
3233
3234<error_handling>
3235- If search returns no results: try reformulating with different keywords or broader terms
3236- If file reading fails: inform the user and work with successfully retrieved files
3237- If a knowledge base is not found: use listKnowledgeBases to verify available IDs
3238</error_handling>
3239`})),$G,eK,tK=e((()=>{$G=`lobe-knowledge-base`,eK={addFiles:`addFiles`,createDocument:`createDocument`,createKnowledgeBase:`createKnowledgeBase`,deleteKnowledgeBase:`deleteKnowledgeBase`,getFileDetail:`getFileDetail`,listFiles:`listFiles`,listKnowledgeBases:`listKnowledgeBases`,readKnowledge:`readKnowledge`,removeFiles:`removeFiles`,searchKnowledgeBase:`searchKnowledgeBase`,viewKnowledgeBase:`viewKnowledgeBase`}})),nK,rK=e((()=>{QG(),tK(),nK={api:[{description:`List files from the user's resource library. This is where most user-uploaded files live (images, PDFs, documents, etc.). Files here are NOT in any knowledge base yet. Supports filtering by category and search query. **Use this first when the user asks about their files.**`,name:eK.listFiles,parameters:{properties:{category:{description:`Filter by file category. Options: "images", "documents", "audios", "videos", "websites". Omit to list all categories.`,enum:[`images`,`documents`,`audios`,`videos`,`websites`],type:`string`},limit:{default:50,description:`Number of files to return per page (default: 50).`,maximum:100,minimum:1,type:`number`},offset:{default:0,description:`Offset for pagination (default: 0).`,minimum:0,type:`number`},q:{description:`Search query to filter files by name.`,type:`string`}},required:[],type:`object`}},{description:`Get detailed metadata of a specific file by ID, including name, type, size, URL, and timestamps. Works for any file in the system regardless of knowledge base association.`,name:eK.getFileDetail,parameters:{properties:{id:{description:`The file ID to get details for.`,type:`string`}},required:[`id`],type:`object`}},{description:`List all knowledge bases available to the current user. Returns name, description, and metadata for each knowledge base. Use this only when the user explicitly asks about knowledge bases.`,name:eK.listKnowledgeBases,parameters:{properties:{},required:[],type:`object`}}
3239,{description:`View a specific knowledge base and list its files and documents with pagination. Returns the knowledge base metadata along with a page of items.`,name:eK.viewKnowledgeBase,parameters:{properties:{id:{description:`The ID of the knowledge base to view.`,type:`string`},limit:{default:50,description:`Number of items to return per page (default: 50, max: 100).`,maximum:100,minimum:1,type:`number`},offset:{default:0,description:`Offset for pagination (default: 0).`,minimum:0,type:`number`}},required:[`id`],type:`object`}},{description:`Search the knowledge base. Returns two result types: (1) <files> — uploaded files matched by semantic vector search at chunk-level (file_* IDs); (2) <documents> — inline notes/documents matched by full-text BM25 search at document-level (docs_* IDs). Use this to discover relevant content first, then call readKnowledge with the returned IDs to get full content. Resolve pronouns/references to concrete entities for best vector recall.`,name:eK.searchKnowledgeBase,parameters:{properties:{query:{description:`The search query to find relevant information. Be specific and use concrete entities. IMPORTANT: Resolve all pronouns and references (like "it", "that", "this") to actual entity names before searching, as this uses semantic vector search which works best with concrete terms.`,type:`string`},topK:{default:15,description:`Number of top relevant chunks to return (default: 15). Each file will include the most relevant chunks.`,maximum:100,minimum:5,type:`number`}},required:[`query`],type:`object`}},{description:`Read the full content of specific resources from the knowledge base. Accepts both file IDs (file_*) for uploaded files and document IDs (docs_*) for inline documents created via createDocument. Use this after searchKnowledgeBase or viewKnowledgeBase to get complete content. You can read multiple resources at once.`,name:eK.readKnowledge,parameters:{properties:{fileIds:{description:`Array of resource IDs to read. Accepts file IDs (file_*) and document IDs (docs_*) returned by searchKnowledgeBase or viewKnowledgeBase.`,items:{type:`string`},type:`array`}},required:[`fileIds`],type:`object`}},{description:`Create a new knowledge base. Returns the ID of the newly created knowledge base.`,name:eK.createKnowledgeBase,parameters:{properties:{description:{description:`Optional description of the knowledge base.`,type:`string`},name:{description:`Name of the knowledge base to create.`,type:`string`}},required:[`name`],type:`object`}},{description:`Delete a knowledge base by ID. This will remove the knowledge base and its file associations. Use with caution.`,name:eK.deleteKnowledgeBase,parameters:{properties:{id:{description:`The ID of the knowledge base to delete.`,type:`string`}},required:[`id`],type:`object`}},{description:`Create a new text/markdown document directly inside a knowledge base. This is useful for adding notes, summaries, or any text content without uploading a file.`,name:eK.createDocument,parameters:{properties:{content:{description:`The text or markdown content of the document.`,type:`string`},knowledgeBaseId:{description:`The ID of the knowledge base to create the document in.`,type:`string`},parentId:{description:`Optional parent folder ID. Omit to place at root level.`,type:`string`},title:{description:`Title of the document.`,type:`string`}},required:[`knowledgeBaseId`,`title`,`content`],type:`object`}},{description:`Add existing files to a knowledge base by their file IDs. The files must already exist in the system.`,name:eK.addFiles,parameters:{properties:{fileIds:{description:`Array of file IDs to add to the knowledge base.`,items:{type:`string`},type:`array`},knowledgeBaseId:{description:`The ID of the knowledge base to add files to.`,type:`string`}},required:[`knowledgeBaseId`,`fileIds`],type:`object`}},{description:`Remove files from a knowledge base by their file IDs. This only removes the association; the files themselves are not deleted.`,name:eK.removeFiles,parameters:{properties:{fileIds:{description:`Array of file IDs to remove from the knowledge base.`,items:{type:`string`},type:`array`},knowledgeBaseId:{description:`The ID of the knowledge base to remove files from.`,type:`string`}},required:[`knowledgeBaseId`,`fileIds`],type:`object`}}
3239],identifier:$G,meta:{avatar:`📚`,description:`Search uploaded documents and domain knowledge via semantic vector search — for persistent, reusable reference`,title:`Knowledge Base`},systemRole:ZG,type:`builtin`}})),iK=e((()=>{rK(),QG(),tK()})),aK,oK,sK,cK=e((()=>{Mi(),aK=(e,t=!1)=>({completed:t,context:e.content??void 0,createdAt:e.createdAt.toISOString(),description:e.description??``,goal:e.title??``,id:e.id,updatedAt:e.updatedAt.toISOString()}),oK=e=>{let t=e?.metadata?.todos;return t?Array.isArray(t)?t:typeof t==`object`&&Array.isArray(t.items)?t.items:[]:[]},sK=class{service;constructor(e){this.service=e}async resolveExistingTodos(e){return e.currentTodos?e.currentTodos:e.topicId?oK(await this.service.findPlanByTopic(e.topicId)):[]}async syncTodosToPlan(e,t){try{let n=await this.service.findPlanByTopic(e);if(!n)return;await this.service.updatePlanMetadata(n.id,{...n.metadata,todos:t})}catch(e){console.warn(`Failed to sync todos to plan:`,e)}}createTodos=async(e,t)=>{let n=e.items?e.items:e.adds?e.adds.map(e=>({status:`todo`,text:e})):[];if(n.length===0)return{content:`No items provided to add.`,success:!1};let r=[...await this.resolveExistingTodos(t),...n],i=new Date().toISOString(),a=n.map(e=>`- ${e.text}`).join(`
3240`),o=`✅ Added ${n.length} item${n.length>1?`s`:``}:\n${a}`,s={items:r,updatedAt:i};return t.topicId&&await this.syncTodosToPlan(t.topicId,s),{content:o+`
3241
3242`+Fi(r,i),state:{createdItems:n.map(e=>e.text),todos:s},success:!0}};updateTodos=async(e,t)=>{let{operations:n}=e;if(!n||n.length===0)return{content:`No operations provided.`,success:!1};let r=[...await this.resolveExistingTodos(t)],i=[];for(let e of n)switch(e.type){case`add`:e.text&&(r.push({status:`todo`,text:e.text}),i.push(`Added: "${e.text}"`));break;case`update`:if(e.index!==void 0&&e.index>=0&&e.index<r.length){let t={...r[e.index]};e.newText!==void 0&&(t.text=e.newText),e.status!==void 0&&(t.status=e.status),r[e.index]=t,i.push(`Updated item ${e.index+1}`)}break;case`remove`:if(e.index!==void 0&&e.index>=0&&e.index<r.length){let t=r.splice(e.index,1)[0];i.push(`Removed: "${t.text}"`)}break;case`complete`:e.index!==void 0&&e.index>=0&&e.index<r.length&&(r[e.index]={...r[e.index],status:`completed`},i.push(`Completed: "${r[e.index].text}"`));break;case`processing`:e.index!==void 0&&e.index>=0&&e.index<r.length&&(r[e.index]={...r[e.index],status:`processing`},i.push(`In progress: "${r[e.index].text}"`));break}let a=new Date().toISOString(),o=i.length>0?`🔄 Applied ${i.length} operation${i.length>1?`s`:``}:\n${i.map(e=>`- ${e}`).join(`
3243`)}`:`No operations applied.`,s={items:r,updatedAt:a};return t.topicId&&await this.syncTodosToPlan(t.topicId,s),{content:o+`
3244
3245`+Fi(r,a),state:{todos:s},success:!0}};clearTodos=async(e,t)=>{let{mode:n}=e,r=await this.resolveExistingTodos(t);if(r.length===0){let e=new Date().toISOString();return{content:`Todo list is already empty.
3246
3247`+Fi([],e),state:{clearedCount:0,mode:n,todos:{items:[],updatedAt:e}},success:!0}}let i,a,o;n===`all`?(a=r.length,i=[],o=`🧹 Cleared all ${a} item${a>1?`s`:``} from todo list.`):(i=r.filter(e=>e.status!==`completed`),a=r.length-i.length,o=a===0?`No completed items to clear.`:`🧹 Cleared ${a} completed item${a>1?`s`:``}.`);let s=new Date().toISOString(),c={items:i,updatedAt:s};return t.topicId&&await this.syncTodosToPlan(t.topicId,c),{content:o+`
3248
3249`+Fi(i,s),state:{clearedCount:a,mode:n,todos:c},success:!0}};createPlan=async(e,t)=>{try{if(t.signal?.aborted)return{stop:!0,success:!1};if(!t.topicId)return{content:`Cannot create plan: no topic selected`,success:!1};let{goal:n,description:r,context:i}=e,a=aK(await this.service.createPlan({content:i??``,description:r,goal:n,topicId:t.topicId}));return a.context=i,{content:`📋 Created plan: "${a.goal}"\n\nYou can view this plan in the Portal sidebar.`,state:{plan:a},success:!0}}catch(e){return{error:{body:e,message:e.message,type:`PluginServerError`},success:!1}}};updatePlan=async(e,t)=>{try{if(t.signal?.aborted)return{stop:!0,success:!1};if(!t.topicId)return{content:`Cannot update plan: no topic selected`,success:!1};
3249let{planId:n,goal:r,description:i,context:a,completed:o}=e,s=await this.service.findPlanById(n);if(!s)return{content:`Plan not found: ${n}`,success:!1};let c=aK(await this.service.updatePlan(n,{content:a,description:i,goal:r},t.topicId),o??!1);return c.context=a??s.content??void 0,{content:`📝 Updated plan: "${c.goal}"`,state:{plan:c},success:!0}}catch(e){return{error:{body:e,message:e.message,type:`PluginServerError`},success:!1}}}}})),lK=e((()=>{Wt()})),uK,dK,fK,pK,mK=e((()=>{lK(),uK=`
3250<sub_agents>
3251You can dispatch **sub-agents** to handle long-running, multi-step work in isolated contexts.
3252
3253**Sub-Agent Tool:**
3254- \`callSubAgent\`: Dispatch a single sub-agent. **Required params: description (brief UI label), instruction (detailed prompt)** - both must be provided.
3255- To run several independent investigations **in parallel**, emit multiple \`callSubAgent\` calls in the same turn — each runs in its own isolated context concurrently.
3256
3257**Use sub-agents when:**
3258- **The request requires gathering external information**: The user wants you to research, investigate, or find information that you don't already know. This needs web searches, reading multiple sources, and synthesizing information.
3259- **The task involves multiple steps**: The request cannot be answered in one simple response - it requires searching, reading, analyzing, and summarizing.
3260- **Quality depends on thorough investigation**: A superficial answer would be insufficient; the user expects comprehensive, well-researched results.
3261- **Independent execution is beneficial**: The task can run separately while freeing up the main conversation.
3262
3263**How to identify sub-agent scenarios:**
3264Ask yourself: "Can I answer this well from my existing knowledge, or does this require actively gathering new information?"
3265- If you need to search the web, read articles, or investigate → Dispatch a sub-agent
3266- If you can answer directly from knowledge → Just respond
3267
3268Use a single \`callSubAgent\` for one task; emit multiple \`callSubAgent\` calls in the same turn to run independent tasks in parallel.
3269
3270**Example scenarios:**
3271- User asks about best restaurants in a city → \`callSubAgent\` (needs current info from reviews, searches)
3272- User wants research on a topic → \`callSubAgent\` (multi-step: search, read, analyze, summarize)
3273- User asks to compare products/services → \`callSubAgent\` (needs data from multiple sources)
3274- User asks a factual question you know → Just answer directly
3275- User wants multiple independent analyses → multiple \`callSubAgent\` calls in one turn (parallel execution)
3276</sub_agents>
3277`,dK=`Use Lobe Agent capabilities only when the active model needs built-in assistance. Prefer the active model's native capabilities whenever they are sufficient. Follow each tool's description and schema, and use tool results to answer the user directly.
3278
3279<visual_analysis>
3280\`analyzeVisualMedia\` is only a fallback when the active model cannot inspect the requested image/video natively.
3281If the media is already visible in the current multimodal context, answer directly without this tool.
3282Use it only for refs/URLs you cannot inspect directly, or when the active model lacks the needed image/video capability.
3283</visual_analysis>
3284
3285
3286<ask_user_question>
3287\`askUserQuestion\` opens a UI-mediated question so the user can clarify their intent before you act.
3288
3289- Use "form" mode with \`fields\` when you need structured or constrained choices (select / multiselect / text / textarea).
3290- Use "freeform" mode for a single open-ended response.
3291- Reach for it only when the request is genuinely ambiguous and the clarification would materially change your answer — do NOT interrogate the user for details you can reasonably infer or that don't affect the outcome.
3292- Ask at most one question at a time, then wait for the user's answer before continuing.
3293- Prefer asking in plain text for trivial confirmations; use this tool when a structured picker or explicit options improve the experience.
3294</ask_user_question>
3295
3296
3297<plan_and_todos>
3298You have **plan and todo management** tools to organize multi-step work over time.
3299
3300- **Plan**: A high-level strategic document describing goals, context, and overall direction. Plans do NOT contain actionable steps - they define the "what" and "why". **Plans should be stable once created** - they represent the overarching objective that rarely changes.
3301- **Todo**: The concrete execution list with actionable items. Todos define the "how" - specific tasks to accomplish the plan. **Todos are dynamic** - they can be added, updated, completed, and removed as work progresses.
3302
3303**Planning Tools** - For high-level goal documentation:
3304- \`createPlan\`: Create a strategic plan document. **Required params: goal, description (brief summary), context** - all three must be provided
3305- \`updatePlan\`: Update plan details (only planId is required)
3306
3307**Todo Tools** - For actionable execution items:
3308- \`createTodos\`: Create new todo items from text array
3309- \`updateTodos\`: Batch update todos (add, update, remove, complete, processing operations)
3310- \`clearTodos\`: Clear completed or all items
3311
3312**Todo Status Workflow:** todo → processing → completed (use "processing" when actively working on an item)
3313
3314<default_workflow>
3315**CRITICAL: Most tasks do NOT need plan/todo tools. Only use them for complex, multi-step projects.**
3316
3317**DO NOT use plan/todo tools for:**
3318- Simple one-step tasks (rename a file, send a message, search something)
3319- Quick questions or lookups
3320- Tasks that can be completed immediately with a single action
3321- Any request that doesn't require tracking progress over time
3322
3323**ONLY use plan/todo tools when ALL of these are true:**
33241. The task has multiple distinct steps that need tracking
33252. The user explicitly wants to plan or organize something
33263. Progress needs to be tracked over time (not completed in one response)
3327
3328**When plan/todo tools ARE appropriate:**
33291. **First**, use \`createPlan\` to document the goal and relevant context
33302. **Then**, use \`createTodos\` to break down the plan into actionable steps
3331
3332**Examples:**
3333- ❌ "Rename this file" → Just do it, no plan/todo needed
3334- ❌ "What's the weather?" → Just answer, no plan/todo needed
3335- ❌ "Help me write an email" → Just write it, no plan/todo needed
3336- ✅ "Help me plan a trip to Japan" → Use createPlan + createTodos
3337- ✅ "I want to learn Python, create a study plan" → Use createPlan + createTodos
3338- ✅ "Help me organize my project tasks" → Use createTodos (user explicitly wants organization)
3339</default_workflow>
3340
3341<when_to_use>
3342**Use Plans when:**
3343- User explicitly asks to "plan", "organize", or "break down" a complex goal
3344- The project spans multiple sessions or days
3345- There's significant context, constraints, or background worth documenting
3346- The task has 5+ distinct steps that benefit from strategic organization
3347
3348**Use Todos when:**
3349- Breaking down a plan into actionable steps (after creating a plan)
3350- User explicitly requests a checklist or task list
3351- Tracking progress on a multi-step project
3352
3353**DO NOT use Plans/Todos when:**
3354- The task can be done in one action (rename, delete, send, search, etc.)
3355- The user just wants something done, not organized
3356- The task will be completed in this single conversation
3357- The user wants a task to repeat automatically on a schedule (daily/weekly/hourly) — use **lobe-cron** instead. Keywords like "daily task", "routine", "recurring", "every day/morning/week", "set as daily", "make it regular" all indicate scheduled automation, not plan/todo management.
3358</when_to_use>
3359
3360<best_practices>
3361- **Plan first, then todos**: Always start with a plan unless explicitly told otherwise
3362- **Separate concerns**: Plans describe goals; Todos list actions
3363- **Actionable todos**: Each todo should be a concrete, completable task
3364- **Context in plans**: Use plan's context field to capture constraints and background
3365- **Regular cleanup**: Clear completed todos to keep the list focused
3366- **Track progress**: Use todo completion to measure plan progress
3367</best_practices>
3368
3369<updateTodos_usage>
3370When using \`updateTodos\`, each operation type requires specific fields:
3371
3372**Todo Status:**
3373- \`todo\`: Not started yet
3374- \`processing\`: Currently in progress
3375- \`completed\`: Done
3376
3377**Minimal required fields per operation type:**
3378- \`{ "type": "add", "text": "todo text" }\` - only type + text
3379- \`{ "type": "complete", "index": 0 }\` - only type + index (marks as completed)
3380- \`{ "type": "processing", "index": 0 }\` - only type + index (marks as in progress)
3381- \`{ "type": "remove", "index": 0 }\` - only type + index
3382- \`{ "type": "update", "index": 0, "newText": "..." }\` - type + index + optional newText/status
3383
3384**Example - mark item 0 as processing, item 1 as complete:**
3385\`\`\`json
3386{
3387  "operations": [
3388    { "type": "processing", "index": 0 },
3389    { "type": "complete", "index": 1 }
3390  ]
3391}
3392\`\`\`
3393
3394**DO NOT** add extra fields like \`"status": "completed"\` for complete/processing operations - they are ignored.
3395</updateTodos_usage>
3396
3397<todo_granularity>
3398**IMPORTANT: Keep todos focused on major stages, not detailed sub-tasks.**
3399
3400- **Limit to 5-10 items**: A todo list should contain around 5-10 major milestones or stages, not 20+ detailed tasks.
3401- **Think in phases**: Group related tasks into higher-level stages (e.g., "Plan itinerary" instead of listing every city separately).
3402- **Use hierarchical numbering** when more detail is needed: Use "1.", "2.", "2.1", "2.2", "3." format to show parent-child relationships.
3403
3404**Good example** (Japan trip - 7 items, stage-focused):
3405- 1. Determine travel dates and duration
3406- 2. Handle visa and documentation
3407- 3. Book flights and accommodation
3408- 4. Plan city itineraries
3409- 5. Arrange local transportation
3410- 6. Prepare for departure
3411- 7. Final confirmation before trip
3412
3413**Bad example** (20+ detailed items):
3414- Book Tokyo hotel
3415- Book Kyoto hotel
3416- Book Osaka hotel
3417- Buy Suica card
3418- Download Google Maps
3419- Download translation app
3420- ... (too granular!)
3421</todo_granularity>
3422
3423<plan_stability>
3424**IMPORTANT: Plans should remain stable once created. Each conversation has only ONE plan.**
3425
3426- **Do NOT update plans** when details change (dates, locations, preferences). Instead, update the todos to reflect new information.
3427- **Only use updatePlan** when the user's goal fundamentally changes (e.g., destination changes from Japan to Korea).
3428- When user provides more specific information (like exact dates or preferences), **update or add todos** - not the plan.
3429</plan_stability>
3430
3431<response_format>
3432When working with plan/todo tools:
3433- Confirm actions: "Created plan: [goal]" or "Added [n] todo items"
3434- Show progress: "Completed [n] items, [m] remaining"
3435- Be concise: Brief confirmations, not verbose explanations
3436- **NEVER repeat the todo list in your response** - Users can already see the todos in the UI component. Do not list or enumerate the todo items in your text output.
3437</response_format>
3438</plan_and_todos>
3439`,fK=`${dK}
3440${uK}`,pK=dK})),hK,gK,_K,vK=e((()=>{hK=`lobe-agent`,gK={analyzeVisualMedia:`analyzeVisualMedia`,askUserQuestion:`askUserQuestion`,callSubAgent:`callSubAgent`,clearTodos:`clearTodos`,createPlan:`createPlan`,createTodos:`createTodos`,updatePlan:`updatePlan`,updateTodos:`updateTodos`},_K=e=>{let t=[`todo`,`processing`,`completed`];return t[(t.indexOf(e)+1)%t.length]}})),yK,bK=e((()=>{lK(),mK(),vK(),yK={api:[{description:`Analyze images or videos selected by visual file refs or direct media URLs and answer a visual question. Prefer the active model's native multimodal capability when it can inspect the visual media directly; use this tool only as a fallback when the active model cannot inspect the requested images or videos. Provide either refs or urls; at least one is required. Prefer refs when stable refs are available in <files_info>, such as msg_xxx.image_1 or msg_xxx.video_1, and use urls only for direct media URLs that are not available as message refs. After this tool returns, answer the user directly with the result.`,name:gK.analyzeVisualMedia,parameters:{additionalProperties:!1,properties:{question:{description:`The visual question or task to answer.`,type:`string`},refs:{description:`Stable visual file ref strings to analyze, such as ["msg_xxx.image_1"] or ["msg_xxx.video_1"].`,items:{type:`string`},minItems:1,type:`array`},urls:{description:`Direct image or video URLs to analyze when no message file ref exists.`,items:{type:`string`},minItems:1,type:`array`}},required:[`question`],type:`object`}},{description:`Create a high-level plan document. Plans define the strategic direction (the "what" and "why"), while todos handle the actionable steps.`,name:gK.createPlan,humanIntervention:`required`,renderDisplayControl:`expand`,parameters:{properties:{goal:{description:`The main goal or objective to achieve (used as document title).`,type:`string`},description:{description:`A brief summary of the plan (1-2 sentences).`,type:`string`},context:{description:`Detailed context, constraints, background information, or strategic considerations relevant to the goal.`,type:`string`}},required:[`goal`,`description`,`context`],type:`object`}},{description:`Update an existing plan document. Only use this when the goal fundamentally changes. Plans should remain stable once created - do not update plans just because details change.`,name:gK.updatePlan,parameters:{properties:{planId:{description:`The document ID of the plan to update (e.g., "docs_xxx"). This ID is returned in the createPlan response. Do NOT use the goal text as planId.`,type:`string`},goal:{description:`Updated goal (document title).`,type:`string`},description:{description:`Updated brief summary.`,type:`string`},context:{description:`Updated detailed context.`,type:`string`}},required:[`planId`],type:`object`}}
3440,{description:`Create new todo items. Pass an array of text strings.`,name:gK.createTodos,humanIntervention:`required`,parameters:{properties:{adds:{description:`Array of todo item texts to create.`,items:{type:`string`},type:`array`}},required:[`adds`],type:`object`}},{description:`Update todo items with batch operations. Each operation type requires specific fields:
3441- "add": requires "text" (the todo text to add)
3442- "update": requires "index", optional "newText" and/or "status"
3443- "remove": requires "index" only
3444- "complete": requires "index" only (marks item as completed)
3445- "processing": requires "index" only (marks item as in progress)`,name:gK.updateTodos,renderDisplayControl:`expand`,parameters:{properties:{operations:{description:`Array of update operations. IMPORTANT: For "complete", "processing" and "remove" operations, only pass "type" and "index" - no other fields needed.`,items:{properties:{type:{description:`Operation type. "add" needs text, "update" needs index + optional newText/status, "remove", "complete" and "processing" need index only.`,enum:[`add`,`update`,`remove`,`complete`,`processing`],type:`string`},text:{description:`Required for "add" only: the text to add.`,type:`string`},index:{description:`Required for "update", "remove", "complete", "processing": the item index (0-based).`,type:`number`},newText:{description:`Optional for "update" only: the new text.`,type:`string`},status:{description:`Optional for "update" only: set status (todo, processing, completed).`,enum:[`todo`,`processing`,`completed`],type:`string`}},required:[`type`],type:`object`},type:`array`}},required:[`operations`],type:`object`}},{description:`Clear todo items. Can clear only completed items or all items.`,name:gK.clearTodos,humanIntervention:`required`,renderDisplayControl:`expand`,parameters:{properties:{mode:{description:`"completed" clears only done items, "all" clears the entire list.`,enum:[`completed`,`all`],type:`string`}},required:[`mode`],type:`object`}},{description:`Ask the user one or more clarifying questions with multiple-choice options.`,humanIntervention:`always`,name:gK.askUserQuestion,renderDisplayControl:`collapsed`,parameters:{properties:{questions:{items:{properties:{header:{type:`string`},multiSelect:{type:`boolean`},options:{items:{properties:{description:{type:`string`},label:{type:`string`}},required:[`label`,`description`],type:`object`},maxItems:4,minItems:2,type:`array`},question:{type:`string`}},required:[`header`,`question`,`options`],type:`object`},maxItems:4,minItems:1,type:`array`}},required:[`questions`],type:`object`}},{description:`Dispatch a single sub-agent that runs in an isolated context to handle a long-running, multi-step request. Use this when the request requires extended processing (web research, multi-source synthesis, deep investigation) that benefits from running independently of the main conversation.`,name:gK.callSubAgent,parameters:{properties:{description:{description:`Brief description of what this sub-agent does (shown in UI).`,type:`string`},instruction:{description:`Detailed instruction/prompt for the sub-agent execution.`,type:`string`},inheritMessages:{description:`Whether to inherit context messages from the parent conversation. Default is false.`,type:`boolean`},timeout:{description:`Optional timeout in milliseconds. Default is 30 minutes.`,type:`number`}},required:[`description`,`instruction`],type:`object`}}],identifier:hK,meta:{avatar:`🤖`,description:`Run built-in Lobe Agent capabilities: plan + todo management, sub-agent dispatch, and visual media analysis.`,readme:`Lobe Agent provides built-in assistant capabilities that can be expanded over time.`,title:`Lobe Agent`},systemRole:fK,type:`builtin`}})),xK,Hwe=e((()=>{bK(),mK(),vK(),xK=e=>e.scope===`group`||e.scope===`group_agent`||e.isSubAgent===!0?{...yK,api:yK.api.filter(e=>e.name!==gK.callSubAgent),systemRole:pK}:yK})),SK,CK,wK,TK,EK,DK,OK,kK,AK,jK,MK,NK,PK,FK,IK,LK,RK,zK,BK,VK,HK=e((()=>{yt(),SK=/\.(?:mp4|m4v|mov|webm|mpeg|mpg|avi|mkv)(?:[?#]|$)/i,CK=/^data:(?:image|video)\//i,wK=new Set([`http:`,`https:`]),TK=new Set([`question`,`refs`,`urls`]),EK=2e6,DK=e=>Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(e=>e.length>0):[],OK=e=>({requestedRefs:DK(e.refs),requestedUrls:DK(e.urls)}),kK=e=>Object.keys(e).filter(e=>!TK.has(e)),AK=e=>{try{let t=new URL(e);return wK.has(t.protocol)?!0:t.protocol===`data:`&&CK.test(e)}catch{return!1}},jK=e=>{let t=[],n=[],r=[];for(let i of e.slice(0,8)){if(i.length>2e6){r.push(i);continue}AK(i)?t.push(i):n.push(i)}
3445return{invalidUrls:n,oversizedUrls:r,tooManyUrls:e.length>8,totalUrls:e.length,validUrls:t}},MK=e=>{let t=e.startsWith(`data:`)?`${e.split(`,`)[0]},...`:e;return t.length>120?`${t.slice(0,117)}...`:t},NK=e=>{let t=[];if(e.tooManyUrls&&t.push(`Too many visual media URLs: ${e.totalUrls}. At most 8 URLs are supported.`),e.oversizedUrls.length>0&&t.push(`Visual media URLs exceed the ${EK} character limit: ${e.oversizedUrls.map(MK).join(`, `)}.`),e.invalidUrls.length>0&&t.push(`Unsupported visual media URLs: ${e.invalidUrls.map(MK).join(`, `)}.`),t.length!==0)return`${t.join(` `)} Only http:, https:, data:image/* and data:video/* URLs are supported.`},PK=e=>!!e&&typeof e==`object`&&((e.imageList?.length??0)>0||(e.videoList?.length??0)>0),FK=e=>!!e&&typeof e==`object`&&e.role===`user`&&PK(e),IK=(e,t=[],n=[])=>[...t.map((t,n)=>{let r=t.alt||t.id||`Image ${n+1}`;return{description:t.alt||`Image ${n+1}`,id:t.id,localRef:Yt(`image`,n),messageId:e?.id,name:r,ref:kt({index:n,messageId:e?.id,type:`image`}),type:`image`,uri:t.url}}),...n.map((t,n)=>{let r=t.alt||t.id||`Video ${n+1}`;return{description:t.alt||`Video ${n+1}`,id:t.id,localRef:Yt(`video`,n),messageId:e?.id,name:r,ref:kt({index:n,messageId:e?.id,type:`video`}),type:`video`,uri:t.url}})],LK=e=>/^data:video\//i.test(e)?`video`:/^data:image\//i.test(e)?`image`:SK.test(e)?`video`:`image`,RK=(e,t)=>{try{let n=new URL(e);return n.protocol===`data:`?`URL ${t+1}`:n.pathname.split(`/`).findLast(Boolean)||`URL ${t+1}`}catch{return`URL ${t+1}`}},zK=e=>e.map((e,t)=>{let n=LK(e),r=RK(e,t);return{description:r,localRef:`url_${t+1}`,name:r,ref:`url_${t+1}`,type:n,uri:e}}),BK=(e,t)=>{if(!t||t.length===0)return{availableRefs:[],invalidRefs:[],selected:[]};let n=t=>e.find(e=>e.ref===t),r=t.map(e=>n(e)).filter(e=>!!e),i=t.filter(e=>!n(e));return{availableRefs:e.map(e=>e.ref),invalidRefs:i,selected:r}},VK=(e,t,n={})=>{let r=[`Analyze the attached visual media and answer the user question.`];return n.includeFallbackInstruction&&r.push(`Do not mention that you are a fallback tool unless it is relevant.`),n.includeFileSummary&&r.push(``,`Files:`,e.map(e=>`- ${e.ref}: ${e.name} (${e.type})`).join(`
3446`)),r.push(``,`Question: ${t}`),[{text:r.join(`
3447`),type:`text`},...e.map(e=>e.type===`image`?{image_url:{detail:`auto`,url:e.uri},type:`image_url`}:{type:`video_url`,video_url:{url:e.uri}})]}})),UK=e((()=>{cK(),bK(),Hwe(),mK(),vK(),HK()})),WK,GK=e((()=>{WK="\n<delivery_checker>\nFor a task that produces a **deliverable** (writing code, editing files, producing a document or a multi-step result), call `generateVerifyPlan` **once at the start**, after you understand the request and before doing the substantive work.\n\nEnumerate the concrete checks the deliverable must satisfy and pass them as `criteria` (one entry per check), with `title` set to the user's task/goal. Derive the criteria from the user's explicit requirements — **each requirement becomes one criterion**. For each criterion:\n- `title`: the single, concrete pass/fail standard (short).\n- `instruction`: a **detailed, fine-grained judging rubric** — the exact pass conditions, what counts as a fail, the concrete evidence the judge must find, and edge cases. Write it thoroughly, not a one-liner; the judge relies entirely on it.\n- `verifierType`: `llm` (default) for qualitative judgement from the output; `agent` when the check needs active investigation (reading files, running checks).\n- `required`: `true` when the check must pass to deliver, `false` when it is optional/advisory.\n\n- The user reviews and confirms the proposed checks; on confirmation they are persisted and the checks run **automatically** when the operation completes. You do **not** run the checks yourself.\n- **Skip it** for simple questions, lookups, or chit-chat with no deliverable, or when you cannot identify any concrete check.\n- After calling it, continue with the task normally — do not wait or ask the user about the checks.\n</delivery_checker>\n"})),KK,qK,JK=e((()=>{KK=`lobe-delivery-checker`,qK={generateVerifyPlan:`generateVerifyPlan`}})),YK,XK=e((()=>{GK(),JK(),YK={api:[{description:"Define the delivery checks for the current Agent Run. Call this BEFORE doing substantive work, once you understand the task. Enumerate the concrete checks the deliverable must satisfy — one `criteria` entry per check — and set `title` to the user's task/goal. On confirmation the criteria and a reusable rubric are created and snapshotted onto the run; the checks run automatically when the run completes — you do NOT run them yourself.",name:qK.generateVerifyPlan,humanIntervention:`required`,renderDisplayControl:`expand`,parameters:{properties:{title:{description:`The delivery standard's title — typically the user's task / goal in one line.`,type:`string`},criteria:{description:`The checks the deliverable must satisfy — one entry per check.`,items:{properties:{title:{description:`The short title of this check.`,type:`string`},description:{description:`A one-sentence summary of what this check verifies.`,type:`string`},instruction:{description:`A detailed, fine-grained judging rubric for this check: the exact pass conditions, what counts as a fail, the concrete evidence the judge must find, and edge cases to check. Write it thoroughly (multiple sentences / bullet points), not a one-liner — the judge relies on it.`,type:`string`},required:{description:`Whether this check is required (must pass to deliver) vs optional. Default true.`,type:`boolean`}
3447,verifierType:{description:`How it is judged. 'llm' (default) judges the deliverable with an LLM; 'agent' spawns a sub-agent that actively investigates (reads files, runs checks); 'program' runs a command (not executed in v1).`,enum:[`llm`,`agent`,`program`],type:`string`},onFail:{description:`Action on failure: 'manual' (default) or 'auto_repair' (attempt an automatic fix).`,enum:[`manual`,`auto_repair`],type:`string`}},required:[`title`,`description`,`instruction`],type:`object`},type:`array`}},required:[`title`,`criteria`],type:`object`}}],identifier:KK,meta:{avatar:`✅`,description:`Define delivery checks the agent run must satisfy; they run automatically on completion.`,title:`Delivery Checker`},systemRole:WK,type:`builtin`}})),ZK=e((()=>{XK(),GK(),JK()})),QK,$K=e((()=>{QK=`You have a LobeHub Memory Tool. This tool is to recognise, retrieve, and coordinate high-quality user memories so downstream extractors can persist them accurately.
3448
3449<session_context>
3450Current user: {{username}}
3451Session date: {{date}}
3452Conversation language: {{language}}
3453Memory effort level: {{memory_effort}}
3454</session_context>
3455
3456<memory_effort_policy>
3457- **low**: Prefer fewer memory operations. Keep retrieval narrow and only save/update/delete when confidence and long-term value are clearly high.
3458- **medium**: Balanced behavior. Perform retrieval and memory updates for clearly relevant, reusable information.
3459- **high**: Be proactive. Use broader retrieval and stronger consistency checks; actively refine, update, or remove stale memory entries when justified.
3460</memory_effort_policy>
3461
3462<core_responsibilities>
34631. Inspect every turn for information that belongs to the five memory layers (identity, context, preference, experience, activity). When information is relevant and clear, err on the side of allowing extraction so specialised aggregators can refine it.
34642. Call **queryTaxonomyOptions** to discover live categories, tags, labels, statuses, roles, and relationships when you need better search vocabulary or extraction guidance.
34653. Call **searchUserMemory** with one or more targeted queries plus structured filters before proposing new memories. Use **timeIntent** for calendar-style requests such as "December 2025", "last month", or "yesterday", and use **timeRange** only when you already know exact boundaries. Compare any potential extraction against retrieved items to avoid duplication and highlight genuine updates.
34664. Enforce that all memory candidates are self-contained, language-consistent, and ready for long-term reuse without relying on the surrounding conversation.
3467</core_responsibilities>
3468
3469<routing_boundaries>
3470- Do **not** use memory tools for requests to create, update, refine, merge, consolidate, or store reusable skills, procedures, workflows, playbooks, checklists, agent capabilities, agent prompts, or agent documents.
3471- If the user asks for a "reusable skill", "future workflow", "PR review checklist skill", "agent capability", or similar operational artifact, leave it to the skill/document management path. Do not convert it into addPreferenceMemory, addExperienceMemory, or addContextMemory.
3472- The same boundary applies in Chinese. Requests about "复用 skill", "可复用流程", "review 流程", "检查清单", "下次参考这个流程", "保留这个流程", or "合并/更新清单" belong to skill/workflow management unless they also contain a separate personal preference.
3473- If recent evidence includes an agent document or tool outcome marked hintIsSkill=true, treat that as skill/document evidence, not memory evidence.
3474- Preference memory is only for durable user preferences about how the assistant should behave; it is not a replacement for executable or document-like procedures.
3475- When a message mixes a personal preference with a skill/procedure request, only persist the personal preference if it remains valuable after removing the skill/procedure content. Otherwise skip memory.
3476</routing_boundaries>
3477
3478<tooling>
3479- **queryTaxonomyOptions**: discover categories, tags, labels, statuses, roles, and relationships that already exist in memory.
3480- **searchUserMemory**: queries?, categories?, tags?, labels?, layers?, types?, relationships?, status?, timeIntent?, timeRange?, topK? → Returns structured memories plus per-layer totals and hasMore signals.
3481- **searchUserMemory argument rule**: \`queries\` must be a JSON array of str
3481ings, for example \`["vegan restaurants", "Tokyo trip"]\`. Never pass one space-separated string to simulate multiple queries such as \`["vegan restaurants Tokyo trip"]\` when you actually mean multiple search intents, and never pass a plain string like \`"vegan restaurants Tokyo trip"\` in place of the array.
3482- **searchUserMemory filter rule**: \`layers\`, \`categories\`, \`tags\`, \`labels\`, \`relationships\`, \`status\`, and \`types\` must also be JSON arrays. For a single layer use \`"layers": ["preference"]\`, never \`"layers": "preference"\`.
3483- **searchUserMemory time rule**: Prefer \`timeIntent\` for relative or calendar expressions. Example: "December 2025" → \`{ "timeIntent": { "selector": "month", "year": 2025, "month": 12 } }\`, "yesterday" → \`{ "timeIntent": { "selector": "yesterday" } }\`, "3 days after December 15 2025" → \`{ "timeIntent": { "selector": "relativeDay", "anchor": { "selector": "day", "date": "2025-12-15T00:00:00.000Z" }, "offsetDays": 3 } }\`. \`timeIntent\` always resolves to a \`createdAt\` time range on the server, so do not add or infer a field inside \`timeIntent\`. Use \`timeRange\` only when exact boundaries are already known.
3484- **addActivityMemory**: title, summary, details?, withActivity → Capture time-bound events (what happened, when/where, who/what was involved, and how it felt).
3485- **addContextMemory**: title, summary, details?, withContext → Capture ongoing situations (actors, resources, status, urgency/impact, description, tags).
3486- **addExperienceMemory**: title, summary, details?, withExperience → Record Situation → Reasoning → Action → Outcome narratives and confidence.
3487- **addIdentityMemory**: title, summary, details?, withIdentity → Store enduring identity facts, relationships, roles, and evidence.
3488- **addPreferenceMemory**: title, summary, details?, withPreference → Persist durable directives and scopes the assistant should follow.
3489- **updateIdentityMemory**: id, mergeStrategy, set → Merge or replace existing identity entries with refined information.
3490- **removeIdentityMemory**: id, reason → Delete incorrect, obsolete, or duplicate identity memories with justification.
3491</tooling>
3492
3493<search_examples>
3494Valid **searchUserMemory** examples:
3495- Single intent: \`{ "queries": ["prefers concise answers"] }\`
3496- Multiple intents: \`{ "queries": ["prefers concise answers", "works in fintech"] }\`
3497- Query with filters: \`{ "queries": ["TypeScript testing preferences"], "layers": ["preference", "experience"], "tags": ["typescript"] }\`
3498- Calendar time filter: \`{ "queries": ["Electron debugging"], "timeIntent": { "selector": "month", "year": 2025, "month": 12 } }\`
3499- Relative time filter: \`{ "queries": ["weekly planning"], "timeIntent": { "selector": "lastMonth" } }\`
3500- Use **queryTaxonomyOptions** first when vocabulary is unclear, then search with the discovered categories/tags/labels.
3501
3502Invalid **searchUserMemory** examples:
3503- Wrong shape: \`{ "queries": "prefers concise answers works in fintech" }\`
3504- Wrong filter shape: \`{ "queries": ["meal preference"], "layers": "preference" }\`
3505- Wrong batching: \`{ "queries": ["prefers concise answers works in fintech"] }\` when these are two separate intents
3506- Wrong temporal shape: \`{ "queries": ["December 2025 project work"] }\` when the time constraint should be expressed via \`timeIntent\`
3507- Over-broad filler terms: \`{ "queries": ["user memory conversation context profile preference"] }\`
3508
3509Query construction guidance:
3510- Each query string should represent one focused retrieval intent.
3511- Split unrelated intents into separate array items instead of concatenating them.
3512- Prefer short natural phrases over keyword stuffing.
3513- Do not encode explicit calendar filters inside the query text when \`timeIntent\` can represent them directly.
3514- If you do not have a meaningful lexical query yet, use structured filters or call **queryTaxonomyOptions** first rather than inventing filler text.
3515- Before deciding retrieval is complete, check whether retrieved memories answer the user's actual entity, relationship, time, object, preference, or situational need.
3516- If retrieved memories are only topically related, run another focused search rather than treating them as sufficient.
3517- For multi-part questions, search each independent intent separately and compare the returned memories before answering.
3518- Prefer grounded memories with source provenance when available, but never expose internal source ids in user-facing responses.
3519</search_examples>
3520
3521<retrieval_sufficiency>
3522- A memory result is sufficient only when it directly supports the answer or memory action being considered.
3523- Topic overlap alone is not sufficient. If the memory mentions the broad topic but misses the specific person, time, object, relationship, or preference, search again with a narrower query.
3524- Use multiple \`queries\` for separate intents instead of one overloaded query string.
3525- Use \`queryTaxonomyOptions\` when a category, tag, label, status, role, or relationship vocabulary would make the next search more precise.
3526- Keep source grounding internal. Source ids and database ids may guide confidence, but final responses should refer to memories by descriptive titles or summaries.
3527</retrieval_sufficiency>
3528
3529<memory_layer_definitions>
3530- **Activity Layer** — time-bound events and interactions. Include narrative, feelings/feedback, start/end times with timezone when present, and associations (people, objects, locations).
3531- **Identity Layer** — enduring facts about people and their relationships: roles, demographics, background, priorities, and relational context.
3532- **Context Layer** — ongoing situations such as projects, goals, partnerships, or environments. Capture actors (associatedSubjects), resources (associatedObjects), currentStatus, timelines, and impact/urgency assessments.
3533- **Preference Layer** — durable directives that guide future assistant behaviour (communication style, workflow choices, priority rules). Exclude single-use task instructions or purely implementation details.
3534- **Experience Layer** — lessons, insights, and transferable know-how. Preserve the Situation → Reasoning → Action → Outcome narrative and note confidence when available.
3535</memory_layer_definitions>
3536
3537<formatting_guardrails>
3538- Every memory must stand alone: repeat explicit subjects (use names such as {{username}} rather than pronouns like he/she/they/it/this).
3539- Preserve the user's language and tone unless explicitly asked to translate.
3540- Include concrete actors, locations, dates, motivations, emotions, and outcomes.
3541- Reference retrieved memories to decide if information is new, materially refined, or a status/progress update. Skip items that add no meaningful nuance.
3542- Do not store transient instructions, tool parameters, or secrets meant only for the current task.
3543- Do not summarize skill-management requests as user preferences. For example, "Create a reusable skill for future PR reviews" is a skill-management request, not a preference memory.
3544- Do not summarize Chinese workflow retention requests as memories. For example, "这个 review 流程挺好,下次也可以参考" is a weak skill/workflow signal, not a user preference memory.
3545</formatting_guardrails>
3546
3547<layer_specific_highlights>
3548- **Activity**: Focus on concrete episodes. Prefer explicit times/timezones when given; avoid guessing. Keep narrative factual and feedback subjective; store both when available.
3549- **Identity**: Track labels, relationships, and life focus areas. Note relationship enums (self, mentor, teammate, etc.) when known.
3550- **Context**: Describe shared storylines tying multiple memories together. Update existing contexts instead of duplicating; surface currentStatus changes and resource/actor involvement.
3551- **Preference**: Record enduring choices that affect future interactions (response formats, decision priorities, recurring do/do-not expectations). Ensure conclusionDirectives are actionable on their own.
3552- **Experience**: Capture practical takeaways, heuristics, or playbooks. Emphasise why the lesson matters and how confident the user is in applying it again.
3553</layer_specific_highlights>
3554
3555<security_and_privacy>
3556- Never persist credentials, financial data, medical records, or any sensitive secrets.
3557- Confirm user intent before storing potentially sensitive material and respect stated boundaries.
3558- Handle personal data conservatively; default to omission when uncertain.
3559</security_and_privacy>
3560
3561<response_expectations>
3562- When memory activity is warranted, explain which layers are affected, cite any matching memories you found, and justify why extraction or updates are needed.
3563- When nothing qualifies, explicitly state that no memory action is required after reviewing the context.
3564- Keep your reasoning concise, structured, and aligned with the conversation language.
3565- **Never expose internal memory IDs** (e.g., mem_xxx, id: xxx) to users in your responses. Refer to memories by their descriptive titles or summaries instead.
3566</response_expectations>`})),eq,tq=e((()=>{eq={addActivityMemory:`addActivityMemory`,addContextMemory:`addContextMemory`,addExperienceMemory:`addExperienceMemory`,addIdentityMemory:`addIdentityMemory`,addPreferenceMemory:`addPreferenceMemory`,queryTaxonomyOptions:`queryTaxonomyOptions`,removeIdentityMemory:`removeIdentityMemory`,searchUserMemory:`searchUserMemory`,updateIdentityMemory:`updateIdentityMemory`}})),nq,rq,iq,aq,oq=e((()=>{Ne(),$K(),tq(),nq=`lobe-user-memory`,rq=[`today`,`yesterday`,`currentWeek`,`lastWeek`,`lastWeekend`,`lastWeekdays`,`currentMonth`,`lastMonth`,`currentYear`,`lastYear`,`day`,`month`,`year`,`relativeDay`,`range`],iq={additionalProperties:!1,description:`Optional calendar-friendly time selector that the server always resolves into an exact createdAt timeRange. Prefer this for prompts like "December 2025", "last month", or "yesterday".`,properties:{anchor:{anyOf:[{enum:[`today`,`yesterday`],type:`string`},{additionalProperties:!1,properties:{anchor:{description:`When nested as a relativeDay anchor, only "today" or "yesterday" is allowed.`,enum:[`today`,`yesterday`],type:`string`},date:{format:`date-time`,type:`string`},end:{format:`date-time`,type:`string`},month:{maximum:12,minimum:1,type:`integer`},offsetDays:{type:`integer`},selector:{enum:[...rq],type:`string`},start:{format:`date-time`,type:`string`},year:{maximum:9999,minimum:1970,type:`integer`}},required:[`selector`],type:`object`}],description:`Anchor for relativeDay. Use the string "today"/"yesterday", or a non-recursive timeIntent object such as { "selector": "day", "date": "2025-12-15T00:00:00.000Z" }.`},date:{format:`date-time`,type:`string`},end:{format:`date-time`,type:`string`},month:{maximum:12,minimum:1,type:`integer`},offsetDays:{type:`integer`},selector:{enum:[...rq],type:`string`},start:{format:`date-time`,type:`string`},year:{maximum:9999,minimum:1970,type:`integer`}},required:[`selector`],type:`object`},aq={api:[{description:`Retrieve memories using one or more search queries plus optional filters for categories, tags, labels, relationships, and time range.`,name:eq.searchUserMemory,parameters:{additionalProperties:!1,properties:{categories:{description:`Optional memory categories to constrain retrieval.`,items:{type:`string`},type:`array`},labels:{description:`Optional extracted labels to constrain retrieval.`,items:{type:`string`},type:`array`},layers:{description:`Optional memory layers to search. Must be an array even for one layer, for example ["preference"].`,items:{enum:[`activity`,`context`,`experience`,`identity`,`preference`],type:`string`},type:`array`},queries:{description:`One or more search queries to retrieve relevant memories.`,items:{type:`string`},type:`array`},relationships:{description:`Optional identity relationships to constrain retrieval.`,items:{enum:j,type:`string`},type:`array`},status:{description:`Optional status values for activity or context memories.`,items:{type:`string`},type:`array`},tags:{description:`Optional user or system tags to constrain retrieval.`,items:{type:`string`},type:`array`},timeIntent:iq,timeRange:{additionalProperties:!1,description:`Optional exact time range filter applied to the selected field. Use this when you already know precise boundaries; otherwise prefer timeIntent.`,properties:{end:{format:`date-time`,type:`string`},field:{enum:[`capturedAt`,`createdAt`,`endsAt`,`episodicDate`,`startsAt`,`updatedAt`],type:`string`},start:{format:`date-time`,type:`string`}},type:`object`},topK:{additionalProperties:!1,description:`Optional limits on number of memories to return per layer.`,properties:{activities:{minimum:0,type:`integer`},contexts:{minimum:0,type:`integer`},experiences:{minimum:0,type:`integer`},identities:{minimum:0,type:`integer`},preferences:{minimum:0,type:`integer`}},type:`object`},types:{description:`Optional memory types to constrain retrieval.`,items:{type:`string`},type:`array`}},type:`object`}},{description:`List existing taxonomy options such as categories, tags, labels, statuses, roles, and relationships so memory retrieval and extraction can use the current vocabulary.`,name:eq.queryTaxonomyOptions,parameters:{additionalProperties:!1,properties:{include:{description:`Select which taxonomy buckets to return. Must be an array even for one bucket.`,items:{enum:[`categories`,`labels`,`relationships`,`roles`,`statuses`,`tags`,`types`],type:`string`},type:`array`},layers:{description:`Optional memory layers to scope the taxonomy lookup. Must be an array even for one layer.`,items:{enum:[`activity`,`context`,`experience`,`identity`,`preference`],type:`string`},type:`array`},limit:{description:`Maximum number of options to return for each bucket.`,minimum:1,type:`integer`},q:{description:`Optional keyword used to filter taxonomy options.`,type:`string`}},type:`object`}},{description:`Create a context memory that captures ongoing situations, projects, or environments. Include actors, resources, statuses, urgency/impact, and a clear description.`,name:eq.addContextMemory,parameters:{additionalProperties:!1,properties:{details:{description:`Optional detailed information`,type:`string`},memoryCategory:{description:`Memory category`,type:`string`},memoryType:{description:`Memory type`,enum:L,type:`string`},summary:{description:`Concise overview of this specific memory`,type:`string`},sourceIds:{description:`Stable source message ids that support this memory. Use [] when unavailable.`,
3566items:{type:`string`},type:[`array`,`null`]},tags:{description:`User defined tags that summarize the context facets`,items:{type:`string`},type:`array`},title:{description:`Brief descriptive title`,type:`string`},withContext:{additionalProperties:!1,properties:{associatedObjects:{description:`Array of objects describing involved roles, entities, or resources, [] empty if none`,items:{additionalProperties:!1,properties:{extra:{description:`Additional metadata about the object, should always be a valid JSON string if present`,type:[`string`,`null`]},name:{description:`Name of the associated object`,type:`string`},type:{description:`Type/category of the associated object`,enum:V,type:`string`}},required:[`extra`,`name`,`type`],type:`object`},type:`array`},associatedSubjects:{description:`Array of JSON objects describing involved subjects or participants, [] empty if none`,items:{additionalProperties:!1,properties:{extra:{description:`Additional metadata about the subject, should always be a valid JSON string if present`,type:[`string`,`null`]},name:{description:`Name of the associated subject`,type:`string`},type:{description:`Type/category of the associated subject`,enum:$e,type:`string`}},required:[`extra`,`name`,`type`],type:`object`},type:`array`},currentStatus:{description:`High level status markers (must be one of 'planned', 'ongoing', 'completed', 'aborted', 'on_hold', 'cancelled')`,enum:te,type:`string`},description:{description:`Rich narrative describing the situation, timeline, or environment`,type:`string`},labels:{description:`Model generated tags that summarize the context themes`,items:{type:`string`},type:`array`},scoreImpact:{description:`Numeric score (0-1 (0% to 100%)) describing importance`,maximum:1,minimum:0,type:`number`},scoreUrgency:{description:`Numeric score (0-1 (0% to 100%)) describing urgency`,maximum:1,minimum:0,type:`number`},title:{description:`Optional synthesized context headline`,type:`string`},type:{description:`High level context archetype (e.g., 'project', 'relationship', 'goal')`,type:`string`}},required:[`associatedObjects`,`associatedSubjects`,`currentStatus`,`description`,`labels`,`scoreImpact`,`scoreUrgency`,`title`,`type`],type:`object`}},required:[`details`,`memoryCategory`,`memoryType`,`summary`,`tags`,`title`,`withContext`],type:`object`}},{description:`Record an activity memory capturing what happened, when, where, with whom, and how it felt. Include narrative, feedback, timing, associations, and tags.`,name:eq.addActivityMemory,parameters:{additionalProperties:!1,properties:{details:{description:`Optional detailed information or longer notes supporting the summary.`,type:`string`},memoryCategory:{description:`Memory category best matching the activity (e.g., work, health).`,type:`string`},memoryType:{const:`activity`,description:`Memory type; always activity.`,type:`string`},summary:{description:`Concise overview of this activity.`,type:`string`},sourceIds:{description:`Stable source message ids that support this memory. Use [] when unavailable.`,items:{type:`string`},type:[`array`,`null`]},tags:{description:`Model generated tags summarizing key facets of the activity.`,items:{type:`string`},type:`array`},title:{description:`Brief descriptive title for the activity.`,type:`string`},withActivity:{additionalProperties:!1,properties:{associatedLocations:{description:`Places linked to this activity.`,items:{additionalProperties:!1,properties:{address:{type:[`string`,`null`]},extra:{type:[`string`,`null`]},name:{type:`string`},tags:{items:{type:`string`},type:[`array`,`null`]},type:{type:`string`}},required:[`name`],type:`object`},type:`array`},associatedObjects:{description:`Non-living entities or items tied to the activity.`,items:{additionalProperties:!1,properties:{extra:{type:[`string`,`null`]},name:{type:`string`},type:{type:`string`}},required:[`name`],type:`object`},type:`array`},associatedSubjects:{description:`Living beings involved (people, pets, groups).`,items:{additionalProperties:!1,properties:{extra:{type:[`string`,`null`]},name:{type:`string`},type:{type:`string`}},required:[`name`],type:`object`},type:`array`},endsAt:{description:`ISO 8601 end time if provided.`,format:`date-time`,type:[`string`,`null`]},feedback:{description:`Subjective feelings or evaluation of how the activity went.`,type:[`string`,`null`]},metadata:{additionalProperties:!0,description:`Additional structured metadata to keep raw hints (JSON object).`,type:[`object`,`null`]},narrative:{description:`Factual story of what happened; required for recall.`,type:`string`},notes:{description:`Short annotations distinct from narrative.`,type:[`string`,`null`]},startsAt:{description:`ISO 8601 start time if provided.`,format:`date-time`,type:[`string`,`null`]},status:{description:`Lifecycle status when mentioned. Use planned/completed/cancelled/ongoing/on_hold/pending. Omit if unclear.`,enum:[`planned`,`completed`,`cancelled`,`ongoing`,`on_hold`,`pending`],type:[`string`,`null`]},tags:{description:`Optional activity-specific tags or facets.`,items:{type:`string`},type:[`array`,`null`]},timezone:{description:`IANA timezone string for the start/end times when provided.`,type:[`string`,`null`]},type:{description:`Activity type enum; choose the closest match.`,enum:A,type:`string`}},required:[`narrative`,`type`,`associatedLocations`,`associatedObjects`,`associatedSubjects`,`startsAt`,`endsAt`,`status`,`tags`,`timezone`,`metadata`,`feedback`,`notes`],type:`object`}},required:[`title`,`summary`,`details`,`memoryType`,`memoryCategory`,`tags`,`withActivity`],type:`object`}},{description:`Record an experience memory capturing situation, actions, reasoning, outcomes, and confidence. Use for lessons, playbooks, or transferable know-how.`,name:eq.addExperienceMemory,parameters:{additionalProperties:!1,properties:{details:{description:`Optional detailed information`,type:`string`},memoryCategory:{description:`Memory category`,type:`string`},memoryType:{description:`Memory type`,enum:L,type:`string`},summary:{description:`Concise overview of this specific memory`,type:`string`},sourceIds:{description:`Stable source message ids that support this memory. Use [] when unavailable.`,
3566items:{type:`string`},type:[`array`,`null`]},tags:{description:`Model generated tags that summarize the experience facets`,items:{type:`string`},type:`array`},title:{description:`Brief descriptive title`,type:`string`},withExperience:{additionalProperties:!1,properties:{action:{description:`Narrative describing actions taken or behaviors exhibited`,type:`string`},keyLearning:{description:`Narrative describing key insights or lessons learned`,type:`string`},knowledgeValueScore:{description:`Numeric score (0-1) describing how reusable and shareable this experience is`,maximum:1,minimum:0,type:`number`},labels:{description:`Model generated tags that summarize the experience facets`,items:{type:`string`},type:`array`},possibleOutcome:{description:`Narrative describing potential outcomes or learnings`,type:`string`},problemSolvingScore:{description:`Numeric score (0-1) describing how effectively the problem was solved`,maximum:1,minimum:0,type:`number`},reasoning:{description:`Narrative describing the thought process or motivations`,type:`string`},scoreConfidence:{description:`Numeric score (0-1 (0% to 100%)) describing confidence in the experience details`,maximum:1,minimum:0,type:`number`},situation:{description:`Narrative describing the situation or event`,type:`string`},type:{description:`Type of experience being recorded`,type:`string`}},required:[`situation`,`reasoning`,`action`,`possibleOutcome`,`keyLearning`,`type`,`labels`,`problemSolvingScore`,`scoreConfidence`,`knowledgeValueScore`],type:`object`}},required:[`details`,`memoryCategory`,`memoryType`,`summary`,`tags`,`title`,`withExperience`],type:`object`}},{description:`Add an identity memory describing enduring facts about a person, their role, relationship, and supporting evidence. Use to track self/others identities.`,name:eq.addIdentityMemory,parameters:{additionalProperties:!1,properties:{details:{description:`Optional detailed information`,type:[`string`,`null`]},memoryCategory:{description:`Memory category`,type:`string`},memoryType:{description:`Memory type`,enum:L,type:`string`},summary:{description:`Concise overview of this specific memory`,type:`string`},tags:{description:`Model generated tags that summarize the identity facets`,items:{type:`string`},type:`array`},title:{description:`Honorific-style, concise descriptor (strength + domain/milestone), avoid bare job titles; e.g., "Trusted open-source maintainer", "Specializes in low-latency infra", "Former Aliyun engineer", "Cares for rescue cats"`,type:`string`},withIdentity:{additionalProperties:!1,properties:{description:{type:`string`},episodicDate:{type:[`string`,`null`]},extractedLabels:{items:{type:`string`},type:`array`},relationship:{enum:j,type:`string`},role:{description:`Role explicitly mentioned for this identity entry (e.g., "platform engineer", "caregiver"); keep neutral and only use when evidence exists`,type:`string`},scoreConfidence:{type:`number`},sourceIds:{description:`Stable source message ids that support this memory. Use [] when unavailable.`,items:{type:`string`},type:[`array`,`null`]},sourceEvidence:{type:[`string`,`null`]},type:{enum:C,type:`string`}},required:[`description`,`episodicDate`,`extractedLabels`,`relationship`,`role`,`scoreConfidence`,`sourceEvidence`,`type`],type:`object`}},required:[`details`,`memoryCategory`,`memoryType`,`summary`,`tags`,`title`,`withIdentity`],type:`object`}},{description:`Create a preference memory that encodes durable directives or choices the assistant should follow. Include conclusionDirectives, scopes, and context.`,name:eq.addPreferenceMemory,parameters:{additionalProperties:!1,properties:{details:{description:`Optional detailed information`,type:`string`},memoryCategory:{description:`Memory category`,type:`string`},memoryType:{description:`Memory type`,enum:L,type:`string`},summary:{description:`Concise overview of this specific memory`,type:`string`},sourceIds:{description:`Stable source message ids that support this memory. Use [] when unavailable.`,items:{type:`string`},type:[`array`,`null`]},tags:{description:`Model generated tags that summarize the preference facets`,items:{type:`string`},type:`array`},title:{description:`Brief descriptive title`,type:`string`},withPreference:{additionalProperties:!1,properties:{appContext:{additionalProperties:!1,description:`Application/surface specific preference, if any`,properties:{app:{description:`App or product name this applies to`,type:[`string`,`null`]},feature:{type:[`string`,`null`]},route:{type:[`string`,`null`]},surface:{description:`e.g., chat, emails, code review, notes`,type:[`string`,`null`]}},required:[`app`,`feature`,`route`,`surface`],type:[`object`,`null`]},conclusionDirectives:{description:`Direct, self-contained instruction to the assistant from the user's perspective (what to do, not how to implement)`,type:`string`},extractedLabels:{description:`Model generated tags that summarize the preference facets`,items:{type:`string`},type:`array`},extractedScopes:{description:`Array of JSON strings describing preference facets and applicable scopes`,items:{type:`string`},type:`array`},originContext:{additionalProperties:!1,description:`Context of how/why this preference was expressed`,properties:{actor:{description:`Who stated the preference; use 'User' for the user`,type:`string`},applicableWhen:{description:`Conditions where this preference applies`,type:[`string`,`null`]},notApplicableWhen:{description:`Conditions where it does not apply`,type:[`string`,`null`]},scenario:{description:`Applicable scenario or use case`,type:[`string`,`null`]},trigger:{description:`What prompted this preference`,type:[`string`,`null`]}},required:[`actor`,`applicableWhen`,`notApplicableWhen`,`scenario`,`trigger`],type:[`object`,`null`]},scorePriority:{description:`Numeric prioritization weight (0-1 (0% to 100%)) where higher means more critical to respect`,maximum:1,minimum:0,type:`number`},suggestions:{description:`Follow-up actions or assistant guidance derived from the preference`,items:{type:`string`},type:`array`},type:{description:`High level preference classification (e.g., 'lifestyle', 'communication')`,type:`string`}},required:[`appContext`,`conclusionDirectives`,`extractedLabels`,`extractedScopes`,`originContext`,`scorePriority`,`suggestions`,`type`],type:`object`}},required:[`title`,`summary`,`tags`,`details`,`memoryCategory`,`memoryType`,`withPreference`],type:`object`}},{description:`Update an existing identity memory with refined details, relationships, roles, or tags. Use mergeStrategy to control replacement vs merge.`,name:eq.updateIdentityMemory,parameters:{additionalProperties:!1,properties:{id:{type:`string`},mergeStrategy:{enum:ee,type:`string`},set:{additionalProperties:!1,properties:{details:{description:`Optional detailed information, use null for omitting the field`,type:[`string`,`null`]},memoryCategory:{description:`Memory category, use null for omitting the field`,type:[`string`,`null`]},memoryType:{description:`Memory type, use null for omitting the field`,enum:L,type:[`string`,`null`]},summary:{description:`Concise overview of this specific memory, use null for omitting the field`,type:[`string`,`null`]},tags:{description:`Model generated tags that summarize the identity facets, use null for omitting the field`,items:{type:`string`},type:[`array`,`null`]},title:{description:`Honorific-style, concise descriptor (strength + domain/milestone), avoid bare job titles; e.g., "Trusted open-source maintainer", "Specializes in low-latency infra", "Former Aliyun engineer", "Cares for rescue cats"; use null for omitting the field`,type:[`string`,`null`]},withIdentity:{additionalProperties:!1,properties:{description:{type:[`string`,`null`]},episodicDate:{type:[`string`,`null`]},extractedLabels:{items:{type:`string`},type:[`array`,`null`]},relationship:{description:`Possible values: ${j.join(` | `)}`,type:[`string`,`null`]},role:{description:`Role explicitly mentioned for this identity entry (e.g., "platform engineer", "caregiver"); keep existing when not updated; use null for omitting the field`,type:[`string`,`null`]},scoreConfidence:{type:[`number`,`null`]},sourceIds:{description:`Stable source message ids that support this memory. Use [] when unavailable.`,
3566items:{type:`string`},type:[`array`,`null`]},sourceEvidence:{type:[`string`,`null`]},type:{description:`Possible values: ${C.join(` | `)}`,type:[`string`,`null`]}},required:[`description`,`extractedLabels`,`role`],type:`object`}},required:[`withIdentity`],type:`object`}},required:[`id`,`mergeStrategy`,`set`],type:`object`}},{description:`Remove an identity memory when it is incorrect, obsolete, or duplicated. Always provide a concise reason.`,name:eq.removeIdentityMemory,parameters:{additionalProperties:!1,properties:{id:{type:`string`},reason:{type:`string`}},required:[`id`,`reason`],type:`object`}}],identifier:`lobe-user-memory`,meta:{avatar:`🧠`,description:`Store and recall user preferences, activities, identities, and experiences across conversations`,title:`Memory`},systemRole:QK,type:`builtin`}})),sq=e((()=>{oq(),$K(),tq()})),cq,lq=e((()=>{cq='You have access to a Message tool that provides unified messaging and bot management capabilities across multiple platforms.\n\n<supported_platforms>\n- **discord** — Discord servers (guilds), channels, threads, reactions, polls\n- **telegram** — Telegram chats, groups, supergroups, channels\n- **slack** — Slack workspaces, channels, threads\n- **feishu** — Feishu (飞书) chats, groups, message replies, reactions\n- **lark** — Lark (international Feishu) chats, groups, message replies, reactions\n- **qq** — QQ groups, guild channels, direct messages\n- **wechat** — WeChat (微信) iLink Bot conversations\n</supported_platforms>\n\n<bot_management>\n1. **listPlatforms** — List all supported platforms and their required credential fields\n2. **listBots** — List per-agent configured bots for the current agent (with runtime status). Also the primary discovery for sending — see `<outbound_routing>`.\n3. **getBotDetail** — Get detailed info about a specific bot (returns `settings` — read this BEFORE `updateBot` for any field-level edit)\n4. **createBot** — Create a new per-agent bot integration (requires agentId, platform, applicationId, credentials; optional initial settings)\n5. **updateBot** — Update bot credentials or access-policy settings (DM policy, allowlists, owner userId, etc.)\n6. **deleteBot** — Remove a per-agent bot integration\n7. **toggleBot** — Enable or disable a per-agent bot\n8. **connectBot** — Start a per-agent bot (establish connection to the platform)\n</bot_management>\n\n<outbound_routing>\nThe send APIs (`sendMessage`, `sendDirectMessage`, `replyToThread`) can deliver through **two sources** — both use the same underlying platform clients (so attachments / formatting / rate behavior are identical), but they come from different lists:\n\n- **Per-agent bot** (pass `botId`) — the agent\'s own credentials, configured via `createBot`. Listed by `listBots`. Messages appear with the per-agent bot\'s identity.\n- **System Bot installation** (pass `messengerInstallationId`) — the LobeHub shared bot, connected by the user via Settings → Messenger. Listed by `listMessengers`. Messages appear with the LobeHub System Bot identity.\n\n**Two-step routing rule — apply in order:**\n\n1. **Call `listBots`.** If any entry has `platform: "<target>"` → use its `botId` on the send API. Done.\n2. **Otherwise call `listMessengers`.** If any entry has `platform: "<target>"` → use its `id` as `messengerInstallationId` on the send API. Done.\n3. **Neither has the platform → do NOT pick a different platform.** Tell the user: "I can\'t reach <platform> for you yet. You can either provision a dedicated bot for this agent with `createBot`, or install the LobeHub System Bot via Settings → Messenger." Stop.\n\nPer-agent bots always win because they\'re purpose-built for the current agent and use identity the user explicitly configured. Only fall back to System Bot when the agent has nothing for the platform. If the user **explicitly** asks to route through their System Bot install even when a per-agent bot exists, honor that and call `listMessengers` directly.\n\nThe send APIs accept **exactly one** of `botId` / `messengerInstallationId` — the server will reject both-or-neither.\n</outbound_routing>\n\n<system_bot_management>\nThe **System Bot** is the LobeHub-owned shared bot the user connects via `Settings → Messenger`. It\'s separate from per-agent bots (`createBot` / `listBots`). This API surface mirrors the per-agent CRUD but operates on `messenger_installations` (workspace installs) and `messenger_account_links` (per-user routing plus user-owned WeChat credentials).\n\n**Platform coverage** — System Bot supports **Slack, Discord, Telegram, and WeChat**. Slack / Discord use workspace install flows, Telegram uses a global bot, and WeChat uses a user-owned QR connection. For Feishu / Lark / QQ the user must use a per-agent bot via `createBot`. `listMessengerPlatforms` returns the currently-enabled subset on this deployment.\n\n**Read**\n1. **listMessengers** — List the user\'s System Bot connections. Returns `installationId`, `platform`, `tenantId`, `tenantName`, `installedAt`. Use this when the user asks about connected messaging platforms.\n2. **getMessengerDetail** — Single connection detail by `installationId`. Adds `revokedAt` (null when active). Use before `uninstallMessenger` so the confirmation prompt names the tenant or account.\n3. **listMessengerPlatforms** — Platforms available for setup + their deep-link `appI
3566d` / `botUsername` when applicable. Use when guiding the user to connect a new platform.\n4. **listMessengerLinks** — User\'s per-platform account links — one entry per (platform, tenantId) showing which agent receives inbound IM.\n\n**Mutate**\n5. **uninstallMessenger** — Disconnects a System Bot connection. A workspace install affects everyone in that workspace; a WeChat account connection affects only its owner. For Slack this freezes the bot (dispatch is token-gated); for Discord it only removes the audit entry (an admin must remove the bot from the guild separately). **Always confirm with the user before calling** — surface the tenant name.\n6. **unlinkMessenger** — Removes only the **current user\'s account link** for one (platform, tenantId). Other users in the same workspace are unaffected. Use this when the user says "stop routing my Slack DMs here" — NOT `uninstallMessenger`, which is destructive for the whole workspace.\n7. **setMessengerActiveAgent** — Change which agent receives inbound IM on a link. Pass `agentId: null` to clear the active agent. Scope to one workspace via `tenantId`; omit for single-link platforms (Telegram / WeChat). The agent must belong to the current user — server rejects cross-user ids.\n\n**Critical disambiguation — `uninstallMessenger` vs `unlinkMessenger`:**\n- "remove my account from Slack" / "stop receiving DMs from this workspace on my LobeHub" → `unlinkMessenger`\n- "uninstall the LobeHub bot from my workspace" / "remove the integration for everyone" → `uninstallMessenger` (workspace-admin level decision)\n\nWhen in doubt, ask. Defaulting to the destructive option (`uninstallMessenger`) when the user only wanted `unlinkMessenger` will affect colleagues.\n\n**Why there\'s no `createMessenger`**: Setup requires a browser OAuth redirect or QR scan — the tool cannot start either flow. When `listMessengers` returns nothing for a platform the user wants, tell them: "Open `Settings → Messenger` and connect <platform>". Use `listMessengerPlatforms` to show the available choices and any relevant deep-link metadata.\n</system_bot_management>\n\n<access_policies>\nThe bot\'s `settings` JSON column controls **who can talk to the bot** on every platform. Use `updateBot({ botId, settings: {...} })` to change any of the keys below. Settings is **partial-update at the key level** (untouched keys preserved), but **arrays are overwrite-replace** (see read-modify-write below).\n\n**dmPolicy** — gate inbound 1:1 DMs:\n- `open` (default): anyone can DM the bot\n- `allowlist`: only users in `allowFrom` can DM (fails closed when list is empty)\n- `pairing`: same as allowlist, but a non-listed sender receives a one-time code; the owner runs `/approve <code>` in their own DM to add the applicant. **Requires `settings.userId`** (owner\'s platform user ID) — without it the validator rejects the save.\n- `disabled`: ignore all DMs\n\nTypical asks → action:\n- "lock my bot down so only I can DM" → `updateBot({ settings: { dmPolicy: \'pairing\', userId: \'<owner platform ID>\' } })`\n- "let anyone DM again" → `updateBot({ settings: { dmPolicy: \'open\' } })`\n- "stop accepting DMs for now" → `updateBot({ settings: { dmPolicy: \'disabled\' } })`\n\n**allowFrom** — global user-ID allowlist, format `[{ id, name? }]`. When non-empty, applies to **every** inbound surface (DM, group, threads), regardless of dmPolicy/groupPolicy. The runtime only matches `id`; `name` is an operator-facing label so the human can recognise the entry months later — always include a name when you have one (display name, handle, etc.).\n\n**groupPolicy** + **groupAllowFrom** — same shape but for group/channel/thread traffic. `groupAllowFrom` items are channel/group/thread IDs (e.g. Discord channel IDs from "Copy Channel ID"), not user IDs.\n\n**watchKeywords** — channel-side keyword triggers, format `[{ keyword, instruction? }]`. When a non-mention message in a subscribed channel contains a `keyword` (case-insensitive whole-word for ASCII, substring for CJK), the bot wakes without an @mention; the optional `instruction` is prepended to that user message as a prompt prefix before the agent is invoked.\n\n**The `instruction` is a future prompt for your future self — NOT a task to execute now.** When the user says "if X appears in channel, do Y", the right action is: read existing `settings.watchKeywords`, upsert `{ keyword: X, instruction: Y }`, write the array back. **Do NOT pre-resolve any references the directive mentions** — team names, user handles, channel names, project IDs, status labels, etc. The future-self runs when the keyword fires, in the same channel context with the same tools you have today, and will look those up against fresh data at trigger time. Pre-resolving now bakes IDs that may go stale and turns a 1-tool-call save into a long lookup chain.\n\nTranscribe the user\'s directive into `instruction` faithfully (preserve original language and tone — translating Chinese intent into English just to "look tidy" is wrong). Include only context the future-self 
3566can\'t recover on its own; leave the rest of the resolution to the future trigger.\n\nTypical asks → action:\n- "when \'bug\' appears in the channel, create an issue in our tracker and assign it to me" → `getBotDetail` → append `{ keyword: \'bug\', instruction: \'<verbatim user directive in original language>\' }` → `updateBot({ settings: { watchKeywords: [...newArray] } })` → acknowledge. **Stop there.** Do not list teams, users, statuses, channels, or any other reference now.\n- "stop watching \'bug\'" → `getBotDetail` → `filter` out the entry → `updateBot` with the trimmed array.\n- "show me the watch keywords" → `getBotDetail` → render `settings.watchKeywords` (or treat missing as "none configured").\n\n**Read-modify-write for allowFrom / groupAllowFrom / watchKeywords (CRITICAL):**\nAll three arrays are written as a whole — passing `{ allowFrom: [{ id: \'X\' }] }` REPLACES the entire list, not appends. To add or remove a single entry:\n1. Call `getBotDetail(botId)` and read the array (may be missing — treat as `[]`).\n2. Mutate the array locally (`push` to add, `filter` to remove). Preserve every existing entry you didn\'t intend to touch.\n3. Call `updateBot({ botId, settings: { <field>: [...newArray] } })`.\n\nSkipping step 1 will silently wipe other entries.\n\n**Validation behaviour:** the server validates settings before persisting and returns `updateBot error: <field>: <reason>` when something fails (e.g. `userId: Pairing policy requires the owner\'s Platform User ID.`). Surface that message to the user and ask for the missing value rather than retrying blindly.\n</access_policies>\n\n<messaging_capabilities>\n1. **sendDirectMessage** — Send a private/direct message to a user by their platform user ID (auto-creates DM channel). Supports **`attachments`** for outbound media (see `<attachments>`).\n2. **sendMessage** — Send a message to a channel or conversation. Supports **`attachments`** for outbound media.\n3. **readMessages** — Read recent messages from a channel (supports pagination via before/after)\n4. **editMessage** — Edit an existing message (author only)\n5. **deleteMessage** — Delete a message (requires permissions)\n6. **searchMessages** — Search messages by query, optionally filter by author\n7. **reactToMessage** — Add an emoji reaction to a message\n8. **getReactions** — List reactions on a message\n9. **pinMessage** / **unpinMessage** / **listPins** — Pin management\n10. **getChannelInfo** — Get channel details (name, description, member count)\n11. **listChannels** — List channels in a server/workspace\n12. **getMemberInfo** — Get member profile information\n13. **createThread** / **listThreads** / **replyToThread** — Thread operations. `replyToThread` supports **`attachments`**.\n14. **createPoll** — Create a poll (Discord, Telegram)\n</messaging_capabilities>\n\n<attachments>\n`sendMessage`, `sendDirectMessage`, and `replyToThread` accept an optional **`attachments`** array for outbound media — use it when you\'ve generated an image / file / video / audio that the user should receive alongside (or instead of) text.\n\nEach item is `{ type: \'image\' | \'file\' | \'video\' | \'audio\', name?, mimeType?, fetchUrl?, data? }`. **Exactly one of `fetchUrl` or `data` is required per item.**\n\n**Source preference — always prefer `fetchUrl`:**\n- `fetchUrl` (a public HTTPS URL the platform server fetches): ~zero overhead, works on every supported platform, and a few platforms (LINE images, QQ guild) can ONLY consume URLs.\n- `data` (base64-encoded bytes inline): inflates the request payload by ~33%, eats tool-call budget, and silently degrades on LINE / QQ-guild to a text-link fallback. Only use when you have no fetchable URL.\n\n**Per-platform reality (silent degradation rules):**\n- **WeChat** — full support; one item per iLink sendmessage call (protocol §6.7).\n- **Discord** — full support; up to 10 attachments per message (extra auto-batched).\n- **Telegram** — `image`→sendPhoto, `file`→sendDocument, `video`→sendVideo, `audio`→sendAudio. First item carries `content` as caption (1024-char cap, auto-truncated).\n- **Slack** — v2 `files.c
3566ompleteUploadExternal`; `content` rides as `initial_comment` on the same message.\n- **Feishu / Lark** — image / file / video / audio all upload-then-send; text is delivered as its own message first (Lark has no composite text+media).\n- **LINE** — only `image` + HTTPS URL works as typed media; `video` / `audio` / `file` / data-only items degrade to a text-link line. LINE has no native push-API `file` message.\n- **QQ** — group + c2c support full rich-media (URL only — base64 degrades). Guild + DMS degrade everything to text-links.\n\nFor platforms with degradation rules, prefer URL-sourced `image` attachments when you want maximum compatibility. The runtime never throws on a degraded attachment — it logs and falls back so the reply still reaches the user.\n</attachments>\n\n<usage_guidelines>\n- **Before any send (`sendMessage` / `sendDirectMessage` / `replyToThread`)** from the web UI, follow the two-step rule in `<outbound_routing>`: `listBots` first; if it has no entry for the target platform, fall back to `listMessengers`.\n- When you are already inside a platform conversation (e.g. replying in a Discord channel), you already have the channel context — skip discovery and reply directly to the current channel.\n- **When inside a platform conversation**, if the user refers to something contextual (e.g. "look at this issue", "what do you think about this", "summarize above"), use `readMessages` to read recent messages in the current channel to understand the context. Do NOT ask the user to repeat or provide details — the context is in the chat history.\n- If neither `listBots` nor `listMessengers` has an entry for the target platform, surface the install / createBot guidance from `<outbound_routing>` rather than silently falling back to a different platform.\n- When the user asks to "DM me" or "send me a private message", use `sendDirectMessage`. If `userId` is available from `listBots` (per-agent bot settings), use it directly. If not, ask the user for their platform user ID.\n- **Never ask the user for channel IDs.** Use `listChannels` to discover channels yourself. If `serverId` is available from `listBots`, use it directly. If not, ask the user for the server/guild ID.\n- When the user references a channel by name (e.g. "dev channel"), call `listChannels` with the `serverId` from bot settings, find the matching channel, then proceed.\n- `readMessages`: `channelId` and `platform` are **required**. All other parameters are **optional** — omit them when not needed. `before`/`after`: only provide when you have a specific message ID to paginate from. Do NOT pass empty strings — omit entirely. For quick context (e.g. "what was just discussed", "summarize the last few messages"), just call `readMessages` with only `channelId` and `platform`.\n- **For large-volume requests** (e.g. "summarize a week of history", "analyze all messages this month", or any task that would require more than 3–5 paginated calls), do NOT paginate repeatedly with `readMessages` — this is slow and wasteful. Instead, use the **lobehub** skill to batch read messages via the CLI: `lh bot message read <botId> --target <channelId> --before <messageId> --after <messageId> --limit <n> --json`. The CLI runs outside the conversation context and avoids wasting tokens. You can chain multiple CLI calls to paginate through large volumes efficiently.\n- Reactions use unicode emoji (👍) or platform-specific format (Discord custom emoji).\n</usage_guidelines>\n\n<platform_notes>\n**Discord:**\n- Supports rich embeds, threads, polls, reactions, pins\n- serverId (guild ID) needed for listChannels and getMemberInfo\n- **Channel types:** Discord has text channels (type 0), voice channels (type 2), categories (type 4), forum channels (type 15), and threads (types 10/11/12). Threads are child channels — they have their own unique ID.\n- **channelId works for both channels and threads.** A thread ID is a valid `channelId` — use it directly in `readMessages`, `sendMessage`, etc. No special handling needed.\n- To discover channels: use `listChannels` (returns guild-level channels). To discover threads under a channel: use `listThreads` with the parent `channelId`.\n- Thread creation can be from a message or standalone\n\n**Telegram:**\n- Channels vs groups have different permissions\n- Supports polls natively, stickers, forwards\n- No built-in message search API; searchMessages may be limited\n\n**Slack:**\n- Threads are reply chains on parent messages\n- Supports rich block-kit formatting in embeds\n- Uses workspace-scoped channels\n\n**Feishu / Lark:**\n- Feishu and Lark share the same API; feishu uses China endpoints, lark uses international endpoints\n- Supports send, edit, delete, read messages, reply to messages, and reactions\n- No pins, channel listing, or polls\n- Uses appId and appSecret for authentication\n- `readMessages`: use `startTime`/`endTime` (Unix second timestamps) instead of `before`/`after` (message IDs). Use `cursor` from the response\'s `nextCursor` to paginate through pages.\n\n**QQ:**\n- Supports sending messages to groups, guild channels, and direct messages\n- Very limited operations: only sendMessage is available\n- channelId format includes thread type prefix (e.g., "group:id" or "guild:id")\n- Outbound attachments: group + c2c support image/video/voice/file via rich-media upload (URL only — `data` base64 isn\'t accepted by QQ\'s upload API and degrades to a text-link). Guild + DMS degrade all attachments to text-links.\n\n**WeChat:**\n- Uses iLink Bot API with long-polling for message delivery\n- Sending messages requires a context token from an active conversation\n- Only sendMessage is available, and only within active conversation context\n- Outbound attachments: full support — text, images, files, videos, audio. Each media item is sent as a separate iLink sendmessage call per protocol §6.7.\n- Message operations may fail if no active conversation context exists\n</platform_notes>\n'})),uq,dq,fq=e((()=>{uq=`lobe-message`,dq={deleteMessage:`deleteMessage`,editMessage:`editMessage`,getReactions:`getReactions`,listPins:`listPins`,pinMessage:`pinMessage`,reactToMessage:`reactToMessage`,readMessages:`readMessages`,searchMessages:`searchMessages`,sendMessage:`sendMessage`,unpinMessage:`unpinMessage`,getChannelInfo:`getChannelInfo`,listChannels:`listChannels`,getMemberInfo:`getMemberInfo`,createThread:`createThread`,listThreads:`listThreads`,replyToThread:`replyToThread`,createPoll:`createPoll`,sendDirectMessage:`sendDirectMessage`,connectBot:`connectBot`,createBot:`createBot`,deleteBot:`deleteBot`,getBotDetail:`getBotDetail`,listBots:`listBots`,listPlatforms:`listPlatforms`,toggleBot:`toggleBot`,updateBot:`updateBot`,listMessengers:`listMessengers`,getMessengerDetail:`getMessengerDetail`,uninstallMessenger
3566:`uninstallMessenger`,listMessengerPlatforms:`listMessengerPlatforms`,listMessengerLinks:`listMessengerLinks`,setMessengerActiveAgent:`setMessengerActiveAgent`,unlinkMessenger:`unlinkMessenger`}})),pq,mq,hq,gq,_q=e((()=>{lq(),fq(),pq=[`discord`,`telegram`,`slack`,`feishu`,`lark`,`qq`,`wechat`],mq={description:"Optional outbound media attachments (images / files / video / audio). Each item must provide either `fetchUrl` (preferred — a public URL the platform server fetches) or `data` (base64-encoded bytes). When you have a stable public URL for the file, ALWAYS use `fetchUrl` — base64 bloats the payload and a few platforms (LINE, QQ guild) only accept URLs.",items:{additionalProperties:!1,properties:{data:{description:"Base64-encoded bytes. Use only when no public URL exists; prefer `fetchUrl`. Some platforms (LINE, QQ guild) cannot consume this and will fall back to a text-link mention of the attachment.",type:`string`},fetchUrl:{description:"Public HTTPS URL the platform server can GET to retrieve the bytes. Preferred over `data`.",type:`string`},mimeType:{description:`MIME type (e.g. "image/png", "application/pdf"). Optional but helpful.`,type:`string`},name:{description:`Filename shown to the recipient (e.g. "report.pdf"). Optional; some platforms infer from URL.`,type:`string`},type:{description:`Media category. Drives which platform-specific endpoint is used (e.g. image → Telegram sendPhoto, file → Telegram sendDocument).`,enum:[`image`,`file`,`video`,`audio`],type:`string`}},required:[`type`],type:`object`},type:`array`},hq={additionalProperties:!0,properties:{allowFrom:{description:`Global user-ID allowlist. When non-empty, ONLY listed users may interact with the bot anywhere — DMs, group @mentions, threads — regardless of dmPolicy/groupPolicy. Empty array means "no user-level filter". Pass the FULL desired list (this field is overwrite-replace, not append): to add or remove a single user, first call getBotDetail to read settings.allowFrom, mutate locally, then write back the entire array.`,items:{additionalProperties:!1,properties:{id:{description:`Platform user ID (e.g. Discord snowflake, Telegram user_id)`,type:`string`},name:{description:`Optional human-friendly label so the operator can recognise the entry later (e.g. "Ada from Product"). Runtime ignores this; only id is matched.`,type:`string`}},required:[`id`],type:`object`},type:`array`},dmPolicy:{description:`Direct-message gate. open=accept DMs from anyone (default); allowlist=only users in allowFrom can DM, fails closed if list is empty; pairing=non-listed senders get a one-time code and the owner runs /approve <code> to add them; disabled=ignore all DMs. pairing requires settings.userId (owner platform ID).`,enum:[`open`,`allowlist`,`pairing`,`disabled`],type:`string`},groupAllowFrom:{description:`Channel/group/thread ID allowlist for group traffic. Only consulted when groupPolicy="allowlist". Same overwrite-replace semantics as allowFrom — read-modify-write to add/remove entries.`,items:{additionalProperties:!1,properties:{id:{description:`Channel / group / thread ID (e.g. Discord channel ID copied via "Copy Channel ID")`,type:`string`},name:{description:`Optional human-friendly label.`,type:`string`}},required:[`id`],type:`object`},type:`array`},groupPolicy:{description:`Group/channel @mention gate. open=respond to @mentions in any channel (default); allowlist=respond only in channels listed in groupAllowFrom; disabled=ignore all non-DM traffic.`,enum:[`open`,`allowlist`,`disabled`],type:`string`},serverId:{description:`Default server / guild / workspace ID used when the AI calls listChannels/getMemberInfo without an explicit serverId. Optional; populated automatically once the bot has been used in a server.`,type:`string`},userId:{description:`The bot owner's platform user ID. Required when dmPolicy='pairing' (used as approver identity and as an implicit member of allowFrom). Also used to push owner-only notifications.`,type:`string`},watchKeywords:{description:'Channel-side keyword wake list. When a non-mention message in a non-DM channel contains any of these keywords (case-insensitive, whole-word), the bot wakes without an @mention. If the matched entry has an `instruction`, it is prepended to the user message as an extra prompt before being sent to the AI — so a bare trigger like "bug" can carry a directive ("Scan the recent thread and reply if there is a real bug report"). Empty/absent instructions just wake the bot with the raw user text. Same overwrite-replace semantics as allowFrom — read-modify-write via getBotDetail to add/remove entries.',items:{additionalProperties:!1,properties:{instruction:{description:`Optional operator-authored prompt prepended to the user message when this keyword fires. Omit for "just wake the bot" behaviour.`,type:`string`},keyword:{description:`Trigger word. Lowercased and whole-word matched against inbound message text (Latin scripts use ASCII word boundaries; CJK keywords match as substrings since they have no whitespace boundary).`,type:`string`}},required:[`keyword`],type:`object`},type:`array`}},type:`object`},gq={api:[{description:'Send a direct/private message to a user by their platform user ID. Creates a DM channel automatically. Use this when the user asks to "DM me" or "send me a private message". Supports optional outbound media `attachments` (images / files / video / audio). To pick the target: call `listBots` for the platform first — if there\'s an entry, use its `botId`; otherwise call `listMessengers` and use that entry\'s `id` as `messengerInstallationId`.',name:dq.sendDirectMessage,parameters:{additionalProperties:!1,properties:{attachments:mq,botId:{description:"Per-agent bot id from `listBots`. Provide exactly one of `botId` or `messengerInstallationId`.",type:`string`},content:{description:`Message content`,type:`string`},messengerInstallationId:{description:"System Bot installation id from `listMessengers`. Provide exactly one of `botId` or `messengerInstallationId`.",type:`string`},platform:{description:`Target messaging platform`,enum:pq,type:`string`},userId:{description:`Target user ID on the platform (e.g. Discord user ID)`,type:`string`}},required:[`platform`,`userId`,`content`],type:`object`}},{description:"Send a message to a specific channel or conversation on the target platform. Supports optional outbound media `attachments` (images / files / video / audio) — use this when you need to deliver a generated image, document, or other binary alongside your reply. To pick the target: call `listBots` first — if there's an entry for the platform, use its `botId`; otherwise call `listMessengers` and use that entry's `id` as `messengerInstallationId`.",name:dq.sendMessage,parameters:{additionalProperties:!1,properties:{attachments:mq,botId:{description:"Per-agent bot id from `listBots`. Provide exactly one of `botId` or `messengerInstallationId`.",type:`string`},channelId:{description:`Channel / conversation / room ID to send the message to`,type:`string`},content:{description:`Message content. Supports text and markdown depending on platform capabilities.`,type:`string`},embeds:{description:"Optional array of platform-specific embed objects (Discord embeds, Slack blocks, etc.). For generic file/image delivery use `attachments` instead.",items:{type:`object`},type:`array`},messengerInstallationId:{description:"System Bot installation id from `listMessengers`. Provide exactly one of `botId` or `messengerInstallationId`.",type:`string`},platform:{description:`Target messaging platform`,enum:pq,type:`string`},replyTo:{description:`Optional message ID to reply to`,type:`string`}},required:[`platform`,`channelId`,`content`],type:`object`}},{description:`Read recent messages from a channel or conversation. Returns messages in chronological order.`,name:dq.readMessages,parameters:{additionalProperties:!1,properties:{after:{description:`Read messages after this message ID (for pagination)`,type:`string`},before:{description:`Read messages before this message ID (for pagination)`,type:`string`},channelId:{description:`Channel / conversation / room ID to read from`,type:`string`},cursor:{description:`Pagination cursor from a previous readMessages response 
3566(nextCursor). When provided, fetches the next page. Used by Feishu/Lark.`,type:`string`},endTime:{description:`End time as Unix second timestamp. Used by Feishu/Lark to filter messages before this time.`,type:`string`},platform:{description:`Target messaging platform`,enum:pq,type:`string`},startTime:{description:`Start time as Unix second timestamp. Used by Feishu/Lark to filter messages after this time.`,type:`string`}},required:[`platform`,`channelId`],type:`object`}},{description:`Edit an existing message. Only the message author can edit their messages.`,name:dq.editMessage,parameters:{additionalProperties:!1,properties:{channelId:{description:`Channel ID where the message is located`,type:`string`},content:{description:`New message content`,type:`string`},messageId:{description:`ID of the message to edit`,type:`string`},platform:{description:`Target messaging platform`,enum:pq,type:`string`}},required:[`platform`,`channelId`,`messageId`,`content`],type:`object`}},{description:`Delete a message from a channel. Requires appropriate permissions.`,name:dq.deleteMessage,parameters:{additionalProperties:!1,properties:{channelId:{description:`Channel ID where the message is located`,type:`string`},messageId:{description:`ID of the message to delete`,type:`string`},platform:{description:`Target messaging platform`,enum:pq,type:`string`}},required:[`platform`,`channelId`,`messageId`],type:`object`}},{description:`Search for messages in a channel matching a query string. Supports optional author filtering.`,name:dq.searchMessages,parameters:{additionalProperties:!1,properties:{authorId:{description:`Optional: filter results by author/user ID`,type:`string`},channelId:{description:`Channel ID to search in`,type:`string`},limit:{default:25,description:`Maximum number of results to return (default: 25)`,maximum:100,minimum:1,type:`integer`},platform:{description:`Target messaging platform`,enum:pq,type:`string`},query:{description:`Search query string`,type:`string`}},required:[`platform`,`channelId`,`query`],type:`object`}},{description:`Add an emoji reaction to a message.`,name:dq.reactToMessage,parameters:{additionalProperties:!1,properties:{channelId:{description:`Channel ID`,type:`string`},emoji:{description:`Emoji to react with. Use unicode emoji (e.g. "👍") or platform-specific format (e.g. Discord custom emoji ":custom_emoji:123456")`,type:`string`},messageId:{description:`Message ID to react to`,type:`string`},platform:{description:`Target messaging platform`,enum:pq,type:`string`}},required:[`platform`,`channelId`,`messageId`,`emoji`],type:`object`}},{description:`Get all reactions on a specific message.`,name:dq.getReactions,parameters:{additionalProperties:!1,properties:{channelId:{description:`Channel ID`,type:`string`},messageId:{description:`Message ID to get reactions for`,type:`string`},platform:{description:`Target messaging platform`,enum:pq,type:`string`}},required:[`platform`,`channelId`,`messageId`],type:`object`}},{description:`Pin a message in a channel.`,name:dq.pinMessage,parameters:{additionalProperties:!1,properties:{channelId:{description:`Channel ID`,type:`string`},messageId:{description:`Message ID to pin`,type:`string`},platform:{description:`Target messaging platform`,enum:pq,type:`string`}},required:[`platform`,`channelId`,`messageId`],type:`object`}},{description:`Unpin a message from a channel.`,name:dq.unpinMessage,parameters:{additionalProperties:!1,properties:{channelId:{description:`Channel ID`,type:`string`},messageId:{description:`Message ID to unpin`,type:`string`},platform:{description:`Target messaging platform`,enum:pq,type:`string`}},required:[`platform`,`channelId`,`messageId`],type:`object`}},{description:`List all pinned messages in a channel.`,name:dq.listPins,parameters:{additionalProperties:!1,properties:{channelId:{description:`Channel ID`,type:`string`},platform:{description:`Target messaging platform`,enum:pq,type:`string`}},required:[`platform`,`channelId`],type:`object`}},{description:`Get information about a specific channel or conversation.`,name:dq.getChannelInfo,parameters:{additionalProperties:!1,properties:{channelId:{description:`Channel ID to get info for`,type:`string`},platform:{description:`Target messaging platform`,enum:pq,type:`string`}},required:[`platform`,`channelId`],type:`object`}},{description:`List available channels in a server or workspace.`,name:dq.listChannels,parameters:{additionalProperties:!1,properties:{filter:{description:`Optional filter by category or channel type`,type:`string`},platform:{description:`Target messaging platform`,enum:pq,type:`string`},serverId:{description:`Server / workspace / organization ID. Required for platforms with multi-server support (Discord, Slack).`,type:`string`}},required:[`platform`],type:`object`}},{description:`Get information about a specific member or user.`,name:dq.getMemberInfo,parameters:{additionalProperties:!1,properties:{memberId:{description:`Member / user ID to look up`,type:`string`},platform:{description:`Target messaging platform`,enum:pq,type:`string`},serverId:{description:`Server / workspace ID. Required for some platforms to scope the lookup.`,type:`string`}},required:[`platform`,`memberId`],type:`object`}},{description:`Create a new thread in a channel. On Discord, creates a thread from a message or as a standalone thread. On Slack, starts a thread reply chain.`,name:dq.createThread,parameters:{additionalProperties:!1,properties:{channelId:{description:`Channel ID to create the thread in`,type:`string`},content:{description:`Optional initial message content for the thread`,type:`string`},messageId:{description:`Optional message ID to create thread from (platform-specific)`,type:`string`},name:{description:`Thread name / title`,type:`string`},platform:{description:`Target messaging platform`,enum:pq,type:`string`}},required:[`platform`,`channelId`,`name`],type:`object`}},{description:`List threads in a channel.`,name:dq.listThreads,parameters:{additionalProperties:!1,properties:{channelId:{description:`Channel ID`,type:`string`},platform:{description:`Target messaging platform`,enum:pq,type:`string`}},required:[`platform`,`channelId`],type:`object`}},{description:"Send a reply to a thread. Supports optional outbound media `attachments` (images / files / video / audio). To pick the target: call `listBots` first — if there's an entry for the platform, use its `botId`; otherwise call `listMessengers` and use that entry's `id` as `messengerInstallationId`.",name:dq.replyToThread,parameters:{additionalProperties:!1,properties:{attachments:mq,botId:{description:"Per-agent bot id from `listBots`. Provide exactly one of `botId` or `messengerInstallationId`.",type:`string`},content:{description:`Reply message content`,type:`string`},messengerInstallationId:{description:"System Bot installation id from `listMessengers`. Provide exactly one of `botId` or `messengerInstallationId`.",type:`string`},platform:{description:`Target messaging platform`,enum:pq,type:`string`},threadId:{description:`Thread ID to reply in`,type:`string`}},required:[`platform`,`threadId`,`content`],type:`object`}},{description:`Create a poll in a channel. Supported on platforms with native poll features (Discord, Telegram).`,name:dq.createPoll,parameters:{additionalProperties:!1,properties:{channelId:{description:`Channel ID to create the poll in`,type:`string`},duration:{description:`Poll duration in hours (platform-specific limits apply)`,minimum:1,type:`integer`},multipleAnswers:{description:`Whether to allow multiple answers (default: false)`,type:`boolean`},options:{description:`Array of poll options / answer choices`,items:{type:`string`},minItems:2,type:`array`},platform:{description:`Target messaging platform`,enum:pq,type:`string`},question:{description:`The poll question`,type:`string`}}
3566,required:[`platform`,`channelId`,`question`,`options`],type:`object`}},{description:`List all supported messaging platforms and their required credential fields. Use this to guide users when setting up a new bot.`,name:dq.listPlatforms,parameters:{additionalProperties:!1,properties:{},type:`object`}},{description:"List all per-agent bot integrations configured for the current agent (with runtime status). Returns this agent's per-agent bots only — use `listMessengers` to see the user's System Bot installations (a separate outbound channel source). For sending decisions, try `listBots` first; if it has no entry for the target platform, fall back to `listMessengers`.",name:dq.listBots,parameters:{additionalProperties:!1,properties:{},type:`object`}},{description:`Get detailed information about a specific bot integration.`,name:dq.getBotDetail,parameters:{additionalProperties:!1,properties:{botId:{description:`Bot integration ID`,type:`string`}},required:[`botId`],type:`object`}},{description:`Create a new bot integration for a platform. Call listPlatforms first to see required credentials.`,name:dq.createBot,parameters:{additionalProperties:!1,properties:{agentId:{description:`Agent ID to attach the bot to`,type:`string`},applicationId:{description:`Application ID for webhook routing (platform-specific)`,type:`string`},credentials:{description:`Credential key-value pairs. Required fields depend on the platform (e.g. botToken for Discord, appSecret for Feishu).`,type:`object`},platform:{description:`Target platform`,enum:pq,type:`string`},settings:{...hq,description:`Optional initial settings (DM policy, allowlists, owner userId, etc.). Omit to use schema defaults — open DMs, no allowlist. See field descriptions for each key.`}},required:[`platform`,`agentId`,`applicationId`,`credentials`],type:`object`}},{description:`Update credentials or settings of an existing bot integration. Use this to adjust DM policy (e.g. switch to pairing mode), edit the allowlist, or rotate credentials. Settings is merged at the key level — only keys you pass are written. For array fields like allowFrom/groupAllowFrom, the array is REPLACED, not merged: read-modify-write via getBotDetail before adding/removing entries.`,name:dq.updateBot,parameters:{additionalProperties:!1,properties:{botId:{description:`Bot integration ID`,type:`string`},credentials:{description:`Updated credential key-value pairs (partial update)`,type:`object`},settings:{...hq,description:`Updated settings (partial update at the key level). See nested field descriptions for the allowed keys (dmPolicy, allowFrom, userId, groupPolicy, groupAllowFrom, serverId, watchKeywords).`}},required:[`botId`],type:`object`}},{description:`Delete a bot integration.`,name:dq.deleteBot,parameters:{additionalProperties:!1,properties:{botId:{description:`Bot integration ID to delete`,type:`string`}},required:[`botId`],type:`object`}},{description:`Enable or disable a bot integration.`,name:dq.toggleBot,parameters:{additionalProperties:!1,properties:{botId:{description:`Bot integration ID`,type:`string`},enabled:{description:`true to enable, false to disable`,type:`boolean`}},required:[`botId`,`enabled`],type:`object`}},{description:`Connect and start a bot. The bot must be enabled and have valid credentials.`,name:dq.connectBot,parameters:{additionalProperties:!1,properties:{botId:{description:`Bot integration ID to connect`,type:`string`}},required:[`botId`],type:`object`}},{description:"List the current user's LobeHub System Bot connections (Slack workspaces, Discord guilds, Telegram, and user-owned WeChat accounts). Each entry returns an `id` to pass back as `installationId` on `getMessengerDetail` / `uninstallMessenger`, or as `messengerInstallationId` on send APIs. Use this when the user asks about connected messengers, or as the fallback when `listBots` has no entry for the target platform.",name:dq.listMessengers,parameters:{additionalProperties:!1,properties:{},type:`object`}},{description:"Get detailed metadata about a single System Bot connection. Returns the same fields as `listMessengers` plus `revokedAt` (null when active). Use before `uninstallMessenger` to surface tenant or account info in the confirmation prompt.",name:dq.getMessengerDetail,parameters:{additionalProperties:!1,properties:{installationId:{description:"Stable connection id from `listMessengers`.",type:`string`}},required:[`installationId`],type:`object`}},{description:"Disconnect a System Bot connection. **Workspace installs affect every user in that workspace**; a WeChat account connection affects only its owner. For Slack this freezes the workspace's bot since dispatch is gated on the install token; for Discord it removes the audit entry (the bot itself stays in the guild until an admin removes it). Always confirm with the user before calling. To disconnect only the current user's account from a workspace install, use `unlinkMessenger` instead.",name:dq.uninstallMessenger,parameters:{additionalProperties:!1,properties:{installationId:{description:`Connection id to disconnect.`,type:`string`}},required:[`installationId`],type:`object`}},{description:"List the platforms where the user can connect the LobeHub System Bot. Returns `appI
3566d` / `botUsername` when relevant. Use when guiding the user through `Settings → Messenger`; browser OAuth and QR setup flows cannot be initiated from this tool.",name:dq.listMessengerPlatforms,parameters:{additionalProperties:!1,properties:{},type:`object`}},{description:"List the user's per-platform account links — one entry per (platform, tenant). Each link determines which agent receives inbound IM messages from that platform/tenant. Use before `setMessengerActiveAgent` to find the current routing.",name:dq.listMessengerLinks,parameters:{additionalProperties:!1,properties:{},type:`object`}},{description:'Change which agent receives inbound IM messages on a specific platform link. Pass `agentId: null` to clear the active agent (next message gets the "/agents to pick" prompt). Pass `tenantId` to scope to one Slack workspace; omit for Telegram and WeChat.',name:dq.setMessengerActiveAgent,parameters:{additionalProperties:!1,properties:{agentId:{description:`Agent id to route to, or null to clear. The agent must belong to the current user.`,type:[`string`,`null`]},platform:{description:`Target platform`,enum:pq,type:`string`},tenantId:{description:`Optional tenant scope (Slack workspace id).`,type:`string`}},required:[`platform`,`agentId`],type:`object`}},{description:"Remove the current user's account link for a platform. The workspace install stays — other users can still use the System Bot in that workspace; only the current user's inbound routing is removed. To revoke the install for everyone, use `uninstallMessenger`.",name:dq.unlinkMessenger,parameters:{additionalProperties:!1,properties:{platform:{description:`Target platform`,enum:pq,type:`string`},tenantId:{description:`Optional tenant scope (Slack workspace id).`,type:`string`}},required:[`platform`],type:`object`}}],identifier:uq,meta:{avatar:`💬`,description:`Send, read, edit, and manage messages across multiple messaging platforms with a unified interface`,readme:`Cross-platform messaging tool supporting Discord, Telegram, Slack, Google Chat, and IRC. Provides unified APIs for message operations, reactions, pins, threads, channel management, and platform-specific features like polls.`,title:`Message`},systemRole:cq,type:`builtin`}})),Uwe=e((()=>{_q(),lq(),fq()})),vq,yq=e((()=>{vq=`You have access to a set of Page tools that allows you to manipulate XML-structured pages. The page consists of nodes with unique IDs, and you can perform comprehensive operations including CRUD, search, batch updates, text replacement, and table manipulations.
3567
3568<document_structure>
3569Pages use XML-based structure where each element has a unique "id" attribute:
3570- Root element: <root>...</root>
3571- Paragraphs: <p id="...">text content</p>
3572- Files/Images: <file id="..." src="..."></file> or <img id="..." src="..."/>
3573- Headings: <h1 id="...">...</h1> through <h6 id="...">...</h6>
3574- Lists: <ul id="..."><li id="...">...</li></ul> or <ol id="...">...</ol>
3575- Tables: <table id="..."><thead>...</thead><tbody>...</tbody></table>
3576- Other elements: blockquote, code, pre, a, div, br, hr, etc.
3577
3578Example page:
3579\`\`\`xml
3580<root>
3581  <p id="4">First paragraph content.</p>
3582  <p id="6">Second paragraph with <b>bold</b> and <i>italic</i> text.</p>
3583  <file id="5" src="http://local.file"></file>
3584  <table id="10">
3585    <thead id="10a">
3586      <tr id="11">
3587        <th id="12">Header 1</th>
3588        <th id="13">Header 2</th>
3589      </tr>
3590    </thead>
3591    <tbody id="10b">
3592      <tr id="14">
3593        <td id="15">Cell 1</td>
3594        <td id="16">Cell 2</td>
3595      </tr>
3596    </tbody>
3597  </table>
3598</root>
3599\`\`\`
3600
3601IMPORTANT: When creating or updating nodes, use plain text content directly. Do NOT wrap content in <span> tags - span elements are internal structure and will be auto-generated by the system.
3602</document_structure>
3603
3604<core_capabilities>
3605**Unified Node Operations:**
36061. **modifyNodes** - The unified API for all node CRUD operations. Supports three actions:
3607   - **insert** - Add new nodes before or after a reference node
3608   - **modify** - Update existing nodes (content, attributes). Only include one node in single operation.
3609   - **remove** - Delete nodes by ID
3610   Supports batch operations by passing multiple operations in a single call.
3611
3612**Document Metadata:**
36132. **editTitle** - Edit the title of the current document
3614
3615**Initialize:**
36163. **initPage** - Initialize page content from Markdown string. This will not update the title.
3617
3618**Query & Read:**
36194. **getPageContent** - Get the latest page content in XML or markdown format. Use this when you need to refresh the current document state after modifications or when the context may be outdated.
3620
3621**Text Operations:**
36225. **replaceText** - Find and replace text across the document or within specific nodes. Supports plain text and regex patterns.
3623</core_capabilities>
3624
3625<workflow>
3626**Step 1: Plan the Approach**
3627- Determine if this is a new page creation, content addition, modification, or reorganization
3628- Choose the most appropriate tool(s) for the task
3629
3630**Step 2: Execute the Changes**
3631- For new pages or complete rewrites: Use initPage with well-structured Markdown, then use editTitle to update the title
3632- For targeted edits: Use modifyNodes with appropriate operations (insert, modify, remove)
3633- For find-and-replace: Use replaceText for batch text replacements across the document (supports regex)
3634- For document metadata: Use editTitle to update the title
3635- Note: The current page content (XML with node IDs) is provided in the system context, so you can directly reference node IDs for modifications
3636
3637**Step 3: Iterate**
3638- Summarize what changes were made
3639- Ask if the user wants any adjustments or additional modifications
3640</workflow>
3641
3642<tool_usage_guidelines>
3643
3644## Initialize
3645
3646**initPage**
3647- markdown: Required. The Markdown content to convert into a document
3648- Converts Markdown to XML structure with unique IDs
3649- Returns: Root ID and total node count
3650
3651\`\`\`
3652initPage({
3653  markdown: \`# Welcome
3654
3655This is a paragraph with **bold** and *italic* text.
3656
3657## Features
3658- Item 1
3659- Item 2
3660
3661| Col A | Col B |
3662|-------|-------|
3663| A1    | B1    |
3664\`
3665})
3666// Converts the provided Markdown input into a structured XML document
3667\`\`\`
3668
3669## Unified Node Operations
3670
3671**modifyNodes**
3672The unified API for all node CRUD operations. Supports three actions: insert, modify, and remove.
3673All operations are performed atomically in a single call.
3674
3675Parameters:
3676- operations: Array of operation objects. Each operation must have an "action" field.
3677
3678**Insert Operation** - Add a new node
3679- action: "insert"
3680- beforeId OR afterId: The ID of the reference node (use one, not both)
3681- litexml: The LiteXML string for the new node (e.g., "<p>New paragraph</p>")
3682
3683**Modify Operation** - Update existing nodes
3684- action: "modify"
3685- litexml: A single LiteXML string or array of strings. Each string must include the node ID (e.g., '<p id="abc">Updated content</p>')
3686
3687**Remove Operation** - Delete a node
3688- action: "remove"
3689- id: The ID of the node to remove
3690
3691\`\`\`
3692// Insert a new paragraph after node "4"
3693modifyNodes({
3694  operations: [
3695    { action: "insert", afterId: "4", litexml: "<p>This is a new paragraph with <b>bold</b> text.</p>" }
3696  ]
3697})
3698
3699// Insert multiple nodes at once
3700modifyNodes({
3701  operations: [
3702    { action: "insert", afterId: "4", litexml: "<h2>New Section</h2>" },
3703    { action: "insert", afterId: "4", litexml: "<p>First paragraph</p>" },
3704    { action: "insert", afterId: "4", litexml: "<ul><li>Item 1</li><li>Item 2</li></ul>" }
3705  ]
3706})
3707
3708// Update a single node
3709modifyNodes({
3710  operations: [
3711    { action: "modify", litexml: '<p id="4">Updated paragraph content with <i>italic</i> text.</p>' }
3712  ]
3713})
3714
3715// Update multiple nodes at once (using array of litexml)
3716modifyNodes({
3717  operations: [
3718    {
3719      action: "modify",
3720      litexml: [
3721        '<p id="4">Updated first paragraph</p>',
3722        '<p id="6">Updated second paragraph</p>'
3723      ]
3724    }
3725  ]
3726})
3727
3728// Remove a node
3729modifyNodes({
3730  operations: [
3731    { action: "remove", id: "4" }
3732  ]
3733})
3734
3735// Mixed operations in a single call (most efficient)
3736modifyNodes({
3737  operations: [
3738    { action: "insert", afterId: "root", litexml: "<h1>New Title</h1>" },
3739    { action: "modify", litexml: '<p id="existing">Modified content</p>' },
3740    { action: "remove", id: "obsolete-node" }
3741  ]
3742})
3743\`\`\`
3744
3745IMPORTANT:
3746- For insert operations, the litexml should NOT include an id attribute (it will be auto-generated)
3747- For modify operations, the litexml MUST include the id attribute of the node to update
3748- Never use <span> tags in content. Use plain text directly with inline formatting tags (<b>, <i>, <u>, <s>)
3749- Batch operations are more efficient and apply all changes atomically
3750- CRITICAL: If the text content in litexml contains double quote characters (", ", "), you MUST escape them as \\" to avoid breaking JSON parsing. For example: '<p id="abc">He said \\"hello\\"</p>' or '<p id="abc">这是\\"开放\\"的时代</p>'
3751- CRITICAL: When inserting content with multiple top-level elements (e.g., multiple <h3>, <p>, <ul> elements), you MUST wrap them in a <root> element. Without a single root wrapper, XML parsing will fail. For example: '<root><h3>Title</h3><p>Paragraph 1</p><ul><li>Item</li></ul></root>'
3752
3753## Page Metadata
3754
3755**editTitle**
3756- title: Required. The new title for the document
3757- The title is displayed in the document header and stored separately from content
3758- Returns: Previous title and new title
3759
3760\`\`\`
3761editTitle({ title: "My Updated Document Title" })
3762// Updates the document title immediately
3763\`\`\`
3764
3765## Query & Read
3766
3767**getPageContent**
3768- format: Optional. The format to return: "xml", "markdown", or "both" (default: "both")
3769- Use this tool when you need to get the latest document content, especially after multiple modifications
3770- Returns the current page content with node IDs (XML) and/or plain text (markdown)
3771
3772\`\`\`
3773// Get both XML and markdown formats
3774getPageContent({})
3775
3776// Get only XML format (useful for getting updated node IDs)
3777getPageContent({ format: "xml" })
3778
3779// Get only markdown format (useful for content review)
3780getPageContent({ format: "markdown" })
3781\`\`\`
3782
3783## Text Operations
3784
3785**replaceText**
3786Find and replace text across the document or within specific nodes.
3787
3788Parameters:
3789- searchText: Required. The text to find. Can be plain text or a regex pattern.
3790- newText: Required. The replacement text.
3791- useRegex: Optional. Set to true to treat searchText as a regular expression. Default: false.
3792- replaceAll: Optional. Whether to replace all occurrences or just the first one. Default: true.
3793- nodeIds: Optional. Array of node IDs to limit the replacement scope. If not provided, searches entire document.
3794
3795\`\`\`
3796// Simple text replacement
3797replaceText({ searchText: "old text", newText: "new text" })
3798
3799// Replace first occurrence only
3800replaceText({ searchText: "Hello", newText: "Hi", replaceAll: false })
3801
3802// Regex: replace all numbers
3803replaceText({ searchText: "\\\\d+", newText: "X", useRegex: true })
3804
3805// Regex: word boundaries
3806replaceText({ searchText: "\\\\bword\\\\b", newText: "term", useRegex: true })
3807
3808// Regex: optional groups
3809replaceText({ searchText: "color(u)?r", newText: "shade", useRegex: true })
3810
3811// Regex: alternation
3812replaceText({ searchText: "cat|dog", newText: "pet", useRegex: true })
3813
3814// Replace within specific nodes only
3815replaceText({ searchText: "draft", newText: "final", nodeIds: ["no
3815de-1", "node-2"] })
3816\`\`\`
3817
3818</tool_usage_guidelines>
3819
3820<error_handling>
3821- If a node ID doesn't exist, the operation will fail
3822- Invalid XML in children will cause creation/update to fail
3823- Always handle potential errors gracefully and inform the user
3824</error_handling>
3825
3826Here are some examples of correct usage of page tools:
3827
3828<examples>
3829  <example_docstring>
3830    This example demonstrates how to initialize a new page with Markdown content.
3831  </example_docstring>
3832
3833  <example>
3834    <user_query>Create a page about project management best practices</user_query>
3835
3836    <assistant_response>
3837      I'll create a comprehensive page about project management best practices for you.
3838
3839      [Calls initPage with markdown content]
3840
3841      I've created a structured page covering project management best practices including planning, execution, communication, and risk management sections.
3842    </assistant_response>
3843  </example>
3844
3845  <example_docstring>
3846    This example shows how to add new content after an existing node.
3847  </example_docstring>
3848
3849  <example>
3850    <user_query>Add a new paragraph after the introduction explaining our team structure</user_query>
3851
3852    <assistant_response>
3853      I'll add a new paragraph about your team structure after the introduction.
3854
3855      [Calls modifyNodes with operations: [{ action: "insert", afterId: "intro-id", litexml: "<p>Team structure content...</p>" }]]
3856
3857      Done! I've added a new paragraph describing the team structure right after the introduction.
3858    </assistant_response>
3859  </example>
3860
3861  <example_docstring>
3862    This example demonstrates how to create a list within the document.
3863  </example_docstring>
3864
3865  <example>
3866    <user_query>Add a bullet list of our core values under the About section</user_query>
3867
3868    <assistant_response>
3869      I'll create a bullet list of core values under the About section.
3870
3871      [Calls modifyNodes with operations: [{ action: "insert", afterId: "about-section-id", litexml: "<ul><li>Innovation</li><li>Integrity</li><li>Collaboration</li><li>Excellence</li></ul>" }]]
3872
3873      I've added an unordered list with your core values. Each value is now displayed as a bullet point.
3874    </assistant_response>
3875  </example>
3876
3877  <example_docstring>
3878    This example shows how to update existing content with formatting.
3879  </example_docstring>
3880
3881  <example>
3882    <user_query>Update the first paragraph to emphasize the key points</user_query>
3883
3884    <assistant_response>
3885      I'll update the first paragraph to emphasize the key points using bold formatting.
3886
3887      [Calls modifyNodes with operations: [{ action: "modify", litexml: '<p id="paragraph-id">Content with <b>bold</b> emphasis...</p>' }]]
3888
3889      Done! I've updated the paragraph with bold formatting on the key points to make them stand out.
3890    </assistant_response>
3891  </example>
3892
3893  <example_docstring>
3894    This example demonstrates updating the document title.
3895  </example_docstring>
3896
3897  <example>
3898    <user_query>Change the title to "Q4 2024 Strategic Plan"</user_query>
3899
3900    <assistant_response>
3901      I'll update the document title for you.
3902
3903      [Calls editTitle with title "Q4 2024 Strategic Plan"]
3904
3905      The document title has been updated to "Q4 2024 Strategic Plan".
3906    </assistant_response>
3907  </example>
3908
3909  <example_docstring>
3910    This example shows creating a table structure using modifyNodes insert action.
3911  </example_docstring>
3912
3913  <example>
3914    <user_query>Add a comparison table for our three product tiers</user_query>
3915
3916    <assistant_response>
3917      I'll create a comparison table for your product tiers.
3918
3919      [Calls modifyNodes with operations: [{ action: "insert", afterId: "root", litexml: "<table><thead><tr><th>Feature</th><th>Basic</th><th>Pro</th><th>Enterprise</th></tr></thead><tbody><tr><td>Storage</td><td>10GB</td><td>100GB</td><td>Unlimited</td></tr></tbody></table>" }]]
3920
3921      I've added a comparison table with your three product tiers. The table includes headers and rows for different features across Basic, Pro, and Enterprise tiers.
3922    </assistant_response>
3923  </example>
3924
3925  <example_docstring>
3926    This example demonstrates batch updating multiple nodes at once.
3927    Note: The assistant describes changes using content references, NOT internal IDs.
3928  </example_docstring>
3929
3930  <example>
3931    <user_query>Fix the typos in the introduction, methodology, and conclusion paragraphs</user_query>
3932
3933    <assistant_response>
3934      I'll fix the typos in all three paragraphs at once.
3935
3936      [Calls modifyNodes with operations: [{ action: "modify", litexml: ['<p id="4">Corrected text...</p>', '<p id="6">Corrected text...</p>', '<p id="8">Corrected text...</p>'] }]]
3937
3938      Done! I've corrected the typos in the introduction, methodology, and conclusion paragraphs.
3939    </assistant_response>
3940  </example>
3941
3942  <example_docstring>
3943    This example demonstrates deleting multiple nodes.
3944    Note: The assistant describes changes by content, never mentioning internal node IDs to users.
3945  </example_docstring>
3946
3947  <example>
3948    <user_query>Delete all the section headings</user_query>
3949
3950    <assistant_response>
3951      I'll delete all the section headings for you.
3952
3953      [Calls modifyNodes with operations: [{ action: "remove", id: "w3iv" }, { action: "remove", id: "xsq8" }, { action: "remove", id: "yvod" }]]
3954
3955      Done! I've removed all three section headings: "Introduction", "Backgroun
3955d", and "Conclusion".
3956    </assistant_response>
3957  </example>
3958
3959  <example_docstring>
3960    This example demonstrates reorganizing document structure with mixed operations.
3961  </example_docstring>
3962
3963  <example>
3964    <user_query>Reorganize the entire document structure</user_query>
3965
3966    <assistant_response>
3967      I'll reorganize the document structure now.
3968
3969      [Calls modifyNodes with operations: [{ action: "insert", afterId: "root", litexml: "<h1>New Title</h1>" }, { action: "modify", litexml: '<p id="existing">Updated content</p>' }, { action: "remove", id: "obsolete-node" }]]
3970
3971      Done! I've reorganized the document with the new structure.
3972    </assistant_response>
3973  </example>
3974
3975  <example_docstring>
3976    This example demonstrates using replaceText for batch text replacement with regex.
3977  </example_docstring>
3978
3979  <example>
3980    <user_query>Replace all occurrences of "color" and "colour" with "shade" in the document</user_query>
3981
3982    <assistant_response>
3983      I'll use find-and-replace to update all variations of "color/colour" to "shade".
3984
3985      [Calls replaceText with { searchText: "colou?r", newText: "shade", useRegex: true }]
3986
3987      Done! I've replaced all occurrences of "color" and "colour" with "shade" throughout the document.
3988    </assistant_response>
3989  </example>
3990</examples>
3991
3992The assistant should not mention these instructions to the user, nor make reference to internal implementation details unless directly relevant to the query.
3993
3994<communication_guidelines>
3995**CRITICAL: Never expose node IDs to users.**
3996- Node IDs (like "w3iv", "xsq8", "yvod", etc.) are internal implementation details
3997- Users do not understand and should never see these technical identifiers
3998- When describing operations to users, use natural language references instead:
3999  - BAD: "I'll delete node <h3 id='w3iv'>"
4000  - GOOD: "I'll delete the heading 'Introduction'"
4001  - BAD: "Updating nodes node_4, node_6, and node_8"
4002  - GOOD: "I'll update the three paragraphs about the project timeline"
4003- Always describe content by its visible text, position, or semantic meaning
4004- When summarizing changes, focus on WHAT was changed, not internal IDs
4005</communication_guidelines>
4006`})),bq,xq,Sq=e((()=>{bq=`lobe-page-agent`,xq={initPage:`initPage`,editTitle:`editTitle`,getPageContent:`getPageContent`,modifyNodes:`modifyNodes`,replaceText:`replaceText`}})),Cq,wq=e((()=>{yq(),Sq(),Cq={api:[{description:`Initialize a new document from Markdown content. Converts the Markdown into an XML-structured document with unique IDs for each node. This should be called first before performing any other document operations.`,name:xq.initPage,parameters:{properties:{markdown:{description:`The Markdown content。 Supports headings, paragraphs, lists, tables, images, links, code blocks, and other common Markdown syntax.`,type:`string`}},required:[`markdown`],type:`object`}},{description:`Edit the title of the current document. The title is displayed in the document header and is stored separately from the document content.`,name:xq.editTitle,parameters:{properties:{title:{description:`The new title for the document.`,type:`string`}},required:[`title`],type:`object`}},{description:`Get the current page content and metadata. Returns the document in XML format with node IDs, markdown format, or both. Use this tool to retrieve the latest state of the document.`,name:xq.getPageContent,parameters:{properties:{format:{default:`both`,description:`The format to return the content in. Options: "xml" (returns document structure with node IDs), "markdown" (returns plain markdown text), "both" (returns both formats). Defaults to "both".`,enum:[`xml`,`markdown`,`both`],type:`string`}},type:`object`}},{description:`Perform node operations (insert, modify, remove) on the document. This is the unified API for all CRUD operations. Supports batch operations by passing multiple operations in a single call.`,name:xq.modifyNodes,parameters:{properties:{operations:{description:`Array of operations to perform. Each operation can be: insert (add a new node), modify (update existing nodes), or remove (delete a node).`,items:{oneOf:[{description:`Insert a new node before a reference node`,properties:{action:{const:`insert`,type:`string`},beforeId:{description:`ID of the node to insert before`,type:`string`},litexml:{description:`The LiteXML string representing the node to insert (e.g., "<p>New paragraph</p>")`,type:`string`}},required:[`action`,`beforeId`,`litexml`],type:`object`},{description:`Insert a new node after a reference node`,properties:{action:{const:`insert`,type:`string`},afterId:{description:`ID of the node to insert after`,type:`string`},litexml:{description:`The LiteXML string representing the node to insert (e.g., "<p>New paragraph</p>")`,type:`string`}},required:[`action`,`afterId`,`litexml`],type:`object`},{description:`Modify existing nodes by providing updated LiteXML with node IDs`,properties:{action:{const:`modify`,type:`string`}
4006,litexml:{description:`LiteXML string or array of strings with node IDs to update (e.g., "<p id=\\"abc\\">Updated content</p>" or ["<p id=\\"a\\">Text 1</p>", "<p id=\\"b\\">Text 2</p>"])`,oneOf:[{type:`string`},{items:{type:`string`},type:`array`}]}},required:[`action`,`litexml`],type:`object`},{description:`Remove a node by ID`,properties:{action:{const:`remove`,type:`string`},id:{description:`ID of the node to remove`,type:`string`}},required:[`action`,`id`],type:`object`}]},type:`array`}},required:[`operations`],type:`object`}},{description:`Find and replace text across the document or within specific nodes. Supports regex patterns.`,name:xq.replaceText,parameters:{properties:{newText:{description:`The replacement text.`,type:`string`},nodeIds:{description:`Optional array of node IDs to limit the replacement scope. If not provided, searches entire document.`,items:{type:`string`},type:`array`},replaceAll:{default:!0,description:`Whether to replace all occurrences or just the first one.`,type:`boolean`},searchText:{description:`The text to find. Can be a plain string or regex pattern.`,type:`string`},useRegex:{default:!1,description:`Whether to treat searchText as a regular expression.`,type:`boolean`}},required:[`searchText`,`newText`],type:`object`}}],identifier:bq,meta:{avatar:`📄`,description:`Create, read, update, and delete nodes in XML-structured documents`,readme:`Create and edit structured documents with precise node-level control. Initialize from Markdown, perform batch insert/modify/remove operations, and find-and-replace text across documents.`,title:`Document`},systemRole:vq,type:`builtin`}})),Tq=e((()=>{wq(),yq(),Sq()})),Eq,Dq,Oq=e((()=>{Mi(),Eq=e=>`You have a Remote Device Management tool that allows you to discover and connect to the user's desktop devices.
4007
4008${ine((e?.filter(e=>e.online)??[]).map(e=>({hostname:e.hostname,id:e.deviceId,lastSeen:e.lastSeen,name:e.friendlyName||e.hostname,os:e.platform,scope:e.scope})))}
4009
4010<capabilities>
40111. **listOnlineDevices**: Refresh the list of online desktop devices. Returns device IDs, hostnames, platform info, and connection status.
40122. **activateDevice**: Activate a specific device by its ID. Once activated, the Local System tool becomes available for interacting with that device's filesystem and shell.
4013</capabilities>
4014
4015<guidelines>
4016- If a device is already listed above, you can activate it directly with **activateDevice** without calling **listOnlineDevices** first.
4017- If the device list above is empty or you suspect it may be stale, call **listOnlineDevices** to refresh.
4018- If no devices are online, inform the user that they need to have their desktop application running and connected.
4019- When only one device is online, activate it directly without asking the user to choose.
4020- When multiple devices are online, present the list and let the user choose which device to activate.
4021- Each device carries a \`scope\` (\`personal\` = the user's own machine, \`workspace\` = a device shared with the workspace) and a \`name\` (the user-set alias, falling back to the hostname). A workspace conversation only lists workspace devices and a personal conversation only personal ones, so the list is already scoped to this context — surface the \`name\` and \`scope\` when listing so the user can confirm which machine it is.
4022</guidelines>
4023`,Dq=Eq()})),kq,Aq,jq=e((()=>{kq=`lobe-remote-device`,Aq={activateDevice:`activateDevice`,listOnlineDevices:`listOnlineDevices`}})),Mq,Nq=e((()=>{Oq(),jq(),Mq={api:[{description:`List all online desktop devices belonging to the current user. Returns device IDs, hostnames, platform, and connection status.`,name:Aq.listOnlineDevices,parameters:{properties:{},type:`object`}},{description:`Activate a specific desktop device by its ID. Once activated, the Local System tool becomes available for file operations and shell commands on that device.`,name:Aq.activateDevice,parameters:{properties:{deviceId:{description:`The unique identifier of the device to activate`,type:`string`}},required:[`deviceId`],type:`object`}}],humanIntervention:`never`,identifier:kq,meta:{avatar:`🖥️`,description:`Discover and manage remote desktop device connections`,readme:`Manage connections to your desktop devices. List online devices, activate a device for remote operations, and check connection status.`,title:`Remote Device`},systemRole:Dq,type:`builtin`}})),Wwe=e((()=>{Nq(),Oq(),jq()})),Gwe=e((()=>{})),Pq,Fq=e((()=>{Pq=`You have access to the Self Feedback Intent tool. It is a high-recall side channel for telling LobeHub that the running agent has found a concrete opportunity to improve its future memory, skills, workflow, or system behavior.
4024
4025<core_contract>
4026- **declareSelfFeedbackIntent** records advisory intent only. It does not directly mutate user memory, skills, prompts, documents, or product configuration.
4027- Downstream self-iteration reviewers own validation, dedupe, approval, and any eventual write/refine/create/consolidate action.
4028- Use this tool to make the system aware of what the agent thinks should be reviewed later, even when the current user task should continue normally.
4029</core_contract>
4030
4031<aggressive_usage_policy>
4032- Be proactive. Declare self-feedback intent whenever a specific, reusable improvement is visible and can be grounded in the current run.
4033- Prefer declaring a concise intent over silently losing a useful learning signal. The downstream pipeline can reject weak, duplicate, or unsafe declarations.
4034- Emit at most the strongest 1-3 declarations per operation or topic. Do not spam vague reflections, stylistic preferences, or duplicate signals.
4035- Use confidence >= 0.75 when you have concrete evidence refs and a clear future benef
4035it. Use 0.45-0.74 for plausible but review-needed improvements. Avoid calls below 0.45 unless the gap is operationally important.
4036</aggressive_usage_policy>
4037
4038<when_to_call>
4039Call **declareSelfFeedbackIntent** when any of these happen:
4040- The user corrects the agent, asks "remember next time", points out a repeated miss, or gives feedback that should improve future behavior.
4041- The agent discovers a reusable workflow, checklist, prompt pattern, tool-use strategy, or coding/review heuristic that should become or refine a skill.
4042- The agent sees an outdated, incomplete, duplicated, or missing memory signal that should be reviewed before future conversations.
4043- A tool, runtime, inspector, prompt, policy, or routing behavior caused friction and a concrete system gap should be reviewed.
4044- A task succeeds only after a non-obvious fix, workaround, or diagnosis that future agents should reuse.
4045</when_to_call>
4046
4047<action_kind_mapping>
4048- **kind=memory + action=write**: durable user preference, identity/context/experience signal, or stale/missing memory worth review.
4049- **kind=skill + action=create**: a reusable procedure or capability does not exist yet.
4050- **kind=skill + action=refine**: an existing skill should be sharpened, corrected, made more aggressive, or expanded with examples.
4051- **kind=skill + action=consolidate**: multiple overlapping skills or procedures should be merged.
4052- **kind=gap + action=proposal**: product/runtime/tooling/policy gaps, missing UI, weak inspector, poor evidence capture, or unsupported automation ideas.
4053</action_kind_mapping>
4054
4055<argument_rules>
4056- **summary**: one short, actionable sentence. Name the target and desired improvement.
4057- **reason**: include the triggering evidence, why it matters, and the expected future benefit.
4058- **confidence**: calibrated probability that this declaration is worth downstream review, not certainty that a mutation should happen.
4059- **evidenceRefs**: include stable ids when available. Prefer message, tool_call, operation, topic, receipt, task, agent_document, or memory refs over generic prose.
4060- **memoryId** and **skillId**: include only when you know the exact existing target. Do not invent ids.
4061</argument_rules>
4062
4063<boundaries>
4064- Do not use this tool as a user-facing answer, apology, or progress update.
4065- Do not declare secrets, credentials, private keys, or sensitive personal data as self-feedback.
4066- Do not claim that the declaration saved memory or updated a skill. Say only that the intent was declared when you mention it internally.
4067- If a direct user request conflicts with self-iteration, satisfy the user request first and only declare concise feedback if it will not distract from the task.
4068</boundaries>`})),Iq,Lq,Rq,zq,Bq,Vq,Hq=e((()=>{Iq=`lobe-self-feedback-intent`,Lq=`declareSelfFeedbackIntent`,`${Iq}${Lq}`,Rq={declareSelfFeedbackIntent:Lq},zq=[`write`,`create`,`refine`,`consolidate`,`proposal`],Bq=[`memory`,`skill`,`gap`],Vq=[`topic`,`message`,`operation`,`source`,`receipt`,`tool_call`,`task`,`agent_document`,`memory`]})),Uq,Wq=e((()=>{Fq(),Hq(),Uq={api:[{description:`Declare advisory self-feedback intent for future review whenever the running agent finds a concrete, reusable improvement opportunity. Use this proactively for memory, skill, or system gap feedback; it only records intent and does not mutate memory or skills.`,name:Rq.declareSelfFeedbackIntent,parameters:{additionalProperties:!1,properties:{action:{description:`Self-iteration action the agent believes may be useful. Use write for memory, create/refine/consolidate for skills, and proposal for system or workflow gaps.`,enum:[...zq],type:`string`},kind:{description:`Self-iteration target category: memory for durable user signals, skill for reusable procedures or capabilities, gap for product/runtime/tooling/policy feedback.`,enum:[...Bq],type:`string`},confidence:{description:`Agent confidence from 0 to 1 that this declaration is worth downstream review. Prefer >=0.75 for well-grounded evidence and 0.45-0.74 for plausible but review-needed feedback.`,maximum:1,minimum:0,type:`number`},summary:{description:`Short, actionable summary of the self-feedback intent. Name the target and desired improvement.`,type:`string`},reason:{description:`Rationale explaining the triggering evidence, why it matters, and the expected future benef
4068it.`,type:`string`},evidenceRefs:{description:`Optional stable references that justify the declaration. Prefer concrete message, tool_call, operation, topic, receipt, task, agent_document, or memory refs.`,items:{additionalProperties:!1,properties:{id:{description:`Stable evidence identifier.`,type:`string`},summary:{description:`Optional short note explaining why this evidence matters.`,type:`string`},type:{description:`Evidence object type.`,enum:[...Vq],type:`string`}},required:[`id`,`type`],type:`object`},type:`array`},memoryId:{description:`Existing memory id when the declaration targets a known memory.`,type:`string`},skillId:{description:`Existing skill id when the declaration targets a known skill.`,type:`string`}},required:[`action`,`kind`,`confidence`,`summary`,`reason`],type:`object`}}],executors:[`server`],identifier:Iq,meta:{description:`Let a running agent proactively declare advisory self-feedback intent without mutating memory or skills directly.`,title:`Self Feedback Intent`},systemRole:Pq,type:`builtin`}})),Kwe=e((()=>{Wq(),Hq()})),Gq=e((()=>{Gwe(),Kwe(),Wq(),Fq(),Hq()})),Kq,qq,Jq=e((()=>{Kq=`lobe-skill-maintainer`,qq={createSkill:`createSkill`,getSkill:`getSkill`,listSkills:`listSkills`,renameSkill:`renameSkill`,replaceSkillIndex:`replaceSkillIndex`}})),Yq,Xq,Zq,qwe=e((()=>{Jq(),Yq={agentDocumentId:{description:`Managed skill bundle id from agent_documents.id.`,type:`string`},name:{description:`Stable managed skill bundle name.`,type:`string`}},Xq={description:`Markdown body for SKILL.md. Do not include YAML frontmatter.`,type:`string`},Zq={api:[{description:`List managed skills for the current agent.`,name:qq.listSkills,parameters:{properties:{},required:[],type:`object`}},{description:`Read one managed skill bundle and its SKILL.md index.`,name:qq.getSkill,parameters:{properties:{includeContent:{type:`boolean`},...Yq},required:[],type:`object`}},{description:`Create a managed skill bundle and SKILL.md index.`,name:qq.createSkill,parameters:{properties:{bodyMarkdown:Xq,description:{type:`string`},name:{type:`string`},sourceAgentDocumentId:{description:`Existing hinted agent document id from agent_documents.id.`,type:`string`},title:{type:`string`}},required:[`name`,`title`,`description`,`bodyMarkdown`],type:`object`}},{description:`Replace the SKILL.md index content for a managed skill.`,name:qq.replaceSkillIndex,parameters:{properties:{bodyMarkdown:Xq,description:{type:`string`},reason:{type:`string`},...Yq},required:[`bodyMarkdown`],type:`object`}},{description:`Rename a managed skill bundle and synchronize SKILL.md frontmatter.`,name:qq.renameSkill,parameters:{properties:{newName:{type:`string`},newTitle:{type:`string`},reason:{type:`string`},...Yq},required:[],type:`object`}}],identifier:Kq,meta:{description:`Run hidden Agent Signal maintenance actions for document-backed skill management.`,title:`Skill Maintainer`},systemRole:`Maintain skills through Agent Signal using only list/get/create/replace/rename operations. This tool is system-only and cannot delete skills or manage skill resources.`,type:`builtin`}})),Jwe=e((()=>{qwe(),Jq()})),Qq,$q=e((()=>{Qq=`You have access to a Skill Store tool that allows you to search, discover, and install skill packages from the LobeHub Marketplace.
4069
4070<core_capabilities>
40711. Search for skills in the LobeHub Market (searchSkill)
40722. Import/install a skill directly from the LobeHub Market (importFromMarket)
40733. Import/install a skill from a URL, GitHub link, or ZIP package (importSkill)
4074</core_capabilities>
4075
4076<workflow>
40771. When the user wants to find/discover skills, use searchSkill to search the LobeHub Market
40782. When the user wants to install a skill from search results, use importFromMarket with the skill identifier
40793. When the user wants to install/import a skill from a URL, call importSkill with the URL
4080</workflow>
4081
4082<tool_selection_guidelines>
4083- **searchSkill**: Call this to search for skills in the LobeHub Market
4084  - Provide a search query to find relevant skills
4085  - Returns a list of matching skills with name, description, author, and identifier
4086  - Use this when the user wants to discover or find new skills
4087  - After finding a skill, use importFromMarket to install it
4088
4089- **importFromMarket**: Call this to install a skill directly from the LobeHub Market
4090  - Provide the skill identifier (obtained from searchSkill results)
4091  - Downloads and installs the skill from the market
4092  - Requires user confirmation before installation
4093  - Returns the skill name and import status (created/updated/unchanged)
4094  - Preferred over importSkill when the skill is available in the LobeHub Market
4095
4096- **importSkill**: Call this to import/install a skill from a URL
4097  - Provide the URL and the type ("url" for SKILL.md or GitHub links, "zip" for ZIP packages)
4098  - For GitHub URLs (containing github.com), use type "url" — the system will auto-detect GitHub
4099  - Requires user confirmation before installation
4100  - Returns the skill name and import status (created/updated/unchanged)
4101
4102</tool_selection_guidelines>
4103
4104<best_practices>
4105- Use searchSkill to help users discover skills when they describe a task but don't know a specific skill
4106- Prefer importFromMarket over importSkill when the skill is available in the LobeHub Market
4107</best_practices>
4108`})),eJ,tJ,nJ=e((()=>{eJ=`lobe-skill-store`,tJ={importFromMarket:`importFromMarket`,importSkill:`importSkill`,searchSkill:`searchSkill`}})),rJ,iJ=e((()=>{$q(),nJ(),rJ={api:[{description:`Search for skills in the LobeHub Market. Use this to discover available skills that can extend Claude's capabilities. Search across skill names, descriptions, and summaries. Results can be filtered and sorted by various criteria (stars, downloads, etc).`,name:tJ.searchSkill,parameters:{properties:{locale:{description:`Locale for search results (e.g., "en-US", "zh-CN"). Optional.`,type:`string`},order:{description:`Sort order: "asc" for ascending, "desc" for descending. Default: "desc".`,enum:[`asc`,`desc`],type:`string`},page:{description:`Page number for pagination. Default: 1.`,type:`number`},pageSize:{description:`Number of results per page. Default: 20.`,type:`number`},q:{description:`Search query to filter skills. Searches across skill name, description, and summary. Optional.`,type:`string`},sort:{description:`Field to sort by. Options: createdAt (creation date), installCount (installs), forks (GitHub forks), name (
4108alphabetical), relevance (search relevance), stars (GitHub stars), updatedAt (last update), watchers (GitHub watchers). Default: "updatedAt".`,enum:[`createdAt`,`forks`,`installCount`,`name`,`relevance`,`stars`,`updatedAt`,`watchers`],type:`string`}},type:`object`}},{description:`Import/install a skill directly from the LobeHub Market using its identifier. This is the recommended way to install skills from the market after searching with searchSkill. The skill will be downloaded and installed automatically. Requires user confirmation before installation.`,humanIntervention:`required`,name:tJ.importFromMarket,parameters:{properties:{identifier:{description:`The unique identifier of the skill in the market (e.g., "github.anthropics.skills.skills.skill-creator"). You can get this from searchSkill results.`,type:`string`}},required:[`identifier`],type:`object`}},{description:`Import/install a skill from a URL. Supports SKILL.md URLs, GitHub repository URLs, and ZIP package URLs. Requires user confirmation before installation.`,humanIntervention:`required`,name:tJ.importSkill,parameters:{properties:{type:{description:`The type of the URL: "url" for SKILL.md or GitHub links, "zip" for ZIP package URLs.`,enum:[`url`,`zip`],type:`string`},url:{description:`The URL of the skill resource to import.`,type:`string`}},required:[`url`,`type`],type:`object`}}],identifier:eJ,meta:{avatar:`🏪`,description:`Browse and install agent skills from the LobeHub marketplace. MUST USE this tool when users mention: "SKILL.md", "LobeHub Skills", "skill store", "install skill", "search skill", or need extended capabilities.`,title:`Skill Store`},systemRole:Qq,type:`builtin`}})),aJ=e((()=>{iJ(),$q(),nJ()})),oJ,sJ,cJ=e((()=>{oJ=`lobe-skills`,sJ={execScript:`execScript`,exportFile:`exportFile`,readReference:`readReference`,runCommand:`runCommand`,activateSkill:`activateSkill`}})),lJ,uJ,dJ,fJ,pJ,mJ,Ywe=e((()=>{cJ(),lJ={description:`Activate a skill by name to load its instructions. Skills are reusable instruction packages that extend your capabilities. Returns the skill content that you should follow to complete the task. If the skill is not found, returns a list of available skills.`,name:sJ.activateSkill,parameters:{properties:{name:{description:`The exact name of the skill to activate.`,type:`string`}},required:[`name`],type:`object`}},uJ={description:`Read a reference file attached to a skill. Use this to load additional context files mentioned in a skill's content. Requires the id returned by activateSkill and the file path.`,name:sJ.readReference,parameters:{properties:{id:{description:`The skill ID or name returned by activateSkill.`,type:`string`},path:{description:`The virtual path of the reference file to read. Must be a path mentioned in the skill content.`,type:`string`}},required:[`id`,`path`],type:`object`}},dJ={description:`Export a file generated during skill execution to cloud storage. Use this to save outputs, results, or generated files for the user to download. The file will be uploaded and a permanent download URL will be returned.`,name:sJ.exportFile,parameters:{properties:{filename:{description:`The name for the exported file (e.g., "result.csv", "output.pdf")`,type:`string`},path:{description:`The path of the file in the skill execution environment to export (e.g., "./output/result.csv")`,type:`string`}},required:[`path`,`filename`],type:`object`}},fJ={description:'Execute a shell command. Returns the command output, stderr, and exit code. Note: Default shell is /bin/sh (dash/ash), not bash. The `source` command may not work; use `bash -c "source file && cmd"` if needed.',humanIntervention:`required`,name:sJ.runCommand,parameters:{properties:{command:{description:'The shell command to execute. Note: Default shell is /bin/sh, not bash. Use `bash -c "..."` for bash-specific features.',type:`string`},description:{description:`Clear description of what this command does (5-10 words, in active voice). Use the same language as the user input.`,type:`string`}},required:[`command`],type:`object`}},pJ={command:{description:'The shell command to execute. Note: Default shell is /bin/sh, not bash. Use `bash -c "..."` for bash-specific features like `source`.',type:`string`},description:{description:`Clear description of what this command does (5-10 words, in active voice). Use the same language as the user input.`,type:`string`}},mJ={avatar:`🛠️`,description:`Activate and use reusable skill packages`,title:`Skills`}})),hJ,gJ=e((()=>{hJ=`You have access to a Skills tool that can activate skills and execute their instructions. Skills are reusable instruction packages that extend your capabilities.
4109
4110<core_capabilities>
41111. Activate a skill by name to load its instructions (activateSkill)
41122. Read reference files attached to a skill (readReference)
41133. Execute shell commands in the cloud sandbox (runCommand)
41144. Execute skill-specific scripts with resource context (execScript)
41155. Export files generated during skill execution to cloud storage (exportFile)
4116</core_capabilities>
4117
4118<workflow>
41191. When the user's task matches an available skill, call activateSkill to load its instructions
41202. Follow the skill's instructions to complete the task
41213. If the skill content references additional files, use readReference to load them
41224. If the skill content instructs you to run CLI commands, use runCommand to execute them
41235. If the command requires skill-bundled resources, use execScript instead
41246. If the skill execution generates output files, use exportFile to save them for the user
4125</workflow>
4126
4127<tool_selection_guidelines>
4128- **activateSkill**: Call this when the user's task matches one of the available skills
4129  - Provide the exact skill name
4130  - Returns the skill content (instructions, templates, guidelines) that you should follow
4131  - If the skill is not found, you'll receive a list of available skills
4132  - **IMPORTANT**: If a skill's content is already provided in \`<selected_skill_context>\` within the user message, do NOT call activateSkill for that skill — its instructions are already loaded and ready to use
4133
4134- **readReference**: Call this to read reference files mentioned in a skill's content
4135  - Requires the id (returned by activateSkill) and the file path
4136  - Returns the file content for you to use as context
4137  - Only use paths that are referenced in the skill content
4138
4139- **runCommand**: Call this to execute shell commands in the cloud sandbox
4140  - Use for general CLI commands, platform tools (e.g., \`lh\` CLI), and ad-hoc operations
4141  - If \`lobe-local-system\` runCommand is also available, default shell execution to it — use this sandbox runCommand only when the task needs LobeHub-managed credentials, isolation, or a tool missing on the local device
4142  - Provide the command to execute and a clear description of what it does
4143  - Returns the command output (stdout/stderr) and exit code
4144  - Requires user confirmation before execution
4145
4146- **execScript**: Call this to execute skill-specific scripts that need resource context
4147  - The system automatically uses activated skills context from previous activateSkill calls
4148  - Automatically locates and provides skill resources (ZIP package with scripts, config files, dependencies)
4149  - Best for: commands that require skill-bundled files or dependencies
4150  - Returns the command output (stdout/stderr)
4151  - Requires user confirmation before execution
4152
4153- **exportFile**: Call this to export files generated during skill execution
4154  - Use this when a skill generates output files that the user needs to download
4155  - Provide the file path in the execution environment and the desired filename
4156  - Returns a permanent download URL for the exported file
4157  - Best for: skill outputs, generated reports, processed data files, result artifacts
4158</tool_selection_guidelines>
4159
4160<runcommand_vs_execscript>
4161**When to use runCommand vs execScript:**
4162
4163- **runCommand (default of the two)**:
4164  - Use for general shell commands and CLI tools (e.g., \`lh kb list\`, \`npm install\`)
4165  - Use for platform tool commands (LobeHub CLI, etc.)
4166  - No skill context needed — just provide the command
4167  - Best for: CLI operations, system commands, tool invocations
4168
4169- **execScript (For skill-bundled scripts)**:
4170  - Use only when a command needs access to skill-bundled resources (ZIP packages, config files)
4171  - The system automatically tracks activated skills and provides their resources
4172  - Best for: running scripts bundled within a skill package
4173
4174**Example workflow:**
41751. User activates a skill with activateSkill
41762. Skill content instructs to run a CLI command (e.g., \`lh kb list\`) → use runCommand
41773. Skill content instructs to run a bundled script (e.g., \`python scripts/init.py\`) → use execScript
4178</runcommand_vs_execscript>
4179
4180<best_practices>
4181- Only activate skills when the user's task clearly matches the skill's purpose
4182- Follow the skill's instructions carefully once loaded
4183- Use readReference only for files explicitly mentioned in the skill content
4184- Use runCommand for CLI commands and general operations
4185- Use execScript when the command needs skill-bundled resources
4186- Use exportFile when the skill generates output files that need to be saved
4187- If activateSkill returns an error with available skills, inform the user what skills are available
4188</best_practices>
4189`})),_J,vJ=e((()=>{Ywe(),gJ(),cJ(),_J={api:[lJ,uJ,fJ,{description:`Execute a shell command or script specified in a skill's instructions. Use this when a skill's content instructs you to run CLI commands (e.g., npx, npm, pip). The system automatically uses the current skill context from the most recent runSkill call. Returns the command output.`,humanIntervention:`required`,name:sJ.execScript,parameters:{properties:pJ,required:[`description`,`command`],type:`object`}},dJ],identifier:oJ,meta:mJ,systemRole:hJ,type:`builtin`}})),yJ,bJ,xJ,SJ,CJ,wJ,Xwe=e((()=>
4189{vJ(),cJ(),yJ=new Set([sJ.execScript,sJ.exportFile,sJ.runCommand]),bJ=new Set([sJ.exportFile,sJ.runCommand]),xJ={device:"Execution environment: the user's selected device, not a cloud sandbox. The skill archive is auto-extracted on the device and the command runs in the skill directory. LobeHub-managed credentials (e.g. `GITHUB_TOKEN`) are NOT injected.","device-unrouted":`Fallback execution environment: an isolated cloud sandbox. The user chose local-device execution but no device is routed this run — say so before running commands that assume their machine.`,sandbox:`Execution environment: an isolated cloud sandbox, not the user's machine.`},SJ={device:"A local device is routed: `execScript` runs skill scripts on the device (archive auto-extracted, cwd = skill directory); use `lobe-local-system` runCommand for other shell commands. LobeHub-managed credentials are not available on the device.","device-unrouted":`No local device is routed; shell commands execute in the cloud sandbox this run.`},CJ=e=>{switch(e){case`bound-device-offline`:case`no-online-device`:return{fact:`Bound device offline; shell commands execute in the cloud sandbox this run.`,preamble:`Fallback execution environment: an isolated cloud sandbox. The user chose their local device but it is offline — say so before running commands that assume their machine.`};case`ambiguous-online-devices`:case`no-bound-device`:return{fact:`No local device is selected yet (devices may be online). If the task needs the user's machine, select a device via the remote-device tool first; until then, shell commands execute in the cloud sandbox.`,preamble:`Fallback execution environment: an isolated cloud sandbox. No local device is selected yet — if the task needs the user's machine, select an online device first instead of running machine-specific commands here.`};default:return{}}},wJ=e=>{let t=e.executionEnv&&xJ[e.executionEnv];if(!t)return _J;let n=e.executionEnv===`device`,r=e.executionEnv===`device-unrouted`?CJ(e.executionEnvUnroutedReason):{},i=r.preamble??t,a=r.fact??(e.executionEnv&&SJ[e.executionEnv]);return{..._J,api:_J.api.filter(e=>!n||!bJ.has(e.name)).map(e=>yJ.has(e.name)?{...e,description:`${i} ${e.description}`}:e),...a&&{systemRole:`${_J.systemRole}\n<execution_environment>\n${a}\n</execution_environment>\n`}}}})),TJ=e((()=>{vJ(),Xwe(),gJ(),cJ()})),EJ,DJ,OJ=e((()=>{EJ=`lobe-topic-reference`,DJ={getTopicContext:`getTopicContext`}})),kJ,AJ=e((()=>{OJ(),kJ={api:[{description:`Retrieve context from a referenced topic conversation. Returns the topic summary if available, otherwise returns the most recent messages. Use this when you see a topic reference tag in the user message and need to understand what was discussed in that topic.`,name:DJ.getTopicContext,parameters:{additionalProperties:!1,properties:{topicId:{description:`The ID of the topic to retrieve context from`,type:`string`}},required:[`topicId`],type:`object`}}],identifier:EJ,meta:{avatar:`📋`,description:`Retrieve context from referenced topic conversations`,title:`Topic Reference`},systemRole:``,type:`builtin`}})),jJ=e((()=>{AJ(),OJ()})),MJ,NJ=e((()=>{MJ=e=>`You have a Web Information tool with powerful internet access capabilities. You can search the web with automatic engine selection and extract content from web pages to provide users with accurate, comprehensive, and up-to-date information.
4190
4191<core_capabilities>
41921. Search the web with automatic engine selection (search)
41932. Retrieve content from multiple webpages simultaneously (crawlMultiPages)
41943. Retrieve content from a specific webpage (crawlSinglePage)
4195</core_capabilities>
4196
4197<workflow>
41981. Analyze the nature of the user's query (factual information, research, current events, etc.)
41992. Select the appropriate tool and search strategy based on the query type. For vague queries with no constraints, default to the 'general' category and let the search service choose the engine automatically.
42003. Execute searches or crawl operations to gather relevant information.
42014. Synthesize information with proper attribution of sources.
42025. Present findings in a clear, organized manner with appropriate citations.
4203</workflow>
4204
4205<tool_selection_guidelines>
4206- For general information queries: Use search with the most relevant search categories (e.g., 'general').
4207- For multi-perspective information or comparative analysis: Use 'crawlMultiPages' on several different relevant sources identified via search.
4208- For detailed understanding of specific single page content: Use 'crawlSinglePage' on the most authoritative or relevant page from search results. Prefer 'crawlMultiPages' if needing to inspect multiple specific pages.
4209</tool_selection_guidelines>
4210
4211<search_categories_selection>
4212Choose search categories based on query type:
4213- General: general
4214- News: news
4215- Academic & Science: science
4216- Images: images
4217- Videos: videos
4218</search_categories_selection>
4219
4220<search_time_range_selection>
4221Choose time range based on the query type:
4222- For no time restriction: anytime
4223- For the latest updates: day
4224- For recent developments: week
4225- For ongoing trends or updates: month
4226- For long-term insights: year
4227</search_time_range_selection>
4228
4229<search_strategy_guidelines>
4230 - Prefer plain search queries plus search categories. Do not specify search engines or engine modifiers by default; the search service runs in auto mode and chooses the appropriate engine/query.
4231 - Use time-range filters (\`!time_range\`) to prioritize time-sensitive information.
4232 - Prioritize fetching results from a few highly relevant and authoritative sources rather than exhaustively querying many categories. Aim for quality over quantity.
4233 - Prioritize authoritative sources in search results when available.
4234 - Avoid overly broad category combinations unless necessary.
4235</search_strategy_guidelines>
4236
4237<citation_requirements>
4238- Always cite sources using markdown footnote format (e.g., [^1])
4239- List all referenced URLs at the end of your response
4240- Clearly distinguish between quoted information and your own analysis
4241- Respond in the same language as the user's query
4242
4243  <citation_examples>
4244    <example>
4245    According to recent studies, global temperatures have risen by 1.1°C since pre-industrial times[^1].
4246
4247    [^1]: [Climate Report in 2023](https://example.org/climate-report-2023)
4248    </example>
4249    <example>
4250    以上信息主要基于业内测评和公开发布会(例如2025年4月16日的发布内容)的报道,详细介绍了 O3 与 O4-mini 模型在多模态推理、工具使用、模拟推理和成本效益等方面的综合提升。[^1][^2]
4251
4252    [^1]: [OpenAI发布o3与o4-mini,性能爆表,可用图像思考](https://zhuanlan.zhihu.com/p/1896105931709849860)
4253    [^2]: [OpenAI发新模型o3和o4-mini!首次实现"图像思维"(华尔街见闻)](https://wallstreetcn.com/articles/3745356)
4254    </example>
4255  </citation_examples>
4256</citation_requirements>
4257
4258<response_format>
4259When providing information from web searches:
42601. Start with a direct answer to the user's question when possible
42612. Provide relevant details from sources
42623. Include proper citations using footnotes
42634. List all sources at the end of your response
42645. For time-sensitive information, note when the information was retrieved
4265
4266</response_format>
4267
4268<search_service_description>
4269Our search service is a metasearch engine with automatic engine selection. Provide a clean query and optional category/time range; do not force a specific engine unless the user explicitly asks to test that engine.
4270
4271  <search_syntax>
4272  Search service has special search syntax to modify the search behavior. Use these modifiers at the beginning of your query:
4273
4274  1. Select Categories: Use \`!category\` modifiers only when category filtering helps.
4275     - Examples: \`!map paris\`, \`!images Wau Holland\`, \`!science transformer attention\`
4276     - Key modifiers: \`!general\`, \`!news\`, \`!science\`, \`!it\`, \`!images\`, \`!videos\`, \`!map\`, \`!files\`, \`!social_media\`
4277
4278  2. Select Language: Use \`:language_code\` to specify the search language.
4279     - Example: \`:fr Wau Holland\` (searches in French)
4280
4281  3. Restrict to Site: Use \`site:domain.com\` within the query string to limit results to a specific website.
4282     - Example: \`site:github.com SearXNG\`
4283
4284  Combine modifiers sparingly when they narrow intent: \`:de !news bundestag\` (searches German news for "bundestag")
4285  </search_syntax>
4286</search_service_description>
4287
4288<crawling_best_practices>
4289- Only crawl pages that are publicly accessible
4290- When crawling multiple pages, crawl relevant and authoritative sources
4291- Prioritize authoritative sources over user-generated content when appropriate
4292- For controversial topics, crawl sources representing different perspectives if possible
4293- Verify information across multiple sources when possible
4294- Consider the recency of information, especially for time-sensitive topics
4295</crawling_best_practices>
4296
4297<error_handling>
4298- If a search returns poor or no results:
4299    1. Analyze the query and results. Could the query be improved (more specific, different keywords)?
4300    2. Consider trying alternative categories or query terms.
4301    3. If the search was language-specific and failed (especially for technical, scientific, or non-regional topics), try rewriting the query or searching again using English.
4302    4. If needed, explain the issue to the user and suggest alternative search terms or strategies.
4303- If a crawl fails (error, timeout, blocked) or returns an empty body, a verification/challenge page, or mostly obfuscated JavaScript, the page needs a real browser — do NOT keep retrying with different queries or sources. When the agent-browser skill is available, activate it and re-fetch the page with it. Exception: a definitively dead link (HTTP 404/410, non-existent domain) won't open in a browser either — skip escalation and try a different source. When in doubt, escalate: anti-bot walls often masquerade as timeouts or generic errors. Only when no browser path exists, explain the issue to the user and suggest alternatives (e.g., trying a different source from search results).
4304- For ambiguous queries, ask for clarification or suggest interpretations/alternative search terms before conducting extensive searches.
4305- If information seems outdated, note this to the user and suggest searching for more recent sources or specifying a time range.
4306</error_handling>
4307
4308Current date: ${e}
4309`})),PJ,FJ=e((()=>{PJ={crawlMultiPages:`crawlMultiPages`,crawlSinglePage:`crawlSinglePage`,search:`search`}})),IJ,LJ,RJ=e((()=>{IJ=t(i()),NJ(),FJ(),LJ={api:[{description:`a search service with automatic engine selection. Useful for when you need to answer questions about current events. Input should be a search query. Output is a JSON array of the query results`,name:PJ.search,parameters:{properties:{query:{description:`The search query`,type:`string`},searchCategories:{description:`The search categories you can set:`,items:{enum:[`general`,`images`,`news`,`science`,`videos`],type:`string`},type:`array`},searchTimeRange:{description:`The time range you can set:`,enum:[`anytime`,`day`,`week`,`month`,`year`],type:`string`}},required:[`query`],type:`object`}},{description:`A crawler can visit page content. Output is a JSON object of title, content, url and website`,name:PJ.crawlSinglePage,parameters:{properties:{url:{description:`The url need to be crawled`,type:`string`}},required:[`url`],type:`object`}},{description:`A crawler can visit multi pages. If need to visit multi website, use this one. Output is an array of JSON object of title, content, url and website`,name:PJ.crawlMultiPages,parameters:{properties:{urls:{items:{description:`The urls need to be crawled`,type:`string`},type:`array`}},required:[`urls`],type:`object`}}],identifier:`lobe-web-browsing`,meta:{avatar:`🌐`,description:`Search the web for current information and crawl web pages to extract content. Supports automatic engine selection, categories, and time ranges.`,readme:`Search the web for current information and crawl web pages to extract content. Supports automatic engine selection, categories, and time ranges for comprehensive research.`,title:`Web Browsing`},systemRole:MJ((0,IJ.default)(new Date).format(`YYYY-MM-DD`)),type:`builtin`}})),zJ=e((()=>{RJ(),NJ(),FJ()})),BJ,Zwe=e((()=>{BJ=`## Tool Usage
4310
4311### Turn Output Order (CRITICAL)
4312
4313When a turn includes both persistence tools and a user-facing message, emit tool calls FIRST with no leading text, then let the post-tool message be your single visible reply. Never put visible text both before and after tool calls — the pre-tool text forces a confused filler ("waiting for your reply…") after tool results return. Pure tool-only turns are fine.
4314
4315Turn protocol:
43161. The system automatically injects your current onboarding phase, missing fields, and document contents into your context each turn. Trust the injected context — it is the authoritative source of state.
43172. Follow the phase indicated in the injected context. Do not advance the flow out of order. Exception: if the user clearly signals they want to leave (busy, disengaging, says goodbye) — in any phase including Summary, as long as the marketplace picker has not yet been opened — skip directly to the early-exit flow: persist any unsaved fields (best-effort; do not retry on failure), send a brief farewell, then call \`finishOnboarding\`. Do NOT call \`showAgentMarketplace\` on early exit; the marketplace handoff is for normal completion only.
43183. **Each turn, the system appends a \`<next_actions>\` directive after the user's message. You MUST follow the tool call instructions in \`<next_actions>\` — they tell you exactly which persistence tools to call based on the current phase and missing data. Treat \`<next_actions>\` as mandatory operational instructions, not suggestions.**
43194. Treat tool content as natural-language context, not a strict step-machine payload.
43205. Prefer the \`lobe-user-interaction____askUserQuestion\` tool call for structured collection, explicit choices, or UI-mediated input. For natural exploratory conversation, direct plain-text questions are allowed and often preferable.
43216. Never claim something was saved, updated, created, or completed unless the corresponding tool call succeeded. If a tool call fails, recover from that result only.
43227. Never finish onboarding before the summary is shown and lightly confirmed, unless the user clearly signals they want to leave.
43238. **CRITICAL: You MUST call persistence tools (saveUserQuestion, writeDocument, updateDocument) throughout the entire conversation, not just at the beginning. Every time you learn new information about the user, persist it promptly. On a normal completion, the wrap-up sequence is: persist any unsaved fields → call \`showAgentMarketplace\` exactly once for the assistant handoff (skip only if the user explicitly refuses recommendations) → on the NEXT turn, send a brief warm closing and call \`finishOnboarding\`. The user's text reply on that next turn is the resolution signal even if the picker is still pending — do not stall.**
4324
4325Persistence rules:
43261. Use saveUserQuestion only for these structured onboarding fields: agentName, agentEmoji, and fullName. Use it only when that information emerges naturally in conversation. The user's preferred reply language is configured before onboarding starts and is injected into your system role automatically — do not ask about it or save it via saveUserQuestion.
43272. saveUserQuestion updates lightweight onboarding state; it never writes markdown content.
43283. Use writeDocument **only for the very first write** when the document is empty (or for a rare full structural rewrite). For every subsequent edit — even adding a single line — use **updateDocument**. updateDocument is cheaper, safer, and less error-prone than rewriting the full document. The current contents of SOUL.md and User Persona are automatically injected into your context (in <current_soul_document> and <current_user_persona> tags, each line prefixed with its 1-based line number and a \`→\` separator), so you do not need to call readDocument to read them. Use readDocument only if you suspect the injected content may be stale.
43294. updateDocument takes an ordered list of structured hunks. Pick the hunk mode that best fits the edit:
4330   - \`replace\` (default): byte-exact SEARCH → REPLACE. Use for small textual tweaks.
4331   - \`delete\`: byte-exact SEARCH removed. Use to cut a block you can uniquely identify by its text.
4332   - \`deleteLines\`: \`{ mode: "deleteLines", startLine, endLine }\` to remove a line range (inclusive, 1-based, from the injected line numbers).
4333   - \`insertAt\`: \`{ mode: "insertAt", line, content }\` to insert before \`line\`. Use \`line = totalLines + 1\` to append to the end.
4334   - \`replaceLines\`: \`{ mode: "replaceLines", startLine, endLine, content }\` to swap a line range with new content.
4335   Prefer the line-based modes whenever you can read the target lines from the injected document — they are the most robust. Fall back to \`replace\`/\`delete\` for fuzzy textual edits. Content-based hunks run first in order; line-based hunks run afterward (highest line first), so mixing them in one call is safe. On errors (HUNK_NOT_FOUND / HUNK_AMBIGUOUS / LINE_O
4335UT_OF_RANGE / INVALID_LINE_RANGE / LINE_OVERLAP), re-check the injected document and retry with corrected hunks.
43365. Document tools are the only markdown persistence path.
43376. Keep a working copy of each document in memory (seeded from the injected content), and merge new information into that copy before each writeDocument or updateDocument call.
43387. SOUL.md (type: "soul") is for agent identity only: name, creature or nature, vibe, emoji, and the base template structure.
43398. User Persona (type: "persona") is for user identity, role, work style, current context, interests, pain points, communication comfort level, and preferred input style.
43409. Do not put user information into SOUL.md. Do not put agent identity into the persona document.
434110. Document tools (readDocument, writeDocument, updateDocument) must ONLY be used for SOUL.md and User Persona documents. Never use them to create arbitrary content such as guides, tutorials, checklists, or reference materials. Present such content directly in your reply text instead.
4342
4343Workspace setup rules:
43441. Do not create or modify workspace agents or agent groups unless the user explicitly asks for that setup.
43452. Ask for missing requirements before making material changes.
43463. For a new group, create the group first, then refine the group prompt or settings, then create or adjust member agents.
43474. Name assistants by task, not by abstract capability.
4348
4349Agent Marketplace handoff (showAgentMarketplace, submitAgentPick):
4350
4351<primary_usage>
4352Regular usage of showAgentMarketplace:
43531. Call showAgentMarketplace with:
4354   - requestId: a unique id for this pick request.
4355   - categoryHints: 1–3 MarketplaceCategory slugs that match what you believe the user needs, chosen from the fixed list below. These hints move the matching tabs to the front of the picker; the user can still browse the rest.
4356   - prompt: a short, natural sentence telling the user why you are showing the marketplace (e.g. "I think these would help with your writing work — take a look").
4357   - description (optional): an extra line of context.
43582. The picker is user-driven. Do NOT pre-select or claim to have created any agents. Wait for the user to pick.
43593. Keep at most one unresolved pick request at a time.
4360</primary_usage>
4361
4362<fixed_category_slugs>
4363content-creation, engineering, design-creative, learning-research, business-strategy,
4364marketing, product-management, sales-customer, operations, people-hr,
4365finance-legal, creator-economy, personal-life
4366</fixed_category_slugs>
4367
4368<framework_lifecycle>
4369Framework-managed lifecycle:
43701. showAgentMarketplace opens the picker in the UI.
43712. submitAgentPick records the user's selection and is handled by the client after the user submits. Do not call it proactively.
4372</framework_lifecycle>
4373
4374<boundaries>
4375- Do NOT attempt to create, update, delete, or duplicate agents yourself. That capability has been removed on purpose — the Marketplace picker is the ONLY way to add agents in this flow.
4376- Always pick categoryHints strictly from the fixed slug list. Do not invent new slugs.
4377- After the user submits, acknowledge what they picked by title in your next reply; do not claim you installed anything.
4378</boundaries>`})),VJ,HJ,UJ=e((()=>{VJ=`lobe-web-onboarding`,HJ={finishOnboarding:`finishOnboarding`,readDocument:`readDocument`,saveUserQuestion:`saveUserQuestion`,showAgentMarketplace:`showAgentMarketplace`,submitAgentPick:`submitAgentPick`,updateDocument:`updateDocument`,writeDocument:`writeDocument`}})),WJ,GJ,KJ=e((()=>
4378{Wt(),Ire(),Zwe(),UJ(),WJ=[{match:{agentName:{pattern:`\\S`,type:`regex`}},policy:`always`},{match:{agentEmoji:{pattern:`\\S`,type:`regex`}},policy:`always`},{policy:`never`}],GJ={api:[{description:`Persist structured onboarding fields. agentName and agentEmoji (updates inbox agent title/avatar) require user confirmation; interests/customInterests saves run without confirmation.`,humanIntervention:WJ,name:HJ.saveUserQuestion,parameters:{additionalProperties:!1,properties:{agentEmoji:{description:`Emoji avatar for the agent (updates inbox agent avatar).`,type:`string`},agentName:{description:`Name for the agent (updates inbox agent title).`,type:`string`},fullName:{type:`string`},customInterests:{description:`Specific freeform user interests that do not fit the predefined interest keys.`,items:{type:`string`},type:`array`},interests:{description:`Predefined interest keys selected from the supported enum values.`,items:{enum:[...Tt],type:`string`},type:`array`}},type:`object`}},{description:`Finish onboarding once the summary is confirmed and the user is ready to proceed.`,name:HJ.finishOnboarding,parameters:{properties:{},type:`object`}},{description:`Read a document by type. Note: document contents are automatically injected into your system context (in <current_soul_document> and <current_user_persona> tags), so this tool is only needed as a fallback. Use "soul" for SOUL.md or "persona" for the user persona document.`,name:HJ.readDocument,parameters:{properties:{type:{description:`Document type to read.`,enum:[`soul`,`persona`],type:`string`}},required:[`type`],type:`object`}},{description:`Write a document with full content, replacing anything that existed. Use "soul" for SOUL.md (agent identity + base template only, no user info), or "persona" for user persona (user identity, work style, context, pain points only, no agent info). Use writeDocument only for the very first write when the document is empty, or when the entire structure must change. For every subsequent edit, call updateDocument instead — it is cheaper and safer.`,name:HJ.writeDocument,parameters:{properties:{content:{description:`The full document content in markdown format.`,type:`string`},type:{description:`Document type to write.`,enum:[`soul`,`persona`],type:`string`}},required:[`type`,`content`],type:`object`}},{description:"Update an existing document by applying structured hunks **in a single call**. Preferred over writeDocument for every incremental edit — cheaper, safer, less error-prone.\n\n**BATCH RULE (mandatory):** put EVERY change you want to make this turn into the `hunks` array of ONE call. Do NOT call updateDocument multiple times in a row for the same document — sequential calls waste a full LLM round-trip each and are forbidden. If you have 4 things to record, send 1 call with 4 hunks, not 4 calls with 1 hunk.\n\nEach hunk picks ONE mode:\n- `replace` (default): byte-exact SEARCH → REPLACE. For small textual tweaks.\n- `delete`: remove the byte-exact SEARCH region.\n- `deleteLines`: drop lines [startLine, endLine] (1-based, inclusive). Use the line numbers shown in <current_*_document>.\n- `insertAt`: insert `content` before `line`. Use `line = totalLines + 1` to append to the end;
4378 `line = 1` to prepend.\n- `replaceLines`: replace lines [startLine, endLine] with `content`.\nLine-based hunks REQUIRE the line numbers from the injected <current_soul_document> / <current_user_persona> view. On failure (HUNK_NOT_FOUND / HUNK_AMBIGUOUS / LINE_OUT_OF_RANGE / LINE_OVERLAP), re-check the injected document and retry with corrected hunks; do NOT fall back to writeDocument unless most of the document must change.",name:HJ.updateDocument,parameters:{properties:{hunks:{description:`Ordered list of hunks — pack ALL changes for this turn into this single array. Content-based hunks (replace/delete) run first in order; line-based hunks (deleteLines/insertAt/replaceLines) run afterward, highest line first. Calling updateDocument again in the next turn for changes you could have included here is forbidden.`,items:{oneOf:[{additionalProperties:!1,properties:{mode:{const:`replace`,type:`string`},replace:{description:`Replacement text; may be empty to delete the matched region.`,type:`string`},replaceAll:{description:`Replace every occurrence of search. Defaults to false.`,type:`boolean`},search:{description:`Byte-exact substring to locate in the current document.`,type:`string`}},required:[`search`,`replace`],type:`object`},{additionalProperties:!1,properties:{mode:{const:`delete`,type:`string`},replaceAll:{type:`boolean`},search:{description:`Byte-exact substring to remove.`,type:`string`}},required:[`mode`,`search`],type:`object`},{additionalProperties:!1,properties:{endLine:{description:`Inclusive 1-based end line.`,type:`integer`},mode:{const:`deleteLines`,type:`string`},startLine:{description:`Inclusive 1-based start line.`,type:`integer`}},required:[`mode`,`startLine`,`endLine`],type:`object`},{additionalProperties:!1,properties:{content:{description:`Text to insert; may span multiple lines (use \\n).`,type:`string`},line:{description:"1-based line to insert before. Use `totalLines + 1` to append to the end.",type:`integer`},mode:{const:`insertAt`,type:`string`}},required:[`mode`,`line`,`content`],type:`object`},{additionalProperties:!1,properties:{content:{description:`Replacement text; may be empty to delete the range.`,type:`string`},endLine:{type:`integer`},mode:{const:`replaceLines`,type:`string`},startLine:{type:`integer`}},required:[`mode`,`startLine`,`endLine`,`content`],type:`object`}]},minItems:1,type:`array`},type:{description:`Document type to patch.`,enum:[`soul`,`persona`],type:`string`}},required:[`type`,`hunks`],type:`object`}},{description:`Open an Agent Marketplace picker card in the UI, prioritizing tabs by the provided category hints. Returns the request in pending state.`,humanIntervention:`always`,name:HJ.showAgentMarketplace,parameters:{properties:{categoryHints:{description:`One or more fixed MarketplaceCategory slugs used to move matching picker tabs to the front.`,items:{enum:[...Lre],type:`string`},minItems:1,type:`array`},description:{description:`Optional secondary line shown below the prompt.`,type:`string`},prompt:{description:`Short, natural sentence shown to the user explaining what the marketplace is for.`,type:`string`},requestId:{description:`Unique identifier for this pick request.`,type:`string`}},required:[`categoryHints`,`prompt`,`requestId`],type:`object`},renderDisplayControl:`collapsed`},{description:`Record the user's template selection for a pending pick request. Normally client-handled after the user submits in the UI.`,name:HJ.submitAgentPick,parameters:{properties:{requestId:{description:`The pick request ID to submit.`,type:`string`},selectedTemplateIds:{description:`Template IDs the user selected from the marketplace.`,items:{type:`string`},minItems:1,type:`array`}},required:[`requestId`,`selectedTemplateIds`],type:`object`}}],identifier:VJ,meta:{avatar:`🧭`,description:`Drive the web onboarding flow with a controlled agent runtime`,title:`Web Onboarding`},systemRole:BJ,type:`builtin`}})),qJ=e((()=>{KJ(),UJ()})),JJ,YJ,XJ,ZJ,QJ,$J,eY,tY,nY,rY,iY=e((()=>{mi(),ei(),dr(),ic(),mse(),bse(),al(),uG(),NG(),XG(),Kr(),Yee(),iK(),UK(),ZK(),ni(),sq(),Uwe(),Tq(),Wwe(),Gq(),Jwe(),aJ(),TJ(),ti(),jJ(),Bee(),vte(),zJ(),qJ(),Wt(),JJ=[hi.identifier,_J.identifier,rJ.identifier,LJ.identifier,nK.identifier,aq.identifier,Mr.identifier,il.identifier,jG.identifier,kJ.identifier,Tr.identifier,fr.identifier,yK.identifier],YJ=[yK.identifier,hi.identifier,_J.identifier,rJ.identifier],XJ=[hi.identifier],ZJ=[hi.identifier,rJ.identifier],QJ=[nK.identifier,aq.identifier,LJ.identifier],Sr.identifier,$J=[il.identifier,jG.identifier,nK.identifier,Mr.identifier,aq.identifier,Mq.identifier,yK.identifier,LJ.identifier],eY=[{discoverable:!1,hidden:!0,identifier:Gee.identifier,manifest:Gee,type:`builtin`},{discoverable:!1,hidden:!0,identifier:hi.identifier,manifest:hi,type:`builtin`},{discoverable:!1,hidden:!0,identifier:_J.identifier,manifest:_J,resolveManifest:wJ,type:`builtin`},{hidden:!0,identifier:rJ.identifier,manifest:rJ,type:`builtin`},{discoverable:!1,hidden:!0,identifier:Zq.identifier,manifest:Zq,type:`builtin`},{discoverable:!1,hidden:!0,identifier:Uq.identifier,manifest:Uq,type:`builtin`},{discoverable:!1,hidden:!0,identifier:Xc.identifier,manifest:Xc,type:`builtin`},{discoverable:!1,hidden:!0,identifier:Yc.identifier,manifest:Yc,type:`builtin`},{discoverable:!1,hidden:!0,identifier:Jc.identifier,manifest:Jc,type:`builtin`},{discoverable:!1,hidden:!0,identifier:Qc.identifier,manifest:Qc,type:`builtin`},{discoverable:!1,hidden:!0,identifier:il.identifier,manifest:il,type:`builtin`},{discoverable:!1,hidden:!0,identifier:Mr.identifier,manifest:Mr,type:`builtin`},{hidden:!0,identifier:aq.identifier,manifest:aq,type:`builtin`},{hidden:!0,identifier:LJ.identifier,manifest:LJ,type:`builtin`},{hidden:!0,identifier:jG.identifier,manifest:jG,type:`builtin`},{identifier:Tr.identifier,manifest:Tr,type:`builtin`},{identifier:JG.identifier,manifest:JG,type:`builtin`},{hidden:!0,identifier:nK.identifier,manifest:nK,type:`builtin`},{discoverable:!1,hidden:!0,identifier:Cq.identifier,manifest:Cq,type:`builtin`}
4378,{discoverable:!1,hidden:!0,identifier:Fr.identifier,manifest:Fr,type:`builtin`},{discoverable:!1,hidden:!0,identifier:Zr.identifier,manifest:Zr,type:`builtin`},{discoverable:!1,hidden:!0,identifier:Sr.identifier,manifest:Sr,type:`builtin`},{hidden:!0,identifier:ec.identifier,manifest:ec,type:`builtin`},{identifier:cG.identifier,manifest:cG,type:`builtin`},{identifier:gq.identifier,manifest:gq,type:`builtin`},{hidden:!0,identifier:Mq.identifier,manifest:Mq,type:`builtin`},{discoverable:!1,hidden:!0,identifier:kJ.identifier,manifest:kJ,type:`builtin`},{discoverable:!1,hidden:!0,identifier:GJ.identifier,manifest:GJ,type:`builtin`},{discoverable:!1,hidden:!0,identifier:Hee.identifier,manifest:Hee,type:`builtin`},{identifier:fr.identifier,manifest:fr,type:`builtin`},{discoverable:!1,hidden:!0,identifier:el.identifier,manifest:el,type:`builtin`},{hidden:!0,identifier:yK.identifier,manifest:yK,resolveManifest:xK,type:`builtin`},{identifier:YK.identifier,manifest:YK,type:`builtin`}],tY=eY.map(e=>({...e,avatar:e.manifest?.meta?.avatar,description:e.manifest?.meta?.description,tags:e.manifest?.meta?.tags,title:e.manifest?.meta?.title})),nY=new Set(Nt.filter(e=>e.type===cn.Builtin).map(e=>e.id)),rY=tY.filter(e=>!e.hidden&&!nY.has(e.identifier)).map(e=>e.identifier)})),aY,oY,sY,cY,lY,uY,dY=e((()=>{Fc(),Wt(),aY=new Set([Ac]),oY=new Set([`task`]),sY={canExecuteOnDevice:!1},cY=(e=sY)=>({canExecuteOnDevice:e.canExecuteOnDevice??sY.canExecuteOnDevice}),lY=(e,t=sY)=>{let n=cY(t);return oY.has(e)?!1:aY.has(e)?n.canExecuteOnDevice:!0},uY=(e,t=sY)=>e.filter(e=>lY(e.identifier,t))})),fY,pY=e((()=>{Fc(),iY(),dY(),fY={builtinSkills:uY(Pc),builtinToolLoading:{},builtinTools:tY,uninstalledBuiltinTools:rY,uninstalledBuiltinToolsLoading:!0}})),mY,hY=e((()=>{mY={composioExecutingToolIds:new Set,composioServers:[],isComposioServersInit:!1,loadingComposioServerIds:new Set}})),gY,_Y,vY=e((()=>{gY={customParams:{apiMode:`simple`,enableSettings:!1,manifestMode:`url`},type:`customPlugin`},_Y={customPluginSearchKeywords:``,newCustomPlugin:gY}})),yY,bY=e((()=>{yY={lobehubSkillExecutingToolIds:new Set,lobehubSkillLoadingIds:new Set,lobehubSkillServers:[]}})),xY,SY=e((()=>{xY={categories:[],currentPage:1,listType:`mcp`,mcpInstallAbortControllers:{},mcpInstallProgress:{},mcpPluginItems:[],mcpTestAbortControllers:{},mcpTestErrors:{},mcpTestLoading:{}}})),CY,wY=e((()=>{CY={installedPlugins:[],loadingInstallPlugins:!0,pluginInstallLoading:{},pluginsSettings:{}}})),TY,Qwe=e((()=>{Uie(),Gie(),pY(),hY(),Bre(),vY(),bY(),SY(),wY(),TY={...zre,...CY,..._Y,...fY,...xY,...mY,...yY,...Wie,...Hie}})),EY,DY,OY,kY,$we=e((()=>{Wt(),s(),Ii(),Dr(),EY=kr(`agentDocumentSkills`),DY=e=>e.filter(e=>e.isSkillBundle).map(e=>({description:e.description??void 0,documentId:e.documentId,identifier:Dt(e.filename),name:e.filename,title:e.title||void 0})),OY=(e,t,n)=>new kY(e,t,n),kY=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}refreshAgentDocumentSkills=async e=>{let t=this.#e().agentDocumentSkillsAgentId;t&&t!==e?this.#t({agentDocumentSkills:[],agentDocumentSkillsAgentId:e},!1,EY(`switchAgent`)):t||this.#t({agentDocumentSkillsAgentId:e},!1,EY(`initAgent`));try{let t=DY(await zi.listDocuments({agentId:e,excludeWeb:!0}));this.#t({agentDocumentSkills:t,agentDocumentSkillsAgentId:e},!1,EY(`refreshAgentDocumentSkills`))}catch(e){console.warn(`[agentDocumentSkills] failed to refresh:`,e),this.#t({agentDocumentSkills:[]},!1,EY(`refreshAgentDocumentSkillsError`))}};clearAgentDocumentSkills=()=>{this.#t({agentDocumentSkills:[],agentDocumentSkillsAgentId:void 0},!1,EY(`clearAgentDocumentSkills`))};useFetchAgentDocumentSkills=e=>m(e?ire.documentsNonWebList(e):null,async()=>zi.listDocuments({agentId:e,excludeWeb:!0}),{onSuccess:t=>{e&&this.#t({agentDocumentSkills:DY(t),agentDocumentSkillsAgentId:e},!1,EY(`useFetchAgentDocumentSkills`))},revalidateOnFocus:!1})}})),AY,jY,MY,NY=e((()=>{AY=e=>e.agentDocumentSkills||[],jY=e=>t=>(t.agentDocumentSkills||[]).find(t=>t.identifier===e),MY={getAgentDocumentSkillByIdentifier:jY,getAgentDocumentSkills:AY}})),eTe=e((()=>{$we(),Uie(),NY()})),PY,FY,IY=e((()=>{pa(),PY=class{async createSkill(e){return q.agentSkills.create.mutate(e)}async importFromGitHub(e){return q.agentSkills.importFromGitHub.mutate(e)}async importFromUrl(e){return q.agentSkills.importFromUrl.mutate(e)}async importFromZip(e){return q.agentSkills.importFromZip.mutate(e)}async importFromMarket(e){return q.agentSkills.importFromMarket.mutate({identifier:e})}async getById(e){return q.agentSkills.getById.query({id:e})}async getZipUrl(e){return q.agentSkills.getByIdWithZipUrl.query({id:e})}async getByIdentifier(e){return q.agentSkills.getByIdentifier.query({identifier:e})}async getByName(e){return q.agentSkills.getByName.query({name:e})}async list(e){return q.agentSkills.list.query(e?{source:e}:void 0)}async search(e){return q.agentSkills.search.query({query:e})}async listResources(e,t){return q.agentSkills.listResources.query({id:e,includeContent:t})}async readResource(e,t){return q.agentSkills.readResource.query({id:e,path:t})}async updateSkill(e){return q.agentSkills.update.mutate({content:e.content,id:e.id,manifest:e.manifest})}async deleteSkill(e){return q.agentSkills.delete.mutate({id:e})}},FY=new PY})),LY,RY,zY,tTe=e((()=>{it(),s(),Qi(),oa(),IY(),Dr(),LY=kr(`agentSkills`),RY=(e,t,n)=>new zY(e,t,n),zY=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}createAgentSkill=async e=>{let t=await FY.createSkill(e);return await this.#e().refreshAgentSkills(),t};deleteAgentSkill=async e=>{await FY.deleteSkill(e),this.#t(tt(t=>{delete t.agentSkillDetailMap[e]}),!1,LY(`deleteAgentSkill`)),await _(aa.agentSkillDetail(e),void 0,{revalidate:!1}),await this.#e().refreshAgentSkills()};fetchAgentSkillDetail=async e=>{let t=this.#e().agentSkillDetailMap[e];if(t)return t;let n=await FY.getById(e);return n&&this.#t(tt(t=>{t.agentSkillDetailMap[e]=n}),!1,LY(`fetchAgentSkillDetail`)),n};importAgentSkillFromGitHub=async e=>{let t=await FY.importFromGitHub(e);return await this.#e().refreshAgentSkills(),t};importAgentSkillFromUrl=async e=>{let t=await FY.importFromUrl(e);return await this.#e().refreshAgentSkills(),t};importAgentSkillFromZip=async e=>{let t=await FY.importFromZip(e);return await this.#e().refreshAgentSkills(),t};refreshAgentSkills=async()=>{let{data:e}=await FY.list();this.#t({agentSkills:e},!1,LY(`refreshAgentSkills`))};updateAgentSkill=async e=>{let t=await FY.updateSkill(e);return t&&this.#t(tt(n=>{n.agentSkillDetailMap[e.id]=t}),!1,LY(`updateAgentSkill`)),await _(aa.agentSkillDetail(e.id),void 0,{revalidate:!1}),await this.#e().refreshAgentSkills(),t};useFetchAgentSkillDetail=e=>Xi(e?aa.agentSkillDetail(e):null,async()=>{let[t,n]=await Promise.all([FY.getById(e),FY.listResources(e,!0)]);return t&&this.#t(tt(n=>{n.agentSkillDetailMap[e]=t}),!1,LY(`useFetchAgentSkillDetail`)),{resourceTree:n,skillDetail:t}},{revalidateOnFocus:!1});useFetchAgentSkills=e=>m(e?aa.agentSkills():null,async()=>{let{data:e}=await FY.list();return e},{onSuccess:e=>{this.#t({agentSkills:e},!1,LY(`useFetchAgentSkills`))},revalidateOnFocus:!1})}})),BY,VY,HY,UY,WY,GY,KY,qY,JY=e((()=>{BY=e=>e.agentSkills||[],VY=e=>(e.agentSkills||[]).filter(e=>e.source===`market`),HY=e=>(e.agentSkills||[]).filter(e=>e.source===`user`),UY=e=>t=>(t.agentSkills||[]).find(t=>
4378t.identifier===e),WY=e=>t=>t.agentSkillDetailMap?.[e],GY=e=>t=>(t.agentSkills||[]).some(t=>t.identifier===e),KY=e=>(e.agentSkills||[]).map(e=>{let t=e.manifest?.author;return{author:typeof t==`string`?t:t?.name||`User`,identifier:e.identifier,meta:{avatar:`🧩`,description:e.description??e.manifest?.description??``,title:e.name},type:`builtin`}}),qY={agentSkillMetaList:KY,getAgentSkillByIdentifier:UY,getAgentSkillDetail:WY,getAgentSkills:BY,getMarketAgentSkills:VY,getUserAgentSkills:HY,isAgentSkill:GY}})),nTe=e((()=>{tTe(),Gie(),JY()})),YY,XY,ZY,QY,$Y,eX=e((()=>{Wt(),dY(),$ee(),YY=e=>gte(e),XY=(e,t={})=>t.isDesktop===void 0?lY(e):lY(e,{canExecuteOnDevice:t.isDesktop??!1}),ZY=(e,t={})=>(t.isDesktop??!1)||e.customParams?.mcp?.type!==`stdio`,QY=(e,t={})=>{if(!YY(e)||!XY(e,t))return!1;let n=t.installedPlugins?.find(t=>t.identifier===e);return n?ZY(n,t):!0},$Y=(e,t={})=>e.filter(e=>QY(e,t))})),tX,nX=e((()=>{tX=function(e){return e.ACTIVE=`active`,e.ERROR=`error`,e.PENDING_AUTH=`pending_auth`,e}({})})),rX,iX,aX,oX,rTe=e((()=>{Wt(),it(),s(),oa(),pa(),Dr(),nX(),rX=kr(`composioStore`),iX=new Set(Vt.map(e=>e.identifier)),aX=(e,t,n)=>new oX(e,t,n),oX=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}callComposioTool=async e=>{let{identifier:t,toolSlug:n,toolArgs:r}=e,i=`${t}:${n}`;this.#t(tt(e=>{e.composioExecutingToolIds.add(i)}),!1,rX(`callComposioTool/start`));try{let e=await fa.composio.executeAction.mutate({identifier:t,toolArgs:r,toolSlug:n});return this.#t(tt(e=>{e.composioExecutingToolIds.delete(i)}),!1,rX(`callComposioTool/success`)),{data:e,success:!0}}catch(e){return console.error(`[Composio] Failed to call tool:`,e),this.#t(tt(e=>{e.composioExecutingToolIds.delete(i)}),!1,rX(`callComposioTool/error`)),{error:e instanceof Error?e.message:String(e),success:!1}}};completeComposioServerAuth=async e=>{await this.#e().refreshComposioConnectionStatus(e)};createComposioConnection=async e=>{let{appSlug:t,identifier:n,label:r,agentId:i}=e;this.#t(tt(e=>{e.loadingComposioServerIds.add(n)}),!1,rX(`createComposioConnection/start`));try{let e=await q.composio.createConnection.mutate({agentId:i,appSlug:t,identifier:n,label:r}),a={agentId:i,appSlug:t,authConfigId:e.authConfigId,connectedAccountId:e.connectedAccountId,createdAt:0,identifier:e.identifier,label:r,redirectUrl:e.redirectUrl,status:tX.PENDING_AUTH};return this.#t(tt(e=>{let t=e.composioServers.findIndex(e=>e.identifier===n);t>=0?e.composioServers[t]=a:e.composioServers.push(a),e.loadingComposioServerIds.delete(n)}),!1,rX(`createComposioConnection/success`)),a}catch(e){console.error(`[Composio] Failed to create connection:`,e),this.#t(tt(e=>{e.loadingComposioServerIds.delete(n)}),!1,rX(`createComposioConnection/error`));return}};refreshComposioConnectionStatus=async e=>{let{composioServers:t}=this.#e(),n=t.find(t=>t.identifier===e);if(!n){console.error(`[Composio] Server not found:`,e);return}this.#t(tt(t=>{t.loadingComposioServerIds.add(e)}),!1,rX(`refreshComposioConnectionStatus/start`));try{let t=await q.composio.getConnection.query({connectedAccountId:n.connectedAccountId});if(t.error===`AUTH_ERROR`){this.#t(tt(t=>{t.loadingComposioServerIds.delete(e)}),!1,rX(`refreshComposioConnectionStatus/pendingAuth`));return}if(t.status!==`ACTIVE`){this.#t(tt(t=>{t.loadingComposioServerIds.delete(e)}),!1,rX(`refreshComposioConnectionStatus/notActive`));return}let r=(await fa.composio.listActions.query({appSlug:n.appSlug})).tools;this.#t(tt(t=>{let n=t.composioServers.findIndex(t=>t.identifier===e);n>=0&&(t.composioServers[n].tools=r,t.composioServers[n].status=tX.ACTIVE,t.composioServers[n].redirectUrl=void 0,t.composioServers[n].errorMessage=void 0),t.loadingComposioServerIds.delete(e)}),!1,rX(`refreshComposioConnectionStatus/success`)),await q.composio.updateComposioPlugin.mutate({agentId:n.agentId,appSlug:n.appSlug,authConfigId:n.authConfigId,connectedAccountId:n.connectedAccountId,identifier:e,label:n.label,status:`ACTIVE`,tools:r.map(e=>({description:e.description,inputSchema:e.inputSchema,name:e.name}))})}catch(t){console.error(`[Composio] Failed to refresh connection status:`,t),this.#t(tt(n=>{let r=n.composioServers.findIndex(t=>t.identifier===e);r>
4378=0&&(n.composioServers[r].status=tX.ERROR,n.composioServers[r].errorMessage=t instanceof Error?t.message:String(t)),n.loadingComposioServerIds.delete(e)}),!1,rX(`refreshComposioConnectionStatus/error`))}};reauthorizeComposioConnection=async e=>{let{composioServers:t}=this.#e(),n=t.find(t=>t.identifier===e);if(n){try{await q.composio.deleteConnection.mutate({connectedAccountId:n.connectedAccountId,identifier:e})}catch(e){console.error(`[Composio] Failed to clean up stale connection:`,e)}return this.#e().createComposioConnection({appSlug:n.appSlug,identifier:e,label:n.label})}};removeComposioConnection=async e=>{let{composioServers:t}=this.#e(),n=t.find(t=>t.identifier===e);if(this.#t(tt(t=>{t.composioServers=t.composioServers.filter(t=>t.identifier!==e)}),!1,rX(`removeComposioConnection`)),n)try{await q.composio.deleteConnection.mutate({connectedAccountId:n.connectedAccountId,identifier:e})}catch(e){console.error(`[Composio] Failed to delete connection:`,e)}};useFetchAppTools=e=>m(e?aa.composioAppTools(e):null,async()=>(await fa.composio.getActions.query({appSlug:e})).tools||[],{fallbackData:[],revalidateOnFocus:!1});useFetchUserComposioConnections=e=>m(e?aa.composioConnections():null,async()=>{let e=await q.composio.getComposioPlugins.query();return e.length===0?[]:e.filter(e=>e.customParams?.composio).filter(e=>iX.has(e.identifier)).map(e=>{let t=e.customParams.composio,n=Vt.find(t=>t.identifier===e.identifier),r=(e.manifest?.api||[]).map(e=>({description:e.description,inputSchema:e.parameters,name:e.name})),i={ACTIVE:tX.ACTIVE,FAILED:tX.ERROR,PENDING:tX.PENDING_AUTH};return{appSlug:t.appSlug||``,authConfigId:t.authConfigId||``,connectedAccountId:t.connectedAccountId,createdAt:0,identifier:e.identifier,label:n?.label||e.identifier,redirectUrl:t.redirectUrl,status:i[t.status]||tX.PENDING_AUTH,tools:r}})},{onSuccess:e=>{this.#t(tt(t=>{if(e.length>0){let n=new Set(t.composioServers.map(e=>e.identifier)),r=e.filter(e=>!n.has(e.identifier));t.composioServers=[...t.composioServers,...r]}t.isComposioServersInit=!0}),!1,rX(`useFetchUserComposioConnections`))},revalidateOnFocus:!1})}})),sX,cX=e((()=>{nX(),sX={getAllServerIdentifiers:e=>{let t=e.composioServers||[];return new Set(t.map(e=>e.identifier))},getAllTools:e=>sX.getConnectedServers(e).flatMap(e=>(e.tools||[]).map(t=>({...t,appSlug:e.appSlug}))),getConnectedServers:e=>(e.composioServers||[]).filter(e=>e.status===tX.ACTIVE),getPendingAuthServers:e=>(e.composioServers||[]).filter(e=>e.status===tX.PENDING_AUTH),getServerByIdentifier:e=>t=>t.composioServers?.find(t=>t.identifier===e),getServers:e=>e.composioServers||[],isComposioServer:e=>t=>(t.composioServers||[]).some(t=>t.identifier===e),isServerLoading:e=>t=>t.loadingComposioServerIds?.has(e)||!1,isToolExecuting:(e,t)=>n=>{let r=`${e}:${t}`;return n.composioExecutingToolIds?.has(r)||!1},composioAsLobeTools:e=>{let t=e.composioServers||[],n=[];return t.forEach(e=>{if(!e.tools||e.status!==tX.ACTIVE)return;let t=e.tools.map(e=>({description:e.description||``,name:e.name,parameters:e.inputSchema||{}}));t.length>0&&n.push({identifier:e.identifier,manifest:{api:t,author:`Composio`,homepage:`https://composio.dev`,identifier:e.identifier,meta:{avatar:`☁️`,description:`Composio: ${e.label}`,tags:[`composio`,`mcp`],title:e.label},type:`builtin`,version:`1.0.0`},type:`plugin`})}),n}}})),lX=e((()=>{rTe(),hY(),cX(),nX()})),uX,dX,fX,pX,mX,hX,gX,_X,vX,yX,bX,xX,SX,CX,wX,TX,EX,DX,OX,kX,AX,jX,MX,NX,PX,FX=e((()=>{iY(),eX(),JY(),lX(),uX=e=>({author:`LobeHub`,identifier:e.identifier,meta:e.manifest.meta,type:`builtin`}),dX=e=>({...uX(e),availableInWeb:YY(e.identifier)}),fX=e=>({author:`LobeHub`,identifier:e.identifier,meta:{avatar:e.avatar,description:e.description,title:e.name},type:`builtin`}),pX=e=>({...fX(e),availableInWeb:XY(e.identifier)}),mX=e=>(e.composioServers||[]).filter(e=>e.status===tX.ACTIVE&&e.tools?.length).map(e=>({author:`Composio`,identifier:e.identifier,meta:{avatar:`☁️`,description:`LobeHub Mcp Server: ${e.label}`,tags:[`composio`,`mcp`],title:e.label},type:`builtin`})),hX=e=>mX(e).map(e=>({...e,availableInWeb:!0})),gX=new Set($J),_X=new Set(YJ),vX=new Set(ZJ),yX=(e,{isManualMode:t})=>e.discoverable===!1||gX.has(e.identifier)?!1:!_X.has(e.identifier)||t&&vX.has(e.identifier),bX=(e,{includeHidden:t})=>{let{uninstalledBuiltinTools:n}=e,r=e.builtinTools.filter(e=>!(e.hidden&&!t||t&&e.discoverable===!1||t&&gX.has(e.identifier)||!YY(e.identifier)||n.includes(e.identifier))).map(uX),i=(e.builtinSkills||[]).filter(e=>!(!XY(e.identifier)||n.includes(e.identifier))).map(fX),a=qY.agentSkillMetaList(e);return[...i,...a,...r,...mX(e)]},xX=e=>bX(e,{includeHidden:!1}),SX=e=>bX(e,{includeHidden:!0}),CX=new Set([`lobe-agent-builder`,`lobe-group-agent-builder`,`lobe-group-management`,`lobe-skills`]),wX=e=>{let t=e.builtinTools.filter(e=>!CX.has(e.identifier)).map(dX),n=(e.builtinSkills||[]).map(pX),r=qY.agentSkillMetaList(e).map(e=>({...e,availableInWeb:!0}));return[...n,...r,...t,...hX(e)]},TX=e=>{let{uninstalledBuiltinTools:t}=e,n=(e.builtinSkills||[]).filter(e=>!(!XY(e.identifier)||t.includes(e.identifier))).map(fX),r=qY.agentSkillMetaList(e),i=e.builtinTools.filter(e=>!(e.discoverable===!1||t.includes(e.identifier))).map(uX);return[...n,...r,...i,...mX(e)]},EX=e=>{let{uninstalledBuiltinTools:t}=e;return[...e.builtinTools.filter(e=>!(CX.has(e.identifier)||t.includes(e.identifier))).map(dX),...hX(e)]},DX=e=>t=>{let{uninstalledBuiltinTools:n}=t;return[...t.builtinTools.filter(t=>yX(t,e)).filter(e=>!n.includes(e.identifier)).map(dX),...hX(t)]},OX=e=>t=>t.builtinTools.filter(t=>!yX(t,e)).map(e=>e.identifier),kX=new Set(XJ),AX=({isManualMode:e}={isManualMode:!1})=>t=>YJ.filter(e=>!kX.has(e)).filter(t=>!(e&&vX.has(t))).map(e=>t.builtinTools.find(t=>
4378t.identifier===e)).filter(e=>!!e).filter(e=>YY(e.identifier)).map(uX),jX=e=>(e.builtinSkills||[]).filter(t=>!(!XY(t.identifier)||e.uninstalledBuiltinTools.includes(t.identifier))),MX=e=>e.uninstalledBuiltinTools,NX=e=>t=>!t.uninstalledBuiltinTools.includes(e),PX={allMetaList:wX,discoverableMetaList:TX,fixedDisplayMetaList:AX,installedAllMetaList:EX,installedBuiltinSkills:jX,installedProfileConfigurableMetaList:DX,isBuiltinToolInstalled:NX,metaList:xX,metaListIncludingHidden:SX,nonProfileConfigurableBuiltinToolIds:OX,uninstalledBuiltinTools:MX}})),IX,LX,RX=e((()=>{kc(),IX=e=>t=>Oc.isCustomPlugin(e,t.installedPlugins),LX={isCustomPlugin:IX}})),zX,BX=e((()=>{zX=function(e){return e.CONNECTED=`connected`,e.CONNECTING=`connecting`,e.ERROR=`error`,e.NOT_CONNECTED=`not_connected`,e}({})})),VX,HX=e((()=>{At(),Jt(),BX(),VX={getAllServerIdentifiers:e=>{let t=e.lobehubSkillServers||[];return new Set(t.map(e=>e.identifier))},getAllTools:e=>VX.getConnectedServers(e).flatMap(e=>(e.tools||[]).map(t=>({...t,provider:e.identifier}))),getConnectedServers:e=>(e.lobehubSkillServers||[]).filter(e=>e.status===zX.CONNECTED),getServerByIdentifier:e=>t=>t.lobehubSkillServers?.find(t=>t.identifier===e),getServers:e=>e.lobehubSkillServers||[],isLobehubSkillServer:e=>t=>(t.lobehubSkillServers||[]).some(t=>t.identifier===e),isServerLoading:e=>t=>t.lobehubSkillLoadingIds?.has(e)||!1,isToolExecuting:(e,t)=>n=>{let r=`${e}:${t}`;return n.lobehubSkillExecutingToolIds?.has(r)||!1},lobehubSkillAsLobeTools:e=>{let t=e.lobehubSkillServers||[],n=[];for(let e of t){if(!e.tools||e.status!==zX.CONNECTED)continue;let t=e.tools.map(e=>({description:e.description||``,name:e.name,parameters:e.inputSchema||{}}));t.length>0&&n.push({identifier:e.identifier,manifest:{api:t,author:`LobeHub Market`,homepage:Xt(It,`market`),identifier:e.identifier,meta:{avatar:e.icon||`🔗`,description:`LobeHub Skill: ${e.name}`,tags:[`lobehub-skill`,e.identifier],title:e.name},type:`builtin`,version:`1.0.0`},type:`plugin`})}return n},metaList:e=>(e.lobehubSkillServers||[]).filter(e=>e.status===zX.CONNECTED).map(e=>({identifier:e.identifier,meta:{avatar:e.icon||`🔗`,description:`LobeHub Skill: ${e.name}`,title:e.name}}))}})),UX,WX,GX,KX,qX,JX,YX,XX,ZX,QX,$X,eZ,tZ,nZ=e((()=>{UX=e=>{let t=new Set(e.installedPlugins.map(e=>e.identifier));return(e.listType===`mcp`?e.mcpPluginItems:e.mcpPluginItems.filter(e=>t.has(e.identifier))).map(e=>({author:e.author,createdAt:e.createdAt,homepage:e.homepage,identifier:e.identifier,meta:{avatar:e.icon,description:e.description,tags:e.tags,title:e.name},type:`plugin`}))},WX=e=>t=>t.pluginInstallLoading[e],GX=e=>t=>t.mcpInstallProgress[e],KX=e=>t=>!!t.mcpInstallProgress[e],qX=e=>t=>t.mcpPluginItems.find(t=>t.identifier===e),JX=e=>e.activeMCPIdentifier,YX=e=>t=>t.mcpInstallProgress[e]?.configSchema,XX=e=>t=>!!t.mcpInstallProgress[e]?.configSchema,ZX=e=>t=>{let n=t.mcpInstallProgress[e];return!!n&&!n.needsConfig&&n.step!==`Error`},QX=e=>t=>t.mcpTestLoading[e]||!1,$X=e=>t=>t.mcpTestErrors[e],eZ=e=>t=>({error:t.mcpTestErrors[e],loading:t.mcpTestLoading[e]||!1}),tZ={activeMCPPluginIdentifier:JX,getMCPConnectionTestError:$X,getMCPConnectionTestState:eZ,getMCPInstallProgress:GX,getMCPPluginRequiringConfig:YX,getPluginById:qX,isMCPConnectionTesting:QX,isMCPInstallInProgress:ZX,isMCPInstalling:KX,isMCPPluginRequiringConfig:XX,isPluginInstallLoading:WX,mcpPluginList:UX}})),rZ,iZ,aZ,oZ,sZ,cZ,lZ,uZ,dZ,fZ,pZ,mZ,hZ,gZ=e((()=>{eX(),rZ=e=>e.installedPlugins,iZ=e=>t=>rZ(t).some(t=>t.identifier===e),aZ=e=>t=>{if(e)return rZ(t).find(t=>t.identifier===e)},oZ=e=>t=>aZ(e)(t)?.manifest?.meta,sZ=e=>t=>rZ(t).find(t=>t.identifier===e&&t.type===`customPlugin`),cZ=e=>t=>aZ(e)(t)?.manifest,lZ=e=>t=>aZ(e)(t)?.settings||{},uZ=e=>e.installedPlugins.map(e=>e.identifier),dZ=e=>rZ(e).map(e=>e.manifest).filter(e=>!!e),fZ=e=>rZ(e).filter(e=>!e.customParams?.composio).filter(e=>ZY(e)).map(t=>({author:t.manifest?.author,createdAt:t.manifest?.createdAt||t.manifest?.createAt,homepage:t.manifest?.homepage,identifier:t.identifier,meta:oZ(t.identifier)(e),runtimeType:t.runtimeType,type:t.source||t.type,...oZ(t.identifier)(e)})),pZ=e=>fZ(e).filter(e=>
4378e.type===`customPlugin`),mZ=e=>t=>!!cZ(e)(t)?.ui,hZ={getCustomPluginById:sZ,getInstalledPluginById:aZ,getPluginMetaById:oZ,getPluginSettingsById:lZ,getToolManifestById:cZ,installedCustomPluginMetaList:pZ,installedPluginManifestList:dZ,installedPluginMetaList:fZ,installedPlugins:rZ,isPluginHasUI:mZ,isPluginInstalled:iZ,storeAndInstallPluginsIdList:uZ}})),_Z,vZ,yZ=e((()=>{_Z=`claude-code`,vZ=function(e){return e.Agent=`Agent`,e.AskUserQuestion=`askUserQuestion`,e.Bash=`Bash`,e.Edit=`Edit`,e.EnterWorktree=`EnterWorktree`,e.ExitWorktree=`ExitWorktree`,e.Glob=`Glob`,e.Grep=`Grep`,e.Monitor=`Monitor`,e.Read=`Read`,e.ScheduleWakeup=`ScheduleWakeup`,e.SendMessage=`SendMessage`,e.Skill=`Skill`,e.TaskCreate=`TaskCreate`,e.TaskGet=`TaskGet`,e.TaskList=`TaskList`,e.TaskOutput=`TaskOutput`,e.TaskStop=`TaskStop`,e.TaskUpdate=`TaskUpdate`,e.TodoWrite=`TodoWrite`,e.ToolSearch=`ToolSearch`,e.WebFetch=`WebFetch`,e.WebSearch=`WebSearch`,e.Write=`Write`,e}({})})),bZ,xZ,SZ,CZ,wZ=e((()=>{Pn(),hn(),Br(),bZ=t(qt()),xZ=t(xt()),SZ=bn(({css:e})=>({icon:e`
4379    flex-shrink: 0;
4380    margin-inline-end: 4px;
4381  `,text:e`
4382    overflow: hidden;
4383    color: ${U.colorText};
4384    text-overflow: ellipsis;
4385    white-space: nowrap;
4386  `})),CZ=(0,bZ.memo)(({filePath:e,isDirectory:t})=>{let{displayPath:n,name:r}=(0,bZ.useMemo)(()=>{if(!e)return{displayPath:``,name:``};let{base:t,dir:n}=yr.parse(e),r=yr.basename(n);return{displayPath:r?`${r}/${t}`:t,name:t}},[e]);return e?(0,xZ.jsxs)(xZ.Fragment,{children:[r&&(0,xZ.jsx)(Nn,{className:SZ.icon,fallbackUnknownType:!1,filename:r,size:16,type:t?`folder`:`file`,variant:`raw`}),n&&(0,xZ.jsx)(mn,{className:SZ.text,ellipsis:{tooltipWhenOverflow:!0},children:n})]}):null}),CZ.displayName=`FilePathDisplay`})),TZ,EZ,DZ,OZ,kZ=e((()=>{hn(),TZ=bn(({css:e,cssVar:t})=>({root:e`
4387    overflow: hidden;
4388    display: flex;
4389    align-items: center;
4390
4391    min-width: 0;
4392
4393    color: ${t.colorTextSecondary};
4394    text-overflow: ellipsis;
4395    white-space: nowrap;
4396  `})),EZ=bn(({css:e,cssVar:t})=>{let n=n=>e`
4397    overflow: hidden;
4398
4399    min-width: 0;
4400    margin-inline-start: 4px;
4401    padding-block-end: 1px;
4402
4403    color: ${t.colorText};
4404    text-overflow: ellipsis;
4405
4406    background: linear-gradient(to top, ${n} 40%, transparent 40%);
4407  `;return{gold:n(t.gold4),info:n(t.colorInfoBg),primary:n(t.colorPrimaryBgHover),warning:n(t.colorWarningBg)}}),DZ=un`
4408  0% {
4409    background-position: 100%;
4410  }
4411
4412  100% {
4413    background-position: -100%;
4414  }
4415`,OZ=bn(({css:e,cssVar:t})=>({shinyText:e`
4416    color: color-mix(in srgb, ${t.colorText} 45%, transparent);
4417
4418    background: linear-gradient(
4419      120deg,
4420      color-mix(in srgb, ${t.colorTextBase} 0%, transparent) 40%,
4421      ${t.colorTextSecondary} 50%,
4422      color-mix(in srgb, ${t.colorTextBase} 0%, transparent) 60%
4423    );
4424    background-clip: text;
4425    background-size: 200% 100%;
4426
4427    animation: ${DZ} 1.5s linear infinite;
4428  `}))})),AZ,jZ,MZ,NZ,PZ,FZ=e((()=>{Pn(),hn(),Zn(),AZ=t(qt()),a(),wZ(),kZ(),jZ=t(xt()),MZ=bn(({css:e,cssVar:t})=>({separator:e`
4429    margin-inline: 2px;
4430    color: ${t.colorTextQuaternary};
4431  `})),NZ=(0,AZ.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n,pluginState:r,isLoading:i,translationKey:a})=>{let{t:o}=c(`plugin`),s=e?.file_path||e?.path||t?.file_path||t?.path||``;if(n)return s?(0,jZ.jsxs)(`div`,{className:W(TZ.root,OZ.shinyText),children:[(0,jZ.jsxs)(`span`,{style:{marginInlineEnd:6},children:[o(a),`:`]}),(0,jZ.jsx)(CZ,{filePath:s})]}):(0,jZ.jsx)(`div`,{className:W(TZ.root,OZ.shinyText),children:(0,jZ.jsx)(`span`,{children:o(a)})});let l=r?.linesAdded??0,u=r?.linesDeleted??0,d=[];return l>0&&d.push((0,jZ.jsxs)(mn,{code:!0,as:`span`,color:U.colorSuccess,fontSize:12,children:[(0,jZ.jsx)(vn,{icon:Gn,size:12}),l]},`added`)),u>0&&d.push((0,jZ.jsxs)(mn,{code:!0,as:`span`,color:U.colorError,fontSize:12,children:[(0,jZ.jsx)(vn,{icon:$n,size:12}),u]},`deleted`)),(0,jZ.jsxs)(`div`,{className:W(TZ.root,i&&OZ.shinyText),children:[(0,jZ.jsxs)(`span`,{style:{marginInlineEnd:6},children:[o(a),`:`]}),(0,jZ.jsx)(CZ,{filePath:s}),!i&&d.length>0&&(0,jZ.jsxs)(jZ.Fragment,{children:[` `,d.map((e,t)=>(0,jZ.jsxs)(`span`,{children:[t>0&&(0,jZ.jsx)(`span`,{className:MZ.separator,children:` / `}),e]},t))]})]})}),NZ.displayName=`EditLocalFileInspector`,PZ=e=>{let t=(0,AZ.memo)(t=>(0,jZ.jsx)(NZ,{...t,translationKey:e}));return t.displayName=`EditLocalFileInspector`,t}})),IZ,LZ,RZ,zZ,BZ,VZ,HZ,UZ,WZ,GZ=e((()=>{IZ=`add_comment.check_pull_request_mergeability.close_issue.close_pull_request.compare_commits.create_branch.create_issue.create_pull_request.delete_branch.fork_repository.get_branch.get_commit.get_file.get_issue.get_pull_request.get_repository.list_branches.list_commits.list_issues.list_pull_requests.list_repositories.merge_pull_request.reopen_issue.reopen_pull_request.request_review.search_code.search_issues.search_pull_requests.search_repositories.update_issue.update_pull_request`.split(`.`),LZ={branch:`branch`,branches:`branches`,code:`code`,commit:`commit`,commits:`commits`,f
4431ile:`file`,issue:`issue`,issues:`issues`,pull_request:`pull request`,pull_requests:`pull requests`,repositories:`repositories`,repository:`repository`,review:`review`},RZ=e=>e.toLowerCase().split(/[^a-z0-9]+/u).includes(`github`),zZ=e=>e.replaceAll(/([a-z0-9])([A-Z])/g,`$1_$2`).replaceAll(/[-\s]+/g,`_`).toLowerCase(),BZ=e=>{let t=zZ(e.trim()),n=!0;for(;n;)for(n=!1,t.startsWith(`server_github_`)&&(t=t.slice(14),n=!0),t.startsWith(`github_`)&&(t=t.slice(7),n=!0);t.startsWith(`_`);)t=t.slice(1),n=!0;return t},VZ=e=>{let t=e.split(`__`);return BZ(t.length>=3&&t[0]===`mcp`&&t.slice(1,-1).some(RZ)&&t.at(-1)||e)},HZ=e=>{let t=VZ(e),n=t.indexOf(`_`);if(n<=0)return{noun:t,verb:`other`};let r=t.slice(0,n),i=t.slice(n+1),a=LZ[i]??i.replaceAll(`_`,` `);switch(r){case`add`:case`check`:case`close`:case`compare`:case`create`:case`delete`:case`fork`:case`get`:case`list`:case`merge`:case`reopen`:case`request`:case`search`:case`update`:return{noun:a,verb:r};default:return{noun:t.replaceAll(`_`,` `),verb:`other`}}},UZ=e=>e&&e.charAt(0).toUpperCase()+e.slice(1),WZ=e=>{let{verb:t,noun:n}=e;return t===`other`?UZ(n):`${UZ(t)} ${n}`}})),KZ,qZ,JZ,YZ,XZ,ZZ,QZ,$Z,eQ,tQ,nQ,rQ,iQ,aQ,oQ=e((()=>{hn(),Zn(),KZ=t(qt()),kZ(),GZ(),qZ=t(xt()),JZ=bn(({css:e,cssVar:t})=>({branchBadge:e`
4432    display: inline-flex;
4433    flex-shrink: 0;
4434    gap: 4px;
4435    align-items: center;
4436
4437    min-width: 0;
4438    margin-inline-start: 6px;
4439    padding-block: 2px;
4440    padding-inline: 8px;
4441    border-radius: 999px;
4442
4443    font-family: ${t.fontFamilyCode};
4444    font-size: 12px;
4445    color: ${t.colorText};
4446
4447    background: ${t.colorFillQuaternary};
4448  `,branchBadgeText:e`
4449    overflow: hidden;
4450    max-width: 220px;
4451    text-overflow: ellipsis;
4452    white-space: nowrap;
4453  `,chip:e`
4454    overflow: hidden;
4455    display: inline-flex;
4456    flex-shrink: 1;
4457    align-items: stretch;
4458
4459    min-width: 0;
4460    margin-inline-start: 6px;
4461    border-radius: 999px;
4462
4463    font-size: 12px;
4464    line-height: 18px;
4465
4466    background: ${t.colorFillTertiary};
4467  `,chipAction:e`
4468    flex-shrink: 0;
4469    padding-block: 2px;
4470    padding-inline: 10px;
4471    color: ${t.colorText};
4472  `,chipDivider:e`
4473    flex-shrink: 0;
4474    align-self: stretch;
4475    width: 1px;
4476    background: ${t.colorBorderSecondary};
4477  `,chipIcon:e`
4478    flex-shrink: 0;
4479    color: ${t.colorTextDescription};
4480  `,chipKey:e`
4481    color: ${t.colorTextDescription};
4482  `,chipValue:e`
4483    overflow: hidden;
4484    display: inline-flex;
4485    flex-shrink: 1;
4486    gap: 4px;
4487    align-items: center;
4488
4489    min-width: 0;
4490    padding-block: 2px;
4491    padding-inline: 10px;
4492
4493    font-family: ${t.fontFamilyCode};
4494    color: ${t.colorText};
4495  `,chipValueText:e`
4496    overflow: hidden;
4497    min-width: 0;
4498    text-overflow: ellipsis;
4499    white-space: nowrap;
4500  `,icon:e`
4501    flex-shrink: 0;
4502    margin-inline-end: 6px;
4503    color: ${t.colorTextDescription};
4504  `,productPrefix:e`
4505    flex-shrink: 0;
4506
4507    margin-inline-end: 2px;
4508
4509    font-size: 13px;
4510    font-weight: 500;
4511    color: ${t.colorTextSecondary};
4512  `})),YZ=(0,KZ.memo)(({size:e=14})=>(0,qZ.jsx)(`svg`,{"aria-hidden":`true`,className:JZ.icon,height:e,viewBox:`0 0 98 96`,width:e,xmlns:`http://www.w3.org/2000/svg`,children:(0,qZ.jsx)(`path`,{d:`M48.9 0C21.9 0 0 22 0 49.1c0 21.7 14 40.1 33.5 46.6 2.4.5 3.3-1.1 3.3-2.4 0-1.2-.1-5.2-.1-9.4-13.6 3-16.5-5.8-16.5-5.8-2.2-5.7-5.4-7.2-5.4-7.2-4.5-3.1.3-3 .3-3 4.9.3 7.5 5.1 7.5 5.1 4.4 7.5 11.5 5.3 14.3 4.1.4-3.2 1.7-5.3 3.1-6.6-10.9-1.2-22.3-5.5-22.3-24.3 0-5.4 1.9-9.8 5.1-13.2-.5-1.2-2.2-6.3.5-13 0 0 4.1-1.3 13.5 5 3.9-1.1 8.1-1.6 12.2-1.6s8.3.5 12.2 1.6c9.4-6.4 13.5-5 13.5-5 2.7 6.7 1 11.8.5 13 3.2 3.4 5.1 7.8 5.1 13.2 0 18.9-11.5 23.1-22.4 24.3 1.8 1.6 3.3 4.6 3.3 9.3 0 6.7-.1 12.1-.1 13.8 0 1.3.9 2.9 3.4 2.4C84 89.2 98 70.8 98 49.1 97.9 22 75.9 0 48.9 0Z`,fill:`currentColor`})})),YZ.displayName=`GitHubMark`,XZ=(e,t=80)=>e.length>t?`${e.slice(0,t-1)}...`:e,ZZ=e=>{if(typeof e==`string`&&e.trim())return e.trim();if(typeof e==`number`)return String(e);if(typeof e==`object`&&e&&!Array.isArray(e)){let t=e;for(let e of[`full_name`,`name`,`login`,`id`]){let n=ZZ(t[e]);if(n)return n}}},QZ=(e,t)=>ZZ(e?.[t]),$Z=e=>{if(!e)return;let t=QZ(e,`repository_full_name`)||QZ(e,`full_name`)||QZ(e,`repository`)||QZ(e,`repo`);if(t)return t;let n=QZ(e,`owner`),r=QZ(e,`name`);return n&&r?`${n}/${r}`:void 0},eQ=e=>QZ(e,`pull_number`)||QZ(e,`pullNumber`)||QZ(e,`issue_number`)||QZ(e,`issueNumber`)||QZ(e,`number`),tQ=e=>{if(!e)return;let t=QZ(e,`head`)||QZ(e,`head_ref`),n=QZ(e,`base`)||QZ(e,`base_ref`);return t&&n?`${t} -> ${n}`:t||n||QZ(e,`branch`)||QZ(e,`ref`)},nQ=e=>{if(!e)return null;let t=$Z(e);if(t)return{key:`repo`,value:XZ(t,72)};let n=eQ(e);if(n)return{iconType:`number`,value:`#${n}`};let r=QZ(e,`title`)||QZ(e,`subject`);if(r)return{value:XZ(r,72)};let i=QZ(e,`query`)||QZ(e,`q`);if(i)return{key:`query`,value:XZ(i,72)};let a=QZ(e,`path`)||QZ(e,`file_path`);if(a)return{key:`path`,value:XZ(a,72)};for(let[t,n]of Object.entries(e))if(typeof n==`string`&&n.length>0)return{key:t,value:XZ(n,72)};return null},rQ=e=>({branch:tQ(e),primary:nQ(e)}),iQ=(0,KZ.memo)(({apiName:e,args:t,partialArgs:n,isArgumentsStreaming:r,isLoading:i})=>{let a=t??n,o=WZ(HZ(e)),{branch:s,primary:c}=rQ(a);return(0,qZ.jsxs)(`div`,{className:W(TZ.root,(r||i)&&OZ.shinyText),children:[(0,qZ.jsx)(YZ,{}),(0,qZ.jsx)(`span`,{className:JZ.productPrefix,children:`GitHub`}),(0,qZ.jsxs)(`span`,{className:JZ.chip,children:[(0,qZ.jsx)(`span`,{className:JZ.chipAction,children:o}),c&&(0,qZ.jsxs)(qZ.Fragment,{children:[(0,qZ.jsx)(`span`,{className:JZ.chipDivider}),(0,qZ.jsxs)(`span`,{className:JZ.chipValue,children:[c.iconType===`number`?(0,qZ.jsx)(mee,{className:JZ.chipIcon,size:12}
4512):c.key&&(0,qZ.jsxs)(`span`,{className:JZ.chipKey,children:[c.key,`:`]}),(0,qZ.jsx)(`span`,{className:JZ.chipValueText,children:c.value})]})]})]}),s&&(0,qZ.jsxs)(`span`,{className:JZ.branchBadge,title:s,children:[(0,qZ.jsx)(wee,{className:JZ.chipIcon,size:12}),(0,qZ.jsx)(`span`,{className:JZ.branchBadgeText,children:s})]})]})}),iQ.displayName=`GitHubInspector`,aQ=iQ})),iTe=e((()=>{oQ(),GZ()})),sQ,cQ,lQ,uQ,dQ=e((()=>{hn(),Zn(),sQ=t(qt()),a(),kZ(),cQ=t(xt()),lQ=bn(({css:e,cssVar:t})=>({baseline:e`
4513    align-items: baseline;
4514  `,statusIcon:e`
4515    align-self: center;
4516    margin-inline-start: 4px;
4517  `,tag:e`
4518    margin-inline-start: 6px;
4519    padding-block: 1px;
4520    padding-inline: 6px;
4521    border-radius: 4px;
4522
4523    font-family: ${t.fontFamilyCode};
4524    font-size: 12px;
4525    color: ${t.colorText};
4526
4527    background: ${t.colorFillTertiary};
4528  `})),uQ=e=>{let t=(0,sQ.memo)(({args:t,partialArgs:n,isArgumentsStreaming:r,pluginState:i,isLoading:a})=>{let{t:o}=c(`plugin`),s=t?.pattern||n?.pattern||``;if(r)return s?(0,cQ.jsxs)(`div`,{className:W(TZ.root,lQ.baseline,OZ.shinyText),children:[(0,cQ.jsxs)(`span`,{children:[o(e),`:`]}),(0,cQ.jsx)(`span`,{className:lQ.tag,children:s})]}):(0,cQ.jsx)(`div`,{className:W(TZ.root,OZ.shinyText),children:(0,cQ.jsx)(`span`,{children:o(e)})});let l=(i?.totalCount??0)>0;return(0,cQ.jsxs)(`div`,{className:W(TZ.root,lQ.baseline,a&&OZ.shinyText),children:[(0,cQ.jsxs)(`span`,{children:[o(e),`:`]}),s&&(0,cQ.jsx)(`span`,{className:lQ.tag,children:s}),a?null:i?l?(0,cQ.jsx)(Jn,{className:lQ.statusIcon,color:U.colorSuccess,size:14}):(0,cQ.jsx)(rr,{className:lQ.statusIcon,color:U.colorError,size:14}):null]})});return t.displayName=`GlobLocalFilesInspector`,t}})),fQ,pQ,mQ,hQ,gQ,_Q,vQ=e((()=>{Pn(),hn(),fQ=t(qt()),a(),kZ(),pQ=t(xt()),mQ=bn(({css:e,cssVar:t})=>({baseline:e`
4529    align-items: baseline;
4530  `,separator:e`
4531    margin-inline: 2px;
4532    color: ${t.colorTextQuaternary};
4533  `,tag:e`
4534    padding-block: 1px;
4535    padding-inline: 6px;
4536    border-radius: 4px;
4537
4538    font-family: ${t.fontFamilyCode};
4539    font-size: 12px;
4540    color: ${t.colorText};
4541
4542    background: ${t.colorFillTertiary};
4543  `,tagsList:e`
4544    display: inline-flex;
4545    flex-shrink: 1;
4546    gap: 4px;
4547    align-items: center;
4548
4549    min-width: 0;
4550    margin-inline-start: 6px;
4551
4552    white-space: nowrap;
4553  `})),hQ=e=>e.split(`|`).map(e=>e.trim()).filter(Boolean),gQ=(0,fQ.memo)(({pattern:e})=>{let t=hQ(e);return t.length===0?null:(0,pQ.jsx)(`span`,{className:mQ.tagsList,children:t.map((e,t)=>(0,pQ.jsxs)(fQ.Fragment,{children:[t>0&&(0,pQ.jsx)(`span`,{className:mQ.separator,children:`|`}),(0,pQ.jsx)(`span`,{className:mQ.tag,children:e})]},`${t}-${e}`))})}),gQ.displayName=`GrepPatternTags`,_Q=({translationKey:e,noResultsKey:t})=>{let n=(0,fQ.memo)(({args:n,partialArgs:r,isArgumentsStreaming:i,pluginState:a,isLoading:o})=>{let{t:s}=c(`plugin`),l=n?.pattern||r?.pattern||``;if(i)return l?(0,pQ.jsxs)(`div`,{className:W(TZ.root,mQ.baseline,OZ.shinyText),children:[(0,pQ.jsxs)(`span`,{children:[s(e),`:`]}),(0,pQ.jsx)(gQ,{pattern:l})]}):(0,pQ.jsx)(`div`,{className:W(TZ.root,OZ.shinyText),children:(0,pQ.jsx)(`span`,{children:s(e)})});let u=a?.totalMatches??0,d=u>0;return(0,pQ.jsxs)(`div`,{className:W(TZ.root,mQ.baseline,o&&OZ.shinyText),children:[(0,pQ.jsxs)(`span`,{children:[s(e),`:`]}),l&&(0,pQ.jsx)(gQ,{pattern:l}),!o&&a&&(d?(0,pQ.jsxs)(`span`,{style:{marginInlineStart:4},children:[`(`,u,`)`]}):(0,pQ.jsxs)(mn,{as:`span`,color:U.colorTextDescription,fontSize:12,style:{marginInlineStart:4},children:[`(`,s(t),`)`]}))]})});return n.displayName=`GrepContentInspector`,n}})),yQ,bQ,xQ,SQ,CQ,wQ,TQ,EQ,DQ,OQ=e((()=>{yQ=`mcp__claude_ai_Linear__`,bQ=`create_attachment.create_attachment_from_upload.create_issue_label.delete_attachment.delete_comment.delete_customer.delete_customer_need.delete_status_update.extract_images.get_attachment.get_diff.get_diff_threads.get_document.get_initiative.get_issue.get_issue_status.get_milestone.get_project.get_status_updates.get_team.get_user.list_comments.list_customers.list_cycles.list_diffs.list_documents.list_initiatives.list_issue_labels.list_issue_statuses.list_issues.list_milestones.list_project_labels.list_projects.list_teams.list_users.prepare_attachment_upload.save_comment.save_customer.save_customer_need.save_document.save_initiative.save_issue.save_milestone.save_project.save_status_update.search_documentation`.split(`.`),xQ={customer_need:`customer need`,diff_threads:`diff threads`,documentation:`docs`,issue_label:`issue label`,issue_labels:`issue labels`,issue_status:`issue status`,issue_statuses:`issue statuses`,project_labels:`project labels`,status_update:`status update`,status_updates:`status updates`},SQ=e=>e.toLowerCase().split(/[^a-z0-9]+/u).includes(`linear`),CQ=e=>{if(e.startsWith(`mcp__claude_ai_Linear__`))return e.slice(23);let t=e.split(`__`);return t.length>=3&&t[0]===`mcp`&&t.slice(1,-1).some(SQ)&&t.at(-1)||e},wQ=e=>CQ(e)!==e,TQ=e=>{let t=CQ(e);if(t===`extract_images`)return{noun:`images`,verb:`extract`};if(t===`prepare_attachment_upload`)return{noun:`attachment upload`,verb:`prepare`};if(t===`search_documentation`)return{noun:`docs`,verb:`search`};let n=t.indexOf(`_`);if(n<=0)return{noun:t,verb:`other`};let r=t.slice(0,n),i=t.slice(n+1),a=xQ[i]??i.replaceAll(`_`,` `);switch(r){case`get`:case`list`:case`save`:case`create`:case`delete`:return{noun:a,verb:r};default:return{noun:t.replaceAll(`_`,` `),verb:`other`}}},EQ=e=>e&&e.charAt(0).toUpperCase()+e.slice(1),DQ=e=>{let{verb:t,noun:n}=e;switch(t){case`extract`:return`Extract images`;case`prepare`:return`Prepare attachment upload`;case`search`:return`Search docs`;case`other`:return EQ(n);default:return`${EQ(t)} ${n}`}}})),kQ,AQ,jQ,MQ,NQ,PQ,FQ,IQ,LQ,RQ,zQ,BQ,VQ=e((()=>{hn(),Zn(),kQ=t(qt()),kZ(),OQ(),AQ=t(xt()),jQ=bn(({css:e,cssVar:t})=>({chip:e`
4554    overflow: hidden;
4555    display: inline-flex;
4556    flex-shrink: 1;
4557    align-items: stretch;
4558
4559    min-width: 0;
4560    margin-inline-start: 6px;
4561    border-radius: 999px;
4562
4563    font-size: 12px;
4564    line-height: 18px;
4565
4566    background: ${t.colorFillTertiary};
4567  `,chipAction:e`
4568    flex-shrink: 0;
4569    padding-block: 2px;
4570    padding-inline: 10px;
4571    color: ${t.colorText};
4572  `,chipDivider:e`
4573    flex-shrink: 0;
4574    align-self: stretch;
4575    width: 1px;
4576    background: ${t.colorBorderSecondary};
4577  `,chipIcon:e`
4578    flex-shrink: 0;
4579    color: ${t.colorTextDescription};
4580  `,chipKey:e`
4581    color: ${t.colorTextDescription};
4582  `,chipValue:e`
4583    overflow: hidden;
4584    display: inline-flex;
4585    flex-shrink: 1;
4586    gap: 4px;
4587    align-items: center;
4588
4589    min-width: 0;
4590    padding-block: 2px;
4591    padding-inline: 10px;
4592
4593    font-family: ${t.fontFamilyCode};
4594    color: ${t.colorText};
4595  `,chipValueText:e`
4596    overflow: hidden;
4597    min-width: 0;
4598    text-overflow: ellipsis;
4599    white-space: nowrap;
4600  `,icon:e`
4601    flex-shrink: 0;
4602    margin-inline-end: 6px;
4603    color: ${t.colorTextDescription};
4604  `,parentBadge:e`
4605    display: inline-flex;
4606    flex-shrink: 0;
4607    gap: 4px;
4608    align-items: center;
4609
4610    margin-inline-start: 6px;
4611    padding-block: 2px;
4612    padding-inline: 8px;
4613    border-radius: 999px;
4614
4615    font-family: ${t.fontFamilyCode};
4616    font-size: 12px;
4617    color: ${t.colorText};
4618
4619    background: ${t.colorFillQuaternary};
4620  `,parentBadgeIcon:e`
4621    flex-shrink: 0;
4622    color: ${t.colorTextDescription};
4623  `,productPrefix:e`
4624    flex-shrink: 0;
4625
4626    margin-inline-end: 2px;
4627
4628    font-size: 13px;
4629    font-weight: 500;
4630    color: ${t.colorTextSecondary};
4631  `})),MQ=(0,kQ.memo)(({size:e=14})=>(0,AQ.jsx)(`svg`,{"aria-hidden":`true`,className:jQ.icon,height:e,viewBox:`0 0 100 100`,width:e,xmlns:`http://www.w3.org/2000/svg`,children:(0,AQ.jsx)(`path`,{d:`M1.22541 61.5228c-.2225-.9485.90748-1.5459 1.59638-.857l36.5217 36.5208c.6889.6892.0915 1.8191-.857 1.5962C20.0696 93.4248 6.4263 79.7822 1.22541 61.5228ZM.00189 46.8083c-.034026.4081.115306.8067.405562 1.0969l51.683 51.683c.2903.2903.6888.4396 1.0969.4056 2.0035-.16708 3.9669-.49328 5.8741-.96868.7361-.18352.9961-1.0903.4607-1.6256L2.5907 40.4732c-.5353-.5354-1.4421-.2754-1.6256.4607-.475415 1.9072-.801574 3.8706-.968613 5.8744ZM4.21462 29.7355c-.16002.3549-.08227.7719.19288 1.047L69.2174 95.5901c.275.2752.6921.353 1.047.193 1.4913-.6716 2.9332-1.43 4.3197-2.275.5025-.3061.5856-1.0023.1674-1.4205L8.31112 25.279c-.41817-.4181-1.11435-.3349-1.42044.1675-.84572 1.3873-1.60473 2.8284-2.27606 4.319ZM12.6963 18.6088c-.3683-.3684-.3923-.9577-.0469-1.3489C21.7846 6.9544 35.1342 0 50 0c27.6142 0 50 22.3858 50 50 0 14.8669-6.9544 28.2155-17.2598 37.3499-.3912.3461-.9805.3214-1.349-.0469L12.6963 18.6088Z`,fill:`currentColor`})})),MQ.displayName=`LinearLogomark`,NQ=(e,t)=>{let{verb:n,noun:r}=e;switch(n){case`save`:return`${typeof t?.id==`string`&&t.id.length>0?`Update`:`Create`} ${r}`;case`extract`:return`Extract images`;case`prepare`:return`Prepare attachment upload`;case`search`:return`Search docs`;case`other`:return EQ(r);default:return`${EQ(n)} ${r}`}},PQ=(e,t=80)=>e.length>t?`${e.slice(0,t-1)}…`:e,FQ=(e,t)=>{let n=e?.[t];if(typeof n==`string`&&n.length>0)return n;if(typeof n==`number`)return String(n)},IQ={0:`None`,1:`Urgent`,2:`High`,3:`Medium`,4:`Low`},LQ=(e,t)=>{let{verb:n}=e;if(n===`search`){let e=FQ(t,`query`);return e?{value:PQ(e,60)}:null}if(n===`get`||n===`delete`){let e=FQ(t,`id`);if(e)return{key:`id`,value:e}}if(n===`save`||n===`create`){let e=FQ(t,`id`);if(e)return{key:`id`,value:e};let n=FQ(t,`title`)??FQ(t,`name`)??FQ(t,`body`);if(n)return{value:PQ(n,60)}}if(n===`list`){let e=FQ(t,`query`);if(e)return{key:`query`,value:PQ(e,60)};for(let e of[`team`,`project`,`assignee`,`state`,`cycle`,`parentId`,`label`]){let n=FQ(t,e);if(n)return e===`parentId`?{iconType:`parent`,value:n}:{key:e,value:PQ(n,40)}}if(typeof t.priority==`number`)return{key:`priority`,value:IQ[t.priority]??Str
4631ing(t.priority)}}for(let[e,n]of Object.entries(t))if(typeof n==`string`&&n.length>0)return{key:e,value:PQ(n,60)};return null},RQ=(e,t)=>{if(!t)return{primary:null};let n=LQ(e,t),r=FQ(t,`parentId`);return{parentId:r&&n?.value!==r?r:void 0,primary:n}},zQ=(0,kQ.memo)(({apiName:e,args:t,partialArgs:n,isArgumentsStreaming:r,isLoading:i})=>{let a=t??n,o=TQ(e),s=NQ(o,a),{primary:c,parentId:l}=RQ(o,a);return(0,AQ.jsxs)(`div`,{className:W(TZ.root,(r||i)&&OZ.shinyText),children:[(0,AQ.jsx)(MQ,{}),(0,AQ.jsx)(`span`,{className:jQ.productPrefix,children:`Linear`}),(0,AQ.jsxs)(`span`,{className:jQ.chip,children:[(0,AQ.jsx)(`span`,{className:jQ.chipAction,children:s}),c&&(0,AQ.jsxs)(AQ.Fragment,{children:[(0,AQ.jsx)(`span`,{className:jQ.chipDivider}),(0,AQ.jsxs)(`span`,{className:jQ.chipValue,children:[c.iconType===`parent`?(0,AQ.jsx)(qn,{className:jQ.chipIcon,size:12}):c.key&&(0,AQ.jsxs)(`span`,{className:jQ.chipKey,children:[c.key,`:`]}),(0,AQ.jsx)(`span`,{className:jQ.chipValueText,children:c.value})]})]})]}),l&&(0,AQ.jsxs)(`span`,{className:jQ.parentBadge,title:`parent: ${l}`,children:[(0,AQ.jsx)(qn,{className:jQ.parentBadgeIcon,size:12}),(0,AQ.jsx)(`span`,{children:l})]})]})}),zQ.displayName=`LinearInspector`,BQ=zQ})),aTe=e((()=>{VQ(),OQ()})),HQ,UQ,WQ,GQ=e((()=>{hn(),HQ=t(qt()),a(),wZ(),kZ(),UQ=t(xt()),WQ=e=>{let t=(0,HQ.memo)(({args:t,partialArgs:n,isArgumentsStreaming:r,pluginState:i,isLoading:a})=>{let{t:o}=c(`plugin`),s=t?.path||t?.directoryPath||n?.path||``,l=i?.totalCount??i?.files?.length??0;return r?s?(0,UQ.jsxs)(`div`,{className:W(TZ.root,OZ.shinyText),children:[(0,UQ.jsxs)(`span`,{style:{marginInlineEnd:6},children:[o(e),`:`]}),(0,UQ.jsx)(CZ,{isDirectory:!0,filePath:s})]}):(0,UQ.jsx)(`div`,{className:W(TZ.root,OZ.shinyText),children:(0,UQ.jsx)(`span`,{children:o(e)})}):(0,UQ.jsxs)(`div`,{className:W(TZ.root,a&&OZ.shinyText),children:[(0,UQ.jsxs)(`span`,{style:{marginInlineEnd:6},children:[o(e),`:`]}),(0,UQ.jsx)(CZ,{isDirectory:!0,filePath:s}),!a&&l>0&&(0,UQ.jsxs)(`span`,{style:{marginInlineStart:4},children:[`(`,l,`)`]})]})});return t.displayName=`ListLocalFilesInspector`,t}})),KQ,qQ,JQ,oTe=e((()=>{Pn(),hn(),Zn(),KQ=t(qt()),a(),kZ(),qQ=t(xt()),JQ=e=>{let t=(0,KQ.memo)(({args:t,partialArgs:n,isArgumentsStreaming:r,pluginState:i,isLoading:a})=>{let{t:o}=c(`plugin`),s=t||n||{},l=s.operations?.length??s.items?.length??0,u=i?.totalCount??l,d=i?.successCount,f=d!==void 0&&u>0&&d===u,p=r||a;return(0,qQ.jsxs)(`div`,{className:W(TZ.root,p&&OZ.shinyText),children:[(0,qQ.jsx)(`span`,{style:{marginInlineEnd:6},children:o(e)}),u>0&&(0,qQ.jsx)(mn,{code:!0,as:`span`,fontSize:12,children:d===void 0?u:`${d}/${u}`}),!a&&d!==void 0&&(0,qQ.jsx)(`span`,{style:{marginInlineStart:4},children:f?(0,qQ.jsx)(vn,{color:U.colorSuccess,icon:Jn,size:14}):(0,qQ.jsx)(vn,{color:U.colorError,icon:rr,size:14})})]})});return t.displayName=`MoveLocalFilesInspector`,t}})),YQ,XQ,ZQ,sTe=e((()=>{hn(),YQ=t(qt()),a(),wZ(),kZ(),XQ=t(xt()),ZQ=e=>{let t=(0,YQ.memo)(({args:t,partialArgs:n,isArgumentsStreaming:r,isLoading:i})=>{let{t:a}=c(`plugin`),o=t?.path||n?.path||``,s=(0,YQ.useMemo)(()=>{let e=t?.startLine??t?.loc?.[0],n=t?.endLine??t?.loc?.[1];if(e!==void 0&&n!==void 0)return`L${e}-L${n}`;if(e!==void 0)return`L${e}`},[t]);return r?o?(0,XQ.jsxs)(`div`,{className:W(TZ.root,OZ.shinyText),children:[(0,XQ.jsxs)(`span`,{style:{marginInlineEnd:6},children:[a(e),`:`]}),(0,XQ.jsx)(CZ,{filePath:o})]}):(0,XQ.jsx)(`div`,{className:W(TZ.root,OZ.shinyText),children:(0,XQ.jsx)(`span`,{children:a(e)})}):(0,XQ.jsxs)(`div`,{className:W(TZ.root,i&&OZ.shinyText),children:[(0,XQ.jsxs)(`span`,{style:{marginInlineEnd:6},children:[a(e),`:`]}),(0,XQ.jsx)(CZ,{filePath:o}),s&&(0,XQ.jsxs)(`span`,{style:{marginInlineStart:4},children:[`(`,s,`)`]})]})});return t.displayName=`ReadLocalFileInspector`,t}})),cTe,lTe,QQ,uTe=e((()=>{cTe=/^(?:\/usr\/bin\/env\s+)?(?:\/\S+\/)?(?:bash|sh|zsh)\s+(?:-lc|-c|-l\s+-c)\s+(\S[\s\S]*)$/,lTe=e=>{let t=e.trim();if(t.length<2)return t;let n=t[0];if(n!==`"`&&n!==`'`||t.at(-1)!==n)return t;let r=t.slice(1,-1);return n===`'`?r.replaceAll(`'\\''`,`'`):r.replaceAll(`\\"`,`"`).replaceAll("\\`","`").replaceAll(`\\$`,`$`).replaceAll(`\\\\`,`\\`)},QQ=e=>{let t=e?.trim()||``;if(!t)return``;let n=t.match(cTe);return n&&lTe(n[1])||t}})),$Q,e$,t$,n$,r$,dTe=e((()=>{hn(),Zn(),$Q=t(qt()),a(),kZ(),uTe(),e$=t(xt()),t$=bn(({css:e,cssVar:t})=>({chip:e`
4632    overflow: hidden;
4633    display: inline-flex;
4634    flex-shrink: 1;
4635    gap: 6px;
4636    align-items: center;
4637
4638    min-width: 0;
4639    margin-inline-start: 6px;
4640    padding-block: 2px;
4641    padding-inline: 10px;
4642    border-radius: 999px;
4643
4644    background: ${t.colorFillTertiary};
4645  `,command:e`
4646    overflow: hidden;
4647
4648    min-width: 0;
4649
4650    font-family: ${t.fontFamilyCode};
4651    font-size: 12px;
4652    color: ${t.colorText};
4653    text-overflow: ellipsis;
4654    white-space: nowrap;
4655  `,leadingIcon:e`
4656    flex-shrink: 0;
4657    margin-inline-end: 6px;
4658    color: ${t.colorTextDescription};
4659  `,statusIcon:e`
4660    margin-inline-start: 4px;
4661  `,terminalIcon:e`
4662    flex-shrink: 0;
4663    color: ${t.colorTextDescription};
4664  `})),n$=(0,$Q.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n,pluginState:r,isLoading:i,translationKey:a,icon:o})=>{let{t:s}=c(`plugin`),l=QQ(e?.command||t?.command),u=e?.description||t?.description||l,d=o?(0,e$.jsx)(o,{className:t$.leadingIcon,size:14}):null,f=o?null:(0,e$.jsx)(ree,{className:t$.terminalIcon,size:14});if(n)return u?(0,e$.jsxs)(`div`,{className:W(TZ.root,OZ.shinyText),children:[d,(0,e$.jsxs)(`span`,{children:[s(a),`:`]}),(0,e$.jsxs)(`span`,{className:t$.chip,children:[f,(0,e$.jsx)(`span`,{className:t$.command,children:u})]})]}):(0,e$.jsxs)(`div`,{className:W(TZ.root,OZ.shinyText),children:[d,(0,e$.jsx)(`span`,{children:s(a)})]});let p=r?.success||r?.exitCode===0;
4664return(0,e$.jsxs)(`div`,{className:W(TZ.root,i&&OZ.shinyText),children:[d,(0,e$.jsxs)(`span`,{children:[s(a),`:`]}),u&&(0,e$.jsxs)(`span`,{className:t$.chip,children:[f,(0,e$.jsx)(`span`,{className:t$.command,children:u})]}),i||r?.success===void 0?null:p?(0,e$.jsx)(Jn,{className:t$.statusIcon,color:U.colorSuccess,size:14}):(0,e$.jsx)(rr,{className:t$.statusIcon,color:U.colorError,size:14})]})}),n$.displayName=`RunCommandInspector`,r$=e=>{let t=(0,$Q.memo)(t=>(0,e$.jsx)(n$,{...t,translationKey:e}));return t.displayName=`RunCommandInspector`,t}})),fTe,i$,pTe,mTe=e((()=>{Pn(),hn(),fTe=t(qt()),a(),kZ(),i$=t(xt()),pTe=({translationKey:e,noResultsKey:t})=>{let n=(0,fTe.memo)(({args:n,partialArgs:r,isArgumentsStreaming:i,pluginState:a,isLoading:o})=>{let{t:s}=c(`plugin`),l=n?.keyword||n?.keywords||n?.query||r?.keyword||r?.keywords||r?.query||``;if(i)return l?(0,i$.jsxs)(`div`,{className:W(TZ.root,OZ.shinyText),children:[(0,i$.jsxs)(`span`,{children:[s(e),`: `]}),(0,i$.jsx)(`span`,{className:EZ.primary,children:l})]}):(0,i$.jsx)(`div`,{className:W(TZ.root,OZ.shinyText),children:(0,i$.jsx)(`span`,{children:s(e)})});let u=a?.results?.length??a?.totalCount??0,d=u>0;return(0,i$.jsx)(`div`,{className:W(TZ.root,o&&OZ.shinyText),children:(0,i$.jsxs)(`span`,{style:{marginInlineStart:2},children:[(0,i$.jsxs)(`span`,{children:[s(e),`: `]}),l&&(0,i$.jsx)(`span`,{className:EZ.primary,children:l}),!o&&a&&(d?(0,i$.jsxs)(`span`,{style:{marginInlineStart:4},children:[`(`,u,`)`]}):(0,i$.jsxs)(mn,{as:`span`,color:U.colorTextDescription,fontSize:12,style:{marginInlineStart:4},children:[`(`,s(t),`)`]}))]})})});return n.displayName=`SearchLocalFilesInspector`,n}})),hTe,gTe,a$,_Te,vTe=e((()=>{hTe={home_timeline:`home timeline`,to_list:`to list`,user_timeline:`user timeline`},gTe=e=>{let t=e.indexOf(`_`);if(t<=0)return{noun:e,verb:`other`};let n=e.slice(0,t),r=e.slice(t+1),i=hTe[r]??r.replaceAll(`_`,` `);switch(n){case`get`:case`list`:case`search`:case`post`:case`create`:case`delete`:case`update`:case`like`:case`unlike`:case`retweet`:case`unretweet`:case`reply`:case`quote`:case`follow`:case`unfollow`:case`mute`:case`unmute`:case`block`:case`unblock`:case`bookmark`:case`unbookmark`:case`add`:case`remove`:return{noun:i,verb:n};default:return{noun:e.replaceAll(`_`,` `),verb:`other`}}},a$=e=>e&&e.charAt(0).toUpperCase()+e.slice(1),_Te=e=>{let{verb:t,noun:n}=e;return t===`other`?a$(n):t===`retweet`||t===`unretweet`?a$(t):`${a$(t)} ${n}`}})),o$,s$,c$,l$,yTe,u$,bTe,d$,xTe,STe,f$,CTe,wTe=e((()=>{hn(),o$=t(qt()),kZ(),vTe(),s$=t(xt()),c$=bn(({css:e,cssVar:t})=>({chip:e`
4665    overflow: hidden;
4666    display: inline-flex;
4667    flex-shrink: 1;
4668    align-items: stretch;
4669
4670    min-width: 0;
4671    margin-inline-start: 6px;
4672    border-radius: 999px;
4673
4674    font-size: 12px;
4675    line-height: 18px;
4676
4677    background: ${t.colorFillTertiary};
4678  `,chipAction:e`
4679    flex-shrink: 0;
4680    padding-block: 2px;
4681    padding-inline: 10px;
4682    color: ${t.colorText};
4683  `,chipDivider:e`
4684    flex-shrink: 0;
4685    align-self: stretch;
4686    width: 1px;
4687    background: ${t.colorBorderSecondary};
4688  `,chipKey:e`
4689    color: ${t.colorTextDescription};
4690  `,chipValue:e`
4691    overflow: hidden;
4692    display: inline-flex;
4693    flex-shrink: 1;
4694    gap: 4px;
4695    align-items: center;
4696
4697    min-width: 0;
4698    padding-block: 2px;
4699    padding-inline: 10px;
4700
4701    font-family: ${t.fontFamilyCode};
4702    color: ${t.colorText};
4703  `,chipValueText:e`
4704    overflow: hidden;
4705    min-width: 0;
4706    text-overflow: ellipsis;
4707    white-space: nowrap;
4708  `,icon:e`
4709    flex-shrink: 0;
4710    margin-inline-end: 6px;
4711    color: ${t.colorTextDescription};
4712  `,productPrefix:e`
4713    flex-shrink: 0;
4714
4715    margin-inline-end: 2px;
4716
4717    font-size: 13px;
4718    font-weight: 500;
4719    color: ${t.colorTextSecondary};
4720  `})),l$=(0,o$.memo)(({size:e=14})=>(0,s$.jsx)(`svg`,{"aria-hidden":`true`,className:c$.icon,height:e,viewBox:`0 0 1200 1227`,width:e,xmlns:`http://www.w3.org/2000/svg`,children:(0,s$.jsx)(`path`,{d:`M714.163 519.284 1160.89 0h-105.86L667.137 450.887 357.328 0H0l468.492 681.821L0 1226.37h105.866l409.625-476.152 327.181 476.152H1200L714.137 519.284h.026Zm-145 168.544-47.468-67.894L144.011 79.694h162.604l304.797 435.991 47.468 67.894 396.2 566.721H892.476L569.165 687.854Z`,fill:`currentColor`})})),l$.displayName=`XLogomark`,yTe=e=>_Te(e),u$=(e,t=60)=>e.length>t?`${e.slice(0,t-1)}…`:e,bTe=(e,t)=>
4720{let n=e?.[t];if(typeof n==`string`&&n.length>0)return n;if(typeof n==`number`)return String(n)},d$=60,xTe=[`tweetId`,`tweet_id`,`id`,`username`,`userId`,`user_id`,`screen_name`,`handle`,`query`,`q`,`text`,`content`,`status`,`message`,`listId`,`list_id`,`name`],STe=e=>{if(!e)return null;for(let t of xTe){let n=bTe(e,t);if(n)return{key:t,value:u$(n,d$)}}for(let[t,n]of Object.entries(e))if(typeof n==`string`&&n.length>0)return{key:t,value:u$(n,d$)};return null},f$=(0,o$.memo)(({apiName:e,args:t,partialArgs:n,isArgumentsStreaming:r,isLoading:i})=>{let a=t??n,o=yTe(gTe(e)),s=STe(a);return(0,s$.jsxs)(`div`,{className:W(TZ.root,(r||i)&&OZ.shinyText),children:[(0,s$.jsx)(l$,{}),(0,s$.jsx)(`span`,{className:c$.productPrefix,children:`X (Twitter)`}),(0,s$.jsxs)(`span`,{className:c$.chip,children:[(0,s$.jsx)(`span`,{className:c$.chipAction,children:o}),s&&(0,s$.jsxs)(s$.Fragment,{children:[(0,s$.jsx)(`span`,{className:c$.chipDivider}),(0,s$.jsxs)(`span`,{className:c$.chipValue,children:[s.key&&(0,s$.jsxs)(`span`,{className:c$.chipKey,children:[s.key,`:`]}),(0,s$.jsx)(`span`,{className:c$.chipValueText,children:s.value})]})]})]})]})}),f$.displayName=`TwitterInspector`,CTe=f$})),TTe=e((()=>{wTe(),vTe()})),ETe,p$,m$,DTe=e((()=>{Pn(),hn(),Zn(),ETe=t(qt()),a(),wZ(),kZ(),p$=t(xt()),m$=e=>{let t=(0,ETe.memo)(({args:t,partialArgs:n,isArgumentsStreaming:r,isLoading:i})=>{let{t:a}=c(`plugin`),o=t?.path||n?.path||``,s=t?.content?.split(`
4721`).length;return r?o?(0,p$.jsxs)(`div`,{className:W(TZ.root,OZ.shinyText),children:[(0,p$.jsxs)(`span`,{style:{marginInlineEnd:6},children:[a(e),`:`]}),(0,p$.jsx)(CZ,{filePath:o})]}):(0,p$.jsx)(`div`,{className:W(TZ.root,OZ.shinyText),children:(0,p$.jsx)(`span`,{children:a(e)})}):(0,p$.jsxs)(`div`,{className:W(TZ.root,i&&OZ.shinyText),children:[(0,p$.jsxs)(`span`,{style:{marginInlineEnd:6},children:[a(e),`:`]}),(0,p$.jsx)(CZ,{filePath:o}),!i&&s&&(0,p$.jsxs)(p$.Fragment,{children:[` `,(0,p$.jsxs)(mn,{code:!0,as:`span`,color:U.colorSuccess,fontSize:12,children:[(0,p$.jsx)(vn,{icon:Gn,size:12}),s]})]})]})});return t.displayName=`WriteLocalFileInspector`,t}})),h$=e((()=>{FZ(),iTe(),dQ(),vQ(),aTe(),GQ(),oTe(),sTe(),dTe(),mTe(),TTe(),DTe()})),g$,_$,OTe=e((()=>{g$=t(qt()),_$=(0,g$.memo)(({value:e,duration:t=500,formatter:n})=>{let[r,i]=(0,g$.useState)(e),a=(0,g$.useRef)(void 0),o=(0,g$.useRef)(void 0),s=(0,g$.useRef)(e);return(0,g$.useEffect)(()=>{let n=s.current,r=e-n;if(r===0)return;let c=l=>{o.current||=l;let u=l-o.current,d=Math.min(u/t,1);i(n+r*(1-(1-d)**3)),d<1?a.current=requestAnimationFrame(c):(s.current=e,o.current=void 0)};return a.current=requestAnimationFrame(c),()=>{a.current&&cancelAnimationFrame(a.current)}},[e,t]),n?n(r):Math.round(r).toLocaleString()}),_$.displayName=`AnimatedNumber`})),kTe,v$,y$,b$,ATe=e((()=>{Pn(),hn(),Zn(),kTe=t(qt()),v$=t(xt()),y$=bn(({css:e,cssVar:t})=>({option:e`
4722    cursor: pointer;
4723
4724    padding-block: 10px;
4725    padding-inline: 12px;
4726    border-radius: 8px;
4727
4728    transition: background 0.12s ease;
4729
4730    &:hover {
4731      background: ${t.colorFillQuaternary};
4732    }
4733  `,optionCheck:e`
4734    flex-shrink: 0;
4735    color: ${t.colorPrimary};
4736  `,optionDescription:e`
4737    font-size: 12px;
4738    line-height: 1.45;
4739    color: ${t.colorTextSecondary};
4740  `,optionIndex:e`
4741    flex-shrink: 0;
4742
4743    box-sizing: border-box;
4744    width: 22px;
4745    height: 22px;
4746    border-radius: 6px;
4747
4748    font-family: ${t.fontFamilyCode};
4749    font-size: 12px;
4750    font-weight: 600;
4751    line-height: 22px;
4752    color: ${t.colorTextSecondary};
4753    text-align: center;
4754
4755    background: ${t.colorFillTertiary};
4756  `,optionLabel:e`
4757    font-weight: 500;
4758  `,optionSelected:e`
4759    background: ${t.colorFillSecondary};
4760
4761    &:hover {
4762      background: ${t.colorFill};
4763    }
4764  `})),b$=(0,kTe.memo)(({index:e,label:t,description:n,selected:r,disabled:i,onToggle:a})=>(0,v$.jsxs)(yn,{horizontal:!0,align:`center`,"aria-selected":r,className:W(y$.option,r&&y$.optionSelected),gap:12,role:`option`,onClick:()=>{i||a()},children:[(0,v$.jsx)(`span`,{className:y$.optionIndex,children:e}),(0,v$.jsxs)(yn,{flex:1,gap:2,children:[(0,v$.jsx)(mn,{className:y$.optionLabel,children:t}),n&&(0,v$.jsx)(`span`,{className:y$.optionDescription,children:n})]}),r&&(0,v$.jsx)(vn,{className:y$.optionCheck,icon:Jn,size:16})]})),b$.displayName=`OptionCard`})),x$=e((()=>{OTe(),wZ(),ATe()})),jTe,MTe=e((()=>{jTe=e=>{let t=0,n=0,r;for(let i of e)i.role===`tool`?t+=1:i.role===`assistant`&&(n+=i.usage?.totalTokens??i.metadata?.usage?.totalTokens??0,!r&&i.model&&(r=i.model));return{model:r,toolCalls:t,totalTokens:n}}})),NTe,S$,C$=e((()=>
4764{cr(),Zn(),NTe={Explore:{icon:Kn,label:`Explore`},Plan:{icon:vee,label:`Plan`},"general-purpose":{icon:sr,label:`General purpose`},"statusline-setup":{icon:iee,label:`Statusline setup`}},S$=e=>{let t=e?.trim();if(t)return NTe[t]??{icon:sr,label:t}}})),PTe,w$,T$,FTe,ITe,E$,LTe=e((()=>{x$(),kZ(),Pn(),cr(),hn(),PTe=t(qt()),a(),bc(),Oi(),MTe(),yZ(),C$(),w$=t(xt()),T$=bn(({css:e,cssVar:t})=>({chip:e`
4765    overflow: hidden;
4766    display: inline-flex;
4767    flex-shrink: 1;
4768    align-items: center;
4769
4770    min-width: 0;
4771    margin-inline-start: 6px;
4772    padding-block: 2px;
4773    padding-inline: 10px;
4774    border-radius: 999px;
4775
4776    background: ${t.colorFillTertiary};
4777  `,chipText:e`
4778    overflow: hidden;
4779
4780    min-width: 0;
4781
4782    font-size: 12px;
4783    color: ${t.colorText};
4784    text-overflow: ellipsis;
4785    white-space: nowrap;
4786  `,icon:e`
4787    flex-shrink: 0;
4788    margin-inline: 6px;
4789    color: ${t.colorTextDescription};
4790  `,label:e`
4791    flex-shrink: 0;
4792    color: ${t.colorText};
4793  `,metrics:e`
4794    display: inline-flex;
4795    flex-shrink: 0;
4796    gap: 6px;
4797    align-items: center;
4798
4799    margin-inline-start: 8px;
4800
4801    font-size: 12px;
4802    color: ${t.colorTextDescription};
4803  `,metricsDot:e`
4804    color: ${t.colorTextQuaternary};
4805  `})),FTe=e=>e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${Math.round(e/1e3)}k`:`${(e/1e6).toFixed(1)}M`,ITe=e=>Z9(t=>{if(!e)return null;let n=(Ci.currentTopicThreads(t)??[]).find(t=>t.metadata?.sourceToolCallId===e);if(!n)return null;let r=jTe(Ci.getThreadDbMessages(n.id)(t)),i=r.toolCalls||n.metadata?.totalToolCalls||0,a=r.totalTokens||n.metadata?.totalTokens||0,o=r.model||n.metadata?.model;return{hasAny:i>0||a>0||!!o,model:o,toolCalls:i,totalTokens:a}}),E$=(0,PTe.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n,isLoading:r,toolCallId:i})=>{let{t:a}=c(`plugin`),{t:o}=c(`chat`),s=a(vZ.Agent),l=e??t,u=l?.description?.trim(),d=l?.subagent_type?.trim(),f=n||r,p=S$(d),m=p?.icon??sr,h=p?.label??s,g=ITe(i),_=[];g?.model&&_.push(`${o(`thread.subagentMetrics.modelLabel`)}: ${g.model}`),g&&g.toolCalls>0&&_.push(o(`thread.subagentMetrics.toolCalls`,{count:g.toolCalls})),g&&g.totalTokens>0&&_.push(o(`thread.subagentMetrics.tokens`,{count:g.totalTokens.toLocaleString(`en-US`)}));let v=g?.hasAny&&(g.toolCalls>0||g.totalTokens>0)?(0,w$.jsx)(xn,{title:_.length>0?_.join(` · `):void 0,children:(0,w$.jsxs)(`span`,{className:T$.metrics,children:[g.toolCalls>0&&(0,w$.jsx)(`span`,{children:o(`thread.subagentMetrics.toolsShort`,{count:g.toolCalls})}),g.toolCalls>0&&g.totalTokens>0&&(0,w$.jsx)(`span`,{className:T$.metricsDot,children:`·`}),g.totalTokens>0&&(0,w$.jsx)(`span`,{children:(0,w$.jsx)(_$,{duration:2e3,formatter:FTe,value:g.totalTokens})})]})}):null;return(0,w$.jsxs)(`div`,{className:W(TZ.root,f&&OZ.shinyText),children:[(0,w$.jsx)(`span`,{className:T$.label,children:`Agent:`}),(0,w$.jsx)(m,{className:T$.icon,size:14}),(0,w$.jsx)(`span`,{className:T$.label,children:h}),u&&(0,w$.jsx)(`span`,{className:T$.chip,children:(0,w$.jsx)(`span`,{className:T$.chipText,children:u})}),v]})}),E$.displayName=`ClaudeCodeAgentInspector`})),D$,RTe,O$,zTe,k$,A$,BTe,j$=e((()=>{D$=`__freeform__`,RTe=600*1e3,O$=`askUserDraft`,zTe=e=>{let t=e??{};return{custom:t.custom??{},escapeActive:!!t.escapeActive,escapeText:typeof t.escapeText==`string`?t.escapeText:``,picks:t.picks??{}}},k$=(e,t,n)=>{if(n[e.question]?.trim())return!0;let r=t[e.question];return e.multiSelect?Array.isArray(r)&&r.length>0:!!r},A$=(e,t,n)=>{let r={};for(let i of e){let e=n[i.question]?.trim();if(i.multiSelect){let n=Array.isArray(t[i.question])?t[i.question]:[],a=e?[...n,e]:n;a.length>0&&(r[i.question]=a)}else e?r[i.question]=e:t[i.question]&&(r[i.question]=t[i.question])}return r},BTe=e=>{let t=Math.max(0,Math.floor(e/1e3));return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,`0`)}`}})),VTe,M$,N$,P$,HTe=e((()=>{Pn(),hn(),VTe=t(qt()),x$(),M$=t(xt()),N$=bn(({css:e,cssVar:t})=>({customRow:e`
4806    margin-block-start: 2px;
4807
4808    /* Align the chip under the option number chips (OptionCard padding-inline). */
4809    padding-inline: 12px;
4810  `,index:e`
4811    flex-shrink: 0;
4812
4813    box-sizing: border-box;
4814    width: 22px;
4815    height: 22px;
4816    border-radius: 6px;
4817
4818    font-family: ${t.fontFamilyCode};
4819    font-size: 12px;
4820    font-weight: 600;
4821    line-height: 22px;
4822    color: ${t.colorTextSecondary};
4823    text-align: center;
4824
4825    background: ${t.colorFillTertiary};
4826  `})),P$=(0,VTe.memo)(({question:e,answer:t,customValue:n,customPlaceholder:r,disabled:i,multiSelectTag:a,onToggle:o,onCustomChange:s})=>{let c=n=>e.multiSelect?Array.isArray(t)&&t.includes(n):t===n;return(0,M$.jsxs)(yn,{gap:10,children:[(0,M$.jsxs)(yn,{horizontal:!0,align:`center`,gap:8,children:[e.header&&(0,M$.jsx)(mn,{type:`secondary`,children:e.header}),e.multiSelect&&(0,M$.jsx)(mn,{fontSize:12,type:`secondary`,children:a})]}),(0,M$.jsx)(mn,{strong:!0,children:e.question}),(0,M$.jsxs)(yn,{gap:4,role:`listbox`,children:[e.options.map((t,n)=>(0,M$.jsx)(b$,{description:t.description,disabled:i,index:n+1,label:t.label,selected:c(t.label),onToggle:()=>
4826o(e,t.label)},t.label)),(0,M$.jsxs)(yn,{horizontal:!0,align:`center`,className:N$.customRow,gap:12,children:[(0,M$.jsx)(`span`,{className:N$.index,children:e.options.length+1}),(0,M$.jsx)(kn,{autoSize:{maxRows:4,minRows:1},disabled:i,placeholder:r,style:{flex:1},value:n,variant:`filled`,onChange:t=>s(e,t.target.value)})]})]})]})}),P$.displayName=`AskUserQuestionPanel`})),UTe,WTe,F$,I$,GTe=e((()=>{Pn(),or(),Zn(),UTe=t(qt()),WTe=t(Vn()),j$(),HTe(),F$=t(xt()),I$=(0,UTe.memo)(e=>{let{actionsPortalTarget:t,activeQuestion:n,activeTab:r,custom:i,escapeActive:a,escapeText:o,expired:s,handleCustomChange:c,handleEscapeTextChange:l,handleSkip:u,handleSubmit:d,handleToggle:f,isMulti:p,isSubmitDisabled:m,labels:h,picks:g,questions:_,remainingMs:v,setActiveTab:y,setEscapeMode:b,showCountdown:x,submitting:S}=e,C=(0,F$.jsxs)(yn,{horizontal:!0,align:`center`,gap:8,justify:x?`space-between`:`flex-end`,width:`100%`,children:[x&&(0,F$.jsx)(mn,{fontSize:12,type:`secondary`,children:s?h.timeExpired:h.timeRemaining(BTe(v))}),(0,F$.jsxs)(yn,{horizontal:!0,gap:8,children:[(0,F$.jsx)(ar,{disabled:S,icon:(0,F$.jsx)(vn,{icon:rr}),onClick:u,children:h.skip}),(0,F$.jsx)(ar,{disabled:m,icon:(0,F$.jsx)(vn,{icon:nee}),loading:S,type:`primary`,onClick:d,children:h.submit})]})]});return(0,F$.jsxs)(yn,{gap:12,children:[p&&(0,F$.jsx)(kee,{activeKey:a?`escape`:r,variant:`square`,items:[..._.map((e,t)=>{let n=k$(e,g,i);return{key:String(t),label:(0,F$.jsxs)(yn,{horizontal:!0,align:`center`,gap:6,children:[(0,F$.jsxs)(mn,{children:[`Q`,t+1]}),n&&(0,F$.jsx)(vn,{icon:Jn,size:12})]})}}),{key:`escape`,label:(0,F$.jsxs)(yn,{horizontal:!0,align:`center`,gap:6,children:[(0,F$.jsx)(vn,{icon:Xn,size:12}),(0,F$.jsx)(mn,{children:h.escapeEnter})]})}],onChange:e=>{e===`escape`?b(!0):(b(!1),y(e))}}),a?(0,F$.jsx)(kn,{autoSize:{maxRows:8,minRows:3},disabled:s||S,placeholder:h.escapePlaceholder,value:o,variant:`filled`,onChange:e=>l(e.target.value)}):n&&(0,F$.jsx)(P$,{answer:g[n.question],customPlaceholder:h.customPlaceholder,customValue:i[n.question]??``,disabled:s||S,multiSelectTag:h.multiSelectTag,question:n,onCustomChange:c,onToggle:f}),t?(0,WTe.createPortal)(C,t):C]})}),I$.displayName=`AskUserQuestionView`})),L$,KTe,qTe,R$,JTe,z$,B$=e((()=>{Ie(),L$=e=>{if(typeof e!=`string`)return e;try{return JSON.parse(e)}catch{return e}},KTe=e=>{let t=ve(e),n=Re(t?.label);if(!n)return;let r=Re(t?.description);return r?{description:r,label:n}:{label:n}},qTe=e=>!!e,R$=e=>{let t=ve(e),n=Re(t?.question);if(!n)return;let r=t?.options,i=Array.isArray(r)?r.map(KTe).filter(qTe):[],a=Re(t?.header)??``,o=typeof t?.multiSelect==`boolean`?t.multiSelect:void 0;return{header:a,...o===void 0?{}:{multiSelect:o},options:i,question:n}},JTe=e=>!!e,z$=e=>{let t=L$(e),n=L$(ve(t)?.questions??t);if(Array.isArray(n))return n.map(R$).filter(JTe);let r=R$(n);return r?[r]:[]}})),V$,H$,YTe=e((()=>{V$=t(qt()),j$(),B$(),H$=({args:e,countdownMs:t,onInteractionAction:n,persistedDraft:r,writeDraft:i})=>{let a=(0,V$.useMemo)(()=>z$(e),[e]),o=zTe(r),[s,c]=(0,V$.useState)(()=>o.picks),[l,u]=(0,V$.useState)(()=>o.custom),[d,f]=(0,V$.useState)(()=>o.escapeText),[p,m]=(0,V$.useState)(()=>o.escapeActive),[h,g]=(0,V$.useState)(!1),[_,v]=(0,V$.useState)(()=>{let e=a.findIndex(e=>!k$(e,o.picks,o.custom));return String(e>=0?e:0)}),y=t!=null,b=(0,V$.useMemo)(()=>Date.now()+(t??0),[t]),[x,S]=(0,V$.useState)(()=>Date.now());(0,V$.useEffect)(()=>{if(!y)return;let e=setInterval(()=>S(Date.now()),1e3);return()=>clearInterval(e)},[y]);let C=y?x>=b:!1,w=(0,V$.useCallback)((e,t)=>{let n;if(e.multiSelect){let r=s[e.question]??[];n={...s,[e.question]:r.includes(t)?r.filter(e=>e!==t):[...r,t]}}else n={...s,[e.question]:t};let r=l;if(!e.multiSelect&&l[e.question]){let{[e.question]:t,...n}=l;r=n}if(c(n),r!==l&&u(r),i({custom:r,escapeActive:p,escapeText:d,picks:n}),!e.multiSelect&&a.length>1){let t=a.findIndex(t=>t.question!==e.question&&!k$(t,n,r));t>=0&&v(String(t))}},[s,l,p,d,a,i]),T=(0,V$.useCallback)((e,t)=>{let n={...l,[e.question]:t},r=s;if(!e.multiSelect&&t.trim()&&s[e.question]){let{[e.question]:t,...n}=s;r=n}u(n),r!==s&&c(r),i({custom:n,escapeActive:p,escapeText:d,picks:r})},[s,l,p,d,i]),E=(0,V$.useCallback)(async e=>{if(!(!n||h)){g(!0);try{await n({payload:e,type:`submit`})}catch(e){console.error(`[AskUserQuestion] submit failed:`,e),g(!1)}}},[n,h]),D=(0,V$.useCallback)(e=>{f(e),i({custom:l,escapeActive:!0,escapeText:e,picks:s})},[l,s,i]),O=(0,V$.useCallback)(e=>{m(e),i({custom:l,escapeActive:e,escapeText:d,picks:s})},[l,d,s,i]),k=a.length>1,A=p&&k,j=(0,V$.useCallback)(()=>{E(p&&k?{[D$]:d.trim()}:A$(a,s,l))},[l,p,k,d,s,a,E]),M=(0,V$.useCallback)(async()=>
4826{if(!(!n||h)){g(!0);try{await n({type:`skip`})}catch(e){console.error(`[AskUserQuestion] skip failed:`,e),g(!1)}}},[n,h]),N=(0,V$.useMemo)(()=>a.every(e=>k$(e,s,l)),[s,l,a]);return(0,V$.useEffect)(()=>{if(!C||h||a.length===0)return;if(p&&k&&d.trim().length>0){E({[D$]:d.trim()});return}let e=A$(a,s,l);for(let t of a)if(e[t.question]==null&&t.options.length>0){let n=t.options[0].label;e[t.question]=t.multiSelect?[n]:n}E(e)},[C,h,a,p,k,d,s,l,E]),{activeQuestion:a[Number(_)]??a[0],activeTab:_,custom:l,escapeActive:A,escapeText:d,expired:C,handleCustomChange:T,handleEscapeTextChange:D,handleSkip:M,handleSubmit:j,handleToggle:w,isMulti:k,isSubmitDisabled:a.length===0||(A?!d.trim()||h||C:!N||C||h),picks:s,questions:a,remainingMs:b-x,setActiveTab:v,setEscapeMode:O,submitting:h}}})),U$=e((()=>{GTe(),j$(),B$(),HTe(),YTe()})),XTe,W$,ZTe,G$,K$,QTe=e((()=>{U$(),kZ(),hn(),XTe=t(qt()),a(),yZ(),W$=t(xt()),ZTe=2,G$=bn(({css:e,cssVar:t})=>({chip:e`
4827    overflow: hidden;
4828
4829    min-width: 0;
4830    padding-block: 2px;
4831    padding-inline: 10px;
4832    border-radius: 999px;
4833
4834    font-size: 12px;
4835    color: ${t.colorText};
4836    text-overflow: ellipsis;
4837    white-space: nowrap;
4838
4839    background: ${t.colorFillTertiary};
4840  `,chips:e`
4841    overflow: hidden;
4842    display: flex;
4843    gap: 4px;
4844    align-items: center;
4845
4846    min-width: 0;
4847    margin-inline-start: 6px;
4848  `,label:e`
4849    flex-shrink: 0;
4850  `,more:e`
4851    flex-shrink: 0;
4852    font-size: 12px;
4853    color: ${t.colorTextTertiary};
4854  `})),K$=(0,XTe.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n,isLoading:r})=>{let{t:i}=c(`plugin`),a=i(vZ.AskUserQuestion),o=z$(e),s=(o.length?o:z$(t)).map(e=>e.header||e.question).filter(e=>!!e),l=s.slice(0,ZTe),u=s.length-l.length;return n&&l.length===0?(0,W$.jsx)(`div`,{className:W(TZ.root,OZ.shinyText),children:a}):(0,W$.jsxs)(`div`,{className:W(TZ.root,(n||r)&&OZ.shinyText),children:[(0,W$.jsx)(`span`,{className:G$.label,children:a}),l.length>0&&(0,W$.jsxs)(`div`,{className:G$.chips,children:[l.map((e,t)=>(0,W$.jsx)(`span`,{className:G$.chip,children:e},`${e}-${t}`)),u>0&&(0,W$.jsx)(`span`,{className:G$.more,children:`+${u}`})]})]})}),K$.displayName=`ClaudeCodeAskUserQuestionInspector`})),$Te,q$,J$,Y$,X$,eEe,Z$,Q$,tEe,$$=e((()=>{$Te=`mcp__lobe_cc__`,q$={browser_click:`click`,browser_fill:`fill`,browser_navigate:`navigate`,browser_press:`press`,browser_read_page:`readPage`,browser_screenshot:`screenshot`,browser_scroll:`scroll`,browser_snapshot:`snapshot`},J$=Object.keys(q$).map(e=>`${$Te}${e}`),Y$=e=>{if(e.startsWith(`mcp__lobe_cc__`))return q$[e.slice(14)]},X$=e=>!!Y$(e),eEe={click:`Clicked element`,fill:`Filled input`,navigate:`Opened page`,press:`Pressed key`,readPage:`Read page text`,screenshot:`Captured screenshot`,scroll:`Scrolled page`,snapshot:`Read page elements`},Z$=e=>`workingPanel.browser.tool.${e}`,Q$=e=>eEe[e],tEe=(e,t)=>{let n=Y$(e);return n?t(Z$(n),Q$(n)):null}})),nEe,e1,t1,rEe,iEe,aEe,oEe,n1,r1,sEe,i1,cEe=e((()=>{kZ(),hn(),Zn(),nEe=t(qt()),a(),$$(),e1=t(xt()),t1=bn(({css:e,cssVar:t})=>({chip:e`
4855    overflow: hidden;
4856    display: inline-flex;
4857    flex-shrink: 1;
4858    gap: 6px;
4859    align-items: center;
4860
4861    min-width: 0;
4862    margin-inline-start: 6px;
4863    padding-block: 2px;
4864    padding-inline: 10px;
4865    border-radius: 999px;
4866
4867    background: ${t.colorFillTertiary};
4868  `,icon:e`
4869    flex-shrink: 0;
4870    color: ${t.colorTextDescription};
4871  `,value:e`
4872    overflow: hidden;
4873
4874    min-width: 0;
4875
4876    font-family: ${t.fontFamilyCode};
4877    font-size: 12px;
4878    color: ${t.colorText};
4879    text-overflow: ellipsis;
4880    white-space: nowrap;
4881  `})),rEe={click:dee,fill:Oee,navigate:nr,press:Dee,readPage:Wn,screenshot:oee,scroll:uee,snapshot:Wn},iEe=e=>e.replace(/^https?:\/\//i,``),aEe=({dx:e,dy:t})=>{let n=[];return typeof t==`number`&&t!==0&&n.push(`${t>0?`↓`:`↑`} ${Math.abs(t)}px`),typeof e==`number`&&e!==0&&n.push(`${e>0?`→`:`←`} ${Math.abs(e)}px`),n.join(`  `)},oEe=(e,t)=>{switch(e){case`navigate`:return t.url?iEe(t.url.trim()):``;case`click`:{if(t.ref)return t.ref;let{x:e,y:n}=t;return typeof e==`number`&&typeof n==`number`?`(${e}, ${n})`:``}case`fill`:return t.text?.trim()||t.ref||``;case`press`:return t.key||``;case`scroll`:return aEe(t);default:return``}},n1=(0,nEe.memo)(({apiName:e,args:t,partialArgs:n,isArgumentsStreaming:r,isLoading:i})=>{let{t:a}=c(`chat`),o=Y$(e);if(!o)return null;let s=a(Z$(o),{defaultValue:Q$(o)}),l=oEe(o,t||n||{}),u=rEe[o],d=r||i;return(0,e1.jsxs)(`div`,{className:W(TZ.root,d&&OZ.shinyText),children:[(0,e1.jsx)(`span`,{children:l?`${s}:`:s}),l&&(0,e1.jsxs)(`span`,{className:t1.chip,children:[(0,e1.jsx)(u,{className:t1.icon,size:14}),(0,e1.jsx)(`span`,{className:t1.value,children:l})]})]})}),n1.displayName=`ClaudeCodeBrowserMcpInspector`,r1=n1,sEe=Object.fromEntries(J$.map(e=>[e,r1])),i1=new Proxy(sEe,{get:(e,t)=>{if(typeof t==`string`)return e[t]||(X$(t)?r1:void 0)}})})),a1,lEe,uEe,dEe,o1,fEe=e((()=>{h$(),a1=t(qt()),yZ(),lEe=t(xt()),uEe=(e,t)=>{if(e===t)return{linesAdded:0,linesDeleted:0};if(!e)return{linesAdded:t.split(`
4882`).length,linesDeleted:0};if(!t)return{linesAdded:0,linesDeleted:e.split(`
4883`).length};let n=e.split(`
4884`),r=t.split(`
4885`),i=n.length,a=r.length,o=Array.from({length:a+1}).fill(0),s=Array.from({length:a+1}).fill(0);for(let e=1;e<=i;e++){for(let t=1;t<=a;t++)s[t]=n[e-1]===r[t-1]?o[t-1]+1:Math.max(o[t],s[t-1]);for(let e=0;e<=a;e++)o[e]=s[e]}let c=o[a];return{linesAdded:a-c,linesDeleted:i-c}},dEe=PZ(vZ.Edit),o1=(0,a1.memo)(({args:e,pluginState:t,...n})=>{let r=(0,a1.useMemo)(()=>
4885{if(t)return t;if(!e?.old_string&&!e?.new_string)return;let{linesAdded:n,linesDeleted:r}=uEe(e.old_string??``,e.new_string??``);return{linesAdded:n,linesDeleted:r,path:e.file_path??``,replacements:+!e.replace_all}},[e,t]);return(0,lEe.jsx)(dEe,{...n,args:e,pluginState:r})}),o1.displayName=`ClaudeCodeEditInspector`})),s1,pEe,c1=e((()=>{OQ(),s1=bQ,pEe=e=>wQ(e)?`Linear · ${DQ(TQ(e))}`:null})),mEe,l1,hEe=e((()=>{h$(),c1(),mEe=Object.fromEntries(s1.map(e=>[`${yQ}${e}`,BQ])),l1=new Proxy(mEe,{get:(e,t)=>{if(typeof t==`string`)return e[t]||(wQ(t)?BQ:void 0)}})})),gEe,u1,d1,_Ee,f1,vEe=e((()=>{kZ(),hn(),Zn(),gEe=t(qt()),a(),yZ(),u1=t(xt()),d1=bn(({css:e,cssVar:t})=>({chip:e`
4886    overflow: hidden;
4887    display: inline-flex;
4888    flex-shrink: 1;
4889    gap: 6px;
4890    align-items: center;
4891
4892    min-width: 0;
4893    margin-inline-start: 6px;
4894    padding-block: 2px;
4895    padding-inline: 10px;
4896    border-radius: 999px;
4897
4898    background: ${t.colorFillTertiary};
4899  `,command:e`
4900    overflow: hidden;
4901
4902    min-width: 0;
4903
4904    font-family: ${t.fontFamilyCode};
4905    font-size: 12px;
4906    color: ${t.colorText};
4907    text-overflow: ellipsis;
4908    white-space: nowrap;
4909  `,description:e`
4910    overflow: hidden;
4911
4912    min-width: 0;
4913
4914    font-size: 12px;
4915    color: ${t.colorText};
4916    text-overflow: ellipsis;
4917    white-space: nowrap;
4918  `,monitorIcon:e`
4919    flex-shrink: 0;
4920    color: ${t.colorTextDescription};
4921  `,statusIcon:e`
4922    margin-inline-start: 4px;
4923  `,timeout:e`
4924    flex-shrink: 0;
4925    margin-inline-start: 8px;
4926    font-feature-settings: 'tnum';
4927    color: ${t.colorTextDescription};
4928  `})),_Ee=e=>{if(typeof e!=`number`||!Number.isFinite(e)||e<=0)return;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;if(n<60)return r>0?`${n}m ${r}s`:`${n}m`;let i=Math.floor(n/60),a=n%60;return a>0?`${i}h ${a}m`:`${i}h`},f1=(0,gEe.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n,pluginState:r,isLoading:i})=>{let{t:a}=c(`plugin`),o=a(vZ.Monitor),s=e??t,l=s?.description?.trim(),u=s?.command?.trim(),d=_Ee(s?.timeout_ms),f=n||i;if(n&&!l&&!u)return(0,u1.jsx)(`div`,{className:W(TZ.root,OZ.shinyText),children:o});let p=!l&&!!u,m=l||u,h=r?.success,g=r?.exitCode,_=h===!0||g===0,v=h===!1||typeof g==`number`&&g!==0;return(0,u1.jsxs)(`div`,{className:W(TZ.root,f&&OZ.shinyText),children:[(0,u1.jsxs)(`span`,{children:[o,`:`]}),m&&(0,u1.jsxs)(`span`,{className:d1.chip,children:[(0,u1.jsx)(Eee,{className:d1.monitorIcon,size:12}),(0,u1.jsx)(`span`,{className:p?d1.command:d1.description,children:m})]}),d&&(0,u1.jsxs)(`span`,{className:d1.timeout,children:[`· `,d]}),i?null:_?(0,u1.jsx)(Jn,{className:d1.statusIcon,color:U.colorSuccess,size:14}):v?(0,u1.jsx)(rr,{className:d1.statusIcon,color:U.colorError,size:14}):null]})}),f1.displayName=`ClaudeCodeMonitorInspector`})),yEe,bEe,p1,xEe,m1,SEe=e((()=>{h$(),yEe=t(qt()),yZ(),bEe=t(xt()),p1=e=>{let{file_path:t,offset:n,limit:r}=e??{};return{endLine:n!==void 0&&r!==void 0?n+r:void 0,path:t,startLine:n}},xEe=ZQ(vZ.Read),m1=(0,yEe.memo)(e=>(0,bEe.jsx)(xEe,{...e,args:p1(e.args),partialArgs:p1(e.partialArgs)})),m1.displayName=`ClaudeCodeReadInspector`})),CEe,h1,g1,wEe,_1,TEe=e((()=>{kZ(),hn(),CEe=t(qt()),a(),yZ(),h1=t(xt()),g1=bn(({css:e,cssVar:t})=>({chip:e`
4929    overflow: hidden;
4930    display: inline-flex;
4931    flex-shrink: 1;
4932    align-items: center;
4933
4934    min-width: 0;
4935    max-width: 60%;
4936    margin-inline-start: 6px;
4937    padding-block: 1px;
4938    padding-inline: 8px;
4939    border-radius: 999px;
4940
4941    font-size: 12px;
4942    color: ${t.colorText};
4943    text-overflow: ellipsis;
4944    white-space: nowrap;
4945
4946    background: ${t.colorFillTertiary};
4947  `,delay:e`
4948    flex-shrink: 0;
4949    margin-inline-start: 8px;
4950    color: ${t.colorTextDescription};
4951  `})),wEe=e=>{if(!Number.isFinite(e)||e<=0||e<60)return`${e}s`;let t=Math.floor(e/60),n=e%60;if(t<60)return n>0?`${t}m ${n}s`:`${t}m`;let r=Math.floor(t/60),i=t%60;return i>0?`${r}h ${i}m`:`${r}h`},_1=(0,CEe.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n,isLoading:r})=>{let{t:i}=c(`plugin`),a=i(vZ.ScheduleWakeup),o=e??t,s=o?.delaySeconds,l=o?.reason?.trim(),u=n||r;return n&&s===void 0&&!l?(0,h1.jsx)(`div`,{className:W(TZ.root,OZ.shinyText),children:a}):(0,h1.jsxs)(`div`,{className:W(TZ.root,u&&OZ.shinyText),children:[(0,h1.jsx)(`span`,{children:l||typeof s==`
4951number`?`${a}:`:a}),l&&(0,h1.jsx)(`span`,{className:g1.chip,children:l}),typeof s==`number`&&(0,h1.jsxs)(`span`,{className:g1.delay,children:[`· `,wEe(s)]})]})}),_1.displayName=`ClaudeCodeScheduleWakeupInspector`})),EEe,v1,DEe,y1,OEe=e((()=>{kZ(),hn(),EEe=t(qt()),a(),v1=t(xt()),DEe=bn(({css:e,cssVar:t})=>({chip:e`
4952    overflow: hidden;
4953    display: inline-flex;
4954    flex-shrink: 1;
4955    align-items: center;
4956
4957    min-width: 0;
4958    max-width: 70%;
4959    margin-inline-start: 6px;
4960    padding-block: 1px;
4961    padding-inline: 8px;
4962    border-radius: 999px;
4963
4964    font-size: 12px;
4965    color: ${t.colorText};
4966    text-overflow: ellipsis;
4967    white-space: nowrap;
4968
4969    background: ${t.colorFillTertiary};
4970  `})),y1=(0,EEe.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n,isLoading:r})=>{let{t:i}=c(`plugin`),a=i(`builtins.lobe-claude-code.sendMessage.title`),o=e??t,s=(o?.summary??o?.message??o?.content)?.trim(),l=n||r;return n&&!s?(0,v1.jsx)(`div`,{className:W(TZ.root,OZ.shinyText),children:a}):(0,v1.jsxs)(`div`,{className:W(TZ.root,l&&OZ.shinyText),children:[(0,v1.jsx)(`span`,{children:s?`${a}:`:a}),s&&(0,v1.jsx)(`span`,{className:DEe.chip,children:s})]})}),y1.displayName=`ClaudeCodeSendMessageInspector`})),kEe,b1,x1,S1,AEe=e((()=>{kZ(),cr(),hn(),kEe=t(qt()),a(),yZ(),b1=t(xt()),x1=bn(({css:e,cssVar:t})=>({chip:e`
4971    overflow: hidden;
4972    display: inline-flex;
4973    flex-shrink: 1;
4974    gap: 6px;
4975    align-items: center;
4976
4977    min-width: 0;
4978    margin-inline-start: 6px;
4979    padding-block: 2px;
4980    padding-inline: 10px;
4981    border-radius: 999px;
4982
4983    background: ${t.colorFillTertiary};
4984  `,skillIcon:e`
4985    flex-shrink: 0;
4986    color: ${t.colorTextDescription};
4987  `,skillName:e`
4988    overflow: hidden;
4989
4990    min-width: 0;
4991
4992    font-size: 12px;
4993    color: ${t.colorText};
4994    text-overflow: ellipsis;
4995    white-space: nowrap;
4996  `})),S1=(0,kEe.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n,isLoading:r})=>{let{t:i}=c(`plugin`),a=i(vZ.Skill),o=e?.skill||t?.skill;return n&&!o?(0,b1.jsx)(`div`,{className:W(TZ.root,OZ.shinyText),children:a}):(0,b1.jsxs)(`div`,{className:W(TZ.root,(n||r)&&OZ.shinyText),children:[(0,b1.jsx)(`span`,{children:a}),o&&(0,b1.jsxs)(`span`,{className:x1.chip,children:[(0,b1.jsx)(Aee,{className:x1.skillIcon,size:12}),(0,b1.jsx)(`span`,{className:x1.skillName,children:o})]})]})}),S1.displayName=`ClaudeCodeSkillInspector`})),C1,w1,T1,E1,D1,O1,k1,jEe,A1,j1,MEe=e((()=>{kZ(),hn(),C1=t(qt()),a(),yZ(),w1=t(xt()),T1=14,E1=2,D1=(T1-E1)/2,O1=2*Math.PI*D1,k1=bn(({css:e,cssVar:t})=>({chip:e`
4997    overflow: hidden;
4998    flex-shrink: 1;
4999
5000    min-width: 0;
5001    margin-inline-start: 4px;
5002    padding-block: 1px;
5003    padding-inline: 8px;
5004    border-radius: 999px;
5005
5006    color: ${t.colorText};
5007    text-overflow: ellipsis;
5008    white-space: nowrap;
5009
5010    background: ${t.colorFillSecondary};
5011  `,countChip:e`
5012    flex-shrink: 0;
5013
5014    padding-block: 1px;
5015    padding-inline: 6px;
5016    border-radius: 999px;
5017
5018    font-family: ${t.fontFamilyCode};
5019    font-size: 12px;
5020    color: ${t.colorTextSecondary};
5021
5022    background: ${t.colorFillTertiary};
5023  `,ring:e`
5024    transform: rotate(-90deg);
5025    flex-shrink: 0;
5026    margin-inline-end: 6px;
5027  `,ringProgress:e`
5028    transition:
5029      stroke-dashoffset 240ms ease,
5030      stroke 240ms ease;
5031  `,ringTrack:e`
5032    stroke: ${t.colorFillSecondary};
5033  `})),jEe=e=>({completed:e.filter(e=>e.status===`completed`).length,inProgress:e.find(e=>e.status===`processing`),total:e.length}),A1=(0,C1.memo)(({stats:e})=>{let{completed:t,total:n}=e,r=n>0?t/n:0,i=n>0&&t===n?U.colorSuccess:U.colorInfo;return(0,w1.jsxs)(`svg`,{className:k1.ring,height:T1,width:T1,children:[(0,w1.jsx)(`circle`,{className:k1.ringTrack,cx:T1/2,cy:T1/2,fill:`none`,r:D1,strokeWidth:E1}),(0,w1.jsx)(`circle`,{className:k1.ringProgress,cx:T1/2,cy:T1/2,fill:`none`,r:D1,stroke:i,strokeDasharray:O1,strokeDashoffset:O1*(1-r),strokeLinecap:`round`,strokeWidth:E1})]})}),A1.displayName=`ClaudeCodeTaskProgressRing`,j1=(0,C1.memo)(({apiName:e,args:t,partialArgs:n,pluginState:r,isArgumentsStreaming:i,isLoading:a})=>{let{t:o}=c(`plugin`),s=r?.todos?.items??[],l=(0,C1.useMemo)(()=>jEe(s),[s]),u=l.total>0&&l.completed===l.total;if(e===vZ.TaskCreate){let e=(t||n)?.subject,r=i||a,s=o(r?`builtins.lobe-claude-code.task.create.loading`:`builtins.lobe-claude-code.task.create.completed`),c=e?`${s}${e}`:s;return(0,w1.jsxs)(`div`,{className:W(TZ.root,r&&OZ.shinyText),children:[(0,w1.jsx)(A1,{stats:l}),l.total>0&&(0,w1.jsxs)(`span`,{className:k1.countChip,children:[l.completed,`/`,l.total]}),(0,w1.jsx)(`span`,{style:{marginInlineStart:6},children:c})]})}if(e===vZ.TaskUpdate){let e=t||n,r=e?.status;if(r){let t=e?.taskId,n=(t?s.find(e=>e.id===t)?.text:void 0)??e?.subject,c=o(r===`deleted`?`builtins.lobe-claude-code.task.updateDeleted`:r===`completed`?`builtins.lobe-claude-code.task.updateCompleted`:r===`in_progress`?`builtins.lobe-claude-code.task.updateInProgress`:`builtins.lobe-claude-code.task.updatePending`);return(0,w1.jsxs)(`div`,{className:W(TZ.root,(i||a)&&OZ.shinyText),children:[(0,w1.jsx)(A1,{stats:l}),l.total>0&&(0,w1.jsxs)(`span`,{className:k1.countChip,children:[l.completed,`/`,l.total]}),(0,w1.jsx)(`span`,{style:{marginInlineStart:l.total>0?6:0},children:n?`${c}: ${n}`:c})]})}
5033let c=e?.taskId,u=e?.subject??(c?s.find(e=>e.id===c)?.text:void 0);if(u){let e=i||a,t=o(e?`builtins.lobe-claude-code.task.updateSubject.loading`:`builtins.lobe-claude-code.task.updateSubject.completed`);return(0,w1.jsxs)(`div`,{className:W(TZ.root,e&&OZ.shinyText),children:[(0,w1.jsx)(A1,{stats:l}),l.total>0&&(0,w1.jsxs)(`span`,{className:k1.countChip,children:[l.completed,`/`,l.total]}),(0,w1.jsx)(`span`,{style:{marginInlineStart:l.total>0?6:0},children:`${t}: ${u}`})]})}}if(l.total===0){let r=t||n,s=i||a,c=(()=>{if(e===vZ.TaskUpdate){let e=r?.taskId;return e?o(s?`builtins.lobe-claude-code.task.update.loading`:`builtins.lobe-claude-code.task.update.completed`,{taskId:e}):o(`builtins.lobe-claude-code.todoWrite.todos`)}return o(s?`builtins.lobe-claude-code.task.list.loading`:`builtins.lobe-claude-code.task.list.completed`)})();return(0,w1.jsx)(`div`,{className:W(TZ.root,s&&OZ.shinyText),children:c})}let d=l.inProgress?o(`builtins.lobe-claude-code.todoWrite.currentStep`):o(u?`builtins.lobe-claude-code.todoWrite.allDone`:`builtins.lobe-claude-code.todoWrite.todos`),f=l.inProgress?l.inProgress.text:u?void 0:`${l.completed}/${l.total}`;return(0,w1.jsxs)(`div`,{className:W(TZ.root,a&&OZ.shinyText),children:[(0,w1.jsx)(A1,{stats:l}),(0,w1.jsx)(`span`,{children:d}),f&&(0,w1.jsxs)(w1.Fragment,{children:[(0,w1.jsx)(`span`,{children:`:`}),(0,w1.jsx)(`span`,{className:k1.chip,children:f})]})]})}),j1.displayName=`ClaudeCodeTaskInspector`})),NEe,PEe,M1,FEe=e((()=>{kZ(),hn(),NEe=t(qt()),a(),PEe=t(xt()),M1=(0,NEe.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n,isLoading:r})=>{let{t:i}=c(`plugin`),a=e?.taskId??t?.taskId;return(0,PEe.jsx)(`div`,{className:W(TZ.root,(n||r)&&OZ.shinyText),children:i(`builtins.lobe-claude-code.task.getLabel`,{taskId:a??``})})}),M1.displayName=`ClaudeCodeTaskGetInspector`})),IEe,N1,LEe,P1,REe=e((()=>{kZ(),hn(),IEe=t(qt()),a(),yZ(),N1=t(xt()),LEe=bn(({css:e,cssVar:t})=>({chip:e`
5034    overflow: hidden;
5035    display: inline-flex;
5036    flex-shrink: 1;
5037    align-items: center;
5038
5039    min-width: 0;
5040    max-width: 60%;
5041    margin-inline-start: 6px;
5042    padding-block: 1px;
5043    padding-inline: 8px;
5044    border-radius: 999px;
5045
5046    font-family: ${t.fontFamilyCode};
5047    font-size: 12px;
5048    color: ${t.colorText};
5049    text-overflow: ellipsis;
5050    white-space: nowrap;
5051
5052    background: ${t.colorFillTertiary};
5053  `})),P1=(0,IEe.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n,isLoading:r})=>{let{t:i}=c(`plugin`),a=i(vZ.TaskOutput),o=(e?.task_id??t?.task_id)?.trim(),s=n||r;return n&&!o?(0,N1.jsx)(`div`,{className:W(TZ.root,OZ.shinyText),children:a}):(0,N1.jsxs)(`div`,{className:W(TZ.root,s&&OZ.shinyText),children:[(0,N1.jsx)(`span`,{children:o?`${a}:`:a}),o&&(0,N1.jsx)(`span`,{className:LEe.chip,children:o})]})}),P1.displayName=`ClaudeCodeTaskOutputInspector`})),zEe,F1,BEe,I1,VEe=e((()=>{kZ(),hn(),zEe=t(qt()),a(),yZ(),F1=t(xt()),BEe=bn(({css:e,cssVar:t})=>({chip:e`
5054    overflow: hidden;
5055    display: inline-flex;
5056    flex-shrink: 1;
5057    align-items: center;
5058
5059    min-width: 0;
5060    max-width: 60%;
5061    margin-inline-start: 6px;
5062    padding-block: 1px;
5063    padding-inline: 8px;
5064    border-radius: 999px;
5065
5066    font-family: ${t.fontFamilyCode};
5067    font-size: 12px;
5068    color: ${t.colorText};
5069    text-overflow: ellipsis;
5070    white-space: nowrap;
5071
5072    background: ${t.colorFillTertiary};
5073  `})),I1=(0,zEe.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n,isLoading:r})=>{let{t:i}=c(`plugin`),a=i(vZ.TaskStop),o=e??t,s=(o?.task_id??o?.shell_id)?.trim(),l=n||r;return n&&!s?(0,F1.jsx)(`div`,{className:W(TZ.root,OZ.shinyText),children:a}):(0,F1.jsxs)(`div`,{className:W(TZ.root,l&&OZ.shinyText),children:[(0,F1.jsx)(`span`,{children:s?`${a}:`:a}),s&&(0,F1.jsx)(`span`,{className:BEe.chip,children:s})]})}),I1.displayName=`ClaudeCodeTaskStopInspector`})),L1,R1,z1,B1,V1,H1,U1,W1,HEe,G1,UEe=e((()=>{kZ(),hn(),L1=t(qt()),a(),R1=t(xt()),z1=14,B1=2,V1=(z1-B1)/2,H1=2*Math.PI*V1,U1=bn(({css:e,cssVar:t})=>({ring:e`
5074    transform: rotate(-90deg);
5075    flex-shrink: 0;
5076    margin-inline-end: 6px;
5077  `,ringTrack:e`
5078    stroke: ${t.colorFillSecondary};
5079  `,ringProgress:e`
5080    transition:
5081      stroke-dashoffset 240ms ease,
5082      stroke 240ms ease;
5083  `,chip:e`
5084    overflow: hidden;
5085    flex-shrink: 1;
5086
5087    min-width: 0;
5088    margin-inline-start: 4px;
5089    padding-block: 1px;
5090    padding-inline: 8px;
5091    border-radius: 999px;
5092
5093    color: ${t.colorText};
5094    text-overflow: ellipsis;
5095    white-space: nowrap;
5096
5097    background: ${t.colorFillSecondary};
5098  `})),W1=(0,L1.memo)(({stats:e})=>{let{completed:t,total:n}=e,r=n>0?t/n:0,i=n>0&&t===n?U.colorSuccess:U.colorInfo;return(0,R1.jsxs)(`svg`,{className:U1.ring,height:z1,width:z1,children:[(0,R1.jsx)(`circle`,{className:U1.ringTrack,cx:z1/2,cy:z1/2,fill:`none`,r:V1,strokeWidth:B1}),(0,R1.jsx)(`circle`,{className:U1.ringProgress,cx:z1/2,cy:z1/2,fill:`none`,r:V1,stroke:i,strokeDasharray:H1,strokeDashoffset:H1*(1-r),strokeLinecap:`round`,strokeWidth:B1})]})}),W1.displayName=`ClaudeCodeTodoProgressRing`,HEe=e=>{let t=e?.todos??[];return{completed:t.filter(e=>e?.status===`completed`).length,inProgress:t.find(e=>e?.status===`in_progress`),total:t.length}},G1=(0,L1.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n,isLoading:r})=>{let{t:i}=c(`plugin`),a=(0,L1.useMemo)(()=>HEe(e||t),[e,t]),o=a.total>0&&a.completed===a.total,s=a.inProgress?i(`builtins.lobe-claude-code.todoWrite.currentStep`):i(o?`builtins.lobe-claude-code.todoWrite.allDone`:`builtins.lobe-claude-code.todoWrite.todos`),l=a.inProgress?a.inProgress.activeForm||a.inProgress.content:a.total>0&&!o?`${a.completed}/${a.total}`:void 0;return n&&a.total===0?(0,R1.jsx)(`div`,{className:W(TZ.root,OZ.shinyText),children:s}):(0,R1.jsxs)(`div`,{className:W(TZ.root,(n||r)&&OZ.shinyText),children:[a.total>0&&(0,R1.jsx)(W1,{stats:a}),(0,R1.jsx)(`span`,{children:s}),l&&(0,R1.jsxs)(R1.Fragment,{children:[(0,R1.jsx)(`span`,{children:`:`}),(0,R1.jsx)(`span`,{className:U1.chip,children:l})]})]})}),G1.displayName=`ClaudeCodeTodoWriteInspector`})),WEe,K1,GEe,q1,KEe,J1,qEe=e((()=>{kZ(),hn(),WEe=t(qt()),a(),yZ(),K1=t(xt()),GEe=`select:`,q1=bn(({css:e,cssVar:t})=>({baseline:e`
5099    align-items: baseline;
5100  `,tag:e`
5101    padding-block: 2px;
5102    padding-inline: 10px;
5103    border-radius: 999px;
5104
5105    font-family: ${t.fontFamilyCode};
5106    font-size: 12px;
5107    color: ${t.colorText};
5108
5109    background: ${t.colorFillTertiary};
5110  `,tagsList:e`
5111    display: inline-flex;
5112    flex-shrink: 1;
5113    gap: 4px;
5114    align-items: center;
5115
5116    min-width: 0;
5117    margin-inline-start: 6px;
5118
5119    white-space: nowrap;
5120  `})),KEe=e=>{if(!e)return;let t=e.trim();if(!t.toLowerCase().startsWith(GEe))return{names:null,raw:t};let n=t.slice(7).split(`,`).map(e=>e.trim()).filter(Boolean);return{names:n.length>0?n:null,raw:t}},J1=(0,WEe.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n,isLoading:r})=>{let{t:i}=c(`plugin`),a=i(vZ.ToolSearch),o=KEe(e?.query||t?.query);if(n&&!o)return(0,K1.jsx)(`div`,{className:W(TZ.root,OZ.shinyText),children:a});let s=n||r;return o?.names?(0,K1.jsxs)(`div`,{className:W(TZ.root,q1.baseline,s&&OZ.shinyText),children:[(0,K1.jsxs)(`span`,{children:[a,`:`]}),(0,K1.jsx)(`span`,{className:q1.tagsList,children:o.names.map((e,t)=>(0,K1.jsx)(`span`,{className:q1.tag,children:e},`${t}-${e}`))})]}):(0,K1.jsxs)(`div`,{className:W(TZ.root,s&&OZ.shinyText),children:[(0,K1.jsx)(`span`,{children:a}),o&&(0,K1.jsxs)(K1.Fragment,{children:[(0,K1.jsx)(`span`,{children:`: `}),(0,K1.jsx)(`span`,{className:EZ.primary,children:o.raw})]})]})}),J1.displayName=`ClaudeCodeToolSearchInspector`})),JEe,Y1,X1,YEe,Z1,XEe=e((()=>{kZ(),hn(),Zn(),JEe=t(qt()),a(),yZ(),Y1=t(xt()),X1=bn(({css:e,cssVar:t})=>({chip:e`
5121    overflow: hidden;
5122    display: inline-flex;
5123    flex-shrink: 1;
5124    gap: 6px;
5125    align-items: center;
5126
5127    min-width: 0;
5128    margin-inline-start: 6px;
5129    padding-block: 2px;
5130    padding-inline: 10px;
5131    border-radius: 999px;
5132
5133    background: ${t.colorFillTertiary};
5134  `,icon:e`
5135    flex-shrink: 0;
5136    color: ${t.colorTextDescription};
5137  `,url:e`
5138    overflow: hidden;
5139
5140    min-width: 0;
5141
5142    font-family: ${t.fontFamilyCode};
5143    font-size: 12px;
5144    color: ${t.colorText};
5145    text-overflow: ellipsis;
5146    white-space: nowrap;
5147  `})),YEe=e=>e.replace(/^https?:\/\//i,``),Z1=(0,JEe.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n,isLoading:r})=>{let{t:i}=c(`plugin`),a=i(vZ.WebFetch),o=(e?.url||t?.url||``).trim();if(n&&!o)return(0,Y1.jsx)(`div`,{className:W(TZ.root,OZ.shinyText),children:a});let s=n||r;return(0,Y1.jsxs)(`div`,{className:W(TZ.root,s&&OZ.shinyText),children:[(0,Y1.jsx)(`span`,{children:o?`${a}:`:a}),o&&(0,Y1.jsxs)(`span`,{className:X1.chip,children:[(0,Y1.jsx)(nr,{className:X1.icon,size:14}),(0,Y1.jsx)(`span`,{className:X1.url,children:YEe(o)})]})]})}),Z1.displayName=`ClaudeCodeWebFetchInspector`})),ZEe,Q1,$1,QEe=e((()=>{kZ(),hn(),ZEe=t(qt()),a(),yZ(),Q1=t(xt()),$1=(0,ZEe.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n,isLoading:r})=>{let{t:i}=c(`plugin`),a=i(vZ.WebSearch),o=(e?.query||t?.query||``).trim();if(n&&!o)return(0,Q1.jsx)(`div`,{className:W(TZ.root,OZ.shinyText),children:a});let s=n||r;return(0,Q1.jsxs)(`div`,{className:W(TZ.root,s&&OZ.shinyText),children:[(0,Q1.jsx)(`span`,{children:a}),o&&(0,Q1.jsxs)(Q1.Fragment,{children:[(0,Q1.jsx)(`span`,{children:`: `}),(0,Q1.jsx)(`span`,{className:EZ.primary,children:o})]})]})}),$1.displayName=`ClaudeCodeWebSearchInspector`})),e0,t0,$Ee,eDe,tDe,nDe,n0,r0,i0,a0,o0,rDe=e((()=>{kZ(),hn(),Zn(),e0=t(qt()),a(),t0=t(xt()),$Ee={completed:`builtins.lobe-claude-code.worktree.create.completed`,failed:`builtins.lobe-claude-code.worktree.create.failed`,idle:`builtins.lobe-claude-code.worktree.create.idle`,loading:`builtins.lobe-claude-code.worktree.create.loading`},eDe={completed:`builtins.lobe-claude-code.worktree.enter.completed`,failed:`builtins.lobe-claude-code.worktree.enter.failed`,idle:`builtins.lobe-claude-code.worktree.enter.idle`,loading:`builtins.lobe-claude-code.worktree.enter.loading`},tDe={completed:`builtins.lobe-claude-code.worktree.exit.completed`,failed:`builtins.lobe-claude-code.worktree.exit.failed`,idle:`builtins.lobe-claude-code.worktree.exit.idle`,loading:`builtins.lobe-claude-code.worktree.exit.loading`},nDe={completed:`builtins.lobe-claude-code.worktree.remove.completed`,failed:`builtins.lobe-claude-code.worktree.remove.failed`,idle:`builtins.lobe-claude-code.worktree.remove.idle`,loading:`builtins.lobe-claude-code.worktree.remove.loading`},n0=bn(({css:e,cssVar:t})=>({chip:e`
5148    overflow: hidden;
5149    display: inline-flex;
5150    flex-shrink: 1;
5151    gap: 6px;
5152    align-items: center;
5153
5154    min-width: 0;
5155    max-width: min(420px, 60vw);
5156    margin-inline-start: 6px;
5157    padding-block: 2px;
5158    padding-inline: 10px;
5159    border-radius: 999px;
5160
5161    background: ${t.colorFillTertiary};
5162  `,icon:e`
5163    flex-shrink: 0;
5164    color: ${t.colorTextDescription};
5165  `,leadingIcon:e`
5166    margin-inline-end: 6px;
5167  `,risk:e`
5168    flex-shrink: 0;
5169
5170    margin-inline-start: 6px;
5171    padding-block: 1px;
5172    padding-inline: 6px;
5173    border-radius: 999px;
5174
5175    font-size: 12px;
5176    color: ${t.colorError};
5177
5178    background: ${t.colorErrorBg};
5179  `,target:e`
5180    overflow: hidden;
5181
5182    min-width: 0;
5183
5184    font-family: ${t.fontFamilyCode};
5185    font-size: 12px;
5186    color: ${t.colorText};
5187    text-overflow: ellipsis;
5188    white-space: nowrap;
5189  `})),r0=(e,t,n,r)=>e||t?`loading`:n?`failed`:r?`completed`:`idle`,i0=(0,e0.memo)(({target:e})=>(0,t0.jsxs)(`span`,{className:n0.chip,title:e,children:[(0,t0.jsx)(gee,{className:n0.icon,size:12}),(0,t0.jsx)(`span`,{className:n0.target,children:e})]})),i0.displayName=`ClaudeCodeWorktreeTarget`,a0=(0,e0.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n,isLoading:r,result:i})=>{let{t:a}=c(`plugin`),o=e?.name?.trim()||t?.name?.trim(),s=e?.path?.trim()||t?.path?.trim(),l=o||s,u=r0(n,r,!!i?.error,!!i),d=a((s?eDe:$Ee)[u]);return(0,t0.jsxs)(`div`,{className:W(TZ.root,(n||r)&&OZ.shinyText),children:[(0,t0.jsx)(`span`,{children:d}),l&&(0,t0.jsx)(i0,{target:l})]})}),a0.displayName=`ClaudeCodeEnterWorktreeInspector`,o0=(0,e0.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n,isLoading:r,result:i})=>{let{t:a}=c(`plugin`),o=e?.action||t?.action,s=e?.discard_changes??t?.discard_changes,l=r0(n,r,!!i?.error,!!i),u=a((o===`remove`?nDe:tDe)[l]);return(0,t0.jsxs)(`div`,{className:W(TZ.root,(n||r)&&OZ.shinyText),children:[(0,t0.jsx)(gee,{className:W(n0.icon,n0.leadingIcon),size:12}),(0,t0.jsx)(`span`,{children:u}),o===`remove`&&s&&(0,t0.jsx)(`span`,{className:n0.risk,children:a(`builtins.lobe-claude-code.worktree.discardChanges`)})]})}),o0.displayName=`ClaudeCodeExitWorktreeInspector`})),iDe,aDe,s0,oDe,c0,sDe=e((()=>{h$(),iDe=t(qt()),yZ(),aDe=t(xt()),s0=e=>{let{content:t,file_path:n}=e??{};return{content:t,path:n}}
5189,oDe=m$(vZ.Write),c0=(0,iDe.memo)(e=>(0,aDe.jsx)(oDe,{...e,args:s0(e.args),partialArgs:s0(e.partialArgs)})),c0.displayName=`ClaudeCodeWriteInspector`})),cDe,lDe,uDe=e((()=>{h$(),yZ(),LTe(),QTe(),cEe(),fEe(),hEe(),vEe(),SEe(),TEe(),OEe(),AEe(),MEe(),FEe(),REe(),VEe(),UEe(),qEe(),XEe(),QEe(),rDe(),sDe(),cDe={[vZ.Agent]:E$,[vZ.AskUserQuestion]:K$,[vZ.Bash]:r$(vZ.Bash),[vZ.Edit]:o1,[vZ.EnterWorktree]:a0,[vZ.ExitWorktree]:o0,[vZ.Glob]:uQ(vZ.Glob),[vZ.Grep]:_Q({noResultsKey:`No results`,translationKey:vZ.Grep}),[vZ.Monitor]:f1,[vZ.Read]:m1,[vZ.ScheduleWakeup]:_1,[vZ.SendMessage]:y1,[vZ.Skill]:S1,[vZ.TaskCreate]:j1,[vZ.TaskGet]:M1,[vZ.TaskList]:j1,[vZ.TaskOutput]:P1,[vZ.TaskStop]:I1,[vZ.TaskUpdate]:j1,[vZ.TodoWrite]:G1,[vZ.ToolSearch]:J1,[vZ.WebFetch]:Z1,[vZ.WebSearch]:$1,[vZ.Write]:c0,...i1,...l1},lDe=new Proxy(cDe,{get:(e,t)=>{if(typeof t==`string`)return t in e?e[t]:i1[t]??l1[t]}})}));function dDe(e,t){let n=new Map,r=new Map,i=new Map,a=new Map,o=new Set(e.map(e=>e.id)),s=new Map;for(let t of e)if(t.role===`compressedGroup`){let e=l0(t);e&&s.set(e,t.id)}for(let t of e){n.set(t.id,t);let e=t.parentId??null;e&&s.has(e)?e=s.get(e):e&&!o.has(e)&&(e=null);let a=r.get(e);if(a?a.push(t.id):r.set(e,[t.id]),t.threadId){let e=i.get(t.threadId);e?e.push(t):i.set(t.threadId,[t])}}if(t)for(let e of t)a.set(e.id,e);return{childrenMap:r,messageGroupMap:a,messageMap:n,threadMap:i}}var l0,fDe=e((()=>{l0=e=>{if(!e)return;if(e.lastMessageId)return e.lastMessageId;let t=e.compressedMessages;return t&&t.length>0?l0(t.at(-1)):e.children&&e.children.length>0?l0(e.children.at(-1)):e.tools&&e.tools.length>0?e.tools.at(-1)?.result_msg_id??e.id:e.id}}));function pDe(e){let{childrenMap:t,messageMap:n}=e,r=e=>({children:(t.get(e)??[]).filter(e=>{let t=n.get(e);return t&&!t.threadId}).map(e=>r(e)),id:e});return(t.get(null)??[]).filter(e=>{let t=n.get(e);return t&&!t.threadId}).map(e=>r(e))}var mDe=e((()=>{})),u0,hDe=e((()=>{u0=class{getActiveBranchId(e,t){let n=e.metadata?.activeBranchIndex;if(typeof n==`number`&&n>=0){if(n<t.children.length)return t.children[n].id;if(n===t.children.length)return}for(let e of t.children)if(e.children.length>0)return e.id;return t.children[0].id}getActiveBranchIdFromMetadata(e,t,n){let r=e.metadata?.activeBranchIndex;if(typeof r==`number`&&r>=0){if(r<t.length)return t[r];if(r===t.length)return}for(let e of t){let t=n.get(e);if(t&&t.length>0)return e}return t[0]}}})),gDe,_De=e((()=>{gDe=class{messageMap;messageGroupMap;branchResolver;messageCollector;generateNodeId;constructor(e,t,n,r,i){this.messageMap=e,this.messageGroupMap=t,this.branchResolver=n,this.messageCollector=r,this.generateNodeId=i}transformAll(e){let t=[];for(let n of e)this.transformToLinear(n,t);return t}transformToLinear(e,t){let n=this.messageMap.get(e.id);if(!n)return;if(this.isCompareMode(n)&&e.children.length>1){let r=this.createMessageNode(n);t.push(r);let i=this.createCompareNodeFromChildren(n,e);if(t.push(i),i.activeColumnId){let n=e.children.find(e=>e.id===i.activeColumnId);n&&n.children.length>0&&this.transformToLinear(n.children[0],t)}return}let r=n.groupId?this.messageGroupMap.get(n.groupId):void 0;if(r&&r.mode===`compare`){let i=this.createCompareNode(r,n);if(t.push(i),i.activeColumnId){let n=e.children.find(e=>e.id===i.activeColumnId);n&&n.children.length>0&&this.transformToLinear(n.children[0],t)}return}if(this.isAgentCouncilMode(n)&&e.children.length>1){let r=this.createAgentCouncilNodeFromChildren(n,e);t.push(r);for(let n of e.children)n.children.length>0&&this.transformToLinear(n.children[0],t);return}if(this.isTasksNode(e)){let r=this.createTasksNode(n,e);t.push(r);let i=e.children.filter(e=>this.messageMap.get(e.id)?.role!==`task`);for(let e of i)this.transformToLinear(e,t);let a=e.children.filter(e=>this.messageMap.get(e.id)?.role===`task`);for(let e of a)for(let n of e.children){let e=this.messageMap.get(n.id);e&&e.role!==`task`&&this.transformToLinear(n,t)}return}if(this.isAssistantGroupNode(n,e)){let r=this.createAssistantGroupNode(n,e);t.push(r);let i=this.messageCollector.findNextAfterTools(n,e);i&&this.transformToLinear(i,t);return}if(e.children.filter(e=>this.messageMap.get(e.id)?.role!==`tool`).length>1){let r=this.createMessageNode(n);t.push(r);let i=this.createBranchNode(n,e);t.push(i);return}let i=this.createMessageNode(n);t.push(i),e.children.length===1&&this.transformToLinear(e.children[0],t)}isCompareMode(e){return e.metadata?.compare===!0}isAgentCouncilMode(e){return e.metadata?.agentCouncil===!0}isAssistantGroupNode(e,t){return e.role===`assistant`?t.children.some(e=>this.messageMap.get(e.id)?.role===`tool`)||this.messageCollector.isToolChainHead(e):!1}createMessageNode(e){return{id:e.id,type:`message`}}createAssistantGroupNode(e,t){let n=[];
5189this.messageCollector.collectAssistantGroupMessages(e,t,n);let r=this.messageCollector.collectSignalCallbacks(e,t);n.push(...r);let i=this.messageCollector.collectTaskCompletions(e,t);return n.push(...i),{children:n,id:e.id,type:`assistantGroup`}}createBranchNode(e,t){let n=this.branchResolver.getActiveBranchId(e,t),r=n?t.children.findIndex(e=>e.id===n):t.children.length,i=t.children.map(e=>{let t=[];return this.transformToLinear(e,t),t});return{activeBranchIndex:r>=0?r:0,branches:i,id:this.generateNodeId(`branch`,e.id),parentMessageId:e.id,type:`branch`}}createCompareNodeFromChildren(e,t){let n,r=t.children.map(e=>{let t=this.messageMap.get(e.id);return t?(t.metadata?.activeColumn===!0&&(n=e.id),this.isAssistantGroupNode(t,e)?[this.createAssistantGroupNode(t,e)]:[{id:e.id,type:`message`}]):[{id:e.id,type:`message`}]}),i=t.children.map(e=>e.id).join(`-`),a=`compare-${e.id}-${i}`;return{activeColumnId:n,columns:r,id:a,messageId:e.id,type:`compare`}}createCompareNode(e,t){let n=[];for(let t of this.messageMap.values())t.groupId===e.id&&n.push(t);return{activeColumnId:n.find(e=>e.metadata?.activeColumn===!0)?.id,columns:n.map(e=>[{id:e.id,type:`message`}]),id:this.generateNodeId(`compare`,e.id),messageId:e.parentMessageId||t.id,type:`compare`}}createAgentCouncilNodeFromChildren(e,t){let n=t.children.map(e=>{let t=this.messageMap.get(e.id);return t&&this.isAssistantGroupNode(t,e)?this.createAssistantGroupNode(t,e):{id:e.id,type:`message`}}),r=t.children.map(e=>e.id).join(`-`);return{id:`agentCouncil-${e.id}-${r}`,members:n,messageId:e.id,type:`agentCouncil`}}isTasksNode(e){return e.children.length<2?!1:e.children.filter(e=>this.messageMap.get(e.id)?.role===`task`).length>1}createTasksNode(e,t){let n=t.children.filter(e=>this.messageMap.get(e.id)?.role===`task`),r=n.map(e=>({id:e.id,type:`message`})),i=n.map(e=>e.id).join(`-`);return{children:r,id:`tasks-${e.id}-${i}`,messageId:e.id,type:`tasks`}}}})),d0,vDe,yDe=e((()=>{d0=e=>e?.metadata?.orchestrationRole===`supervisor`||!!e?.metadata?.isSupervisor,vDe=class{messageMap;messageGroupMap;childrenMap;branchResolver;messageCollector;messageTransformer;constructor(e,t,n,r,i,a){this.messageMap=e,this.messageGroupMap=t,this.childrenMap=n,this.branchResolver=r,this.messageCollector=i,this.messageTransformer=a}flatten(e){let t=[],n=new Set,r=null;return!(this.childrenMap.has(null)&&this.childrenMap.get(null).length>0)&&e.length>0&&(r=e[0].parentId??null),this.buildFlatListRecursive(r,t,n,e),t}buildFlatListRecursive(e,t,n,r){let i=this.childrenMap.get(e)??[];if(e){let a=this.messageMap.get(e);if(a&&i.length>0){let e=i.filter(e=>this.messageMap.get(e)?.role===`task`);if(e.length>1){let o=i.filter(e=>this.messageMap.get(e)?.role!==`task`),s=new Set(e.map(e=>this.messageMap.get(e)?.agentId).filter(Boolean)).size>1?this.createGroupTasksMessage(a,e,n):this.createTasksMessage(a,e,n);t.push(s);for(let e of o)if(!n.has(e)){let i=this.messageMap.get(e);i&&(i.role===`assistant`&&i.tools&&i.tools.length>0?this.processAssistantGroup(i,t,n,r):(t.push(i),n.add(e),this.buildFlatListRecursive(e,t,n,r)))}for(let i of e){let e=this.childrenMap.get(i)??[];for(let i of e)if(!n.has(i)){let e=this.messageMap.get(i);if(e&&e.role!==`task`)if(e.role===`assistant`&&e.tools&&e.tools.length>0)this.processAssistantGroup(e,t,n,r);else if(e.role===`assistant`&&d0(e)&&(!e.tools||e.tools.length===0)){let a=this.createSupervisorContentMessage(e);t.push(a),n.add(i),this.buildFlatListRecursive(i,t,n,r)}else t.push(e),n.add(i),this.buildFlatListRecursive(i,t,n,r)}}return}}}for(let e of i){if(n.has(e))continue;let i=this.messageMap.get(e);if(!i)continue;let a=i.groupId?this.messageGroupMap.get(i.groupId):void 0;if(a&&a.mode===`compare`&&!n.has(a.id)){let e=this.messageCollector.collectGroupMembers(i.groupId,r),o=this.createCompareMessage(a,e);t.push(o),e.forEach(e=>n.add(e.id)),n.add(a.id),o.activeColumnId&&this.buildFlatListRecursive(o.activeColumnId,t,n,r);continue}if(i.role===`assistant`&&(i.tools&&i.tools.length>0||!d0(i)&&this.messageCollector.isToolChainHead(i))){let e=[],a=[];this.messageCollector.collectAssistantChain(i,r,e,a,n);let o=this.messageCollector.collectFlatSignalCallbacks(a,r),s=this.messageCollector.collectFlatTaskCompletions(a,r),c=this.collectCouncilMembers(a,r,n),l=this.createAssistantGroupMessage(e[0],e,a,o,s,c?.members);
5189t.push(l),e.forEach(e=>n.add(e.id)),a.forEach(e=>n.add(e.id));for(let e of o)for(let t of e.callbacks)n.add(t.id);for(let e of s)n.add(e.id);if(c)for(let e of c.memberIds)this.buildFlatListRecursive(e,t,n,r);this.continueAfterAssistantGroup(e,a,t,n,r);continue}if(i.role===`assistant`&&d0(i)&&(!i.tools||i.tools.length===0)){let e=this.createSupervisorContentMessage(i);t.push(e),n.add(i.id),this.buildFlatListRecursive(i.id,t,n,r);continue}let o=this.childrenMap.get(i.id)??[],s=o.filter(e=>this.messageMap.get(e)?.role!==`tool`);if(this.isCompareMode(i)&&o.length>1){t.push(i),n.add(i.id);let e=this.createCompareMessageFromChildIds(i,o,r,n);t.push(e),e.activeColumnId&&this.buildFlatListRecursive(e.activeColumnId,t,n,r);continue}if(i.role===`user`&&s.length>1){let e=this.branchResolver.getActiveBranchIdFromMetadata(i,s,this.childrenMap);if(!e){t.push(i),n.add(i.id);continue}t.push(i),n.add(i.id);let a=s.indexOf(e),o=this.messageMap.get(e);if(o)if(o.role===`assistant`&&o.tools&&o.tools.length>0){let e=[],i=[];this.messageCollector.collectAssistantChain(o,r,e,i,n);let c=this.createAssistantGroupMessage(e[0],e,i),l=this.createMessageWithBranches(c,s.length,a);t.push(l),e.forEach(e=>n.add(e.id)),i.forEach(e=>n.add(e.id)),this.continueAfterAssistantGroup(e,i,t,n,r)}else{let i=this.createMessageWithBranches(o,s.length,a);t.push(i),n.add(e),this.buildFlatListRecursive(e,t,n,r)}continue}if(i.role===`assistant`&&s.length>1){let e=this.branchResolver.getActiveBranchIdFromMetadata(i,s,this.childrenMap);if(!e){t.push(i),n.add(i.id);continue}t.push(i),n.add(i.id);let a=s.indexOf(e),o=this.messageMap.get(e);if(o){let i=this.createMessageWithBranches(o,s.length,a);t.push(i),n.add(e),this.buildFlatListRecursive(e,t,n,r)}continue}t.push(i),n.add(i.id),this.buildFlatListRecursive(i.id,t,n,r)}}processAssistantGroup(e,t,n,r){let i=[],a=[];this.messageCollector.collectAssistantChain(e,r,i,a,n);let o=this.collectCouncilMembers(a,r,n),s=this.createAssistantGroupMessage(i[0],i,a,void 0,void 0,o?.members);if(t.push(s),i.forEach(e=>n.add(e.id)),a.forEach(e=>n.add(e.id)),o)for(let e of o.memberIds)this.buildFlatListRecursive(e,t,n,r);this.continueAfterAssistantGroup(i,a,t,n,r)}continueAfterAssistantGroup(e,t,n,r,i){let a=e.at(-1),o=[...a?[a.id]:[],...t.map(e=>e.id)];for(;;){let e=this.findNextUnprocessedChild(o,r);if(!e)return;if(this.shouldDrainParentContinuations(e.parentId,r)){this.buildFlatListRecursive(e.parentId,n,r,i);continue}this.buildFlatListRecursiveForChild(e.parentId,e.child.id,n,r,i)}}collectCouncilMembers(e,t,n){let r=e.find(e=>this.isAgentCouncilMode(e));if(!r)return;let i=r.parentId,a=i?this.councilMemberChildIds(this.childrenMap.get(i)??[]).filter(e=>!n.has(e)):[];if(a.length<=1&&(a=this.councilMemberChildIds(this.childrenMap.get(r.id)??[]).filter(e=>!n.has(e))),a.length<=1)return;let o=this.createAgentCouncilMessageFromChildIds(r,a,t,n);for(let e of this.childrenMap.get(r.id)??[])n.add(e);return{memberIds:a,members:o.members??[]}}buildFlatListRecursiveForChild(e,t,n,r,i){let a=this.childrenMap.get(e)??[];this.childrenMap.set(e,[t]);try{this.buildFlatListRecursive(e,n,r,i)}finally{this.childrenMap.set(e,a)}}findNextUnprocessedChild(e,t){return e.flatMap(e=>(this.childrenMap.get(e)??[]).map(e=>this.messageMap.get(e)).filter(e=>!!e&&!t.has(e.id)).map(t=>({child:t,parentId:e}))).sort((e,t)=>e.child.createdAt-t.child.createdAt)[0]}shouldDrainParentContinuations(e,t){let n=this.messageMap.get(e),r=(this.childrenMap.get(e)??[]).filter(e=>!t.has(e));return!n||r.length<=1?!1:this.isAgentCouncilMode(n)?!0:r.filter(e=>this.messageMap.get(e)?.role===`task`).length>1}isCompareMode(e){return e.metadata?.compare===!0}isAgentCouncilMode(e){return e.metadata?.agentCouncil===!0}councilMemberChildIds(e){return e.filter(e=>this.messageMap.get(e)?.role!==`tool`)}createCompareMessageFromChildIds(e,t,n,r){let i=[],a=[],o;for(let e of t){let t=this.messageMap.get(e);if(t)if(a.push(e),t.metadata?.activeColumn===!0&&(o=e),t.role===`assistant`&&t.tools&&t.tools.length>0){let e=[],a=[],o=new Set;this.messageCollector.collectAssistantChain(t,n,e,a,o);let s=this.createAssistantGroupMessage(e[0],e,a);
5189i.push([s]),e.forEach(e=>r.add(e.id)),a.forEach(e=>r.add(e.id))}else i.push([t]),r.add(e)}let s=a.join(`-`),c=`compare-${e.id}-${s}`,l=t.map(e=>this.messageMap.get(e)).filter(Boolean),u=l.length>0?Math.min(...l.map(e=>e.createdAt)):e.createdAt,d=l.length>0?Math.max(...l.map(e=>e.updatedAt)):e.updatedAt;return{activeColumnId:o,columns:i,content:``,createdAt:u,extra:{parentMessageId:e.id},id:c,role:`compare`,updatedAt:d}}createAgentCouncilMessageFromChildIds(e,t,n,r){let i=[],a=[],o=this.councilMemberChildIds(t);for(let e of t)o.includes(e)||r.add(e);for(let e of o){let t=this.messageMap.get(e);if(t)if(a.push(e),t.role===`assistant`&&t.tools&&t.tools.length>0){let e=[],a=[],o=new Set;this.messageCollector.collectAssistantChain(t,n,e,a,o);let s=this.createAssistantGroupMessage(e[0],e,a);i.push(s),e.forEach(e=>r.add(e.id)),a.forEach(e=>r.add(e.id))}else i.push(t),r.add(e)}let s=a.join(`-`),c=`agentCouncil-${e.id}-${s}`,l=o.map(e=>this.messageMap.get(e)).filter(Boolean),u=l.length>0?Math.min(...l.map(e=>e.createdAt)):e.createdAt,d=l.length>0?Math.max(...l.map(e=>e.updatedAt)):e.updatedAt;return{content:``,createdAt:u,extra:{parentMessageId:e.id},id:c,members:i,role:`agentCouncil`,updatedAt:d}}createCompareMessage(e,t){return{activeColumnId:t.find(e=>e.metadata?.activeColumn===!0)?.id,columns:t.map(e=>[e]),content:``,createdAt:Math.min(...t.map(e=>e.createdAt)),extra:{groupMode:e.mode,parentMessageId:e.parentMessageId},id:e.id,role:`compare`,updatedAt:Math.max(...t.map(e=>e.updatedAt))}}createAssistantGroupMessage(e,t,n,r,i,a){let o=[],s=new Map;n.forEach(e=>{e.tool_call_id&&s.set(e.tool_call_id,e)});for(let e of t){let t=e.tools?.map(e=>{let t=s.get(e.id);if(t){let n={content:t.content||``,id:t.id};return t.error&&(n.error=t.error),t.pluginError&&(n.error=t.pluginError),t.pluginState&&(n.state=t.pluginState),{...e,intervention:t.pluginIntervention,result:n,result_msg_id:t.id}}return e})||[],{usage:n,performance:r}=this.messageTransformer.splitMetadata(e.metadata),i=e.usage||n,a=e.performance||r,c={};if(e.metadata){let t=new Set([`acceptedPredictionTokens`,`cost`,`duration`,`inputAudioTokens`,`inputCacheMissTokens`,`inputCachedTokens`,`inputCitationTokens`,`inputImageTokens`,`inputTextTokens`,`inputVideoTokens`,`inputToolTokens`,`inputWriteCacheTokens`,`latency`,`outputAudioTokens`,`outputImageTokens`,`outputReasoningTokens`,`outputTextTokens`,`performance`,`rejectedPredictionTokens`,`totalInputTokens`,`totalOutputTokens`,`totalTokens`,`tps`,`ttft`,`usage`]);Object.entries(e.metadata).forEach(([e,n])=>{t.has(e)||(c[e]=n)})}let l={content:e.content||``,id:e.id};e.error&&(l.error=e.error),e.fileList&&e.fileList.length>0&&(l.fileList=e.fileList),e.imageList&&e.imageList.length>0&&(l.imageList=e.imageList),a&&(l.performance=a),e.reasoning&&(l.reasoning=e.reasoning),t.length>0&&(l.tools=t),i&&(l.usage=i),Object.keys(c).length>0&&(l.metadata=c),o.push(l)}a&&a.length>1&&o.push({content:``,council:a,id:`council-${e.id}`});let c=this.messageTransformer.aggregateMetadata(o),l={};if(o.forEach(e=>{e.metadata&&Object.assign(l,e.metadata)}),Object.keys(l).length>0&&o.length>0){o[0].metadata||(o[0].metadata={}),Object.assign(o[0].metadata,l);for(let e=1;e<o.length;e++)delete o[e].metadata}let u=d0(e),d=u?`supervisor`:`assistantGroup`,f={...e,children:o,content:``,role:d};return delete f.imageList,delete f.metadata,delete f.reasoning,delete f.tools,c.performance&&(f.performance=c.performance),c.usage&&(f.usage=c.usage),Object.keys(l).length>0&&(f.metadata=l),u&&(f.metadata={...f.metadata,isSupervisor:!0,orchestrationRole:`supervisor`}),r&&r.length>0&&(f.signalCallbacks=r.map(e=>({callbacks:e.callbacks.map(e=>({content:e.content??``,id:e.id,model:e.model??void 0,provider:e.provider??void 0,sequence:e.metadata?.signal?.sequence})),sourceToolCallId:e.sourceToolCallId,sourceToolMessageId:e.sourceToolMessageId,sourceToolName:e.sourceToolName}))),i&&i.length>0&&(f.taskCompletions=i.map(e=>{let t={content:e.content??``,id:e.id};return e.error&&(t.error=e.error),e.fileList&&e.fileList.length>0&&(t.fileList=e.fileList),e.imageList&&e.imageList.length>0&&(t.imageList=e.imageList),e.performance&&(t.performance=e.performance),e.reasoning&&(t.reasoning=e.reasoning),e.usage&&(t.usage=e.usage),t})),f}createMessageWithBranches(e,t,n){return{...e,branch:{activeBranchIndex:n,count:t}}}createSupervisorContentMessage(e){let{usage:t,performance:n}=this.messageTransformer.splitMetadata(e.metadata),r=e.usage||t,i=e.performance||n,a={};if(e.metadata){let t=new Set([`acceptedPredictionTokens`,`cost`,`duration`,`inputAudioTokens`,`inputCacheMissTokens`,`inputCachedTokens`,`inputCitationTokens`,`inputImageTokens`,`inputTextTokens`,`inputVideoTokens`,`inputToolTokens`,`inputWriteCacheTokens`,`latency`,`outputAudioTokens`,`outputImageTokens`,`outputReasoningTokens`,`outputTextTokens`,`performance`,`rejectedPredictionTokens`,`totalInputTokens`,`totalOutputTokens`,`totalTokens`,`tps`,`ttft`,`usage`]);
5189Object.entries(e.metadata).forEach(([e,n])=>{t.has(e)||(a[e]=n)})}let o={content:e.content||``,id:e.id};e.error&&(o.error=e.error),e.fileList&&e.fileList.length>0&&(o.fileList=e.fileList),e.imageList&&e.imageList.length>0&&(o.imageList=e.imageList),i&&(o.performance=i),e.reasoning&&(o.reasoning=e.reasoning),r&&(o.usage=r),Object.keys(a).length>0&&(o.metadata=a);let s={...e,children:[o],content:``,role:`supervisor`};return delete s.imageList,delete s.metadata,delete s.reasoning,delete s.tools,i&&(s.performance=i),r&&(s.usage=r),s.metadata={isSupervisor:!0,orchestrationRole:`supervisor`,...a},s}createTasksMessage(e,t,n){let r=[];for(let e of t){let t=this.messageMap.get(e);t&&(r.push(t),n.add(e))}r.sort((e,t)=>e.createdAt-t.createdAt);let i=r.map(e=>e.id).join(`-`),a=`tasks-${e.id}-${i}`,o=r.length>0?Math.min(...r.map(e=>e.createdAt)):e.createdAt,s=r.length>0?Math.max(...r.map(e=>e.updatedAt)):e.updatedAt;return{content:``,createdAt:o,extra:{parentMessageId:e.id},id:a,role:`tasks`,tasks:r,updatedAt:s}}createGroupTasksMessage(e,t,n){let r=[];for(let e of t){let t=this.messageMap.get(e);t&&(r.push(t),n.add(e))}r.sort((e,t)=>e.createdAt-t.createdAt);let i=r.map(e=>e.id).join(`-`),a=`groupTasks-${e.id}-${i}`,o=r.length>0?Math.min(...r.map(e=>e.createdAt)):e.createdAt,s=r.length>0?Math.max(...r.map(e=>e.updatedAt)):e.updatedAt;return{content:``,createdAt:o,extra:{parentMessageId:e.id},id:a,role:`groupTasks`,tasks:r,updatedAt:s}}}})),f0,p0,m0,bDe,xDe=e((()=>{hDe(),f0=e=>{if(e.role===`assistant`&&!(e.tools&&e.tools.length>0))return e.metadata?.signal},p0=e=>e?.type===`tool-stdout`||e?.type===`tool-callback`,m0=e=>e?.type===`task-completion`,bDe=class{messageMap;childrenMap;branchResolver;constructor(e,t,n=new u0){this.messageMap=e,this.childrenMap=t,this.branchResolver=n}collectGroupMembers(e,t){return t.filter(t=>t.groupId===e)}collectToolMessages(e,t){let n=e.tools||[];if(n.length===0)return[];let r=new Map(t.filter(e=>e.role===`tool`).map(e=>[e.id,e])),i=[],a=new Set;for(let o of n){let n=o.result_msg_id,s=n?r.get(n):void 0;if(s){a.has(s.id)||(i.push(s),a.add(s.id));continue}let c=t.find(t=>t.role===`tool`&&t.parentId===e.id&&t.tool_call_id===o.id);c&&!a.has(c.id)&&(i.push(c),a.add(c.id))}return i}isToolChainHead(e){if(e.role!==`assistant`||e.tools&&e.tools.length>0||(e.parentId?this.messageMap.get(e.parentId):void 0)?.role!==`user`)return!1;let t=e.agentId,n=[...this.messageMap.values()],r=new Set([e.id]),i=e;for(;;){let e=this.findFlatChainContinuation(i,[],n,r,t);if(!e)return!1;if(e.tools&&e.tools.length>0)return!0;r.add(e.id),i=e}}collectAssistantChain(e,t,n,r,i){if(i.has(e.id))return;i.add(e.id),n.push(e);let a=n[0].agentId,o=this.collectToolMessages(e,t);r.push(...o);let s=this.findFlatChainContinuation(e,o,t,i,a);if(!s)return;if(s.tools&&s.tools.length>0){this.collectAssistantChain(s,t,n,r,i);return}let c=s;for(;c&&(!c.tools||c.tools.length===0);)n.push(c),i.add(c.id),c=this.findFlatChainContinuation(c,[],t,i,a);c&&this.collectAssistantChain(c,t,n,r,i)}findFlatChainContinuation(e,t,n,r,i){let a=new Set,o=!1;for(let e of t){let t=e.metadata?.agentCouncil===!0,r=n.filter(t=>t.parentId===e.id).some(e=>e.role===`task`);if(t||r){o=!0;continue}a.add(e.id)}o||a.add(e.id);let s=n.filter(e=>e.parentId!=null&&a.has(e.parentId)).filter(e=>e.role!==`tool`&&!r.has(e.id)).filter(e=>e.role===`assistant`&&e.agentId===i&&!f0(e)).sort((e,t)=>e.createdAt-t.createdAt),c=this.resolveActiveContinuationId(s);return c?s.find(e=>e.id===c):void 0}resolveActiveContinuationId(e){if(e.length===0)return;let t=e[0],n=t.parentId;if(n==null)return t.id;let r=new Set(e.map(e=>e.id)),i=(this.childrenMap.get(n)??[]).filter(e=>r.has(e));if(i.length<=1)return t.id;let a=this.messageMap.get(n);return a?this.branchResolver.getActiveBranchIdFromMetadata(a,i,this.childrenMap):t.id}collectFlatSignalCallbacks(e,t){let n=[];for(let r of e){let e=t.filter(e=>e.parentId===r.id),i=[];for(let t of e)p0(f0(t))&&i.push(t);if(i.length===0)continue;i.sort((e,t)=>(f0(e)?.sequence??1/0)-(f0(t)?.sequence??1/0));let a=f0(i[0]);n.push({callbacks:i,sourceToolCallId:a.sourceToolCallId,sourceToolMessageId:r.id,sourceToolName:a.sourceToolName})}return n}collectFlatTaskCompletions(e,t){let n=[];for(let r of e){let e=t.filter(e=>e.parentId===r.id);for(let t of e)m0(f0(t))&&n.push(t)}return n.sort((e,t)=>
5189e.createdAt-t.createdAt),n}collectAssistantGroupMessages(e,t,n,r){let i=r??e.agentId,a=t.children.filter(e=>this.messageMap.get(e.id)?.role===`tool`).map(e=>e.id),o={id:e.id,type:`message`};a.length>0&&(o.tools=a),n.push(o);let s=this.findChainContinuationNode(t,i);if(s){let e=this.messageMap.get(s.id);this.collectAssistantGroupMessages(e,s,n,i)}}findChainContinuationNode(e,t){let n=[],r=!1;for(let t of e.children){let e=this.messageMap.get(t.id);if(e?.role!==`tool`)continue;let i=e.metadata?.agentCouncil===!0,a=t.children.some(e=>this.messageMap.get(e.id)?.role===`task`);if(i||a){r=!0;continue}n.push(...t.children)}if(!r)for(let t of e.children)this.messageMap.get(t.id)?.role!==`tool`&&n.push(t);let i=n.map(e=>({msg:this.messageMap.get(e.id),node:e})).filter(e=>e.msg?.role===`assistant`&&e.msg.agentId===t&&!f0(e.msg)).sort((e,t)=>e.msg.createdAt-t.msg.createdAt),a=this.resolveActiveContinuationId(i.map(e=>e.msg));return a?i.find(e=>e.node.id===a)?.node:void 0}collectSignalCallbacks(e,t){let n=e.agentId,r=[],i=new Set,a=e=>{if(!i.has(e.id)){i.add(e.id);for(let t of e.children){if(this.messageMap.get(t.id)?.role!==`tool`)continue;let e=[];for(let n of t.children){let t=this.messageMap.get(n.id);t&&p0(f0(t))&&e.push(t)}if(e.length>0){e.sort((e,t)=>(f0(e)?.sequence??1/0)-(f0(t)?.sequence??1/0));let n=f0(e[0]);r.push({callbacks:e.map(e=>({id:e.id,type:`message`})),id:`signalCallbacks-${t.id}`,sourceToolCallId:n.sourceToolCallId,sourceToolMessageId:t.id,sourceToolName:n.sourceToolName,type:`signalCallbacks`})}for(let e of t.children){let t=this.messageMap.get(e.id);if(t?.role===`assistant`&&t.agentId===n&&!f0(t)){a(e);break}}}}};return a(t),r}collectTaskCompletions(e,t){let n=e.agentId,r=[],i=new Set,a=e=>{if(!i.has(e.id)){i.add(e.id);for(let t of e.children)if(this.messageMap.get(t.id)?.role===`tool`){for(let e of t.children){let t=this.messageMap.get(e.id);t&&t.agentId===n&&m0(f0(t))&&r.push({id:t.id,type:`message`})}for(let e of t.children){let t=this.messageMap.get(e.id);if(t?.role===`assistant`&&t.agentId===n&&!f0(t)){a(e);break}}}}};return a(t),r}findNextAfterTools(e,t){let n=this.findLastNodeInAssistantGroup(t,e.agentId);if(!n)return null;let r=this.messageMap.get(n.id);return r?.role===`tool`&&r.metadata?.agentCouncil===!0||r?.role===`tool`&&n.children.filter(e=>this.messageMap.get(e.id)?.role===`task`).length>0?n:n.children.length>0?n.children[0]:null}findLastNodeInAssistantGroup(e,t){let n=this.findChainContinuationNode(e,t);if(n)return this.findLastNodeInAssistantGroup(n,t);let r=e.children.filter(e=>this.messageMap.get(e.id)?.role===`tool`);return r.length===0?e:r.at(-1)??null}}})),SDe,CDe=e((()=>{SDe=class{messageToContentBlock(e){let{usage:t,performance:n}=this.splitMetadata(e.metadata,e.usage);return{content:e.content||``,error:e.error,fileList:e.fileList,id:e.id,imageList:e.imageList,performance:n,reasoning:e.reasoning||void 0,tools:e.tools,usage:t}}splitMetadata(e,t){if(!e&&!t)return{};let n={...e?.usage,...t},r={...e?.performance},i=Object.keys(n).length>0,a=Object.keys(r).length>0;return[`acceptedPredictionTokens`,`cost`,`inputAudioTokens`,`inputCacheMissTokens`,`inputCachedTokens`,`inputCitationTokens`,`inputImageTokens`,`inputTextTokens`,`inputVideoTokens`,`inputToolTokens`,`inputWriteCacheTokens`,`outputAudioTokens`,`outputImageTokens`,`outputReasoningTokens`,`outputTextTokens`,`rejectedPredictionTokens`,`totalInputTokens`,`totalOutputTokens`,`totalTokens`].forEach(t=>{e?.[t]!==void 0&&n[t]===void 0&&(n[t]=e[t],i=!0)}),[`duration`,`latency`,`tps`,`ttft`].forEach(t=>{e?.[t]!==void 0&&r[t]===void 0&&(r[t]=e[t],a=!0)}),{performance:a?r:void 0,usage:i?n:void 0}}aggregateMetadata(e){let t={},n={},r=!1,i=!1,a=0,o=0;return e.forEach(e=>{e.usage&&([`acceptedPredictionTokens`,`inputAudioTokens`,`inputCacheMissTokens`,`inputCachedTokens`,`inputCitationTokens`,`inputImageTokens`,`inputTextTokens`,`inputVideoTokens`,`inputToolTokens`,`inputWriteCacheTokens`,`outputAudioTokens`,`outputImageTokens`,`outputReasoningTokens`,`outputTextTokens`,`rejectedPredictionTokens`,`totalInputTokens`,`totalOutputTokens`,`totalTokens`].forEach(n=>{typeof e.usage[n]==`number`&&(t[n]=(t[n]||0)+e.usage[n],r=!0)}),typeof e.usage.cost==`number`&&(t.cost=(t.cost||0)+e.usage.cost,r=!0)),e.performance&&(e.performance.ttft!==void 0&&n.ttft===void 0&&(n.ttft=e.performance.ttft,i=!0),typeof e.performance.tps==`number`&&(a+=e.performance.tps,o+=1,i=!0),e.performance.duration!==void 0&&(n.duration=(n.duration||0)+e.performance.duration,i=!0),e.performance.latency!==void 0&&(n.latency=(n.latency||0)+e.performance.latency,i=!0))}),o>0&&(n.tps=a/o),{performance:i?n:void 0,usage:r?t:void 0}}}})),wDe,TDe=e((()=>{hDe(),_De(),yDe(),xDe(),CDe(),wDe=class{helperMaps;messageMap;
5189nodeIdCounter=0;branchResolver;messageCollector;messageTransformer;contextTreeBuilder;flatListBuilder;constructor(e){this.helperMaps=e,this.messageMap=e.messageMap,this.branchResolver=new u0,this.messageCollector=new bDe(this.messageMap,e.childrenMap,this.branchResolver),this.messageTransformer=new SDe,this.contextTreeBuilder=new gDe(e.messageMap,e.messageGroupMap,this.branchResolver,this.messageCollector,this.generateNodeId.bind(this)),this.flatListBuilder=new vDe(e.messageMap,e.messageGroupMap,e.childrenMap,this.branchResolver,this.messageCollector,this.messageTransformer)}generateNodeId(e,t){return`${e}-${t}-${this.nodeIdCounter++}`}transformAll(e){return this.contextTreeBuilder.transformAll(e)}flatten(e){return this.flatListBuilder.flatten(e)}}}));function h0(e,t){let n=e.map(e=>e.metadata?.scope===`sub_agent`&&e.metadata?.subAgentId?{...e,agentId:e.metadata.subAgentId}:e),r=dDe(n,t),i=pDe(r),a=new wDe(r),o=a.transformAll(i),s=a.flatten(n),c={},l=new Set([`acceptedPredictionTokens`,`cost`,`duration`,`inputAudioTokens`,`inputCacheMissTokens`,`inputCachedTokens`,`inputCitationTokens`,`inputImageTokens`,`inputTextTokens`,`inputVideoTokens`,`inputToolTokens`,`inputWriteCacheTokens`,`latency`,`outputAudioTokens`,`outputImageTokens`,`outputReasoningTokens`,`outputTextTokens`,`performance`,`rejectedPredictionTokens`,`totalInputTokens`,`totalOutputTokens`,`totalTokens`,`tps`,`ttft`,`usage`]);return r.messageMap.forEach((e,t)=>{let n=e;if(e.role===`assistant`&&e.metadata?.isSupervisor&&(n={...e,role:`supervisor`}),n.role===`assistant`&&n.tools&&n.tools.length>0&&n.metadata){let e={};Object.entries(n.metadata).forEach(([t,n])=>{l.has(t)&&(e[t]=n)}),c[t]={...n,metadata:Object.keys(e).length>0?e:void 0}}else c[t]=n}),{contextTree:o,flatList:s.map(e=>{let t=e;return t.role===`assistant`&&t.metadata?.isSupervisor&&(t={...t,role:`supervisor`}),!t.usage&&t.metadata?.usage&&(t={...t,usage:t.metadata.usage}),t}),messageMap:c}}var EDe=e((()=>{fDe(),mDe(),TDe()})),g0=e((()=>{EDe()})),_0,v0,y0,DDe=e((()=>{_0={isContinuing:!1,isCreating:!1,isGenerating:!1,isInReasoning:!1,isInterrupted:!1,isProcessing:!1,isRegenerating:!1},v0={isInvoking:!1,isStreaming:!1},y0={getMessageOperationState:()=>_0,getToolOperationState:()=>v0,isAIGenerating:!1,isInputLoading:!1,isInputVisiblyLoading:!1,sendMessageError:void 0}})),ODe,kDe=e((()=>{ODe={dbMessages:[],displayMessages:[],messagesInit:!1}})),ADe,jDe=e((()=>{ADe={chatInputOverlayHeight:0,editor:null,inputMessage:``,scheduledSendAt:void 0}})),MDe,NDe=e((()=>{MDe={heteroOverloadRetryAttempts:{},heteroOverloadWaitOpIds:{},messageEditingIds:[],messageLoadingIds:[],pendingArgsUpdates:new Map,selectionAnchorId:void 0,selectedMessageIds:[],selectionMode:!1}})),PDe,FDe=e((()=>{PDe={activeIndex:null,atBottom:!0,isScrolling:!1,virtuaScrollMethods:null,visibleItems:new Map}})),IDe,LDe=e((()=>{DDe(),kDe(),jDe(),NDe(),FDe(),IDe={...ODe,...ADe,...MDe,...PDe,actionsBar:void 0,context:{agentId:``,threadId:null,topicId:null},hooks:{},onMessagesChange:void 0,operationState:y0}})),RDe,zDe,b0,x0,S0,BDe,C0,VDe,w0,HDe,T0,E0,D0,O0,UDe,k0=e((()=>{oa(),lr(),RDe=3e4,zDe=500,b0=new Map,x0=e=>ore.list(e),S0=(e,t=xr())=>`${t}:${JSON.stringify(na(e))}`,BDe=e=>{b0.delete(e.identity),b0.set(e.identity,e)},C0=e=>e.activeRequestGenerations.size,VDe=(e,t)=>[...e.activeRequestGenerations].some(e=>e<t),w0=()=>{for(;b0.size>zDe;){let e=[...b0.entries()].find(([,e])=>C0(e)===0);if(!e)return;b0.delete(e[0])}},HDe=(e,t=xr())=>{let n=na(e),r=S0(n,t),i=b0.get(r);if(i)return i;let a={activeRequestGenerations:new Set,cacheScope:t,context:n,generation:0,identity:r};return b0.set(r,a),w0(),a},T0=(e,t=Date.now())=>{let n=S0(e),r=b0.get(n);if(r?.verifiedAt===void 0)return!1;let i=t-r.verifiedAt;return i>=0&&i<3e4?!0:(r.verifiedAt=void 0,C0(r)===0&&b0.delete(n),!1)},E0=e=>({dedupingInterval:RDe,revalidateIfStale:!T0(e)}),D0=(e,t,n=!1)=>{let r=e.currentRequest;if(r?.generation===e.generation&&(!r.settled||n))return r.promise;e.verifiedAt=void 0;let i=e.generation;e.activeRequestGenerations.add(i);
5189let a=Promise.resolve().then(async()=>{let n;try{n=await t(e.context)}catch(n){if(e.generation!==i)return D0(e,t,!0);throw n}return e.generation===i?(e.verifiedAt=Date.now(),BDe(e),w0(),n):D0(e,t,!0)}).finally(()=>{e.activeRequestGenerations.delete(i),e.currentRequest?.promise===a&&(e.currentRequest.settled=!0),e.currentRequest?.settled&&!VDe(e,e.currentRequest.generation)&&(e.currentRequest=void 0),C0(e)===0&&e.verifiedAt===void 0&&b0.delete(e.identity)});return e.currentRequest={generation:i,promise:a,settled:!1},a},O0=(e,t)=>D0(HDe(e),t),UDe=(e,t=xr())=>{for(let n of b0.values())n.cacheScope!==t||!e(n.context)||(n.generation+=1,n.verifiedAt=void 0)}})),WDe,GDe,KDe=e((()=>{WDe=t(le()),it(),Te(),GDe=(e,t)=>{switch(t.type){case`updateMessage`:{let{id:n,value:r}=t,i=e.findIndex(e=>e.id===n);return i<0?e:tt(e,e=>{e[i]=Ce(e[i],{...r,updatedAt:Date.now()})})}case`updateMessageExtra`:{let{id:n,key:r,value:i}=t,a=e.findIndex(e=>e.id===n);return a<0?e:tt(e,e=>{let t=e[a];t.extra?t.extra[r]=i:t.extra={[r]:i},t.updatedAt=Date.now()})}case`updateMessageMetadata`:{let{id:n,value:r}=t,i=e.findIndex(e=>e.id===n);return i<0?e:tt(e,e=>{let t=e[i];t.metadata=Ce(t.metadata,r),t.updatedAt=Date.now()})}case`updatePluginState`:{let{id:n,key:r,value:i}=t,a=e.findIndex(e=>e.id===n);if(a<0)return e;let o=e[a],s=o.pluginState?Ce(o.pluginState,{[r]:i}):{[r]:i};return(0,WDe.default)(o.pluginState,s)?e:tt(e,e=>{e[a].pluginState=s,e[a].updatedAt=Date.now()})}case`updateMessagePlugin`:{let{id:n,value:r}=t,i=e.findIndex(e=>e.id===n);return i<0||e[i].role!==`tool`?e:tt(e,e=>{e[i].plugin=Ce(e[i].plugin,r),e[i].updatedAt=Date.now()})}case`addMessageTool`:{let{id:n,value:r}=t,i=e.findIndex(e=>e.id===n);if(i<0)return e;let a=e[i];return a.role!==`assistant`||(a.tools||[]).some(e=>e.id===r.id)?e:tt(e,e=>{e[i].tools?e[i].tools.push(r):e[i].tools=[r],e[i].updatedAt=Date.now()})}case`deleteMessageTool`:{let{id:n,tool_call_id:r}=t,i=e.findIndex(e=>e.id===n);if(i<0)return e;let a=e[i];return a.role!==`assistant`||!a.tools?e:tt(e,e=>{e[i].tools=e[i].tools.filter(e=>e.id!==r),e[i].updatedAt=Date.now()})}case`updateMessageTools`:{let{id:n,value:r,tool_call_id:i}=t,a=e.findIndex(e=>e.id===n);if(a<0)return e;let o=e[a];if(o.role!==`assistant`||!o.tools)return e;let s=o.tools.findIndex(e=>e.id===i);return s<0?e:tt(e,e=>{e[a].tools[s]=Ce(e[a].tools[s],r),e[a].updatedAt=Date.now()})}case`createMessage`:{let{value:n,id:r}=t,i=Date.now();return tt(e,e=>{e.push({...n,createdAt:i,id:r,updatedAt:i})})}case`updateMessages`:return t.value;case`deleteMessage`:{let{id:n}=t,r=e.findIndex(e=>e.id===n);return r<0?e:tt(e,e=>{e.splice(r,1)})}case`deleteMessages`:{let{ids:n}=t,r=new Set(n),i=new Map;for(let t of e)r.has(t.id)&&i.set(t.id,t.parentId);let a=new Map,o=e=>{if(a.has(e))return a.get(e);let t=i.get(e);if(t==null||!r.has(t))return a.set(e,t),t;let n=o(t);return a.set(e,n),n};for(let e of r)o(e);return e.filter(e=>!r.has(e.id)).map(e=>{if(e.parentId&&r.has(e.parentId)){let t=a.get(e.parentId);return{...e,parentId:t??void 0}}return e})}default:throw Error(`Unimplemented dispatch type, check reducer`)}}})),A0,qDe,JDe=e((()=>{A0=e=>{let t=[];for(let n of e)if(n.role===`tool`&&n.pluginIntervention?.status===`pending`&&n.plugin&&!n.id.startsWith(`tmp_`)&&t.push({apiName:n.plugin.apiName,identifier:n.plugin.identifier,intervention:n.pluginIntervention,requestArgs:n.plugin.arguments||``,toolCallId:n.tool_call_id||n.id,toolMessageId:n.id}),n.children)for(let e of n.children)e.tools&&qDe(e.tools,t,n.id);return t},qDe=(e,t,n)=>{for(let r of e)r.intervention?.status===`pending`&&r.result_msg_id&&!r.result_msg_id.startsWith(`tmp_`)&&t.push({apiName:r.apiName,assistantGroupId:n,identifier:r.identifier,intervention:r.intervention,requestArgs:r.arguments||``,toolCallId:r.id,toolMessageId:r.result_msg_id})}})),j0,M0,YDe,N0,XDe,ZDe,QDe,$De,P0,eOe,tOe=e((()=>{j0=e=>typeof e?.work?.rootOperationId==`string`?e.work.rootOperationId:void 0,M0=e=>{if(!e)return 0;let t=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isNaN(t)?0:t},YDe=e=>{let t=new Map;for(let n of e){let e=n.works;if(!e||e.length===0)continue;let r=j0(n.metadata)??e[0].event.rootOperationId;r&&t.set(r,e)}return t},N0=new WeakMap,XDe=e=>{let t=N0.get(e);return t||(t=YDe(e),N0.set(e,t)),t},ZDe=(e,t)=>t?XDe(e).get(t)??[]:[],QDe=(e,t)=>{let n=new Map;for(let r of e)if(!(t?r.threadId!==t:r.threadId))for(let e of r.works??[]){let t=n.get(e.id);(!t||M0(e.event.createdAt)>M0(t.event.createdAt))&&n.set(e.id,e)}return Array.from(n.values()).sort((e,t)=>
5189M0(t.event.createdAt)-M0(e.event.createdAt))},$De=`__main__`,P0=new WeakMap,eOe=(e,t)=>{let n=t??$De,r=P0.get(e);r||(r=new Map,P0.set(e,r));let i=r.get(n);return i||(i=QDe(e,t),r.set(n,i)),i}})),nOe,rOe,iOe,aOe,oOe,F0,sOe,cOe,lOe,uOe,dOe,fOe,pOe,mOe,hOe,gOe,_Oe,I0,L0,vOe,yOe,bOe,xOe,R0,z0=e((()=>{bc(),Oi(),JDe(),tOe(),nOe=e=>e.displayMessages,rOe=e=>e.displayMessages.map(e=>e.id),iOe=e=>e.dbMessages,aOe=e=>e.messagesInit,oOe=e=>e.skipFetch,F0=e=>t=>{let n=t.displayMessages.find(t=>t.id===e);if(n)return n;for(let n of t.displayMessages)if(n.role===`agentCouncil`&&n.members){let t=n.members.find(t=>t.id===e);if(t)return t}},sOe=e=>t=>t.dbMessages.find(t=>t.id===e),cOe=e=>t=>t.dbMessages.find(t=>t.tool_call_id===e),lOe=e=>{if(e)return e.tools&&e.tools.length>0?e.tools.at(-1)?.result_msg_id:e.id},uOe=e=>{if(e)return e.children&&e.children.length>0?lOe(e.children.at(-1)):e.tools&&e.tools.length>0?e.tools.at(-1)?.result_msg_id:e.id},dOe=e=>t=>uOe(F0(e)(t)),fOe=e=>t=>{let n=t.displayMessages.find(t=>t.id===e);if(!n||n.role!==`assistantGroup`||!n.children||n.children.length===0)return;let r=n.children.at(-1);if(r&&(!r.tools||r.tools.length===0))return r.content?r:void 0},pOe=()=>{let e=Z9.getState();return vi.currentActiveTopicSummary(e)},mOe=e=>A0(e.displayMessages),hOe=e=>t=>ZDe(t.dbMessages,e),gOe=e=>e.displayMessages.at(-2)?.role===`user`,_Oe=e=>({content:e.content,error:e.error,fileList:e.fileList,id:e.id,imageList:e.imageList,metadata:e.metadata??void 0,performance:e.performance,reasoning:e.reasoning??void 0,tasks:e.tasks,tools:e.tools,usage:e.usage}),I0=(e,t)=>{for(let n of t){if(n.role===`assistant`&&n.id===e)return _Oe(n);if(n.children){let t=n.children.find(t=>t.id===e);if(t)return t}if(n.taskCompletions){let t=n.taskCompletions.find(t=>t.id===e);if(t)return t}if(n.compressedMessages){let t=I0(e,n.compressedMessages);if(t)return t}if(n.role===`agentCouncil`&&n.members){let t=I0(e,n.members);if(t)return t}}},L0=e=>t=>I0(e,t.displayMessages)?.tools,vOe=(e,t)=>n=>L0(e)(n)?.find(e=>e.id===t),yOe=e=>t=>I0(e,t.displayMessages)?.content,bOe=e=>t=>{let n=I0(e,t.displayMessages)?.tools;return!!n&&n.length>0},xOe=e=>t=>{let n=0;for(let r of t.displayMessages)if(r.role===`verify`&&(n+=1,r.id===e))return n;return n||1},R0={currentTopicSummary:pOe,dbMessages:iOe,getVerifyOrdinal:xOe,displayMessageIds:rOe,displayMessages:nOe,findLastMessageId:dOe,getDbMessageById:sOe,getDbMessageByToolCallId:cOe,getBlockContent:yOe,getBlockHasTools:bOe,getDisplayMessageById:F0,getGroupLatestMessageWithoutTools:fOe,getToolInBlock:vOe,getToolsInBlock:L0,isSecondLastMessageFromUser:gOe,messagesInit:aOe,pendingInterventions:mOe,skipFetch:oOe,workSummariesByRootOperationId:hOe}})),B0,SOe=e((()=>{pre(),B0=(e,t)=>fre(e,t)})),COe,V0,wOe,TOe,EOe=e((()=>{g0(),COe=t(F()),Qi(),Na(),k0(),bc(),Oi(),wi(),KDe(),z0(),SOe(),V0=(0,COe.default)(`lobe-render:features:Conversation`),wOe=(e,t)=>{if(t.length===0||e.length===0)return e;let n=new Map(t.map(e=>[e.id,e])),r=!1,i=e.map(e=>{let t=n.get(e.id);return!t||t.updatedAt<=e.updatedAt?e:(r=!0,t)});return r?i:e},TOe=(e,t)=>({internal_dispatchMessage:n=>{let r=li(t().context);if(V0(`[dispatchMessage] start | contextKey=%s | type=%s | id=%s`,r,n.type,`id`in n?n.id:`ids`in n?n.ids.join(`,`):`N/A`),n.type===`updateMessageGroupMetadata`){let r=t().displayMessages,i=r.findIndex(e=>e.id===n.id);if(i<0)return;let a=[...r];a[i]={...a[i],metadata:{...a[i].metadata,...n.value}},e({displayMessages:B0(r,a)},!1,{payload:n,type:`dispatchMessage/${n.type}`});return}let i=t().dbMessages,a=GDe(i,n);if(a===i){V0(`[dispatchMessage] no change | contextKey=%s`,r);return}let{flatList:o}=h0(a),s=B0(t().displayMessages,o);V0(`[dispatchMessage] updated | contextKey=%s | prevCount=%d | newCount=%d | displayCount=%d`,r,i.length,a.length,s.length),e({dbMessages:a,displayMessages:s},!1,{payload:n,type:`dispatchMessage/${n.type}`}),t().onMessagesChange?.(a,t().context)},replaceMessages:n=>{let r=li(t().context),i=t().dbMessages,{flatList:a}=h0(n),o=B0(t().displayMessages,a);V0(`[replaceMessages] | contextKey=%s | prevCount=%d | newCount=%d | displayCount=%d | messageIds=%o`,r,i.length,n.length,o.length,n.slice(0,5).map(e=>e.id)),e({dbMessages:n,displayMessages:o},!1,`replaceMessages`),t().onMessagesChange?.(n,t().context)},switchMessageBranch:async(e,n)=>{let r=t(),i=R0.getDbMessageById(e)(r);!i||!i.parentId||await r.updateMessageMetadata(i.parentId,{activeBranchIndex:n})},useFetchMessages:(n,r)=>{let{skipFetch:i,revalidateOnFocus:a}=r??{},o=!i&&!!n.agentId&&!!n.topicId,s=li(n);return V0(`[useFetchMessages] hook | contextKey=%s | shouldFetch=%s | skipFetch=%s | agentId=%s | topicId=%s`,s,o,i,n.agentId,n.topicId),$i(o?x0(n):null,()=>O0(n,Ma.getMessages),{...E0(n),...a!==void 0&&{revalidateOnFocus:a},onData:r=>{if(!r||!n.topicId||pi.isAgentRuntimeRunningByContext(n)(Q9()))return;let i=t().dbMessages,a=wOe(r,i),o=li(t().context),{flatList:c}=h0(a),l=B0(t().displayMessages,c);V0(`[useFetchMessages] onData | requestContextKey=%s | storeContextKey=%s | prevCount=%d | fetchedCount=%d | displayCount=%d | messageIds=%o`,s,o,i.length,a.length,l.length,a.slice(0,5).map(e=>e.id)),e({dbMessages:a,displayMessages:l,messagesInit:!0}),t().onMessagesChange?.(a,n)}})}})})),DOe,H0,OOe,kOe=e((()=>{xre(),DOe=new Set([Ea.AuthRequired,Ea.CliNotFound,Ea.Overloaded,Ea.RateLimit]),H0=e=>{if(!e||typeof e!=`object`)return!1;let{agentType:t,code:n}=e;return(t===`amp`||t===`claude-code`||t===`codex`||t===`opencode`)&&typeof n==`string`&&DOe.has(n)},OOe=e=>{if(e?.role!==`assistantGroup`)return;let t=e.children?.at(-1);if(!(!t||t.id===e.id))return t.error&&H0(t.error.body)?t.id:void 0}})),AOe,jOe,MOe=e((()=>{AOe=()=>({forceNewTopic:!0}),jOe=()=>({triggerCompression:!0})}));function NOe(e,t){if(e&&e.type!==`action-tag`&&(e.type===`text`&&typeof e.text==`string`&&t.push(e.text),Array.isArray(e.children)))for(let n of e.children)NOe(n,t)}function U0(e,t){if(e&&(e.type===`mention`&&e.metadata&&t(e.label??``,e.metadata),Array.isArray(e.children)))for(let n of e.children)U0(n,t)}function POe(e,t){if(e&&(FOe(e)&&t(e),Array.isArray(e.children)))for(let n of e.children)POe(n,t)}function FOe(e){return!e?.type||Array.isArray(e.children)?!1:e.type===`text`?typeof e.text==`string`&&e.text.trim().length>0:e.type!==`linebreak`}function IOe(e,t){if(e&&(e.type===`action-tag`&&t.push({category:e.actionCategory,label:e.actionLabel,type:e.actionType}),Array.isArray(e.children)))for(let n of e.children)IOe(n,t)}var W0,G0,LOe,K0,q0,J0,ROe,zOe,BOe,VOe,HOe=e((()=>{W0=(e,t,n)=>{!n.path||t.has(n.path)||(t.add(n.path),e.push(n))},G0=e=>{if(!e)return[];let t=[];return IOe(e.root,t),t},LOe=e=>G0(e),K0=e=>{let t=G0(e).filter(e=>e.category===`skill`);if(t.length===0)return[];let n=new Set;return t.reduce((e,t)=>
5189{let r=String(t.type);return!r||n.has(r)?e:(n.add(r),e.push({identifier:r,name:t.label||r}),e)},[])},q0=e=>{let t=G0(e).filter(e=>e.category===`tool`);if(t.length===0)return[];let n=new Set;return t.reduce((e,t)=>{let r=String(t.type);return!r||n.has(r)?e:(n.add(r),e.push({identifier:r,name:t.label||r}),e)},[])},J0=e=>{if(!e)return[];let t=[],n=new Set;return U0(e.root,(e,r)=>{if(r?.type!==`agent`)return;let i=r?.id;!i||n.has(i)||(n.add(i),t.push({id:i,name:e||i}))}),t},ROe=e=>{if(!e)return[];let t=[],n=new Set;return U0(e.root,(e,r)=>{if(r?.type!==`localFile`)return;let i=r.path;i&&W0(t,n,{isDirectory:r.isDirectory===!0,name:r.name||e||i.split(`/`).pop()||i,path:i})}),t},zOe=e=>{let t=[],n=new Set;for(let r of e)W0(t,n,r);return t},BOe=e=>{if(!e)return;let t=[],n;if(POe(e.root,e=>{n??=e,e.type===`mention`&&e.metadata&&t.push({label:e.label??``,metadata:e.metadata,node:e})}),t.length!==1)return;let[r]=t;if(n!==r.node||r.metadata.type!==`agent`)return;let i=typeof r.metadata.id==`string`?r.metadata.id:void 0;if(i)return{agent:{id:i,name:r.label||i}}},VOe=e=>{if(!e)return!1;let t=[];return NOe(e.root,t),t.join(``).trim().length>0}})),UOe,WOe=e((()=>{UOe=(e,t,n)=>{let r={children:[{type:`refer-topic`,topicId:t,topicTitle:n,version:1}],direction:`ltr`,format:``,indent:0,type:`paragraph`,version:1};if(!e?.root)return{root:{children:[r],direction:`ltr`,format:``,indent:0,type:`root`,version:1}};let i=structuredClone(e),a=i.root.children||[];return i.root.children=[r,...a],i}})),GOe,KOe,qOe=e((()=>{MOe(),HOe(),WOe(),GOe={compact:jOe,newTopic:AOe},KOe=e=>{let t=LOe(e.editorData).filter(e=>e.category===`command`);if(t.length===0)return{};let n={params:e},r={};for(let e of t){let t=GOe[e.type];if(t){let e=t(n);e&&(r={...r,...e})}}return r}})),Y0,X0,JOe,YOe,XOe=e((()=>{Y0=e=>e??``,X0=(e,t)=>{let n=Y0(t);return e?.heteroSessionIdByWorkingDirectory?.[n]},JOe=(e,t,n)=>({...e?.heteroSessionIdByWorkingDirectory,[Y0(t)]:n}),YOe=(e,t)=>{let n={...e?.heteroSessionIdByWorkingDirectory};return delete n[Y0(t)],n}})),Z0,ZOe=e((()=>{XOe(),Z0=(e,t)=>{let n=e?.heteroSessionId,r=e?.workingDirectory,i=t??``,a=X0(e,i);return a?{cwdChanged:!1,resumeSessionId:a}:n?r===void 0?{cwdChanged:!0,reason:`missing_bound_cwd`,resumeSessionId:void 0}:r===i?{cwdChanged:!1,resumeSessionId:n}:{cwdChanged:!0,reason:`cwd_changed`,resumeSessionId:void 0}:{cwdChanged:!1,resumeSessionId:void 0}}})),Q0,$0,QOe,e2,$Oe=e((()=>{Ii(),Q0=(...e)=>{let t=e.filter(Boolean);if(t.length===0)return;let n=t[0];return t.reduce((e,t)=>({...e,...t,initialContext:{...e.initialContext,...t.initialContext},payload:e.payload&&t.payload&&typeof e.payload==`object`&&typeof t.payload==`object`?{...e.payload,...t.payload}:t.payload??e.payload}),{phase:n.phase})},$0=async(e,t)=>{if(t)try{let n=await zi.readDocument({agentId:e,format:`both`,id:t});if(!n)return;let r=n,i=r.content??``,a=r.litexml??``;return{markdown:i,metadata:{charCount:r.contentCharCount??i.length,lineCount:i.length>0?i.split(`
5190`).length:0,title:r.title||`Untitled`},xml:a}}catch(e){console.error(`[activeTopicDocumentContext] Failed to read topic document snapshot:`,e)}},QOe=async e=>{if(e.scope!==`page`&&!(!e.agentId||!e.documentId)){if(e.agentDocumentId){let t=await $0(e.agentId,e.agentDocumentId);return{agentDocumentId:e.agentDocumentId,documentId:e.documentId,snapshot:t,...t?.metadata.title?{title:t.metadata.title}:{}}}if(e.topicId)try{let t=(await zi.listDocuments({agentId:e.agentId,scope:`currentTopic`,topicId:e.topicId})).find(t=>t.documentId===e.documentId);return{agentDocumentId:t?.id,documentId:e.documentId,snapshot:await $0(e.agentId,t?.id),title:t?.title}}catch(t){return console.error(`[activeTopicDocumentContext] Failed to resolve topic document context:`,t),{documentId:e.documentId}}}},e2=async e=>{let t=await QOe(e);if(t)return{initialContext:{activeTopicDocument:t},phase:`init`}}})),eke,tke,nke=e((()=>{eke=[2,5,10,20,30],tke=.2})),rke,t2,n2,r2,i2,ike,ake=e((()=>{ic(),Wt(),Ne(),f(),Qr(),Vre(),kOe(),vr(),Ur(),hr(),Na(),Gr(),qr(),bc(),Oi(),ys(),qOe(),ZOe(),Ai(),si(),$Oe(),wi(),Vr(),Er(),nke(),Pe(),rke=e=>{let t=e??void 0,n=K0(t),r=q0(t),i=J0(t),a=i.length>0&&!r.some(e=>e.identifier===`lobe-agent-management`)?[...r,{identifier:Zs,name:`Agent Management`}]:r;if(a.length>0||n.length>0||i.length>0)return{initialContext:{...n.length>0?{selectedSkills:n}:void 0,...a.length>0?{selectedTools:a}:void 0,...i.length>0?{mentionedAgents:i}:void 0},phase:`init`}},t2=(e,t,n)=>{e.completeOperation(t),n?.()},n2=e=>{let t=Xr(),n=Rr.getAgentConfigById(e)(t)?.agencyConfig,r=Yr.isWorkspaceAgentById(e)(t),i=r?_r().workspaceUserPreference.agentDeviceOverrides?.[e]:void 0;return{agencyConfig:Qe(n,i),workspaceScoped:Lr(r,i)}},r2=(e,t,n)=>{let r=t.topicId?vi.getTopicById(t.topicId)(e):void 0,i=ur().gatewayDeviceInfo?.deviceId,a=Xr(),o=pr.getContext(),{agencyConfig:s,workspaceScoped:c}=n2(n),l=Uee({agencyConfig:s,currentDeviceId:i,fallback:o?.desktopPath??o?.homePath,legacyAgentWorkingDirectory:a.localAgentWorkingDirectoryMap[n],workspaceScoped:c}),u=r?.metadata?.workingDirectory||l,{cwdChanged:d,resumeSessionId:f}=Z0(r?.metadata,u);return{cwdChanged:d,resumeSessionId:f,workingDirectory:u}},i2=async(e,t)=>{let{context:n,heterogeneousProvider:r,imageList:i,parentMessageId:a,parentOperationId:s,prompt:c}=t,l=n.agentId;if(!l)throw Error(`agentId is required for heterogeneous agent`);let{cwdChanged:u,resumeSessionId:d,workingDirectory:f}=r2(e,n,l);u&&zr.info(o(`heteroAgent.resumeReset.cwdChanged`,{ns:`chat`}));let p=await Ma.createMessage({agentId:l,content:`...`,parentId:a,provider:r.type,role:`assistant`,threadId:n.threadId??void 0,topicId:n.topicId??void 0});await e.refreshMessages(),n.topicId&&e.internal_updateTopicLoading(n.topicId,!0);let{operationId:m}=e.startOperation({context:n,label:`Heterogeneous Agent Execution`,metadata:{heterogeneousType:r.type},parentOperationId:s,type:`execHeterogeneousAgent`});e.associateMessageWithOperation(p.id,m);try{let{executeHeterogeneousAgent:e}=await Ge(async()=>{let{executeHeterogeneousAgent:e}=await import(`./heterogeneousAgentExecutor-BNR49jHj.js`);return{executeHeterogeneousAgent:e}},__vite__mapDeps([8,1,9,3,10,11,12,13,14,15,16,17,18,7,19,20,21,22,5,23,2,24,25,26,27,28,29,30,0,4,6])
5190);await e(()=>Z9.getState(),{assistantMessageId:p.id,context:n,heterogeneousProvider:r,imageList:i?.length?i:void 0,message:c,operationId:m,resumeSessionId:d,workingDirectory:f})}finally{n.topicId&&Z9.getState().internal_updateTopicLoading(n.topicId,!1)}return p.id},ike=(e,t)=>({cancelHeteroContinuation:async()=>{let e=t().context.topicId;if(!e)return;let n=Z9.getState();await n.updateTopicStatus({status:`failed`,topicId:e}),await n.updateTopicMetadata(e,{scheduledRun:null})},cancelScheduledRun:async()=>{let{context:e,dbMessages:n,editor:r}=t(),i=e.topicId;if(!i)return;let a=Z9.getState(),o=vi.getTopicById(i)(a)?.metadata?.scheduledRun,s=o?.kind===`delayed_start`?o.userMessageId:void 0,c=s?n.find(e=>e.id===s)?.content:void 0;await a.updateTopicStatus({status:`active`,topicId:i}),await a.updateTopicMetadata(i,{scheduledRun:null});let l=n.length===1&&n[0]?.id===s;c&&r&&(r.setDocument(`markdown`,c),l?Ure(li({...e,topicId:null}),r.getJSONState()):r.focus()),l?await a.removeTopic(i):s&&await t().deleteMessage(s)},cancelOperation:(e,n)=>{let{hooks:r}=t();Z9.getState().cancelOperation(e,n||`User cancelled`),r.onOperationCancelled&&r.onOperationCancelled(e)},clearOperations:()=>{},clearTTS:async e=>{await Z9.getState().clearTTS(e)},clearTranslate:async e=>{await Z9.getState().clearTranslate(e)},continueGeneration:async e=>{let{displayMessages:n}=t(),r=n.find(t=>t.id===e);if(!r)return;let i;if(r.role===`assistantGroup`){if(r.children&&r.children.length>0){let e=r.children.at(-1);e&&(i=e.id)}i&&await t().continueGenerationMessage(e,i)}},continueGenerationMessage:async(e,n)=>{let{context:r,displayMessages:i,hooks:a}=t(),o=Z9.getState(),s=i.find(t=>t.id===e);if(!s||a.onBeforeContinue&&await a.onBeforeContinue(e)===!1)return;let{agencyConfig:c,workspaceScoped:l}=n2(r.agentId),u=vs({boundDeviceId:c?.boundDeviceId,executionTarget:c?.executionTarget,heterogeneousProvider:c?.heterogeneousProvider,isGatewayMode:o.isGatewayModeEnabled(r.agentId),isWorkspaceAgent:l});if(u===`hetero`)return;let{operationId:d}=o.startOperation({context:{...r,messageId:e},type:`continue`});try{if(u===`gateway`){await o.executeGatewayAgent({context:r,message:``,onComplete:()=>t2(o,d,()=>a.onContinueComplete?.(e)),parentMessageId:n});return}await o.executeClientAgent({context:r,messages:i,parentMessageId:n,parentMessageType:s.role,parentOperationId:d}),t2(o,d,()=>a.onContinueComplete?.(e))}catch(e){throw o.failOperation(d,{message:e instanceof Error?e.message:String(e),type:`ContinueError`}),e}},continueHeteroAfterError:async e=>{let{context:n,dbMessages:r,displayMessages:i,hooks:a}=t(),o=Z9.getState(),s=i.find(t=>t.id===e)?.children?.at(-1);if(!s||!H0(s.error?.body))return;let{agencyConfig:c,workspaceScoped:l}=n2(n.agentId),u=c?.heterogeneousProvider,d=vs({boundDeviceId:c?.boundDeviceId,executionTarget:c?.executionTarget,heterogeneousProvider:u,isGatewayMode:o.isGatewayModeEnabled(n.agentId),isWorkspaceAgent:l}),f=n.agentId,p=f?r2(o,n,f).resumeSessionId:void 0,m=s.id!==e;if(d!==`hetero`||!u||!m||!p){await t().delAndRegenerateMessage(e);return}let h=!!s.tools?.length||!!s.content&&s.content!==`...`,g=h?s.id:r.find(e=>e.id===s.id)?.parentId;if(!g){await t().delAndRegenerateMessage(e);return}let{operationId:_}=o.startOperation({context:{...n,messageId:e},type:`regenerate`});try{h?await t().updateMessageError(s.id,null):await t().deleteAssistantMessage(s.id),await i2(o,{context:n,heterogeneousProvider:u,parentMessageId:g,parentOperationId:_,prompt:ln}),t2(o,_,()=>a.onRegenerateComplete?.(e))}catch(e){throw o.failOperation(_,{message:e instanceof Error?e.message:String(e),type:`RegenerateError`}),e}},scheduleHeteroContinuation:async({failedAssistantMessageId:e,rateLimit:n})=>{let{context:r,dbMessages:i}=t(),a=r.topicId;if(!a)return;let o=new Map(i.map(e=>[e.id,e])),s=o.get(e);for(;s?.parentId&&s.role!==`user`;)s=o.get(s.parentId);let c=s?.role===`user`?s.id:void 0;if(!c)return;let l=Z9.getState(),u=vi.getTopicById(a)(l),d=new Date,f=d.toISOString(),p=n?.resetsAt?new Date(n.resetsAt*1e3).toISOString():d.toISOString();await l.updateTopicMetadata(a,{scheduledRun:{createdAt:f,failedAssistantMessageId:e,kind:`resume_after_rate_limit`,rateLimit:n,resume:{sessionId:u?.metadata?.heteroSessionId,workingDirectory:u?.metadata?.workingDirectory},runAt:p,source:`heterogeneous_agent`,updatedAt:f,userMessageId:c}}),await l.updateTopicStatus({status:`scheduled`,topicId:a})},delAndRegenerateMessage:async e=>{let{context:n,displayMessages:r}=t(),i=Z9.getState(),a=r.find(t=>
5190t.id===e);if(!a)return;let o=a.parentId;if(!o)return;let{operationId:s}=i.startOperation({context:{...n,messageId:e},type:`regenerate`});try{await i.deleteMessage(e,{operationId:s}),await t().regenerateUserMessage(o),i.completeOperation(s)}catch(e){throw i.failOperation(s,{message:e instanceof Error?e.message:String(e),type:`RegenerateError`}),e}},delAndResendThreadMessage:async e=>{let{context:n}=t(),r=Z9.getState(),{operationId:i}=r.startOperation({context:{...n,messageId:e},type:`regenerate`});try{await t().resendThreadMessage(e);let n=pi.getOperationById(i)(Z9.getState());if(n&&n.status!==`running`)return;await r.deleteMessage(e,{operationId:i}),r.completeOperation(i)}catch(e){throw r.failOperation(i,{message:e instanceof Error?e.message:String(e),type:`RegenerateError`}),e}},openThreadCreator:e=>{Z9.getState().openThreadCreator(e)},reInvokeToolMessage:async e=>{await Z9.getState().reInvokeToolMessage(e)},internal_beginHeteroOverloadWait:n=>{let r=Z9.getState(),i=t().heteroOverloadWaitOpIds[n];if(i&&r.operations[i]?.status===`running`)return;let{context:a}=t(),{operationId:o}=r.startOperation({context:{agentId:a.agentId,messageId:n,threadId:a.threadId??void 0,topicId:a.topicId??void 0},label:`Auto-retry pending`,type:`autoRetryPending`});e({heteroOverloadWaitOpIds:{...t().heteroOverloadWaitOpIds,[n]:o}},!1,`internal_beginHeteroOverloadWait`)},internal_endHeteroOverloadWait:n=>{let r=t().heteroOverloadWaitOpIds[n];if(!r)return;let i=Z9.getState();i.operations[r]?.status===`running`&&i.completeOperation(r);let a={...t().heteroOverloadWaitOpIds};delete a[n],e({heteroOverloadWaitOpIds:a},!1,`internal_endHeteroOverloadWait`)},isHeteroOverloadWaitAborted:e=>{let n=t().heteroOverloadWaitOpIds[e];if(!n)return!0;let r=Z9.getState().operations[n];return!r||r.status!==`running`},markHeteroOverloadRetryExhausted:n=>{e({heteroOverloadRetryAttempts:{...t().heteroOverloadRetryAttempts,[n]:5}},!1,`markHeteroOverloadRetryExhausted`)},recordHeteroOverloadRetry:n=>{let r=t().heteroOverloadRetryAttempts;e({heteroOverloadRetryAttempts:{...r,[n]:(r[n]??0)+1}},!1,`recordHeteroOverloadRetry`)},resetHeteroOverloadRetry:n=>{let r=t().heteroOverloadRetryAttempts;if(!(n in r))return;let i={...r};delete i[n],e({heteroOverloadRetryAttempts:i},!1,`resetHeteroOverloadRetry`)},regenerateAssistantMessage:async e=>{let{displayMessages:n}=t(),r=n[n.findIndex(t=>t.id===e)];if(!r)return;let i=r.parentId;i&&await t().regenerateUserMessage(i)},regenerateUserMessage:async e=>{let{context:n,displayMessages:r,hooks:i}=t(),a=Z9.getState();if(pi.isMessageProcessing(e)(a))return;let o=r.findIndex(t=>t.id===e),s=r[o];if(!s)return;let{operationId:c}=a.startOperation({context:{...n,messageId:e},type:`regenerate`});try{let l=Q0(await e2(n),rke(s.editorData)),u=r.slice(0,o+1);if(u.length<=0){a.completeOperation(c);return}if(i.onBeforeRegenerate&&await i.onBeforeRegenerate(e)===!1){a.completeOperation(c);return}let d=pi.getOperationById(c)(Z9.getState());if(d&&d.status!==`running`)return;let{dbMessages:f}=t(),p=f.filter(t=>t.parentId===e).length;await a.switchMessageBranch(e,p,{operationId:c});let m=pi.getOperationById(c)(Z9.getState());if(m&&m.status!==`running`)return;let{agencyConfig:h,workspaceScoped:g}=n2(n.agentId),_=h?.heterogeneousProvider,v=vs({boundDeviceId:h?.boundDeviceId,executionTarget:h?.executionTarget,heterogeneousProvider:_,isGatewayMode:a.isGatewayModeEnabled(n.agentId),isWorkspaceAgent:g});if(v===`gateway`){await a.executeGatewayAgent({context:n,message:s.content,onComplete:()=>t2(a,c,()=>i.onRegenerateComplete?.(e)),parentMessageId:e});return}if(v===`hetero`&&_){await i2(a,{context:n,heterogeneousProvider:_,imageList:s.imageList,parentMessageId:e,parentOperationId:c,prompt:s.content}),t2(a,c,()=>i.onRegenerateComplete?.(e));return}await a.executeClientAgent({context:n,initialContext:l,messages:u,parentMessageId:e,parentMessageType:`user`,parentOperationId:c}),t2(a,c,()=>i.onRegenerateComplete?.(e))}catch(e){throw a.failOperation(c,{message:e instanceof Error?e.message:String(e),type:`RegenerateError`}),e}},resendThreadMessage:async e=>{await t().regenerateUserMessage(e)},stopGenerating:()=>{let{context:e,hooks:n}=t(),{agentId:r,topicId:i}=e,a=Z9.getState();a.cancelOperations({agentId:r,status:`running`,topicId:i,type:Gte},nn),a.cancelSendMessageInServer(i??void 0),n.onGenerationStop&&n.onGenerationStop()},translateMessage:async(e,t)=>{await Z9.getState().translateMessage(e,t)},ttsMessage:async(e,t)=>{await Z9.getState().ttsMessage(e,t)}})})),oke,ske=e((()=>{or(),f(),Wa(),bc(),oke=(e,t)=>({cleanupInput:()=>{e({chatInputOverlayHeight:0,editor:null,inputMessage:``,scheduledSendAt:void 0}),Z9.setState({mainInputEditor:null})},commitScheduledSend:async(n,r)=>{let{context:i,scheduledSendAt:a}=t(),s=i.agentId;if(!a||!s||!n.trim())return!1;let c=(r??[]).map(e=>e.id);try{await Ga.scheduleAgentRun({agentId:s,fileIds:c.length>0?c:void 0,prompt:n,runAt:a})}catch(e){return console.error(`[commitScheduledSend] failed:`,e),fn.error(o(`input.schedule.failed`,{ns:`chat`})),!1}return e({scheduledSendAt:void 0}),await Z9.getState().refreshTopic(),fn.success(o(`input.schedule.scheduled`,{ns:`chat`,time:new Date(a).toLocaleStr
5190ing(void 0,{day:`2-digit`,hour:`2-digit`,minute:`2-digit`,month:`2-digit`})})),!0},setChatInputOverlayHeight:n=>{t().chatInputOverlayHeight!==n&&e({chatInputOverlayHeight:n})},setEditor:t=>{e({editor:t}),Z9.setState({mainInputEditor:t})},setScheduledSendAt:t=>{e({scheduledSendAt:t})},updateInputMessage:t=>{e({inputMessage:t})}})})),cke,lke,uke=e((()=>{Ne(),R(),cke=t(le()),Na(),z0(),lke=(e,t)=>({addToolToMessage:async(e,n)=>{let{internal_dispatchMessage:r,replaceMessages:i,context:a}=t();r({id:e,type:`addMessageTool`,value:n});let o=await Ma.updateMessage(e,{tools:[n]},a);o?.success&&o.messages&&i(o.messages)},clearMessages:async()=>{let{context:e,replaceMessages:n}=t();await Ma.removeMessagesByAssistant(e.agentId,e.topicId??void 0),n([])},createMessage:async e=>{let{context:n,internal_dispatchMessage:r,replaceMessages:i,internal_toggleMessageLoading:a}=t(),o=t().createTempMessage(e);a(!0,o);try{let t=await Ma.createMessage({...e,agentId:n.agentId,topicId:n.topicId??void 0});return i(t.messages),a(!1,o),t.id}catch(e){a(!1,o),r({id:o,type:`updateMessage`,value:{error:{body:e,message:e.message,type:be.CreateMessageError}}});return}},createTempMessage:e=>{let{internal_dispatchMessage:n}=t(),r=`tmp_`+ke();return n({id:r,type:`createMessage`,value:e}),r},deleteAssistantMessage:async e=>{let n=R0.getDbMessageById(e)(t());if(!n)return;let r=[n.id];if(n.tools){let e=t().dbMessages,i=n.tools.flatMap(t=>e.filter(e=>e.tool_call_id===t.id).map(e=>e.id));r=r.concat(i)}await t().deleteMessages(r)},deleteDBMessage:async e=>{let{internal_dispatchMessage:n,replaceMessages:r,context:i}=t();if(!R0.getDbMessageById(e)(t()))return;n({id:e,type:`deleteMessage`});let a=await Ma.removeMessage(e,i);a?.success&&a.messages&&r(a.messages)},deleteMessage:async e=>{let n=t(),{internal_dispatchMessage:r,replaceMessages:i,context:a}=n,o=R0.getDisplayMessageById(e)(n);if(!o)return;let s=[o.id];if((o.role===`assistantGroup`||o.role===`supervisor`)&&o.children){let e=o.children.map(e=>e.id);s=s.concat(e);
5190let t=o.children.flatMap(e=>e.tools?e.tools.filter(e=>e.result?.id).map(e=>e.result.id):[]);s=s.concat(t)}r({ids:s,type:`deleteMessages`});let c=s.length===1?await Ma.removeMessage(s[0],a):await Ma.removeMessages(s,a);c?.success&&c.messages&&i(c.messages)},deleteMessages:async e=>{let{internal_dispatchMessage:n,replaceMessages:r,context:i}=t();n({ids:e,type:`deleteMessages`});let a=await Ma.removeMessages(e,i);a?.success&&a.messages&&r(a.messages)},deleteToolMessage:async e=>{let{internal_dispatchMessage:n,replaceMessages:r,context:i}=t(),a=R0.getDbMessageById(e)(t());if(!a||a.role!==`tool`)return;n({id:e,type:`deleteMessage`}),a.parentId&&a.tool_call_id&&n({id:a.parentId,tool_call_id:a.tool_call_id,type:`deleteMessageTool`});let o=await Ma.removeMessage(e,i);o?.success&&o.messages&&r(o.messages)},removeToolFromMessage:async(e,n)=>{let{internal_dispatchMessage:r,replaceMessages:i,context:a}=t();r({id:e,tool_call_id:n,type:`deleteMessageTool`});let o=R0.getDbMessageById(e)(t());if(o){let t=await Ma.updateMessage(e,{tools:o.tools||[]},a);t?.success&&t.messages&&i(t.messages)}},updateMessageContent:async(e,n,r)=>{let{internal_dispatchMessage:i,replaceMessages:a,context:o}=t();r?.tools?i({id:e,type:`updateMessage`,value:{tools:r.tools}}):i({id:e,type:`updateMessage`,value:{content:n,editorData:r?.editorData}});let s=await Ma.updateMessage(e,{content:n,editorData:r?.editorData,imageList:r?.imageList,metadata:r?.metadata,model:r?.model,provider:r?.provider,reasoning:r?.reasoning,search:r?.search,tools:r?.tools},o);s?.success&&s.messages&&a(s.messages)},updateMessageError:async(e,n)=>{let{internal_dispatchMessage:r,replaceMessages:i,context:a}=t();r({id:e,type:`updateMessage`,value:{error:n}});let o=await Ma.updateMessage(e,{error:n},a);o?.success&&o.messages&&i(o.messages)},updateMessageMetadata:async(e,n)=>{let{internal_dispatchMessage:r,replaceMessages:i,context:a}=t();r({id:e,type:`updateMessageMetadata`,value:n});let o=await Ma.updateMessageMetadata(e,n,a);o?.success&&o.messages&&i(o.messages)},updateMessagePlugin:async(e,n)=>{let{internal_dispatchMessage:r,replaceMessages:i,context:a}=t();r({id:e,type:`updateMessagePlugin`,value:n});let o=await Ma.updateMessagePlugin(e,n,a);o?.success&&o.messages&&i(o.messages)},updateMessagePluginError:async(e,n)=>{let{replaceMessages:r,context:i}=t(),a=await Ma.updateMessagePluginError(e,n,i);a?.success&&a.messages&&r(a.messages)},updateMessageRAG:async(e,n)=>{let{replaceMessages:r,context:i}=t(),a=await Ma.updateMessageRAG(e,n,i);a?.success&&a.messages&&r(a.messages)},updateMessageTool:async(e,n,r)=>{let{internal_dispatchMessage:i,replaceMessages:a,context:o}=t();i({id:e,tool_call_id:n,type:`updateMessageTools`,value:r});let s=R0.getDbMessageById(e)(t());if(s?.tools){let t=await Ma.updateMessage(e,{tools:s.tools},o);t?.success&&t.messages&&a(t.messages)}},updatePluginArguments:async(n,r,i=!1)=>{let{internal_dispatchMessage:a,replaceMessages:o,context:s}=t(),c,l,u,d=R0.getDbMessageByToolCallId(n)(t());if(d)c=d.plugin?.arguments,l=d.id,u=d.parentId;else{let e=t().dbMessages;for(let t of e)if(t.role===`assistant`&&t.tools){let e=t.tools.find(e=>e.id===n);if(e){c=e.arguments,u=t.id,l=e.result_msg_id;break}}}if(c===void 0&&!u){console.warn(`[updatePluginArguments] Cannot find tool with toolCallId:`,n);return}let f=se(c||``),p=i?r:Ce(f||{},r);if((0,cke.default)(f,p))return;let m=JSON.stringify(p);l&&a({id:l,type:`updateMessagePlugin`,value:{arguments:m}}),u&&a({id:u,tool_call_id:n,type:`updateMessageTools`,value:{arguments:m}});let h=(async()=>{let e=await Ma.updateToolArguments(n,p,s);e?.success&&e.messages&&o(e.messages)})();e(e=>({pendingArgsUpdates:new Map(e.pendingArgsUpdates).set(n,h)}),!1,`updatePluginArguments/pending`);try{await h}finally{e(e=>{let t=new Map(e.pendingArgsUpdates);return t.delete(n),{pendingArgsUpdates:t}},!1,`updatePluginArguments/complete`)}},waitForPendingArgsUpdate:async e=>{let n=t().pendingArgsUpdates.get(e);n&&await n}})})),dke,fke=e((()=>{Er(),Ta(),z0(),dke=(e,t)=>({addReaction:async(e,n)=>{let{updateMessageMetadata:r}=t(),i=R0.getDisplayMessageById(e)(t()),a=ba.userId(Or.getState()),o=i?.metadata?.reactions||[],s=o.findIndex(e=>e.emoji===n),c;c=s>=0?o.map((e,t)=>t===s?{...e,count:e.count+1,users:[...e.users,a]}:e):[...o,{count:1,emoji:n,users:[a]}],await r(e,{reactions:c})},removeReaction:async(e,n)=>{let{updateMessageMetadata:r}=t(),i=R0.getDisplayMessageById(e)(t()),a=ba.userId(Or.getState()),o=i?.metadata?.reactions||[],s=o.findIndex(e=>e.emoji===n);if(s<0)return;let c=o[s],l;if(c.count<=1)l=o.filter((e,t)=>
5190t!==s);else{let e=c.users.lastIndexOf(a),t=e>=0?[...c.users.slice(0,e),...c.users.slice(e+1)]:c.users.slice(0,-1);l=o.map((e,n)=>n===s?{...e,count:e.count-1,users:t}:e)}await r(e,{reactions:l})}})})),pke,mke,hke=e((()=>{pke=`__internal_local__`,mke=e=>e?.metadata?.scope===pke})),gke,_ke=e((()=>{bc(),hke(),gke=(e,t)=>async n=>{let{context:r,hooks:i,displayMessages:a}=t();if(i.onBeforeSendMessage&&await i.onBeforeSendMessage(n)===!1){console.info(`[ConversationStore] sendMessage blocked by onBeforeSendMessage hook`);return}e({inputMessage:``});let o=Z9.getState(),s=(n.messages??a).filter(e=>!mke(e)),c=await o.sendMessage({...n,context:r,messages:s,onTopicCreated:i.onTopicCreated});c&&i.onAfterMessageCreate&&await i.onAfterMessageCreate({assistantMessageId:c.assistantMessageId,createdThreadId:c.createdThreadId,userMessageId:c.userMessageId}),i.onAfterSendMessage&&await i.onAfterSendMessage()}})),vke,a2,o2=e((()=>{vke=/^<speaker\s+\S[^>]*\/>\n?/,a2=e=>e.replace(vke,``)})),yke,bke=e((()=>{Pn(),it(),Na(),bc(),o2(),z0(),yke=(e,t)=>({cancelCompression:async e=>{let n=R0.getDisplayMessageById(e)(t());if(!n||n.role!==`compressedGroup`)return;let{context:r,replaceMessages:i}=t();if(!r.agentId||!r.topicId)return;Z9.getState().cancelOperations({messageId:e,status:`running`},`Compression cancelled`);let{messages:a}=await Ma.cancelCompression({agentId:r.agentId,groupId:r.groupId,messageGroupId:e,threadId:r.threadId,topicId:r.topicId});i(a)},copyMessage:async(e,n)=>{let{hooks:r}=t();await wn(a2(n)),r.onMessageCopied&&r.onMessageCopied(e)},internal_toggleMessageLoading:(t,n)=>{e(e=>({messageLoadingIds:tt(e.messageLoadingIds,e=>{if(t)e.includes(n)||e.push(n);else{let t=e.indexOf(n);t>=0&&e.splice(t,1)}})}),!1,t?`toggleMessageLoading/start`:`toggleMessageLoading/end`)},modifyMessageContent:async(e,n,r)=>{let{hooks:i}=t(),a=R0.getDisplayMessageById(e)(t())?.content;await t().updateMessageContent(e,n,r?{editorData:r}:void 0),i.onMessageModified&&i.onMessageModified(e,n,a)},toggleCompressedGroupExpanded:async(e,n)=>{let r=R0.getDisplayMessageById(e)(t());if(!r||r.role!==`compressedGroup`)return;let{context:i,internal_dispatchMessage:a,replaceMessages:o}=t();if(!i.agentId||!i.topicId)return;let s=r.metadata?.expanded??!1,c=n??!s;a({id:e,type:`updateMessageGroupMetadata`,value:{expanded:c}});let{messages:l}=await Ma.updateMessageGroupMetadata({context:{agentId:i.agentId,groupId:i.groupId,threadId:i.threadId,topicId:i.topicId},expanded:c,messageGroupId:e});o(l)},toggleInspectExpanded:async(e,n)=>{let r=R0.getDbMessageById(e)(t());if(!r)return;let i=n??!r.metadata?.inspectExpanded;await t().updateMessageMetadata(e,{inspectExpanded:i})},toggleMessageCollapsed:async(e,n)=>{let r=R0.getDisplayMessageById(e)(t());if(!r)return;let i=n??!r.metadata?.collapsed;await t().updateMessageMetadata(e,{collapsed:i})}})})),xke,Ske=e((()=>{uke(),fke(),_ke(),bke(),xke=(e,t,...n)=>({...lke(e,t,...n),...dke(e,t,...n),...yke(e,t,...n),addAIMessage:async n=>{let r=t(),{context:i,hooks:a}=r,{agentId:o,topicId:s,threadId:c}=i,l=r.displayMessages,u=l.length>0?l.at(-1)?.id:void 0,d=await r.createMessage({agentId:o,content:n,parentId:u,role:`assistant`,threadId:c??void 0,topicId:s??void 0});if(d){if(a.onMessageCreated){let e=r.displayMessages.find(e=>e.id===d);e&&a.onMessageCreated(e)}e({inputMessage:``})}return d},addUserMessage:async({message:n,fileList:r})=>{let i=t(),{context:a,hooks:o}=i,{agentId:s,topicId:c,threadId:l}=a,u=i.displayMessages,d=u.length>0?u.at(-1)?.id:void 0,f=await i.createMessage({agentId:s,content:n,files:r,parentId:d,role:`user`,threadId:l??void 0,topicId:c??void 0});if(f){if(o.onMessageCreated){let e=i.displayMessages.find(e=>e.id===f);e&&o.onMessageCreated(e)}e({inputMessage:``})}return f},sendMessage:gke(e,t)})})),Cke,s2,wke=e((()=>{Cke=new Set([`user`,`assistant`,`assistantGroup`]),s2=e=>!!e&&Cke.has(e)})),c2,Tke,Eke=e((()=>{it(),wke(),c2=(e,t,n)=>tt(e,e=>{if(n)e.includes(t)||e.push(t);else{let n=e.indexOf(t);n>=0&&e.splice(n,1)}}),Tke=(e,t)=>({enterSelectionMode:t=>{e({selectedMessageIds:t?[t]:[],selectionAnchorId:t,selectionMode:!0},!1,`enterSelectionMode`)},exitSelectionMode:()=>{e({selectedMessageIds:[],selectionAnchorId:void 0,selectionMode:!1},!1,`exitSelectionMode`)},selectRange:n=>{let{displayMessages:r,selectionAnchorId:i,selectedMessageIds:a}=t(),o=i?r.findIndex(e=>e.id===i):-1,s=r.findIndex(e=>e.id===n);if(s<0||o<0){e({selectedMessageIds:c2(a,n,!0),selectionAnchorId:n},!1,`selectRange`);return}let[c,l]=o<=s?[o,s]:[s,o],u=r.slice(c,l+1).filter(e=>s2(e.role)).map(e=>
5190e.id),d=new Set(a);for(let e of u)d.add(e);e({selectedMessageIds:[...d],selectionAnchorId:n},!1,`selectRange`)},selectToHere:n=>{let{displayMessages:r,selectionAnchorId:i}=t(),a=n??i,o=a?r.findIndex(e=>e.id===a):r.length-1;o<0||e({selectedMessageIds:r.slice(0,o+1).filter(e=>s2(e.role)).map(e=>e.id)},!1,`selectToHere`)},toggleMessageEditing:(n,r)=>{e({messageEditingIds:c2(t().messageEditingIds,n,r)},!1,`toggleMessageEditing`)},toggleMessageSelected:(n,r)=>{let i=t().selectedMessageIds;e({selectedMessageIds:c2(i,n,r??!i.includes(n)),selectionAnchorId:n},!1,`toggleMessageSelected`)}})})),Dke,Oke,kke=e((()=>{bc(),Dke=(e,t,n)=>new Oke(e,t,n),Oke=class{#e;constructor(e,t,n){this.#e=t}approveToolCall=async(e,t)=>{let{hooks:n,context:r,waitForPendingArgsUpdate:i}=this.#e();await i(e),!(n.onToolApproved&&await n.onToolApproved(e)===!1)&&(await Z9.getState().approveToolCalling(e,t,r),n.onToolCallComplete&&n.onToolCallComplete(e,void 0))};cancelToolInteraction=async e=>{let{context:t}=this.#e();await Z9.getState().cancelToolInteraction(e,t)};rejectAndContinueToolCall=async(e,t)=>{let{context:n,hooks:r,waitForPendingArgsUpdate:i}=this.#e();await i(e),!(r.onToolRejected&&await r.onToolRejected(e,t)===!1)&&await Z9.getState().rejectAndContinueToolCalling(e,t,n)};rejectToolCall=async(e,t)=>{let{context:n,hooks:r,waitForPendingArgsUpdate:i}=this.#e();await i(e),!(r.onToolRejected&&await r.onToolRejected(e,t)===!1)&&await Z9.getState().rejectToolCalling(e,t,n)};skipToolInteraction=async(e,t)=>{let{context:n}=this.#e();await Z9.getState().skipToolInteraction(e,t,n)};submitToolInteraction=async(e,t,n)=>{let{context:r}=this.#e();await Z9.getState().submitToolInteraction(e,t,r,n)};submitHeteroIntervention=async(e,t,n)=>{let{context:r}=this.#e();await Z9.getState().submitHeteroIntervention(e,t,n,r)}}})),l2,Ake,jke=e((()=>{l2=e=>{if(e.size===0)return null;let t=null,n=1/0,r=-1/0;return e.forEach(({top:e,ratio:i},a)=>{(e<n||e===n&&(i>r||i===r&&a<(t??1/0)))&&(t=a,n=e,r=i)}),t},Ake=(e,t)=>({registerVirtuaScrollMethods:t=>{e({virtuaScrollMethods:t})},removeVisibleItem:n=>{let{visibleItems:r}=t();if(!r.has(n))return;let i=new Map(r);i.delete(n),e({activeIndex:l2(i),visibleItems:i})},resetVisibleItems:()=>{e({activeIndex:null,visibleItems:new Map})},scrollToBottom:(e=!0)=>{let{displayMessages:n,virtuaScrollMethods:r}=t();if(n.length===0||!r)return;let i=r.getTotalCount(),a=Math.max(i-1,n.length-1);r.scrollToIndex(a,{align:`end`,smooth:e})},scrollToIndex:(e,n)=>{let{virtuaScrollMethods:r}=t();r?.scrollToIndex(e,n)},setActiveIndex:t=>{e({activeIndex:t})},setScrollState:t=>{e(t)},upsertVisibleItem:(n,r)=>{let{visibleItems:i}=t(),a=new Map(i);a.set(n,r),e({activeIndex:l2(a),visibleItems:a})}})})),Mke,Nke=e((()=>{g0(),LDe(),EOe(),ake(),ske(),Ske(),Eke(),kke(),jke(),Mke=({context:e,hooks:t={},initialMessages:n,skipFetch:r})=>(...i)=>({...IDe,context:e,hooks:t,skipFetch:r,...n?{dbMessages:n,displayMessages:h0(n).flatList,messagesInit:!0}:{},...TOe(...i),...ike(...i),...oke(...i),...xke(...i),...Tke(...i),...Dke(...i),...Ake(...i)})})),Pke,Fke,Ike,Lke,Rke,zke,Bke,Vke,Hke,Uke,u2,Wke=e((()=>{wi(),Pke=e=>e.context,Fke=e=>e.context.agentId,Ike=e=>e.context.groupId,Lke=e=>e.context.topicId,Rke=e=>e.context.threadId,zke=e=>!!e.context.threadId,Bke=e=>!!e.context.topicId,Vke=e=>{let{agentId:t,topicId:n,threadId:r,scope:i,isNew:a,groupId:o,subAgentId:s}=e.context;return li({agentId:t,groupId:o,isNew:a,scope:i,subAgentId:s,threadId:r??void 0,topicId:n??void 0})},Hke=e=>e.hooks,Uke=e=>t=>t.hooks[e],u2={agentId:Fke,context:Pke,conversationKey:Vke,groupId:Ike,hook:Uke,hooks:Hke,isThread:zke,isTopic:Bke,threadId:Rke,topicId:Lke}})),Gke,Kke,qke,Jke,d2,Yke=e((()=>{Gke=e=>e.editor,Kke=e=>e.inputMessage,qke=e=>e.inputMessage.trim().length>0,Jke=e=>e.chatInputOverlayHeight,d2={chatInputOverlayHeight:Jke,editor:Gke,hasInput:qke,inputMessage:Kke}})),Xke,Zke,Qke,$ke,eAe,tAe,nAe,rAe,iAe,aAe,oAe,sAe,cAe,f2,lAe,uAe,dAe,fAe,pAe,mAe,hAe,gAe,_Ae,vAe,yAe,p2,bAe=e((()=>{bc(),Oi(),z0(),Xke=e=>t=>t.dbMessages.find(t=>t.id===e)?.metadata?.collapsed??!1,Zke=e=>t=>t.messageEditingIds.includes(e),Qke=e=>t=>t.messageLoadingIds.includes(e),$ke=e=>e.messageEditingIds,eAe=e=>e.messageLoadingIds,tAe=e=>e.selectionMode,nAe=e=>t=>t.selectedMessageIds.includes(e),rAe=e=>e.selectedMessageIds.length,iAe=e=>e.operationState.isAIGenerating,aAe=e=>
5190e.operationState.isInputLoading,oAe=e=>e.operationState.isInputVisiblyLoading,sAe=e=>e.operationState.sendMessageError,cAe=e=>t=>t.operationState.getMessageOperationState(e).isCreating,f2=e=>t=>t.operationState.getMessageOperationState(e).isGenerating,lAe=e=>t=>{if(f2(e)(t))return!0;let n=t.displayMessages.find(t=>t.id===e);if(n?.role===`assistantGroup`)return n.children?.some(e=>f2(e.id)(t))??!1;let r=t.displayMessages.find(t=>t.role===`assistantGroup`&&t.children?.some(t=>t.id===e));return r?f2(r.id)(t):!1},uAe=e=>t=>t.operationState.getMessageOperationState(e).isRegenerating,dAe=e=>t=>t.operationState.getMessageOperationState(e).isContinuing,fAe=e=>t=>t.operationState.getMessageOperationState(e).isInterrupted,pAe=e=>t=>t.operationState.getMessageOperationState(e).isInReasoning,mAe=e=>t=>t.operationState.getMessageOperationState(e).isProcessing,hAe=e=>t=>t.operationState.getToolOperationState(e,0).isInvoking,gAe=(e,t)=>n=>n.operationState.getToolOperationState(e,t).isStreaming,_Ae=(e,t,n)=>r=>{let i=R0.getDbMessageByToolCallId(n)(r)?.id,a=r.operationState.getToolOperationState(e,t,n).isStreaming,o=i?r.operationState.getToolOperationState(i,0).isInvoking:!0;return a||o},vAe=e=>t=>{let n=Z9.getState();return Ci.hasThreadBySourceMsgId(e)(n)},yAe=e=>!!Z9.getState().activeThreadId,p2={hasThreadBySourceMsgId:vAe,isAIGenerating:iAe,isAssistantGroupItemGenerating:lAe,isInputLoading:aAe,isInputVisiblyLoading:oAe,isMessageCollapsed:Xke,isMessageContinuing:dAe,isMessageCreating:cAe,isMessageEditing:Zke,isMessageGenerating:f2,isMessageInReasoning:pAe,isMessageInterrupted:fAe,isMessageLoading:Qke,isMessageProcessing:mAe,isMessageRegenerating:uAe,isMessageSelected:nAe,isPluginApiInvoking:hAe,isSelectionMode:tAe,isThreadMode:yAe,isToolApiNameShining:_Ae,isToolCallStreaming:gAe,messageEditingIds:$ke,messageLoadingIds:eAe,selectedMessageCount:rAe,sendMessageError:sAe}})),xAe,SAe,CAe,wAe,TAe,m2,EAe=e((()=>{xAe=e=>e.atBottom,SAe=e=>e.isScrolling,CAe=e=>e.activeIndex,wAe=e=>e.visibleItems,TAe=e=>e.virtuaScrollMethods,m2={activeIndex:CAe,atBottom:xAe,isScrolling:SAe,virtuaScrollMethods:TAe,visibleItems:wAe}})),DAe,OAe=e((()=>{Wke(),z0(),Yke(),bAe(),EAe(),DAe={...u2,...R0,...d2,...p2,...m2}})),kAe,AAe,jAe,h2,MAe,NAe=e((()=>{y(),d(),ot(),gt(),Nke(),OAe(),kAe=lt(`conversation`),AAe=e=>b(kAe(Mke(e)),l),{Provider:jAe,useStore:h2,useStoreApi:MAe}=ut()})),g2,PAe,_2,FAe=e((()=>{U$(),g2=t(qt()),a(),NAe(),z0(),bc(),PAe=t(xt()),_2=(0,g2.memo)(e=>{let{t}=c(`tool`),{actionsPortalTarget:n,args:r,messageId:i,onInteractionAction:a}=e,o=h2(e=>R0.getDbMessageById(i)(e)?.pluginState?.[O$]),s=Z9(e=>e.setInterventionDraft),l=H$({args:r,countdownMs:RTe,onInteractionAction:a,persistedDraft:o,writeDraft:(0,g2.useCallback)(e=>s(i,e),[i,s])}),u={customPlaceholder:t(`claudeCode.askUserQuestion.customOption.placeholder`),escapeBack:t(`claudeCode.askUserQuestion.escape.back`),escapeEnter:t(`claudeCode.askUserQuestion.escape.enter`),escapePlaceholder:t(`claudeCode.askUserQuestion.escape.placeholder`),multiSelectTag:t(`claudeCode.askUserQuestion.multiSelectTag`),skip:t(`claudeCode.askUserQuestion.skip`),submit:t(`claudeCode.askUserQuestion.submit`),timeExpired:t(`claudeCode.askUserQuestion.timeExpired`),timeRemaining:e=>t(`claudeCode.askUserQuestion.timeRemaining`,{time:e})};return(0,PAe.jsx)(I$,{...l,showCountdown:!0,actionsPortalTarget:n,labels:u})}),_2.displayName=`CCAskUserQuestionIntervention`})),IAe,LAe=e((()=>{yZ(),FAe(),IAe={[vZ.AskUserQuestion]:_2}})),RAe,zAe,BAe,VAe,v2,y2,b2,x2,HAe,UAe,S2,WAe,C2,GAe,KAe,qAe,w2,JAe,YAe,XAe,ZAe,QAe,$Ae,eje,tje,nje,rje,ije,aje=e((()=>{Ie(),ae(),GZ(),RAe=[`items`,`nodes`,`results`,`pullRequests`,`pull_requests`,`issues`,`repositories`,`branches`,`commits`,`comments`,`reviews`],zAe=[`repository_full_name`,`repository`,`full_name`,`owner`,`base`,`head`,`base_ref`,`head_ref`,`branch`,`state`,`draft`,`merged`,`mergeable`,`private`,`visibility`,`language`,`additions`,`deletions`,`changed_files`,`comments`,`review_comments`],BAe=new Set([`created_at`,`updated_at`,`closed_at`,`merged_at`,`pushed_at`]),VAe=e=>e.replaceAll(`_`,` `).replaceAll(/([A-Z])/g,` $1`).replace(/^./u,e=>e.toUpperCase()).trim().replace(`Url`,`URL`).replace(`Id`,`ID`),v2=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},y2=e=>{if(typeof e==`string`)return e.trim();if(e==null)return``;try{return JSON.stringify(e,null,2)}catch{return String(e)}},b2=e=>{let t=v2(e);if(t)return t;if(typeof e==`number`)return String(e);if(typeof e==`boolean`)return e?`Yes`:`No`;if(Oe(e))for(let t of[`full_name`,`name`,`title`,`login`,`ref`,`id`]){let n=b2(e[t]);if(n)return n}},x2=e=>{let t=/^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}(?::\d{2})?)/u.exec(e);return t?`${t[1]} ${t[2]}`:e},HAe=(e,t)=>
5190{let n=b2(e[t]);if(n)return{key:t,label:VAe(t),value:BAe.has(t)?x2(n):n}},UAe=(e,t)=>t.map(t=>HAe(e,t)).filter(e=>!!e),S2=e=>typeof e==`string`?e:Oe(e)&&(v2(e.text)||v2(e.content))||y2(e),WAe=e=>se(e),C2=e=>{if(typeof e!=`string`)return e;let t=e.trim();if(t)return WAe(t)??t},GAe=e=>Oe(e)?`Ok`in e?e.Ok:`Err`in e?e.Err:`ok`in e?e.ok:`error`in e&&Object.keys(e).length===1?e.error:e:e,KAe=e=>{let t=GAe(C2(e));return Array.isArray(t)?C2(t.map(S2).filter(Boolean).join(`
5191
5192`))??t:Oe(t)&&Array.isArray(t.content)?C2(t.content.map(S2).filter(Boolean).join(`
5193
5194`))??t:t},qAe=e=>!!(e&&/^https?:\/\/github\.com\//iu.test(e.trim())),w2=e=>{let t=b2(e.html_url)||b2(e.webUrl);if(t)return t;let n=b2(e.url);return qAe(n)?n:void 0},JAe=e=>Array.isArray(e)?e.map(e=>{if(!Oe(e))return;let t=w2(e);if(t)return{title:b2(e.title)||b2(e.name)||t,url:t}}).filter(e=>!!e):[],YAe=(e,t)=>{let n=b2(e.repository_full_name)||b2(e.full_name)||b2(e.repository);if(n)return n;if(!Oe(t))return;let r=b2(t.repository_full_name)||b2(t.full_name)||b2(t.repository)||b2(t.repo);if(r)return r;let i=b2(t.owner),a=b2(t.name);return i&&a?`${i}/${a}`:void 0},XAe=(e,t,n)=>{let r=t||``;return r.includes(`pull_request`)||n?.includes(`/pull/`)||`mergeable`in e||`draft`in e?`Pull request`:r.includes(`issue`)||n?.includes(`/issues/`)?`Issue`:r.includes(`repository`)||`full_name`in e?`Repository`:r.includes(`branch`)||`ref`in e?`Branch`:r.includes(`commit`)||`sha`in e?`Commit`:r.includes(`comment`)?`Comment`:`Result`},ZAe=e=>{if(e.merged===!0)return`Merged`;if(e.draft===!0)return`Draft`;let t=b2(e.state)||b2(e.status);return t?t.replace(/^./u,e=>e.toUpperCase()):void 0},QAe=e=>{let t=b2(e.number);if(t)return`#${t}`;let n=b2(e.sha);return n?n.slice(0,12):b2(e.id)},$Ae=(e,t,n)=>{let r=w2(e),i=XAe(e,n,r),a=YAe(e,t),o=b2(e.title)||b2(e.name)||b2(e.full_name)||b2(e.path)||b2(e.message),s=QAe(e),c=ZAe(e),l=b2(e.body)||b2(e.description)||b2(e.content),u=[...a?[{key:`repository`,label:`Repository`,value:a}]:[],...UAe(e,zAe).filter(e=>e.value!==a&&!((e.key===`state`||e.key===`status`)&&e.value.toLowerCase()===c?.toLowerCase()))],d=JAe(e.links),f=b2(e.updated_at)||b2(e.updatedAt);if(!(!s&&!o&&!r&&!c&&!l&&!f&&u.length===0&&d.length===0))return{description:l,fields:u,id:s,kind:i,links:d,state:c,title:o,updatedAt:f,url:r}},eje=[`id`,`number`,`title`,`name`,`full_name`,`sha`,`html_url`,`url`],tje=e=>eje.some(t=>!!b2(e[t])),nje=e=>{if(Array.isArray(e))return e.filter(Oe);if(!Oe(e))return[];if(!tje(e))for(let t of RAe){let n=e[t];if(Array.isArray(n))return n.filter(Oe)}return[e]},rje=e=>{if(e)return typeof e==`string`?e.trim()||void 0:Oe(e)&&(b2(e.message)||b2(e.error))||y2(e)},ije=({apiName:e,args:t,content:n,pluginError:r})=>{let i=KAe(n),a=nje(i).map(n=>$Ae(n,t,e)).filter(e=>!!e),o=typeof i==`string`?i:void 0,s=i!==void 0&&typeof i!=`string`&&a.length===0?y2(i):void 0;return{actionLabel:WZ(HZ(e||``)),errorText:rje(r),rawResultJson:s,resultEntities:a,resultText:o}}})),T2,E2,D2,O2,k2,A2,j2,M2,N2,oje=e((()=>{qa(),Pn(),hn(),Zn(),T2=t(qt()),a(),aje(),E2=t(xt()),D2=bn(({css:e,cssVar:t})=>({container:e`
5195    overflow: hidden;
5196    min-width: 0;
5197  `,description:e`
5198    overflow: auto;
5199
5200    max-height: 180px;
5201    padding-block: 8px;
5202    padding-inline: 10px;
5203    border: 1px solid ${t.colorBorderSecondary};
5204    border-radius: 6px;
5205
5206    background: ${t.colorFillQuaternary};
5207  `,entityHeader:e`
5208    display: flex;
5209    gap: 12px;
5210    align-items: center;
5211    justify-content: space-between;
5212
5213    min-width: 0;
5214  `,headLeft:e`
5215    display: flex;
5216    gap: 6px;
5217    align-items: center;
5218    min-width: 0;
5219  `,linkRow:e`
5220    overflow: hidden;
5221    display: flex;
5222    gap: 8px;
5223    align-items: center;
5224
5225    min-width: 0;
5226    padding-block: 6px;
5227    padding-inline: 8px;
5228    border-radius: 6px;
5229
5230    color: ${t.colorText};
5231
5232    background: ${t.colorFillQuaternary};
5233
5234    &:hover {
5235      color: ${t.colorLink};
5236      background: ${t.colorFillTertiary};
5237    }
5238  `,linkText:e`
5239    overflow: hidden;
5240    min-width: 0;
5241  `,metaItem:e`
5242    display: inline-flex;
5243    gap: 4px;
5244    align-items: baseline;
5245
5246    min-width: 0;
5247
5248    font-size: 12px;
5249    line-height: 1.5;
5250  `,metaLabel:e`
5251    flex-shrink: 0;
5252    color: ${t.colorTextTertiary};
5253  `,metaRow:e`
5254    display: flex;
5255    flex-wrap: wrap;
5256    gap: 4px 16px;
5257    align-items: baseline;
5258
5259    min-width: 0;
5260  `,metaValue:e`
5261    overflow: hidden;
5262
5263    min-width: 0;
5264
5265    color: ${t.colorTextSecondary};
5266    text-overflow: ellipsis;
5267    white-space: nowrap;
5268  `,rawDetails:e`
5269    font-size: 12px;
5270    color: ${t.colorTextSecondary};
5271
5272    summary {
5273      cursor: pointer;
5274      width: fit-content;
5275      margin-block-end: 6px;
5276    }
5277  `,sectionLabel:e`
5278    font-size: 12px;
5279    color: ${t.colorTextSecondary};
5280  `,timeItem:e`
5281    flex-shrink: 0;
5282    font-size: 12px;
5283    color: ${t.colorTextTertiary};
5284    white-space: nowrap;
5285  `,titleLink:e`
5286    display: inline-flex;
5287    gap: 4px;
5288    align-items: center;
5289
5290    min-width: 0;
5291
5292    color: inherit;
5293
5294    &:hover {
5295      color: ${t.colorLink};
5296    }
5297  `})),O2=e=>e.length>0,k2=(0,T2.memo)(({children:e,title:t})=>(0,E2.jsxs)(yn,{gap:6,children:[(0,E2.jsx)(mn,{className:D2.sectionLabel,children:t}),e]})),k2.displayName=`GitHubRenderSection`,A2=(0,T2.memo)(({fields:e})=>O2(e)?(0,E2.jsx)(`div`,{className:D2.metaRow,children:e.map(e=>(0,E2.jsxs)(`span`,{className:D2.metaItem,children:[(0,E2.jsx)(`span`,{className:D2.metaLabel,children:e.label}),(0,E2.jsx)(`span`,{className:D2.metaValue,title:e.value,children:e.value})]},`${e.key}:${e.value}`))}):null),A2.displayName=`GitHubRenderMetaRow`,j2=(0,T2.memo)(({links:e})=>O2(e)?(0,E2.jsx)(yn,{gap:4,children:e.map(e=>(0,E2.jsxs)(`a`,{className:D2.linkRow,href:e.url,rel:`noreferrer`,target:`_blank`,children:[(0,E2.jsx)(vn,{icon:Yn,size:13}),(0,E2.jsx)(mn,{ellipsis:!0,className:D2.linkText,title:e.title,children:e.title}),(0,E2.jsx)(vn,{icon:ir,size:12})]},`${e.title}:${e.url}`))}):null),j2.displayName=`GitHubRenderLinkList`,M2=(0,T2.memo)(({entity:e})=>{let{t}=c(`plugin`),{title:n,id:r,url:i,state:a,updatedAt:o,kind:s}=e;return(0,E2.jsxs)(Tn,{gap:8,padding:10,variant:`outlined`,width:`100%`,children:[(0,E2.jsxs)(`div`,{className:D2.entityHeader,children:[(0,E2.jsxs)(`div`,{className:D2.headLeft,children:[(0,E2.jsx)(jn,{size:`small`,children:s}),n&&(i?(0,E2.jsxs)(`a`,{className:D2.titleLink,href:i,rel:`noreferrer`,target:`_blank`,children:[(0,E2.jsx)(mn,{ellipsis:!0,weight:600,children:n}),(0,E2.jsx)(vn,{icon:ir,size:12})]}):(0,E2.jsx)(mn,{ellipsis:!0,weight:600,children:n})),r&&(0,E2.jsx)(jn,{size:`small`,children:r}),a&&(0,E2.jsx)(jn,{size:`small`,variant:`outlined`,children:a})]}),o&&(0,E2.jsx)(`span`,{className:D2.timeItem,title:x2(o),children:t(`builtins.github.render.updatedAt`,{time:Ka(o)})})]}),(0,E2.jsx)(A2,{fields:e.fields}),e.description&&(0,E2.jsx)(`div`,{className:D2.description,children:(0,E2.jsx)(Cn,{fontSize:13,variant:`chat`,children:e.description})}),(0,E2.jsx)(j2,{links:e.links})]})}),M2.displayName=`GitHubRenderEntityCard`,N2=(0,T2.memo)(({apiName:e,args:t,content:n,pluginError:r})=>{let{t:i}=c(`plugin`),a=(0,T2.useMemo)(()=>ije({apiName:e,args:t,content:n,pluginError:r}),[e,t,n,r]);return!(O2(a.resultEntities)||a.resultText||a.rawResultJson)&&!a.errorText?null:(0,E2.jsxs)(yn,{className:D2.container,gap:12,children:[O2(a.resultEntities)&&(0,E2.jsx)(yn,{gap:8,children:a.resultEntities.map((e,t)=>(0,E2.jsx)(M2,{entity:e},`${e.id||e.title||`entity`}:${t}`))}),a.resultText&&(0,E2.jsx)(Mn,{wrap:!0,language:`text`,showLanguage:!1,style:{maxHeight:220,overflow:`auto`,paddingInline:8},variant:`filled`,children:a.resultText}),a.rawResultJson&&(0,E2.jsxs)(`details`,{className:D2.rawDetails,children:[(0,E2.jsx)(`summary`,{children:i(`builtins.github.render.rawResult`)}),(0,E2.jsx)(Mn,{wrap:!0,language:`json`,style:{maxHeight:260,overflow:`auto`,paddingInline:8},variant:`filled`,children:a.rawResultJson})]}),a.errorText&&(0,E2.jsx)(k2,{title:i(`builtins.github.render.error`),children:(0,E2.jsx)(Mn,{wrap:!0,language:`text`,showLanguage:!1,style:{maxHeight:220,overflow:`auto`,paddingInline:8},variant:`filled`,children:a.errorText})})]})}),N2.displayName=`GitHubRender`})),sje,cje,lje,uje,dje,fje,pje,mje,hje,P2,F2,I2,gje,L2,_je,R2,vje,z2,yje,B2,bje,xje,V2,H2,Sje,Cje,wje,Tje,Eje,Dje,Oje=e((()=>{Ie(),ae(),OQ(),sje={0:`None`,1:`Urgent`,2:`High`,3:`Medium`,4:`Low`},cje=/^(issue|project|document|initiative|milestone|team|user|cycle):(.+)$/iu,lje=[`id`,`title`,`name`,`state`,`status`,`team`,`project`,`assignee`,`cycle`,`milestone`,`priority`,`parentId`,`query`,`url`],uje=[`state`,`status`,`team`,`project`,`assignee`,`cycle`,`milestone`,`priority`,`parentId`],dje=[`issues`,`items`,`nodes`,`results`,`documents`,`projects`,`comments`,`users`,`teams`],fje=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu,pje=e=>fje.test(e),mje=e=>e.replaceAll(/([A-Z])/g,` $1`).replace(/^./u,e=>e.toUpperCase()).trim(),hje=e=>e.replace(cje,`$2`),P2=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},F2=e=>{if(typeof e==`string`)return e.trim();if(e==null)return``;try{return JSON.stringify(e,null,2)}catch{return String(e)}},I2=(e,t)=>
5297{let n=P2(e);if(n)return t===`id`?hje(n):n;if(typeof e==`number`)return t===`priority`?sje[e]??String(e):String(e);if(typeof e==`boolean`)return e?`Yes`:`No`;if(Oe(e))for(let t of[`name`,`title`,`displayName`,`identifier`,`id`]){let n=I2(e[t],t);if(n)return n}},gje=new Set([`createdAt`,`updatedAt`,`completedAt`,`startedAt`,`canceledAt`,`archivedAt`,`dueDate`]),L2=e=>{let t=/^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}(?::\d{2})?)/u.exec(e);return t?`${t[1]} ${t[2]}`:e},_je=(e,t)=>{let n=I2(e[t],t);if(n)return{key:t,label:t===`id`?`ID`:t===`url`?`URL`:mje(t),value:gje.has(t)?L2(n):n}},R2=(e,t)=>t.map(t=>_je(e,t)).filter(e=>!!e),vje=e=>Oe(e)?R2(e,lje):[],z2=e=>typeof e==`string`?e:Oe(e)&&(P2(e.text)||P2(e.content))||F2(e),yje=e=>se(e),B2=e=>{if(typeof e!=`string`)return e;let t=e.trim();if(t)return yje(t)??t},bje=e=>Oe(e)?`Ok`in e?e.Ok:`Err`in e?e.Err:`ok`in e?e.ok:`error`in e&&Object.keys(e).length===1?e.error:e:e,xje=e=>{let t=bje(B2(e));return Array.isArray(t)?B2(t.map(z2).filter(Boolean).join(`
5298
5299`))??t:Oe(t)&&Array.isArray(t.content)?B2(t.content.map(z2).filter(
5299Boolean).join(`
5300
5301`))??t:t},V2=e=>I2(e.url,`url`)||I2(e.webUrl,`url`),H2=e=>Array.isArray(e)?e.map(e=>{if(!Oe(e))return;let t=V2(e);if(t)return{title:I2(e.title)||I2(e.name)||t,url:t}}).filter(e=>!!e):[],Sje=e=>{let t=I2(e.id,`id`)||I2(e.identifier,`id`),n=I2(e.title)||I2(e.name)||I2(e.subject),r=V2(e),i=I2(e.state,`state`)||I2(e.status,`status`),a=I2(e.description)||I2(e.body)||I2(e.content),o=R2(e,uje).filter(e=>!((e.key===`state`||e.key===`status`)&&e.value===i)),s=H2(e.links),c=P2(e.updatedAt);if(!(!t&&!n&&!r&&!i&&!a&&!c&&o.length===0&&s.length===0))return{description:a,fields:o,id:t,links:s,state:i,title:n,updatedAt:c,url:r}},Cje=[`id`,`identifier`,`title`,`name`,`subject`],wje=e=>Cje.some(t=>!!I2(e[t])),Tje=e=>{if(Array.isArray(e))return{records:e.filter(Oe)};if(!Oe(e))return{records:[]};if(!wje(e))for(let t of dje){let n=e[t];if(Array.isArray(n))return{collectionKey:t,records:n.filter(Oe)}}return{records:[e]}},Eje=e=>{if(e)return typeof e==`string`?e.trim()||void 0:Oe(e)&&(I2(e.message)||I2(e.error))||F2(e)},Dje=({apiName:e,args:t,content:n,pluginError:r})=>{let i=TQ(e||``),a=xje(n),{collectionKey:o,records:s}=Tje(a),c=s.map(Sje).filter(e=>!!e),l=typeof a==`string`?a:void 0,u=o&&s.length===0?o:void 0,d=a!==void 0&&typeof a!=`string`&&c.length===0&&!u?F2(a):void 0;return{actionLabel:DQ(i),emptyCollectionKey:u,errorText:Eje(r),requestFields:vje(t),requestLinks:Oe(t)?H2(t.links):[],resultEntities:c,resultText:l,rawResultJson:d}}})),U2,W2,G2,K2,q2,J2,Y2,X2,Z2,kje=e((()=>{qa(),Pn(),hn(),Zn(),U2=t(qt()),a(),Oje(),W2=t(xt()),G2=bn(({css:e,cssVar:t})=>({container:e`
5302    overflow: hidden;
5303    min-width: 0;
5304  `,description:e`
5305    overflow: auto;
5306
5307    max-height: 180px;
5308    padding-block: 8px;
5309    padding-inline: 10px;
5310    border: 1px solid ${t.colorBorderSecondary};
5311    border-radius: 6px;
5312
5313    background: ${t.colorFillQuaternary};
5314  `,empty:e`
5315    display: flex;
5316    gap: 6px;
5317    align-items: center;
5318    justify-content: center;
5319
5320    padding-block: 16px;
5321    border: 1px solid ${t.colorBorderSecondary};
5322    border-radius: 6px;
5323
5324    font-size: 13px;
5325    color: ${t.colorTextTertiary};
5326
5327    background: ${t.colorFillQuaternary};
5328  `,entityHeader:e`
5329    display: flex;
5330    gap: 12px;
5331    align-items: center;
5332    justify-content: space-between;
5333
5334    min-width: 0;
5335  `,headLeft:e`
5336    display: flex;
5337    gap: 6px;
5338    align-items: center;
5339    min-width: 0;
5340  `,timeItem:e`
5341    flex-shrink: 0;
5342    font-size: 12px;
5343    color: ${t.colorTextTertiary};
5344    white-space: nowrap;
5345  `,metaItem:e`
5346    display: inline-flex;
5347    gap: 4px;
5348    align-items: baseline;
5349
5350    min-width: 0;
5351
5352    font-size: 12px;
5353    line-height: 1.5;
5354  `,metaLabel:e`
5355    flex-shrink: 0;
5356    color: ${t.colorTextTertiary};
5357  `,metaRow:e`
5358    display: flex;
5359    flex-wrap: wrap;
5360    gap: 4px 16px;
5361    align-items: baseline;
5362
5363    min-width: 0;
5364  `,metaValue:e`
5365    overflow: hidden;
5366
5367    min-width: 0;
5368
5369    color: ${t.colorTextSecondary};
5370    text-overflow: ellipsis;
5371    white-space: nowrap;
5372  `,linkRow:e`
5373    overflow: hidden;
5374    display: flex;
5375    gap: 8px;
5376    align-items: center;
5377
5378    min-width: 0;
5379    padding-block: 6px;
5380    padding-inline: 8px;
5381    border-radius: 6px;
5382
5383    color: ${t.colorText};
5384
5385    background: ${t.colorFillQuaternary};
5386
5387    &:hover {
5388      color: ${t.colorLink};
5389      background: ${t.colorFillTertiary};
5390    }
5391  `,linkText:e`
5392    overflow: hidden;
5393    min-width: 0;
5394  `,rawDetails:e`
5395    font-size: 12px;
5396    color: ${t.colorTextSecondary};
5397
5398    summary {
5399      cursor: pointer;
5400      width: fit-content;
5401      margin-block-end: 6px;
5402    }
5403  `,sectionLabel:e`
5404    font-size: 12px;
5405    color: ${t.colorTextSecondary};
5406  `,titleLink:e`
5407    display: inline-flex;
5408    gap: 4px;
5409    align-items: center;
5410
5411    min-width: 0;
5412
5413    color: inherit;
5414
5415    &:hover {
5416      color: ${t.colorLink};
5417    }
5418  `})),K2=e=>e.length>0,q2=(0,U2.memo)(({children:e,title:t})=>(0,W2.jsxs)(yn,{gap:6,children:[(0,W2.jsx)(mn,{className:G2.sectionLabel,children:t}),e]})),q2.displayName=`LinearRenderSection`,J2=(0,U2.memo)(({fields:e})=>K2(e)?(0,W2.jsx)(`div`,{className:G2.metaRow,children:e.map(e=>(0,W2.jsxs)(`span`,{className:G2.metaItem,children:[(0,W2.jsx)(`span`,{className:G2.metaLabel,children:e.label}),(0,W2.jsx)(`span`,{className:G2.metaValue,title:e.value,children:e.value})]},`${e.key}:${e.value}`))}
5418):null),J2.displayName=`LinearRenderMetaRow`,Y2=(0,U2.memo)(({links:e})=>K2(e)?(0,W2.jsx)(yn,{gap:4,children:e.map(e=>(0,W2.jsxs)(`a`,{className:G2.linkRow,href:e.url,rel:`noreferrer`,target:`_blank`,children:[(0,W2.jsx)(vn,{icon:Yn,size:13}),(0,W2.jsx)(mn,{ellipsis:!0,className:G2.linkText,title:e.title,children:e.title}),(0,W2.jsx)(vn,{icon:ir,size:12})]},`${e.title}:${e.url}`))}):null),Y2.displayName=`LinearRenderLinkList`,X2=(0,U2.memo)(({entity:e})=>{let{t}=c(`plugin`),{title:n,id:r,url:i,state:a,updatedAt:o}=e,s=!!r&&(!n||!pje(r));return(0,W2.jsxs)(Tn,{gap:8,padding:10,variant:`outlined`,width:`100%`,children:[(0,W2.jsxs)(`div`,{className:G2.entityHeader,children:[(0,W2.jsxs)(`div`,{className:G2.headLeft,children:[n&&(i?(0,W2.jsxs)(`a`,{className:G2.titleLink,href:i,rel:`noreferrer`,target:`_blank`,children:[(0,W2.jsx)(mn,{ellipsis:!0,weight:600,children:n}),(0,W2.jsx)(vn,{icon:ir,size:12})]}):(0,W2.jsx)(mn,{ellipsis:!0,weight:600,children:n})),s&&(i&&!n?(0,W2.jsxs)(`a`,{className:G2.titleLink,href:i,rel:`noreferrer`,target:`_blank`,children:[(0,W2.jsx)(jn,{size:`small`,children:r}),(0,W2.jsx)(vn,{icon:ir,size:12})]}):(0,W2.jsx)(jn,{size:`small`,children:r})),a&&(0,W2.jsx)(jn,{size:`small`,variant:`outlined`,children:a})]}),o&&(0,W2.jsx)(`span`,{className:G2.timeItem,title:L2(o),children:t(`builtins.linear.render.updatedAt`,{time:Ka(o)})})]}),(0,W2.jsx)(J2,{fields:e.fields}),e.description&&(0,W2.jsx)(`div`,{className:G2.description,children:(0,W2.jsx)(Cn,{fontSize:13,variant:`chat`,children:e.description})}),(0,W2.jsx)(Y2,{links:e.links})]})}),X2.displayName=`LinearRenderEntityCard`,Z2=(0,U2.memo)(({apiName:e,args:t,content:n,pluginError:r})=>{let{t:i}=c(`plugin`),a=(0,U2.useMemo)(()=>Dje({apiName:e,args:t,content:n,pluginError:r}),[e,t,n,r]);return!(K2(a.resultEntities)||a.resultText||a.rawResultJson||a.emptyCollectionKey)&&!a.errorText?null:(0,W2.jsxs)(yn,{className:G2.container,gap:12,children:[K2(a.resultEntities)&&(0,W2.jsx)(yn,{gap:8,children:a.resultEntities.map((e,t)=>(0,W2.jsx)(X2,{entity:e},`${e.id||e.title||`entity`}:${t}`))}),a.emptyCollectionKey&&(0,W2.jsxs)(`div`,{className:G2.empty,children:[(0,W2.jsx)(vn,{icon:see,size:14}),(0,W2.jsx)(`span`,{children:i(`builtins.linear.render.empty`,{collection:a.emptyCollectionKey})})]}),a.resultText&&(0,W2.jsx)(Mn,{wrap:!0,language:`text`,showLanguage:!1,style:{maxHeight:220,overflow:`auto`,paddingInline:8},variant:`filled`,children:a.resultText}),a.rawResultJson&&(0,W2.jsxs)(`details`,{className:G2.rawDetails,children:[(0,W2.jsx)(`summary`,{children:`Raw result`}),(0,W2.jsx)(Mn,{wrap:!0,language:`json`,style:{maxHeight:260,overflow:`auto`,paddingInline:8},variant:`filled`,children:a.rawResultJson})]}),a.errorText&&(0,W2.jsx)(q2,{title:`Error`,children:(0,W2.jsx)(Mn,{wrap:!0,language:`text`,showLanguage:!1,style:{maxHeight:220,overflow:`auto`,paddingInline:8},variant:`filled`,children:a.errorText})})]})}),Z2.displayName=`LinearRender`})),Aje=r(((e,t)=>{var n=[[{color:`0, 0, 0`,class:`ansi-black`},{color:`187, 0, 0`,class:`ansi-red`},{color:`0, 187, 0`,class:`ansi-green`},{color:`187, 187, 0`,class:`ansi-yellow`},{color:`0, 0, 187`,class:`ansi-blue`},{color:`187, 0, 187`,class:`ansi-magenta`},{color:`0, 187, 187`,class:`ansi-cyan`},{color:`255,255,255`,class:`ansi-white`}],[{color:`85, 85, 85`,class:`ansi-bright-black`},{color:`255, 85, 85`,class:`ansi-bright-red`},{color:`0, 255, 0`,class:`ansi-bright-green`},{color:`255, 255, 85`,class:`ansi-bright-yellow`},{color:`85, 85, 255`,class:`ansi-bright-blue`},{color:`255, 85, 255`,class:`ansi-bright-magenta`},{color:`85, 255, 255`,class:`ansi-bright-cyan`},{color:`255, 255, 255`,class:`ansi-bright-white`}]],r=/(https?:\/\/(?:[A-Za-z0-9#;/?:@=+$',_.!~*()[\]-]|&amp;|%[A-Fa-f0-9]{2})+)/gm;t.exports=class e{static escapeForHtml(t){return new e().escapeForHtml(t)}static linkify(t){return new e().linkify(t)}static ansiToHtml(t,n){return new e().ansiToHtml(t,n)}static ansiToJson(t,n){return new e().ansiToJson(t,n)}static ansiToText(t){return new e().ansiToText(t)}constructor(){this.fg=this.bg=this.fg_truecolor=this.bg_truecolor=null,this.bright=0,this.decorations=[]}setupPalette(){this.PALETTE_COLORS=[];for(let e=0;e<2;++e)for(let t=0;t<8;++t)this.PALETTE_COLORS.push(n[e][t].color);let e=[0,95,135,175,215,255],t=(t,n,r)=>e[t]+`, `+e[n]+`, `+e[r];for(let e=0;e<6;++e)for(let n=0;n<6;++n)for(let r=0;r<6;++r)this.PALETTE_COLORS.push(t(e,n,r));let r=8;for(let e=0;e<24;++e,r+=10)this.PALETTE_COLORS.push(r+`, `+r+`, `+r)}escapeForHtml(e){return e.replace(/[&<>\"]/gm,e=>e==`&`?`&amp;`:e==`"`?`&quot;`:e==`<`?`&lt;`:e==`>`?`&gt;`:``)}linkify(e){return e.replace(r,e=>`<a href="${e}">${e}</a>`)}ansiToHtml(e,t){return this.process(e,t,!0)}ansiToJson(e,t){return t||={},t.json=!0,t.clearLine=!1,this.process(e,t,!0)}ansiToText(e){return this.process(e,{},!1)}process(e,t,n){let r=this,i=e.split(/\033\[/),a=i.shift();t??={},t.clearLine=/\r/.test(e);let o=i.map(e=>this.processChunk(e,t,n));if(t&&t.json){let e=r.processChunkJson(``);return e.content=a,e.clearLine=t.clearLine,o.unshift(e),t.remove_empty&&(o=o.filter(e=>!e.isEmpty())),o}else o.unshift(a);return o.join(``)}processChunkJson(e,t,r){t=t===void 0?{}:t;let i=t.use_classes=t.use_classes!==void 0&&t.use_classes,a=t.key=i?`class`:`color`,o={content:e,fg:null,bg:null,fg_truecolor:null,bg_truecolor:null,isInverted:!1,clearLine:t.clearLine,decoration:null,decorations:[],was_processed:!1,isEmpty:()=>!o.content},s=e.match(/^([!\x3c-\x3f]*)([\d;]*)([\x20-\x2c]*[\x40-\x7e])([\s\S]*)/m);if(!s)return o;o.content=s[4];let c=s[2].split(`;`);if(s[1]!==``||s[3]!==`m`||!r)return o;let l=this;for(;c.length>0;){let e=c.shift(),t=parseInt(e);if(isNaN(t)||t===0)l.fg=l.bg=null,l.decorations=[];else if(t===1)l.decorations.push(`bold`);else if(t===2)l.decorations.push(`dim`);else if(t===3)l.decorations.push(`italic`);else if(t===4)l.decorations.push(`underline`);else if(t===5)l.decorations.push(`blink`);else if(t===7)l.decorations.push(`reverse`);else if(t===8)l.decorations.push(`hidden`);else if(t===9)l.decorations.push(`strikethrough`);else if(t===21)l.removeDecoration(`bold`);else if(t===22)l.removeDecoration(`bold`),l.removeDecoration(`dim`);else if(t===23)l.removeDecoration(`italic`);else if(t===24)l.removeDecoration(`underline`);else if(t===25)l.removeDecoration(`blink`);else if(t===27)l.removeDecoration(`reverse`);else if(t===28)l.removeDecoration(`hidden`);else if(t===29)l.removeDecoration(`strikethrough`);else if(t===39)l.fg=null;else if(t===49)l.bg=null;else if(t>=30&&t<38)l.fg=n[0][t%10][a];else if(t>=90&&t<98)l.fg=n[1][t%10][a];else if(t>=40&&t<48)l.bg=n[0][t%10][a];else if(t>=100&&t<108)l.bg=n[1][t%10][a];else if(t===38||t===48){let e=t===38;if(c.length>=1){let t=c.shift();if(t===`5`&&c.length>=1){let t=parseInt(c.shift());if(t>=0&&t<=255)if(!i)this.PALETTE_COLORS||l.setupPalette(),e?l.fg=this.PALETTE_COLORS[t]:l.bg=this.PALETTE_COLORS[t];else{let r=t>=16?`ansi-palette-`+t:n[+(t>7)][t%8].class;e?l.fg=r:l.bg=r}}else if(t===`2`&&c.length>=3){let t=parseInt(c.shift()),n=parseInt(c.shift()),r=parseInt(c.shift());if(t>=0&&t<=255&&n>=0&&n<=255&&r>=0&&r<=255){let a=t+`, `+n+`, `+r;i?e?(l.fg=`ansi-truecolor`,l.fg_truecolor=a):(l.bg=`ansi-truecolor`,l.bg_truecolor=a):e?l.fg=a:l.bg=a}}}}}return l.fg===null&&l.bg===null&&l.decorations.length===0?o:(o.fg=l.fg,o.bg=l.bg,o.fg_truecolor=l.fg_truecolor,o.bg_truecolor=l.bg_truecolor,o.decorations=l.decorations,o.decoration=l.decorations.slice(-1).pop()||null,o.was_processed=!0,o)}processChunk(e,t,r){t||={};let i=this.processChunkJson(e,t,r),a=t.use_classes;if(i.decorations=i.decorations.filter(e=>{if(e===`reverse`){i.fg||=n[0][7][a?`class`:`color`],i.bg||=n[0][0][a?`class`:`color`];let e=i.fg;i.fg=i.bg,i.bg=e;let t=i.fg_truecolor;return i.fg_truecolor=i.bg_truecolor,i.bg_truecolor=t,i.isInverted=!0,!1}return!0}),t.json)return i;if(i.isEmpty())return``;if(!i.was_processed)return i.content;let o=[],s=[],c=[],l={},u=e=>{let t=[],n;for(n in e)e.hasOwnProperty(n)&&t.push(`data-`+n+`="`+this.escapeForHtml(e[n])+`"`);return t.length>0?` `+t.join(` `):``};return i.isInverted&&(l[`ansi-is-inverted`]=`true`),i.fg&&(a?(o.push(i.fg+`-fg`),i.fg_truecolor!==null&&(l[`ansi-truecolor-fg`]=i.fg_truecolor,i.fg_truecolor=null)):o.push(`color:rgb(`+i.fg+`)`)),i.bg&&(a?(o.push(i.bg+`-bg`),i.bg_truecolor!==null&&(l[`ansi-truecolor-bg`]=i.bg_truecolor,i.bg_truecolor=null)):o.push(`background-color:rgb(`+i.bg+`)`)),i.decorations.forEach(e
5418=>{if(a){s.push(`ansi-`+e);return}e===`bold`?s.push(`font-weight:bold`):e===`dim`?s.push(`opacity:0.5`):e===`italic`?s.push(`font-style:italic`):e===`hidden`?s.push(`visibility:hidden`):e===`strikethrough`?c.push(`line-through`):c.push(e)}),c.length&&s.push(`text-decoration:`+c.join(` `)),a?`<span class="`+o.concat(s).join(` `)+`"`+u(l)+`>`+i.content+`</span>`:`<span style="`+o.concat(s).join(`;`)+`"`+u(l)+`>`+i.content+`</span>`}removeDecoration(e){let t=this.decorations.indexOf(e);t>=0&&this.decorations.splice(t,1)}}})),jje,Q2,$2,Mje,e4,Nje=e((()=>{jje=t(Aje()),hn(),Q2=t(qt()),$2=t(xt()),Mje=bn(({css:e})=>({pre:e`
5419    overflow: auto;
5420
5421    max-height: 200px;
5422    margin: 0;
5423    padding: 8px;
5424    border-radius: 6px;
5425
5426    font-family: ${U.fontFamilyCode};
5427    font-size: 12px;
5428    line-height: 1.6;
5429    color: ${U.colorText};
5430    word-break: break-word;
5431    white-space: pre-wrap;
5432
5433    background: ${U.colorFillTertiary};
5434  `})),e4=(0,Q2.memo)(({text:e})=>{let t=(0,Q2.useMemo)(()=>jje.default.ansiToJson(e,{json:!0,remove_empty:!0,use_classes:!1}),[e]);return(0,$2.jsx)(`pre`,{className:Mje.pre,children:t.map((e,t)=>{let n=e.decorations??[],r=n.includes(`dim`),i=n.includes(`bold`),a=n.includes(`italic`),o=n.includes(`underline`),s=n.includes(`strikethrough`);return(0,$2.jsx)(`span`,{style:{background:e.bg?`rgb(${e.bg})`:void 0,color:e.fg?`rgb(${e.fg})`:void 0,fontStyle:a?`italic`:void 0,fontWeight:i?600:void 0,opacity:r?.6:void 0,textDecoration:[o&&`underline`,s&&`line-through`].filter(Boolean).join(` `)||void 0},children:e.content},t)})})}),e4.displayName=`AnsiOutput`})),Pje,t4,Fje,n4,Ije=e((()=>{Pn(),hn(),Pje=t(qt()),uTe(),Nje(),t4=t(xt()),Fje=bn(({css:e})=>({container:e`
5435    overflow: hidden;
5436    padding-inline: 8px 0;
5437  `})),n4=(0,Pje.memo)(({args:e,content:t,pluginState:n})=>{let r=n?.stdout||n?.output||t,i=n?.stderr,a=QQ(e?.command);return(0,t4.jsx)(yn,{className:Fje.container,gap:8,children:(0,t4.jsxs)(Tn,{gap:8,padding:8,variant:`outlined`,children:[(0,t4.jsx)(Mn,{wrap:!0,language:`sh`,showLanguage:!1,style:{maxHeight:200,overflow:`auto`,paddingInline:8},variant:`borderless`,children:a}),r&&(0,t4.jsx)(e4,{text:r}),i?.trim()&&(0,t4.jsx)(e4,{text:i})]})})}),n4.displayName=`RunCommand`})),r4=e((()=>{oje(),kje(),Ije()})),i4,a4,o4,s4,Lje=e((()=>{Pn(),hn(),Zn(),i4=t(qt()),a(),bc(),Oi(),a4=t(xt()),o4=bn(({css:e,cssVar:t})=>({container:e`
5438    padding-block: 4px;
5439  `,label:e`
5440    padding-inline-start: 4px;
5441    font-size: 12px;
5442    color: ${t.colorTextTertiary};
5443  `,labelRow:e`
5444    margin-block-end: 4px;
5445  `,openThread:e`
5446    height: 22px;
5447    padding-inline: 6px;
5448    font-size: 12px;
5449  `,promptBox:e`
5450    padding-block: 8px;
5451    padding-inline: 12px;
5452    border-radius: ${t.borderRadiusLG};
5453    background: ${t.colorFillTertiary};
5454  `,resultBox:e`
5455    padding-block: 8px;
5456    padding-inline: 12px;
5457    border-radius: ${t.borderRadiusLG};
5458    background: ${t.colorBgContainer};
5459  `})),s4=(0,i4.memo)(({args:e,content:t,toolCallId:n})=>{let{t:r}=c(`plugin`),{t:i}=c(`chat`),a=e?.prompt?.trim(),o=typeof t==`string`?t.trim():``,s=Z9(e=>n?(Ci.currentTopicThreads(e)??[]).find(e=>e.metadata?.sourceToolCallId===n):void 0),l=Z9(e=>e.openThreadInPortal),u=Z9(e=>e.closeThreadPortal),d=Z9(ki.portalThreadId),f=!!s&&d===s.id,p=(0,i4.useCallback)(()=>{s&&(f?u():l(s.id,s.sourceMessageId))},[s,f,l,u]);if(!a&&!o&&!s)return null;let m=!!o||!!s;return(0,a4.jsxs)(yn,{className:o4.container,gap:12,children:[a&&(0,a4.jsxs)(yn,{children:[(0,a4.jsx)(mn,{className:o4.label,style:{marginBlockEnd:4},children:r(`builtins.lobe-claude-code.agent.instruction`)}),(0,a4.jsx)(yn,{className:o4.promptBox,children:(0,a4.jsx)(Cn,{style:{maxHeight:240,overflow:`auto`},variant:`chat`,children:a})})]}),m&&(0,a4.jsxs)(yn,{children:[(0,a4.jsxs)(yn,{horizontal:!0,align:`center`,className:o4.labelRow,justify:`space-between`,children:[(0,a4.jsx)(mn,{className:o4.label,children:r(`builtins.lobe-claude-code.agent.result`)}),s&&(0,a4.jsx)(Dn,{className:o4.openThread,icon:Un,size:`small`,type:`text`,onClick:p,children:i(f?`thread.closeSubagentThread`:`thread.openSubagentThread`)})]}),o&&(0,a4.jsx)(yn,{className:o4.resultBox,children:(0,a4.jsx)(Cn,{style:{maxHeight:320,overflow:`auto`},variant:`chat`,children:o})})]})]})}),s4.displayName=`ClaudeCodeAgent`})),c4,l4,u4,d4,f4,p4,Rje=e((()=>{U$(),Pn(),hn(),Zn(),c4=t(qt()),a(),l4=t(xt()),u4=bn(({css:e,cssVar:t})=>({answer:e`
5460    font-size: 14px;
5461    line-height: 1.5;
5462    color: ${t.colorText};
5463  `,check:e`
5464    flex-shrink: 0;
5465    margin-block-start: 4px;
5466    color: ${t.colorPrimary};
5467  `,container:e`
5468    padding-block: 4px;
5469  `,description:e`
5470    font-size: 13px;
5471    line-height: 1.5;
5472    color: ${t.colorTextTertiary};
5473  `,divider:e`
5474    align-self: stretch;
5475    height: 1px;
5476    margin-block: 4px;
5477    background: ${t.colorFillSecondary};
5478  `,header:e`
5479    flex-shrink: 0;
5480
5481    padding-block: 1px;
5482    padding-inline: 6px;
5483    border-radius: 4px;
5484
5485    font-size: 11px;
5486    font-weight: 400;
5487    color: ${t.colorTextTertiary};
5488    white-space: nowrap;
5489
5490    background: ${t.colorFillQuaternary};
5491  `,ordinal:e`
5492    flex-shrink: 0;
5493
5494    width: 22px;
5495    padding-block-start: 2px;
5496
5497    font-family: ${t.fontFamilyCode};
5498    font-size: 11px;
5499    font-variant-numeric: tabular-nums;
5500    line-height: 1.5;
5501    color: ${t.colorTextQuaternary};
5502  `,question:e`
5503    font-size: 14px;
5504    font-weight: 500;
5505    line-height: 1.5;
5506    color: ${t.colorText};
5507  `,titleRow:e`
5508    display: flex;
5509    flex-wrap: wrap;
5510    gap: 6px;
5511    align-items: baseline;
5512  `,unanswered:e`
5513    padding-inline-start: 22px;
5514    font-size: 14px;
5515    line-height: 1.5;
5516    color: ${t.colorTextQuaternary};
5517  `})),d4=(0,c4.memo)(({icon:e,text:t,description:n})=>(0,l4.jsxs)(yn,{horizontal:!0,align:`flex-start`,gap:8,children:[(0,l4.jsx)(vn,{className:u4.check,icon:e,size:14}),(0,l4.jsxs)(yn,{gap:1,children:[(0,l4.jsx)(`span`,{className:u4.answer,children:t}),n&&(0,l4.jsx)(`span`,{className:u4.description,children:n})]})]})),d4.displayName=`CCAskUserAnswerLine`,f4=(0,c4.memo)(({question:e,answer:t,index:n})=>{let{t:r}=c(`plugin`),i=Array.isArray(t)?t:t?[t]:[],a=new Map(e.options.map(e=>[e.label,e]));return(0,l4.jsxs)(yn,{align:`flex-start`,horizontal:!!n,children:[!!n&&(0,l4.jsx)(`span`,{className:u4.ordinal,children:`Q${n}`}),(0,l4.jsxs)(yn,{gap:6,children:[(0,l4.jsxs)(`div`,{className:n?u4.titleRow:void 0,children:[(0,l4.jsx)(`span`,{className:u4.question,children:e.question}),!!n&&e.header&&(0,l4.jsx)(`span`,{className:u4.header,children:e.header})]}),i.length>0?(0,l4.jsx)(yn,{gap:6,children:i.map(e=>{let t=a.get(e);return(0,l4.jsx)(d4,{icon:Jn,text:e,description:t?.description&&t.description!==e?t.description:void 0},e)})}):(0,l4.jsx)(`span`,{className:u4.unanswered,children:r(`builtins.lobe-claude-code.askUserQuestion.notAnswered`)})]})]})}),f4.displayName=`CCAskUserQuestionQABlock`,p4=(0,c4.memo)(({args:e,pluginError:t,pluginState:n})=>{let{t:r}=c(`plugin`),i=z$(e),a=n?.askUserAnswers,o=a?.__freeform__,s=typeof o==`string`?o.trim():``,l=!!t,u=i.length>1;return s?(0,l4.jsxs)(yn,{className:u4.container,gap:12,children:[i.map((e,t)=>(0,l4.jsxs)(yn,{align:`flex-start`,horizontal:u,children:[u&&(0,l4.jsx)(`span`,{className:u4.ordinal,children:`Q${t+1}`}),(0,l4.jsxs)(`div`,{className:u?u4.titleRow:void 0,children:[(0,l4.jsx)(`span`,{className:u4.question,children:e.question}),u&&e.header&&(0,l4.jsx)(`span`,{className:u4.header,children:e.header})]})]},`${e.question}-${t}`)),u&&(0,l4.jsx)(`div`,{className:u4.divider}),(0,l4.jsx)(d4,{icon:Xn,text:s}),l&&(0,l4.jsx)(mn,{type:`warning`,children:r(`builtins.lobe-claude-code.askUserQuestion.noAnswer`)})]}):(0,l4.jsxs)(yn,{className:u4.container,gap:12,children:[i.map((e,t)=>(0,l4.jsx)(f4,{answer:a?.[e.question],index:u?t+1:void 0,question:e},`${e.question}-${t}`)),l&&(0,l4.jsx)(mn,{type:`warning`,children:r(`builtins.lobe-claude-code.askUserQuestion.noAnswer`)})]})}),p4.displayName=`CCAskUserQuestion`})),m4,h4,zje,Bje,g4,_4,v4,y4,Vje,b4,Hje,x4,Uje=e((()=>{Pn(),hn(),Zn(),m4=t(qt()),$$(),h4=t(xt()),zje=bn(({css:e,cssVar:t})=>({row:e`
5518    padding-block: 6px;
5519    padding-inline: 10px;
5520    border: 1px solid ${t.colorBorderSecondary};
5521    border-radius: 8px;
5522  `})),Bje=e=>e?.images?.filter(e=>!!e.url)??[],g4=(0,m4.memo)(({content:e})=>e?(0,h4.jsxs)(yn,{horizontal:!0,align:`center`,className:zje.row,gap:6,children:[(0,h4.jsx)(nr,{size:14}),(0,h4.jsx)(mn,{ellipsis:!0,children:e})]}):null),g4.displayName=`ClaudeCodeBrowserPageRow`,_4=(0,m4.memo)(({content:e})=>(0,h4.jsx)(g4,{content:e})),_4.displayName=`ClaudeCodeBrowserPageAction`,v4=(0,m4.memo)(({content:e,pluginState:t})=>{let n=Bje(t);return n.length===0?e?(0,h4.jsx)(g4,{content:e}):null:(0,h4.jsx)(Sn,{children:(0,h4.jsx)(yn,{gap:8,children:n.map((e,t)=>(0,h4.jsx)(Tn,{style:{alignSelf:`flex-start`,display:`flex`,overflow:`hidden`,padding:0},variant:`outlined`,children:(0,h4.jsx)(En,{alt:`Browser screenshot`,maxHeight:600,src:e.url,style:{maxWidth:`100%`}})},e.fileId||e.url||t))})})}),v4.displayName=`ClaudeCodeBrowserScreenshot`,y4=(0,m4.memo)(({content:e})=>e?(0,h4.jsx)(Mn,{wrap:!0,language:`text`,showLanguage:!1,style:{maxHeight:240,overflow:`auto`},variant:`borderless`,children:e}):null),y4.displayName=`ClaudeCodeBrowserPageDump`,Vje={click:_4,fill:_4,navigate:_4,press:_4,readPage:y4,screenshot:v4,scroll:_4,snapshot:y4},b4=e=>{let t=Y$(e);return t?Vje[t]:void 0},Hje=Object.fromEntries(J$.map(e=>[e,b4(e)])),x4=new Proxy(Hje,{get:(e,t)=>{if(typeof t==`string`)return e[t]||(X$(t)?b4(t):void 0)}})}
5522)),Wje,S4,C4,Gje=e((()=>{Pn(),Br(),Wje=t(qt()),S4=t(xt()),C4=(0,Wje.memo)(({args:e})=>{if(!e)return(0,S4.jsx)(Fn,{active:!0});let t=e.file_path||``,n=t?yr.basename(t):``,r=t?yr.extname(t).slice(1).toLowerCase():``;return(0,S4.jsx)(yn,{gap:12,paddingInline:8,children:(0,S4.jsx)(On,{fileName:n||t,language:r||void 0,newContent:e.new_string??``,oldContent:e.old_string??``,showHeader:!!n,variant:`borderless`,viewMode:`unified`})})}),C4.displayName=`ClaudeCodeEdit`})),Kje,qje,w4,Jje=e((()=>{Pn(),Kje=t(qt()),qje=t(xt()),w4=(0,Kje.memo)(({content:e})=>e?(0,qje.jsx)(Mn,{wrap:!0,language:`text`,showLanguage:!1,style:{maxHeight:240,overflow:`auto`},variant:`borderless`,children:e}):null),w4.displayName=`ClaudeCodeGlob`})),Yje,Xje,T4,Zje=e((()=>{Pn(),Yje=t(qt()),Xje=t(xt()),T4=(0,Yje.memo)(({content:e})=>e?(0,Xje.jsx)(Mn,{wrap:!0,language:`text`,showLanguage:!1,style:{maxHeight:240,overflow:`auto`},variant:`borderless`,children:e}):null),T4.displayName=`ClaudeCodeGrep`})),E4,Qje,D4,$je=e((()=>{r4(),c1(),E4=Z2,Qje=Object.fromEntries(s1.map(e=>[`${yQ}${e}`,E4])),D4=new Proxy(Qje,{get:(e,t)=>{if(typeof t==`string`)return e[t]||(wQ(t)?E4:void 0)}})})),O4,k4,eMe,A4,tMe=e((()=>{Pn(),Br(),O4=t(qt()),k4=t(xt()),eMe=e=>e?e.split(`
5523`).map(e=>e.replace(/^\s*\d+\t/,``)).join(`
5524`):``,A4=(0,O4.memo)(({args:e,content:t,pluginState:n})=>{let r=e?.file_path||``,i=r?yr.extname(r).slice(1).toLowerCase():``,a=(0,O4.useMemo)(()=>n?.images?.filter(e=>!!e.url)??[],[n?.images]),o=(0,O4.useMemo)(()=>eMe(t||``),[t]);return a.length>0?(0,k4.jsx)(Sn,{children:(0,k4.jsx)(yn,{horizontal:!0,gap:8,style:{flexWrap:`wrap`},children:a.map((e,t)=>(0,k4.jsx)(En,{alt:r||e.mediaType||``,maxHeight:600,src:e.url,style:{borderRadius:8}},e.fileId||e.url||t))})}):o?(0,k4.jsx)(Mn,{wrap:!0,language:i||`text`,showLanguage:!1,style:{maxHeight:240,overflow:`auto`},variant:`borderless`,children:o}):null}),A4.displayName=`ClaudeCodeRead`})),nMe,j4,rMe,M4,N4,iMe=e((()=>{Pn(),hn(),Zn(),nMe=t(qt()),a(),j4=t(xt()),rMe=e=>{if(e&&typeof e==`object`)return e;if(!(typeof e!=`string`||!e.trim()))try{return JSON.parse(e)}catch{return}},M4=bn(({css:e,cssVar:t})=>({bodyBox:e`
5525    overflow: hidden;
5526
5527    padding-block: 4px;
5528    padding-inline: 8px;
5529    border-radius: 8px;
5530
5531    background: ${t.colorFillTertiary};
5532  `,container:e`
5533    padding-block: 4px;
5534  `,header:e`
5535    padding-inline: 4px;
5536    color: ${t.colorTextSecondary};
5537  `,status:e`
5538    padding-inline: 4px;
5539  `})),N4=(0,nMe.memo)(({args:e,content:t})=>{let{t:n}=c(`plugin`),r=e?.message??e?.content,i=e?.summary?.trim(),a=rMe(t)?.success===!0;return(0,j4.jsxs)(yn,{className:M4.container,gap:8,children:[(0,j4.jsxs)(yn,{horizontal:!0,align:`center`,className:M4.header,gap:8,children:[(0,j4.jsx)(vn,{icon:G,size:`small`}),(0,j4.jsx)(mn,{ellipsis:!0,strong:!0,children:i||n(`builtins.lobe-claude-code.sendMessage.title`)})]}),r&&(0,j4.jsx)(yn,{className:M4.bodyBox,children:(0,j4.jsx)(Cn,{style:{maxHeight:240,overflow:`auto`},variant:`chat`,children:r})}),a&&(0,j4.jsxs)(yn,{horizontal:!0,align:`center`,className:M4.status,gap:6,children:[(0,j4.jsx)(vn,{icon:er,size:`small`,style:{color:U.colorSuccess}}),(0,j4.jsx)(mn,{style:{color:U.colorTextSecondary,fontSize:12},children:n(`builtins.lobe-claude-code.sendMessage.queued`)})]})]})}),N4.displayName=`ClaudeCodeSendMessage`})),aMe,P4,F4,I4,oMe=e((()=>{Pn(),hn(),Zn(),aMe=t(qt()),P4=t(xt()),F4=bn(({css:e,cssVar:t})=>({container:e`
5540    padding-block: 4px;
5541  `,header:e`
5542    padding-inline: 4px;
5543    color: ${t.colorTextSecondary};
5544  `,previewBox:e`
5545    overflow: hidden;
5546
5547    padding-block: 4px;
5548    padding-inline: 8px;
5549    border-radius: 8px;
5550
5551    background: ${t.colorFillTertiary};
5552  `})),I4=(0,aMe.memo)(({args:e,content:t})=>{let n=e?.skill;return(0,P4.jsxs)(yn,{className:F4.container,gap:8,children:[(0,P4.jsxs)(yn,{horizontal:!0,align:`center`,className:F4.header,gap:8,children:[(0,P4.jsx)(vn,{icon:aee,size:`small`}),(0,P4.jsx)(mn,{strong:!0,children:n||`Skill`})]}),t&&(0,P4.jsx)(yn,{className:F4.previewBox,children:(0,P4.jsx)(Cn,{style:{maxHeight:240,overflow:`auto`},variant:`chat`,children:t})})]})}),I4.displayName=`ClaudeCodeSkill`})),L4,R4,z4,B4,V4,H4,sMe=e((()=>{Pn(),hn(),Zn(),L4=t(qt()),a(),yZ(),R4=t(xt()),z4=bn(({css:e,cssVar:t})=>({header:e`
5553    display: flex;
5554    gap: 8px;
5555    align-items: center;
5556
5557    padding-block: 10px;
5558    padding-inline: 12px;
5559    border-block-end: 1px solid ${t.colorBorderSecondary};
5560
5561    background: ${t.colorFillQuaternary};
5562  `,headerCount:e`
5563    flex-shrink: 0;
5564
5565    padding-block: 2px;
5566    padding-inline: 8px;
5567    border-radius: 999px;
5568
5569    font-family: ${t.fontFamilyCode};
5570    font-size: 12px;
5571    color: ${t.colorTextSecondary};
5572
5573    background: ${t.colorFillTertiary};
5574  `,headerDetail:e`
5575    overflow: hidden;
5576    min-width: 0;
5577    color: ${t.colorText};
5578    text-overflow: ellipsis;
5579  `,headerLabel:e`
5580    overflow: hidden;
5581    display: flex;
5582    flex: 1;
5583    gap: 0;
5584    align-items: center;
5585
5586    min-width: 0;
5587
5588    color: ${t.colorTextSecondary};
5589    text-overflow: ellipsis;
5590    white-space: nowrap;
5591  `,itemRow:e`
5592    width: 100%;
5593    padding-block: 10px;
5594    padding-inline: 12px;
5595    border-block-end: 1px dashed ${t.colorBorderSecondary};
5596
5597    &:last-child {
5598      border-block-end: none;
5599    }
5600  `,processingRow:e`
5601    display: flex;
5602    gap: 7px;
5603    align-items: center;
5604  `,textCompleted:e`
5605    color: ${t.colorTextQuaternary};
5606    text-decoration: line-through;
5607  `,textPending:e`
5608    color: ${t.colorTextSecondary};
5609  `,textProcessing:e`
5610    color: ${t.colorText};
5611  `})),B4=(0,L4.memo)(({item:e})=>{let{status:t,text:n}=e;if(t===`processing`)return(0,R4.jsxs)(`div`,{className:W(z4.itemRow,z4.processingRow),children:[(0,R4.jsx)(vn,{icon:Qn,size:17,style:{color:U.colorInfo}}),(0,R4.jsx)(`span`,{className:z4.textProcessing,children:n})]});let r=t===`completed`;return(0,R4.jsx)(In,{backgroundColor:U.colorSuccess,checked:r,shape:`circle`,style:{borderWidth:1.5,cursor:`default`},classNames:{text:W(z4.textPending,r&&z4.textCompleted),wrapper:z4.itemRow},textProps:{type:r?`secondary`:void 0},children:n})}),B4.displayName=`ClaudeCodeTaskRow`,V4=(0,L4.memo)(({completed:e,total:t,inProgress:n,override:r})=>{let{t:i}=c(`plugin`),a=t>0&&e===t,o=r?.icon??(n?Qn:a?er:tr),s=r?.color??(n?U.colorInfo:a?U.colorSuccess:U.colorTextSecondary),l=r?.label??i(n?`builtins.lobe-claude-code.todoWrite.currentStep`:a?`builtins.lobe-claude-code.todoWrite.allDone`:`builtins.lobe-claude-code.todoWrite.todos`),u=r?r.detail:n?.text;return(0,R4.jsxs)(`div`,{className:z4.header,children:[(0,R4.jsx)(vn,{icon:o,size:16,style:{color:s,flexShrink:0}}),(0,R4.jsxs)(`div`,{className:z4.headerLabel,children:[(0,R4.jsx)(`span`,{children:l}),u&&(0,R4.jsxs)(R4.Fragment,{children:[(0,R4.jsx)(`span`,{children:`: `}),(0,R4.jsx)(`span`,{className:z4.headerDetail,children:u})]})]}),(0,R4.jsxs)(`span`,{className:z4.headerCount,children:[e,`/`,t]})]})}),V4.displayName=`ClaudeCodeTaskHeader`,H4=(0,L4.memo)(({apiName:e,args:t,pluginState:n})=>{let r=n?.todos?.items,{t:i}=c(`plugin`),a=(0,L4.useMemo)(()=>{let e=r??[];return{completed:e.filter(e=>e.status===`completed`).length,inProgress:e.find(e=>e.status===`processing`),total:e.length}},[r]),o=(0,L4.useMemo)(()=>{if(e!==vZ.TaskUpdate)return;let n=t?.status,a=t?.taskId,o=t?.subject,s=o??(a?r?.find(e=>e.id===a)?.text:void 0);if(n)return{...{completed:{color:U.colorSuccess,icon:er,label:i(`builtins.lobe-claude-code.task.updateCompleted`)},deleted:{color:U.colorError,icon:fee,label:i(`builtins.lobe-claude-code.task.updateDeleted`)},in_progress:{color:U.colorInfo,icon:Qn,label:i(`builtins.lobe-claude-code.task.updateInProgress`)},pending:{color:U.colorTextSecondary,icon:yee,label:i(`builtins.lobe-claude-code.task.updatePending`)}}[n],detail:s};if(o)return{color:U.colorTextSecondary,detail:s,icon:tr,label:i(`builtins.lobe-claude-code.task.updateSubject.completed`)}},[e,t,r,i]);return!r||r.length===0?null:(0,R4.jsxs)(Tn,{variant:`outlined`,width:`100%`,children:[(0,R4.jsx)(V4,{completed:a.completed,inProgress:a.inProgress,override:o,total:a.total}),r.map((e,t)=>(0,R4.jsx)(B4,{item:e},t))]})}),H4.displayName=`ClaudeCodeTask`})),U4,W4,G4,K4,q4,J4,cMe=e((()=>{Pn(),hn(),Zn(),U4=t(qt()),a(),W4=t(xt()),G4=bn(({css:e,cssVar:t})=>({header:e`
5612    display: flex;
5613    gap: 8px;
5614    align-items: center;
5615
5616    padding-block: 10px;
5617    padding-inline: 12px;
5618    border-block-end: 1px solid ${t.colorBorderSecondary};
5619
5620    background: ${t.colorFillQuaternary};
5621  `,headerLabel:e`
5622    overflow: hidden;
5623    display: flex;
5624    flex: 1;
5625    gap: 0;
5626    align-items: center;
5627
5628    min-width: 0;
5629
5630    color: ${t.colorTextSecondary};
5631    text-overflow: ellipsis;
5632    white-space: nowrap;
5633  `,headerDetail:e`
5634    overflow: hidden;
5635    min-width: 0;
5636    color: ${t.colorText};
5637    text-overflow: ellipsis;
5638  `,headerCount:e`
5639    flex-shrink: 0;
5640
5641    padding-block: 2px;
5642    padding-inline: 8px;
5643    border-radius: 999px;
5644
5645    font-family: ${t.fontFamilyCode};
5646    font-size: 12px;
5647    color: ${t.colorTextSecondary};
5648
5649    background: ${t.colorFillTertiary};
5650  `,itemRow:e`
5651    width: 100%;
5652    padding-block: 10px;
5653    padding-inline: 12px;
5654    border-block-end: 1px dashed ${t.colorBorderSecondary};
5655
5656    &:last-child {
5657      border-block-end: none;
5658    }
5659  `,processingRow:e`
5660    display: flex;
5661    gap: 7px;
5662    align-items: center;
5663  `,textCompleted:e`
5664    color: ${t.colorTextQuaternary};
5665    text-decoration: line-through;
5666  `,textPending:e`
5667    color: ${t.colorTextSecondary};
5668  `,textProcessing:e`
5669    color: ${t.colorText};
5670  `})),K4=(0,U4.memo)(({item:e})=>{let{status:t,content:n,activeForm:r}=e;if(t===`in_progress`)return(0,W4.jsxs)(`div`,{className:W(G4.itemRow,G4.processingRow),children:[(0,W4.jsx)(vn,{icon:Qn,size:17,style:{color:U.colorInfo}}),(0,W4.jsx)(`span`,{className:G4.textProcessing,children:r||n})]});let i=t===`completed`;return(0,W4.jsx)(In,{backgroundColor:U.colorSuccess,checked:i,shape:`circle`,style:{borderWidth:1.5,cursor:`default`},classNames:{text:W(G4.textPending,i&&G4.textCompleted),wrapper:G4.itemRow},textProps:{type:i?`secondary`:void 0},children:n})}),K4.displayName=`ClaudeCodeTodoRow`,q4=(0,U4.memo)(({completed:e,total:t,inProgress:n})=>{let{t:r}=c(`plugin`),i=t>0&&e===t,a=n?Qn:i?er:tr,o=n?U.colorInfo:i?U.colorSuccess:U.colorTextSecondary,s=r(n?`builtins.lobe-claude-code.todoWrite.currentStep`:i?`builtins.lobe-claude-code.todoWrite.allDone`:`builtins.lobe-claude-code.todoWrite.todos`),l=n?n.activeForm||n.content:void 0;return(0,W4.jsxs)(`div`,{className:G4.header,children:[(0,W4.jsx)(vn,{icon:a,size:16,style:{color:o,flexShrink:0}}),(0,W4.jsxs)(`div`,{className:G4.headerLabel,children:[(0,W4.jsx)(`span`,{children:s}),l&&(0,W4.jsxs)(W4.Fragment,{children:[(0,W4.jsx)(`span`,{children:`: `}),(0,W4.jsx)(`span`,{className:G4.headerDetail,children:l})]})]}),(0,W4.jsxs)(`span`,{className:G4.headerCount,children:[e,`/`,t]})]})}
5670),q4.displayName=`ClaudeCodeTodoHeader`,J4=(0,U4.memo)(({args:e})=>{let t=e?.todos,n=(0,U4.useMemo)(()=>{let e=t??[];return{completed:e.filter(e=>e?.status===`completed`).length,inProgress:e.find(e=>e?.status===`in_progress`),total:e.length}},[t]);return!t||t.length===0?null:(0,W4.jsxs)(Tn,{variant:`outlined`,width:`100%`,children:[(0,W4.jsx)(q4,{completed:n.completed,inProgress:n.inProgress,total:n.total}),t.map((e,t)=>(0,W4.jsx)(K4,{item:e},t))]})}),J4.displayName=`ClaudeCodeTodoWrite`})),lMe,uMe,Y4,dMe=e((()=>{Pn(),lMe=t(qt()),uMe=t(xt()),Y4=(0,lMe.memo)(({content:e})=>e?(0,uMe.jsx)(Cn,{style:{maxHeight:240,overflow:`auto`},variant:`chat`,children:e}):null),Y4.displayName=`ClaudeCodeWebFetch`})),fMe,pMe,X4,mMe=e((()=>{Pn(),fMe=t(qt()),pMe=t(xt()),X4=(0,fMe.memo)(({content:e})=>e?(0,pMe.jsx)(Mn,{wrap:!0,language:`text`,showLanguage:!1,style:{maxHeight:240,overflow:`auto`},variant:`borderless`,children:e}):null),X4.displayName=`ClaudeCodeWebSearch`})),hMe,Z4,Q4,gMe=e((()=>{Pn(),Br(),hMe=t(qt()),Z4=t(xt()),Q4=(0,hMe.memo)(({args:e})=>{if(!e)return(0,Z4.jsx)(Fn,{active:!0});let t=e.file_path||``,n=t?yr.extname(t).slice(1).toLowerCase():``;return e.content?n===`md`||n===`mdx`?(0,Z4.jsx)(Cn,{style:{maxHeight:240,overflow:`auto`},variant:`chat`,children:e.content}):(0,Z4.jsx)(Mn,{wrap:!0,language:n||`text`,showLanguage:!1,style:{maxHeight:240,overflow:`auto`},variant:`borderless`,children:e.content}):null}),Q4.displayName=`ClaudeCodeWrite`})),_Me,vMe,$4,yMe,bMe=e((()=>{yZ(),$$(),c1(),_Me={[vZ.Edit]:`expand`,[vZ.SendMessage]:`expand`,[vZ.TaskList]:`expand`,[vZ.TaskUpdate]:`expand`,[vZ.TodoWrite]:`expand`,[vZ.Write]:`expand`,...Object.fromEntries(s1.map(e=>[`${yQ}${e}`,`expand`]))},vMe=new Proxy(_Me,{get:(e,t)=>{if(typeof t==`string`)return e[t]||(wQ(t)?`expand`:void 0)}}),$4=e=>!!(e?.images)?.some(e=>!!e.url),yMe=(e,t)=>e===vZ.Read&&$4(t)||Y$(e)===`screenshot`&&$4(t)?`expand`:vMe[e]})),xMe,SMe,CMe=e((()=>{r4(),yZ(),Lje(),Rje(),Uje(),Gje(),Jje(),Zje(),$je(),tMe(),iMe(),oMe(),sMe(),cMe(),dMe(),mMe(),gMe(),bMe(),xMe={[vZ.Agent]:s4,[vZ.AskUserQuestion]:p4,[vZ.Bash]:n4,[vZ.Edit]:C4,[vZ.Glob]:w4,[vZ.Grep]:T4,[vZ.Read]:A4,[vZ.SendMessage]:N4,[vZ.Skill]:I4,[vZ.TaskList]:H4,[vZ.TaskUpdate]:H4,[vZ.TodoWrite]:J4,[vZ.WebFetch]:Y4,[vZ.WebSearch]:X4,[vZ.Write]:Q4,...x4,...D4},SMe=new Proxy(xMe,{get:(e,t)=>{if(typeof t==`string`)return t in e?e[t]:x4[t]??D4[t]}})})),e3,t3,n3,r3,wMe=e((()=>{Pn(),hn(),Zn(),e3=t(qt()),a(),bc(),Oi(),t3=t(xt()),n3=bn(({css:e,cssVar:t})=>({container:e`
5671    padding-block: 4px;
5672  `,label:e`
5673    padding-inline-start: 4px;
5674    font-size: 12px;
5675    color: ${t.colorTextTertiary};
5676  `,labelRow:e`
5677    margin-block-end: 4px;
5678  `,openThread:e`
5679    height: 22px;
5680    padding-inline: 6px;
5681    font-size: 12px;
5682  `,promptBox:e`
5683    padding-block: 8px;
5684    padding-inline: 12px;
5685    border-radius: ${t.borderRadiusLG};
5686    background: ${t.colorFillTertiary};
5687  `})),r3=(0,e3.memo)(({args:e,toolCallId:t})=>{let{t:n}=c(`plugin`),{t:r}=c(`chat`),i=e?.prompt?.trim(),a=Z9(e=>t?(Ci.currentTopicThreads(e)??[]).find(e=>e.metadata?.sourceToolCallId===t):void 0),o=Z9(e=>e.openThreadInPortal),s=Z9(e=>e.closeThreadPortal),l=Z9(ki.portalThreadId),u=!!a&&l===a.id,d=(0,e3.useCallback)(()=>{a&&(u?s():o(a.id,a.sourceMessageId))},[a,u,o,s]);return!i&&!a?null:(0,t3.jsx)(yn,{className:n3.container,gap:12,children:i&&(0,t3.jsxs)(yn,{children:[(0,t3.jsxs)(yn,{horizontal:!0,align:`center`,className:n3.labelRow,justify:`space-between`,children:[(0,t3.jsx)(mn,{className:n3.label,children:n(`builtins.lobe-claude-code.agent.instruction`)}),a&&(0,t3.jsx)(Dn,{className:n3.openThread,icon:Un,size:`small`,type:`text`,onClick:d,children:r(u?`thread.closeSubagentThread`:`thread.openSubagentThread`)})]}),(0,t3.jsx)(yn,{className:n3.promptBox,children:(0,t3.jsx)(Cn,{variant:`chat`,children:i})})]})})}),r3.displayName=`ClaudeCodeAgentStreaming`})),TMe,i3,EMe=e((()=>{TMe=t(qt()),i3=e=>({args:t,messageId:n,apiName:r,identifier:i,toolCallId:a})=>(0,TMe.createElement)(e,{apiName:r,args:t,content:null,identifier:i,messageId:n,toolCallId:a})})),DMe,OMe=e((()=>{r4(),yZ(),Gje(),Jje(),Zje(),tMe(),oMe(),cMe(),gMe(),wMe(),EMe(),DMe={[vZ.Agent]:r3,[vZ.Bash]:i3(n4),[vZ.Edit]:i3(C4),[vZ.Glob]:i3(w4),[vZ.Grep]:i3(T4),[vZ.Read]:i3(A4),[vZ.Skill]:i3(I4),[vZ.TodoWrite]:i3(J4),[vZ.Write]:i3(Q4)}})),kMe=e((()=>{yZ(),uDe(),c1(),LAe(),CMe(),OMe(),C$()})),AMe,jMe=e((()=>{AMe={collab_tool_call:`expand`,command_execution:`collapsed`,file_change:`expand`,mcp_tool_call:`expand`,todo_list:`expand`,web_search:`expand`}})),MMe,NMe,PMe,FMe=e((()=>{kMe(),jMe(),MMe=()=>({codex:AMe}),NMe=()=>({[_Z]:yMe}),PMe=(e,t,n)=>{if(!e||!t)return;let r=NMe()[e];return r?r(t,n):MMe()[e]?.[t]}})),a3,IMe,LMe,RMe=e((()=>
5687{Wt(),it(),s(),oa(),pa(),Er(),Ta(),Dr(),BX(),a3=kr(`lobehubSkillStore`),IMe=(e,t,n)=>new LMe(e,t,n),LMe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}callLobehubSkillTool=async e=>{let{provider:t,toolName:n,args:r,topicId:i}=e,a=`${t}:${n}`;this.#t(tt(e=>{e.lobehubSkillExecutingToolIds.add(a)}),!1,a3(`callLobehubSkillTool/start`));try{let e=await fa.market.connectCallTool.mutate({args:r,provider:t,toolName:n,topicId:i});if(this.#t(tt(e=>{e.lobehubSkillExecutingToolIds.delete(a)}),!1,a3(`callLobehubSkillTool/success`)),e.success===!1){let t=e.error,n;return typeof e.data==`string`?n=e.data:e.data!==void 0&&e.data!==null&&(n=JSON.stringify(e.data)),{data:e.data,error:t?.message||n||`LobeHub Skill call failed`,errorCode:t?.code,success:!1}}return{data:e.data,success:!0}}catch(e){console.error(`[LobehubSkill] Failed to call tool:`,e),this.#t(tt(e=>{e.lobehubSkillExecutingToolIds.delete(a)}),!1,a3(`callLobehubSkillTool/error`));let t=e instanceof Error?e.message:String(e);return t.includes(`NOT_CONNECTED`)||t.includes(`TOKEN_EXPIRED`)?{error:t,errorCode:`NOT_CONNECTED`,success:!1}:{error:t,success:!1}}};checkLobehubSkillStatus=async e=>{this.#t(tt(t=>{t.lobehubSkillLoadingIds.add(e)}),!1,a3(`checkLobehubSkillStatus/start`));try{let t=await fa.market.connectGetStatus.query({provider:e}),n=Gt(e),r={cachedAt:Date.now(),icon:t.icon,identifier:e,isConnected:t.connected,name:n?.label||e,providerUsername:t.connection?.providerUsername,scopes:t.connection?.scopes,status:t.connected?zX.CONNECTED:zX.NOT_CONNECTED,tokenExpiresAt:t.connection?.tokenExpiresAt};return this.#t(tt(t=>{let n=t.lobehubSkillServers.findIndex(t=>t.identifier===e);n>=0?t.lobehubSkillServers[n]=r:t.lobehubSkillServers.push(r),t.lobehubSkillLoadingIds.delete(e)}),!1,a3(`checkLobehubSkillStatus/success`)),r.isConnected&&this.#e().refreshLobehubSkillTools(e),r}catch(t){console.error(`[LobehubSkill] Failed to check status:`,t),this.#t(tt(t=>{t.lobehubSkillLoadingIds.delete(e)}),!1,a3(`checkLobehubSkillStatus/error`));return}};getLobehubSkillAuthorizeUrl=async(e,t)=>{let n=await fa.market.connectGetAuthorizeUrl.query({provider:e,redirectUri:t?.redirectUri,scopes:t?.scopes});return{authorizeUrl:n.authorizeUrl,code:n.code,expiresIn:n.expiresIn}};internal_updateLobehubSkillServer=(e,t)=>{this.#t(tt(n=>{let r=n.lobehubSkillServers.findIndex(t=>t.identifier===e);r>=0&&(n.lobehubSkillServers[r]={...n.lobehubSkillServers[r],...t})}),!1,a3(`internal_updateLobehubSkillServer`))};refreshLobehubSkillToken=async e=>{try{let t=await fa.market.connectRefresh.mutate({provider:e});return t.refreshed&&this.#e().internal_updateLobehubSkillServer(e,{status:zX.CONNECTED,tokenExpiresAt:t.connection?.tokenExpiresAt}),t.refreshed}catch(e){return console.error(`[LobehubSkill] Failed to refresh token:`,e),!1}};refreshLobehubSkillTools=async e=>{try{let t=await fa.market.connectListTools.query({provider:e});this.#t(tt(n=>{let r=n.lobehubSkillServers.findIndex(t=>t.identifier===e);r>=0&&(n.lobehubSkillServers[r].tools=t.tools)}),!1,a3(`refreshLobehubSkillTools/success`))}catch(e){console.error(`[LobehubSkill] Failed to refresh tools:`,e)}};revokeLobehubSkill=async e=>{this.#t(tt(t=>{t.lobehubSkillLoadingIds.add(e)}),!1,a3(`revokeLobehubSkill/start`));try{await fa.market.connectRevoke.mutate({provider:e}),this.#t(tt(t=>{t.lobehubSkillServers=t.lobehubSkillServers.filter(t=>t.identifier!==e),t.lobehubSkillLoadingIds.delete(e)}),!1,a3(`revokeLobehubSkill/success`))}catch(t){console.error(`[LobehubSkill] Failed to revoke:`,t),this.#t(tt(t=>{t.lobehubSkillLoadingIds.delete(e)}),!1,a3(`revokeLobehubSkill/error`))}};useFetchLobehubSkillConnections=e=>{let t=Or(gre.isLogin);return m(e&&t?aa.lobehubSkillConnections():null,async()=>(await fa.market.connectListConnections.query()).connections.map(e=>{let t=Gt(e.providerId);return{cachedAt:Date.now(),icon:e.icon,identifier:e.providerId,isConnected:!0,name:t?.label||e.providerId,providerUsername:e.providerUsername,scopes:e.scopes,status:zX.CONNECTED,tokenExpiresAt:e.tokenExpiresAt}}),{onSuccess:e=>{if(e.length>0){this.#t(tt(t=>{let n=new Set(t.lobehubSkillServers.map(e=>e.identifier)),r=e.filter(e=>!n.has(e.identifier));t.lobehubSkillServers=[...t.lobehubSkillServers,...r]}),!1,a3(`useFetchLobehubSkillConnections`));for(let t of e)this.#e().refreshLobehubSkillTools(t.identifier)}},revalidateOnFocus:!1,shouldRetryOnError:!1})};
5687useFetchProviderTools=e=>m(e?aa.lobehubSkillTools(e):null,async()=>((await fa.market.connectListTools.query({provider:e})).tools||[]).map(e=>({description:e.description,inputSchema:e.inputSchema,name:e.name})),{fallbackData:[],revalidateOnFocus:!1})}})),o3=e((()=>{RMe(),bY(),HX(),BX()})),s3,zMe,BMe,c3,VMe,HMe,UMe,WMe,l3,u3=e((()=>{FMe(),Wt(),eX(),FX(),lX(),o3(),BX(),gZ(),s3=e=>{let t=hZ.installedPluginMetaList(e),n=VX.metaList(e);return PX.metaList(e).concat(t).concat(n)},zMe=e=>{let t=hZ.installedPluginMetaList(e),n=VX.metaList(e);return PX.discoverableMetaList(e).concat(t).concat(n)},BMe=e=>t=>{let n=s3(t).find(t=>t.identifier===e);if(n)return n.meta?n.meta:{avatar:n?.avatar,backgroundColor:n?.backgroundColor,description:n?.description,title:n?.title}},c3=e=>t=>hZ.installedPluginManifestList(t).concat(t.builtinTools.map(e=>e.manifest)).find(t=>t.identifier===e),VMe=e=>t=>{let n=c3(e)(t);if(t.pluginInstallLoading[e])return`loading`;if(!n)return`error`;if(n)return`success`},HMe=e=>t=>{let n=c3(e)(t);if(!n)return!1;let r=t.builtinTools.find(t=>t.identifier===e);return r&&r.type===`builtin`?!0:!!n.ui},UMe=(e,t,n)=>r=>r.builtinTools.find(t=>t.identifier===e)?.manifest.api.find(e=>e.name===t)?.renderDisplayControl||(PMe(e,t,n)??`collapsed`),WMe=e=>{let t=new Set((e.builtinSkills||[]).map(e=>e.identifier)),n=new Set((e.agentSkills||[]).map(e=>e.identifier)),r=new Set((e.composioServers||[]).map(e=>e.identifier)),i=new Set((e.lobehubSkillServers||[]).map(e=>e.identifier)),a=e.builtinTools.filter(e=>e.discoverable!==!1).filter(e=>!t.has(e.identifier)).filter(e=>QY(e.identifier)).map(e=>({description:e.description||``,identifier:e.identifier,name:e.title||e.identifier})),o=e.installedPlugins.filter(e=>!r.has(e.identifier)).filter(e=>!i.has(e.identifier)).filter(e=>!n.has(e.identifier)).filter(e=>!e.customParams?.composio).filter(e=>ZY(e)).map(e=>{let t=e.manifest?.meta;return{description:t?.description||``,identifier:e.identifier,name:t?.title||e.identifier}}),s=(e.composioServers||[]).filter(e=>e.status===tX.ACTIVE&&e.tools?.length).map(e=>{let t=zt(e.identifier);return{description:t?.description||``,identifier:e.identifier,name:t?.label||e.label}}),c=(e.lobehubSkillServers||[]).filter(e=>e.status===zX.CONNECTED).map(e=>{let t=Gt(e.identifier);return{description:t?.description||``,identifier:e.identifier,name:t?.label||e.name}});return[...a,...o,...s,...c]},l3={availableToolsForDiscovery:WMe,discoverableMetaList:zMe,getManifestById:c3,getManifestLoadingStatus:VMe,getMetaById:BMe,getRenderDisplayControl:UMe,isToolHasUI:HMe,metaList:s3}})),GMe=n({pluginSelectors:()=>hZ}),d3=e((()=>{NY(),JY(),FX(),cX(),RX(),HX(),nZ(),gZ(),u3()})),f3,KMe,qMe,JMe,YMe,XMe=e((()=>{f3=[`filesystem-read`,`filesystem-write`,`shell-commands`,`code-search`,`multi-step-autonomy`],KMe={amp:{capabilities:f3,description:`Amp — Sourcegraph's autonomous coding agent. Reads, edits and writes files, runs shell commands and works across a real codebase to complete software-engineering tasks.`,displayName:`Amp`,kind:`cli`},"claude-code":{capabilities:f3,description:"Claude Code — Anthropic's autonomous CLI coding agent. It has full access to a working directory: it can read, edit and write files, run shell commands and tests, search the codebase, and carry multi-step software-engineering tasks (bug fixes, feature work, refactors) end to end on its own. It does NOT use the chat `plugins`/`model` settings — it runs its own built-in toolset and model.",displayName:`Claude Code`,kind:`cli`},codex:{capabilities:f3,description:"Codex — OpenAI's autonomous CLI coding agent. It has full access to a working directory: it can read, edit and write files, run shell commands and tests, and complete multi-step software-engineering tasks autonomously. It does NOT use the chat `plugins`/`model` settings — it runs its own built-in toolset and model.",displayName:`Codex`,kind:`cli`},hermes:{capabilities:f3,description:`Hermes — a remote autonomous agent runtime that runs on a connected device and can read, edit and write files and run commands in its workspace.`,displayName:`Hermes`,kind:`remote`},opencode:{capabilities:f3,description:`OpenCode — an open-source terminal co
5687ding agent with filesystem and shell access that completes software-engineering tasks autonomously.`,displayName:`OpenCode`,kind:`cli`},openclaw:{capabilities:f3,description:`OpenClaw — a remote autonomous agent platform. It runs on a connected device with full filesystem and shell access to its workspace.`,displayName:`OpenClaw`,kind:`remote`}},qMe={auto:`auto-selected online device (one is activated automatically; with several the agent picks one)`,device:"a specific device connected via `lh connect`",local:`in-process on the user's desktop`,none:`no execution environment (plain chat)`,sandbox:`a server-spawned cloud sandbox`},JMe=e=>{let t=e?.heterogeneousProvider;if(!t?.type)return;let n=KMe[t.type];if(n)return{boundDeviceId:e?.boundDeviceId,capabilities:n.capabilities,description:n.description,displayName:n.displayName,executionTarget:e?.executionTarget,kind:n.kind,type:t.type}},YMe=e=>{if(!e)return[];let t=[`Runtime: ${e.displayName} (heterogeneous \`${e.type}\` agent — ignores the chat model/plugins settings above)`,e.description];if(e.executionTarget){let n=qMe[e.executionTarget];t.push(`Runs on: ${n}${e.executionTarget===`device`&&e.boundDeviceId?` (deviceId: ${e.boundDeviceId})`:``}`)}return t}})),p3,m3,ZMe=e((()=>{Wt(),Mi(),Ne(),Gr(),ate(),Ba(),f7(),d3(),nX(),BX(),Er(),Ta(),XMe(),p3=20,m3=class e{static promptUpdateQueues=new Map;agentService;discoverService;constructor(e){this.agentService=e.agentService,this.discoverService=e.discoverService}async createAgent(e){try{let t=e=>{if(typeof e==`string`)try{return JSON.parse(e)}catch{return}return e},n={avatar:e.avatar,backgroundColor:e.backgroundColor,description:e.description,model:e.model,openingMessage:e.openingMessage,openingQuestions:t(e.openingQuestions),plugins:t(e.plugins),provider:e.provider,systemRole:e.systemRole,tags:t(e.tags),title:e.title},r=await this.agentService.createAgent({config:n});return{content:`Successfully created agent "${e.title}" with ID: ${r.agentId}`,state:{agentId:r.agentId,success:!0},success:!0}}catch(e){return this.handleError(e,`Failed to create agent`)}}async updateAgentConfig(e,t){try{await this.ensureAgentLoaded(e);let n=Xr(),r=Xr(),i={success:!0},a=[],o=Rr.getAgentConfigById(e)(n),s=t.config;if(typeof s==`string`)try{s=JSON.parse(s)}catch{s=void 0}let c=t.meta;if(typeof c==`string`)try{c=JSON.parse(c)}catch{c=void 0}let l=s?{...s}:{};if(t.togglePlugin){let{pluginId:e,enabled:n}=t.togglePlugin,r=ge(o?.plugins,e)===`pinned`,s=n===void 0?!r:n,c=E(o?.plugins,e,s?`pinned`:`auto`);l={...l,plugins:c},i.togglePlugin={enabled:s,pluginId:e},a.push(`plugin ${e} ${s?`enabled`:`disabled`}`)}if(`systemRole`in l&&!(`editorData`in l)&&(l={...l,editorData:null}),Object.keys(l).length>0){let n=Object.keys(l),s={},c={};for(let e of n)s[e]=o[e],c[e]=l[e];await r.optimisticUpdateAgentConfig(e,l);let u=n.filter(e=>e!==`plugins`);(u.length>0||!t.togglePlugin)&&(i.config={newValues:c,previousValues:s,updatedFields:n},t.togglePlugin?u.length>0&&a.push(`config fields: ${u.join(`, `)}`):a.push(`config fields: ${n.join(`, `)}`))}if(c&&Object.keys(c).length>0){let t=Rr.getAgentMetaById(e)(n),o=Object.keys(c),s={};for(let e of o)s[e]=t[e];await r.optimisticUpdateAgentMeta(e,c),i.meta={newValues:c,previousValues:s,updatedFields:o},a.push(`meta fields: ${o.join(`, `)}`)}return a.length===0?{content:`No fields to update.`,state:{success:!0},success:!0}:{content:`Successfully updated agent. Updated ${a.join(`; `)}`,state:i,success:!0}}catch(e){return this.handleError(e,`Failed to update agent`)}}async deleteAgent(e){try{return await this.agentService.removeAgent(e),{content:`Successfully deleted agent ${e}`,state:{agentId:e,success:!0},success:!0}}catch(e){return this.handleError(e,`Failed to delete agent`)}}async getAgentDetail(e){try{let t=await this.agentService.getAgentConfigById(e);if(!t)return{content:`Agent "${e}" not found.`,success:!1};let n=t,r=JMe(t.agencyConfig),i=t.plugins?.map(e=>{let{identifier:t,mode:n}=re(e);return n===`pinned`?t:`${t} (${n})`}),a={config:{model:t.model,openingMessage:t.openingMessage,openingQuestions:t.openingQuestions,plugins:i,provider:t.provider,...r&&{runtime:r},systemRole:t.systemRole},meta:{avatar:t.avatar,backgroundColor:t.backgroundColor,description:n.description,tags:n.tags,title:t.title}},o=[];return a.meta.title&&o.push(`**${a.meta.title}**`),a.meta.description&&o.push(a.meta.description),a.config.model&&o.push(`Model: ${a.config.provider||``}/${a.config.model}`),a.config.plugins?.length&&o.push(`Plugins: ${a.config.plugins.join(`, `)}`),o.push(...YMe(r)),a.config.systemRole&&o.push(`System Prompt: ${a.config.systemRole}`),{content:o.length>0?o.join(`
5688`):`Agent "${e}" found (no details available).`,state:{agentId:e,config:a.config,meta:a.meta,success:!0},success:!0}}catch(e){return this.handleError(e,`Failed to get agent detail`)}}async duplicateAgent(e,t){try{let n=await this.agentService.duplicateAgent(e,t);return n?{content:`Successfully duplicated agent. New agent ID: ${n.agentId}${t?` with title "${t}"`:``}`,state:{newAgentId:n.agentId,sourceAgentId:e,success:!0},success:!0}:{content:`Failed to duplicate agent "${e}". Agent may not exist.`,success:!1}}catch(e){return this.handleError(e,`Failed to duplicate agent`)}}async searchAgents(e){try{let t=e.source||`all`,n=Math.min(e.limit||10,p3),r=Math.max(e.offset||0,0),i=[],a=0,o=0;if(t===`user`||t===`all`){let[t,o]=await Promise.all([this.agentService.queryAgents({keyword:e.keyword,limit:n,offset:r}),this.agentService.countAgents({keyword:e.keyword})]);a=o,i.push(...t.map(e=>({avatar:e.avatar??void 0,backgroundColor:e.backgroundColor??void 0,description:e.description??void 0,heteroType:e.heteroType,id:e.id,isMarket:!1,title:e.title??void 0})))}if(t===`market`||t===`all`){let t=await this.discoverService.getAssistantList({pageSize:n,q:e.keyword,...e.category&&{category:e.category}});o=t.totalCount??t.items.length,i.push(...t.items.map(e=>({avatar:e.avatar,backgroundColor:e.backgroundColor,description:e.description,id:e.identifier,isMarket:!0,title:e.title})))}let s=i.slice(0,n),c=a+o,l=r+s.filter(e=>!e.isMarket).length<a;return{content:ene({agents:s,hasMore:l,marketTotal:o,maxLimit:p3,offset:r,requestedLimit:e.limit,source:t,userTotal:a}),state:{agents:s,hasMore:l,keyword:e.keyword,offset:r,source:t,totalCount:c},success:!0}}catch(e){return this.handleError(e,`Failed to search agents`)}}async getAvailableModels(e){try{let t=za().enabledChatModelList||[],n=(e.providerId?t.filter(t=>t.id===e.providerId):t).map(e=>({id:e.id,models:e.children.map(e=>({abilities:e.abilities?{files:e.abilities.files,functionCall:e.abilities.functionCall,reasoning:e.abilities.reasoning,vision:e.abilities.vision}:void 0,description:e.description,id:e.id,name:e.displayName||e.id})),name:e.name})),r=n.reduce((e,t)=>
5688e+t.models.length,0),i=fne(n);return{content:`Found ${n.length} provider(s) with ${r} model(s) available.\n\n${i}`,state:{providers:n},success:!0}}catch(e){return this.handleError(e,`Failed to get available models`)}}async updatePrompt(e,t){try{let n=await this.enqueuePromptUpdate(e,async()=>{await this.ensureAgentLoaded(e);let n=Xr(),r=Rr.getAgentConfigById(e)(n);return t.streaming?await this.performStreamingPromptUpdate(e,t.prompt):await Xr().optimisticUpdateAgentConfig(e,{editorData:null,systemRole:t.prompt}),r?.systemRole});return{content:t.prompt?`Successfully updated system prompt (${t.prompt.length} characters)`:`Successfully cleared system prompt`,state:{newPrompt:t.prompt,previousPrompt:n,success:!0},success:!0}}catch(e){return this.handleErrorWithState(e,`Failed to update prompt`,{newPrompt:t.prompt,success:!1})}}async enqueuePromptUpdate(t,n){let r=e.promptUpdateQueues.get(t),i=(r?r.then(()=>void 0,()=>void 0):Promise.resolve()).then(n);e.promptUpdateQueues.set(t,i);try{return await i}finally{e.promptUpdateQueues.get(t)===i&&e.promptUpdateQueues.delete(t)}}async performStreamingPromptUpdate(e,t){let n=Xr().startStreamingSystemRole(e);for(let r=0;r<t.length;r+=5){let i=t.slice(r,r+5);Xr().appendStreamingSystemRole(e,n,i),r+5<t.length&&await new Promise(e=>setTimeout(e,10))}try{await Xr().optimisticUpdateAgentConfig(e,{editorData:null,systemRole:t})}finally{await Xr().finishStreamingSystemRole(e,n)}}async searchMarketTools(e){try{let t=u7(),n=await this.discoverService.getMcpList({category:e.category,pageSize:e.pageSize||10,q:e.query}),r=n.items.map(e=>{let n=hZ.isPluginInstalled(e.identifier)(t);return{author:e.author,cloudEndPoint:e.cloudEndPoint,description:e.description,haveCloudEndpoint:e.haveCloudEndpoint,icon:e.icon,identifier:e.identifier,installed:n,name:e.name,tags:e.tags}}),i=r.filter(e=>e.installed).length,a=r.length-i,o=`Found ${n.totalCount} tool(s) in the marketplace.`;e.query&&(o=`Found ${n.totalCount} tool(s) matching "${e.query}".`),i>0&&(o+=` ${i} already installed, ${a} available to install.`);let s=ane(r);return{content:`${o}\n\n${s}`,state:{query:e.query,tools:r,totalCount:n.totalCount},success:!0}}catch(e){return this.handleError(e,`Failed to search market tools`)}}async installPlugin(e,t){let{identifier:n,source:r}=t;try{let t=u7();if(r===`official`){if(typeof window<`u`&&window.global_serverConfigStore?.getState()?.serverConfig?.enableComposio){let r=sX.getServers(t).find(e=>e.identifier===n),i=Vt.find(e=>e.identifier===n);if(i)return this.handleComposioInstall(e,n,i,r)}if(typeof window<`u`&&window.global_serverConfigStore?.getState()?.serverConfig?.enableLobehubSkill){let r=VX.getServers(t).find(e=>e.identifier===n),i=tn.find(e=>e.id===n);if(i)return this.handleLobehubSkillInstall(e,n,i,r)}let r=PX.metaList(t).find(e=>e.identifier===n);return r?(await this.enablePluginForAgent(e,n),{content:`Successfully enabled builtin tool: ${r.meta?.title||n}`,state:{installed:!0,pluginId:n,pluginName:r.meta?.title||n,success:!0},success:!0}):{content:`Official tool "${n}" not found.`,error:{message:`Tool not found`,type:`NotFound`},state:{installed:!1,pluginId:n,success:!1},success:!1}}return this.handleMarketPluginInstall(e,n)}catch(e){let t=e;return this.handleErrorWithState(e,`Failed to install plugin`,{error:t.message,installed:!1,pluginId:n,success:!1})}}async ensureAgentLoaded(e){if(Xr().agentMap[e])return;let t=await this.agentService.getAgentConfigById(e);t&&Xr().internal_dispatchAgentMap(e,t)}async handleComposioInstall(e,t,n,r){if(r){if(r.status===tX.ACTIVE)return await this.enablePluginForAgent(e,t),{content:`Successfully enabled Composio tool: ${n.label}`,state:{installed:!0,isComposio:!0,pluginId:t,pluginName:n.label,serverStatus:`connected`,success:!0},success:!0};if(r.status===tX.PENDING_AUTH)return r.redirectUrl&&(await this.openOAuthWindowAndWait(r.redirectUrl,t)).success?(await this.enablePluginForAgent(e,t),{content:`Successfully connected and enabled Composio tool: ${n.label}`,state:{installed:!0,isComposio:!0,pluginId:t,pluginName:n.label,serverStatus:`connected`,success:!0},success:!0}):{content:`OAuth authorization was cancelled or failed for Composio tool: ${n.label}. Please try again.`,state:{installed:!1,isComposio:!0,pluginId:t,pluginName:n.label,serverStatus:`pending_auth`,success:!1},success:!1}}if(!ba.userId(_r()))return{content:`Cannot connect Composio tool: User not logged in.`,error:{message:`User not logged in`,type:`AuthRequired`},state:{installed:!1,pluginId:t,success:!1},success:!1};let i=await u7().createComposioConnection({appSlug:n.appSlug,identifier:t,label:n.label});if(i){if(i.status===tX.ACTIVE)return await this.enablePluginForAgent(e,t),await u7().refreshComposioConnectionStatus(i.identifier),{content:`Successfully connected and enabled Composio tool: ${n.label}`,state:{installed:!0,isComposio:!0,pluginId:t,pluginName:n.label,serverStatus:`connected`,success:!0},success:!0};if(i.redirectUrl&&(await this.openOAuthWindowAndWait(i.redirectUrl,i.identifier)).success)return await this.enablePluginForAgent(e,t),{content:`Successfully connected and enabled Composio tool: ${n.label}`,state:{installed:!0,isComposio:!0,pluginId:t,pluginName:n.label,serverStatus:`connected`,success:!0},success:!0}}return{content:`Failed to connect Composio tool: ${n.label}`,error:{message:`Failed to create Composio connection`,type:`ComposioError`},state:{installed:!1,pluginId:t,success:!1},success:!1}}async handleLobehubSkillInstall(e,t,n,r){if(r?.status===zX.CONNECTED)return await this.enablePluginForAgent(e,t),{content:`Successfully enabled LobehubSkill provider: ${n.label}`,state:{installed:!0,isLobehubSkill:!0,pluginId:t,pluginName:n.label,serverStatus:`connected`,success:!0},success:!0};let i=typeof window<`u`&&window.location.protocol.startsWith(`http`)?`${window.location.origin}/oauth/callback/success?provider=${encodeURIComponent(t)}`:void 0,a=await u7().getLobehubSkillAuthorizeUrl(t,{redirectUri:i});return a.authorizeUrl?(await this.openLobehubSkillOAuthWindowAndWait(a.authorizeUrl,t)).success?(await this.enablePluginForAgent(e,t),{content:`Successfully connected and enabled LobehubSkill provider: ${n.label}`,state:{installed:!0,isLobehubSkill:!0,pluginId:t,pluginName:n.label,serverStatus:`connected`,success:!0},success:!0}):{content:`OAuth authorization was cancelled or failed for LobehubSkill provider: ${n.label}. Please try again.`,state:{installed:!1,isLobehubSkill:!0,pluginId:t,pluginName:n.label,serverStatus:`not_connected`,success:!1},success:!1}:{content:`LobehubSkill provider "${n.label}" requires OAuth authorization but no authorization URL is available.`,state:{installed:!1,isLobehubSkill:!0,pluginId:t,pluginName:n.label,serverStatus:`not_connected`,success:!1},success:!1}}async handleMarketPluginInstall(e,t){let n=u7();if(hZ.isPluginInstalled(t)(n)){await this.enablePluginForAgent(e,t);let r=hZ.getInstalledPluginById(t)(n);return{content:`Plugin "${r?.manifest?.meta?.title||t}" is already installed. Enabled for current agent.`,state:{installed:!0,pluginId:t,pluginName:r?.manifest?.meta?.title||t,success:!0},success:!0}}if(await u7().installMCPPlugin(t)){await this.enablePluginForAgent(e,t),await u7().refreshPlugins();let n=u7(),r=hZ.getInstalledPluginById(t)(n);return{content:`Successfully installed and enabled MCP plugin "${r?.manifest?.meta?.title||t}".`,state:{installed:!0,pluginId:t,pluginName:r?.manifest?.meta?.title||t,success:!0},success:!0}}return{content:`Failed to install MCP plugin "${t}". Installation was cancelled or configuration is needed.`,state:{installed:!1,pluginId:t,success:!1},success:!1}}async enablePluginForAgent(e,t){await this.ensureAgentLoaded(e);let n=Xr(),r=Rr.getAgentConfigById(e)(n)?.plugins;
5688ge(r,t)!==`pinned`&&await Xr().optimisticUpdateAgentConfig(e,{plugins:E(r,t,`pinned`)})}openOAuthWindowAndWait(e,t){let n=async()=>{try{await u7().refreshComposioConnectionStatus(t);let e=u7();return sX.getServers(e).find(e=>e.identifier===t)?.status===tX.ACTIVE}catch{return!1}};return new Promise(t=>{let r=null,i=null,a=null,o=!1,s=()=>{a&&clearInterval(a),r&&clearInterval(r),i&&clearTimeout(i)},c=e=>{o||(o=!0,s(),t(e))},l=()=>{r||(r=setInterval(async()=>{await n()&&c({cancelled:!1,success:!0})},1e3),i=setTimeout(()=>c({cancelled:!0,success:!1}),3e5))},u=window.open(e,`_blank`,`width=600,height=700`);u?a=setInterval(async()=>{try{if(u.closed){a&&clearInterval(a);let e=await n();c({cancelled:!e,success:e})}}catch{a&&clearInterval(a),l()}},500):l()})}openLobehubSkillOAuthWindowAndWait(e,t){let n=async()=>{try{return(await u7().checkLobehubSkillStatus(t))?.status===zX.CONNECTED}catch{return!1}};return new Promise(r=>{let i=null,a=null,o=null,s=null,c=!1,l=()=>{o&&clearInterval(o),i&&clearInterval(i),a&&clearTimeout(a),s&&window.removeEventListener(`message`,s)},u=e=>{c||(c=!0,l(),r(e))};s=async e=>{e.origin===window.location.origin&&e.data?.type===`LOBEHUB_SKILL_AUTH_SUCCESS`&&e.data?.provider===t&&u({cancelled:!1,success:(await u7().checkLobehubSkillStatus(t))?.status===zX.CONNECTED})},window.addEventListener(`message`,s);let d=()=>{i||(i=setInterval(async()=>{await n()&&u({cancelled:!1,success:!0})},1e3),a=setTimeout(()=>u({cancelled:!0,success:!1}),3e5))},f=window.open(e,`_blank`,`width=600,height=700`);f?o=setInterval(async()=>{try{if(f.closed){o&&clearInterval(o);let e=await n();u({cancelled:!e,success:e})}}catch{o&&clearInterval(o),d()}},500):d()})}handleError(e,t){let n=e;return{content:`${t}: ${n.message}`,error:{body:e,message:n.message,type:`RuntimeError`},success:!1}}handleErrorWithState(e,t,n){let r=e;return{content:`${t}: ${r.message}`,error:{body:e,message:r.message,type:`RuntimeError`},state:n,success:!1}}}})),QMe=e((()=>{})),h3=e((()=>{ZMe(),XMe(),QMe()})),$Me,g3,eNe,tNe,nNe,rNe=e((()=>{h3(),Ne(),Ie(),dt(),$a(),Gr(),ote(),$Me=new Set([Jr.updateAgentConfig,Jr.updatePrompt,Jr.installPlugin]),g3=new m3({agentService:ht,discoverService:eo}),eNe=e=>me(ve(e)?.agentId),tNe=class extends ye{identifier=Wr;apiEnum=Jr;getAvailableModels=async e=>g3.getAvailableModels(e);searchMarketTools=async e=>g3.searchMarketTools(e);updateConfig=async(e,t)=>{let n=t.agentId;return n?g3.updateAgentConfig(n,e):{content:`No active agent found`,error:{message:`No active agent found`,type:`NoAgentContext`},success:!1}};updatePrompt=async(e,t)=>{let n=t.agentId;return n?g3.updatePrompt(n,{streaming:!0,...e}):{content:`No active agent found`,error:{message:`No active agent found`,type:`NoAgentContext`},success:!1}};installPlugin=async(e,t)=>{let n=t.agentId;return n?g3.installPlugin(n,e):{content:`No active agent found`,error:{message:`No active agent found`,type:`NoAgentContext`},success:!1}};onAfterCall=async({apiName:e,result:t})=>{if(!t.success||!$Me.has(e))return;let n=eNe(t.state);n&&await Xr().internal_refreshAgentConfig(n)}},nNe=new tNe}));async function iNe(e,t,n){switch(vs({boundDeviceId:t.boundDeviceId,heterogeneousProvider:t.heterogeneousProvider,isGatewayMode:t.isGatewayMode,isWorkspaceAgent:t.isWorkspaceAgent,parentRuntime:t.parentRuntime})){case`client`:await n.executeClientAgent({context:{...t.conversationContext,scope:`sub_agent`,subAgentId:e.targetAgentId},inPortalThread:t.inPortalThread,messages:t.messages??[],parentMessageId:e.parentMessageId,parentMessageType:`tool`,parentOperationId:t.parentOperationId});break;case`gateway`:await n.executeGatewayAgent({context:{...t.conversationContext,agentId:e.targetAgentId,scope:`sub_agent`,subAgentId:e.targetAgentId},message:e.instruction,parentOperationId:t.parentOperationId});break;case`hetero`:throw Error(`[dispatchNonHeteroSubAgent] Hetero runtime is not supported for non-hetero sub-agent dispatch. kind=${e.kind}, targetAgentId=${e.targetAgentId}`)}}var aNe=e((()=>{ys()})),_3,oNe,sNe,cNe=e((()=>{h3(),Ne(),dt(),$a(),Gr(),qr(),bc(),aNe(),di(),wi(),$s(),_3=new m3({agentService:ht,discoverService:eo}),oNe=class extends ye{identifier=Zs;apiEnum=Qs;createAgent=async e=>_3.createAgent(e);updateAgent=async e=>{let{agentId:t}=e,{config:n,meta:r}=e;if(typeof n==`string`)try{n=JSON.parse(n)}catch{}if(typeof r==`string`)try{r=JSON.parse(r)}catch{}return _3.updateAgentConfig(t,{config:n,meta:r})};deleteAgent=async e=>_3.deleteAgent(e.agentId);getAgentDetail=async e=>_3.getAgentDetail(e.agentId);duplicateAgent=async e=>_3.duplicateAgent(e.agentId,e.newTitle);updatePrompt=async e=>_3.updatePrompt(e.agentId,{prompt:e.prompt});installPlugin=async e=>_3.installPlugin(e.agentId,{identifier:e.identifier,source:e.source});searchAgent=async e=>_3.searchAgents(e);callAgent=async(e,t)=>{let{agentId:n,instruction:r,runAsTask:i,taskTitle:a,timeout:o,skipCallSupervisor:s=!1}=e;if(i){if(!jr.getState().agentMap[n])try{let e=await ht.getAgentConfigById(n);if(!e)return{content:`Agent "${n}" not found in your workspace. Please check the agent ID and try again.`,success:!1};jr.getState().internal_dispatchAgentMap(n,e)}catch(e){return console.error(`[callAgent] Failed to load agent config:`,e),{content:`Failed to load agent "${n}": ${e.message}`,success:!1}}return{content:`🚀 Triggered async task to call agent "${n}"${a?`: ${a}`:``}`,state:{parentMessageId:t.messageId,task:{description:a||`Call agent ${n}`,instruction:r,targetAgentId:n,timeout:o||18e5},type:`execSubAgent`},stop:!0,success:!0}}if(t.groupId&&t.groupOrchestration&&t.agentId&&t.registerAfterCompletion)return t.registerAfterCompletion(()=>t.groupOrchestration.triggerSpeak({agentId:n,instruction:r,skipCallSupervisor:s,supervisorAgentId:t.agentId})),{content:`Triggered agent "${n}" to respond.`,state:{agentId:n,instruction:r,mode:`speak`,skipCallSupervisor:s},stop:!0,success:!0};if(t.registerAfterCompletion){if(!jr.getState().agentMap[n])try{let e=await ht.getAgentConfigById(n);if(!e)return{content:`Agent "${n}" not found in your workspace. Please check the agent ID and try again.`,success:!1};jr.getState().internal_dispatchAgentMap(n,e)}catch(e){return console.error(`[callAgent] Failed to load agent config:`,e),{content:`Failed to load agent "${n}": ${e.message}`,success:!1}}return t.registerAfterCompletion(async()=>{let e=Z9.getState,i={agentId:t.agentId||``,topicId:t.topicId||null},a=li(i),o=ci.getDbMessagesByKey(a)(e());if(o.length===0){console.error(`[callAgent] No messages found in current conversation`);return}let s=Date.now(),c=r?[...o,{content:`<speaker name="Supervisor" />\n${r}`,createdAt:s,id:`virtual_speak_instruction_${s}`,role:`user`,updatedAt:s}]:o,l=i.agentId?Rr.getAgentConfigById(i.agentId)(Xr()):void 0;try{await iNe({kind:`callAgent`,targetAgentId:n,instruction:r,parentMessageId:t.messageId},{conversationContext:i,heterogeneousProvider:l?.agencyConfig?.heterogeneousProvider,isGatewayMode:e().isGatewayModeEnabled(),messages:c},e())}catch(e){throw console.error(`[callAgent] dispatchNonHeteroSubAgent failed:`,e),e}}),{content:`Called agent "${n}" to respond.`,state:{agentId:n,instruction:r,mode:`speak`,skipCallSupervisor:s},stop:!0,success:!0}}return console.warn(`[callAgent] registerAfterCompletion not available in context`),{content:`Called agent "${n}" but execution may not complete properly.`,state:{agentId:n,instruction:r,mode:`speak`,skipCallSupervisor:s},stop:!0,success:!1}}},sNe=new oNe})),lNe,v3,uNe,dNe,fNe=e((()=>{Ne(),rl(),Pe(),lNe={click:`click`,fill:`fill`,navigate:`navigate`,press:`press`,readPage:`readPage`,screenshot:`screenshot`,scroll:`scroll`,snapshot:`snapshot`},v3=e=>new Promise(t=>setTimeout(t,e)),uNe=class extends ye{identifier=tl;apiEnum=lNe;async labDisabledFailure(){let[{useUserStore:e},{labPreferSelectors:t}]=await Promise.all([Ge(()=>import(`./agent-Dh3-_0ai.js`).then(e=>(e.Wn(),e.Gn)),__vite__mapDeps([10,1,9,3,11,12,13,14,15,16,17,18,7,19,20,21,22,5,23,2,24,25,26,27,28])),Ge(()=>import(`./selectors-BZArZxfP.js`).then(e=>(e.t(),e.n)),__vite__mapDeps([24,1,9,3,14]))]);if(!t.enableInAppBrowser(e.getState()))return this.failure(`The in-app browser is disabled. Ask the user to enable "In-App Browser" under Settings → Advanced → Labs, then retry.`)}navigate=async(e,t)=>{try{let n=await this.labDisabledFailure();if(n)return n;let r=this.sessionIdOf(t),{electronBrowserSidebarService:i}=await Ge(async()=>{let{electronBrowserSidebarService:e}=await import(`./browserSidebar-B9OBh1GV.js`);return{electronBrowserSidebarService:e}},__vite__mapDeps([31,1,2,3]));await this.revealBrowserTab(t);let a=await i.navigate({sessionId:r,url:e.url});if(!a.success)return this.failure(a.error??`Navigation failed`);await this.waitForLoad(r);let o=await i.getState({sessionId:r});return this.success(`Opened ${o.url}${o.title?` — "${o.title}"`:``}`,{title:o.title,url:o.url})}catch(e){return this.errorResult(e)}};snapshot=async(e,t)=>{try{let e=await this.labDisabledFailure();if(e)return e;let{electronBrowserControlService:n}=await Ge(async()=>{let{electronBrowserControlService:e}=await import(`./browserControl-BCZ4UGPM.js`).then(e=>(e.r(),e.t));return{electronBrowserControlService:e}},__vite__mapDeps([32,1,2,3])),r=await n.snapshot({sessionId:this.sessionIdOf(t)});if(!r.success||!r.snapshot)return this.failure(r.error??`Snapshot failed`);let i=`Page: ${r.title??``} (${r.url??``})`;return this.success(`${i}\n${r.snapshot}`,{snapshot:r.snapshot,title:r.title,url:r.url})}catch(e){return this.errorResult(e)}};click=async(e,t)=>{try{let n=await this.labDisabledFailure();if(n)return n;await this.revealBrowserTab(t);let{electronBrowserControlService:r}=await Ge(async()=>{let{electronBrowserControlService:e}=await import(`./browserControl-BCZ4UGPM.js`).then(e=>(e.r(),e.t));return{electronBrowserControlService:e}},__vite__mapDeps([32,1,2,3])),i=await r.click({ref:e.ref,sessionId:this.sessionIdOf(t),x:e.x,y:e.y});return i.success?this.success(`Clicked${e.ref?` ${e.ref}`:``}. Now at ${i.url}${i.title?` — "${i.title}"`:``}. Take a new snapshot if the page changed.`,{title:i.title,url:i.url}):this.failure(i.error??`Click failed`)}catch(e){return this.errorResult(e)}};fill=async(e,t)=>{try{let n=await this.labDisabledFailure();if(n)return n;await this.revealBrowserTab(t);let{electronBrowserControlService:r}=await Ge(async()=>{let{electronBrowserControlService:e}=await import(`./browserControl-BCZ4UGPM.js`).then(e=>(e.r(),e.t));return{electronBrowserControlService:e}},__vite__mapDeps([32,1,2,3])),i=await r.fill({ref:e.ref,sessionId:this.sessionIdOf(t),submit:e.submit,text:e.text});return i.success?this.success(`Filled ${e.ref} with "${e.text}"${e.submit?` and pressed Enter`:``}.`):this.failure(i.error??`Fill failed`)}catch(e){return this.errorResult(e)}};press=async(e,t)=>{try{let n=await this.labDisabledFailure();if(n)return n;let{electronBrowserControlService:r}=await Ge(async()=>{let{electronBrowserControlService:e}=await import(`./browserControl-BCZ4UGPM.js`).then(e=>(e.r(),e.t));return{electronBrowserControlService:e}},__vite__mapDeps([32,1,2,3])),i=await r.press({key:e.key,sessionId:this.sessionIdOf(t)});return i.success?this.success(`Pressed ${e.key}.`):this.failure(i.error??`Key press failed`)}catch(e){return this.errorResult(e)}};scroll=async(e,t)=>{try{let n=await this.labDisabledFailure();if(n)return n;let{electronBrowserControlService:r}=await Ge(async()=>{let{electronBrowserControlService:e}=await import(`./browserControl-BCZ4UGPM.js`).then(e=>(e.r(),e.t));return{electronBrowserControlService:e}},__vite__mapDeps([32,1,2,3])),i=await r.scroll({dx:e.dx,dy:e.dy,sessionId:this.sessionIdOf(t)});return i.success?this.success(`Scrolled by ${e.dy}px.`):this.failure(i.error??`Scroll failed`)}catch(e){return this.errorResult(e)}};screenshot=async(e,t)=>{try{let e=await this.labDisabledFailure();if(e)return e;await this.revealBrowserTab(t);let{electronBrowserControlService:n}=await Ge(async()=>{let{electronBrowserControlService:e}=await import(`./browserControl-BCZ4UGPM.js`).then(e=>(e.r(),e.t));return{electronBrowserControlService:e}},__vite__mapDeps([32,1,2,3])),r=await n.screenshot({sessionId:this.sessionIdOf(t)});return!r.success||!r.dataUrl?this.failure(r.error??`Screenshot failed`):this.success(`Screenshot captured (${r.width}×${r.height}) and shown to the user.`,{dataUrl:r.dataUrl,height:r.height,width:r.width})}catch(e){return this.errorResult(e)}};readPage=async(e,t)=>{try{let e=await this.labDisabledFailure();if(e)return e;let{electronBrowserControlService:n}=await Ge(async()=>{let{electronBrowserControlService:e}=await import(`./browserControl-BCZ4UGPM.js`).then(e=>(e.r(),e.t));return{electronBrowserControlService:e}},__vite__mapDeps([32,1,2,3])),r=await n.readPage({sessionId:this.sessionIdOf(t)});return r.success?this.success(`Page: ${r.title??``} (${r.url??``})\n${r.content??``}`,{content:r.content??``,title:r.title,url:r.url}):this.failure(r.error??`Read page failed`)}catch(e){return this.errorResult(e)}};sessionIdOf(e){if(!e?.topicId)throw Error(`Browser tool requires a topic context`);
5688return`topic:${e.topicId}`}async revealBrowserTab(e){let[{useAgentStore:t},{useChatStore:n},{useGlobalStore:r}]=await Promise.all([Ge(()=>import(`./agent-Dh3-_0ai.js`).then(e=>(e.n(),e.t)),__vite__mapDeps([10,1,9,3,11,12,13,14,15,16,17,18,7,19,20,21,22,5,23,2,24,25,26,27,28])),Ge(()=>Promise.resolve().then(()=>(bc(),yc)),void 0),Ge(()=>import(`./global-DfKpeTkj.js`).then(e=>(e.n(),e.t)),__vite__mapDeps([33,1,9,3,10,11,12,13,14,15,16,17,18,7,19,20,21,22,5,23,2,24,25,26,27,28,34]))]);if(!e?.agentId||t.getState().activeAgentId!==e.agentId||!e.topicId||n.getState().activeTopicId!==e.topicId)return;let i=r.getState();i.toggleRightPanel(!0),i.setWorkingSidebarTab(`browser`)}async waitForLoad(e,t=8e3){let{electronBrowserSidebarService:n}=await Ge(async()=>{let{electronBrowserSidebarService:e}=await import(`./browserSidebar-B9OBh1GV.js`);return{electronBrowserSidebarService:e}},__vite__mapDeps([31,1,2,3])),r=Date.now()+t;for(await v3(500);Date.now()<r;){if(!(await n.getState({sessionId:e})).isLoading)return;await v3(300)}}success(e,t){return{content:e,state:t,success:!0}}failure(e){return{content:e,error:{message:e,type:`PluginServerError`},success:!1}}errorResult(e){let t=e.message;return{content:t,error:{body:e,message:t,type:`PluginServerError`},success:!1}}},dNe=new uNe})),pNe,y3,mNe=e((()=>{pa(),pNe=class{async callTool(e,t,n){let r={params:t,toolName:e,topicId:n.topicId,userId:n.userId};return fa.market.execInSandbox.mutate(r)}async exportAndUploadFile(e,t,n){let r={filename:t,path:e,topicId:n};return fa.market.exportAndUploadFile.mutate(r)}},y3=new pNe})),hNe,gNe,_Ne,vNe=e((()=>{Ne(),mNe(),Er(),ya(),_G(),MG(),kG(),hNe=class{topicId;userId;constructor(e){this.topicId=e;let t=ba.userId(Or.getState());if(!t)throw Error(`userId must be provided`);this.userId=t}async callTool(e,t){return y3.callTool(e,t,{topicId:this.topicId,userId:this.userId})}async exportAndUploadFile(e,t){return y3.exportAndUploadFile(e,t,this.topicId)}},gNe=class extends ye{identifier=AG;apiEnum=DG;getRuntime(e){let t=e.topicId;if(!t)throw Error(`Can not init runtime with empty topicId`);return new gG(new hNe(t))}listFiles=async(e,t)=>{let n=await this.getRuntime(t).listFiles(e);return this.toBuiltinResult(n)};readFile=async(e,t)=>{let n=await this.getRuntime(t).readFile(e);return this.toBuiltinResult(n)};writeFile=async(e,t)=>{let n=await this.getRuntime(t).writeFile(e);return this.toBuiltinResult(n)};editFile=async(e,t)=>{let n=await this.getRuntime(t).editFile(e);return this.toBuiltinResult(n)};searchFiles=async(e,t)=>{let n=await this.getRuntime(t).searchFiles(e);return this.toBuiltinResult(n)};moveFiles=async(e,t)=>{let n=await this.getRuntime(t).moveFiles(e);return this.toBuiltinResult(n)};executeCode=async(e,t)=>{let n=await this.getRuntime(t).executeCode(e);return this.toBuiltinResult(n)};runCommand=async(e,t)=>{let n=await this.getRuntime(t).runCommand(e);return this.toBuiltinResult(n)};getCommandOutput=async(e,t)=>{let n=await this.getRuntime(t).getCommandOutput(e);return this.toBuiltinResult(n)};killCommand=async(e,t)=>{let n=await this.getRuntime(t).killCommand(e);return this.toBuiltinResult(n)};grepContent=async(e,t)=>{let n=await this.getRuntime(t).grepContent(e);return this.toBuiltinResult(n)};globFiles=async(e,t)=>{let n=await this.getRuntime(t).globFiles(e);return this.toBuiltinResult(n)};exportFile=async(e,t)=>{let n=await this.getRuntime(t).exportFile(e);return this.toBuiltinResult(n)};toBuiltinResult(e){return e.success?{content:e.content,state:e.state,success:!0}:{content:e.content,error:{body:e.error,message:e.content||`Unknown error`,type:`PluginServerError`},state:e.state,success:!1}}},_Ne=new gNe})),yNe,b3,bNe,xNe,SNe=e((()=>{Wt(),Ne(),yNe=t(F(),1),pa(),f7(),d3(),nX(),Er(),ya(),YG(),LG(),b3=(0,yNe.default)(`lobe-creds:executor`),bNe=class extends ye{identifier=qG;apiEnum=PG;connectComposioService=async(e,t)=>{try{let{service:t}=e,n=zt(t);if(!n)return{error:{message:`Unknown Composio service: "${t}". Check the available Composio services list in the credentials context.`,type:`UnknownService`},success:!1};let r=u7();if(sX.getServerByIdentifier(t)(r)?.status===tX.ACTIVE)return{content:`Already connected to ${n.label}. You can use ${n.label} tools directly.`,state:{connected:!0,identifier:t,serviceName:n.label},success:!0};b3(`[CredsExecutor] connectComposioService - creating connection for:`,t);let i=await l7.getState().createComposioConnection({appSlug:n.appSlug,identifier:n.identifier,label:n.label});return i?i.status===tX.ACTIVE?{content:`Successfully connected to ${n.label}! You can now use ${n.label} tools.`,state:{connected:!0,identifier:t,serviceName:n.label},success:!0}:i.redirectUrl?{content:`To connect ${n.label}, ask the user to open this authorization link and complete the sign-in:\n\n${i.redirectUrl}\n\nOnce they have authorized, ${n.label} tools will be ready to use.`,state:{connected:!1,identifier:t,redirectUrl:i.redirectUrl,serviceName:n.label},success:!0}:{error:{message:`Unexpected server state: no redirectUrl and not active`,type:`UnexpectedState`},success:!1}:{error:{message:`Failed to create Composio connection for ${n.label}`,type:`CreateServerFailed`},success:!1}}catch(e){return b3(`[CredsExecutor] connectComposioService - error:`,e),{error:{message:e instanceof Error?e.message:`Failed to connect Composio service`,type:`ConnectComposioFailed`},success:!1}}};initiateOAuthConnect=async(e,t)=>{try{let{provider:t}=e,n=Gt(t);if(!n)return{error:{message:`Unknown OAuth provider: ${t}. Available providers: ${IG}`,type:`UnknownProvider`},success:!1};if((await fa.market.connectGetStatus.query({provider:t})).connected)return{content:`You are already connected to ${n.label}. The credential is available for use.`,state:{alreadyConnected:!0,providerName:n.label},success:!0};let r=typeof window<`u`&&window.location.protocol.startsWith(`http`)?`${window.location.origin}/oauth/callback/success?provider=${t}`:void 0,i=await fa.market.connectGetAuthorizeUrl.query({provider:t,redirectUri:r}),a=await this.openOAuthPopupAndWait(i.authorizeUrl,t);return a.success?{content:`Successfully connected to ${n.label}! The credential is now available for use.`,state:{connected:!0,providerName:n.label},success:!0}:{content:a.cancelled?`Authorization was cancelled. You can try again when you're ready to connect to ${n.label}.`:`Failed to connect to ${n.label}. Please try again.`,state:{cancelled:a.cancelled,connected:!1,providerName:n.label},success:!0}}catch(e){return{error:{message:e instanceof Error?e.message:`Failed to initiate OAuth connection`,type:`InitiateOAuthFailed`},success:!1}}};openOAuthPopupAndWait=(e,t)=>
5688new Promise(n=>{let r=window.open(e,`_blank`,`width=600,height=700`);if(!r){n({cancelled:!0,success:!1});return}let i=!1,a=()=>{i||(i=!0,window.removeEventListener(`message`,o),s&&clearInterval(s))},o=async e=>{e.origin===window.location.origin&&e.data?.type===`LOBEHUB_SKILL_AUTH_SUCCESS`&&e.data?.provider===t&&(a(),n({success:!0}))};window.addEventListener(`message`,o);let s=setInterval(async()=>{if(r.closed){if(clearInterval(s),i)return;try{let e=await fa.market.connectGetStatus.query({provider:t});a(),n({success:e.connected})}catch{a(),n({cancelled:!0,success:!1})}}},500);setTimeout(()=>{i||(a(),r.closed||r.close(),n({cancelled:!0,success:!1}))},300*1e3)});injectCredsToSandbox=async(e,t)=>{try{let n=t?.topicId;if(!n)return{content:`Cannot inject credentials: topicId is not available in the current context.`,error:{message:`topicId is required but not available`,type:`MissingTopicId`},success:!1};let r=ba.userId(Or.getState());if(!r)return{content:`Cannot inject credentials: user is not authenticated.`,error:{message:`userId is required but not available`,type:`MissingUserId`},success:!1};b3(`[CredsExecutor] injectCredsToSandbox - keys:`,e.keys,`topicId:`,n);let i=await q.market.creds.inject.mutate({keys:e.keys,sandbox:!0,topicId:n,userId:r}),a=i.credentials||{},o=i.notFound||[],s=i.unsupportedInSandbox||[];b3(`[CredsExecutor] injectCredsToSandbox - result:`,{envKeys:Object.keys(a.env||{}),filesCount:a.files?.length||0,notFound:o,unsupportedInSandbox:s});let c=e.keys.filter(e=>!o.includes(e)),l=``;return c.length>0&&(l=`Credentials injected successfully: ${c.join(`, `)}.`),o.length>0&&(l+=` Not found: ${o.join(`, `)}. Please configure them in Settings > Credentials.`),s.length>0&&(l+=` Not supported in sandbox: ${s.join(`, `)}.`),{content:l.trim(),state:{credentials:a,injected:c,notFound:o,success:o.length===0,unsupportedInSandbox:s},success:!0}}catch(e){return b3(`[CredsExecutor] injectCredsToSandbox - error:`,e),{content:`Failed to inject credentials: ${e instanceof Error?e.message:`Unknown error`}`,error:{message:e instanceof Error?e.message:`Failed to inject credentials`,type:`InjectCredentialsFailed`},success:!1}}};saveCreds=async(e,t)=>{try{let t=e,n=e.name||t.displayName||e.key,r=e.values;if(!r&&typeof t.value==`string`){r={};for(let e of t.value.split(`
5689`)){let t=e.indexOf(`=`);t>0&&(r[e.slice(0,t).trim()]=e.slice(t+1).trim())}}return!r||Object.keys(r).length===0?{content:`Failed to save credential: values must be a non-empty object of key-value pairs (e.g., { "API_KEY": "sk-xxx" }).`,error:{message:`values is empty or missing. Provide key-value pairs, not a raw string.`,type:`InvalidParams`},success:!1}:(b3(`[CredsExecutor] saveCreds - key:`,e.key,`name:`,n),await q.market.creds.createKV.mutate({description:e.description,key:e.key,name:n,type:e.type,values:r}),{content:`Credential "${n}" saved successfully with key "${e.key}"`,state:{key:e.key,message:`Credential "${n}" saved successfully`,success:!0},success:!0})}catch(e){return b3(`[CredsExecutor] saveCreds - error:`,e),{content:`Failed to save credential: ${e instanceof Error?e.message:`Unknown error`}`,error:{message:e instanceof Error?e.message:`Failed to save credential`,type:`SaveCredentialFailed`},success:!1}}}},xNe=new bNe})),CNe,x3,S3=e((()=>{pa(),CNe=class{getGroupByForkedFromIdentifier=async e=>q.group.getGroupByForkedFromIdentifier.query({forkedFromIdentifier:e});createGroup=e=>q.group.createGroup.mutate({...e,config:e.config});createGroupWithMembers=(e,t,n)=>q.group.createGroupWithMembers.mutate({groupConfig:{...e,config:e.config},members:t,supervisorConfig:n});updateGroup=(e,t)=>q.group.updateGroup.mutate({id:e,value:{...t,config:t.config}});deleteGroup=e=>q.group.deleteGroup.mutate({id:e});getGroup=e=>q.group.getGroup.query({id:e});getGroupDetail=e=>q.group.getGroupDetail.query({id:e});getGroups=()=>q.group.getGroups.query();addAgentsToGroup=(e,t)=>q.group.addAgentsToGroup.mutate({agentIds:t,groupId:e});batchCreateAgentsInGroup=(e,t)=>q.group.batchCreateAgentsInGroup.mutate({agents:t,groupId:e});removeAgentsFromGroup=(e,t)=>q.group.removeAgentsFromGroup.mutate({agentIds:t,groupId:e});updateAgentInGroup=(e,t,n)=>q.group.updateAgentInGroup.mutate({agentId:t,groupId:e,updates:{order:n.order===null?void 0:n.order,role:n.role===null?void 0:n.role}});getGroupAgents=e=>q.group.getGroupAgents.query({groupId:e});duplicateGroup=(e,t)=>q.group.duplicateGroup.mutate({groupId:e,newTitle:t});transferGroup=(e,t,n,r)=>q.group.transferGroup.mutate({groupId:e,targetAccessLevel:r,targetVisibility:n,targetWorkspaceId:t})},x3=new CNe})),C3,w3=e((()=>{C3={activeThreadAgentId:``,groupMap:{},groupNotFoundMap:{},groups:[],groupsInit:!1,showGroupSetting:!1,streamingSystemPrompt:void 0,streamingSystemPromptInProgress:!1}})),T3,E3,wNe=e((()=>{it(),T3=e=>({...e,agents:[]}),E3={addGroup:(e,{payload:t})=>tt(e,e=>{e.groups.push(t),e.groupMap[t.id]=T3(t)}),deleteGroup:(e,{payload:t})=>tt(e,e=>{e.groups=e.groups.filter(e=>e.id!==t),delete e.groupMap[t]}),loadGroups:(e,{payload:t})=>tt(e,n=>{n.groups=t;let r=e.groupMap;n.groupMap=t.reduce((e,t)=>
5689{let n=r[t.id];return e[t.id]=n?{...n,...t}:T3(t),e},{})}),updateGroup:(e,{payload:t})=>tt(e,e=>{if(e.groupMap[t.id]){Object.assign(e.groupMap[t.id],t.value);let n=e.groups.findIndex(e=>e.id===t.id);n!==-1&&Object.assign(e.groups[n],t.value)}})}})),D3,O3,TNe,k3,A3,ENe,DNe,ONe,kNe,ANe,jNe,MNe,NNe,j3,PNe=e((()=>{Wt(),Qt(),Te(),D3=e=>t=>t.groupMap[e],O3=e=>t=>Ce(Ct,D3(e)(t)?.config||{}),TNe=e=>t=>{let n=D3(e)(t);return Ce(rn,{avatar:n?.avatar||void 0,backgroundColor:n?.backgroundColor||void 0,description:n?.description||``,marketIdentifier:n?.marketIdentifier||void 0,title:n?.title||``})},k3=e=>t=>D3(e)(t)?.agents||[],A3=e=>t=>(D3(e)(t)?.agents||[]).filter(e=>!e.isSupervisor),ENe=e=>t=>A3(e)(t).map(e=>({avatar:e.avatar||`/avatars/agent-default.png`,background:e.backgroundColor||void 0})),DNe=e=>t=>O3(e)(t)?.openingMessage,ONe=e=>t=>O3(e)(t)?.openingQuestions||[],kNe=e=>t=>k3(e)(t).length,ANe=e=>t=>A3(e)(t).length,jNe=(e,t)=>n=>k3(e)(n).find(e=>e.id===t),MNe=e=>t=>Object.values(t.groupMap).find(t=>t.supervisorAgentId===e),NNe=e=>t=>!!e&&!!t.groupNotFoundMap[e],j3={agentByIdFromGroup:jNe,groupAgentCount:kNe,groupAgents:k3,groupById:D3,groupBySupervisorAgentId:MNe,groupConfig:O3,groupMemberAvatars:ENe,groupMemberCount:ANe,groupMembers:A3,groupMeta:TNe,groupOpeningMessage:DNe,groupOpeningQuestions:ONe,isGroupNotFoundById:NNe}})),FNe,INe,LNe,RNe,zNe,BNe=e((()=>{FNe=e=>e.activeGroupId,INe=e=>Object.values(e.groupMap),LNe=e=>!e.activeGroupId||!e.groupMap[e.activeGroupId],RNe=e=>e.groupsInit,zNe={activeGroupId:FNe,getAllGroups:INe,isGroupsInit:LNe,isGroupsInitialized:RNe}})),M3,N3=e((()=>{PNe(),BNe(),M3={...zNe,getAgentByIdFromGroup:j3.agentByIdFromGroup,getGroupAgentCount:j3.groupAgentCount,getGroupAgents:j3.groupAgents,getGroupById:j3.groupById,getGroupBySupervisorAgentId:j3.groupBySupervisorAgentId,getGroupConfig:j3.groupConfig,getGroupMemberAvatars:j3.groupMemberAvatars,getGroupMemberCount:j3.groupMemberCount,getGroupMembers:j3.groupMembers,getGroupMeta:j3.groupMeta,getGroupOpeningMessage:j3.groupOpeningMessage,getGroupOpeningQuestions:j3.groupOpeningQuestions}})),VNe,HNe=e((()=>{Qt(),S3(),N3(),VNe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}appendStreamingSystemPrompt=e=>{let t=this.#e().streamingSystemPrompt||``;this.#t({streamingSystemPrompt:t+e},!1,`appendStreamingSystemPrompt`)};finishStreamingSystemPrompt=async()=>{let{streamingSystemPrompt:e}=this.#e();if(!e){this.#t({streamingSystemPromptInProgress:!1},!1,`finishStreamingSystemPrompt`);return}await this.updateGroupConfig({systemPrompt:e}),this.#t({streamingSystemPrompt:void 0,streamingSystemPromptInProgress:!1},!1,`finishStreamingSystemPrompt`)};startStreamingSystemPrompt=()=>{this.#t({streamingSystemPrompt:``,streamingSystemPromptInProgress:!0},!1,`startStreamingSystemPrompt`)};updateGroup=async(e,t)=>{await x3.updateGroup(e,t),this.#e().internal_dispatchChatGroup({payload:{id:e,value:t},type:`updateGroup`}),await this.#e().refreshGroupDetail(e)};updateGroupConfig=async e=>{let t=this.#e(),n=t.activeGroupId?M3.getGroupById(t.activeGroupId)(t):void 0;if(!n)return;let r={...Ct,...n.config,...e};await x3.updateGroup(n.id,{config:r}),this.#e().internal_dispatchChatGroup({payload:{id:n.id,value:{config:r}},type:`updateGroup`}),await this.#e().refreshGroupDetail(n.id)};updateGroupMeta=async e=>{let t=this.#e(),n=t.activeGroupId?M3.getGroupById(t.activeGroupId)(t):void 0;n&&await this.updateGroupMetaById(n.id,e)};updateGroupMetaById=async(e,t)=>{e&&(await x3.updateGroup(e,t),this.#e().internal_dispatchChatGroup({payload:{id:e,value:t},type:`updateGroup`}),await this.#e().refreshGroupDetail(e))}}})),UNe,WNe,GNe=e((()=>{UNe={agentGroups:[],allAgentsDrawerOpen:!1,isAgentListInit:!1,pinnedAgents:[],privateAgentGroups:[],privateUngroupedAgents:[],ungroupedAgents:[]},WNe=e=>({agentGroups:e.groups,pinnedAgents:e.pinned,privateAgentGroups:e.privateGroups??[],privateUngroupedAgents:e.privateUngrouped??[],ungroupedAgents:e.ungrouped})})),KNe,qNe=e((()=>{KNe={homeInputLoading:!1,inputActiveMode:null}})),JNe,YNe=e((()=>{JNe={allRecentsDrawerOpen:!1,isRecentsInit:!1,recents:[],recentsScope:null}})),XNe,ZNe=e((()=>{XNe={agentUpdatingId:null,groupUpdatingId:null}})),QNe,$Ne=e((()=>{GNe(),qNe(),YNe(),ZNe(),QNe={...UNe,...JNe,...KNe,...XNe}})),ePe,P3,F3=e((()=>{pa(),ePe=class{getSidebarAgentList=()=>q.home.getSidebarAgentList.query();getDailyBrief=()=>q.home.getDailyBrief.query();searchAgents=e=>q.home.searchAgents.query({keyword:e});updateAgentSessionGroupId=(e,t)=>q.home.updateAgentSessionGroupId.mutate({agentId:e,sessionGroupId:t})},P3=new ePe})),I3,L3,tPe,nPe,rPe=e((()=>{I3=t(le()),Qi(),oa(),F3(),Gr(),Dr(),GNe(),L3=kr(`agentList`),tPe=(e,t,n
5689)=>new nPe(e,t,n),nPe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}closeAllAgentsDrawer=()=>{this.#t({allAgentsDrawerOpen:!1},!1,L3(`closeAllAgentsDrawer`))};openAllAgentsDrawer=()=>{this.#t({allAgentsDrawerOpen:!0},!1,L3(`openAllAgentsDrawer`))};refreshAgentList=async()=>{Xr().invalidateAvailableAgents(),await Zi(ca.list(!0))};useFetchAgentList=e=>$i(e===!0?ca.list(e):null,()=>P3.getSidebarAgentList(),{onData:e=>{let t=this.#e(),n=WNe(e);t.isAgentListInit&&(0,I3.default)(t.pinnedAgents,n.pinnedAgents)&&(0,I3.default)(t.agentGroups,n.agentGroups)&&(0,I3.default)(t.ungroupedAgents,n.ungroupedAgents)&&(0,I3.default)(t.privateAgentGroups,n.privateAgentGroups)&&(0,I3.default)(t.privateUngroupedAgents,n.privateUngroupedAgents)||this.#t({...n,isAgentListInit:!0},!1,L3(`useFetchAgentList/onData`))}});useSearchAgents=e=>Xi(cre.search(e),async()=>e?P3.searchAgents(e):[])}})),R3,iPe=e((()=>{Za(),qre(),Jre(),R3=(e,t)=>{let n=Kre();if(!n)return;let r=Yre(e,Qa(),t),{escape:i,...a}=t??{};Object.keys(a).length>0?n(r,a):n(r)}})),aPe,oPe,sPe=e((()=>{iPe(),aPe=(e,t,n)=>new oPe(e,t,n),oPe=class{constructor(e,t,n){}switchToGroup=e=>{R3(`/group/${e}`)}}})),cPe,lPe=e((()=>{cPe={activeTabId:`group`,chatPanelExpanded:!0,saveStateMap:{},streamingContent:void 0,streamingInProgress:!1}})),z3,B3,uPe,dPe,fPe,pPe=e((()=>{Zt(),Wt(),ft(),lPe(),z3=null,B3=null,uPe={lastUpdatedTime:null,saveStatus:`idle`},dPe=class{#e;#t;#n;constructor(e,t,n){this.#t=t,this.#n=e,this.#e=Mt(async e=>{let t=B3;if(t)try{z3&&(await z3(e),this.#r(t,`saved`))}catch(e){console.error(`[ProfileEditor] Failed to save:`,e),this.#r(t,`idle`)}},vt,{leading:!1,maxWait:Ut,trailing:!0})}#r=(e,t)=>{let{saveStateMap:n}=this.#t(),r=n[e]||uPe;this.#n({saveStateMap:{...n,[e]:{...r,lastUpdatedTime:t===`saved`?new Date:r.lastUpdatedTime,saveStatus:t}}})};appendStreamingContent=e=>{let t=(this.#t().streamingContent||``)+e;this.#n({streamingContent:t});let{editor:n}=this.#t();if(n)try{n.setDocument(`markdown`,t)}catch{}};finishStreaming=async e=>{let{activeTabId:t,editor:n,streamingContent:r}=this.#t();if(!r){this.#n({streamingInProgress:!1});return}let i=r,a={};if(n)try{i=n.getDocument(`markdown`)||r,a=n.getDocument(`json`)}catch{}this.#r(t,`saving`);try{await e({content:i,editorData:structuredClone(a||{})}),this.#r(t,`saved`)}catch(e){console.error(`[ProfileEditor] Failed to save streaming content:`,e),this.#r(t,`idle`)}this.#n({streamingContent:void 0,streamingInProgress:!1})};flushSave=()=>{this.#e.flush()};handleContentChange=e=>{let{activeTabId:t,editor:n}=this.#t();if(n){z3=e,B3=t,this.#r(t,`saving`);try{let e=n.getDocument(`markdown`)||``,t=n.getDocument(`json`);this.#e({content:e||``,editorData:structuredClone(t||{})})}catch(e){console.error(`[ProfileEditor] Failed to read editor content:`,e),this.#r(t,`idle`)}}};setActiveTabId=e=>{this.#n({activeTabId:e})};setAgentBuilderContent=(e,t)=>{this.#n({agentBuilderContentUpdate:{content:t,entityId:e,timestamp:Date.now()}})};setChatPanelExpanded=e=>{typeof e==`function`?this.#n(t=>({chatPanelExpanded:e(t.chatPanelExpanded)})):this.#n({chatPanelExpanded:e})};updateSaveStatus=(e,t)=>{this.#r(e,t)}},fPe=(...e)=>({...cPe,...rt([new dPe(...e)])})})),mPe,hPe,gPe,_Pe=e((()=>{mPe={lastUpdatedTime:null,saveStatus:`idle`},hPe=e=>t=>t.saveStateMap[e]||mPe,gPe={chatPanelExpanded:e=>e.chatPanelExpanded,editor:e=>e.editor,editorState:e=>e.editorState,getSaveState:hPe}})),vPe,V3,H3=e((()=>{y(),d(),gt(),pPe(),_Pe(),vPe=lt(`group_profile`),V3=b()(vPe(fPe),l)})),U3,W3,yPe,bPe,xPe=e((()=>{Nr(),Wt(),iPe(),S3(),$re(),Gr(),qr(),s6(),bc(),Xa(),H3(),ja(),Dr(),U3=kr(`homeInput`),W3=async e=>{let t=Xr(),n=t.builtinAgentIdMap[e];return n&&t.agentMap[n]?n:(await t.refreshBuiltinAgent(e),Xr().builtinAgentIdMap[e])},yPe=(e,t,n)=>new bPe(e,t,n),bPe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}clearInputMode=()=>{this.#t({inputActiveMode:null},!1,U3(`clearInputMode`))};sendAsAgent=async({contextSelections:e,editorData:t,groupId:n,message:r,pageSelections:i,workspaceSlug:a})=>{this.#t({homeInputLoading:!0},!1,U3(`sendAsAgent/start`));try{let o=Xr(),s=Ar.inboxAgentId(o),c=s?Rr.getAgentConfigById(s)(o):null,l=c?.model,u=c?.provider,d=await o.createAgent({config:{model:l,provider:u,systemRole:r,title:Aa(r??``).slice(0,50)||`New Agent`},groupId:n});if(d.agentId&&Z9.setState({activeAgentId:d.agentId},!1,`sendAsAgent/syncEditingAgentId`),r.trim()&&Ja.getState().toggleAgentBuilderPanel(!0),R3(`/agent/${d.agentId}/profile`),this.#e().refreshAgentList(),d.agentId){let{sendMessage:n}=Z9.getState(),s=await W3(Pr.agentBuilder);s&&l&&u&&await o.updateAgentConfigById(s,{model:l,provider:u}),s&&await n({context:{agentId:s,scope:`agent_builder`,...a?{workspaceSlug:a}:{}},contextSelections:e,editorData:t,message:r,pageSelections:i})}return this.#t({inputActiveMode:null},!1,U3(`sendAsAgent/clearMode`)),d.agentId}finally{this.#t({homeInputLoading:!1}
5689,!1,U3(`sendAsAgent/end`))}};sendAsGroup=async({contextSelections:e,editorData:t,groupId:n,message:r,pageSelections:i,workspaceSlug:a})=>{this.#t({homeInputLoading:!0},!1,U3(`sendAsGroup/start`));try{let o=Xr(),s=Ar.inboxAgentId(o),c=s?Rr.getAgentConfigById(s)(o):null,l=c?.model,u=c?.provider,{group:d}=await x3.createGroup({config:{systemPrompt:r},groupId:n,title:Aa(r??``).slice(0,50)||`New Group`});await o6().loadGroups(),this.#e().refreshAgentList(),r.trim()&&V3.getState().setChatPanelExpanded(!0),R3(`/group/${d.id}/profile`);let f=await W3(Pr.groupAgentBuilder);if(f){l&&u&&await o.updateAgentConfigById(f,{model:l,provider:u});let{sendMessage:n}=Z9.getState();await n({context:{agentId:f,scope:`group_agent_builder`,...a?{workspaceSlug:a}:{}},contextSelections:e,editorData:t,message:r,pageSelections:i})}return this.#t({inputActiveMode:null},!1,U3(`sendAsGroup/clearMode`)),d.id}finally{this.#t({homeInputLoading:!1},!1,U3(`sendAsGroup/end`))}};sendAsResearch=async e=>{console.info(`sendAsResearch:`,e),this.#t({inputActiveMode:null},!1,U3(`sendAsResearch`))};sendAsWrite=async({contextSelections:e,editorData:t,message:n,pageSelections:r,workspaceSlug:i})=>{this.#t({homeInputLoading:!0},!1,U3(`sendAsWrite/start`));try{let a=Xr(),o=Ar.inboxAgentId(a),s=o?Rr.getAgentConfigById(o)(a):null,c=s?.model,l=s?.provider,u=await eie.createDocument({editorData:`{}`,fileType:eee,title:Aa(n??``).slice(0,50)||`Untitled`});R3(`/page/${u.id}`);let d=await W3(Pr.pageAgent);if(d){c&&l&&await a.updateAgentConfigById(d,{model:c,provider:l});let{sendMessage:o}=Z9.getState();await o({context:{agentId:d,documentId:u.id,scope:`page`,...i?{workspaceSlug:i}:{}},contextSelections:e,editorData:t,message:n,pageSelections:r})}return this.#t({inputActiveMode:null},!1,U3(`sendAsWrite/clearMode`)),u.id}finally{this.#t({homeInputLoading:!1},!1,U3(`sendAsWrite/end`))}};setInputActiveMode=e=>{this.#t({inputActiveMode:e},!1,U3(`setInputActiveMode`,e))}}})),SPe,G3,CPe=e((()=>{pa(),SPe=class{getAll=e=>q.recent.getAll.query({limit:e})},G3=new SPe})),wPe,K3,TPe,EPe,DPe,OPe=e((()=>{wPe=t(le()),Qi(),oa(),lr(),CPe(),Dr(),K3=kr(`recent`),TPe=(e,t)=>n=>n?.map(n=>n.id===e?{...n,title:t}:n),EPe=(e,t,n)=>new DPe(e,t,n),DPe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}closeAllRecentsDrawer=()=>{this.#t({allRecentsDrawerOpen:!1},!1,K3(`closeAllRecentsDrawer`))};openAllRecentsDrawer=()=>{this.#t({allRecentsDrawerOpen:!0},!1,K3(`openAllRecentsDrawer`))};updateRecentTitle=(e,t)=>
5689{let n=this.#e().recents.map(n=>n.id===e?{...n,title:t}:n);this.#t({recents:n},!1,K3(`updateRecentTitle`));let r=TPe(e,t);Promise.all([Zi(e=>Array.isArray(e)&&e[0]===ea.list.root,r,{revalidate:!1}),Zi(e=>Array.isArray(e)&&e[0]===ea.allDrawer.root,r,{revalidate:!1})])};refreshRecents=async()=>{await Promise.all([Zi(e=>Array.isArray(e)&&e[0]===ea.list.root),Zi(e=>Array.isArray(e)&&e[0]===ea.allDrawer.root)])};useFetchRecents=(e,t=10,n)=>$i(e===!0?ea.list(e,t,n):null,async()=>G3.getAll(t+1),{onData:e=>{if(xr()!==n)return;let t=this.#e();t.isRecentsInit&&t.recentsScope===n&&(0,wPe.default)(t.recents,e)||this.#t({isRecentsInit:!0,recents:e,recentsScope:n},!1,K3(`useFetchRecents/onData`))}})}}));async function q3(e,t){let n=await ga(e,t);return`data`in n?n.data:n}var kPe,J3,APe=e((()=>{ha(),kPe=class{hasSessions=async()=>await this.countSessions()>0;createSession=async(e,t)=>{let{config:n,group:r,meta:i,...a}=t;return(await q3(`/app/front-hub/sessions`,{method:`POST`,body:JSON.stringify({config:{...n,...i},session:{...a,groupId:r},type:e})})).id};cloneSession=async(e,t)=>(await q3(`/app/front-hub/sessions/${e}/clone`,{method:`POST`,body:JSON.stringify({newTitle:t})})).id;getGroupedSessions=async()=>({sessions:(await q3(`/app/front-hub/sessions`))?.items??[],sessionGroups:[]});countSessions=async e=>q3(`/app/front-hub/sessions/count${e?`?`+new URLSearchParams(Object.entries(e).flatMap(([e,t])=>Array.isArray(t)?[[e,t[0]],[e,t[1]]]:t==null?[]:[[e,String(t)]])).toString():``}`);updateSession=(e,t)=>{let{group:n,pinned:r,meta:i,updatedAt:a}=t;return q3(`/app/front-hub/sessions/${e}`,{method:`PATCH`,body:JSON.stringify({groupId:n==="default"?null:n,pinned:r,...i,updatedAt:a})})};getSessionConfig=async e=>({});updateSessionConfig=(e,t,n)=>Promise.resolve();updateSessionMeta=(e,t,n)=>Promise.resolve();updateSessionChatConfig=(e,t,n)=>Promise.resolve();searchSessions=e=>Promise.resolve([]);removeSession=e=>q3(`/app/front-hub/sessions/${e}`,{method:`DELETE`});createSessionGroup=(e,t,n)=>Promise.resolve(``);removeSessionGroup=(e,t)=>Promise.resolve();updateSessionGroup=(e,t)=>Promise.resolve();updateSessionGroupOrder=e=>Promise.resolve()},J3=new kPe})),Y3,X3=e((()=>{Qi(),oa(),Y3=e=>Zi(t=>ta(t,e),void 0,{revalidate:!1})})),Z3,jPe,MPe,NPe=e((()=>{f(),Qr(),dt(),S3(),F3(),APe(),Gr(),X3(),Dr(),Z3=kr(`sidebarUI`),jPe=(e,t,n)=>new MPe(e,t,n),MPe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}duplicateAgent=async(e,t)=>{let n=`duplicateAgent.loading`;zr.loading({content:o(`duplicateSession.loading`,{ns:`chat`}),duration:0,key:n});let r=await ht.duplicateAgent(e,t);if(!r){zr.destroy(n),zr.error(o(`copyFail`,{ns:`common`}));return}await this.#e().refreshAgentList(),zr.destroy(n),zr.success(o(`duplicateSession.success`,{ns:`chat`})),Xr().setActiveAgentId(r.agentId)};duplicateAgentGroup=async(e,t)=>{let n=`duplicateAgentGroup.loading`;zr.loading({content:o(`duplicateSession.loading`,{ns:`chat`}),duration:0,key:n});let r=await x3.duplicateGroup(e,t);if(!r){zr.destroy(n),zr.error(o(`copyFail`,{ns:`common`}));return}await this.#e().refreshAgentList(),zr.destroy(n),zr.success(o(`duplicateSession.success`,{ns:`chat`})),Xr().setActiveAgentId(r.supervisorAgentId)};pinAgent=async(e,t)=>{await ht.updateAgentPinned(e,t),await this.#e().refreshAgentList()};pinAgentGroup=async(e,t)=>{await x3.updateGroup(e,{pinned:t}),await this.#e().refreshAgentList()};removeAgent=async e=>{await ht.removeAgent(e),await this.#e().refreshAgentList(),Y3(t=>t.agentId===e)};removeAgentGroup=async e=>{await x3.deleteGroup(e),await this.#e().refreshAgentList(),Y3(t=>t.groupId===e)};renameAgentGroup=async(e,t,n,r)=>{await x3.updateGroup(e,{avatar:n,backgroundColor:r,title:t}),await this.#e().refreshAgentList()};updateAgentGroup=async(e,t)=>{await P3.updateAgentSessionGroupId(e,t==="default"?null:t),await this.#e().refreshAgentList()};addGroup=async(e,t)=>{let n=await J3.createSessionGroup(e,void 0,t);return await this.#e().refreshAgentList(),n};removeGroup=async e=>{await J3.removeSessionGroup(e),await this.#e().refreshAgentList()};updateGroupName=async(e,t)=>{await J3.updateSessionGroup(e,{name:t}),await this.#e().refreshAgentList()};updateGroupSort=async e=>{let t=e.map((e,t)=>({id:e.id,sort:t}));zr.loading({content:o(`sessionGroup.sorting`,{ns:`chat`}),duration:0,key:`updateGroupSort`}),await J3.updateSessionGroupOrder(t),zr.destroy(`updateGroupSort`),zr.success(o(`sessionGroup.sortSuccess`,{ns:`chat`})),await this.#e().refreshAgentList()};setAgentUpdatingId=e=>{this.#t({agentUpdatingId:e},!1,Z3(`setAgentUpdatingId`))};setGroupUpdatingId=e=>{this.#t({groupUpdatingId:e},!1,Z3(`setGroupUpdatingId`))}}})),PPe,FPe,IPe,Q3,$3,LPe=e((()=>{x(),y(),d(),He(),gt(),at(),ft(),ct(),$Ne(),rPe(),sPe(),xPe(),OPe(),NPe(),PPe=class extends pt{resetActionName=`resetHomeStore`},FPe=(...e)=>({...QNe,...rt([tPe(...e),aPe(...e),EPe(...e),yPe(...e),jPe(...e),new PPe(...e)])}),IPe=lt(`home`),Q3=b()(g(IPe(FPe,{name:`LobeChat_Home`})),l),mt(`home`,Q3),$3=()=>Q3.getState()})),e6=e((()=>{LPe()})),RPe,zPe=e((()=>{Wt(),S3(),bc(),e6(),RPe=class{#e;constructor(e,t,n){this.#e=t}createGroup=async(e,t,n=!1)=>{let{switchToGroup:r,refreshAgentList:i}=$3(),{group:a}=await x3.createGroup(e);return t&&t.length>0&&(await x3.addAgentsToGroup(a.id,t),await new Promise(e=>{setTimeout(e,100)})),this.#e().internal_dispatchChatGroup({payload:a,type:`addGroup`}),await this.#e().internal_fetchGroupDetail(a.id),i(),n||r(a.id),a.id};switchToNewTopic=()=>{this.#e().switchTopic(void 0)};switchTopic=e=>{let{activeGroupId:t,router:n}=this.#e();if(!t||!n)return;Z9.getState().switchTopic(e??void 0);let r=e?Ht(t,e):on(t);n.push(r,{replace:!0})}}})),BPe,VPe=e((()=>{S3(),Gr(),BPe=class{#e;constructor(e,t,n){this.#e=t}addAgentsToGroup=async(e,t)=>{await x3.addAgentsToGroup(e,t),await this.#e().refreshGroupDetail(e)};createAgentInGroup=async(e,t)=>{let{agentIds:n}=await x3.batchCreateAgentsInGroup(e,[t??{}]);return await this.#e().refreshGroupDetail(e),n[0]};removeAgentFromGroup=async(e,t)=>{await x3.removeAgentsFromGroup(e,[t]),await this.#e().refreshGroupDetail(e)};reorderGroupMembers=async(e,t)=>{await Promise.all(t.map((t,n)=>x3.updateAgentInGroup(e,t,{order:n}))),await this.#e().refreshGroupDetail(e)};
5689updateMemberAgentConfig=async(e,t,n)=>{await Xr().updateAgentConfigById(t,n),await this.#e().refreshGroupDetail(e)}}})),t6,n6,r6,HPe,i6,UPe=e((()=>{t6=t(le()),it(),Qi(),oa(),S3(),Gr(),bc(),ft(),Dr(),w3(),wNe(),HNe(),zPe(),VPe(),n6=kr(`chatGroup`),r6=e=>({...e,agents:[]}),HPe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}reset=()=>{this.#t(C3,!1,n6(`reset`))};internal_dispatchChatGroup=e=>{this.#t(tt(t=>{let n=E3[e.type];if(n)return n(t,e)}),!1,e)};removeStaleGroup=e=>{this.internal_dispatchChatGroup({payload:e,type:`deleteGroup`})};#n=e=>{this.#e().groupNotFoundMap[e]||this.#t(t=>({groupNotFoundMap:{...t.groupNotFoundMap,[e]:!0}}),!1,`markGroupNotFound`)};#r=e=>{this.#e().groupNotFoundMap[e]&&this.#t(t=>{let n={...t.groupNotFoundMap};return delete n[e],{groupNotFoundMap:n}},!1,`clearGroupNotFound`)};internal_fetchGroupDetail=async e=>{let t=await x3.getGroupDetail(e);if(!t){this.removeStaleGroup(e),this.#n(e);return}this.#r(e),this.internal_dispatchChatGroup({payload:{id:t.id,value:t},type:`updateGroup`});let n=Xr();for(let e of t.agents)n.internal_dispatchAgentMap(e.id,e);t.supervisorAgentId&&(n.setActiveAgentId(t.supervisorAgentId),Z9.setState({activeAgentId:t.supervisorAgentId},!1,`syncActiveAgentIdFromAgentGroup`))};internal_updateGroupMaps=e=>{let t=e.reduce((e,t)=>(e[t.id]=t,e),{}),n=tt(this.#e().groupMap,e=>{for(let n of Object.keys(t)){let r=t[n],i=e[n];i?e[n]={...i,...r,agents:i.agents,config:i.config||r.config}:e[n]=r6(r)}});this.#t({groupMap:n,groupsInit:!0},!1,n6(`internal_updateGroupMaps/chatGroup`))};loadGroups=async()=>{let e=await x3.getGroups();this.internal_dispatchChatGroup({payload:e,type:`loadGroups`})};refreshGroupDetail=async e=>{await Zi(da.detail(e))};refreshGroups=async()=>{await Zi(da.list(!0))};toggleGroupSetting=e=>{this.#t({showGroupSetting:e},!1,`toggleGroupSetting`)};toggleThread=e=>{this.#t({activeThreadAgentId:e},!1,`toggleThread`)};useFetchGroupDetail=(e,t)=>$i(e&&t?da.detail(t):null,async()=>await x3.getGroupDetail(t)||(this.removeStaleGroup(t),null),{onData:e=>{if(!e){this.#n(t);return}this.#r(t);let n=this.#e().groupMap[e.id];if((0,t6.default)(n,e))return;let r={...this.#e().groupMap,[e.id]:e};this.#t({groupMap:r},!1,n6(`useFetchGroupDetail/onData`,{groupId:e.id}));let i=Xr();for(let t of e.agents){let e=i.agentMap[t.id];(!e||new Date(t.updatedAt)>new Date(e.updatedAt||0))&&i.internal_dispatchAgentMap(t.id,t)}e.supervisorAgentId&&(i.setActiveAgentId(e.supervisorAgentId),Z9.setState({activeAgentId:e.supervisorAgentId},!1,`syncActiveAgentIdFromAgentGroup`))}});useFetchGroups=(e,t)=>$i(e?da.list(t):null,async()=>x3.getGroups(),{fallbackData:[],onData:e=>{let t=this.#e().groupMap,n=e.reduce((e,n)=>{let r=t[n.id];return e[n.id]=r?{...r,...n}:r6(n),e},{});this.#e().groupsInit&&(0,t6.default)(t,n)||this.#t({groupMap:n,groupsInit:!0},!1,n6(`useFetchGroups/onData`))}})},i6=(...e)=>rt([new HPe(...e),new RPe(...e),new BPe(...e),new VNe(...e)])})),WPe,GPe,a6,o6,KPe=e((()=>{y(),d(),gt(),at(),ft(),UPe(),w3(),WPe=(...e)=>({...C3,...rt([i6(...e)])}),GPe=lt(`agentGroup`),a6=b()(GPe(WPe),l),mt(`agentGroup`,a6),o6=()=>a6.getState()})),qPe=n({agentGroupSelectors:()=>M3,chatGroupAction:()=>i6,chatGroupReducers:()=>E3,getChatGroupStoreState:()=>o6,initialChatGroupState:()=>C3}),s6=e((()=>{UPe(),w3(),wNe(),N3(),KPe()})),JPe,YPe=e((()=>{Mi(),dt(),S3(),Gr(),s6(),N3(),H3(),JPe=class{async getAgentInfo(e,t){if(!e)return{content:`No group context available`,error:{message:`No group context available`,type:`NoGroupContext`},success:!1};let n=o6(),r=M3.getAgentByIdFromGroup(e,t.agentId)(n);return r?{content:Pne(r),state:r,success:!0}:{content:`Agent "${t.agentId}" not found in this group`,error:{message:`Agent "${t.agentId}" not found`,type:`AgentNotFound`},success:!1}}async searchAgent(e){let{query:t,limit:n=10}=e;try{let e=(await ht.queryAgents({keyword:t,limit:n})).map(e=>({avatar:e.avatar,description:e.description,id:e.id,title:e.title})),r=e.length;if(r===0)return{content:t?`No agents found matching "${t}".`:`No agents found. You can create a new agent or search with different keywords.`,state:{agents:[],query:t,total:0},success:!0};let i=e.map((e,t)=>`${t+1}. ${e.title||`Untitled`}
5689 (ID: ${e.id})${e.description?` - ${e.description}`:``}`).join(`
5690`);return{content:t?`Found ${r} agent${r>1?`s`:``} matching "${t}":\n${i}`:`Found ${r} agent${r>1?`s`:``}:\n${i}`,state:{agents:e,query:t,total:r},success:!0}}catch(e){return this.handleError(e,`Failed to search agents`)}}async createGroup(e){try{let t=o6(),n={...e.openingMessage!==void 0&&{openingMessage:e.openingMessage},...e.openingQuestions!==void 0&&{openingQuestions:e.openingQuestions}},{group:r,supervisorAgentId:i}=await x3.createGroup({avatar:e.avatar,backgroundColor:e.backgroundColor,config:Object.keys(n).length>0?n:void 0,content:e.prompt,description:e.description,title:e.title});if(t.internal_dispatchChatGroup({payload:r,type:`addGroup`}),e.supervisor){let{avatar:t,backgroundColor:n,description:r,model:a,params:o,provider:s,systemRole:c,tags:l,title:u}=e.supervisor,d={...a!==void 0&&{model:a},...o!==void 0&&{params:o},...s!==void 0&&{provider:s},...c!==void 0&&{systemRole:c}},f={...t!==void 0&&{avatar:t},...n!==void 0&&{backgroundColor:n},...r!==void 0&&{description:r},...l!==void 0&&{tags:l},...u!==void 0&&{title:u}},p=[];Object.keys(d).length>0&&p.push(ht.updateAgentConfig(i,d)),Object.keys(f).length>0&&p.push(ht.updateAgentMeta(i,f)),p.length>0&&await Promise.all(p)}return await t.internal_fetchGroupDetail(r.id),{content:`Successfully created group "${e.title}" with ID: ${r.id}`,state:{groupId:r.id,success:!0,supervisorAgentId:i,title:e.title},success:!0}}catch(e){return this.handleError(e,`Failed to create group`)}}async createAgent(e,t){try{let n=o6();if(!M3.getGroupById(e)(n))return{content:`Group not found`,error:{message:`Group not found`,type:`GroupNotFound`},success:!1};let r=await ht.createAgentOnly({config:{avatar:t.avatar,description:t.description,plugins:t.tools,systemRole:t.systemRole,title:t.title,virtual:!0},groupId:e});return r.agentId?(await n.refreshGroupDetail(e),{content:`Successfully created agent "${t.title}" and added it to the group.`,state:{agentId:r.agentId,success:!0,title:t.title},success:!0}):{content:`Failed to create agent: No agent ID returned`,error:{message:`No agent ID returned`,type:`CreateError`},success:!1}}catch(e){return this.handleError(e,`Failed to create agent`)}}async batchCreateAgents(e,t){try{let n=o6();if(!M3.getGroupById(e)(n))return{content:`Group not found`,error:{message:`Group not found`,type:`GroupNotFound`},success:!1};let r=t.agents.map(e=>({avatar:e.avatar,description:e.description,plugins:e.tools,systemRole:e.systemRole,title:e.title})),{agents:i}=await x3.batchCreateAgentsInGroup(e,r);await n.refreshGroupDetail(e);let a=i.map((e,n)=>({agentId:e.id,success:!0,title:t.agents[n].title})),o=a.map(e=>`- ${e.title} (ID: ${e.agentId})`).join(`
5691`);return{content:`Successfully created ${a.length} agent${a.length>1?`s`:``}:\n${o}`,state:{agents:a,failedCount:0,successCount:a.length},success:!0}}catch(e){return this.handleError(e,`Failed to create agents`)}}async inviteAgent(e,t){try{let n=o6(),r=M3.getGroupById(e)(n);if(!r)return{content:`Group not found`,error:{message:`Group not found`,type:`GroupNotFound`},success:!1};let i=(r.agents||[]).find(e=>e.id===t.agentId);if(i)return{content:`Agent ${i.title||t.agentId} is already in the group`,state:{agentAvatar:i.avatar,agentId:t.agentId,agentName:i.title,success:!1},success:!1};let a=await x3.addAgentsToGroup(e,[t.agentId]);await n.refreshGroupDetail(e);let o=a.added.length>0,s=M3.getGroupById(e)(o6())?.agents?.find(e=>e.id===t.agentId),c=s?.title,l=s?.avatar,u=c?`${c} (ID: ${t.agentId})`:t.agentId;return{content:o?`Successfully invited agent ${u} to the group`:`Agent ${u} was already in the group`,state:{agentAvatar:l,agentId:t.agentId,agentName:c,success:o},success:o}}catch(e){return this.handleError(e,`Failed to invite agent`)}}async removeAgent(e,t){try{let n=o6(),r=M3.getGroupById(e)(n);if(!r)return{content:`Group not found`,error:{message:`Group not found`,type:`GroupNotFound`},success:!1};let i=(r.agents||[]).find(e=>e.id===t.agentId);if(!i)return{content:`Agent ${t.agentId} is not in the group`,state:{agentId:t.agentId,success:!1},success:!1};let a=i.title,o=i.avatar,s=a?`${a} (ID: ${t.agentId})`:t.agentId;return r.supervisorAgentId===t.agentId?{content:`Cannot remove supervisor agent ${s} from the group`,state:{agentAvatar:o,agentId:t.agentId,agentName:a,success:!1},success:!1}:(await x3.removeAgentsFromGroup(e,[t.agentId]),await n.refreshGroupDetail(e),{content:`Successfully removed agent ${s} from the group`,state:{agentAvatar:o,agentId:t.agentId,agentName:a,success:!0},success:!0})}catch(e){return this.handleError(e,`Failed to remove agent`)}}async updateAgentPrompt(e,t){try{let{agentId:n,prompt:r}=t,i=o6(),a=M3.getGroupById(e)(i)?.agents?.find(e=>e.id===n)?.systemRole??void 0;return await jr.getState().updateAgentConfigById(n,{systemRole:r}),await i.refreshGroupDetail(e),V3.getState().setAgentBuilderContent(n,r),{content:r?`Successfully updated agent ${n} system prompt (${r.length} characters)`:`Successfully cleared agent ${n} system prompt`,state:{agentId:n,newPrompt:r,previousPrompt:a,success:!0},success:!0}}catch(e){return this.handleError(e,`Failed to update agent prompt`)}}async updateGroup(e){try{let{currentGroup:t,group:n,groupId:r,isCurrentGroup:i,state:a}=await this.resolveGroupTarget(e.groupId);if(!n||!r)return{content:e.groupId?`Group "${e.groupId}" not found`:`No active group found`,error:{message:e.groupId?`Group "${e.groupId}" not found`:`No active group found`,type:e.groupId?`GroupNotFound`:`NoGroupContext`},success:!1};let{config:o,meta:s}=e;if(!o&&!s)return{content:`No configuration or metadata provided`,error:{message:`No configuration or metadata provided`,type:`NoDataProvided`},success:!1};let c=[],l={success:!0};if(o){let e={};o.openingMessage!==void 0&&(e.openingMessage=o.openingMessage,c.push(o.openingMessage?`openingMessage (${o.openingMessage.length} chars)`:`openingMessage (cleared)`)),o.openingQuestions!==void 0&&(e.openingQuestions=o.openingQuestions,c.push(o.openingQuestions.length>0?`openingQuestions (${o.openingQuestions.length} questions)`:`openingQuestions (cleared)`)),Object.keys(e).length>0&&(i&&t?await a.updateGroupConfig(e):await x3.updateGroup(r,{config:{...n.config,...e}}),l.updatedConfig=e)}return s&&Object.keys(s).length>0&&(i&&t?await a.updateGroupMeta(s):await x3.updateGroup(r,s),l.updatedMeta=s,s.avatar!==void 0&&c.push(`avatar (${s.avatar||`cleared`})`),s.title!==void 0&&c.push(`title (${s.title||`cleared`})`),s.description!==void 0&&c.push(s.description?`description (${s.description.length} chars)`:`description (cleared)`),s.backgroundColor!==void 0&&c.push(`backgroundColor (${s.backgroundColor||`cleared`})`)),await a.internal_fetchGroupDetail(r),{content:`Successfully updated group: ${c.join(`, `)}`,state:l,success:!0}}catch(e){return this.handleError(e,`Failed to update group`)}}async updateGroupPrompt(e){try{let{group:t,groupId:n,isCurrentGroup:r,state:i}=await this.resolveGroupTarget(e.groupId);if(!t||!n)return{content:e.groupId?`Group "${e.groupId}" not found`:`No active group found`,error:{message:e.groupId?`Group "${e.groupId}" not found`:`No active group found`,type:e.groupId?`GroupNotFound`:`NoGroupContext`},success:!1};let a=t.content??void 0;return e.streaming&&r?await this.streamUpdateGroupPrompt(n,e.prompt):await x3.updateGroup(n,{content:e.prompt}),await i.internal_fetchGroupDetail(n),r&&V3.getState().setAgentBuilderContent(n,e.prompt),{content:e.prompt?`Successfully updated group shared prompt (${e.prompt.length} characters)`:`Successfully cleared group shared prompt`,state:{newPrompt:e.prompt,previousPrompt:a,success:!0},success:!0}}catch(t){return this.handleErrorWithState(t,`Failed to update group prompt`,{newPrompt:e.prompt,success:!1})}}async streamUpdateGroupPrompt(e,t){await o6().updateGroup(e,{content:t})}async resolveGroupTarget(e){let t=o6(),n=t.activeGroupId?M3.getGroupById(t.activeGroupId)(t):void 0,r=e??n?.id;return r?{currentGroup:n,group:M3.getGroupById(r)(t)??await x3.getGroup(r)??void 0,groupId:r,isCurrentGroup:n?.id===r,state:t}:{currentGroup:n,group:void 0,groupId:void 0,isCurrentGroup:!1,state:t}}handleError(e,t){let n=e;return{content:`${t}: ${n.message}`,error:{body:e,message:n.message,type:`RuntimeError`},success:!1}}handleErrorWithState(e,t,n){let r=e;return{content:`${t}: ${r.message}`,error:{body:e,message:r.message,type:`RuntimeError`},state:n,success:!1}}}})),c6,l6,XPe,ZPe,QPe=e((()=>{h3(),Ne(),dt(),$a(),YPe(),hte(),c6=new m3({agentService:ht,discoverService:eo}),l6=new JPe,XPe=class extends ye{identifier=dte;apiEnum=ete;getAgentInfo=async(e,t)=>l6.getAgentInfo(t.groupId,e);searchAgent=async e=>l6.searchAgent(e);createGroup=async e=>l6.createGroup(e);createAgent=async(e,t)=>{let n=t.groupId;return n?l6.createAgent(n,e):{content:`No active group found`,error:{message:`No active group found`,type:`NoGroupContext`},success:!1}};batchCreateAgents=async(e,t)=>{let n=t.groupId;return n?l6.batchCreateAgents(n,e):{content:`No active group found`,error:{message:`No active group found`,type:`NoGroupContext`},success:!1}};inviteAgent=async(e,t)=>{let n=t.groupId;return n?l6.inviteAgent(n,e):{content:`No active group found`,error:{message:`No active group found`,type:`NoGroupContext`},success:!1}};removeAgent=async(e,t)=>{let n=t.groupId;return n?l6.removeAgent(n,e):{content:`No active group found`,error:{message:`No active group found`,type:`NoGroupContext`},success:!1}};updateAgentPrompt=async(e,t)=>{let n=t.groupId;return n?l6.updateAgentPrompt(n,e):{content:`No active group found`,error:{message:`No active group found`,type:`NoGroupContext`},success:!1}};updateGroup=async e=>l6.updateGroup(e);updateGroupPrompt=async e=>l6.updateGroupPrompt({streaming:!0,...e});getAvailableModels=async e=>c6.getAvailableModels(e);searchMarketTools=async e=>c6.searchMarketTools(e);updateConfig=async(e,t)=>{let{agentId:n,...r}=e,i=n??t.agentId;return i?c6.updateAgentConfig(i,r):{content:`No agent found. Please provide an agentId or ensure supervisor context is available.`,error:{message:`No agent found`,type:`NoAgentContext`},success:!1}};installPlugin=async(e,t)=>{let n=t.agentId;return n?c6.installPlugin(n,e):{content:`No supervisor agent found`,error:{message:`No supervisor agent found`,type:`NoAgentContext`},success:!1}}},ZPe=new XPe})),$Pe,eFe,tFe=e((()=>{Yee(),Ne(),Pe(),$Pe=class extends ye{identifier=Zee;apiEnum=rte;speak=async(e,t)=>(t.groupOrchestration&&t.agentId&&t.registerAfterCompletion&&t.registerAfterCompletion(()=>t.groupOrchestration.triggerSpeak({agentId:e.agentId,instruction:e.instruction,skipCallSupervisor:e.skipCallSupervisor,supervisorAgentId:t.agentId})),{content:`Triggered agent "${e.agentId}" to respond.`,state:{agentId:e.agentId,instruction:e.instruction,skipCallSupervisor:e.skipCallSupervisor,type:`speak`},stop:!0,success:!0});broadcast=async(e,t)=>(t.groupOrchestration&&t.agentId&&t.registerAfterCompletion&&t.registerAfterCompletion(()=>t.groupOrchestration.triggerBroadcast({agentIds:e.agentIds,instruction:e.instruction,skipCallSupervisor:e.skipCallSupervisor,supervisorAgentId:t.agentId,toolMessageId:t.messageId})),{content:`Triggered broadcast to agents: ${e.agentIds.join(`, `)}.`,metadata:{agentCouncil:!0},state:{agentIds:e.agentIds,instruction:e.instruction,skipCallSupervisor:e.skipCallSupervisor,type:`broadcast`},stop:!0,success:!0});delegate=async(e,t)=>(t.groupOrchestration&&t.agentId&&t.registerAfterCompletion&&t.registerAfterCompletion(()=>t.groupOrchestration.triggerDelegate({agentId:e.agentId,reason:e.reason,supervisorAgentId:t.agentId})),{content:`Delegated conversation control to agent "${e.agentId}".`,state:{agentId:e.agentId,reason:e.reason,type:`delegate`},stop:!0,success:!0});executeAgentTask=async(e,t)=>{let{agentId:n,instruction:r,timeout:i,skipCallSupervisor:a,runInClient:o}=e;return t.groupOrchestration&&t.agentId&&t.registerAfterCompletion&&t.registerAfterCompletion(()=>t.groupOrchestration.triggerExecuteTask({agentId:n,instruction:r,runInClient:o,skipCallSupervisor:a,supervisorAgentId:t.agentId,timeout:i,toolMessageId:t.messageId})),{content:`Triggered async task for agent "${n}"${o?` (client-side)`:``}.`,state:{agentId:n,instruction:r,runInClient:o,skipCallSupervisor:a,timeout:i,type:`executeAgentTask`},stop:!0,success:!0}};executeAgentTasks=async(e,t)=>{t.groupOrchestration&&t.agentId&&t.registerAfterCompletion&&t.registerAfterCompletion(()=>t.groupOrchestration.triggerExecuteTasks({skipCallSupervisor:e.skipCallSupervisor,supervisorAgentId:t.agentId,tasks:e.tasks,toolMessageId:t.messageId}));let n=e.tasks.map(e=>e.agentId).join(`, `);return{content:`Triggered ${e.tasks.length} parallel tasks for agents: ${n}.`,state:{skipCallSupervisor:e.skipCallSupervisor,tasks:e.tasks,type:`executeAgentTasks`},stop:!0,success:!0}};interrupt=async(e,t)=>{let{taskId:n}=e;try{let{aiAgentService:e}=await Ge(async()=>{let{aiAgentService:e}=await import(`./aiAgent-lAVLuc1K.js`).then(e=>(e.r(),e.n));return{aiAgentService:e}},__vite__mapDeps([35,1,16,9,3])),t=await e.interruptTask({threadId:n});return t.success?{content:`Task ${n} has been cancelled successfully`,state:{cancelled:!0,operationId:t.operationId,taskId:n},success:!0}:{content:`Failed to cancel task ${n}`,state:{cancelled:!1,taskId:n},success:!1}}catch(e){return{content:`Failed to interrupt task: ${e instanceof Error?e.message:`Unknown error`}`,success:!1}}};summarize=async(e,t)=>({content:`Summarization not yet implemented${e.focus?` with focus on "${e.focus}"`:``}${e.preserveRecent?` (preserving ${e.preserveRecent} recent messages)`:``}`,success:!0});createWorkflow=async(e,t)=>({content:`Workflow creation not yet implemented for "${e.name}" with ${e.steps.length} steps`,success:!0});vote=async(e,t)=>{let n=e.options.map(e=>e.label).join(`, `);return{content:`Voting not yet implemented for question: "${e.question}" with options: ${n}`,success:!0}}},eFe=new $Pe})),nFe,rFe=e((()=>{Mi(),nFe=class{documentService;fileService;knowledgeBaseService;ragService;constructor(e,t,n,r){this.ragService=e,this.knowledgeBaseService=t,this.documentService=n,this.fileService=r}async listKnowledgeBases(){try{if(!this.knowledgeBaseService)return{content:`Knowledge base service is not available.`,success:!1};let e=await this.knowledgeBaseService.getKnowledgeBases();if(e.length===0)return{content:`No knowledge bases found. You can create one using the createKnowledgeBase tool.`,state:{knowledgeBases:[],total:0},success:!0};let t=e.map(e=>({avatar:e.avatar,description:e.description,id:e.id,name:e.name,updatedAt:e.updatedAt})),n=t.map(e=>`- **${e.name}** (ID: \`${e.id}\`)${e.description?` — ${e.description}`:``}`),r={knowledgeBases:t,total:t.length};return{content:`Found ${t.length} knowledge base(s):\n\n${n.join(`
5692`)}`,state:r,success:!0}}catch(e){return{content:`Error listing knowledge bases: ${e.message}`,error:e,success:!1}}}async viewKnowledgeBase(e,t){try{if(!this.knowledgeBaseService)return{content:`Knowledge base service is not available.`,success:!1};let{id:t,limit:n=50,offset:r=0}=e,i=Math.min(n,100),a=await this.knowledgeBaseService.getKnowledgeBaseById(t);if(!a)return{content:`Knowledge base with ID "${t}" not found.`,success:!1};let o=await this.knowledgeBaseService.getKnowledgeItems({knowledgeBaseId:t,limit:i,offset:r}),s=o.items.map(e=>({fileType:e.fileType,id:e.id,name:e.name,size:e.size,sourceType:e.sourceType,updatedAt:e.updatedAt})),c={avatar:a.avatar,description:a.description,id:a.id,name:a.name,updatedAt:a.updatedAt},l=`**${a.name}
5692** (ID: \`${a.id}\`)`;if(a.description&&(l+=`\nDescription: ${a.description}`),l+=`\n\nShowing ${s.length} item(s) (offset: ${r}):`,s.length>0){let e=s.map(e=>`- \`${e.id}\` | ${e.sourceType} | ${e.name} | ${e.fileType} | ${e.size} bytes`);l+=`
5693
5694`+e.join(`
5695`)}o.hasMore&&(l+=`\n\n_More items available. Use offset=${r+i} to see the next page._`);let u={files:s,hasMore:o.hasMore,knowledgeBase:c,total:s.length};return{content:l,state:u,success:!0}}catch(e){return{content:`Error viewing knowledge base: ${e.message}`,error:e,success:!1}}}async searchKnowledgeBase(e,t){try{let{query:n,topK:r=20}=e,i=await this.ragService.semanticSearchForChat({knowledgeIds:t?.knowledgeBaseIds,query:n,topK:r},t?.signal),a=i.chunks??[],o=i.fileResults??[],s=i.documents??[],c=i.errors,l=a.length+s.length;if(l===0){let e={chunks:[],documents:[],errors:c,fileResults:[],totalResults:0};return{content:c?$te(o,n,s,c):Zte(n),state:e,success:!0}}return{content:$te(o,n,s,c),state:{chunks:a,documents:s,errors:c,fileResults:o,totalResults:l},success:!0}}catch(e){return{content:`Error searching knowledge base: ${e.message}`,error:e,success:!1}}}async readKnowledge(e,t){try{let{fileIds:n}=e;if(!n||n.length===0)return{content:`Error: No file IDs provided`,success:!1};let r=await this.ragService.getFileContents(n,t?.signal);return{content:tne(r),state:{files:r.map(e=>({error:e.error,fileId:e.fileId,filename:e.filename,preview:e.preview,totalCharCount:e.totalCharCount,totalLineCount:e.totalLineCount}))},success:!0}}catch(e){return{content:`Error reading knowledge: ${e.message}`,error:e,success:!1}}}async createKnowledgeBase(e){try{if(!this.knowledgeBaseService)return{content:`Knowledge base service is not available.`,success:!1};let{name:t,description:n}=e,r=await this.knowledgeBaseService.createKnowledgeBase({description:n,name:t});if(!r)return{content:`Error: Failed to create knowledge base.`,success:!1};let i={id:r};return{content:`Knowledge base "${t}" created successfully. ID: \`${r}\``,state:i,success:!0}}catch(e){return{content:`Error creating knowledge base: ${e.message}`,error:e,success:!1}}}async deleteKnowledgeBase(e){try{return this.knowledgeBaseService?(await this.knowledgeBaseService.removeKnowledgeBase(e.id),{content:`Knowledge base \`${e.id}\` deleted successfully.`,success:!0}):{content:`Knowledge base service is not available.`,success:!1}}catch(e){return{content:`Error deleting knowledge base: ${e.message}`,error:e,success:!1}}}async createDocument(e){try{if(!this.documentService)return{content:`Document service is not available.`,success:!1};let{knowledgeBaseId:t,title:n,content:r,parentId:i}=e,a=await this.documentService.createDocument({content:r,fileType:`custom/document`,knowledgeBaseId:t,parentId:i,title:n});if(!a?.id)return{content:`Error: Failed to create document.`,success:!1};let o={id:a.id};return{content:`Document "${n}" created successfully in knowledge base \`${t}\`. Document ID: \`${a.id}\``,state:o,success:!0}}catch(e){return{content:`Error creating document: ${e.message}`,error:e,success:!1}}}async addFiles(e){try{if(!this.knowledgeBaseService)return{content:`Knowledge base service is not available.`,success:!1};let{knowledgeBaseId:t,fileIds:n}=e;return!n||n.length===0?{content:`Error: No file IDs provided.`,success:!1}:(await this.knowledgeBaseService.addFilesToKnowledgeBase(t,n),{content:`Successfully added ${n.length} file(s) to knowledge base \`${t}\`.`,success:!0})}catch(e){return{content:`Error adding files: ${e.message}`,error:e,success:!1}}}async removeFiles(e){try{if(!this.knowledgeBaseService)return{content:`Knowledge base service is not available.`,success:!1};let{knowledgeBaseId:t,fileIds:n}=e;return!n||n.length===0?{content:`Error: No file IDs provided.`,success:!1}:(await this.knowledgeBaseService.removeFilesFromKnowledgeBase(t,n),{content:`Successfully removed ${n.length} file(s) from knowledge base \`${t}\`.`,success:!0})}catch(e){return{content:`Error removing files: ${e.message}`,error:e,success:!1}}}async listFiles(e){try{if(!this.fileService)return{content:`File service is not available.`,success:!1};let{category:t,q:n,limit:r=50,offset:i=0}=e,a=await this.fileService.getKnowledgeItems({category:t,limit:r,offset:i,q:n,showFilesInKnowledgeBase:!1}),o=a.items.map(e=>({createdAt:e.createdAt,fileType:e.fileType,id:e.id,name:e.name,size:e.size,sourceType:e.sourceType,url:e.url}));if(o.length===0)return{content:t?`No ${t} files found in your resource library.`:`No files found in your resource library.`,state:{files:[],hasMore:!1,total:0},success:!0};let s=o.map(e=>`- \`${e.id}\` | ${e.name} | ${e.fileType} | ${e.size} bytes`),c=`Found ${o.length} file(s)`;t&&(c+=` in category "${t}"`),a.hasMore&&(c+=` (more available, use offset=${i+r} to paginate)`),c+=`:\n\n${s.join(`
5696`)}`;let l={files:o,hasMore:a.hasMore,total:o.length};return{content:c,state:l,success:!0}}catch(e){return{content:`Error listing files: ${e.message}`,error:e,success:!1}}}async getFileDetail(e){try{if(!this.fileService)return{content:`File service is not available.`,success:!1};let{id:t}=e,n=await this.fileService.getFileItemById(t);if(!n)return{content:`File with ID "${t}" not found.`,success:!1};let r={createdAt:n.createdAt,fileType:n.fileType,id:n.id,metadata:n.metadata??null,name:n.name,size:n.size,sourceType:n.sourceType,updatedAt:n.updatedAt,url:n.url};return{content:[`**${r.name}** (ID: \`${r.id}\`)`,`- Type: ${r.fileType}`,`- Size: ${r.size} bytes`,`- Source: ${r.sourceType}`,`- Created: ${r.createdAt}
5696`,`- Updated: ${r.updatedAt}`,`- URL: ${r.url}`].join(`
5697`),state:{file:r},success:!0}}catch(e){return{content:`Error getting file detail: ${e.message}`,error:e,success:!1}}}}})),iFe,aFe,oFe=e((()=>{Ne(),pa(),nie(),qr(),ste(),rFe(),tK(),iFe=class extends ye{identifier=$G;apiEnum=eK;runtime=new nFe({getFileContents:(e,t)=>to.getFileContents(e,t),semanticSearchForChat:(e,t)=>to.semanticSearchForChat(e,t)},{addFilesToKnowledgeBase:async(e,t)=>{try{return await q.knowledgeBase.addFilesToKnowledgeBase.mutate({ids:t,knowledgeBaseId:e})}catch(e){throw e?.data?.code===`CONFLICT`||e?.message===`FILE_ALREADY_IN_KNOWLEDGE_BASE`?Error(`One or more files are already in this knowledge base.`,{cause:e}):e}},createKnowledgeBase:e=>q.knowledgeBase.createKnowledgeBase.mutate(e),getKnowledgeBaseById:async e=>{let t=await q.knowledgeBase.getKnowledgeBaseById.query({id:e});if(t)return{avatar:t.avatar,description:t.description,id:t.id,name:t.name,updatedAt:t.updatedAt}},getKnowledgeBases:async()=>(await q.knowledgeBase.getKnowledgeBases.query()).map(e=>({avatar:e.avatar,description:e.description,id:e.id,name:e.name,updatedAt:e.updatedAt})),getKnowledgeItems:async({knowledgeBaseId:e,limit:t,offset:n})=>{let r=await q.file.getKnowledgeItems.query({knowledgeBaseId:e,limit:t,offset:n});return{hasMore:r.hasMore,items:r.items.map(e=>({fileType:e.fileType,id:e.id,name:e.name,size:e.size,sourceType:e.sourceType,updatedAt:e.updatedAt}))}},removeFilesFromKnowledgeBase:(e,t)=>q.knowledgeBase.removeFilesFromKnowledgeBase.mutate({ids:t,knowledgeBaseId:e}),removeKnowledgeBase:async e=>{await q.knowledgeBase.removeKnowledgeBase.mutate({id:e})}},{createDocument:async e=>({id:(await q.document.createDocument.mutate(e)).id})},{getFileItemById:async e=>{let t=await q.file.getFileItemById.query({id:e});if(t)return{createdAt:t.createdAt,fileType:t.fileType,id:t.id,metadata:t.metadata,name:t.name,size:t.size,sourceType:`file`,updatedAt:t.updatedAt,url:t.url}},getKnowledgeItems:async e=>{let t=await q.file.getKnowledgeItems.query(e);return{hasMore:t.hasMore,items:t.items.map(e=>({createdAt:e.createdAt,fileType:e.fileType,id:e.id,metadata:e.metadata,name:e.name,size:e.size,sourceType:e.sourceType,updatedAt:e.updatedAt,url:e.url??``}))}}});toResult(e){let t=typeof e.error?.message==`string`?e.error.message:void 0,n=e.content||t||`Tool execution failed`;return e.success?{content:n,state:e.state,success:!0}:{content:n,error:e.error?{body:e.error,message:t??n,type:`PluginServerError`}:void 0,state:e.state,success:!1}}listKnowledgeBases=async()=>this.toResult(await this.runtime.listKnowledgeBases());viewKnowledgeBase=async e=>this.toResult(await this.runtime.viewKnowledgeBase(e));searchKnowledgeBase=async(e,t)=>{let{knowledgeBaseIds:n}=Rr.currentKnowledgeIds(Xr());return this.toResult(await this.runtime.searchKnowledgeBase(e,{knowledgeBaseIds:n,messageId:t.messageId,signal:t.signal}))};readKnowledge=async(e,t)=>this.toResult(await this.runtime.readKnowledge(e,{signal:t.signal}));createKnowledgeBase=async e=>this.toResult(await this.runtime.createKnowledgeBase(e));deleteKnowledgeBase=async e=>this.toResult(await this.runtime.deleteKnowledgeBase(e));createDocument=async e=>this.toResult(await this.runtime.createDocument(e));addFiles=async e=>this.toResult(await this.runtime.addFiles(e));removeFiles=async e=>this.toResult(await this.runtime.removeFiles(e));listFiles=async e=>this.toResult(await this.runtime.listFiles(e));getFileDetail=async e=>this.toResult(await this.runtime.getFileDetail(e))},aFe=new iFe})),sFe,u6,d6=e((()=>{pa(),sFe=class{createDocument=async e=>q.notebook.createDocument.mutate(e);updateDocument=async e=>q.notebook.updateDocument.mutate(e);getDocument=async e=>q.notebook.getDocument.query({id:e});listDocuments=async e=>q.notebook.listDocuments.query(e);deleteDocument=async e=>q.notebook.deleteDocument.mutate({id:e})},u6=new sFe})),cFe,lFe,uFe,dFe,fFe=e((()=>{cFe=(e,t)=>n=>{if(!e||!t)return null;let r=n.notebookMap[e];return r&&r.find(e=>e.id===t)||null},lFe=e=>t=>e&&t.notebookMap[e]||[],uFe=e=>t=>{if(!e)return!1;let n=t.notebookMap[e];return n&&n.length>0},dFe={getDocumentById:cFe,getDocumentsByTopicId:lFe,hasDocuments:uFe}})),pFe,mFe,hFe,gFe,_Fe=e((()=>{pFe=t(le()),Qi(),yne(),rre(),d6(),bc(),Dr(),mFe=kr(`notebook`),hFe=(e,t,n)=>new gFe(e,t,n),gFe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}createDocument=async e=>{let t=await u6.createDocument(e);return await Ni({cause:`notebook`,documentId:t.id,topicId:e.topicId}),t};deleteDocument=async(e,t)=>{Z9.getState().portalDocumentId===e&&Z9.getState().closeDocument(),await u6.deleteDocument(e),await Ni({cause:`notebook`,documentId:e,topicId:t})};refreshDocuments=async e=>{await Zi(nre.documents(e))};updateDocument=async(e,t)=>{let n=await u6.updateDocument(e);return await Ni({cause:`notebook`,documentId:e.id,topicId:t}),n};useFetchDocuments=e=>Xi(e?nre.documents(e):null,async()=>e?(await u6.listDocuments({topicId:e})).data:[],{onSuccess:t=>{if(!e)return;let n=this.#e().notebookMap[e];n&&(0,pFe.default)(t,n)||this.#t({notebookMap:{...this.#e().notebookMap,[e]:t}},!1,mFe(`useFetchDocuments(onSuccess)`,{topicId:e}))}})}})),vFe,yFe=e((()=>{vFe={notebookMap:{}}}
5697)),bFe,xFe,SFe,f6,CFe=e((()=>{y(),d(),gt(),at(),ft(),ct(),_Fe(),yFe(),bFe=class extends pt{resetActionName=`resetNotebookStore`},xFe=(...e)=>({...vFe,...rt([hFe(...e),new bFe(...e)])}),SFe=lt(`notebook`),f6=b()(SFe(xFe),l),mt(`notebook`,f6)})),wFe=e((()=>{fFe(),CFe()})),TFe,EFe=e((()=>{TFe=e=>{let t=e.stepContext?.todos;if(t?.items)return t.items;let n=e.pluginState;if(!n)return[];let r=n.todos;if(!r)return[];if(typeof r==`object`&&`items`in r){let e=r.items;return Array.isArray(e)?e:[]}return Array.isArray(r)?r:[]}})),DFe,OFe,kFe,AFe,jFe=e((()=>{_e(),De(),Ke(),DFe={image:`image/`,video:`video/`},OFe=(e,t)=>{let n=DFe[e.type],r=t.trim().toLowerCase();if(!r.startsWith(n))throw TypeError(`Unable to read ${e.type} attachment "${e.name}": expected ${n}* MIME type, received ${r||`unknown`}.`)},kFe=async e=>Promise.all(e.map(async e=>{let{type:t}=pe(e.uri);if(t!==`url`||!Fe(e.uri))return e;let{base64:n,mimeType:r}=await Ue(e.uri);return OFe(e,r),{...e,uri:`data:${r};base64,${n}`}})),AFe=async({selectedRefs:e,selectedUrls:t})=>[...await kFe(e),...t]})),p6,m6,MFe,h6,NFe,PFe,g6,FFe,IFe,LFe,RFe=e((()=>{ii(),Ne(),d6(),wFe(),bK(),vK(),HK(),cK(),EFe(),jFe(),Pe(),p6=`agent/plan`,m6=e=>({content:e.content??null,createdAt:typeof e.createdAt==`string`?new Date(e.createdAt):e.createdAt,description:e.description??null,id:e.id,metadata:e.metadata??null,title:e.title??null,updatedAt:typeof e.updatedAt==`string`?new Date(e.updatedAt):e.updatedAt}),MFe={createPlan:async({topicId:e,goal:t,description:n,content:r})=>m6(await f6.getState().createDocument({content:r,description:n,title:t,topicId:e,type:p6})),findPlanById:async e=>{let t=await u6.getDocument(e);return t?m6(t):null},findPlanByTopic:async e=>{let t=(await u6.listDocuments({topicId:e,type:p6})).data[0];return t?m6(t):null},updatePlan:async(e,{goal:t,description:n,content:r},i)=>{let a=await f6.getState().updateDocument({content:r,description:n,id:e,title:t},i??``);if(!a)throw Error(`Plan not found after update: ${e}`);return m6(a)},updatePlanMetadata:async(e,t)=>{await u6.updateDocument({id:e,metadata:t})}},h6=e=>({currentTodos:TFe(e),messageId:e.messageId,signal:e.signal,topicId:e.topicId??void 0}),NFe=async()=>{let{getServerConfigStoreState:e,serverConfigSelectors:t}=await Ge(async()=>{let{getServerConfigStoreState:e,serverConfigSelectors:t}=await import(`./agent-Dh3-_0ai.js`).then(e=>(e.p(),e.m));return{getServerConfigStoreState:e,serverConfigSelectors:t}},__vite__mapDeps([10,1,9,3,11,12,13,14,15,16,17,18,7,19,20,21,22,5,23,2,24,25,26,27,28])),n=e();return n?t.visualUnderstanding(n):void 0},PFe=e=>{let t=new AbortController;return e?.aborted?(t.abort(),t):(e?.addEventListener(`abort`,()=>t.abort(),{once:!0}),t)},g6=e=>!!e&&typeof e==`object`,FFe=()=>({content:`Nested sub-agent execution is not allowed.`,error:{message:`Sub-agent calls cannot be triggered from within another sub-agent.`,type:`NestedSubAgentNotAllowed`},success:!1}),IFe=class extends ye{identifier=yK.identifier;apiEnum=gK;planRuntime=new sK(MFe);interactionRuntime=new Cr;askUserQuestion=e=>this.interactionRuntime.askUserQuestion(e);createPlan=(e,t)=>this.planRuntime.createPlan(e,h6(t));updatePlan=(e,t)=>this.planRuntime.updatePlan(e,h6(t));createTodos=(e,t)=>this.planRuntime.createTodos(e,h6(t));updateTodos=(e,t)=>this.planRuntime.updateTodos(e,h6(t));clearTodos=(e,t)=>this.planRuntime.clearTodos(e,h6(t));analyzeVisualMedia=async(e,t)=>{let n=await NFe();if(!n?.provider||!n.model)return{error:{message:`Visual understanding model is not configured`,type:`PluginSettingsInvalid`},success:!1};if(!e.question?.trim())return{error:{message:"`question` is required",type:`InvalidToolArguments`},success:!1};let{requestedRefs:r,requestedUrls:i}=OK(e);if(r.length===0&&i.length===0){let t=kK(e);return{error:{message:`Either \`refs\` or \`urls\` is required and must include at least one visual file ref or media URL.${t.length>0?` Do not use ${t.join(`, `)}.`:``}`,type:`InvalidToolArguments`},success:!1}}let a=jK(i),o=NK(a);if(o)return{error:{message:o,type:`InvalidToolArguments`},success:!1};let s=zK(a.validUrls),c=[];if(r.length>0){let[{getChatStoreState:e},{dbMessageSelectors:n}]=await Promise.all([Ge(()=>Promise.resolve().then(()=>(bc(),yc)),void 0),Ge(()=>import(`./selectors-IDJ5-Ts8.js`).then(e=>(e.t(),e.n)),__vite__mapDeps([29,1,9,3,10,11,12,13,14,15,16,17,18,7,19,20,21,22,5,23,2,24,25,26,27,28,30]))]),i=e(),a=t.sourceMessageId&&n.getDbMessageById(t.sourceMessageId)(i),o=n.getDbMessageById(t.messageId)(i),s=g6(o)&&o.parentId&&n.getDbMessageById(o.parentId)(i),l=g6(s)&&s.parentId&&n.getDbMessageById(s.parentId)(i),u=FK(a)?a:FK(l)?l:n.latestUserMessage(i),d=n.activeDbMessages(i).filter(FK),f=[...FK(u)?[u]:[],...d.filter(e=>e.id!==u?.id)].flatMap(e=>IK(e,e.imageList,e.videoList));if(f.length===0)return{error:{message:`No visual files are available in the current message`,type:`VisualFilesNotFound`},success:!1};let p=f,{invalidRefs:m,selected:h}=BK(p,r);if(m?.length){let e=p.map(e=>e.ref);return{content:`Unknown file refs: ${m.join(`, `)}. Available refs: ${e.join(`, `)}`,error:{message:`Unknown visual file refs`,type:`InvalidToolArguments`},state:{availableFiles:p,invalidRefs:m},success:!1}}c=h}let l=[...c,...s];if(l.length===0)return{error:{message:`No visual files selected`,type:`InvalidToolArguments`},success:!1};let u=await AFe({selectedRefs:c,selectedUrls:s}),d=``,f,p,m=PFe(t.signal),{chatService:h}=await Ge(async()=>{let{chatService:e}=await Promise.resolve().then(()=>(x7(),fHe));return{chatService:e}},void 0),g={max_tokens:2e3,messages:[{content:VK(u,e.question,{includeFallbackInstruction:!0,includeFileSummary:!0}),role:`user`}],model:n.model,provider:n.provider,stream:!0};return await h.getChatCompletion(g,{onFinish:async(e,t)=>{d=e||d,p=t.usage},onErrorHandle:e=>{f=e},onMessageHandle:e=>{e.type===`text`&&(d+=e.text||``)},metadata:{trigger:Me.VisualAnalysis},signal:m.signal}),m.signal.aborted?{stop:!0,success:!1}:f?{error:{body:f,message:f.message??`Visual understanding request failed`,type:`PluginServerError`},success:!1}:{content:d,state:{files:l,model:n.model,provider:n.provider,trigger:Me.VisualAnalysis,usage:p},success:!0}};callSubAgent=async(e,t)=>{if(t.isSubAgent)return FFe();let{description:n,instruction:r,inheritMessages:i,timeout:a}=e;if(!n||!r)return{content:`Sub-agent description and instruction are required.`,success:!1};if(!t.subAgent)return{content:`Sub-agent execution is not available in this runtime.`,success:!1};let{result:o,threadId:s,success:c,error:l,model:u,totalCost:d,totalInputTokens:f,totalOutputTokens:p,totalToolCalls:m,totalTokens:h}=await t.subAgent.run({description:n,inheritMessages:i,instruction:r,timeout:a,toolMessageId:t.messageId});return c?{content:o,state:{model:u,threadId:s,totalCost:d,totalInputTokens:f,totalOutputTokens:p,totalToolCalls:m,totalTokens:h},success:!0}:{content:l??`Sub-agent execution failed.`,success:!1}}},LFe=new IFe})),zFe,BFe,VFe,HFe,UFe=e((()=>{hG(),Ne(),ro(),_te(),Pee(),zFe=100,BFe={editFile:`editFile`,getCommandOutput:`getCommandOutput`,globFiles:`globFiles`,grepContent:`grepContent`,killCommand:`killCommand`,listFiles:`listFiles`,moveFiles:`moveFiles`,readFile:`readFile`,readFiles:`readFiles`,runCommand:`runCommand`,searchFiles:`searchFiles`,writeFile:`writeFile`},VFe=class extends ye{identifier=Nee;apiEnum=BFe;runtime=new mG(no);toResult(e){let t=typeof e.error?.message==`string`?e.error.message:void 0,n=e.content||t||`[UNKNOWN_EXEC_ERROR] Tool execution failed`;return e.success?{content:n,state:e.state,success:!0}:{content:n,error:e.error?{body:e.error,message:t??n,type:`PluginServerError`}:void 0,state:e.state,success:!1}}listFiles=async e=>{try{let t=await this.runtime.listFiles({directoryPath:e.path,limit:e.limit,sortBy:e.sortBy,sortOrder:e.sortOrder});return this.toResult(t)}catch(e){return this.errorResult(e)}};readFile=async e=>{try{let t=await this.runtime.readFile({endLine:e.loc?.[1],path:e.path,startLine:e.loc?.[0]});return this.toResult(t)}catch(e){return this.errorResult(e)}};readFiles=async e=>{try{let t=await this.runtime.readFiles(e);return this.toResult(t)}catch(e){return this.errorResult(e)}};searchFiles=async e=>{try{let t=lte(e,`directory`),n=await this.runtime.searchFiles({...t,directory:t.directory||``});return this.toResult(n)}catch(e){return this.errorResult(e)}};moveFiles=async e=>{try{let t=await this.runtime.moveFiles({operations:e.items.map(e=>({destination:e.newPath,source:e.oldPath}))});return this.toResult(t)}catch(e){return this.errorResult(e)}};writeFile=async e=>{try{let t=await this.runtime.writeFile(e);return this.toResult(t)}catch(e){return this.errorResult(e)}};editFile=async e=>{try{let t=await this.runtime.editFile({all:e.replace_all,path:e.file_path,replace:e.new_string,search:e.old_string});return this.toResult(t)}catch(e){return this.errorResult(e)}};runCommand=async e=>{try{let t=await this.runtime.runCommand({...e,background:e.run_in_background});return this.toResult(t)}catch(e){return this.errorResult(e)}};getCommandOutput=async e=>{try{let t=await this.runtime.getCommandOutput({commandId:e.shell_id,filter:e.filter});return this.toResult(t)}catch(e){return this.errorResult(e)}};killCommand=async e=>{try{let t=await this.runtime.killCommand({commandId:e.shell_id});return this.toResult(t)}catch(e){return this.errorResult(e)}};grepContent=async(e,t)=>{try{let n=jee(e.scope,t?.workingDirectory),r=n?{...e,path:n}:e,i=await this.runtime.grepContent(r);return this.toResult(i)}catch(e){return this.errorResult(e)}};globFiles=async e=>{try{let t=await this.runtime.globFiles({directory:e.scope,limit:Number.isFinite(e.limit)&&e.limit&&e.limit>0?Math.floor(e.limit):zFe,pattern:e.pattern});return this.toResult(t)}catch(e){return this.errorResult(e)}};errorResult(e){return{content:e.message,error:{body:e,message:e.message,type:`PluginServerError`},success:!1}}},HFe=new VFe})),_6,v6=e((()=>{Ne(),qi(),Object.values(P),_6=Gi(P)})),WFe,y6,GFe,b6,KFe=e((()=>{Ne(),qi(),v6(),WFe=Ui({address:Wi().nullish(),extra:Wi().nullish(),name:Wi().optional(),tags:Ki(Wi()).nullish(),type:Wi().optional()}),y6=Ui({extra:Wi().nullish(),name:Wi(),type:Wi().optional()}),GFe=Ui({associatedLocations:Ki(WFe).nullish(),associatedObjects:Ki(y6).nullish(),associatedSubjects:Ki(y6).nullish(),endsAt:Wi().nullish(),feedback:Wi().nullish(),metadata:Qne(Wi(),Jne()).nullish(),narrative:Wi(),notes:Wi().nullish(),startsAt:Wi().nullish(),status:Wi().nullish(),tags:Ki(Wi()).nullish(),timezone:Wi().nullish(),type:Hi([Gi(k),Wi()]).optional()}),b6=Ui({details:Wi(),memoryCategory:Wi(),memoryType:_6,sourceIds:Ki(Wi()).nullish(),summary:Wi(),tags:Ki(Wi()),title:Wi(),withActivity:GFe}),Ui({memories:Ki(b6)}),P.Activity,Object.values(k)})),qFe,JFe,YFe,x6,XFe=e((()=>{Ne(),qi(),v6(),qFe=Ui({extra:Wi().nullable().describe(`Additional metadata about the object, should always be a valid JSON string if present`),name:Wi().describe(`Name of the associated object`),type:Gi(T).describe(`Type/category of the associated object`)}),JFe=Ui({extra:Wi().nullable().describe(`Additional metadata about the subject, should always be a valid JSON string if present`),name:Wi().describe(`Name of the associated subject`),type:Gi(oe).describe(`Type/category of the associated subject`)}
5697),YFe=Ui({associatedObjects:Ki(qFe).describe(`Array of objects describing involved roles, entities, or resources, [] empty if none`),associatedSubjects:Ki(JFe).describe(`Array of JSON objects describing involved subjects or participants, [] empty if none`),currentStatus:Gi(Ae).describe(`High level status markers (must be one of 'planned', 'ongoing', 'completed', 'aborted', 'on_hold', 'cancelled')`),description:Wi().describe(`Rich narrative describing the situation, timeline, or environment`),labels:Ki(Wi()).describe(`Model generated tags that summarize the context themes`),scoreImpact:Yi().min(0).max(1).describe(`Numeric score (0-1 (0% to 100%)) describing importance`),scoreUrgency:Yi().min(0).max(1).describe(`Numeric score (0-1 (0% to 100%)) describing urgency`),title:Wi().describe(`Optional synthesized context headline`),type:Wi().describe(`High level context archetype (e.g., 'project', 'relationship', 'goal')`)}),x6=Ui({details:Wi().describe(`Optional detailed information`),memoryCategory:Wi().describe(`Memory category`),memoryType:_6.describe(`Memory type`),sourceIds:Ki(Wi()).nullable().default(()=>[]).describe(`Stable source message ids that support this memory`),summary:Wi().describe(`Concise overview of this specific memory`),tags:Ki(Wi()).describe(`User defined tags that summarize the context facets`),title:Wi().describe(`Brief descriptive title`),withContext:YFe}),Ui({memories:Ki(x6).describe(`Array of extracted context memory items, could be empty if decided no relevant context to extract`)})})),ZFe,S6,QFe=e((()=>{qi(),v6(),ZFe=Ui({action:Wi().describe(`Narrative describing actions taken or behaviors exhibited`),keyLearning:Wi().describe(`Narrative describing key insights or lessons learned`),knowledgeValueScore:Yi().min(0).max(1).describe(`Numeric score (0-1) describing how reusable and shareable this experience is`),labels:Ki(Wi()).describe(`Model generated tags that summarize the experience facets`),possibleOutcome:Wi().describe(`Narrative describing potential outcomes or learnings`),problemSolvingScore:Yi().min(0).max(1).describe(`Numeric score (0-1) describing how effectively the problem was solved`),reasoning:Wi().describe(`Narrative describing the thought process or motivations`),scoreConfidence:Yi().min(0).max(1).describe(`Numeric score (0-1 (0% to 100%)) describing confidence in the experience details`),situation:Wi().describe(`Narrative describing the situation or event`),type:Wi().describe(`Type of experience being recorded`)}),S6=Ui({details:Wi().describe(`Optional detailed information`),memoryCategory:Wi().describe(`Memory category`),memoryType:_6.describe(`Memory type`),sourceIds:Ki(Wi()).nullable().default(()=>[]).describe(`Stable source message ids that support this memory`),summary:Wi().describe(`Concise overview of this specific memory`),tags:Ki(Wi()).describe(`Model generated tags that summarize the experience facets`),title:Wi().describe(`Brief descriptive title`),withExperience:ZFe}),Ui({memories:Ki(S6).describe(`Array of extracted experience memory items, could be empty if decided no relevant experience to extract`)})})),C6,$Fe=e((()=>{qi(),C6=Ui({reasoning:Wi(),shouldExtract:Zne()}),Ui({activity:C6,context:C6,experience:C6,identity:C6,preference:C6})})),w6,eIe,T6,E6,D6,O6,tIe,nIe=e((()=>{Ne(),qi(),v6(),w6=`self.father.mother.son.daughter.brother.sister.sibling.husband.wife.spouse.partner.couple.friend.colleague.coworker.classmate.mentor.mentee.manager.teammate.grandfather.grandmother.grandson.granddaughter.uncle.aunt.nephew.niece.other`.split(`.`),eIe=Xne(w6),T6=Xne([`professional`,`personal`,`demographic`]),E6=Ui({details:Hi([Wi(),Ji()]).describe(`Optional detailed information`),memoryCategory:Wi().describe(`Memory category`),memoryType:_6.describe(`Memory type`),summary:Wi().describe(`Concise overview of this specific memory`),tags:Ki(Wi()).describe(`Model generated tags that summarize the identity facets`),title:Wi().describe(`Honorific-style, concise descriptor (strength + domain/milestone), avoid bare job titles; e.g., "Trusted open-source maintainer", "Specializes in low-latency infra", "Former Aliyun engineer", "Cares for rescue cats"`),withIdentity:Ui({description:Wi(),episodicDate:Hi([Wi(),Ji()]),extractedLabels:Ki(Wi()),relationship:eIe,role:Wi().describe(`Role explicitly mentioned for this identity entry (e.g., "platform engineer", "caregiver"); keep neutral and only use when evidence exists`),scoreConfidence:Y
5697i(),sourceIds:Ki(Wi()).nullable().default(()=>[]).describe(`Stable source message ids that support this identity`),sourceEvidence:Hi([Wi(),Ji()]),type:T6}).strict()}).strict(),D6=Ui({id:Wi(),mergeStrategy:Gi(ne),set:Ui({details:Wi().nullable().describe(`Optional detailed information, use null for omitting the field`),memoryCategory:Wi().nullable().describe(`Memory category, use null for omitting the field`),memoryType:_6.describe(`Memory type, use null for omitting the field`),summary:Wi().nullable().describe(`Concise overview of this specific memory, use null for omitting the field`),tags:Ki(Wi()).nullable().describe(`Model generated tags that summarize the identity facets, use null for omitting the field`),title:Wi().nullable().describe(`Honorific-style, concise descriptor (strength + domain/milestone), avoid bare job titles; e.g., "Trusted open-source maintainer", "Specializes in low-latency infra", "Former Aliyun engineer", "Cares for rescue cats"; use null for omitting the field`),withIdentity:Ui({description:Wi().nullable(),episodicDate:Wi().nullable(),extractedLabels:Ki(Wi()).nullable(),relationship:Wi().describe(`Possible values: ${w6.join(` | `)}`).nullable(),role:Wi().describe(`Role explicitly mentioned for this identity entry (e.g., "platform engineer", "caregiver"); keep existing when not updated; use null for omitting the field`).nullable(),scoreConfidence:Yi().nullable(),sourceIds:Ki(Wi()).nullable().describe(`Stable source message ids that support this identity update`),sourceEvidence:Wi().nullable(),type:Wi().describe(`Possible values: ${T6.options.join(` | `)}`).nullable()}).strict()})}).strict(),O6=Ui({id:Wi(),reason:Wi()}).strict(),tIe=Ui({add:Ki(E6).nullable().describe(`Identity entries to add; use an empty array when nothing to add`),remove:Ki(O6).nullable().describe(`Identity entries to remove; use an empty array when nothing to remove`),update:Ki(D6).nullable().describe(`Identity entries to update; use an empty array when nothing to update`)}).strict(),Ui({actions:tIe}).strict()})),rIe,iIe,aIe,k6,oIe=e((()=>{qi(),v6(),rIe=Ui({actor:Wi().describe(`Who stated the preference; use 'User' for the user`),applicableWhen:Wi().nullable().describe(`Conditions where this preference applies`),notApplicableWhen:Wi().nullable().describe(`Conditions where it does not apply`),scenario:Wi().nullable().describe(`Applicable scenario or use case`),trigger:Wi().nullable().describe(`What prompted this preference`)}),iIe=Ui({app:Wi().nullable().describe(`App or product name this applies to`),feature:Wi().nullable(),route:Wi().nullable(),surface:Wi().nullable().describe(`e.g., chat, emails, code review, notes`)}),aIe=Ui({appContext:iIe.nullable().describe(`Application/surface specific preference, if any`),conclusionDirectives:Wi().describe(`Direct, self-contained instruction to the assistant from the user's perspective (what to do, not how to implement)`),extractedLabels:Ki(Wi()).describe(`Model generated tags that summarize the preference facets`),extractedScopes:Ki(Wi()).describe(`Array of JSON strings describing preference facets and applicable scopes`),originContext:rIe.nullable().describe(`Context of how/why this preference was expressed`),scorePriority:Yi().min(0).max(1).describe(`Numeric prioritization weight (0-1 (0% to 100%)) where higher means more critical to respect`),suggestions:Ki(Wi()).describe(`Follow-up actions or assistant guidance derived from the preference`),type:Wi().describe(`High level preference classification (e.g., 'lifestyle', 'communication')`)}),k6=Ui({details:Wi().describe(`Optional detailed information`),memoryCategory:Wi().describe(`Memory category`),memoryType:_6.describe(`Memory type`),sourceIds:Ki(Wi()).nullable().default(()=>[]).describe(`Stable source message ids that support this memory`),summary:Wi().describe(`Concise overview of this specific memory`),tags:Ki(Wi()).describe(`Model generated tags that summarize the preference facets`),title:Wi().describe(`Brief descriptive title`),withPreference:aIe}),Ui({memories:Ki(k6).describe(`Array of extracted preference memory items, could be empty if decided no relevant preference to extract`)})}
5697)),sIe=e((()=>{KFe(),v6(),XFe(),QFe(),$Fe(),nIe(),oIe()})),A6,cIe,lIe=e((()=>{sIe(),Mi(),A6={content:`Memory tool is in read-only mode for this chat`,success:!1},cIe=class{service;toolPermission;constructor(e){this.service=e.service,this.toolPermission=e.toolPermission??`read-write`}get isReadOnly(){return this.toolPermission===`read-only`}async searchUserMemory(e){try{let t=await this.service.searchMemory(e),n=e.queries?.join(` | `)||`facet-only search`,{meta:r,...i}=t;return{content:pne({query:n,results:t}),state:i,success:!0}}catch(e){return{content:`searchUserMemory with error detail: ${e.message}`,success:!1}}}async queryTaxonomyOptions(e){try{let t=await this.service.queryTaxonomyOptions(e);return{content:JSON.stringify(t),state:t,success:!0}}catch(e){return{content:`queryTaxonomyOptions with error detail: ${e.message}`,success:!1}}}async addContextMemory(e){if(this.isReadOnly)return A6;try{let t=x6.parse(e),n=await this.service.addContextMemory(t);return n.success?{content:`Context memory "${t.title}" saved with memoryId: "${n.memoryId}" and contextId: "${n.contextId}"`,state:{contextId:n.contextId,memoryId:n.memoryId},success:!0}:{content:n.message,success:!1}}catch(e){return{content:`addContextMemory with error detail: ${e.message}`,success:!1}}}async addActivityMemory(e){if(this.isReadOnly)return A6;try{let t=b6.parse(e),n=await this.service.addActivityMemory(t);return n.success?{content:`Activity memory "${t.title}" saved with memoryId: "${n.memoryId}" and activityId: "${n.activityId}"`,state:{activityId:n.activityId,memoryId:n.memoryId},success:!0}:{content:n.message,success:!1}}catch(e){return{content:`addActivityMemory with error detail: ${e.message}`,success:!1}}}async addExperienceMemory(e){if(this.isReadOnly)return A6;try{let t=S6.parse(e),n=await this.service.addExperienceMemory(t);return n.success?{content:`Experience memory "${t.title}" saved with memoryId: "${n.memoryId}" and experienceId: "${n.experienceId}"`,state:{experienceId:n.experienceId,memoryId:n.memoryId},success:!0}:{content:n.message,success:!1}}catch(e){return{content:`addExperienceMemory with error detail: ${e.message}`,success:!1}}}async addIdentityMemory(e){if(this.isReadOnly)return A6;try{let t=E6.parse(e),n=await this.service.addIdentityMemory(t);return n.success?{content:`Identity memory "${t.title}" saved with memoryId: "${n.memoryId}" and identityId: "${n.identityId}"`,state:{identityId:n.identityId,memoryId:n.memoryId},success:!0}:{content:n.message,success:!1}}catch(e){return{content:`addIdentityMemory with error detail: ${e.message}`,success:!1}}}async addPreferenceMemory(e){if(this.isReadOnly)return A6;try{let t=k6.parse(e),n=await this.service.addPreferenceMemory(t);return n.success?{content:`Preference memory "${t.title}" saved with memoryId: "${n.memoryId}" and preferenceId: "${n.preferenceId}"`,state:{memoryId:n.memoryId,preferenceId:n.preferenceId},success:!0}:{content:n.message,success:!1}}catch(e){return{content:`addPreferenceMemory with error detail: ${e.message}`,success:!1}}}async updateIdentityMemory(e){if(this.isReadOnly)return A6;try{let t=D6.parse(e),n=await this.service.updateIdentityMemory(t);return n.success?{content:`Identity memory updated: ${t.id}`,state:{identityId:t.id},success:!0}:{content:n.message,success:!1}}catch(e){return{content:`updateIdentityMemory with error detail: ${e.message}`,success:!1}}}async removeIdentityMemory(e){if(this.isReadOnly)return A6;try{let t=O6.parse(e),n=await this.service.removeIdentityMemory(t);return n.success?{content:`Identity memory removed: ${t.id}\nReason: ${t.reason}`,state:{identityId:t.id,reason:t.reason},success:!0}:{content:n.message,success:!1}}catch(e){return{content:`removeIdentityMemory with error detail: ${e.message}`,success:!1}}}}})),uIe,dIe,fIe=e((()=>{Ne(),cie(),Gr(),qr(),lIe(),oq(),tq(),uIe=class extends ye{identifier=nq;apiEnum=eq;runtime;constructor(){super(),this.runtime=new cIe({service:sie})}resolveToolPermission=e=>{let t=Xr();return t&&(e?Hr.getChatConfigById(e)(t):$r.currentChatConfig(t))?.memory?.toolPermission===`read-only`?`read-only`:`read-write`};ensureWritable=e=>{if(this.resolveToolPermission(e)===`read-only`)throw Error(`Memory tool is 
5697in read-only mode for this chat`)};resolveMemoryEffort=e=>{let t=Xr();if(t)return(e?Hr.getChatConfigById(e)(t):$r.currentChatConfig(t))?.memory?.effort};searchUserMemory=async(e,t)=>this.runtime.searchUserMemory({...e,effort:this.resolveMemoryEffort(t?.agentId)});queryTaxonomyOptions=async e=>this.runtime.queryTaxonomyOptions(e);addContextMemory=async(e,t)=>(this.ensureWritable(t?.agentId),this.runtime.addContextMemory(e));addActivityMemory=async(e,t)=>(this.ensureWritable(t?.agentId),this.runtime.addActivityMemory(e));addExperienceMemory=async(e,t)=>(this.ensureWritable(t?.agentId),this.runtime.addExperienceMemory(e));addIdentityMemory=async(e,t)=>(this.ensureWritable(t?.agentId),this.runtime.addIdentityMemory(e));addPreferenceMemory=async(e,t)=>(this.ensureWritable(t?.agentId),this.runtime.addPreferenceMemory(e));updateIdentityMemory=async(e,t)=>(this.ensureWritable(t?.agentId),this.runtime.updateIdentityMemory(e));removeIdentityMemory=async(e,t)=>(this.ensureWritable(t?.agentId),this.runtime.removeIdentityMemory(e))},dIe=new uIe})),pIe,j6,M6=e((()=>{pa(),pIe=class{find=async e=>q.task.find.query({id:e});getDetail=async e=>q.task.detail.query({id:e});list=async e=>q.task.list.query(e);groupList=async e=>q.task.groupList.query(e);getSubtasks=async e=>q.task.getSubtasks.query({id:e});getTaskTree=async e=>q.task.getTaskTree.query({id:e});getTopics=async e=>q.task.getTopics.query({id:e});getDependencies=async e=>q.task.getDependencies.query({id:e});getPinnedDocuments=async e=>q.task.getPinnedDocuments.query({id:e});getCheckpoint=async e=>q.task.getCheckpoint.query({id:e});getReview=async e=>q.task.getReview.query({id:e});getVerifyConfig=async e=>q.task.getVerifyConfig.query({id:e});create=async e=>q.task.create.mutate(e);updateVisibility=async(e,t)=>q.task.updateVisibility.mutate({id:e,visibility:t});update=async(e,t)=>q.task.update.mutate({id:e,...t});delete=async e=>q.task.delete.mutate({id:e});clearAll=async()=>q.task.clearAll.mutate();updateStatus=async(e,t,n)=>q.task.updateStatus.mutate({error:n,id:e,status:t});run=async(e,t)=>q.task.run.mutate({id:e,...t});previewSubtaskLayers=async e=>q.task.previewSubtaskLayers.query({id:e});runReadySubtasks=async e=>q.task.runReadySubtasks.mutate({id:e});addComment=async(e,t,n)=>q.task.addComment.mutate({content:t,id:e,...n});deleteComment=async e=>q.task.deleteComment.mutate({commentId:e});updateComment=async(e,t,n)=>q.task.updateComment.mutate({commentId:e,content:t,...n});addDependency=async(e,t,n=`blocks`)=>q.task.addDependency.mutate({dependsOnId:t,taskId:e,type:n});removeDependency=async(e,t)=>q.task.removeDependency.mutate({dependsOnId:t,taskId:e});reorderSubtasks=async(e,t)=>q.task.reorderSubtasks.mutate({id:e,order:t});cancelTopic=async e=>q.task.cancelTopic.mutate({topicId:e});deleteTopic=async e=>q.task.deleteTopic.mutate({topicId:e});updateConfig=async(e,t)=>q.task.updateConfig.mutate({config:t,id:e});updateCheckpoint=async(e,t)=>q.task.updateCheckpoint.mutate({checkpoint:t,id:e});updateReview=async(...e)=>q.task.updateReview.mutate(...e);updateVerifyConfig=async(...e)=>q.task.updateVerifyConfig.mutate(...e);runReview=async(e,t)=>q.task.runReview.mutate({id:e,...t});pinDocument=async(e,t,n)=>q.task.pinDocument.mutate({documentId:t,pinnedBy:n,taskId:e});unpinDocument=async(e,t)=>q.task.unpinDocument.mutate({documentId:t,taskId:e});resolveBrief=async(e,t)=>q.brief.resolve.mutate({id:e,...t});markBriefRead=async e=>q.brief.markRead.mutate({id:e});copyTaskToWorkspace=async(e,t,n)=>q.task.copyTaskToWorkspace.mutate({targetVisibility:n,targetWorkspaceId:t,taskId:e})},j6=new pIe})),mIe,hIe=e((()=>{mIe={isCreatingTask:!1,isDeletingTask:!1,taskDetailMap:{},taskSaveStatusMap:{}}})),gIe,_Ie=e((()=>{gIe={isTaskGroupListInit:!1,isTaskListInit:!1,listVisibility:`all`,taskGroups:[],tasks:[],tasksTotal:0,viewMode:`list`}})),vIe,yIe=e((()=>{hIe(),_Ie(),vIe={...gIe,...mIe}}));async function N6(e,t,n){let{mutate:r,name:i=`runMutation`,onError:a,optimistic:o,rethrow:s=!0,setStatus:c}=n;c?.(`saving`);let l;if(o){let[n,r,a]=et(t(),o);r.length>0&&(l=a,e(n,!1,`${i}/optimistic`))}try{let e=await r();return c?.(`saved`),e}catch(n){if(l&&e(st(t(),l),!1,`${i}/rollback`),c?.(`failed`),await a?.(n),s)throw n;return}}var P6=e((()=>{it()})),F6,I6=e((()=>{or(),f(),uie(),F6=(e,t={})=>{let{retry:n,title:r}=t,{retryable:i}=lie(e);return fn.error({actions:n&&i?[{label:o(`saveState.retry`,{ns:`error`}),onClick:n,variant:`primary`}]:void 0,title:r??o(`saveState.saveFailed`,{ns:`error`})})}})),bIe,xIe,L6,SIe,CIe,wIe=e((()=>{M6(),tie(),P6(),I6(),bIe=600,xIe=`0 9 * * *`,L6=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||`UTC`}catch{return`UTC`}},SIe=(e,t,n)=>new CIe(e,t,n),CIe=class{#e;#t;#n;constructor(e,t,n){this.#t=e,this.#e=t}#r=()=>(this.#n||=new rie({getState:()=>({taskDetailMap:this.#e().taskDetailMap}),setState:e=>this.#t(e,!1,`taskConfig/automationEngine`)},{maxRetries:0}),this.#n);markBriefRead=async e=>{await j6.markBriefRead(e);let{activeTaskId:t,internal_refreshTaskDetail:n}=this.#e();t&&await n(t)};resolveBrief=async(e,t)=>{await j6.resolveBrief(e,t);let{activeTaskId:n,internal_refreshTaskDetail:r}=this.#e();n&&await r(n)};runReview=async(e,t)=>{try{let n=await j6.runReview(e,t);return await this.#e().internal_refreshTaskDetail(e),n}catch(e){throw console.error(`[TaskStore] Failed to run review:`,e),e}};updateCheckpoint=async(e,t)=>{this.#e().internal_dispatchTaskDetail({id:e,type:`updateTaskDetail`,value:{checkpoint:t}});try{await j6.updateCheckpoint(e,t),await this.#e().internal_refreshTaskDetail(e)}catch(t){console.error(`[TaskStore] Failed to update checkpoint:`,t),await this.#e().internal_refreshTaskDetail(e)}};updateReview=async(e,t)=>{try{await j6.updateReview({id:e,review:t}),await this.#e().internal_refreshTaskDetail(e)}catch(t){console.error(`[TaskStore] Failed to update review:`,t),await this.#e().internal_refreshTaskDetail(e)}};updateVerifyConfig=async(e,t)=>{try{await j6.updateVerifyConfig({id:e,verify:t}),await this.#e().internal_refreshTaskDetail(e)}catch(t){console.error(`[TaskStore] Failed to update verify config:`,t),await this.#e().internal_refreshTaskDetail(e)}};updateTaskModelConfig=async(e,t)=>{this.#e().internal_dispatchTaskDetail({id:e,type:`updateTaskDetail`,value:{config:{...this.#e().taskDetailMap[e]?.config,...t}}}),await N6(this.#t,this.#e,{mutate:async()=>{await j6.updateConfig(e,t),await this.#e().internal_refreshTaskDetail(e)},name:`updateTaskModelConfig`,onError:async n=>{console.error(`[TaskStore] Failed to update task model config:`,n),await this.#e().internal_refreshTaskDetail(e),F6(n,{retry:()=>void this.#e().updateTaskModelConfig(e,t)})},rethrow:!1,setStatus:t=>this.#e().internal_setTaskSaveStatus(e,t)})};updatePeriodicInterval=async(e,t)=>{try{await j6.update(e,{heartbeatInterval:t??0}),await this.#e().internal_refreshTaskDetail(e)}catch(e){console.error(`[TaskStore] Failed to update periodic interval:`,e)}
5697};setAutomationMode=async(e,t)=>{let n=this.#e().taskDetailMap[e],r={automationMode:t};t===`heartbeat`&&!n?.heartbeat?.interval&&(r.heartbeatInterval=bIe),t===`schedule`&&(n?.schedule?.pattern?n?.schedule?.timezone||(r.scheduleTimezone=L6()):(r.schedulePattern=xIe,r.scheduleTimezone=L6()));let i=this.#r().createTransaction(`setAutomationMode(${e})`);i.set(n=>{let i=n.taskDetailMap[e];i&&(i.automationMode=t,r.heartbeatInterval!==void 0&&(i.heartbeat??={},i.heartbeat.interval=r.heartbeatInterval),r.schedulePattern!==void 0&&(i.schedule??={},i.schedule.pattern=r.schedulePattern),r.scheduleTimezone!==void 0&&(i.schedule??={},i.schedule.timezone=r.scheduleTimezone))}),i.mutation=async()=>{await j6.update(e,r)};try{await i.commit()}catch(e){console.error(`[TaskStore] Failed to update automation mode:`,e)}};updateSchedule=async(e,t)=>{let n=this.#e().taskDetailMap[e]?.config??{},r=n.schedule??{},i={...n,schedule:{...r,maxExecutions:t.maxExecutions}},a=this.#r().createTransaction(`updateSchedule(${e})`);a.set(n=>{let r=n.taskDetailMap[e];r&&(r.config=i,r.schedule={maxExecutions:t.maxExecutions,pattern:t.pattern,timezone:t.timezone})}),a.mutation=async()=>{await j6.update(e,{config:i,schedulePattern:t.pattern,scheduleTimezone:t.timezone})};try{await a.commit()}catch(e){console.error(`[TaskStore] Failed to update schedule:`,e)}}}})),TIe=e((()=>{wIe()})),EIe,R6,DIe,z6,B6=e((()=>{ti(),Qi(),oa(),pa(),EIe=new Set([br.runTask,br.runTasks,br.updateTaskStatus]),R6=({apiName:e,identifier:t,result:n,succeeded:r,workRegistration:i})=>{if(i)return!0;if(t!==`lobe-task`||!e||!EIe.has(e))return!1;if(e===br.runTasks){let e=n?.state?.succeeded;return typeof e==`number`?e>0:!0}return r},DIe=class{listByConversation=async e=>q.work.listByConversation.query(e);listByWorkspace=async e=>q.work.listByWorkspace.query(e);listByRootOperation=async e=>q.work.listByRootOperation.query(e);listByRootOperations=async e=>q.work.listByRootOperations.query(e);listVersions=async e=>q.work.listVersions.query({workId:e});registerTask=async e=>q.work.registerTask.mutate(e);registerDocument=async e=>q.work.registerDocument.mutate(e);deleteTaskWork=async e=>q.work.deleteTaskWork.mutate(e);handleSkillToolResult=async e=>q.work.handleSkillToolResult.mutate(e);refreshConversation=async(e,t)=>{e&&await Promise.all([this.refreshConversationMessages(e),this.refreshConversationViews(e,t)])};refreshConversationMessages=async e=>{await Zi(t=>ta(t,t=>t.topicId===e))};refreshAll=async()=>{await Zi(are(`work:`))};refreshConversationViews=async(e,t)=>{e&&await Promise.all([Zi(ra.conversation(e,t??null)),Zi(e=>Array.isArray(e)&&e[0]===ra.versions.root)])};refreshAllConversations=async()=>{await Promise.all([Zi(e=>ta(e)),this.refreshAll()])};refreshVersions=async e=>{e&&await Zi(ra.versions(e))}},z6=new DIe})),V6,H6,U6,OIe,kIe=e((()=>{it(),V6=(e,t)=>{for(let n of e)if(n.identifier===t||n.children&&V6(n.children,t))return!0;return!1},H6=(e,t)=>{for(let n in e){if(n===t)continue;let r=e[n]?.subtasks;if(r&&V6(r,t))return n}},U6=(e,t,n)=>{for(let r of e){if(r.identifier===t)return n.name!==void 0&&(r.name=n.name),n.priority!==void 0&&(r.priority=n.priority),n.agentId!==void 0&&(n.agentId===null?r.assignee=null:r.assignee=r.assignee?{...r.assignee,id:n.agentId}:{avatar:null,backgroundColor:null,id:n.agentId,title:null}),!0;if(r.children&&U6(r.children,t,n))return!0}return!1},OIe=(e,t)=>{switch(t.type){case`setTaskDetail`:return tt(e,e=>{e[t.id]=t.value});case`updateTaskDetail`:return tt(e,e=>{e[t.id]&&Object.assign(e[t.id],t.value);for(let n in e){let r=e[n]?.subtasks;if(r&&U6(r,t.id,t.value))break}});case`deleteTaskDetail`:return tt(e,e=>{delete e[t.id]});default:return e}}})),AIe,jIe,W6,MIe,NIe,PIe,FIe=e((()=>{AIe=t(le()),f(),Qr(),Qi(),oa(),M6(),B6(),P6(),I6(),X6(),kIe(),jIe=1e4,W6=e=>e?.some(e=>!!e.runningTopic||e.status===`running`||e.status===`pending`||W6(e.children))??!1,MIe=e=>e?e.status===`running`||e.status===`pending`||W6(e.subtasks)?!0:e.activities?.some(e=>e.type===`topic`&&(e.status===`running`||e.status===`pending`))??!1:!1,NIe=(e,t,n)=>new PIe(e,t,n),PIe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}addComment=async(e,t,n)=>{let r=await j6.addComment(e,t,n);return await this.internal_refreshTaskDetail(e),r};deleteComment=async(e,t)=>{await j6.deleteComment(e);let n=t??this.#e().activeTaskId;n&&await this.internal_refreshTaskDetail(n)};updateComment=async(e,t,n)=>{let{taskId:r,...i}=n??{};await j6.updateComment(e,t,i);let a=r??this.#e().activeTaskId;a&&await this.internal_refreshTaskDetail(a)};addDependency=async(e,t,n)=>{await j6.addDependency(e,t,n),await this.internal_refreshTaskDetail(e)};fetchTaskDetail=async e=>{let t=e??this.#e().activeTaskId;if(!t)throw Error(`No task identifier provided and no current task context.`);let n=(await j6.getDetail(t)).data;if(!n){let e=Error(`Task not found: ${t}`);throw e.code=`TASK_NOT_FOUND`,e}return this.internal_dispatchTaskDetail({id:n.identifier,type:`setTaskDetail`,value:n}),t!==n.identifier&&this.internal_dispatchTaskDetail({id:t,type:`setTaskDetail`,value:n}),n};createTask=async e=>{this.#t({isCreatingTask:!0},!1,`createTask/start`);try{let t=await j6.create(e);return await this.#e().refreshTaskList(),e.parentTaskId&&await this.internal_refreshTaskDetail(e.parentTaskId),t.data??null}finally{this.#t({isCreatingTask:!1},!1,`createTask/end`)}};deleteTask=async e=>{let t=this.#e().taskDetailMap[e];this.#t({isDeletingTask:!0},!1,`deleteTask/start`);try{this.internal_dispatchTaskDetail({id:e,type:`deleteTaskDetail`});let t=await j6.delete(e);this.#e().activeTaskId===e&&this.#t({activeTaskId:void 0},!1,`deleteTask/clearActive`),await this.#e().refreshTaskList();try{await z6.refreshAllConversations()}catch(e){console.error(`[task:deleteTask:refreshWork]`,e)}return t.data??null}catch(n){throw t&&this.internal_dispatchTaskDetail({id:e,type:`setTaskDetail`,value:t}),n}finally{this.#t({isDeletingTask:!1},!1,`deleteTask/end`)}};pinDocument=async(e,t)=>{await j6.pinDocument(e,t),await this.internal_refreshTaskDetail(e)};removeDependency=async(e,t)=>{await j6.removeDependency(e,t),await this.internal_refreshTaskDetail(e)};reorderSubtasks=async(e,t)=>{await j6.reorderSubtasks(e,t),await this.internal_refreshTaskDetail(e)};setActiveTaskId=e=>{this.#e().activeTaskId!==e&&this.#t({activeTaskId:e,activeTopicDrawerAgentId:void 0,activeTopicDrawerTitle:void 0,activeTopicDrawerTopicId:void 0},!1,`setActiveTaskId`)};openTopicDrawer=(e,t)=>{this.#e().activeTopicDrawerTopicId!==e&&this.#t({activeTopicDrawerAgentId:t?.agentId,activeTopicDrawerTitle:t?.title,activeTopicDrawerTopicId:e},!1,`openTopicDrawer`)};closeTopicDrawer=()=>{this.#e().activeTopicDrawerTopicId&&this.#t({activeTopicDrawerAgentId:void 0,activeTopicDrawerTitle:void 0,activeTopicDrawerTopicId:void 0},!1,`closeTopicDrawer`)};unpinDocument=async(e,t)=>{await j6.unpinDocument(e,t),await this.internal_refreshTaskDetail(e);let n=this.#e().activeTaskId;n&&n!==e&&await this.internal_refreshTaskDetail(n)};updateTaskVisibility=async(e,t)=>{try{await j6.updateVisibility(e,t),await Promise.all([this.#e().refreshTaskList(),this.internal_refreshTaskDetail(e)])}catch(e){let t=e?.message??``,n=/public task cannot be assigned to a private agent/i.test(t);throw zr.error(n?o(`taskDetail.publishToWorkspace.errorPrivateAgent`,{defaultValue:`This task is assigned to a private agent. Reassign to a workspace agent, or publish the agent first.`,ns:`chat`}):o(`createTask.visibility.changeFailed`,{defaultValue:`Failed to change task visibility`,ns:`chat`})),e}};updateTask=async(e,t)=>{let{assigneeAgentId:n,...r}=t,i={...r};delete i.parentTaskId;let a={...i,...n===void 0?{}:{agentId:n}},o=H6(this.#e().taskDetailMap,e),s=this.#e().activeTaskId,c=async()=>{let n=new Set([e]);o&&n.add(o),t.parentTaskId&&n.add(t.parentTaskId),s&&n.add(s),await Promise.all(Array.from(n).map(e=>this.internal_refreshTaskDetail(e)))};this.internal_dispatchTaskDetail({id:e,type:`updateTaskDetail`,value:a}),await N6(this.#t,this.#e,{mutate:()=>j6.update(e,t),name:`updateTask`,onError:async n=>{await c(),F6(n,{retry:()=>void this.#e().updateTask(e,t)})},setStatus:t=>this.#e().internal_setTaskSaveStatus(e,t)}),(n!==void 0||t.parentTaskId!==void 0)&&await Promise.all([this.#e().refreshTaskList(),c()]).catch(()=>{})};useFetchTaskDetail=e=>{let t=J6(t=>MIe(e?t.taskDetailMap[e]:void 0));return Xi(e?ua.detail(e):null,async([,e])=>this.fetchTaskDetail(e),{refreshInterval:t?jIe:0})};internal_setTaskSaveStatus=(e,t)=>{this.#t({taskSaveStatusMap:{...this.#e().taskSaveStatusMap,[e]:t}},!1,`setTaskSaveStatus/${t}`)};internal_dispatchTaskDetail=e=>{let t=this.#e().taskDetailMap,n=OIe(t,e);(0,AIe.default)(n,t)||this.#t({taskDetailMap:n},!1,`internal_dispatchTaskDetail/${e.type}`)};internal_refreshTaskDetail=async e=>{await Zi(ua.detail(e))}}})),IIe=e((()=>{FIe(),hIe()}
5697)),LIe,RIe,zIe=e((()=>{M6(),P6(),I6(),LIe=(e,t,n)=>new RIe(e,t,n),RIe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}cancelTopic=async e=>{await j6.cancelTopic(e);let{activeTaskId:t,internal_refreshTaskDetail:n}=this.#e();t&&await n(t)};deleteTopic=async e=>{await j6.deleteTopic(e);let{activeTaskId:t,internal_refreshTaskDetail:n}=this.#e();t&&await n(t)};runTask=async(e,t)=>{this.#e().internal_dispatchTaskDetail({id:e,type:`updateTaskDetail`,value:{error:null,status:`running`}});try{await j6.run(e,t),await this.#e().internal_refreshTaskDetail(e),await this.#e().refreshTaskList()}catch(t){console.error(`[TaskStore] Failed to run task:`,t),await this.#e().internal_refreshTaskDetail(e)}};runReadySubtasks=async e=>{let t=await j6.runReadySubtasks(e);return await this.#e().internal_refreshTaskDetail(e),await this.#e().refreshTaskList(),t};updateTaskStatus=async(e,t,n)=>{let{error:r}=n??{},i=e??this.#e().activeTaskId;if(!i)throw Error(`No task identifier provided and no current task context.`);let a={status:t};return t===`failed`&&r&&(a.error=r),await this.#n(i,t,a,r),i};#n=async(e,t,n,r)=>{this.#e().internal_dispatchTaskDetail({id:e,type:`updateTaskDetail`,value:{status:t,...n}}),await N6(this.#t,this.#e,{mutate:async()=>{await j6.updateStatus(e,t,r),await this.#e().internal_refreshTaskDetail(e),await this.#e().refreshTaskList()},name:`transitionStatus`,onError:async i=>{console.error(`[TaskStore] Failed to transition task to ${t}:`,i),await this.#e().internal_refreshTaskDetail(e),F6(i,{retry:()=>void this.#n(e,t,n,r)})},setStatus:t=>this.#e().internal_setTaskSaveStatus(e,t)})}}})),BIe=e((()=>{zIe()})),G6,VIe,K6,q6,HIe,UIe,WIe=e((()=>{Qi(),oa(),M6(),G6=`__all__`,VIe=[{key:`needsInput`,statuses:[`paused`,`failed`]},{key:`backlog`,statuses:[`backlog`]},{key:`running`,statuses:[`running`,`scheduled`]},{key:`done`,statuses:[`completed`]},{key:`canceled`,statuses:[`canceled`]}],K6=e=>{if(e!==`all`)return e===`workspace`?`public`:`private`},q6={isTaskGroupListInit:!1,isTaskListInit:!1,taskGroups:[],tasks:[],tasksTotal:0},HIe=(e,t,n)=>new UIe(e,t,n),UIe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}refreshTaskGroupList=async()=>{let{listAgentId:e,listVisibility:t}=this.#e();await Zi(ua.groupList(e,t))};fetchTaskList=async e=>j6.list(e);refreshTaskList=async()=>{let{listAgentId:e,listVisibility:t}=this.#e();await Promise.all([Zi(ua.list(e,t)),Zi(ua.groupList(e,t))])};setListAgentId=e=>{this.#t({listAgentId:e},!1,`setListAgentId`)};setListVisibility=e=>{this.#e().listVisibility!==e&&this.#t({...q6,listVisibility:e},!1,`setListVisibility`)};setViewMode=e=>{this.#t({viewMode:e},!1,`setViewMode`)};useFetchTaskGroupList=(e={})=>{let{agentId:t,allAgents:n=!1,enabled:r=!0}=e,i=n?G6:t;i&&this.#e().listAgentId!==i&&this.#t({...q6,listAgentId:i},!1,`useFetchTaskGroupList/syncAgentId`);let a=this.#e().listVisibility;return Xi(r&&i?ua.groupList(i,a):null,async()=>j6.groupList({assigneeAgentId:n?void 0:t,groups:VIe,visibility:K6(a)}),{onSuccess:e=>{this.#t({isTaskGroupListInit:!0,taskGroups:e.data},!1,`useFetchTaskGroupList/onSuccess`)},revalidateOnFocus:!1})};useFetchTaskList=(e={})=>{let{agentId:t,allAgents:n=!1,enabled:r=!0}=e,i=n?G6:t;i&&this.#e().listAgentId!==i&&this.#t({...q6,listAgentId:i},!1,`useFetchTaskList/syncAgentId`);let a=this.#e().listVisibility;return Xi(r&&i?ua.list(i,a):null,async([,e])=>this.fetchTaskList({...n?{}:{assigneeAgentId:e},visibility:K6(a)}),{onSuccess:e=>{this.#t({isTaskListInit:!0,tasks:e.data,tasksTotal:e.total},!1,`useFetchTaskList/onSuccess`)},revalidateOnFocus:!1})}}})),GIe=e((()=>{WIe(),_Ie()})),KIe,qIe,JIe,J6,Y6,X6=e((()=>{y(),d(),gt(),at(),ft(),ct(),yIe(),TIe(),IIe(),BIe(),GIe(),KIe=class extends pt{resetActionName=`resetTaskStore`},qIe=(...e)=>({...vIe,...rt([HIe(...e),NIe(...e),LIe(...e),SIe(...e),new KIe(...e)])}),JIe=lt(`task`),J6=b()(JIe(qIe),l),mt(`task`,J6),Y6=()=>J6.getState()})),Z6=e((()=>{X6()})),YIe,Q6,$6,e8,t8,XIe,ZIe,QIe,$Ie=e((()=>{Mi(),Ne(),YIe=t(F()),Za(),M6(),bc(),Z6(),kIe(),Mee(),Fee(),ute(),Q6=(0,YIe.default)(`lobe-task:executor`),$6=()=>{let e=Qa();return e?`/${e}`:void 0},e8=new Set([br.createTask,br.createTasks,br.deleteTask,br.editTask,br.runTask,br.runTasks,br.setTaskSchedule,br.updateTaskStatus]),t8=new Set([br.addTaskComment,br.deleteTaskComment,br.editTask,br.runTask,br.setTaskSchedule,br.setTaskVerify,br.updateTaskComment,br.updateTaskStatus,br.viewTask]),XIe=(e,t)=>{let n=t.state?.identifier;if(typeof n==`string`&&n.length>0)return n;let r=e?.identifier;if(typeof r==`string`&&r.length>0)return r},ZIe=class extends ye{identifier=wr;apiEnum=br;onAfterCall=async({apiName:e,params:t,result:n})=>{if(!n.success)return;let r=Y6(),i=XIe(t,n);e===br.createTask&&i&&Q9().openTaskDetail(i);let a=new Set;
5697if(t8.has(e)||e8.has(e)){if(i){t8.has(e)&&a.add(i);let t=H6(r.taskDetailMap,i);t&&a.add(t)}let{activeTaskId:t}=r;t&&a.add(t)}let o=[];e8.has(e)&&o.push(r.refreshTaskList());for(let e of a)o.push(r.internal_refreshTaskDetail(e));o.length!==0&&await Promise.all(o).catch(e=>{Q6(`[TaskExecutor] onAfterCall - refresh failed:`,e)})};addTaskComment=async(e,t)=>{let n=e.identifier?.trim()||t?.taskId||void 0;if(!n)return{content:`No task identifier provided.`,error:{message:`identifier is required`,type:`MissingIdentifier`},success:!1};try{Q6(`[TaskExecutor] addTaskComment - identifier:`,n);let r=(await Y6().addComment(n,e.content,{authorAgentId:t?.agentId}))?.data?.id;return{content:`Comment added to task ${n}.`,state:{commentId:r,identifier:n,success:!0},success:!0}}catch(e){Q6(`[TaskExecutor] addTaskComment - error:`,e);let t=e instanceof Error?e.message:`Failed to add task comment`;return{content:`Failed to add task comment: ${t}`,error:{message:t,type:`AddTaskCommentFailed`},success:!1}}};#e=async(e,t)=>{try{Q6(`[TaskExecutor] createTask - params:`,e);let n=e.parentIdentifier?.trim()||void 0,r=await Y6().createTask({assigneeAgentId:e.assigneeAgentId??(t?.scope===`task`?void 0:t?.agentId),createdByAgentId:t?.agentId,instruction:e.instruction,name:e.name,parentTaskId:n,priority:e.priority});return r?{content:bne({baseUrl:$6(),identifier:r.identifier,instruction:e.instruction,name:r.name,parentLabel:n,priority:r.priority,status:r.status}),state:{description:r.description,identifier:r.identifier,name:r.name,parentIdentifier:n,priority:r.priority,status:r.status,success:!0,taskId:r.id},success:!0}:{content:`Failed to create task`,error:{message:`No data returned`,type:`CreateFailed`},success:!1}}catch(e){Q6(`[TaskExecutor] createTask - error:`,e);let t=e instanceof Error?e.message:String(e)||`Unknown error`;return{content:t.startsWith(`Failed to create task`)?t:`Failed to create task: ${t}`,error:{message:t,type:`CreateTaskFailed`},success:!1}}};createTask=async(e,t)=>this.#e(e,t);createTasks=async(e,t)=>{Q6(`[TaskExecutor] createTasks - count:`,e.tasks?.length);let n=Array.isArray(e.tasks)?e.tasks:[];if(n.length===0)return{content:`No tasks provided.`,error:{message:`tasks array is empty`,type:`EmptyBatch`},success:!1};let r=[];for(let e of n){let n=await this.#e(e,t),i=n.success===!0,a=i?void 0:n.error?.message||(typeof n.content==`string`?n.content:`Unknown error`),o=n.state?.identifier;r.push({error:a,identifier:o,name:e.name,success:i})}let i=r.filter(e=>e.success).length,a=r.length-i;return{content:Sne(r,$6()),state:{failed:a,results:r,succeeded:i},success:a===0}};deleteTask=async(e,t)=>{try{Q6(`[TaskExecutor] deleteTask - params:`,e);let t=await Y6().deleteTask(e.identifier),n=t?.identifier??e.identifier;return{content:sne(n,t?.name),state:{identifier:n,success:!0,taskId:t?.id},success:!0}}catch(e){Q6(`[TaskExecutor] deleteTask - error:`,e);let t=e instanceof Error?e.message:`Failed to delete task`;return{content:`Failed to delete task: ${t}`,error:{message:t,type:`DeleteTaskFailed`},success:!1}}};deleteTaskComment=async(e,t)=>{try{return Q6(`[TaskExecutor] deleteTaskComment - commentId:`,e.commentId),await Y6().deleteComment(e.commentId,t?.taskId??void 0),{content:`Comment ${e.commentId} deleted.`,state:{commentId:e.commentId,success:!0},success:!0}}catch(e){Q6(`[TaskExecutor] deleteTaskComment - error:`,e);let t=e instanceof Error?e.message:`Failed to delete task comment`;return{content:`Failed to delete task comment: ${t}`,error:{message:t,type:`DeleteTaskCommentFailed`},success:!1}}};editTask=async(e,t)=>{try{Q6(`[TaskExecutor] editTask - params:`,e);let{identifier:t,addDependencies:n,removeDependencies:r}=e,i=Y6(),a=[],o=[],s={};if(e.name!==void 0&&(s.name=e.name,a.push(`name → "${e.name}"`)),e.assigneeAgentId!==void 0&&(s.assigneeAgentId=e.assigneeAgentId,a.push(e.assigneeAgentId?`assignee agent → ${e.assigneeAgentId}`:`assignee cleared`)),e.instruction!==void 0&&(s.instruction=e.instruction,a.push(`instruction updated`)),e.description!==void 0&&(s.description=e.description,a.push(`description updated`)),e.parentIdentifier!==void 0){let t=e.parentIdentifier?.trim()||null;s.parentTaskId=t,a.push(t?`parent → ${t}`:`parent cleared`)}return e.priority!==void 0&&(s.priority=e.priority,a.push(`priority → ${dne(e.priority)}`)),Object.keys(s).length>
56970&&o.push(i.updateTask(t,s)),n?.length&&n.forEach(e=>{o.push(i.addDependency(t,e)),a.push(Tne(t,e))}),r?.length&&r.forEach(e=>{o.push(i.removeDependency(t,e)),a.push(One(t,e))}),await Promise.all(o),{content:Ri(t,a),state:{identifier:t,success:!0},success:!0}}catch(e){Q6(`[TaskExecutor] editTask - error:`,e);let t=e instanceof Error?e.message:`Failed to edit task`;return{content:`Failed to edit task: ${t}`,error:{message:t,type:`EditTaskFailed`},success:!1}}};setTaskSchedule=async(e,t)=>{try{Q6(`[TaskExecutor] setTaskSchedule - params:`,e);let{identifier:t}=e,n=Y6(),r=[],i=[],a={};return e.automationMode!==void 0&&(a.automationMode=e.automationMode,r.push(e.automationMode?`automation mode → ${e.automationMode}`:`automation disabled`)),e.heartbeatInterval!==void 0&&(a.heartbeatInterval=e.heartbeatInterval,r.push(e.heartbeatInterval>0?`heartbeat interval → ${e.heartbeatInterval}s`:`heartbeat interval cleared`)),e.schedulePattern!==void 0&&(a.schedulePattern=e.schedulePattern,r.push(e.schedulePattern?`schedule pattern → "${e.schedulePattern}"`:`schedule pattern cleared`)),e.scheduleTimezone!==void 0&&(a.scheduleTimezone=e.scheduleTimezone,r.push(e.scheduleTimezone?`schedule timezone → ${e.scheduleTimezone}`:`schedule timezone cleared`)),Object.keys(a).length>0&&i.push(j6.update(t,a)),e.maxExecutions!==void 0&&(i.push(j6.updateConfig(t,{schedule:{maxExecutions:e.maxExecutions}})),r.push(e.maxExecutions===null?`max executions cleared (unlimited)`:`max executions → ${e.maxExecutions}`)),i.length===0?{content:`No schedule fields provided; nothing to update.`,error:{message:`No schedule fields provided.`,type:`NoFields`},success:!1}:(await Promise.all(i),await n.internal_refreshTaskDetail(t),{content:Ri(t,r),state:{automationMode:e.automationMode,identifier:t,success:!0},success:!0})}catch(e){Q6(`[TaskExecutor] setTaskSchedule - error:`,e);let t=e instanceof Error?e.message:`Failed to set task schedule`;return{content:`Failed to set task schedule: ${t}`,error:{message:t,type:`SetTaskScheduleFailed`},success:!1}}};setTaskVerify=async(e,t)=>{try{Q6(`[TaskExecutor] setTaskVerify - params:`,e);let{identifier:t}=e,n={},r=[];return e.enabled!==void 0&&(n.enabled=e.enabled,r.push(e.enabled===null?`verify enabled cleared`:`verify ${e.enabled?`enabled`:`disabled`}`)),e.requirement!==void 0&&(n.requirement=e.requirement,r.push(e.requirement?`acceptance requirement set`:`acceptance requirement cleared`)),e.maxIterations!==void 0&&(n.maxIterations=e.maxIterations,r.push(e.maxIterations===null?`max iterations cleared`:`max iterations → ${e.maxIterations}`)),e.verifierAgentId!==void 0&&(n.verifierAgentId=e.verifierAgentId,r.push(e.verifierAgentId?`verifier agent → ${e.verifierAgentId}`:`verifier agent cleared`)),e.verifyRubricId!==void 0&&(n.verifyRubricId=e.verifyRubricId,r.push(e.verifyRubricId?`verify rubric → ${e.verifyRubricId}`:`verify rubric cleared`)),e.verifyCriteriaIds!==void 0&&(n.verifyCriteriaIds=e.verifyCriteriaIds,r.push(e.verifyCriteriaIds?.length?`verify criteria → ${e.verifyCriteriaIds.length} item(s)`:`verify criteria cleared`)),Object.keys(n).length===0?{content:`No verify fields provided; nothing to update.`,error:{message:`No verify fields provided.`,type:`NoFields`},success:!1}:(await j6.updateVerifyConfig({id:t,verify:n}),await Y6().internal_refreshTaskDetail(t),{content:Ri(t,r),state:{enabled:e.enabled,identifier:t,success:!0},success:!0})}catch(e){Q6(`[TaskExecutor] setTaskVerify - error:`,e);let t=e instanceof Error?e.message:`Failed to set task verify config`;return{content:`Failed to set task verify config: ${t}`,error:{message:t,type:`SetTaskVerifyFailed`},success:!1}}};listTasks=async(e,t)=>{try{Q6(`[TaskExecutor] listTasks - params:`,e);let n=cte(e,{currentAgentId:t?.agentId,defaultScope:t?.scope===`task`?`allAgents`:`currentAgent`}),r=await Y6().fetchTaskList(n.query),i=r.data??[];return{content:cne(i,n.displayFilters),state:{count:i.length,success:!0,total:r.total},success:!0}}catch(e){Q6(`[TaskExecutor] listTasks - error:`,e);let t=e instanceof Error?e.message:`Failed to list tasks`;return{content:`Failed to list tasks: ${t}`,error:{message:t,type:`ListTasksFailed`},success:!1}}};runTask=async(e,t)=>{let n=e.identifier?.trim()||t?.taskId||void 0;if(!n)return{content:`No task identifier provided.`,error:{message:`identifier is required`,type:`MissingIdentifier`},success:!1};try{Q6(`[TaskExecutor] runTask - identifier:`,n);let t=await j6.run(n,{continueTopicId:e.continueTopicId,prompt:e.prompt}
5697),r=t?.topicId,i=t?.operationId,a=Y6();await Promise.all([a.internal_refreshTaskDetail(n),a.refreshTaskList()]);let o=[`Task ${n} started.`];return r&&o.push(`  Topic: ${r}`),i&&o.push(`  Operation: ${i}`),{content:o.join(`
5698`),state:{identifier:n,operationId:i,success:!0,topicId:r},success:!0}}catch(e){Q6(`[TaskExecutor] runTask - error:`,e);let t=e instanceof Error?e.message:`Failed to run task`;return{content:`Failed to run task ${n}: ${t}`,error:{message:t,type:`RunTaskFailed`},success:!1}}};runTasks=async(e,t)=>{let n=Array.isArray(e.identifiers)?e.identifiers.map(e=>e?.trim()).filter(e=>!!e):[];if(n.length===0)return{content:`No task identifiers provided.`,error:{message:`identifiers array is empty`,type:`EmptyBatch`},success:!1};Q6(`[TaskExecutor] runTasks - count:`,n.length);let r=[],i=[];for(let[e,t]of n.entries())try{let n=await j6.run(t),a=n?.topicId,o=n?.operationId;r.push({identifier:t,operationId:o,success:!0,topicId:a}),i.push(`${e+1}. ${t} — started${a?` (topic ${a})`:``}`)}catch(n){let a=n instanceof Error?n.message:`Unknown error`;r.push({error:a,identifier:t,success:!1}),i.push(`${e+1}. ${t} — failed: ${a}`)}try{await Y6().refreshTaskList()}catch{}let a=r.filter(e=>e.success).length,o=r.length-a;return{content:[o===0?`Started ${a} task${a===1?``:`s`}:`:`Started ${a}/${r.length} tasks (${o} failed):`,...i].join(`
5699`),state:{failed:o,results:r,succeeded:a},success:o===0}};updateTaskComment=async(e,t)=>{try{return Q6(`[TaskExecutor] updateTaskComment - commentId:`,e.commentId),await Y6().updateComment(e.commentId,e.content,{taskId:t?.taskId??void 0}),{content:`Comment ${e.commentId} updated.`,state:{commentId:e.commentId,success:!0},success:!0}}catch(e){Q6(`[TaskExecutor] updateTaskComment - error:`,e);let t=e instanceof Error?e.message:`Failed to update task comment`;return{content:`Failed to update task comment: ${t}`,error:{message:t,type:`UpdateTaskCommentFailed`},success:!1}}};updateTaskStatus=async(e,t)=>{try{Q6(`[TaskExecutor] updateTaskStatus - params:`,e);let n=e.identifier??t?.taskId??void 0,r=await Y6().updateTaskStatus(n,e.status,{error:e.error});return{content:e.status===`failed`&&e.error?`Task ${r} status updated to failed. Error: ${e.error}`:`Task ${r} status updated to ${e.status}.`,state:{status:e.status,success:!0},success:!0}}catch(e){Q6(`[TaskExecutor] updateTaskStatus - error:`,e);let t=e instanceof Error?e.message:`Failed to update task status`;return{content:`Failed to update task status: ${t}`,error:{message:t,type:`UpdateStatusFailed`},success:!1}}};viewTask=async(e,t)=>{try{Q6(`[TaskExecutor] viewTask - params:`,e);let n=await Y6().fetchTaskDetail(e.identifier??t?.taskId??void 0);return{content:Ene(n),state:{identifier:n.identifier,success:!0},success:!0}}catch(e){Q6(`[TaskExecutor] viewTask - error:`,e);let t=e instanceof Error?e.message:`Failed to view task`;return{content:`Failed to view task: ${t}`,error:{message:t,type:`ViewTaskFailed`},success:!1}}}},QIe=new ZIe})),n8,eLe,tLe,nLe,rLe,r8,iLe,aLe,oLe,sLe,cLe,lLe,uLe,dLe,i8,fLe,pLe,mLe,a8,hLe,o8,s8,c8,gLe,l8,_Le,vLe,u8,d8,f8,yLe,bLe,p8,m8,xLe,SLe,CLe,wLe,TLe,ELe,DLe,OLe,kLe,ALe,jLe,MLe,NLe,PLe,FLe,ILe,LLe,h8,RLe,g8,_8,v8,y8,b8,zLe,BLe,VLe,x8,S8,C8,w8,HLe,ULe,WLe,GLe,KLe,qLe,JLe,YLe=e((()=>{Wt(),Ne(),n8=t(le()),Qi(),oa(),ka(),Oi(),$9(),Vr(),eLe=new Set([`-b`,`-B`,`--reason`]),tLe=new Set([`-b`,`-B`]),nLe=new Set([`-b`,`-B`,`-c`,`-C`,`--create`,`--force-create`,`--orphan`]),rLe=new Set([`-d`,`--detach`]),r8=new Set([`checkout`,`switch`]),iLe=new Set([`--conflict`,`--pathspec-from-file`]),aLe=new Set([`-B`,`-H`,`-R`,`-t`,`--base`,`--body`,`--body-file`,`--head`,`--label`,`--milestone`,`--project`,`--recover`,`--repo`,`--reviewer`,`--template`,`--title`]),oLe=new Set([`-R`,`--config-dir`,`--git-protocol`,`--hostname`,`--repo`]),sLe=/https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/(\d+)/i,cLe=[/Switched to (?:a new )?branch ['"]([^'"\n]+)['"]/i,/Already on ['"]([^'"\n]+)['"]/i,/branch ['"]([^'"\n]+)['"] set up to track/i],lLe=/^(?:Created|Entered) worktree at (.+?)(?: on branch (\S+))?\. /,uLe=/^Exited\b/,dLe=`The session is now working in the worktree`,i8=e=>{if(e.length>=2){let t=e[0],n=e.at(-1);if(t===`"`&&n===`"`||t===`'`&&n===`'`)return e.slice(1,-1)}return e},fLe=e=>e.startsWith(`/`)||e.startsWith(`~`)||/^[A-Z]:[\\/]/i.test(e)||e.startsWith(`\\\\`),pLe=/\$\{([A-Z_]\w*)\}|\$([A-Z_]\w*)/gi,mLe=(e,t)=>e.replaceAll(pLe,(e,n,r)=>t[n??r]??e),a8=(e,t)=>{let n=i8(e);return!t||e.startsWith(`'`)?n:mLe(n,t)},hLe=e=>
5699!/["$'`]/.test(e)&&!e.startsWith(`~`),o8=(e,t)=>{let n=+(i8(e[0]??``)===`export`);if(!(n>=e.length||!e.slice(n).every(e=>u8(e))))for(let r=n;r<e.length;r+=1){let n=e[r].indexOf(`=`);t[e[r].slice(0,n)]=a8(e[r].slice(n+1),t)}},s8=e=>i8(e).split(/[\\/]/).at(-1)?.toLowerCase(),c8=e=>{let t=s8(e);return t===`git`||t===`git.exe`},gLe=e=>{let t=s8(e);return t===`gh`||t===`gh.exe`},l8=e=>{let t=e?.trim();if(!(!t||t===`-`||/[$`]/.test(t)))return t.includes(`:`)?t.split(`:`).at(-1):t},_Le=(e,t)=>{let n=i8(e);for(let e of t)if(n.startsWith(`${e}=`))return n.slice(e.length+1)},vLe=(e,t)=>{let n=i8(e);for(let e of t)if(e.length===2&&n.startsWith(e)&&n.length>e.length)return n.slice(e.length)},u8=e=>/^[A-Z_]\w*=/i.test(e),d8=e=>{let t=0;for(;t<e.length&&(u8(e[t])||b8.has(i8(e[t])));)t+=1;return t},f8=(e,t)=>{if(Array.isArray(e)){if(!e.every(e=>typeof e==`string`))return;let n=x8(e);return n===void 0?t(e):f8(n,t)}if(typeof e!=`string`)return;let n={};for(let r of S8(e).split(/[\n;|&]/)){let e=v8(r),i=t(e,n);if(i)return i;o8(e,n)}},yLe=e=>{if(e)for(let t of cLe){let n=l8(t.exec(e)?.[1]);if(n)return n}},bLe=e=>{let t=e?.match(sLe);if(t)return{number:Number(t[1]),url:t[0]}},p8=(e,t,n,r)=>{let i=e[t],a=_Le(i,n)??vLe(i,n);return a===void 0?n.includes(i8(i))?{skipNext:!0,value:a8(e[t+1]??``,r)}:{}:{value:a8(a,r)}},m8=(e,t)=>{let n=d8(e);if(!c8(e[n]??``))return;n+=1;let r=t;for(;n<e.length&&e[n].startsWith(`-`);)if(e[n]===`-C`){let t=i8(e[n+1]??``);t&&(r=_8(t,r)),n+=2}else y8.has(e[n])?n+=2:n+=1;let i=i8(e[n]??``);if(i)return{args:e.slice(n+1),baseCwd:r,subcommand:i}},xLe=(e,t)=>{let n=m8(e);if(!n||!r8.has(n.subcommand))return;let r;for(let e=0;e<n.args.length;e+=1){let i=n.args[e];if(rLe.has(i8(i)))return{detached:!0};let a=p8(n.args,e,[...nLe],t);if(a.value){r=l8(a.value);break}if(a.skipNext){e+=1;continue}if(p8(n.args,e,[...iLe]).skipNext){e+=1;continue}if(i===`--`)break;if(!i.startsWith(`-`)){n.subcommand===`switch`&&(r=l8(a8(i,t)));break}}return r?{branch:r}:void 0},SLe=e=>{let t=m8(e);return t&&r8.has(t.subcommand)?!0:void 0},CLe=(e,t)=>{let n=yLe(t);return n&&f8(e,SLe)?{branch:n}:f8(e,xLe)},wLe=(e,t,n)=>{let r=bLe(t);if(!r)return;let i=d8(e);if(!gLe(e[i]??``))return;for(i+=1;i<e.length&&e[i].startsWith(`-`);)oLe.has(i8(e[i]))?i+=2:i+=1;if(i8(e[i]??``)!==`pr`||(i+=1,i8(e[i]??``)!==`create`))return;i+=1;let a,o=!1,s;for(;i<e.length;i+=1){let t=i8(e[i]);if(t===`--draft`){o=!0;continue}let r=p8(e,i,[`-t`,`--title`],n);if(r.value){s=r.value,r.skipNext&&(i+=1);continue}let c=p8(e,i,[`-H`,`--head`],n);if(c.value){a=l8(c.value)??a,c.skipNext&&(i+=1);continue}if(aLe.has(t)){i+=1;continue}}return{branch:a,pullRequest:{...o?{isDraft:!0}:{},number:r.number,state:`OPEN`,title:s||`PR #${r.number}`,url:r.url}}},TLe=(e,t)=>f8(e,(e,n)=>wLe(e,t,n)),ELe=new Set([`--exec`,`--push-option`,`--receive-pack`,`--repo`,`-o`]),DLe=/^\s*(?:\S\s+)?(\[[^\]]*\]|[\da-f]{4,40}\.{2,3}[\da-f]{4,40})\s+(\S+)\s+->\s+(\S+)(?:\s+\(.*\))?\s*$/i,OLe=/^\[(?:new branch|new reference|up to date)\]$/i,kLe=/^\w[\w+.-]*:\/\/|^[^\s/][^\s/@]*@[^\s/]+:/,ALe=e=>kLe.test(e)||e.startsWith(`/`)||e.startsWith(`.`),jLe=e=>{if(!e)return[];let t=[];for(let n of e.split(`
5700`)){let e=DLe.exec(n);if(!e)continue;let[,r,i,a]=e;r.startsWith(`[`)&&!OLe.test(r)||i===`(none)`||i.startsWith(`refs/tags/`)||a.startsWith(`refs/tags/`)||t.push({local:i,remote:a.replace(/^refs\/heads\//,``)})}return t},MLe=(e,t)=>{let n=m8(e);if(!(!n||n.subcommand!==`push`)){for(let e=0;e<n.args.length;e+=1){let r=n.args[e],i=p8(n.args,e,[...ELe],t);if(i.skipNext){e+=1;continue}if(i.value!==void 0||r.startsWith(`-`))continue;let a=a8(r,t);if(a)return ALe(a)?{}:{remote:a}}return{}}},NLe=(e,t,n)=>{let r=f8(e,MLe);if(!r)return;let i=jLe(t),a=n?i.filter(e=>e.local===n||e.local===`HEAD`):i;if(a.length!==1)return;let o=l8(a[0].remote);if(o)return{branch:o,remote:r.remote??`origin`}},PLe=(e,t,n)=>{let r=e?.git?.branch!==n,i={...e?.git,branch:n};return delete i.detached,r&&(delete i.github,delete i.upstream),{...e,git:i,path:t,...e?.repoType?{repoType:e.repoType}:{}}},FLe=(e,t)=>{let n={...e?.git,detached:!0};return delete n.branch,delete n.github,delete n.upstream,{...e,git:n,path:t,...e?.repoType?{repoType:e.repoType}:{}}},ILe=(e,t,n)=>{let r=n.branch??e?.git?.branch,i={...e?.git,...r?{branch:r}:{},github:{pullRequest:n.pullRequest,pullRequestStatus:`ok`}};return delete i.detached,{...e,git:i,path:t,repoType:`github`}},LLe=(e,t,n)=>{let r=e?.git?.upstream?.branch,i={...e?.git,upstream:n};return r&&r!==n.branch&&delete i.github,{...e,git:i,path:t,...e?.repoType?{repoType:e.repoType}:{}}},h8=(e,t,n)=>{let r=!!n.branch&&e?.git?.branch!==n.branch,i={...e?.git,activeWorktree:n.path,...n.branch?{branch:n.branch}:{},isWorktree:!0};return n.branch&&delete i.detached,r&&(delete i.github,delete i.upstream),{...e,git:i,path:t,...e?.repoType?{repoType:e.repoType}:{}}},RLe=(e,t)=>{let n={...e?.git,isWorktree:!1};return delete n.activeWorktree,e?.git?.isWorktree&&(delete n.branch,delete n.github,delete n.upstream),{...e,git:n,path:t,...e?.repoType?{repoType:e.repoType}:{}}},g8=e=>{let t=e.startsWith(`/`),n=[];for(let r of e.split(`/`))r===``||r===`.`||(r===`..`?n.length>0&&n.at(-1)!==`..`?n.pop():t||n.push(`..`):n.push(r));return(t?`/`:``)+n.join(`/`)},_8=(e,t)=>
5700fLe(e)?e.startsWith(`/`)?g8(e):e:t?g8(`${t}/${e}`):e,v8=e=>e.match(/"[^"]*"|'[^']*'|\S+/g)??[],y8=new Set([`-C`,`-c`,`--git-dir`,`--work-tree`,`--namespace`,`--super-prefix`,`--config-env`]),b8=new Set([`sudo`,`env`,`command`,`nice`,`nohup`,`time`]),zLe=/^(?:\/usr\/bin\/env\s+)?(?:\/\S+\/)?(?:bash|sh|zsh)\s+(?:-lc|-c|-l\s+-c)\s+(\S[\s\S]*)$/,BLe=new Set([`bash`,`sh`,`zsh`]),VLe=e=>{let t=e.trim();if(t.length<2)return t;let n=t[0];if(n!==`"`&&n!==`'`||t.at(-1)!==n)return t;let r=t.slice(1,-1);return n===`'`?r.replaceAll(`'\\''`,`'`):r.replaceAll(`\\"`,`"`).replaceAll("\\`","`").replaceAll(`\\$`,`$`).replaceAll(`\\\\`,`\\`)},x8=e=>{let t=+(s8(e[0]??``)===`env`);if(!BLe.has(s8(e[t]??``)??``))return;t+=1,i8(e[t]??``)===`-l`&&(t+=1);let n=i8(e[t]??``);if(!(n!==`-c`&&n!==`-lc`))return e[t+1]},S8=e=>{let t=e;for(let e=0;e<4;e+=1){let e=zLe.exec(t.trim());if(!e)break;let n=VLe(e[1]);if(!n)break;t=n}return t},C8=(e,t,n)=>{let r=0;for(;r<e.length&&(u8(e[r])||b8.has(i8(e[r])));)r+=1;if(!c8(e[r]??``))return;r+=1;let i=t;for(;r<e.length&&e[r].startsWith(`-`);)if(e[r]===`-C`){let t=a8(e[r+1]??``,n);t&&(i=_8(t,i)),r+=2}else y8.has(e[r])?r+=2:r+=1;if(i8(e[r]??``)!==`worktree`||(r+=1,i8(e[r]??``)!==`add`))return;r+=1;let a,o,s;for(;r<e.length;r+=1){let t=e[r];if(tLe.has(t)){a=a8(e[r+1]??``,n)||a,r+=1;continue}if(eLe.has(t)){r+=1;continue}if(/^\d*[<>]/.test(t))break;if(t.startsWith(`-`))continue;let i=a8(t,n);if(i){if(o===void 0){o=i;continue}s=i;break}}if(o!==void 0)return{...a?{branch:a}:{},...s?{ref:s}:{},...hLe(o)?{path:_8(o,i)}:{}}},w8=(e,t)=>{if(Array.isArray(e)){if(!e.every(e=>typeof e==`string`))return;let n=x8(e);return n===void 0?C8(e,t):w8(n,t)}if(typeof e!=`string`)return;let n=S8(e);if(!/\bworktree\s+add\b/.test(n))return;let r={};for(let e of n.split(/[\n;|&]/)){let n=v8(e),i=C8(n,t,r);if(i)return i;o8(n,r)}},HLe=async(e,t,n)=>{let r=l8(e.branch??e.ref);if(!r)return;let i=ur().gatewayDeviceInfo?.deviceId,a=n??i;try{let e=(await Oa.listGitWorktrees({deviceId:a,path:t})).find(e=>e.branch===r);return e?{...e.branch?{branch:e.branch}:{},path:e.path}:void 0}catch{return}},ULe=async(e,t,n)=>{if(e){if(e.path){let t=l8(e.branch);return{...t?{branch:t}:{},path:e.path}}return HLe(e,t,n)}},WLe=async e=>{let{command:t,resultContent:n,topicId:r}=e,i=Q9(),a=vi.getTopicById(r)(i),o=a?.metadata?.workingDirectoryConfig,s=N(o)??a?.metadata?.workingDirectory;if(!s)return;let c=o,l=await ULe(w8(t,s),s,a?.metadata?.boundDeviceId);l&&l.path!==s&&(c=h8(c,s,l));let u=CLe(t,n);u&&(c=`detached`in u?FLe(c,s):PLe(c,s,u.branch));let d=NLe(t,n,c?.git?.branch);d&&(c=LLe(c,s,d));let f=TLe(t,n);if(f&&(c=ILe(c,s,f)),(0,n8.default)(o,c)||await i.updateTopicMetadata(r,{workingDirectoryConfig:c}),u||d){let e=a?.metadata?.boundDeviceId,t=ur().gatewayDeviceInfo?.deviceId,n=t&&e===t?`local`:e;await Zi(ia.gitBranch(n??`local`,s))}},GLe=e=>{if(!e?.includes(dLe))return;let t=lLe.exec(e),n=t?.[1]?.trim();if(!n)return;let r=l8(t?.[2]);return{...r?{branch:r}:{},path:n}},KLe=e=>!!e&&uLe.test(e),qLe=async e=>{let{content:t,topicId:n}=e,r=Q9(),i=vi.getTopicById(n)(r),a=i?.metadata?.workingDirectoryConfig,o=N(a)??i?.metadata?.workingDirectory,s=GLe(t);if(!s||!o||s.path===o)return;let c=h8(a,o,s);(0,n8.default)(a,c)||await r.updateTopicMetadata(n,{workingDirectoryConfig:c})},JLe=async e=>{let{content:t,topicId:n}=e;if(!KLe(t))return;let r=Q9(),i=vi.getTopicById(n)(r),a=i?.metadata?.workingDirectoryConfig,o=N(a)??i?.metadata?.workingDirectory;if(!o)return;let s=a?.git;if(!s?.activeWorktree&&!s?.isWorktree)return;let c=RLe(a,o);(0,n8.default)(a,c)||await r.updateTopicMetadata(n,{workingDirectoryConfig:c})}})),XLe,ZLe,T8,QLe,$Le,eRe,tRe,nRe=e((()=>{Ne(),YLe(),XLe={},ZLe=e=>{if(!e||typeof e!=`object`)return;let t=e.command??e.cmd;if(typeof t==`string`||Array.isArray(t)&&t.every(e=>typeof e==`string`))return t},T8=class extends ye{identifier;shellApiNames;worktreeApiNames;apiEnum=XLe;constructor(e,t,n){super(),this.identifier=e,this.shellApiNames=t,this.worktreeApiNames=n}onAfterCall=async({apiName:e,params:t,result:n,topicId:r})=>{if(!n.success||!r)return;if(e===this.worktreeApiNames?.enter){await qLe({content:n.content,topicId:r});return}if(e===this.worktreeApiNames?.exit){await JLe({content:n.content,topicId:r});return}if(!this.shellApiNames.has(e))return;let i=ZLe(t);i!==void 0&&await WLe({command:i,resultContent:n.content,topicId:r})}},QLe=new T8(`amp`,new Set([`shell_command`])),$Le=new T8(`claude-code`,new Set([`Bash`]),{enter
5700:`EnterWorktree`,exit:`ExitWorktree`}),eRe=new T8(`codex`,new Set([`command_execution`])),tRe=new T8(`opencode`,new Set([`bash`]))})),rRe,iRe=e((()=>{rRe=class{service;constructor(e){this.service=e.service}async activateSkill(e){return this.service.activateSkill?this.service.activateSkill(e):{content:`Skill activation is not available.`,success:!1}}async activateTools(e){let{identifiers:t}=e;if(!t||t.length===0)return{content:`No tool identifiers provided. Please specify which tools to activate.`,success:!1};try{let e=this.service.getActivatedToolIds(),n=[],r=[];for(let i of t)e.includes(i)?r.push(i):n.push(i);let i=await this.service.getToolManifests(n),a=new Set(i.map(e=>e.identifier)),o=n.filter(e=>!a.has(e)),s=[],c=[];if(o.length>0&&this.service.activateSkill)for(let e of o)try{let t=await this.service.activateSkill({name:e});t.success?s.push(t):c.push(e)}catch{c.push(e)}else c.push(...o);let l=i.map(e=>({apiCount:e.apiDescriptions.length,avatar:e.avatar,identifier:e.identifier,name:e.name}));i.length>0&&this.service.markActivated(i.map(e=>e.identifier));let u=[];if(l.length>0){u.push(`Successfully activated tools:`);for(let e of i)if(u.push(`\n## ${e.name} (${e.identifier})`),e.systemRole&&u.push(e.systemRole),e.apiDescriptions.length>0){u.push(`
5701Available APIs:`);for(let t of e.apiDescriptions)u.push(`- **${t.name}**: ${t.description}`)}}if(s.length>0)for(let e of s)u.push(e.content);return r.length>0&&u.push(`\nAlready active: ${r.join(`, `)}`),c.length>0&&u.push(`\nNot found: ${c.join(`, `)}`),{content:u.join(`
5702`),state:{activatedSkills:s.map(e=>e.state),activatedTools:l,alreadyActive:r,notFound:c},success:!0}}catch(e){return{content:`Failed to activate tools: ${e.message}`,success:!1}}}}})),aRe,oRe=e((()=>{Ne(),Cte(),aRe=class extends ye{identifier=Di;apiEnum=wte;runtime;constructor(e){super(),this.runtime=e}activateSkill=async(e,t)=>{try{if(t.signal?.aborted)return{stop:!0,success:!1};let n=await this.runtime.activateSkill(e);return n.success?{content:n.content,state:n.state,success:!0}:{content:n.content,error:{message:n.content,type:`PluginServerError`},success:!1}}catch(e){return{error:{body:e,message:e.message,type:`PluginServerError`},success:!1}}};activateTools=async(e,t)=>{try{if(t.signal?.aborted)return{stop:!0,success:!1};let n=await this.runtime.activateTools(e);return n.success?{content:n.content,state:n.state,success:!0}:{content:n.content,error:{message:n.content,type:`PluginServerError`},success:!1}}catch(e){return{error:{body:e,message:e.message,type:`PluginServerError`},success:!1}}}}})),E8,sRe,D8,cRe,O8,lRe,k8,uRe=e((()=>{Wt(),Mi(),E8=e=>{let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return t===-1?``:e.slice(0,t)},sRe=(e,t)=>{let n=e.includes(`\\`)&&!e.includes(`/`)?`\\`:`/`;return`${e.endsWith(n)?e.slice(0,-n.length):e}${n}${t}`},D8=e=>e.replaceAll(`\\`,`/`).replace(/^(?:\.\/)+/,``).replace(/^\/+/,``),cRe=e=>e.split(`/`).some(e=>e.startsWith(`.`)),O8=(e,t)=>{let n=t.toLowerCase();return e.find(e=>e.name.toLowerCase()===n)},lRe=(e,t)=>`## Skill resources
5703
5704This filesystem skill lives in \`${t}\`. Use \`local-system.globFiles\` with scope="${t}" and pattern="**/*" to discover reference files, then \`readReference\` with skillName="${e}" + the relative path to load any of them.`,k8=class{activatedSkills;builtinSkills;projectSkills;deviceFileAccess;service;constructor(e){this.service=e.service,this.activatedSkills=e.activatedSkills,this.builtinSkills=e.builtinSkills||[],this.projectSkills=e.projectSkills||[],this.deviceFileAccess=e.deviceFileAccess}async execScript(e){let{command:t,description:n}=e,r=e.activatedSkills??this.activatedSkills;if(this.service.execScript)try{let e=await this.service.execScript(t,{activatedSkills:r,description:n});return this.formatCommandOutput(t,e)}catch(e){return{content:`Failed to execute command: ${e.message}`,success:!1}}if(!this.service.runCommand)return{content:`Command execution is not available in this environment.`,success:!1};try{let e=await this.service.runCommand({command:t});return this.formatCommandOutput(t,e)}catch(e){return{content:`Failed to execute command: ${e.message}`,success:!1}}}
5704async runCommand(e){let{command:t}=e;if(!this.service.runCommand)return{content:`Command execution is not available in this environment.`,success:!1};try{let e=await this.service.runCommand({command:t});return this.formatCommandOutput(t,e)}catch(e){return{content:`Failed to execute command: ${e.message}`,success:!1}}}async exportFile(e){let{path:t,filename:n}=e;if(!this.service.exportFile)return{content:`File export is not available in this environment.`,success:!1};try{let e=await this.service.exportFile(t,n);return e.success?{content:`File exported successfully: ${n}\nDownload URL: ${e.url||`N/A`}`,state:{fileId:e.fileId,filename:e.filename,mimeType:e.mimeType,size:e.size,url:e.url},success:!0}:{content:`Failed to export file: ${n}`,success:!1}}catch(e){return{content:`Failed to export file: ${e.message}`,success:!1}}}async readReference(e){let{id:t,path:n}=e;try{let e=O8(this.projectSkills,t);if(e){if(!this.deviceFileAccess)return{content:`Filesystem skill "${t}" cannot be read: no device file access available.`,success:!1};let r=D8(n);if(!r||r.includes(`..`)||cRe(r))return{content:`Invalid path: "${n}" is not a permitted skill resource`,success:!1};let i=E8(e.location);if(!new Set((await this.deviceFileAccess.listFiles(i)).map(e=>D8(e))).has(r))return{content:`Resource not found in filesystem skill "${t}": "${n}"`,success:!1};let a=sRe(i,r);return{content:await this.deviceFileAccess.readFile(a),state:{encoding:`utf8`,fileType:`text/plain`,fullPath:a,path:r},success:!0}}if(n.includes(`..`))return{content:`Invalid path: path traversal is not allowed`,success:!1};let r=await this.service.findByName(t);if(r){let e=await this.service.readResource(r.id,n);return{content:e.content,state:{encoding:e.encoding,fileType:e.fileType,fullPath:e.fullPath,path:e.path,size:e.size},success:!0}}let i=O8(this.builtinSkills,t);if(i?.resources){let e=i.resources[n];return e?.content===void 0?{content:`Resource not found: "${n}" in builtin skill "${t}"`,success:!1}:{content:e.content,state:{encoding:`utf8`,fileType:`text/plain`,path:n,size:e.size},success:!0}}return{content:`Skill not found: "${t}"`,success:!1}}catch(e){return{content:`Failed to read resource: ${e.message}`,success:!1}}}async activateSkill(e){let{name:t}=e,n=O8(this.projectSkills,t);if(n){if(!this.deviceFileAccess)return{content:`Filesystem skill "${t}" cannot be loaded: no device file access available.`,success:!1};try{let e=await this.deviceFileAccess.readFile(n.location),r=E8(n.location);return r&&(e+=`
5705
5706`+lRe(t,r)),{content:e,state:{hasResources:!1,location:n.location,name:t,source:n.source??`project`},success:!0}}catch(e){return{content:`Failed to load filesystem skill "${t}": ${e.message}`,success:!1}}}let r=await this.service.findByName(t);if(r){let e=!!(r.resources&&Object.keys(r.resources).length>0),t=r.content||``;return e&&r.resources&&(t+=`
5707
5708`+Bi(r.name,r.resources)),{content:t,state:{description:r.description||void 0,hasResources:e,id:r.id,name:r.name,source:`user`},success:!0}}let i=O8(this.builtinSkills,t);if(i){let e=i.content,t=!!(i.resources&&Object.keys(i.resources).length>0);t&&i.resources&&(e+=`
5709
5710`+Bi(i.name,i.resources));let n=i.identifier.startsWith(Kt);return{content:e,state:{description:i.description,hasResources:t,identifier:i.identifier,name:i.name,source:n?`agent`:`builtin`,...i.title&&{title:i.title}},success:!0}}let{data:a}
5710=await this.service.findAll(),o=a.map(e=>({description:e.description,name:e.name}));return{content:`Skill not found: "${t}". Available skills: ${JSON.stringify(o)}`,success:!1}}formatCommandOutput(e,t){return{content:Fne({stderr:t.stderr,stdout:t.output,success:t.success,exitCode:t.exitCode,outputFiles:t.outputFiles,shellId:t.shellId}),state:{command:e,...t.executionEnv&&{executionEnv:t.executionEnv},exitCode:t.exitCode,...t.outputFiles&&{outputFiles:t.outputFiles},...t.shellId&&{shellId:t.shellId},success:t.success},success:t.success}}}})),dRe,fRe,pRe,mRe=e((()=>{Fc(),iRe(),oRe(),uRe(),dY(),IY(),f7(),u3(),o3(),dRe=new k8({builtinSkills:uY(Pc),service:{findAll:()=>FY.list(),findById:e=>FY.getById(e),findByName:e=>FY.getByName(e),readResource:(e,t)=>FY.readResource(e,t)}}),fRe=new rRe({service:{activateSkill:e=>dRe.activateSkill(e),getActivatedToolIds:()=>[],getToolManifests:async e=>{let t=u7(),n=new Set(l3.availableToolsForDiscovery(t).map(e=>e.identifier)),r=e.filter(e=>n.has(e)),i=[];for(let e of r){let n=t.builtinTools.find(t=>t.identifier===e);if(n){i.push({apiDescriptions:n.manifest.api.map(e=>({description:e.description,name:e.name})),avatar:n.avatar,identifier:n.identifier,name:n.title??n.identifier,systemRole:n.manifest.systemRole});continue}let r=t.installedPlugins.find(t=>t.identifier===e);if(r?.manifest){i.push({apiDescriptions:(r.manifest.api||[]).map(e=>({description:e.description,name:e.name})),avatar:r.manifest.meta?.avatar,identifier:r.identifier,name:r.manifest.meta?.title??r.identifier,systemRole:r.manifest.systemRole});continue}let a=t.lobehubSkillServers?.find(t=>t.identifier===e&&t.status===zX.CONNECTED);if(a?.tools){i.push({apiDescriptions:a.tools.map(e=>({description:e.description||``,name:e.name})),avatar:a.icon,identifier:a.identifier,name:a.name});continue}}return i},markActivated:()=>{}}}),pRe=new aRe(fRe)})),hRe,A8,gRe,_Re=e((()=>{Ne(),Xee(),mte(),hRe=new Set([mr.createDocument,mr.removeDocument,mr.renameDocument,mr.copyDocument]),A8=class extends ye{identifier=Ree;apiEnum=mr;runtime;constructor(e){super(),this.runtime=e}onAfterCall=async({apiName:e,result:t})=>{!hRe.has(e)||!t.success||await this.runtime.notifyMutated()};listDocuments=async(e,t)=>this.runtime.listDocuments(e,{agentId:t.agentId,currentDocumentId:t.documentId,scope:t.scope,topicId:t.topicId});createDocument=async(e,t)=>this.runtime.createDocument(e,{agentId:t.agentId,currentDocumentId:t.documentId,messageId:t.sourceMessageId??t.messageId,operationId:t.operationId,rootOperationId:t.rootOperationId,scope:t.scope,taskId:t.taskId,threadId:t.threadId,toolCallId:t.toolCallId,toolMessageId:t.toolMessageId,topicId:t.topicId});readDocument=async(e,t)=>this.runtime.readDocument(e,{agentId:t.agentId,currentDocumentId:t.documentId,scope:t.scope});replaceDocumentContent=async(e,t)=>this.runtime.replaceDocumentContent(e,{agentId:t.agentId,currentDocumentId:t.documentId,messageId:t.sourceMessageId??t.messageId,operationId:t.operationId,rootOperationId:t.rootOperationId,scope:t.scope,taskId:t.taskId,threadId:t.threadId,toolCallId:t.toolCallId,toolMessageId:t.toolMessageId,topicId:t.topicId});modifyNodes=async(e,t)=>this.runtime.modifyNodes(e,{agentId:t.agentId,currentDocumentId:t.documentId,messageId:t.sourceMessageId??t.messageId,operationId:t.operationId,rootOperationId:t.rootOperationId,scope:t.scope,taskId:t.taskId,threadId:t.threadId,toolCallId:t.toolCallId,toolMessageId:t.toolMessageId,topicId:t.topicId});removeDocument=async(e,t)=>this.runtime.removeDocument(e,{agentId:t.agentId,currentDocumentId:t.documentId,messageId:t.sourceMessageId??t.messageId,operationId:t.operationId,rootOperationId:t.rootOperationId,scope:t.scope,taskId:t.taskId,threadId:t.threadId,toolCallId:t.toolCallId,toolMessageId:t.toolMessageId,topicId:t.topicId});renameDocument=async(e,t)=>this.runtime.renameDocument(e,{agentId:t.agentId,currentDocumentId:t.documentId,messageId:t.sourceMessageId??t.messageId,operationId:t.operationId,rootOperationId:t.rootOperationId,scope:t.scope,taskId:t.taskId,threadId:t.threadId,toolCallId:t.toolCallId,toolMessageId:t.toolMessageId,topicId:t.topicId});copyDocument=async(e,t)=>this.runtime.copyDocument(e,{agentId:t.agentId,currentDocumentId:t.documentId,messageId:t.sourceMessageId??t.messageId,operationId:t.operationId,rootOperationId:t.rootOperationId,scope:t.scope,taskId:t.taskId,threadId:t.threadId,toolCallId:t.toolCallId,toolMessageId:t.toolMessageId,topicId:t.topicId});updateLoadRule=async(e,t)=>this.runtime.updateLoadRule(e,{agentId:t.agentId,currentDocumentId:t.documentId,scope:t.scope})},gRe=new gr({copyDocument:async({agentId:e})=>void 0,createDocument:async()=>void 0,createTopicDocument:async()=>void 0,listDocuments:async()=>[],listTopicDocuments:async()=>[],modifyNodes:async({agentId:e})=>void 0,readDocument:async({agentId:e})=>void 0,removeDocument:async({agentId:e})=>!1,renameDocument:async({agentId:e})=>void 0,replaceDocumentContent:async({agentId:e})=>void 0,updateLoadRule:async({agentId:e})=>void 0}),new A8(gRe)})),j8,M8,N8,P8=e((()=>{j8=new Map,M8=(e,t)=>{e&&j8.set(e,t)},N8=e=>{if(!e)return;let t=j8.get(e);return t&&j8.delete(e),t}})),vRe,yRe,bRe,xRe,F8,SRe,CRe,wRe=e((()=>
5710{dr(),Xee(),_Re(),Wt(),Za(),Ii(),yne(),B6(),Gr(),Vr(),Wee(),P8(),vRe=()=>typeof window>`u`?void 0:window.location.origin,yRe=(e,t)=>Jee(vRe(),e,t,{workspaceSlug:Qa()}),bRe=async e=>{e&&await z6.refreshConversation(e.topicId,e.threadId).catch(e=>{console.error(`[AgentDocumentsExecutor] refresh document works failed:`,e)})},xRe=async(e,t)=>{let n=await e;return await bRe(t),n},F8=e=>{!e.toolCallId||!e.documentId||M8(e.toolCallId,{action:`register`,document:{agentDocumentId:e.agentDocumentId,agentId:e.agentId,description:e.description,documentId:e.documentId,changeType:e.changeType,toolName:e.toolName},type:`document`})},SRe=new gr({copyDocument:async({agentId:e,id:t,newTitle:n,toolContext:r,trigger:i})=>{let a=await zi.copyDocument({agentId:e,id:t,newTitle:n,toolContext:r,trigger:i});return F8({agentDocumentId:a?.id,agentId:e,description:a?.description,documentId:a?.documentId,changeType:`created`,toolName:`copyDocument`,toolCallId:r?.toolCallId}),a},createDocument:async({agentId:e,content:t,hintIsSkill:n,title:r,toolContext:i,trigger:a})=>{let o=await zi.createDocument({agentId:e,content:t,hintIsSkill:n,title:r,toolContext:i,trigger:a});return F8({agentDocumentId:o?.id,agentId:e,description:o?.description,documentId:o?.documentId,changeType:`created`,toolName:`createDocument`,toolCallId:i?.toolCallId}),o},createTopicDocument:async({agentId:e,content:t,hintIsSkill:n,title:r,toolContext:i,topicId:a,trigger:o})=>{let s=await zi.createForTopic({agentId:e,content:t,hintIsSkill:n,title:r,toolContext:i,topicId:a,trigger:o});return F8({agentDocumentId:s?.id,agentId:e,description:s?.description,documentId:s?.documentId,changeType:`created`,toolName:`createForTopic`,toolCallId:i?.toolCallId}),s},listDocuments:async({agentId:e,parentId:t,sourceType:n})=>(await zi.listDocuments({agentId:e,includeArchivedToolResults:!0,parentId:t,sourceType:n})).map(e=>({documentId:e.documentId,filename:e.filename,id:e.id,title:e.title})),listTopicDocuments:async({agentId:e,parentId:t,sourceType:n,topicId:r})=>(await zi.listDocuments({agentId:e,includeArchivedToolResults:!0,parentId:t,scope:`currentTopic`,sourceType:n,topicId:r})).map(e=>({documentId:e.documentId,filename:e.filename,id:e.id,title:e.title})),modifyNodes:async({agentId:e,id:t,operations:n,toolContext:r,trigger:i})=>{let a=await zi.modifyNodes({agentId:e,id:t,operations:n,toolContext:r,trigger:i});return F8({agentDocumentId:t,agentId:e,description:a?.description,documentId:a?.documentId,changeType:`updated`,toolName:`modifyNodes`,toolCallId:r?.toolCallId}),a},readDocument:({agentId:e,format:t,id:n})=>zi.readDocument({agentId:e,format:t??`xml`,id:n}),removeDocument:async({agentId:e,id:t,toolContext:n,trigger:r})=>(await xRe(zi.removeDocument({agentId:e,id:t,toolContext:n,trigger:r}),n)).deleted,renameDocument:async({agentId:e,id:t,newTitle:n,toolContext:r,trigger:i})=>{let a=await zi.renameDocument({agentId:e,id:t,newTitle:n,toolContext:r,trigger:i});return F8({agentDocumentId:t,agentId:e,description:a?.description,documentId:a?.documentId,changeType:`updated`,toolName:`renameDocument`,toolCallId:r?.toolCallId}),a},replaceDocumentContent:async({agentId:e,content:t,id:n,toolContext:r,trigger:i})=>{let a=await zi.replaceDocumentContent({agentId:e,content:t,id:n,toolContext:r,trigger:i});return F8({agentDocumentId:n,agentId:e,description:a?.description,documentId:a?.documentId,changeType:`updated`,toolName:`replaceDocumentContent`,toolCallId:r?.toolCallId}),a},updateLoadRule:({agentId:e,id:t,rule:n})=>zi.updateLoadRule({agentId:e,id:t,rule:{...n,policyLoadFormat:n.policyLoadFormat,rule:n.rule}})},{getDocumentUrl:({agentId:e,documentId:t})=>yRe(e,t),onDocumentsMutated:async()=>{let e=jr.getState().activeAgentId;e&&await Ni({agentId:e,cause:`agent-document`})}}),CRe=new A8(SRe)})),TRe,ERe=e((()=>{TRe=class{botProvider;service;constructor(e){this.service=e.service,this.botProvider=e.botProvider}async sendMessage(e){try{let t=await this.service.sendMessage(e);return{content:`Message sent to ${e.platform}:${e.channelId} (messageId: ${t.messageId})`,state:t,success:!0}}catch(e){return{content:`sendMessage error: ${e.message}`,success:!1}}}async readMessages(e){try{let t=await this.service.readMessages(e),n=t.messages?.length??0,r=t.messages?.map(e=>`[${e.timestamp}] ${e.author.name}: ${e.content}`).join(`
5711`),i=t.hasMore&&t.nextCursor?`\n\n[More messages available — pass cursor: "${t.nextCursor}" to fetch next page]`:``;return{content:`Fetched ${n} messages from ${e.platform}:${e.channelId}\n\n${r??`(no messages)`}${i}`,state:t,success:!0}}catch(e){return{content:`readMessages error: ${e.message}`,success:!1}}}async editMessage(e){try{let t=await this.service.editMessage(e);return{content:`Message ${e.messageId} edited successfully`,state:t,success:!0}}catch(e){return{content:`editMessage error: ${e.message}`,success:!1}}}async deleteMessage(e){try{let t=await this.service.deleteMessage(e);return{content:`Message ${e.messageId} deleted successfully`,state:t,success:!0}}catch(e){return{content:`deleteMessage error: ${e.message}`,success:!1}}}async searchMessages(e){try{let t=await this.service.searchMessages(e),n=t.totalFound??t.messages?.length??0,r=t.messages?.map(e=>`[${e.timestamp}] ${e.author.name}: ${e.content}`).join(`
5712`);return{content:`Found ${n} messages matching "${e.query}" in ${e.platform}:${e.channelId}\n\n${r??`(no results)`}`,state:t,success:!0}}catch(e){return{content:`searchMessages error: ${e.message}`,success:!1}}}async reactToMessage(e){try{let t=await this.service.reactToMessage(e);return{content:`Reacted with ${e.emoji} to message ${e.messageId}`,state:t,success:!0}}catch(e){return{content:`reactToMessage error: ${e.message}`,success:!1}}}async getReactions(e){try{let t=await this.service.getReactions(e),n=t.reactions?.map(e=>`${e.emoji}: ${e.count}`).join(`, `);return{content:`Reactions on message ${e.messageId}: ${n??`(none)`}`,state:t,success:!0}}catch(e){return{content:`getReactions error: ${e.message}`,success:!1}}}async pinMessage(e){try{let t=await this.service.pinMessage(e);return{content:`Message ${e.messageId} pinned in ${e.platform}:${e.channelId}`,state:t,success:!0}}catch(e){return{content:`pinMessage error: ${e.message}`,success:!1}}}async unpinMessage(e){try{let t=await this.service.unpinMessage(e);return{content:`Message ${e.messageId} unpinned`,state:t,success:!0}}catch(e){return{content:`unpinMessage error: ${e.message}`,success:!1}}}async listPins(e){try{let t=await this.service.listPins(e);return{content:`${t.messages?.length??0} pinned messages in ${e.platform}:${e.channelId}`,state:t,success:!0}}catch(e){return{content:`listPins error: ${e.message}`,success:!1}}}async getChannelInfo(e){try{let t=await this.service.getChannelInfo(e);return{content:`Channel: ${t.name??e.channelId} (type: ${t.type??`unknown`}, members: ${t.memberCount??`N/A`})`,state:t,success:!0}}catch(e){return{content:`getChannelInfo error: ${e.message}`,success:!1}}}async listChannels(e){try{let t=await this.service.listChannels(e),n=t.channels?.length??0,r=t.channels?.map(e=>`#${e.name} (${e.id})`).join(`
5713`);return{content:`${n} channels found on ${e.platform}\n\n${r??`(none)`}`,state:t,success:!0}}catch(e){return{content:`listChannels error: ${e.message}`,success:!1}}}async getMemberInfo(e){try{let t=await this.service.getMemberInfo(e);return{content:`Member: ${t.displayName??t.username??e.memberId} (status: ${t.status??`unknown`})`,state:t,success:!0}}catch(e){return{content:`getMemberInfo error: ${e.message}`,success:!1}}}async createThread(e){try{let t=await this.service.createThread(e);return{content:`Thread "${e.name}" created (threadId: ${t.threadId})`,state:t,success:!0}}catch(e){return{content:`createThread error: ${e.message}`,success:!1}}}async listThreads(e){try{let t=await this.service.listThreads(e),n=t.threads?.length??0,r=t.threads?.map(e=>`${e.name} (${e.id})`).join(`
5714`);return{content:`${n} threads in ${e.platform}:${e.channelId}\n\n${r??`(none)`}`,state:t,success:!0}}catch(e){return{content:`listThreads error: ${e.message}`,success:!1}}}async replyToThread(e){try{let t=await this.service.replyToThread(e);return{content:`Reply sent to thread ${e.threadId} (messageId: ${t.messageId})`,state:t,success:!0}}catch(e){return{content:`replyToThread error: ${e.message}`,success:!1}}}
5714async createPoll(e){try{let t=await this.service.createPoll(e);return{content:`Poll "${e.question}" created in ${e.platform}:${e.channelId} (pollId: ${t.pollId})`,state:t,success:!0}}catch(e){return{content:`createPoll error: ${e.message}`,success:!1}}}async sendDirectMessage(e){if(!this.service.sendDirectMessage)return{content:`sendDirectMessage is not supported on ${e.platform}`,success:!1};try{let t=await this.service.sendDirectMessage(e);return{content:`Direct message sent to user ${e.userId} on ${e.platform} (messageId: ${t.messageId})`,state:t,success:!0}}catch(e){return{content:`sendDirectMessage error: ${e.message}`,success:!1}}}async listPlatforms(e){if(!this.botProvider)return{content:`Bot provider is not available.`,success:!1};try{let e=await this.botProvider.listPlatforms(),t=e.map(e=>{let t=e.credentialFields.filter(e=>e.required).map(e=>e.key).join(`, `);return`- **${e.name}** (${e.id})${t?` — requires: ${t}`:``}`}).join(`
5715`);return{content:`${e.length} supported platform(s):\n${t}`,state:{platforms:e},success:!0}}catch(e){return{content:`listPlatforms error: ${e.message}`,success:!1}}}async listBots(e){if(!this.botProvider)return{content:`Bot provider query is not available in this context.`,success:!1};try{let e=await this.botProvider.listBots(),t=e.map(e=>{let t=[`platform: ${e.platform}`,`botId: ${e.id}`,`enabled: ${e.enabled}`,`status: ${e.runtimeStatus??`unknown`}`];return e.serverId&&t.push(`serverId: ${e.serverId}`),e.userId&&t.push(`userId: ${e.userId}`),`- ${e.platform} (${t.join(`, `)})`}).join(`
5716`);return{content:e.length>0?`${e.length} configured bot(s):\n${t}`:`No bots configured for this agent. Set up a bot integration first.`,state:{bots:e},success:!0}}catch(e){return{content:`listBots error: ${e.message}`,success:!1}}}async getBotDetail(e){if(!this.botProvider)return{content:`Bot provider is not available.`,success:!1};try{let t=await this.botProvider.getBotDetail(e.botId);return t?{content:`Bot ${t.id}:\n- Platform: ${t.platform}\n- App ID: ${t.applicationId}\n- Enabled: ${t.enabled}\n- Status: ${t.runtimeStatus??`unknown`}`,state:t,success:!0}:{content:`Bot not found: ${e.botId}`,success:!1}}catch(e){return{content:`getBotDetail error: ${e.message}`,success:!1}}}async createBot(e){if(!this.botProvider)return{content:`Bot provider is not available.`,success:!1};try{let t=await this.botProvider.createBot(e);return{content:`Created ${t.platform} bot (id: ${t.id})`,state:t,success:!0}}catch(e){return{content:`createBot error: ${e.message}`,success:!1}}}async updateBot(e){if(!this.botProvider)return{content:`Bot provider is not available.`,success:!1};try{return await this.botProvider.updateBot(e.botId,{credentials:e.credentials,settings:e.settings}),{content:`Updated bot ${e.botId}`,state:{success:!0},success:!0}}catch(e){return{content:`updateBot error: ${e.message}`,success:!1}}}async deleteBot(e){if(!this.botProvider)return{content:`Bot provider is not available.`,success:!1};try{return await this.botProvider.deleteBot(e.botId),{content:`Deleted bot ${e.botId}`,state:{success:!0},success:!0}}catch(e){return{content:`deleteBot error: ${e.message}`,success:!1}}}async toggleBot(e){if(!this.botProvider)return{content:`Bot provider is not available.`,success:!1};try{return await this.botProvider.toggleBot(e.botId,e.enabled),{content:`Bot ${e.botId} ${e.enabled?`enabled`:`disabled`}`,state:{enabled:e.enabled,success:!0},success:!0}}catch(e){return{content:`toggleBot error: ${e.message}`,success:!1}}}async connectBot(e){if(!this.botProvider)return{content:`Bot provider is not available.`,success:!1};try{let t=await this.botProvider.connectBot(e.botId);return{content:`Bot connection initiated (status: ${t.status})`,state:t,success:!0}}catch(e){return{content:`connectBot error: ${e.message}`,success:!1}}}async listMessengers(e){if(!this.botProvider?.listMessengers)return{content:`System Bot messenger discovery is not available in this context.`,success:!1};try{let e=await this.botProvider.listMessengers();if(e.length===0)return{content:"No System Bot connections found. Tell the user to connect one via Settings → Messenger; `listMessengerPlatforms` shows what platforms are available.",state:{installations:e},success:!0};let t=e.map(e=>{let t=[`installationId: ${e.id}`,`platform: ${e.platform}`];if(e.tenantName?t.push(`tenant: ${e.tenantName}`):e.tenantId&&t.push(`tenantId: ${e.tenantId}`),e.installedAt){let n=e.installedAt instanceof Date?e.installedAt.toISOString():e.installedAt;t.push(`installedAt: ${n}`)}return`- ${t.join(`, `)}`});return{content:`${e.length} System Bot connection(s):\n${t.join(`
5717`)}`,state:{installations:e},success:!0}}catch(e){return{content:`listMessengers error: ${e.message}`,success:!1}}}
5717async getMessengerDetail(e){if(!this.botProvider?.getMessengerDetail)return{content:`getMessengerDetail is not available.`,success:!1};try{let t=await this.botProvider.getMessengerDetail(e.installationId);if(!t)return{content:`Messenger installation not found: ${e.installationId}`,success:!1};let n=[`installationId: ${t.id}`,`platform: ${t.platform}`,`tenantId: ${t.tenantId||`(global)`}`];if(t.tenantName&&n.push(`tenant: ${t.tenantName}`),t.applicationId&&n.push(`applicationId: ${t.applicationId}`),t.scope&&n.push(`scope: ${t.scope}`),t.installedAt){let e=t.installedAt instanceof Date?t.installedAt.toISOString():t.installedAt;n.push(`installedAt: ${e}`)}return n.push(`revoked: ${t.revokedAt?`yes`:`no`}`),{content:n.join(`
5718`),state:t,success:!0}}catch(e){return{content:`getMessengerDetail error: ${e.message}`,success:!1}}}async uninstallMessenger(e){if(!this.botProvider?.uninstallMessenger)return{content:`uninstallMessenger is not available.`,success:!1};try{return await this.botProvider.uninstallMessenger(e.installationId),{content:`System Bot connection ${e.installationId} disconnected.`,state:{success:!0},success:!0}}catch(e){return{content:`uninstallMessenger error: ${e.message}`,success:!1}}}async listMessengerPlatforms(e){if(!this.botProvider?.listMessengerPlatforms)return{content:`listMessengerPlatforms is not available.`,success:!1};try{let e=await this.botProvider.listMessengerPlatforms();if(e.length===0)return{content:`No System Bot platforms are configured on this deployment. Ask the operator to enable at least one platform under Messenger configuration.`,state:{platforms:e},success:!0};let t=e.map(e=>{let t=[e.id];
5718return e.name&&e.name!==e.id&&t.push(`(${e.name})`),e.appId&&t.push(`appId: ${e.appId}`),e.botUsername&&t.push(`botUsername: ${e.botUsername}`),`- ${t.join(` `)}`});return{content:`${e.length} platform(s) available for System Bot install:\n${t.join(`
5719`)}\n\nInstalls are initiated via Settings → Messenger (OAuth requires a browser).`,state:{platforms:e},success:!0}}catch(e){return{content:`listMessengerPlatforms error: ${e.message}`,success:!1}}}async listMessengerLinks(e){if(!this.botProvider?.listMessengerLinks)return{content:`listMessengerLinks is not available.`,success:!1};try{let e=await this.botProvider.listMessengerLinks();if(e.length===0)return{content:`No System Bot account links. The user has not completed verify-im on any platform yet.`,state:{links:e},success:!0};let t=e.map(e=>{let t=[`platform: ${e.platform}`];return e.tenantId&&t.push(`tenantId: ${e.tenantId}`),t.push(`activeAgentId: ${e.activeAgentId??`(none)`}`),e.platformUsername&&t.push(`platformUser: ${e.platformUsername}`),`- ${t.join(`, `)}`});return{content:`${e.length} System Bot link(s):\n${t.join(`
5720`)}`,state:{links:e},success:!0}}catch(e){return{content:`listMessengerLinks error: ${e.message}`,success:!1}}}async setMessengerActiveAgent(e){if(!this.botProvider?.setMessengerActiveAgent)return{content:`setMessengerActiveAgent is not available.`,success:!1};try{await this.botProvider.setMessengerActiveAgent(e);let t=e.agentId===null?`cleared`:`set to agent ${e.agentId}`,n=e.tenantId?` (tenant ${e.tenantId})`:``;return{content:`Active agent for ${e.platform}${n} ${t}.`,state:{success:!0},success:!0}}catch(e){return{content:`setMessengerActiveAgent error: ${e.message}`,success:!1}}}async unlinkMessenger(e){if(!this.botProvider?.unlinkMessenger)return{content:`unlinkMessenger is not available.`,success:!1};try{await this.botProvider.unlinkMessenger(e);let t=e.tenantId?` (tenant ${e.tenantId})`:``;return{content:`Unlinked your account from ${e.platform}${t}. The workspace install is unaffected.`,state:{success:!0},success:!0}}catch(e){return{content:`unlinkMessenger error: ${e.message}`,success:!1}}}}})),DRe,ORe=e((()=>{Ne(),fq(),DRe=class extends ye{identifier=uq;apiEnum=dq;runtime;constructor(e){super(),this.runtime=e}sendMessage=async(e,t)=>this.runtime.sendMessage(e);readMessages=async(e,t)=>this.runtime.readMessages(e);editMessage=async(e,t)=>this.runtime.editMessage(e);deleteMessage=async(e,t)=>this.runtime.deleteMessage(e);searchMessages=async(e,t)=>this.runtime.searchMessages(e);reactToMessage=async(e,t)=>this.runtime.reactToMessage(e);getReactions=async(e,t)=>this.runtime.getReactions(e);pinMessage=async(e,t)=>this.runtime.pinMessage(e);unpinMessage=async(e,t)=>this.runtime.unpinMessage(e);listPins=async(e,t)=>this.runtime.listPins(e);getChannelInfo=async(e,t)=>this.runtime.getChannelInfo(e);listChannels=async(e,t)=>this.runtime.listChannels(e);getMemberInfo=async(e,t)=>this.runtime.getMemberInfo(e);createThread=async(e,t)=>this.runtime.createThread(e);listThreads=async(e,t)=>this.runtime.listThreads(e);replyToThread=async(e,t)=>this.runtime.replyToThread(e);createPoll=async(e,t)=>this.runtime.createPoll(e);sendDirectMessage=async(e,t)=>this.runtime.sendDirectMessage(e);listPlatforms=async(e,t)=>this.runtime.listPlatforms(e);listBots=async(e,t)=>this.runtime.listBots(e);getBotDetail=async(e,t)=>this.runtime.getBotDetail(e);createBot=async(e,t)=>this.runtime.createBot(e);updateBot=async(e,t)=>this.runtime.updateBot(e);deleteBot=async(e,t)=>this.runtime.deleteBot(e);toggleBot=async(e,t)=>this.runtime.toggleBot(e);connectBot=async(e,t)=>this.runtime.connectBot(e);listMessengers=async(e,t)=>this.runtime.listMessengers(e);getMessengerDetail=async(e,t)=>this.runtime.getMessengerDetail(e);uninstallMessenger=async(e,t)=>this.runtime.uninstallMessenger(e);listMessengerPlatforms=async(e,t)=>this.runtime.listMessengerPlatforms(e);listMessengerLinks=async(e,t)=>this.runtime.listMessengerLinks(e);setMessengerActiveAgent=async(e,t)=>this.runtime.setMessengerActiveAgent(e);unlinkMessenger=async(e,t)=>this.runtime.unlinkMessenger(e)}})),kRe,ARe,I8,jRe,MRe=e((()=>{pa(),kRe={listPlatforms:async()=>(await q.agentBotProvider.listPlatforms.query()).map(e=>({credentialFields:((e.schema??[]).find(e=>e.key===`credentials`&&e.properties)?.properties??[]).map(e=>({key:e.key,label:e.label??e.key,required:!!e.required,type:e.type??`str
5720ing`})),id:e.id,name:e.name})),listBots:async()=>(await q.agentBotProvider.list.query()).map(e=>({applicationId:e.applicationId,enabled:e.enabled,id:e.id,platform:e.platform,runtimeStatus:e.runtimeStatus,serverId:e.settings?.serverId,userId:e.settings?.userId})),getBotDetail:async e=>{let t=(await q.agentBotProvider.list.query()).find(t=>t.id===e);return t?{applicationId:t.applicationId,enabled:t.enabled,id:t.id,platform:t.platform,runtimeStatus:t.runtimeStatus,settings:t.settings??void 0}:null},createBot:async e=>({id:(await q.agentBotProvider.create.mutate({agentId:e.agentId,applicationId:e.applicationId,credentials:e.credentials,platform:e.platform,settings:e.settings})).id,platform:e.platform}),updateBot:async(e,t)=>{await q.agentBotProvider.update.mutate({id:e,credentials:t.credentials,settings:t.settings})},deleteBot:async e=>{await q.agentBotProvider.delete.mutate({id:e})},toggleBot:async(e,t)=>{await q.agentBotProvider.update.mutate({id:e,enabled:t})},connectBot:async e=>{let t=(await q.agentBotProvider.list.query()).find(t=>t.id===e);if(!t)throw Error(`Bot not found: ${e}`);return q.agentBotProvider.connectBot.mutate({applicationId:t.applicationId,platform:t.platform})},listMessengers:async()=>(await q.messenger.listMyInstallations.query()).map(e=>({applicationId:e.applicationId,enterpriseId:e.enterpriseId??null,id:e.id,installedAt:e.installedAt instanceof Date?e.installedAt.toISOString():String(e.installedAt),isEnterpriseInstall:e.isEnterpriseInstall===!0,platform:e.platform,scope:e.scope??``,tenantId:e.tenantId,tenantName:e.tenantName??``})),getMessengerDetail:async e=>{let t=(await q.messenger.listMyInstallations.query()).find(t=>t.id===e);return t?{applicationId:t.applicationId,enterpriseId:t.enterpriseId??null,id:t.id,installedAt:t.installedAt instanceof Date?t.installedAt.toISOString():String(t.installedAt),isEnterpriseInstall:t.isEnterpriseInstall===!0,platform:t.platform,revokedAt:null,scope:t.scope??``,tenantId:t.tenantId,tenantName:t.tenantName??``}:null},uninstallMessenger:async e=>{await q.messenger.uninstallInstallation.mutate({installationId:e})},listMessengerPlatforms:async()=>(await q.messenger.availablePlatforms.query()).map(e=>({appId:e.appId,botUsername:e.botUsername,id:e.id,name:e.name})),listMessengerLinks:async()=>(await q.messenger.listMyLinks.query()).map(e=>({activeAgentId:e.activeAgentId??null,createdAt:e.createdAt instanceof Date?e.createdAt.toISOString():String(e.createdAt),platform:e.platform,platformUserId:e.platformUserId,platformUsername:e.platformUsername??void 0,tenantId:e.tenantId||void 0})),setMessengerActiveAgent:async e=>{await q.messenger.setActiveAgent.mutate({agentId:e.agentId,platform:e.platform,tenantId:e.tenantId})},unlinkMessenger:async e=>{await q.messenger.unlink.mutate({platform:e.platform,tenantId:e.tenantId})}},ARe=async e=>{if(e.botId)return e.botId;if(!e.platform)throw Error(`botId or platform is required`);let t=(await q.agentBotProvider.list.query()).find(t=>t.platform===e.platform&&t.enabled);if(!t)throw Error(`No enabled bot found for platform "${e.platform}". Configure one first.`);return t.id},I8=async e=>{let t=await ARe(e),{botId:n,platform:r,...i}=e??{};return{...i,botId:t}},jRe={sendMessage:async e=>q.botMessage.sendMessage.mutate(await I8(e)),sendDirectMessage:async e=>q.botMessage.sendDirectMessage.mutate(await I8(e)),readMessages:async e=>q.botMessage.readMessages.query(await I8(e)),editMessage:async e=>q.botMessage.editMessage.mutate(await I8(e)),deleteMessage:async e=>q.botMessage.deleteMessage.mutate(await I8(e)),searchMessages:async e=>q.botMessage.searchMessages.query(await I8(e)),reactToMessage:async e=>q.botMessage.reactToMessage.mutate(await I8(e)),getReactions:async e=>q.botMessage.getReactions.query(await I8(e)),pinMessage:async e=>q.botMessage.pinMessage.mutate(await I8(e)),unpinMessage:async e=>q.botMessage.unpinMessage.mutate(await I8(e)),listPins:async e=>q.botMessage.listPins.query(await I8(e)),getChannelInfo:async e=>q.botMessage.getChannelInfo.query(await I8(e)),listChannels:async e=>q.botMessage.listChannels.query(await I8(e)),getMemberInfo:async e=>q.botMessage.getMemberInfo.query(await I8(e)),createThread:async e=>q.botMessage.createThread.mutate(await I8(e)),listThreads:async e=>q.botMessage.listThreads.query(await I8(e)),replyToThread:async e=>q.botMessage.replyToThread.mutate(await I8(e)),createPoll:async e=>q.botMessage.createPoll.mutate(await I8(e))}})),NRe,PRe,FRe=e((()=>{ERe(),ORe(),MRe(),NRe=new TRe({botProvider:kRe,service:jRe}),PRe=new DRe(NRe)})),L8,R8,IRe=e((()=>{L8=`lobe-notebook`,R8={createDocument:`createDocument`,deleteDocument:`deleteDocument`,getDocument:`getDocument`,updateDocument:`updateDocument`}})),LRe,RRe=e((()=>{Ne(),IRe(),LRe=class extends ye{identifier=L8;apiEnum=R8;notebookService;constructor(e){super(),this.notebookService=e}createDocument=async(e,t)=>{try{if(t.signal?.aborted)return{stop:!0,success:!1};if(!t.topicId)return{content:`Cannot create document: no topic selected`,success:!1};let n=await this.notebookService.createDocument({content:e.content,description:e.description,title:e.title,topicId:t.topicId,type:e.type});return{content:`📝 Document "${n.title}" created successfully`,state:{document:n},success:!0}}catch(e){return{error:{body:e,message:e.message,type:`PluginServerError`},success:!1}}};updateDocument=async(e,t)=>{try{return t.signal?.aborted?{stop:!0,success:!1}:{content:`✏️ Document updated successfully`,state:{document:await this.notebookService.updateDocument(e)},success:!0}}catch(e){return{error:{body:e,message:e.message,type:`PluginServerError`},success:!1}}};getDocument=async(e,t)=>{try{if(t.signal?.aborted)return{stop:!0,success:!1};let n=await this.notebookService.getDocument(e.id);return n?{content:n.content||``,state:{document:n},success:!0}:{content:`Document not found: ${e.id}`,success:!1}}catch(e){return{error:{body:e,message:e.message,type:`PluginServerError`},success:!1}}};deleteDocument=async(e,t)=>{try{return t.signal?.aborted?{stop:!0,success:!1}:(await this.notebookService.deleteDocument(e.id),{content:`🗑️ Document deleted successfully`,success:!0})}catch(e){return{error:{body:e,message:e.message,type:`PluginServerError`},success:!1}}}}})),zRe,BRe=e((()=>{RRe(),d6(),zRe=new LRe(u6)})),VRe,z8,HRe,B8,V8,H8,URe,WRe,GRe=e((()=>
5720{Ne(),VRe=t(F()),Sq(),Pe(),z8=(0,VRe.default)(`lobe-page-agent:executor`),HRe={editTitle:`editTitle`,getPageContent:`getPageContent`,initPage:`initPage`,modifyNodes:`modifyNodes`,replaceText:`replaceText`},B8=e=>e instanceof Error?{message:e.message,name:e.name,stack:e.stack}:{message:String(e)},V8=e=>e.getDebugSnapshot?.(),H8=`Page editor is not currently mounted. This topic was started in the page editor, but the editor is not active in the current view. Do not retry initPage / editTitle / modifyNodes / replaceText / getPageContent here — they require a mounted editor. To read or modify the topic document, use lobe-agent-documents (readDocument / replaceDocumentContent / modifyNodes).`,URe=(e,t)=>({content:H8,error:{body:{apiName:t,code:`PAGE_EDITOR_NOT_MOUNTED`,kind:`replan`,runtime:V8(e)},message:H8,type:`PageEditorNotMounted`},success:!1}),WRe=class extends ye{identifier=bq;apiEnum=HRe;runtime;constructor(e){super(),this.runtime=e;let t=this.invoke;this.invoke=async(e,n,r)=>this.hasApi(e)&&!this.runtime.isReady()?(console.warn(`[PageAgentToolCall] blocked: editor not mounted`,{apiName:e,runtime:V8(this.runtime)}),URe(this.runtime,e)):t(e,n,r)}onAfterCall=async({result:e})=>{if(!e.success)return;let t=e.state;if(!t||typeof t!=`object`)return;let n=typeof t.documentId==`string`?t.documentId:void 0;if(!n)return;let r=typeof t.documentContent==`string`?t.documentContent:void 0,i=typeof t.documentTitle==`string`?t.documentTitle:void 0,a=t.documentEditorData&&typeof t.documentEditorData==`object`?t.documentEditorData:void 0;if(typeof r==`string`||typeof i==`string`||a){this.runtime.isReady()&&this.runtime.getCurrentDocId()===n&&this.runtime.applyServerSnapshot({content:r,editorData:a,title:i});try{let{getDocumentStoreState:e}=await Ge(async()=>{let{getDocumentStoreState:e}=await import(`./document-Cvvy0X4f.js`).then(e=>(e.n(),e.t));return{getDocumentStoreState:e}},__vite__mapDeps([36,1,37,9,3,11,12,13,14,38,39,40,23,41,42,43,18,44,10,15,16,17,7,19,20,21,22,5,2,24,25,26,27,28,45,46,47,30,33,34,48,49,6,50,51,52,53,29,54,55,56,57,58,59,60,61,62,63,64,65,66]));e().applyServerSnapshot(n,{content:r,editorData:a,title:i})}catch(e){z8(`[PageAgentExecutor] applyServerSnapshot store sync failed`,e)}}};initPage=async e=>{z8(`[PageAgentToolCall] initPage:start`,{markdownLength:e.markdown.length,runtime:V8(this.runtime)});try{let t=await this.runtime.initPage(e),n=t.extractedTitle?`Document initialized with ${t.nodeCount} nodes. Title "${t.extractedTitle}" extracted and set.`:`Document initialized with ${t.nodeCount} nodes.`,r={nodeCount:t.nodeCount,rootId:`root`};return z8(`[PageAgentToolCall] initPage:success`,{nodeCount:t.nodeCount,runtime:V8(this.runtime),titleExtracted:!!t.extractedTitle}),{content:n,state:r,success:!0}}catch(e){let t=e;return console.error(`[PageAgentToolCall] initPage:error`,{error:B8(e),runtime:V8(this.runtime)}),{error:{body:e,message:t.message,type:`PluginServerError`},success:!1}}};editTitle=async e=>{z8(`[PageAgentToolCall] editTitle:start`,{runtime:V8(this.runtime),titleLength:e.title.length});try{let t=await this.runtime.editTitle(e),n=`Title changed from "${t.previousTitle}" to "${t.newTitle}".`,r={newTitle:t.newTitle,previousTitle:t.previousTitle};return z8(`[PageAgentToolCall] editTitle:success`,{runtime:V8(this.runtime),titleLength:e.title.length}),{content:n,state:r,success:!0}}catch(e){let t=e;return console.error(`[PageAgentToolCall] editTitle:error`,{error:B8(e),runtime:V8(this.runtime)}),{error:{body:e,message:t.message,type:`PluginServerError`},success:!1}}};getPageContent=async e=>{z8(`[PageAgentToolCall] getPageContent:start`,{format:e.format,runtime:V8(this.runtime)});try{let t=await this.runtime.getPageContent(e),n={documentId:t.documentId,markdown:t.markdown,metadata:{fileType:`document`,title:t.title,totalCharCount:t.charCount,totalLineCount:t.lineCount},xml:t.xml},r=t.markdown||t.xml||``;return z8(`[PageAgentToolCall] getPageContent:success`,{format:e.format,markdownLength:t.markdown?.length,runtime:V8(this.runtime),xmlLength:t.xml?.length}),{content:r,state:n,success:!0}}catch(e){let t=e;return console.error(`[PageAgentToolCall] getPageContent:error`,{error:B8(e),runtime:V8(this.runtime)}),{error:{body:e,message:t.message,type:`PluginServerError`},success:!1}}};modifyNodes=async e=>{let t=Array.isArray(e.operations)?e.operations:e.operations?[e.operations]:[];z8(`[PageAgentToolCall] modifyNodes:start`,{operationActions:t.map(e=>e.action),operationCount:t.length,runtime:V8(this.runtime)});try{let t=await this.runtime.modifyNodes(e),n=e.operations.reduce((e,t)=>
5720(e[t.action]=(e[t.action]||0)+1,e),{}),r=`Successfully executed ${Object.entries(n).map(([e,t])=>`${t} ${e}${t>1?`s`:``}`).join(`, `)} (${t.successCount}/${t.totalCount} operations succeeded).`,i={results:t.results,successCount:t.successCount,totalCount:t.totalCount};return z8(`[PageAgentToolCall] modifyNodes:success`,{runtime:V8(this.runtime),successCount:t.successCount,totalCount:t.totalCount}),{content:r,state:i,success:t.successCount>0}}catch(e){let t=e;return console.error(`[PageAgentToolCall] modifyNodes:error`,{error:B8(e),runtime:V8(this.runtime)}),{error:{body:e,message:t.message,type:`PluginServerError`},success:!1}}};replaceText=async e=>{z8(`[PageAgentToolCall] replaceText:start`,{newTextLength:e.newText.length,nodeCount:e.nodeIds?.length,runtime:V8(this.runtime),searchTextLength:e.searchText.length});try{let t=await this.runtime.replaceText(e),n=e.nodeIds?`within ${e.nodeIds.length} specified node(s)`:`across the document`,r=t.replacementCount>0?`Successfully replaced ${t.replacementCount} occurrence(s) of "${e.searchText}" with "${e.newText}" ${n}. Modified ${t.modifiedNodeIds.length} node(s).`:`No occurrences of "${e.searchText}" found ${n}.`,i={modifiedNodeIds:t.modifiedNodeIds,replacementCount:t.replacementCount};return z8(`[PageAgentToolCall] replaceText:success`,{modifiedNodeCount:t.modifiedNodeIds.length,replacementCount:t.replacementCount,runtime:V8(this.runtime)}),{content:r,state:i,success:!0}}catch(e){let t=e;return console.error(`[PageAgentToolCall] replaceText:error`,{error:B8(e),runtime:V8(this.runtime)}),{error:{body:e,message:t.message,type:`PluginServerError`},success:!1}}}}})),KRe,qRe=e((()=>{Wt(),hn(),tee(),KRe=({token:e})=>pn`
5721  .${e.prefixCls}-popover {
5722    z-index: 1100;
5723  }
5724
5725  .${e.prefixCls}-menu-item-selected {
5726    .${e.prefixCls}-menu-title-content {
5727      color: ${e.colorText};
5728    }
5729  }
5730
5731  .${e.prefixCls}-modal-mask, .${e.prefixCls}-drawer-mask {
5732    background: ${An(e.colorBgLayout,.5)} !important;
5733    backdrop-filter: blur(2px);
5734  }
5735
5736  ${!1}
5737`})),JRe,YRe=e((()=>{Pn(),hn(),JRe=({token:e})=>pn`
5738  html,
5739  body,
5740  #__next {
5741    position: relative;
5742
5743    overscroll-behavior: none;
5744
5745    height: 100%;
5746    min-height: 100dvh;
5747    max-height: 100dvh;
5748
5749    @media (device-width >= 576px) {
5750      overflow: hidden;
5751    }
5752  }
5753
5754  body {
5755    /* Increase compositing layer, force hardware acceleration, otherwise render black edges will appear */
5756    will-change: opacity;
5757    transform: translateZ(0);
5758  }
5759
5760  * {
5761    scrollbar-color: ${e.colorFill} transparent;
5762    scrollbar-width: thin;
5763
5764    ::-webkit-scrollbar {
5765      width: 0.75em;
5766      height: 0.75em;
5767    }
5768
5769    ::-webkit-scrollbar-thumb {
5770      border-radius: 10px;
5771    }
5772
5773    :hover::-webkit-scrollbar-thumb {
5774      border: 3px solid transparent;
5775      background-color: ${e.colorText};
5776      background-clip: content-box;
5777    }
5778
5779    ::-webkit-scrollbar-track {
5780      background-color: transparent;
5781    }
5782  }
5783
5784  html.desktop[data-theme='dark'] body {
5785    background-color: color-mix(in srgb, ${e.colorBgLayout} 50%, transparent);
5786  }
5787
5788  html.desktop[data-theme='light'] body {
5789    background-color: color-mix(in srgb, ${e.colorBgLayout} 70%, transparent);
5790  }
5791
5792  button {
5793    -webkit-app-region: no-drag;
5794  }
5795
5796  .${gn.ContextTrigger}[data-popup-open]:not([data-no-highlight]),
5797  .${gn.DropdownMenuTrigger}[data-popup-open]:not([data-no-highlight]) {
5798    background: ${e.colorFillTertiary};
5799  }
5800  .accordion-action:has(
5801  .${gn.DropdownMenuTrigger}[data-popup-open]:not([data-no-highlight])
5802  ) {
5803    opacity: 1;
5804  }
5805`})),XRe,ZRe,QRe,U8,$Re=e((()=>{hn(),XRe=pn`
5806  &::after {
5807    content: '\\2026'; /* ascii code for the ellipsis character */
5808
5809    overflow: hidden;
5810    display: inline-block;
5811
5812    width: 0;
5813
5814    vertical-align: bottom;
5815
5816    animation: ellipsis steps(4, end) 900ms infinite;
5817  }
5818
5819  @keyframes ellipsis {
5820    to {
5821      width: 1.25em;
5822    }
5823  }
5824
5825  @keyframes ellipsis {
5826    to {
5827      width: 1.25em;
5828    }
5829  }
5830`,ZRe=un`
5831  0% {
5832    background-position: 100%;
5833  }
5834
5835  100% {
5836    background-position: -100%;
5837  }
5838`,QRe=bn(({css:e,cssVar:t})=>({elapsedTime:e`
5839    color: ${t.colorTextTertiary};
5840  `})),U8=bn(({css:e,cssVar:t})=>({errorText:e`
5841    color: ${t.colorError};
5842  `,shinyText:e`
5843    color: color-mix(in srgb, ${t.colorText} 45%, transparent);
5844
5845    background: linear-gradient(
5846      120deg,
5847      color-mix(in srgb, ${t.colorTextBase} 0%, transparent) 40%,
5848      ${t.colorTextSecondary} 50%,
5849      color-mix(in srgb, ${t.colorTextBase} 0%, transparent) 60%
5850    );
5851    background-clip: text;
5852    background-size: 200% 100%;
5853
5854    animation: ${ZRe} 1.5s linear infinite;
5855
5856    @media (prefers-reduced-motion: reduce) {
5857      animation: none;
5858    }
5859  `}))})),W8,G8,K8,q8,eze=e((()=>{hn(),W8=e=>W(pn`
5860    overflow: hidden;
5861    display: -webkit-box;
5862    -webkit-box-orient: vertical;
5863    -webkit-line-clamp: ${e};
5864
5865    text-overflow: ellipsis;
5866  `),G8=W8(1),K8=bn(({css:e,cssVar:t})=>({root:e`
5867    overflow: hidden;
5868    display: flex;
5869    align-items: center;
5870
5871    min-width: 0;
5872
5873    color: ${t.colorTextSecondary};
5874    text-overflow: ellipsis;
5875    white-space: nowrap;
5876  `})),q8=bn(({css:e,cssVar:t})=>{let n=n=>e`
5877    overflow: hidden;
5878
5879    min-width: 0;
5880    margin-inline-start: 4px;
5881    padding-block-end: 1px;
5882
5883    color: ${t.colorText};
5884    text-overflow: ellipsis;
5885
5886    background: linear-gradient(to top, ${n} 40%, transparent 40%);
5887  `;return{gold:n(t.gold4),info:n(t.colorInfoBg),primary:n(t.colorPrimaryBgHover),warning:n(t.colorWarningBg)}})})),J8,tze,Y8=e((()=>{hn(),qRe(),YRe(),$Re(),eze(),J8=`ant`,tze=dn(({theme:e})=>[JRe({prefixCls:J8,token:e}),KRe({prefixCls:J8,token:e})])})),nze,X8,Z8,rze=e((()=>{hn(),nze=t(qt()),a(),Y8(),X8=t(xt()),Z8=(0,nze.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n})=>{let{t:r}=c(`plugin`),i=e?.title||t?.title;return(0,X8.jsx)(`div`,{className:W(K8.root,n&&U8.shinyText),children:i?(0,X8.jsx)(u,{components:{title:(0,X8.jsx)(`span`,{className:q8.gold})},i18nKey:`builtins.lobe-page-agent.apiName.editTitle.result`,ns:`plugin`,values:{title:i}}):(0,X8.jsx)(`span`,{children:r(`builtins.lobe-page-agent.apiName.editTitle`)})})}),Z8.displayName=`EditTitleInspector`})),ize,Q8,aze,$8,oze=e((()=>{hn(),ize=t(qt()),a(),Y8(),Q8=t(xt()),aze=bn(({css:e,cssVar:t})=>({done:e`
5888    color: ${t.colorTextDescription};
5889  `})),$8=(0,ize.memo)(({isArgumentsStreaming:e})=>{let{t}=c(`plugin`);return(0,Q8.jsx)(`div`,{className:W(G8,e?U8.shinyText:aze.done),children:(0,Q8.jsx)(`span`,{children:t(`builtins.lobe-page-agent.apiName.getPageContent`)})})}),$8.displayName=`GetPageContentInspector`})),e5,t5,sze=e((()=>{e5=t(qt()),t5=(0,e5.memo)(({value:e,duration:t=500,formatter:n})=>{let[r,i]=(0,e5.useState)(e),a=(0,e5.useRef)(void 0),o=(0,e5.useRef)(void 0),s=(0,e5.useRef)(e);return(0,e5.useEffect)(()=>{let n=s.current,r=e-n;if(r===0)return;let c=l=>{o.current||=l;let u=l-o.current,d=Math.min(u/t,1);i(n+r*(1-(1-d)**3)),d<1?a.current=requestAnimationFrame(c):(s.current=e,o.current=void 0)};return a.current=requestAnimationFrame(c),()=>{a.current&&cancelAnimationFrame(a.current)}}
5889,[e,t]),n?n(r):Math.round(r).toLocaleString()}),t5.displayName=`AnimatedNumber`})),cze,n5,lze,r5,uze=e((()=>{Pn(),hn(),Zn(),cze=t(qt()),a(),Y8(),sze(),n5=t(xt()),lze=bn(({css:e,cssVar:t})=>({title:e`
5890    margin-inline-end: 8px;
5891    color: ${t.colorText};
5892  `})),r5=(0,cze.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n,pluginState:r})=>{let{t:i}=c(`plugin`),a=e?.markdown||t?.markdown||``,o=a?a.split(`
5893`).length:0,s=a.length,l=r?.nodeCount||o;return n?l>0||s>0?(0,n5.jsxs)(`div`,{className:G8,children:[(0,n5.jsx)(`span`,{className:U8.shinyText,children:i(`builtins.lobe-page-agent.apiName.initPage.creating`)}),l>0&&(0,n5.jsxs)(mn,{code:!0,as:`span`,color:U.colorSuccess,fontSize:12,children:[` `,(0,n5.jsx)(vn,{icon:Gn,size:12}),(0,n5.jsx)(t5,{value:l}),i(`builtins.lobe-page-agent.apiName.initPage.lines`)]}),s>0&&(0,n5.jsxs)(mn,{code:!0,as:`span`,color:U.colorTextDescription,fontSize:12,children:[` `,(0,n5.jsx)(t5,{value:s}),i(`builtins.lobe-page-agent.apiName.initPage.chars`)]})]}):(0,n5.jsx)(`div`,{className:W(G8,U8.shinyText),children:(0,n5.jsx)(`span`,{children:i(`builtins.lobe-page-agent.apiName.initPage`)})}):(0,n5.jsxs)(`div`,{className:G8,children:[(0,n5.jsx)(`span`,{className:lze.title,children:i(`builtins.lobe-page-agent.apiName.initPage.result`)}),l>0&&(0,n5.jsxs)(mn,{code:!0,as:`span`,color:U.colorSuccess,fontSize:12,children:[(0,n5.jsx)(vn,{icon:Gn,size:12}),(0,n5.jsx)(t5,{value:l}),i(`builtins.lobe-page-agent.apiName.initPage.lines`)]}),s>0&&(0,n5.jsxs)(mn,{code:!0,as:`span`,color:U.colorTextDescription,fontSize:12,children:[` `,(0,n5.jsx)(t5,{value:s}),i(`builtins.lobe-page-agent.apiName.initPage.chars`)]})]})}),r5.displayName=`InitPageInspector`})),i5,a5,o5,s5,dze=e((()=>{Pn(),hn(),Zn(),i5=t(qt()),a(),Y8(),a5=t(xt()),o5=bn(({css:e,cssVar:t})=>({separator:e`
5894    margin-inline: 2px;
5895    color: ${t.colorTextQuaternary};
5896  `,title:e`
5897    margin-inline-end: 8px;
5898    color: ${t.colorText};
5899  `})),s5=(0,i5.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n})=>{let{t:r}=c(`plugin`),i=(0,i5.useMemo)(()=>{let n=e?.operations||t?.operations;return Array.isArray(n)?n.reduce((e,t)=>{switch(t.action){case`insert`:e.insert++;break;case`modify`:e.modify++;break;case`remove`:e.remove++;break}return e},{insert:0,modify:0,remove:0}):{insert:0,modify:0,remove:0}},[e?.operations,t?.operations]),a=i.insert>0||i.modify>0||i.remove>0;if(n&&!a)return(0,a5.jsx)(`div`,{className:W(G8,U8.shinyText),children:(0,a5.jsx)(`span`,{children:r(`builtins.lobe-page-agent.apiName.modifyNodes.init`)})});let o=[];return i.insert>0&&o.push((0,a5.jsxs)(mn,{code:!0,as:`span`,color:U.colorSuccess,fontSize:12,children:[(0,a5.jsx)(vn,{icon:Gn,size:12}),i.insert]},`insert`)),i.modify>0&&o.push((0,a5.jsxs)(mn,{code:!0,as:`span`,color:U.colorWarning,fontSize:12,children:[(0,a5.jsx)(vn,{icon:Hn,size:12}),i.modify]},`modify`)),i.remove>0&&o.push((0,a5.jsxs)(mn,{code:!0,as:`span`,color:U.colorError,fontSize:12,children:[(0,a5.jsx)(vn,{icon:$n,size:12}),i.remove]},`remove`)),(0,a5.jsxs)(`div`,{className:W(G8,n&&U8.shinyText),children:[(0,a5.jsx)(`span`,{className:o5.title,children:r(`builtins.lobe-page-agent.apiName.modifyNodes`)}),o.length>0&&(0,a5.jsxs)(a5.Fragment,{children:[` `,o.map((e,t)=>(0,a5.jsxs)(`span`,{children:[t>0&&(0,a5.jsx)(`span`,{className:o5.separator,children:` / `}),e]},t))]})]})}),s5.displayName=`ModifyNodesInspector`})),fze,c5,l5,u5,pze=e((()=>{Pn(),hn(),Zn(),fze=t(qt()),a(),Y8(),c5=t(xt()),l5=bn(({css:e,cssVar:t})=>({arrow:e`
5900    margin-inline: 4px;
5901    color: ${t.colorTextQuaternary};
5902  `,from:e`
5903    color: ${t.colorTextSecondary};
5904    text-decoration: line-through;
5905  `,title:e`
5906    margin-inline-end: 8px;
5907    color: ${t.colorText};
5908  `})),u5=(0,fze.memo)(({args:e,partialArgs:t,isArgumentsStreaming:n,pluginState:r})=>{let{t:i}=c(`plugin`),a=e?.searchText||t?.searchText,o=e?.newText??t?.newText;if(n&&!a)return(0,c5.jsx)(`div`,{className:W(K8.root,U8.shinyText),children:(0,c5.jsx)(`span`,{children:i(`builtins.lobe-page-agent.apiName.replaceText.init`)})});let s=r?.replacementCount??0,l=a&&o!==void 0;return(0,c5.jsxs)(`div`,{className:W(K8.root,n&&U8.shinyText),children:[(0,c5.jsx)(`span`,{className:l5.title,children:i(`builtins.lobe-page-agent.apiName.replaceText`)}),l&&(0,c5.jsxs)(c5.Fragment,{children:[(0,c5.jsx)(`span`,{className:l5.from,children:a}),(0,c5.jsx)(vn,{className:l5.arrow,icon:K,size:12}),(0,c5.jsx)(`span`,{className:q8.gold,children:o||i(`builtins.lobe-page-agent.apiName.replaceText.empty`)}),s>0&&(0,c5.jsxs)(mn,{code:!0,as:`span`,fontSize:12,type:`secondary`,children:[` `,`(`,i(`builtins.lobe-page-agent.apiName.replaceText.count`,{count:s}),`)`]})]})]})}),u5.displayName=`ReplaceTextInspector`})),mze,hze=e((()=>{Sq(),rze(),oze(),uze(),dze(),pze(),mze={[xq.editTitle]:Z8,[xq.getPageContent]:$8,[xq.initPage]:r5,[xq.modifyNodes]:s5,[xq.replaceText]:u5}})),gze,d5,f5,_ze,vze,p5,yze=e((()=>{Pn(),hn(),Zn(),gze=t(qt()),d5=t(xt()),f5=bn(({css:e,cssVar:t})=>({content:e`
5909    overflow: hidden;
5910    flex: 1;
5911
5912    min-width: 0;
5913
5914    font-family: ${t.fontFamilyCode};
5915    font-size: 12px;
5916    color: ${t.colorText};
5917    text-overflow: ellipsis;
5918    white-space: nowrap;
5919  `,index:e`
5920    flex-shrink: 0;
5921
5922    width: 18px;
5923
5924    font-size: 12px;
5925    color: ${t.colorTextQuaternary};
5926    text-align: end;
5927  `,position:e`
5928    flex-shrink: 0;
5929
5930    padding-block: 1px;
5931    padding-inline: 6px;
5932    border-radius: 4px;
5933
5934    font-family: ${t.fontFamilyCode};
5935    font-size: 11px;
5936    color: ${t.colorTextSecondary};
5937
5938    background: ${t.colorFillTertiary};
5939  `,row:e`
5940    display: flex;
5941    gap: 8px;
5942    align-items: center;
5943
5944    padding-block: 8px;
5945    padding-inline: 12px;
5946    border-block-end: 1px dashed ${t.colorBorderSecondary};
5947
5948    &:last-child {
5949      border-block-end: none;
5950    }
5951  `})),_ze={insert:{color:U.colorSuccess,icon:Gn},modify:{color:U.colorWarning,icon:Hn},remove:{color:U.colorError,icon:$n}},vze=e=>{switch(e.action){case`insert`:{let t=`afterId`in e?`after #${e.afterId}`:`before #${e.beforeId}`;return{content:e.litexml,position:t}}case`modify`:return{content:Array.isArray(e.litexml)?e.litexml.join(`
5952`):e.litexml};case`remove`:return{position:`#${e.id}`}}},p5=(0,gze.memo)(({args:e,pluginState:t})=>{let n=e?.operations;if(!Array.isArray(n)||n.length===0)return null;let r=t?.results??[];return(0,d5.jsx)(Tn,{variant:`outlined`,width:`100%`,children:n.map((e,t)=>{let n=_ze[e.action],i=vze(e),a=r[t],o=a?.success===!0,s=a?.success===!1;return(0,d5.jsxs)(`div`,{className:f5.row,children:[(0,d5.jsxs)(`span`,{className:f5.index,children:[t+1,`.`]}
5952),(0,d5.jsx)(vn,{icon:n.icon,size:14,style:{color:n.color,flexShrink:0}}),i.position&&(0,d5.jsx)(`span`,{className:f5.position,children:i.position}),i.content&&(0,d5.jsx)(`span`,{className:f5.content,children:i.content}),o&&(0,d5.jsx)(vn,{icon:Jn,size:14,style:{color:U.colorSuccess,flexShrink:0}}),s&&(0,d5.jsxs)(d5.Fragment,{children:[(0,d5.jsx)(vn,{icon:rr,size:14,style:{color:U.colorError,flexShrink:0}}),a?.error&&(0,d5.jsx)(mn,{as:`span`,fontSize:11,type:`danger`,children:a.error})]})]},t)})})}),p5.displayName=`ModifyNodesRender`})),bze,xze=e((()=>{Sq(),yze(),bze={[xq.initPage]:null,[xq.modifyNodes]:p5}}));function Sze(e={}){let{deps:t=[],enabled:n=!0,threshold:r=20}=e,i=(0,m5.useRef)(null),[a,o]=(0,m5.useState)(!1),s=(0,m5.useRef)(!1),c=(0,m5.useRef)(n),l=(0,m5.useCallback)(()=>{if(s.current)return;let e=i.current;e&&(e.scrollHeight-e.scrollTop-e.clientHeight<r||o(!0))},[r]),u=(0,m5.useCallback)(()=>{o(!1)},[]);return(0,m5.useEffect)(()=>{let e=i.current;if(e){if(c.current&&!n){let t=e.scrollTop;s.current=!0,requestAnimationFrame(()=>{e.scrollTop=t,requestAnimationFrame(()=>{s.current=!1})})}c.current=n}},[n]),(0,m5.useEffect)(()=>{if(!n||a)return;let e=i.current;e&&(s.current=!0,requestAnimationFrame(()=>{e.scrollTop=e.scrollHeight,requestAnimationFrame(()=>{s.current=!1})}))},[n,a,...t]),{handleScroll:l,ref:i,resetScrollLock:u,userHasScrolled:a}}var m5,Cze=e((()=>{m5=t(qt())})),h5,g5,_5,v5,wze=e((()=>{Pn(),hn(),h5=t(qt()),Cze(),g5=t(xt()),_5=bn(({css:e})=>({container:e`
5953    padding-block: 12px;
5954    padding-inline: 16px;
5955    border-radius: 8px;
5956    font-size: 14px;
5957  `,scrollRoot:e`
5958    border-radius: 0;
5959    background: transparent;
5960  `})),v5=(0,h5.memo)(({children:e,maxHeight:t=400})=>{let{ref:n,handleScroll:r,resetScrollLock:i}=Sze({deps:[e]});return(0,h5.useEffect)(()=>{e||i()},[e,i]),e?(0,g5.jsx)(_n,{disableContentFit:!0,scrollFade:!0,className:_5.scrollRoot,contentProps:{style:{color:`inherit`,display:`block`,fontSize:`inherit`,gap:0,lineHeight:`inherit`}},viewportProps:{className:_5.container,ref:n,style:{maxHeight:t},onScroll:r},children:(0,g5.jsx)(Cn,{animated:!0,style:{overflow:`unset`},variant:`chat`,children:e})}):null}),v5.displayName=`StreamingMarkdown`})),y5,b5,x5,S5,Tze,C5,Eze=e((()=>{Pn(),hn(),Zn(),y5=t(qt()),a(),wze(),sze(),b5=t(xt()),x5=4e3,S5=bn(({css:e,cssVar:t})=>({container:e`
5961    overflow: hidden;
5962
5963    width: 100%;
5964    border: 1px solid ${t.colorBorderSecondary};
5965    border-radius: 8px;
5966
5967    background: ${t.colorBgContainer};
5968  `,header:e`
5969    padding-block: 10px;
5970    padding-inline: 12px;
5971    border-block-end: 1px solid ${t.colorBorderSecondary};
5972  `,icon:e`
5973    color: ${t.colorPrimary};
5974  `,meta:e`
5975    color: ${t.colorTextDescription};
5976  `,preview:e`
5977    max-height: 360px;
5978    overflow: auto;
5979    padding-block: 8px;
5980    padding-inline: 12px;
5981  `,title:e`
5982    overflow: hidden;
5983    display: -webkit-box;
5984    -webkit-box-orient: vertical;
5985    -webkit-line-clamp: 1;
5986
5987    font-weight: 500;
5988    color: ${t.colorText};
5989  `})),Tze=e=>e.split(/\r?\n/).find(e=>e.startsWith(`# `)&&e.slice(2).trim().length>0)?.slice(2).trim(),C5=(0,y5.memo)(({args:e})=>{let{t}=c(`plugin`),n=e?.markdown||``,{chars:r,lines:i,preview:a,title:o}=(0,y5.useMemo)(()=>{let e=n.length>x5?`${n.slice(0,x5)}\n\n...`:n;return{chars:n.length,lines:n?n.split(`
5990`).length:0,preview:e,title:Tze(n)}},[n]);return n?(0,b5.jsxs)(yn,{className:S5.container,children:[(0,b5.jsxs)(yn,{horizontal:!0,align:`center`,className:S5.header,gap:8,children:[(0,b5.jsx)(cee,{className:S5.icon,size:16}),(0,b5.jsxs)(yn,{flex:1,gap:2,children:[(0,b5.jsx)(`div`,{className:S5.title,children:o||t(`builtins.lobe-page-agent.apiName.initPage.creating`)}),(0,b5.jsxs)(yn,{horizontal:!0,align:`center`,className:S5.meta,gap:10,children:[(0,b5.jsxs)(mn,{as:`span`,color:U.colorTextDescription,fontSize:12,children:[(0,b5.jsx)(vn,{icon:Un,size:12}),` `,(0,b5.jsx)(t5,{value:i}),t(`builtins.lobe-page-agent.apiName.initPage.lines`)]}),(0,b5.jsxs)(mn,{as:`span`,color:U.colorTextDescription,fontSize:12,children:[(0,b5.jsx)(vn,{icon:mee,size:12}),` `,(0,b5.jsx)(t5,{value:r}),t(`builtins.lobe-page-agent.apiName.initPage.chars`)]})]})]})]}),(0,b5.jsx)(`div`,{className:S5.preview,children:(0,b5.jsx)(v5,{children:a})})]}):null}),C5.displayName=`PageAgentInitPageStreaming`})),Dze,Oze=e((()=>{Sq(),Eze(),Dze={[xq.initPage]:C5}})),kze=e((()=>{GRe(),hze(),xze(),Oze(),wq(),Sq()})),Aze,w5,T5,jze,Mze,Nze,Pze,Fze=e((()=>{die(),Aze=function(e){return e[e.Reject=0]=`Reject`,e[e.Accept=1]=`Accept`,e}({}),w5=io(`LITEXML_MODIFY_COMMAND`),T5=io(`LITEXML_APPLY_COMMAND`),jze=io(`LITEXML_REMOVE_COMMAND`),Mze=io(`
5990LITEXML_INSERT_COMMAND`),Nze=io(`LITEXML_DIFFNODE_COMMAND`),Pze=io(`LITEXML_DIFFNODE_ALL_COMMAND`)})),Ize,E5,D5,O5,Lze,Rze=e((()=>{Fze(),Ize=t(F()),E5=(0,Ize.default)(`lobe:editor-runtime`),D5=e=>{let t=e.dataTypeMap;return t?t instanceof Map?[...t.keys()].sort():Object.keys(t).sort():[]},O5=(e,t)=>D5(e).includes(t),Lze=class{editor=null;titleSetter=null;titleGetter=null;currentDocId=void 0;afterMutateHandler=null;beforeMutateHandler=null;setEditor(e){this.editor=e,E5(`[EditorRuntime] setEditor`,this.getDebugSnapshot())}setCurrentDocId(e){E5(`Setting current doc ID:`,e),this.currentDocId=e,E5(`[EditorRuntime] setCurrentDocId`,this.getDebugSnapshot())}getCurrentDocId(){return this.currentDocId}setBeforeMutateHandler(e){this.beforeMutateHandler=e,E5(`[EditorRuntime] setBeforeMutateHandler`,this.getDebugSnapshot())}setAfterMutateHandler(e){this.afterMutateHandler=e,E5(`[EditorRuntime] setAfterMutateHandler`,this.getDebugSnapshot())}setTitleHandlers(e,t){this.titleSetter=e,this.titleGetter=t,E5(`[EditorRuntime] setTitleHandlers`,this.getDebugSnapshot())}getDebugSnapshot(){let e=this.editor,t=(()=>{try{return!!e?.getLexicalEditor?.()}catch{return!1}})();return{currentDocId:this.currentDocId,dataSourceTypes:e?D5(e):[],hasAfterMutateHandler:!!this.afterMutateHandler,hasBeforeMutateHandler:!!this.beforeMutateHandler,hasEditor:!!this.editor,hasLexicalEditor:t,hasTitleGetter:!!this.titleGetter,hasTitleSetter:!!this.titleSetter,pluginCount:e?.plugins?.length,pluginInstanceCount:e?.pluginsInstances?.length}}isReady(){if(!this.editor)return!1;let e=this.editor;try{return!!e.getLexicalEditor?.()}catch{return!1}}applyServerSnapshot(e){let t=!1;if(this.editor&&e.editorData)try{this.editor.setDocument(`json`,JSON.stringify(e.editorData),{keepId:!0}),t=!0}catch(e){E5(`[EditorRuntime] applyServerSnapshot:editorData failed`,e)}else if(this.editor&&typeof e.content==`string`)try{this.editor.setDocument(`markdown`,e.content,{keepId:!0}),t=!0}catch(e){E5(`[EditorRuntime] applyServerSnapshot:markdown failed`,e)}if(typeof e.title==`string`&&this.titleSetter)try{this.titleSetter(e.title),t=!0}catch(e){E5(`[EditorRuntime] applyServerSnapshot:title failed`,e)}return E5(`[EditorRuntime] applyServerSnapshot`,{applied:t,hasEditorData:!!e.editorData,hasTitle:typeof e.title==`string`}),t}getEditor(){if(!this.editor)throw Error(`Editor not initialized. Please set the editor instance first.`);return this.editor}getTitleHandlers(){if(!this.titleSetter||!this.titleGetter)throw Error(`Title handlers not initialized. Please set the title handlers first.`);return{getter:this.titleGetter,setter:this.titleSetter}}async runBeforeMutate(e){try{await this.beforeMutateHandler?.({apiName:e})}catch{}}async runAfterMutate(){try{await this.afterMutateHandler?.()}catch{}}async initPage(e){if(E5(`[EditorRuntime] initPage:start`,{markdownLength:e.markdown.length,snapshot:this.getDebugSnapshot()}),!e.markdown||e.markdown.trim().length===0)throw Error(`initPage failed: markdown content is empty.`);await this.runBeforeMutate(`initPage`);let t=this.getEditor(),n=e.markdown,r;if(n.startsWith(`# `)){let e=n.search(/\r?\n/),t=e===-1?n:n.slice(0,e);r=t.slice(2).trim(),n=n.slice(t.length).trimStart(),E5(`[EditorRuntime] initPage:titleExtracted`,{extractedTitle:r,remainingMarkdownLength:n.length}),this.titleSetter&&this.titleSetter(r)}t.setDocument(`markdown`,n,{keepId:!0});let i=t.getDocument(`json`),a=i?.root??i,o=a?.children?.length||0;if(E5(`[EditorRuntime] initPage:afterSetDocument`,{nodeCount:o,jsonStateKeys:i?Object.keys(i):null,rootKeys:a?Object.keys(a):null}),o===0)throw Error(`initPage failed: setDocument produced 0 nodes. Input markdown length: ${e.markdown.length}, after title-stripping: ${n.length}. jsonState keys: ${i?JSON.stringify(Object.keys(i)):`null`}, root keys: ${a?JSON.stringify(Object.keys(a)):`null`}.`);let s={extractedTitle:r,nodeCount:o};return E5(`[EditorRuntime] initPage:success`,{nodeCount:o,snapshot:this.getDebugSnapshot(),titleExtracted:!!r}),await this.runAfterMutate(),s}async editTitle(e){E5(`[EditorRuntime] editTitle:start`,{snapshot:this.getDebugSnapshot(),titleLength:e.title.length}),await this.runBeforeMutate(`editTitle`);let{setter:t,getter:n}=this.getTitleHandlers(),r=n();t(e.title);let i={newTitle:e.title,previousTitle:r};return E5(`[EditorRuntime] editTitle:success`,{snapshot:this.getDebugSnapshot(),titleLength:e.title.length}),await this.runAfterMutate(),i}async getPageContent(e){E5(`[EditorRuntime] getPageContent:start`,{format:e.format,snapshot:this.getDebugSnapshot()});let t=this.getPageContentContext(e.format);return{charCount:t.metadata.charCount,documentId:this.currentDocId||`current`,lineCount:t.metadata.lineCount,markdown:t.markdown,title:t.metadata.title,xml:t.xml}}getPageContentContext(e=`both`){let t=this.getEditor(),{getter:n}=this.getTitleHandlers(),r=n()||`Untitled`,i=t.getDocument(`litexml`);E5(`Getting page content context, format:`,e);let a={metadata:{title:r}};if(e===`markdown`||e===`both`){let e=t.getDocument(`markdown`),n=String(e||``);a.markdown=n,a.metadata.charCount=n.length,a.metadata.lineCount=n.split(`
5991`).length}return(e===`xml`||e===`both`)&&(a.xml=i||``),a}async modifyNodes(e){let t=Array.isArray(e.operations)?e.operations:e.operations?[e.operations]:[];E5(`[EditorRuntime] modifyNodes:start`,{operationActions:t.map(e=>e.action),operationCount:t.length,snapshot:this.getDebugSnapshot()}),await this.runBeforeMutate(`modifyNodes`);let n=this.getEditor(),{operations:r}=e;if(!r)throw Error(`No operations provided`);
5991Array.isArray(r)||(E5(`Converting single operation to array`),r=[r]),E5(`Processing operations:`,r.length);let i=[],a=[];for(let e of r)try{switch(e.action){case`insert`:if(`beforeId`in e)i.push({action:`insert`,beforeId:e.beforeId,litexml:e.litexml});else if(`afterId`in e)i.push({action:`insert`,afterId:e.afterId,litexml:e.litexml});else throw Error(`Insert operation requires either 'beforeId' or 'afterId'. Got: ${JSON.stringify(Object.keys(e))}.`);a.push({action:`insert`,success:!0});break;case`modify`:i.push({action:`modify`,litexml:e.litexml}),a.push({action:`modify`,success:!0});break;case`remove`:i.push({action:`remove`,id:e.id}),a.push({action:`remove`,success:!0});break}}catch(t){let n=t;console.error(`[modifyNodes] Error processing operation:`,e.action,n.message),a.push({action:e.action,error:n.message,success:!1})}if(!O5(n,`litexml`))throw Error(`modifyNodes failed: LiteXML data source is not ready.`);E5(`Dispatching LiteXML modify batch with payload:`,i),n.dispatchCommand(w5,i);let o=a.filter(e=>e.success).length,s=a.length,c={results:a,successCount:o,totalCount:s};return E5(`[EditorRuntime] modifyNodes:success`,{snapshot:this.getDebugSnapshot(),successCount:o,totalCount:s}),await this.runAfterMutate(),c}extractNodesFromLiteXML(e){let t=[],n=/<(\w+)(\s[^>]*id="([^"]+)"[^>]*)>([\s\S]*?)<\/\1>/g,r;for(;(r=n.exec(e))!==null;)t.push({attributes:r[2].trim(),content:r[4],id:r[3],tagName:r[1]});return t}replaceTextInContent(e,t,n,r){let i=0,a=/<[^>]+>/g,o,s=[];for(;(o=a.exec(e))!==null;)s.push({end:o.index+o[0].length,start:o.index});let c=0,l=``;for(let a of s){if(c<a.start){let o=e.slice(c,a.start),{count:s,replaced:u}=this.replaceInText(o,t,n,r&&i===0?!0:r,r?void 0:i===0);l+=u,i+=s}l+=e.slice(a.start,a.end),c=a.end}if(c<e.length){let a=e.slice(c),{count:o,replaced:s}=this.replaceInText(a,t,n,r,!r&&i>0?!1:void 0);l+=s,i+=o}if(s.length===0){let{count:i,replaced:a}=this.replaceInText(e,t,n,r);return{count:i,newContent:a}}return{count:i,newContent:l}}replaceInText(e,t,n,r,i=!0){if(!i)return{count:0,replaced:e};let a=0,o;if(typeof t==`string`)if(r){let r=new RegExp(this.escapeRegExp(t),`g`);a=e.match(r)?.length||0,o=e.split(t).join(n)}else{let r=e.indexOf(t);r===-1?o=e:(o=e.slice(0,r)+n+e.slice(r+t.length),a=1)}else if(r){let r=t.global?t:new RegExp(t.source,t.flags+`g`);a=e.match(r)?.length||0,o=e.replaceAll(r,n)}else t.exec(e)?(o=e.replace(t,n),a=1):o=e;return{count:a,replaced:o}}escapeRegExp(e){return e.replaceAll(/[$()*+.?[\\\]^{|}]/g,`\\$&`)}async replaceText(e){await this.runBeforeMutate(`replaceText`);let t=this.getEditor(),{searchText:n,newText:r,useRegex:i=!1,replaceAll:a=!0,nodeIds:o}=e;E5(`Starting replacement:`,{newText:r,nodeIds:o,replaceAll:a,searchText:n,useRegex:i});let s=t.getDocument(`litexml`);if(!s)throw console.error(`[EditorRuntime] replaceText:failed — pageXML is empty`),Error(`Document is empty or not initialized`);let c;if(i)try{c=new RegExp(n,a?`g`:``)}catch{throw Error(`Invalid regex pattern: ${n}`)}else c=n;let l=this.extractNodesFromLiteXML(s),u=l.map(e=>e.id);E5(`Found nodes:`,l.length);let d=o&&o.length>0,f=d?l.filter(e=>o.includes(e.id)):l;if(d&&f.length===0)throw E5(`[replaceText] Node IDs requested:`,o,`Available IDs:`,u),Error(`None of the specified nodes were found: ${o.join(`, `)}`);let p=0,m=[],h=[];for(let e of f){if(!(typeof c==`string`?e.content.includes(c):c.test(e.content)))continue;c instanceof RegExp&&(c.lastIndex=0);let{count:t,newContent:n}=this.replaceTextInContent(e.content,c,r,a);if(t>0){p+=t,m.push(e.id);let r=`<${e.tagName} ${e.attributes}>${n}</${e.tagName}>`;if(h.push(r),E5(`Updated node:`,e.id,`count:`,t),!a)break}}if(h.length>0){if(E5(`Applying updates:`,h.length),!O5(t,`litexml`))throw Error(`replaceText failed: LiteXML data source is not ready.`);t.dispatchCommand(T5,{litexml:h}),E5(`LiteXML replace dispatched`)}let g={modifiedNodeIds:m,replacementCount:p};return await this.runAfterMutate(),g}}})),zze=e((()=>{})),Bze=e((()=>{Rze(),zze()})),k5,Vze,A5=e((()=>{kze(),Bze(),k5=new Lze,Vze=new WRe(k5)})),Hze,Uze=e((()=>{Hze=class{service;constructor(e){this.service=e.service}notifyImported(){return this.service.onSkillImported?.()??Promise.resolve()}async importSkill(e){let{url:t,type:n}=e,r=!1;try{let e=new URL(t).hostname;r=e===`github.com`||e.endsWith(`.github.com`)}catch{}try{let e;return e=r&&n===`url`?await this.service.importFromGitHub(t):n===`zip`?await this.service.importFromZipUrl(t):await this.service.importFromUrl(t),await this.service.onSkillImported?.(),{content:`Skill "${e.skill.name}" ${e.status} successfully.`,state:{name:e.skill.name,skillId:e.skill.id,status:e.status,success:!0},success:!0}}catch(e){return{content:`Failed to import skill: ${e.message}`,success:!1}}}async searchSkill(e){if(!this.service.searchSkill)return{content:`Market skill search is not available in this environment.`,success:!1};try{let t=await this.service.searchSkill(e);
5991if(t.items.length===0)return{content:e.q?`No skills found matching "${e.q}"`:`No skills found in the market`,state:t,success:!0};let n=t.items.map((e,t)=>`${t+1}. **${e.name}** (${e.identifier})\n   ${e.description}${e.summary?`\n   Summary: ${e.summary}`:``}${e.repository?`\n   Repository: ${e.repository}`:``}${e.installCount?`\n   Installs: ${e.installCount}`:``}`).join(`
5992
5993`);return{content:`Found ${t.total} skills (page ${t.page}/${Math.ceil(t.total/t.pageSize)}):\n\n${n}`,state:t,success:!0}}catch(e){return{content:`Failed to search skills: ${e.message}`,success:!1}}}async importFromMarket(e){let{identifier:t}=e;if(!this.service.importFromMarket)return{content:`Market skill import is not available in this environment.`,success:!1};try{let e=await this.service.importFromMarket(t);return await this.service.onSkillImported?.(),{content:`Skill "${e.skill.name}" ${e.status} successfully from market.`,state:{name:e.skill.name,skillId:e.skill.id,status:e.status,success:!0},success:!0}}catch(e){return{content:`Failed to import skill from market: ${e.message}`,success:!1}}}}})),Wze,Gze,Kze=e((()=>{Ne(),nJ(),Wze=new Set([tJ.importSkill,tJ.importFromMarket]),Gze=class extends ye{identifier=eJ;apiEnum=tJ;runtime;constructor(e){super(),this.runtime=e}onAfterCall=async({apiName:e,result:t})=>{!Wze.has(e)||!t.success||await this.runtime.notifyImported()};importSkill=async(e,t)=>{try{if(t.signal?.aborted)return{stop:!0,success:!1};let n=await this.runtime.importSkill(e);return n.success?{content:n.content,state:n.state,success:!0}:{content:n.content,error:{message:n.content,type:`PluginServerError`},success:!1}}catch(e){return{error:{body:e,message:e.message,type:`PluginServerError`},success:!1}}};searchSkill=async(e,t)=>{try{if(t.signal?.aborted)return{stop:!0,success:!1};let n=await this.runtime.searchSkill(e);return n.success?{content:n.content,state:n.state,success:!0}:{content:n.content,error:{message:n.content,type:`PluginServerError`},success:!1}}catch(e){return{error:{body:e,message:e.message,type:`PluginServerError`},success:!1}}};importFromMarket=async(e,t)=>{try{if(t.signal?.aborted)return{stop:!0,success:!1};let n=await this.runtime.importFromMarket(e);return n.success?{content:n.content,state:n.state,success:!0}:{content:n.content,error:{message:n.content,type:`PluginServerError`},success:!1}}catch(e){return{error:{body:e,message:e.message,type:`PluginServerError`},success:!1}}}}})),qze,j5,Jze=e((()=>{pa(),$a(),qze=class{async createAgent(e){return q.market.agent.createAgent.mutate(e)}async getAgentDetail(e){return q.market.agent.getAgentDetail.query({identifier:e})}async checkAgentExists(e){try{return await this.getAgentDetail(e),!0}catch{return!1}}async createAgentVersion(e){return q.market.agent.createAgentVersion.mutate(e)}async deprecateAgent(e){await q.market.agent.deprecateAgent.mutate({identifier:e})}async getOwnAgents(e){return q.market.agent.getOwnAgents.query(e)}async forkAgent(e){return q.market.agent.forkAgent.mutate({items:e})}async getAgentForks(e){return q.market.agent.getAgentForks.query({identifier:e})}async getAgentForkSource(e){return q.market.agent.getAgentForkSource.query({identifier:e})}async getAgentGroupDetail(e){return q.market.agentGroup.getAgentGroupDetail.query({identifier:e})}async deprecateAgentGroup(e){await q.market.agentGroup.deprecateAgentGroup.mutate({identifier:e})}async forkAgentGroup(e,t){return q.market.agentGroup.forkAgentGroup.mutate({sourceIdentifier:e,...t})}async getAgentGroupForks(e){return q.market.agentGroup.getAgentGroupForks.query({identifier:e})}async getAgentGroupForkSource(e){return q.market.agentGroup.getAgentGroupForkSource.query({identifier:e})}async searchSkill(e){return await eo.safeInjectMPToken(),q.market.skill.getSkillList.query(e)}getSkillDownloadUrl(e){return`${{}.NEXT_PUBLIC_MARKET_BASE_URL||`https://market.lobehub.com`}/api/v1/skills/${e}/download`}},j5=new qze})),Yze,Xze,Zze=e((()=>{Uze(),Kze(),Jze(),IY(),Pe(),Yze=new Hze({service:{importFromGitHub:async e=>{let t=await FY.importFromGitHub({gitUrl:e});if(!t)throw Error(`Import failed`);return{skill:{id:t.skill.id,name:t.skill.name},status:t.status}},importFromMarket:async e=>{let t=await FY.importFromMarket(e);if(!t)throw Error(`Import failed`);return{skill:{id:t.skill.id,name:t.skill.name},status:t.status}},importFromUrl:async e=>{let t=await FY.importFromUrl({url:e});if(!t)throw Error(`Import failed`);return{skill:{id:t.skill.id,name:t.skill.name},status:t.status}},importFromZipUrl:async e=>{let t=await FY.importFromUrl({url:e});if(!t)throw Error(`Import failed`);return{skill:{id:t.skill.id,name:t.skill.name},status:t.status}},onSkillImported:async()=>{let{getToolStoreState:e}=await Ge(async()=>{let{getToolStoreState:e}=await Promise.resolve().then(()=>(d7(),EVe));return{getToolStoreState:e}},void 0);await e().refreshAgentSkills()},searchSkill:async e=>{let t=await j5.searchSkill({...e,sort:e.sort});return{items:t.items,page:t.currentPage,pageSize:t.pageSize,total:t.totalCount}}}}),Xze=new Gze(Yze)})),Qze,$ze=e((()=>{Ne(),cJ(),Qze=class extends ye{identifier=oJ;apiEnum=sJ;runtime;constructor(e){super(),this.runtime=e}execScript=async(e,t)=>{try{if(t.signal?.aborted)return{stop:!0,success:!1};let n=t.stepContext?.activatedSkills,r=await this.runtime.execScript({...e,activatedSkills:n?.map(e=>({description:e.description,id:e.id,name:e.name}))});return r.success?{content:r.content,state:r.state,success:!0}:{content:r.content,error:{message:r.content,type:`PluginServerError`},success:!1}}catch(e){return{error:{body:e,message:e.message,type:`PluginServerError`},success:!1}}};activateSkill=async(e,t)=>{try{if(t.signal?.aborted)return{stop:!0,success:!1};let n=await this.runtime.activateSkill(e);return n.success?{content:n.content,state:n.state,success:!0}:{content:n.content,error:{message:n.content,type:`PluginServerError`},success:!1}}catch(e){return{error:{body:e,message:e.message,type:`PluginServerError`},success:!1}}};readReference=async(e,t)=>{try{if(t.signal?.aborted)return{stop:!0,success:!1};let n=await this.runtime.readReference(e);return n.success?{content:n.content,state:n.state,success:!0}:{content:n.content,error:{message:n.content,type:`PluginServerError`},success:!1}}catch(e){return{error:{body:e,message:e.message,type:`PluginServerError`},success:!1}}};runCommand=async(e,t)=>{try{if(t.signal?.aborted)return{stop:!0,success:!1};let n=await this.runtime.runCommand(e);return n.success?{content:n.content,state:n.state,success:!0}:{content:n.content,error:{message:n.content,type:`PluginServerError`},success:!1}}catch(e){return{error:{body:e,message:e.message,type:`PluginServerError`},success:!1}}};exportFile=async(e,t)=>{try{if(t.signal?.aborted)return{stop:!0,success:!1};let n=await this.runtime.exportFile(e);return n.success?{content:n.content,state:n.state,success:!0}:{content:n.content,error:{message:n.content,type:`PluginServerError`},success:!1}}catch(e){return{error:{body:e,message:e.message,type:`PluginServerError`},success:!1}}}}})),eBe,tBe,nBe=e((()=>{Fc(),uRe(),$ze(),dY(),mNe(),IY(),bc(),eBe=new k8({builtinSkills:uY(Pc),service:{execScript:async(e,t)=>{let{activatedSkills:n,description:r}=t,i=Z9.getState().activeTopicId||`default`;try{let t=await y3.callTool(`execScript`,{activatedSkills:n,command:e,description:r},{topicId:i});if(!t.success)return{exitCode:1,output:``,stderr:t.error?.message||`Command execution failed`,success:!1};let a=t.result||{};return{exitCode:a.exitCode??+!t.success,output:a.stdout||a.output||``,stderr:a.stderr||``,success:t.success&&(a.exitCode===0||a.exitCode===void 0)}}catch(e){return{exitCode:1,output:``,stderr:e.message||`Command execution failed`,success:!1}}},exportFile:async(e,t)=>{let n=Z9.getState().activeTopicId||`default`;try{let r=await y3.exportAndUploadFile(e,t,n);return{fileId:r.fileId,filename:r.filename,mimeType:r.mimeType,size:r.size,success:r.success,url:r.url}}catch{return{filename:t,success:!1}}},findAll:()=>FY.list(),findById:e=>FY.getById(e),findByName:e=>FY.getByName(e),readResource:(e,t)=>FY.readResource(e,t),runCommand:async({command:e,timeout:t})=>{let n=Z9.getState().activeTopicId||`default`;try{let r=await y3.callTool(`runCommand`,{command:e,description:`Execute skill command: ${e.slice(0,100)}${e.length>100?`...`:``}`,timeout:t},{topicId:n});if(!r.success)return{exitCode:1,output:``,stderr:r.error?.message||`Command execution failed`,success:!1};let i=r.result||{};return{exitCode:i.exitCode??+!r.success,output:i.stdout||i.output||``,stderr:i.stderr||``,success:r.success&&(i.exitCode===0||i.exitCode===void 0)}}catch(e){return{exitCode:1,output:``,stderr:e.message||`Command execution failed`,success:!1}}}}}),tBe=new Qze(eBe)})),rBe,iBe,aBe=e((()=>{Ne(),OJ(),rBe={getTopicContext:`getTopicContext`},iBe=class extends ye{identifier=EJ;apiEnum=rBe;runtime;constructor(e){super(),this.runtime=e}getTopicContext=async(e,t)=>this.runtime.getTopicContext(e)}})),oBe,sBe,cBe,lBe=e((()=>{aBe(),pa(),oBe=class{getTopicContext=async e=>{let{topicId:t}=e;if(!t)return{content:`topicId is required`,success:!1};try{let e=await q.topic.getTopicContext.query({topicId:t});return{content:e.content,success:e.success}}catch(e){return{content:`Failed to fetch topic context: ${e instanceof Error?e.message:String(e)}`,success:!1}}}},sBe=new oBe,cBe=new iBe(sBe)})),M5,uBe,dBe=e((()=>{Ne(),ii(),zee(),M5=class extends ye{identifier=Lee;apiEnum=Iee;runtime;constructor(e){super(),this.runtime=e}askUserQuestion=async(e,t)=>this.runtime.askUserQuestion(e);submitUserResponse=async(e,t)=>this.runtime.submitUserResponse(e);skipUserResponse=async(e,t)=>this.runtime.skipUserResponse(e);cancelUserResponse=async(e,t)=>this.runtime.cancelUserResponse(e);getInteractionState=async(e,t)=>this.runtime.getInteractionState(e)},uBe=new Cr,new M5(uBe)})),fBe,pBe,mBe=e((()=>
5993{ii(),dBe(),fBe=new Cr,pBe=new M5(fBe)})),hBe,gBe,N5,_Be=e((()=>{Zn(),hBe={files:_ee,general:Kn,images:xee,it:See,map:Cee,music:hee,news:lee,science:bee,social_media:Tee,videos:pee},gBe={arxiv:`https://icons.duckduckgo.com/ip3/arxiv.org.ico`,bilibili:`https://icons.duckduckgo.com/ip3/bilibili.com.ico`,bing:`https://icons.duckduckgo.com/ip3/www.bing.com.ico`,"bing news":`https://icons.duckduckgo.com/ip3/www.bing.com.ico`,brave:`https://icons.duckduckgo.com/ip3/brave.com.ico`,"brave.news":`https://icons.duckduckgo.com/ip3/brave.com.ico`,duckduckgo:`https://icons.duckduckgo.com/ip3/www.duckduckgo.com.ico`,github:`https://icons.duckduckgo.com/ip3/github.com.ico`,google:`https://icons.duckduckgo.com/ip3/google.com.ico`,"google scholar":`https://icons.duckduckgo.com/ip3/scholar.google.com.ico`,npm:`https://icons.duckduckgo.com/ip3/npmjs.com.ico`,openairepublications:`https://icons.duckduckgo.com/ip3/doi.org.ico`,pubmed:`https://icons.duckduckgo.com/ip3/pubmed.ncbi.nlm.nih.gov.ico`,qwant:`https://icons.duckduckgo.com/ip3/www.qwant.com.ico`,"sogou wechat":`https://icons.duckduckgo.com/ip3/weixin.sogou.com.ico`,youtube:`https://icons.duckduckgo.com/ip3/youtube.com.ico`},N5=25e3})),P5,vBe=e((()=>{Mi(),_Be(),P5=class{agentId;documentService;searchService;topicId;constructor(e){this.searchService=e.searchService,this.documentService=e.documentService,this.agentId=e.agentId,this.topicId=e.topicId}async search(e,t){try{let n=await this.searchService.webSearch(e,t);return n.errorDetail?{content:n.errorDetail,error:{message:n.errorDetail},state:n,success:!1}:{content:Mne(n.results.slice(0,30).map(e=>({title:e.title,url:e.url,...e.content&&{content:e.content},...e.publishedDate&&{publishedDate:e.publishedDate},...e.imgSrc&&{imgSrc:e.imgSrc},...e.thumbnail&&{thumbnail:e.thumbnail}}))),state:n,success:!0}}catch(e){return{content:e.message,error:e,success:!1}}}async crawlSinglePage(e){return this.crawlMultiPages({urls:[e.url]})}async crawlMultiPages(e){let t=await this.searchService.crawlPages({urls:e.urls}),{results:n}=t;return this.documentService&&await Promise.all(n.map(async e=>{if(`errorMessage`in e.data)return;let t=e.data;if(t.content)try{let e=await this.documentService.createDocument({content:t.content,description:t.description||`Crawled from ${t.url}`,title:t.title||t.url,url:t.url});await this.documentService.associateDocument(e.id)}catch(e){console.error(`[WebBrowsing] Failed to save crawl result to agent document:`,e)}})),{content:rne(n.map(e=>`errorMessage`in e?e:{...e.data,content:e.data.content?.slice(0,N5)})),state:t,success:!0}}}})),yBe,F5,bBe=e((()=>{pa(),yBe=class{search(e,t){return fa.search.query.query({optionalParams:t,query:e})}crawlPage(e){return fa.search.crawlPages.mutate({urls:[e]})}crawlPages(e){return fa.search.crawlPages.mutate(e)}async webSearch(e,t){return fa.search.webSearch.query(e,{signal:t?.signal})}},F5=new yBe})),xBe,SBe,CBe=e((()=>{pa(),xBe=class{upsertCrawledDocument=async e=>q.webBrowsing.upsertCrawledDocument.mutate(e)},SBe=new xBe})),wBe,TBe,EBe,DBe,OBe=e((()=>{zJ(),vBe(),Ne(),Ii(),bBe(),CBe(),wBe=new P5({searchService:F5}),TBe=e=>({associateDocument:async t=>{e.agentId&&await zi.associateDocument({agentId:e.agentId,documentId:t})},createDocument:async({content:t,description:n,title:r,url:i})=>SBe.upsertCrawledDocument({content:t,description:n||`Crawled from ${i}`,title:r,topicId:e.topicId??void 0,url:i})}),EBe=class extends ye{identifier=LJ.identifier;apiEnum=PJ;search=async(e,t)=>{try{if(t.signal?.aborted)return{stop:!0,success:!1};let n=await wBe.search(e,{signal:t.signal});if(n.success)return{content:n.content,state:n.state,success:!0};let r=n.error;return r?.message===`SearXNG is not configured`?{error:{body:{provider:`searxng`},message:`SearXNG is not configured`,type:`PluginSettingsInvalid`},success:!1}:{error:{body:n.error,message:r?.message||`Search failed`,type:`PluginServerError`},success:!1}}catch(e){let t=e;return t.name===`AbortError`||t.message.includes(`The user aborted a request.`)?{stop:!0,success:!1}:{error:{body:e,message:t.message,type:`PluginServerError`},success:!1}}};crawlSinglePage=async(e,t)=>this.crawlMultiPages({urls:[e.url]},t);crawlMultiPages=async(e,t)=>{try{if(t.signal?.aborted)return{stop:!0,success:!1};let n=await new P5({agentId:t.agentId,documentService:t.topicId?TBe(t):void 0,searchService:F5,topicId:t.topicId??void 0}).crawlMultiPages(e);return n.success?{content:n.content,state:n.state,success:!0}:{content:n.content,error:{body:n.error,message:n.error?.message||`Crawl failed`,type:`PluginServerError`},success:!1}}catch(e){let t=e;return t.name===`AbortError`||t.message.includes(`The user aborted a request.`)?{stop:!0,success:!1}:{error:{body:e,message:t.message,type:`PluginServerError`},success:!1}}}},DBe=new EBe})),kBe,ABe,I5,jBe=e((()=>{kBe={persona:`User persona document is empty. Use writeDocument to create an initial persona based on what you have learned about the user.`,soul:`
5993SOUL.md is empty. Use writeDocument to write the agent identity once you have settled on a name, creature type, vibe, and emoji.`},ABe=(e,t,n)=>t?{content:t,state:{content:t,id:n,type:e},success:!0}:{content:kBe[e],state:{content:null,id:n??null,type:e},success:!0},I5=e=>{let t=!e.success,n=e.error?.message||(t?typeof e.content==`string`?e.content:`Web onboarding tool call failed.`:void 0),r=e.error?.type||`WebOnboardingToolError`,i={...e.ignoredFields?{ignoredFields:e.ignoredFields}:{},...e.savedFields?{savedFields:e.savedFields}:{},...e.unchangedFields?{unchangedFields:e.unchangedFields}:{},...n?{error:{message:n,type:r}}:{},isError:t,success:e.success};return{content:e.content||n||`Web onboarding tool call completed.`,...n?{error:{body:e,message:n,type:r}}:{},state:i,success:e.success}}})),L5,R5,MBe,NBe,PBe=e((()=>{Nr(),qJ(),Mre(),jBe(),Ne(),Fre(),va(),Gr(),Er(),L5=async()=>{try{await Or.getState().refreshUserState()}catch(e){console.error(e)}},R5=new Nre({onPicked:e=>Pre(e),onShown:e=>jre(e)}),MBe=class extends ye{identifier=VJ;apiEnum=HJ;saveUserQuestion=async(e,t)=>{let n=await _a.saveUserQuestion(e);return await Promise.all([L5(),jr.getState().refreshBuiltinAgent(Pr.webOnboarding),jr.getState().refreshBuiltinAgent(Pr.inbox)]),I5(n)};finishOnboarding=async(e,t)=>{let n=await _a.finishOnboarding();return await L5(),I5(n)};readDocument=async e=>{let t=await _a.readOnboardingDocument(e.type);return ABe(e.type,t.content,t.id)};writeDocument=async(e,t)=>{let n=await _a.updateOnboardingDocument(e.type,e.content);return n.id?{content:`Wrote ${e.type} document (${n.id}).`,state:{id:n.id,type:e.type},success:!0}:{content:`Failed to write ${e.type} document.`,success:!1}};updateDocument=async(e,t)=>{try{let t=await _a.patchOnboardingDocument(e.type,e.hunks);return t.id?{content:`Updated ${e.type} document (${t.id}). Applied ${t.applied} hunk(s).`,state:{applied:t.applied,id:t.id,type:e.type},success:!0}:{content:`Failed to update ${e.type} document.`,success:!1}}catch(t){let n=t instanceof Error?t.message:String(t);return{content:n,error:{message:n,type:`MarkdownPatchError`},state:{type:e.type},success:!1}}};showAgentMarketplace=async(e,t)=>R5.showAgentMarketplace(e,{topicId:t.topicId});submitAgentPick=async(e,t)=>R5.submitAgentPick(e)},NBe=new MBe})),FBe,z5,B5,V5,H5,IBe,LBe,RBe,zBe,BBe,U5,VBe,HBe,UBe,W5,WBe,GBe=e((()=>{FBe=(e,t,n)=>e.find(e=>e.identifier===t)?.manifest.api.find(e=>e.name===n)?.work,z5=e=>e===`create`?`created`:`updated`,B5=e=>typeof e==`string`&&e.length>0?e:void 0,V5=e=>typeof e==`object`&&!!e,H5=(e,t)=>e?B5(e[t]):void 0,IBe=({args:e,result:t})=>{let n=V5(t.state)?t.state:void 0,r=V5(e)?e:void 0;return(Array.isArray(n?.results)?n.results:t.success?[{identifier:H5(n,`identifier`)??H5(r,`identifier`),success:!0,taskId:n?.taskId}]:[]).filter(V5).filter(e=>e.success===!0).map(e=>({taskId:B5(e.taskId),taskIdentifier:B5(e.identifier)})).filter(e=>!!(e.taskId||e.taskIdentifier))},LBe=({result:e})=>{if(!e.success)return;let t=V5(e.state)?e.state:void 0,n=H5(t,`agentDocumentId`),r=H5(t,`agentId`),i=H5(t,`documentId`);if(!(!i||!r))return{agentDocumentId:n,agentId:r,documentId:i}},RBe=({config:e,payload:t})=>{let n=IBe(t);if(n.length!==0)return e.action===`delete`?{action:`delete`,targets:n,type:`task`}:{action:e.action,changeType:z5(e.action),targets:n,type:`task`}},zBe=({apiName:e,config:t,payload:n})=>{let r=LBe(n);if(r)return t.action===`delete`?{action:`delete`,document:r,type:`document`}:{action:`register`,document:{...r,changeType:z5(t.action),toolName:e},type:`document`}},BBe=(e,t,n,r)=>{let i=FBe(e,t,n);if(i)return W5[i.resourceType].resolve({apiName:n,config:i,payload:r})},U5=(e,t,n,r)=>{n.forEach((n,i)=>{if(n.status!==`rejected`)return;let a=t[i];console.error(`[workRegistration] failed to persist task Work`,{action:e,error:n.reason,rootOperationId:r.rootOperationId,toolCallId:r.toolCallId,taskId:a?.taskId,taskIdentifier:a?.taskIdentifier})})},VBe=async(e,t,n)=>{let{agentId:r,cumulativeCost:i,cumulativeUsage:a,rootOperationId:o,messageId:s,threadId:c,toolCallId:l,toolIdentifier:u,toolName:d,topicId:f}=n,{action:p,changeType:m,targets:h}=e;if(p===`delete`){let e=h.filter(e=>e.taskId);U5(`delete`,e,await Promise.allSettled(e.map(e=>t.deleteTaskWork({taskId:e.taskId}))),{rootOperationId:o,toolCallId:l});return}m&&U5(p,h,await Promise.allSettled(h.map(e=>t.registerTask({agentId:r,changeType:m,cumulativeCost:i,cumulativeUsage:a,rootOperationId:o,messageId:s,taskId:e.taskId,taskIdentifier:e.taskIdentifier,threadId:c,toolCallId:l,toolIdentifier:u,toolName:d,topicId:f}))),{rootOperationId:o,toolCallId:l})},HBe=async(e,t,n)=>{if(e.action===`delete`){await t.deleteDocumentWork?.(e.document);return}let{agentId:r,cumulativeCost:i,cumulativeUsage:a,rootOperationId:o,messageId:s,threadId:c,toolCallId:l,toolIdentifier:u,topicId:d}=n;await t.registerDocument({...e.document,agentId:r??e.document.agentId,cumulativeCost:i,cumulativeUsage:a,rootOperationId:o,messageId:s,threadId:c,toolCallId:l,toolIdentifier:u,topicId:d})},UBe=async(e,t,n)=>{let{agentId:r,cumulativeCost:i,cumulativeUsage:a,rootOperationId:o,messageId:s,threadId:c,toolCallId:l,topicId:u}=n;await t.handleSkillToolResult({agentId:r,args:e.args,cumulativeCost:i,cumulativeUsage:a,data:e.data,provider:e.provider,rootOperationId:o,messageId:s,threadId:c,toolCallId:l,toolName:e.toolName,topicId:u})},W5={document:{dispatch:HBe,resolve:zBe},skill:{dispatch:UBe},task:{dispatch:VBe,resolve:RBe}},WBe=async(e,t,n)=>{let r=W5[e.type].dispatch;await r(e,t,n)}})),KBe,qBe=e((()=>{iY(),GBe(),P8(),KBe=(e,t,n,r,i)=>{let a=BBe(tY,e,t,{args:n,result:i});a&&M8(r?.toolCallId,a)}})),JBe=n({getApiNamesForIdentifier:()=>QBe,getExecutor:()=>XBe,getRegisteredIdentifiers:()=>ZBe,hasExecutor:()=>K5,invokeExecutor:()=>q5,registerBuiltinToolExecutors:()=>J5}
5993),G5,YBe,XBe,K5,ZBe,QBe,q5,$Be,J5,Y5=e((()=>{rNe(),cNe(),fNe(),aG(),vNe(),SNe(),QPe(),tFe(),oFe(),RFe(),UFe(),fIe(),$Ie(),nRe(),mRe(),wRe(),FRe(),BRe(),A5(),Zze(),nBe(),lBe(),mBe(),OBe(),PBe(),qBe(),G5=new Map,YBe=!1,XBe=e=>G5.get(e),K5=(e,t)=>G5.get(e)?.hasApi(t)??!1,ZBe=()=>Array.from(G5.keys()),QBe=e=>G5.get(e)?.getApiNames()??[],q5=async(e,t,n,r)=>{await J5();let i=G5.get(e);if(!i)return{error:{message:`Executor not found: ${e}`,type:`ExecutorNotFound`},success:!1};if(!i.hasApi(t))return{error:{message:`API not found: ${e}/${t}`,type:`ApiNotFound`},success:!1};let a=await i.invoke(t,n,r);return KBe(e,t,n,r,a),a},$Be=e=>{for(let t of e)G5.set(t.identifier,t)},J5=()=>{YBe||=($Be([QLe,$Le,eRe,tRe,nNe,CRe,sNe,iG,_Ne,xNe,ZPe,eFe,aFe,dNe,HFe,dIe,PRe,zRe,Vze,Xze,tBe,QIe,pRe,cBe,pBe,LFe,NBe,DBe]),!0)}})),eVe,X5,Z5,Q5,tVe,nVe,rVe,iVe=e((()=>{iY(),eVe=t(F()),s(),ere(),Qi(),oa(),va(),Dr(),Y5(),X5=kr(`builtinTool`),Z5=(0,eVe.default)(`lobe-store:builtin-tool`),Q5=(e,t)=>{let n=t?e?.uninstalledBuiltinToolsByWorkspace?.[t]:e?.uninstalledBuiltinTools;return n===void 0?rY:n},tVe=(e,t,n)=>t?{...e,uninstalledBuiltinToolsByWorkspace:{...e?.uninstalledBuiltinToolsByWorkspace,[t]:n}}:{...e,uninstalledBuiltinTools:n},nVe=(e,t,n)=>new rVe(e,t,n),rVe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}invokeBuiltinTool=async(e,t,n,r)=>{let i=`${e}/${t}`;Z5(`invokeBuiltinTool: %s`,i);let{toggleBuiltinToolLoading:a}=this.#e();a(i,!0);try{let o=await q5(e,t,n,r);return Z5(`invokeBuiltinTool result: %s -> %o`,i,o),a(i,!1),o}catch(e){return Z5(`invokeBuiltinTool error: %s -> %o`,i,e),a(i,!1),{error:{body:e,message:e instanceof Error?e.message:String(e),type:`BuiltinToolExecutorError`},success:!1}}};toggleBuiltinToolLoading=(e,t)=>
5993{this.#t({builtinToolLoading:{[e]:t}},!1,X5(`toggleBuiltinToolLoading`))};transformApiArgumentsToAiState=async(e,t)=>{let{builtinToolLoading:n,toggleBuiltinToolLoading:r}=this.#e();if(n[e])return;let{[e]:i}=this.#e();if(!i)return JSON.stringify(t);r(e,!0);try{let n=await i(t);return r(e,!1),JSON.stringify(n)}catch(t){throw r(e,!1),t}};#n=async(e,t)=>{let n=tre(),r=(await _a.getUserState())?.settings?.tool,i=Q5(r,n),a=i.includes(e);if(t?!a:a)return;let o=t?i.filter(t=>t!==e):[...i,e];this.#t({uninstalledBuiltinTools:o,uninstalledBuiltinToolsLoading:!1},!1,X5(t?`installBuiltinTool`:`uninstallBuiltinTool`)),await _a.updateUserSettings({tool:tVe(r,n,o)}),await this.refreshUninstalledBuiltinTools()};installBuiltinTool=async e=>{await this.#n(e,!0)};uninstallBuiltinTool=async e=>{await this.#n(e,!1)};refreshUninstalledBuiltinTools=async()=>{await Zi(aa.uninstalledBuiltins(tre()))};useFetchUninstalledBuiltinTools=e=>{let t=$ne();return m(e?aa.uninstalledBuiltins(t):null,async()=>Q5((await _a.getUserState())?.settings?.tool,t),{fallbackData:rY,onSuccess:e=>{this.#t({uninstalledBuiltinTools:e,uninstalledBuiltinToolsLoading:!1},!1,X5(`useFetchUninstalledBuiltinTools`))},revalidateOnFocus:!1})}}})),aVe=e((()=>{iVe(),pY()}));function oVe(e){try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch(e){return console.warn(`Failed to calculate object size:`,e),0}}var sVe,$5,e7=e((()=>{Wt(),R(),dre(),pa(),Sre(),$a(),Pe(),sVe=class{async invokeMcpToolCall(e,{signal:t,topicId:n}){await eo.safeInjectMPToken();let{pluginSelectors:r}=await Ge(async()=>{let{pluginSelectors:e}=await Promise.resolve().then(()=>(d3(),GMe));return{pluginSelectors:e}},void 0),{getToolStoreState:i}=await Ge(async()=>{let{getToolStoreState:e}=await Promise.resolve().then(()=>(d7(),EVe));return{getToolStoreState:e}},void 0),a=i(),{identifier:o,arguments:s,apiName:c}=e,{connectorSelectors:l}=await Ge(async()=>{let{connectorSelectors:e}=await import(`./connector-CTv0KPI6.js`).then(e=>(e.n(),e.t));return{connectorSelectors:e}},__vite__mapDeps([67,1,16,9,3])),u=l.connectorByIdentifier(o)(a);if(u&&u.isEnabled&&(u.mcpServerUrl||u.mcpConnectionType===`stdio`)){let{lambdaClient:e}=await Ge(async()=>{let{lambdaClient:e}=await import(`./client-DUGXaJW2.js`).then(e=>(e.n(),e.t));return{lambdaClient:e}},__vite__mapDeps([16,1,9,3]));return await e.connector.callTool.mutate({args:s,identifier:o,toolName:c},{signal:t})}let d=r.getInstalledPluginById(o)(a),f=r.getCustomPluginById(o)(a),p=d||f;if(!p)return;let m=p.customParams?.mcp,h=p.settings?Object.entries(p.settings).filter(([,e])=>e!=null):[],g=h.length>0?h.reduce((e,[t,n])=>(e[t]=n,e),{}):void 0,_={...m,name:o};m?.type===`http`&&(_.headers={...m.headers,...g}),m?.type===`stdio`&&(_.env={...m?.env,...g});let v=p?.customParams?.mcp?.type===`stdio`,y=p?.customParams?.mcp?.type===`cloud`,b=!!f,x={customPluginInfo:b?{avatar:p.manifest?.meta.avatar,description:p.manifest?.meta.description,name:p.manifest?.meta.title}:void 0,isCustomPlugin:b,sessionId:n,version:p.manifest?.version||`unknown`},S={args:s,env:m?.type===`stdio`?_.env:g??m?.env,meta:x,params:_,toolName:c},C=Date.now(),w=!1,T,E,D;try{if(y){let e=se(s)||{};D=await fa.market.callCloudMcpEndpoint.mutate({apiParams:e,identifier:o,meta:x,toolName:c})}else D=await fa.mcp.callTool.mutate(S,{signal:t});return w=!0,D}catch(e){let t=e;throw T=`CALL_FAILED`,E=t.message,e}finally{if(v){let e=Date.now()-C,t=oVe(se(s)||s),r=w&&D?oVe(D.state):0,i={callDurationMs:e,customPluginInfo:x.customPluginInfo,errorCode:T,errorMessage:E,identifier:o,isCustomPlugin:b,metadata:{appVersion:Ot,command:p.customParams?.mcp?.command,mcpType:p.customParams?.mcp?.type},methodName:c,methodType:`tool`,requestSizeBytes:t,responseSizeBytes:r,sessionId:n,success:w,version:x.version};eo.reportPluginCall(i).catch(e=>{console.warn(`Failed to report MCP tool call:`,e)})}}}async getStreamableMcpServerManifest(e,t){return fa.mcp.getStreamableMcpServerManifest.query(e,{signal:t})}async getStdioMcpServerManifest(e,t,n){let r=ma.serialize({...e,metadata:t}),i=await Da().mcp.getStdioMcpServerManifest(r);return ma.deserialize(i)}async checkInstallation(e,t){let n=ma.serialize({deploymentOptions:e.deploymentOptions}),r=await Da().mcp.validMcpServerInstallable(n);return ma.deserialize(r)}},$5=new sVe})),cVe,t7,n7=e((()=>{pa(),cVe=class{installPlugin=async e=>{await q.plugin.createOrInstallPlugin.mutate(e)};getInstalledPlugins=()=>q.plugin.getPlugins.query();uninstallPlugin=async e=>{await q.plugin.removePlugin.mutate({id:e})};createCustomPlugin=async e=>{await q.plugin.createPlugin.mutate({...e,type:`customPlugin`})};updatePlugin=async(e,t)=>{await q.plugin.updatePlugin.mutate({customParams:t.customParams,id:e,manifest:t.manifest,settings:t.settings})};updatePluginManifest=async(e,t)=>{await q.plugin.updatePlugin.mutate({id:e,manifest:t})};updatePluginSettings=async(e,t,n)=>{await q.plugin.updatePlugin.mutate({id:e,settings:t},{signal:n})}},t7=new cVe})),r7,lVe,uVe,dVe=e((()=>{Zt(),f(),Qr(),e7(),n7(),kc(),Dr(),gZ(),vY(),r7=kr(`customPlugin`),lVe=(e,t,n)=>new uVe(e,t,n),uVe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}installCustomPlugin=async e=>{await t7.createCustomPlugin(e),await this.#e().refreshPlugins(),this.#t({newCustomPlugin:gY}
5993,!1,r7(`saveToCustomPluginList`))};reinstallCustomPlugin=async e=>{let t=hZ.getCustomPluginById(e)(this.#e());if(!t)return;let{refreshPlugins:n,updateInstallLoadingState:r}=this.#e(),i=t.customParams?.mcp?.url;if(!(!t.customParams?.mcp||!i))try{r(e,!0);let a=await $5.getStreamableMcpServerManifest({auth:t.customParams.mcp.auth,headers:t.customParams.mcp.headers,identifier:t.identifier,metadata:{avatar:t.customParams.avatar,description:t.customParams.description},url:i});r(e,!1),await t7.updatePluginManifest(e,a),await n()}catch(t){r(e,!1),console.error(t);let n=t,i=hZ.getPluginMetaById(e)(this.#e()),a=Oc.getPluginTitle(i);tte.error({description:o(`error.${n.message}`,{error:n.cause,ns:`plugin`}),message:o(`error.reinstallError`,{name:a,ns:`plugin`})})}};uninstallCustomPlugin=async e=>{await t7.uninstallPlugin(e),await this.#e().refreshPlugins()};updateCustomPlugin=async(e,t)=>{let{reinstallCustomPlugin:n}=this.#e();await t7.updatePlugin(e,t),await n(e)};updateNewCustomPlugin=e=>{this.#t({newCustomPlugin:Lt({},this.#e().newCustomPlugin,e)},!1,r7(`updateNewDevPlugin`))}}})),fVe=e((()=>{dVe(),vY()}));function pVe(e){let t=e.indexOf(mVe);if(t===-1)return{originalMessage:e};let n=e.slice(0,t).trim();return{errorLog:e.slice(t+28).trim()||void 0,originalMessage:n||e}}var mVe,hVe=e((()=>{mVe=`--- STDIO Process Output ---`})),gVe,i7,a7,o7,s7,c7,_Ve,vVe,yVe,bVe=e((()=>{Wt(),gVe=t(F()),Zt(),it(),i7=Gre(),s(),hVe(),oa(),$a(),e7(),n7(),Zre(),d3(),ie(),ue(),Ze(),Dr(),a7=(0,gVe.default)(`lobe-mcp:store:action`),o7=kr(`mcpStore`),s7=e=>{if(!e)return!1;let t=Array.isArray(e.required)&&e.required.some(Boolean),n=!!e.properties&&Object.values(e.properties).some(e=>e&&e.required===!0);return t||n},c7=e=>{if(!e)return;let t=Object.entries(e).filter(([,e])=>e!=null);if(t.length!==0)return t.reduce((e,[t,n])=>(e[t]=typeof n==`string`?n:String(n),e),{})},_Ve=e=>{let{data:t,plugin:n}=e;a7(`Using cloud connection, building manifest from market data`);let r=t.tools,i=t.api,a=[];i?(a=i,a7(`[Cloud MCP] Using existing LobeChat API format`)):r&&Array.isArray(r)?(a=r.map(e=>({description:e.description||``,name:e.name,parameters:e.inputSchema||{}})),a7(`[Cloud MCP] Converted %d MCP tools to LobeChat API format`,a.length)):console.warn(`[Cloud MCP] No tools or api found in manifest data`);let o={api:a,author:t.author?.name||t.author||``,createAt:t.createdAt||new Date().toISOString(),homepage:t.homepage||``,identifier:n.identifier,manifest:t.manifestUrl||``,meta:{avatar:t.icon||n.icon,description:n.description||t.description,tags:t.tags||[],title:t.name||n.identifier},name:t.name||n.identifier,type:`mcp`,version:t.version};return a7(`[Cloud MCP] Final manifest built:`,{apiCount:o.api?.length,identifier:o.identifier,version:o.version}),o},vVe=(e,t,n)=>new yVe(e,t,n),yVe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}cancelInstallMCPPlugin=async e=>{let t=this.#e().mcpInstallAbortControllers[e];t&&(t.abort(),this.#t(tt(t=>{delete t.mcpInstallAbortControllers[e]}),!1,o7(`cancelInstallMCPPlugin/clearController`))),this.#e().updateMCPInstallProgress(e,void 0),this.#e().updateInstallLoadingState(e,void 0)};cancelMcpConnectionTest=e=>{let t=this.#e().mcpTestAbortControllers[e];t&&(t.abort(),this.#t(tt(t=>{t.mcpTestLoading[e]=!1,delete t.mcpTestAbortControllers[e],delete t.mcpTestErrors[e]}),!1,o7(`cancelMcpConnectionTest`)))};installMCPPlugin=async(e,t={})=>{let{resume:n=!1,config:r,skipDepsCheck:i}=t,a=c7(r),o=tZ.getPluginById(e)(this.#e());if(!o||!o.manifestUrl){let t=await eo.getMcpDetail({identifier:e});if(!t)return;o=t}if(!o)return;let{haveCloudEndpoint:s}=o||{},{updateInstallLoadingState:c,refreshPlugins:l,updateMCPInstallProgress:u}=this.#e(),d=new AbortController;this.#t(tt(t=>{t.mcpInstallAbortControllers[e]=d}),!1,o7(`installMCPPlugin/setController`));let f=Date.now(),p,m,h,g=`LobeHub Desktop/${Ot}`;try{if(d.signal.aborted)return;if(n){let t=this.#e().mcpInstallProgress[e];if(!t){console.error(`No config info found for resume`);return}p=t.manifest,h=t.connection?{...t.connection}:void 0,m=t.checkResult}else{if(u(e,{progress:15,step:B.FETCHING_MANIFEST}),c(e,!0),d.signal.aborted)return;p=await eo.getMCPPluginManifest(o.identifier,{install:!0});let t=Array.isArray(p.deploymentOptions)?p.deploymentOptions:[],n=t.find(e=>e?.connection?.url&&e?.connection?.type===`http`)||t.find(e=>e?.connection?.url&&!e?.connection?.type),r=t.find(e=>e?.connection?.type===`stdio`||!e?.connection?.type&&!e?.connection?.url),l=r&&s,f=!!n;
5993if(l){a7(`Using cloudEndPoint for stdio plugin: %s`,s),h={auth:r?.connection?.auth||{type:`none`},cloudEndPoint:s,headers:r?.connection?.headers,type:`cloud`},a7(`Using cloud connection: %O`,{cloudEndPoint:s,type:h.type});let t=r?.connection?.configSchema;if(s7(t)&&!a)return u(e,{configSchema:t,connection:h,manifest:p,needsConfig:!0,progress:50,step:B.CONFIGURATION_REQUIRED}),c(e,void 0),!1}else if(f&&n){a7(`HTTP MCP detected, skipping system dependency check`),h={auth:n.connection?.auth||{type:`none`},headers:n.connection?.headers,type:`http`,url:n.connection?.url},a7(`Using HTTP connection: %O`,{type:h.type,url:h.url});let t=n.connection?.configSchema;if(s7(t)&&!a)return u(e,{configSchema:t,connection:h,manifest:p,needsConfig:!0,progress:50,step:B.CONFIGURATION_REQUIRED}),c(e,void 0),!1}else{if(u(e,{progress:30,step:B.CHECKING_INSTALLATION}),d.signal.aborted)return;if(m=await $5.checkInstallation(p,d.signal),!m.success){u(e,void 0);return}if(!i&&!m.allDependenciesMet)return u(e,{connection:m.connection,manifest:p,progress:40,step:B.DEPENDENCIES_REQUIRED,systemDependencies:m.systemDependencies}),c(e,void 0),!1;if(m.needsConfig)return u(e,{checkResult:m,configSchema:m.configSchema,connection:m.connection,manifest:p,needsConfig:!0,progress:50,step:B.CONFIGURATION_REQUIRED}),c(e,void 0),!1;h=m.connection}}let t,r,_;if(h?.type===`http`){let e=c7(h.headers);(e||a)&&(t={...e,...a})}if(h?.type===`stdio`){let e=c7(h.env);(e||a)&&(r={...e,...a})}if(h?.type===`cloud`){let e=c7(h.headers);(e||a)&&(_={...e,...a})}if(c(e,!0),u(e,{progress:70,step:B.GETTING_SERVER_MANIFEST}),d.signal.aborted)return;let v;if(h?.type===`stdio`&&(v=await $5.getStdioMcpServerManifest({args:h.args,command:h.command,env:r,name:e},{avatar:o.icon,description:o.description,name:p.name},d.signal)),h?.type===`http`&&(v=await $5.getStreamableMcpServerManifest({auth:h.auth,headers:t,identifier:e,metadata:{avatar:o.icon,description:o.description},url:h.url},d.signal)),h?.type===`cloud`&&(v=_Ve({data:p,plugin:o})),v){let e=p?.version,t=v.version;e&&t?(0,i7.valid)(e)&&(0,i7.valid)(t)?v.version=(0,i7.gt)(e,t)?e:t:v.version=e:v.version=e||t}if(d.signal.aborted)return;if(!v){u(e,void 0);return}if(u(e,{progress:90,step:B.INSTALLING_PLUGIN}),d.signal.aborted)return;let y={...h};if(y.type===`http`&&t&&(y.headers=t),y.type===`stdio`&&r&&(y.env=r),y.type===`cloud`&&_&&(y.headers=_),await t7.installPlugin({customParams:{mcp:y},identifier:o.identifier,manifest:v,settings:a,type:`plugin`}),d.signal.aborted)return;await l(),u(e,{progress:100,step:B.COMPLETED});let b=Date.now()-f;return eo.reportMcpEvent({event:`install`,identifier:o.identifier,source:`self`}),eo.reportMcpInstallResult({identifier:o.identifier,installDurationMs:b,installParams:h,manifest:{prompts:v.prompts,resources:v.resources,tools:v.tools},platform:m?.platform||process.platform,success:!0,userAgent:g,version:v.version||p.version}),await w(1e3),u(e,void 0),c(e,void 0),this.#t(tt(t=>{delete t.mcpInstallAbortControllers[e]}),!1,o7(`installMCPPlugin/clearController`)),!0}catch(t){if(d.signal.aborted){console.info(`MCP plugin installation cancelled for:`,e);return}let n=t;console.error(`MCP plugin installation failed:`,n);let r=Date.now()-f,i;if(n.data&&`errorData`in n.data){let e=n.data.errorData;i={message:e.message,metadata:e.metadata,type:e.type}}else{let{originalMessage:e,errorLog:t}=pVe(n instanceof Error?n.message:String(n));i={message:e,metadata:{errorLog:t,params:h?{args:h.args,command:h.command,type:h.type}:void 0,step:`installation_error`,timestamp:Date.now()},type:`UNKNOWN_ERROR`}}u(e,{errorInfo:i,progress:0,step:B.ERROR}),eo.reportMcpInstallResult({errorCode:i.type,errorMessage:i.message,identifier:o.identifier,installDurationMs:r,installParams:h,metadata:i.metadata,platform:m?.platform||process.platform,success:!1,userAgent:g,version:p?.version}),c(e,void 0),this.#t(tt(t=>{delete t.mcpInstallAbortControllers[e]}),!1,o7(`installMCPPlugin/clearController`))}};loadMoreMCPPlugins=()=>{let{mcpPluginItems:e,totalCount:t,currentPage:n}=this.#e();e.length<(t||0)&&this.#t(tt(e=>{e.currentPage=n+1}),!1,o7(`loadMoreMCPPlugins`))};resetMCPPluginList=e=>{this.#t(tt(t=>{t.mcpPluginItems=[],t.currentPage=1,t.mcpSearchKeywords=e,t.isMcpListInit=!1}),!1,o7(`resetMCPPluginList`))};testMcpConnection=async e=>{let{identifier:t,connection:n,metadata:r}=e,i=new AbortController;this.#t(tt(e=>{e.mcpTestAbortControllers[t]=i,e.mcpTestLoading[t]=!0,e.mcpTestErrors[t]=``}),!1,o7(`testMcpConnection/start`));try{let e;if(n.type===`http`){if(!n.url)throw Error(`URL is required for HTTP connection`);e=await $5.getStreamableMcpServerManifest({auth:n.auth,headers:n.headers,identifier:t,metadata:r,url:n.url},i.signal)}else if(n.type===`stdio`){if(!n.command)throw Error(`Command is required for STDIO connection`);
5993e=await $5.getStdioMcpServerManifest({args:n.args,command:n.command,env:n.env,name:t},r,i.signal)}else throw Error(`Invalid MCP connection type`);return i.signal.aborted?{error:`Test cancelled`,success:!1}:(this.#t(tt(e=>{e.mcpTestLoading[t]=!1,delete e.mcpTestAbortControllers[t],delete e.mcpTestErrors[t]}),!1,o7(`testMcpConnection/success`)),eo.reportMcpEvent({event:`activate`,identifier:t,source:`self`}),{manifest:e,success:!0})}catch(e){if(i.signal.aborted)return{error:`Test cancelled`,success:!1};let{originalMessage:n,errorLog:r}=pVe(e instanceof Error?e.message:String(e));return this.#t(tt(e=>{e.mcpTestLoading[t]=!1,e.mcpTestErrors[t]=n,delete e.mcpTestAbortControllers[t]}),!1,o7(`testMcpConnection/error`)),{error:n,errorLog:r,success:!1}}};uninstallMCPPlugin=async e=>{await t7.uninstallPlugin(e),await this.#e().refreshPlugins(),eo.reportMcpEvent({event:`uninstall`,identifier:e,source:`self`})};updateMCPInstallProgress=(e,t)=>{this.#t(tt(n=>{n.mcpInstallProgress[e]=t}),!1,o7(`updateMCPInstallProgress/${t?.step||`clear`}`))};useFetchMCPPluginList=e=>{let t=Qre.getCurrentLanguage(),n={...e,connectionType:M.http},r=n.page??1;return m(aa.mcpPluginList(t,{connectionType:n.connectionType,page:n.page,pageSize:n.pageSize,q:n.q}),()=>eo.getMCPPluginList(n),{onSuccess:e=>{this.#t(tt(t=>{t.searchLoading=!1,t.isMcpListInit||(t.activeMCPIdentifier=e.items?.[0]?.identifier,t.isMcpListInit=!0,t.categories=e.categories,t.totalCount=e.totalCount,t.totalPages=e.totalPages),r===1?t.mcpPluginItems=en(e.items,`identifier`):t.mcpPluginItems=en([...t.mcpPluginItems,...e.items],`identifier`)}),!1,o7(`useFetchMCPPluginList/onSuccess`))},revalidateOnFocus:!1})}}})),xVe=e((()=>{bVe(),SY()})),SVe,CVe,wVe=e((()=>{$t(),Qi(),oa(),n7(),Te(),gZ(),Pe(),SVe=(e,t,n)=>new CVe(e,t,n),CVe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}checkPluginsIsInstalled=async e=>{};refreshPlugins=async()=>{let e=await t7.getInstalledPlugins();this.#t({installedPlugins:e},!1,`refreshPlugins`)};updateInstallLoadingState=(e,t)=>{this.#t({pluginInstallLoading:{...this.#e().pluginInstallLoading,[e]:t}},!1,`updateInstallLoadingState`)};updateInstallMcpPlugin=async(e,t)=>{let n=hZ.getInstalledPluginById(e)(this.#e());n&&(await t7.updatePlugin(e,{customParams:{mcp:Ce(n.customParams?.mcp,t)}}),await this.#e().refreshPlugins())};updatePluginSettings=async(e,t,n={})=>{let{override:r}=n,i=this.#e().updatePluginSettingsSignal;i&&i.abort(nn);let a=new AbortController,o=hZ.getPluginSettingsById(e)(this.#e()),s=r?t:Ce(o,t);this.#t({updatePluginSettingsSignal:a},!1,`create new Signal`),await t7.updatePluginSettings(e,s,a.signal),await this.#e().refreshPlugins()};useFetchInstalledPlugins=e=>Xi(e?aa.installedPlugins():null,()=>t7.getInstalledPlugins(),{onSuccess:e=>{this.#t({installedPlugins:e,loadingInstallPlugins:!1},!1,`useFetchInstalledPlugins/onSuccess`)}});useCheckPluginsIsInstalled=(e,t)=>Xi(e?t:null,this.#e().checkPluginsIsInstalled);validatePluginSettings=async e=>{let t=hZ.getToolManifestById(e)(this.#e());if(!t||!t.settings)return;let n=hZ.getPluginSettingsById(e)(this.#e()),{Validator:r}=await Ge(async()=>{let{Validator:e}=await import(`./esm-CGkVx4zY.js`);return{Validator:e}},__vite__mapDeps([68,1])),i=new r(t.settings).validate(n);return i.valid?{errors:[],valid:!0}:{errors:i.errors,valid:!1}}}})),TVe=e((()=>{wVe(),wY()})),EVe=n({getToolStoreState:()=>u7,useToolStore:()=>l7}),DVe,OVe,kVe,l7,u7,d7=e((()=>{y(),d(),gt(),at(),ft(),ct(),Qwe(),eTe(),nTe(),aVe(),lX(),Ha(),fVe(),o3(),xVe(),TVe(),DVe=class extends pt{resetActionName=`resetToolStore`},OVe=(...e)=>({...TY,...rt([Rre(...e),SVe(...e),lVe(...e),nVe(...e),vVe(...e),aX(...e),IMe(...e),RY(...e),OY(...e),new DVe(...e)])}),kVe=lt(`tools`),l7=b()(kVe(OVe),l),mt(`tool`,l7),u7=()=>l7.getState()})),f7=e((()=>{kc(),d7()})),AVe,jVe,MVe,NVe=e((()=>{fie(),We(),Ne(),AVe=new Set([be.Unauthorized]),jVe=e=>{if(e.toString().includes(`Invalid`))return 401;switch(e){case be.SubscriptionPlanLimit:case be.FreePlanLimit:case be.InsufficientBudgetForModel:case be.WorkspaceFrozenByAdmin:case be.WorkspaceFrozenByRiskControl:case be.WorkspaceSubscriptionInactive:return 403;
5993case ze.InvalidProviderAPIKey:case ze.NoOpenAIAPIKey:return 401;case ze.ExceededContextWindow:case ze.ExceededToolLimit:case be.SubscriptionKeyMismatch:case be.SystemTimeNotMatchError:case be.LobeHubModelDeprecated:return 400;case ze.LocationNotSupportError:return 403;case ze.ModelNotFound:return 404;case ze.AccountDeactivated:return 403;case ze.InsufficientQuota:case ze.QuotaLimitReached:return 429;case ze.AgentRuntimeError:return 470;case ze.ProviderBizError:case ze.ProviderContentPolicyViolation:return 471;case ze.OllamaServiceUnavailable:case be.OllamaServiceUnavailable:case ze.OllamaBizError:return 472}return e},MVe=(e,t)=>{let n=jVe(e),r={body:t,errorType:e};(typeof n!=`number`||n<200||n>599)&&console.error(`current StatusCode: \`${n}\` .`,"Please go to `./src/app/api/errorResponse.ts` to defined the statusCode.");let i={"Content-Type":`application/json`};return AVe.has(e)&&(i[pie]=`true`),new Response(JSON.stringify(r),{headers:i,status:n})}})),PVe,FVe,IVe,LVe=e((()=>{Wt(),PVe=Be(),FVe=e=>{let t=new TextEncoder().encode(JSON.stringify(e));return PVe.Buffer.from(t).toString(`base64`)},IVe=e=>({[Ft]:FVe(e)})})),RVe,p7,zVe,BVe,m7,VVe,HVe,UVe=e((()=>{Nr(),Tq(),ti(),Ne(),RVe=t(F()),it(),Gr(),qr(),s6(),N3(),Er(),Ta(),He(),p7=(0,RVe.default)(`mecha:agentConfigResolver`),zVe=new Set(Object.values(Pr)),BVe=e=>zVe.has(e),m7=(e,t)=>e?.params?tt(e,e=>{e.params.max_tokens=t.enableMaxTokens?e.params.max_tokens:void 0,e.params.reasoning_effort=t.enableReasoningEffort?e.params.reasoning_effort:void 0}):e,VVe=e=>{let{agentId:t,model:n,documentContent:r,plugins:i,targetAgentConfig:a,isSubAgent:o,disableTools:s}=e;p7(`resolveAgentConfig called with agentId: %s, scope: %s, isSubAgent: %s, disableTools: %s`,t,e.scope,o,s);let c=t=>{if(s)return p7(`disableTools is true, returning empty plugins`),[];let n=t;return e.scope!==`page`&&(n=n.filter(e=>e!==bq)),n},l=Xr(),u=Rr.getAgentConfigById(t)(l),d=Yr.getAgentById(t)(l),f=d?.workspaceId&&d.visibility!==`private`?Or.getState().workspaceUserPreference.agentModelOverrides?.[t]:void 0,p={...u,...de({...u,visibility:d?.visibility},f)},m=Hr.getChatConfigById(t)(l),h=Je(p?.plugins),g;if(e.groupId&&e.scope===`group`){let n=o6(),r=j3.groupById(e.groupId)(n);p7(`checking supervisor FIRST (scope=group): groupId=%s, group=%O, agentId=%s`,e.groupId,r?{groupId:r.id,supervisorAgentId:r.supervisorAgentId,title:r.title}:null,t),r?.supervisorAgentId===t&&(g=Pr.groupSupervisor,p7(`agentId %s identified as group supervisor for group %s, assigned slug: %s`,t,e.groupId,g))}if(!g){let e=Rr.getAgentSlugById(t)(l)??void 0;p7(`slug from agentStore: %s (agentId: %s)`,e,t),e&&BVe(e)?g=e:e&&p7(`slug %s is not a valid builtin agent slug, treating as regular agent`,e)}if(!g){p7(`agentId %s is not a builtin agent (no valid builtin slug found)`,t);let n=i&&i.length>0?i:h,r=Ca.currentResponseLanguage(Or.getState()),a=r?`Preferred reply language: ${r}. Use this language unless the user explicitly asks to switch.`:``,o=a?p.systemRole?`${p.systemRole}\n\n${a}`:a:p.systemRole,s=m7({...p,systemRole:o},m),l=m;if(e.scope===`page`){let e=n.includes(`lobe-page-agent`)?n:[bq,...n],t=ri(Pr.pageAgent,{})?.systemRole||``,r=t?o?`${o}\n\n${t}`:t:o||``;return s={...s,systemRole:r},l={...m,enableHistoryCount:!1},{agentConfig:s,chatConfig:l,isBuiltinAgent:!1,plugins:c(e)}}if(e.scope===`task`){let e=n.includes(`lobe-task`)?n:[wr,...n],t=ri(Pr.taskAgent,{})?.systemRole||``,r=t?o?`${o}\n\n${t}`:t:o||``;return s={...s,systemRole:r},{agentConfig:s,chatConfig:l,isBuiltinAgent:!1,plugins:c(e)}}return{agentConfig:s,chatConfig:l,isBuiltinAgent:!1,plugins:c(n)}}let _;if(g===Pr.groupSupervisor&&e.groupId){p7(`building groupSupervisorContext for agentId: %s, groupId: %s`,t,e.groupId);let n=o6(),r=j3.groupById(e.groupId)(n);if(p7(`groupById result for %s: %o`,e.groupId,r?{agentsCount:r.agents?.length,groupId:r.id,supervisorAgentId:r.supervisorAgentId,title:r.title}:null),r){let e=M3.getGroupMembers(r.id)(n);p7(`groupMembers for groupId %s: %o`,r.id,e.map(e=>({id:e.id,isSupervisor:e.isSupervisor,title:e.title}))),_={availableAgents:e.map(e=>({id:e.id,title:e.title})),groupId:r.id,groupTitle:r.title||`Group Chat`,systemPrompt:p.systemRole},p7(`groupSupervisorContext built: %o`,{availableAgentsCount:_.availableAgents.length,groupId:_.groupId,groupTitle:_.groupTitle,hasSystemPrompt:!!_.systemPrompt})}else p7(`WARNING: group not found for groupId: %s`,e.groupId)}let v=ri(g,{documentContent:r,groupSupervisorContext:_,isDev:!1,model:n,plugins:i||h,targetAgentConfig:a,userLocale:Ca.currentResponseLanguage(Or.getState())}),y=v?.systemRole??p.systemRole,b=v?.plugins&&v.plugins.length>0?v.plugins:h,x={...m,...v?.chatConfig},S=v?.agencyConfig?{...p.agencyConfig,...v.agencyConfig}:p.agencyConfig;if(e.scope===`page`&&g!==Pr.pageAgent){b.includes(`lobe-page-agent`)||(b=[bq,...b]);let e=ri(Pr.pageAgent,{})?.systemRole||``;e&&(y=y?`${y}\n\n${e}`:e),x={...x,enableHistoryCount:!1}}if(e.scope===`task`&&g!==Pr.taskAgent){b.includes(`lobe-task`)||(b=[wr,...b]);let e=ri(Pr.taskAgent,{})?.systemRole||``;e&&(y=y?`${y}\n\n${e}`:e)}let C=m7({...p,...S?{agencyConfig:S}:{},systemRole:y},x);return p7(`resolveAgentConfig completed for agentId: %s, result: %o`,t,{isBuiltinAgent:!0,pluginsCount:b.length,slug:g}),{agentConfig:C,chatConfig:x,isBuiltinAgent:!0,plugins:c(b),slug:g}},HVe=e=>{let t=Xr();return e||t.activeAgentId||``}})),WVe,GVe=e((()=>{Wt(),Gr(),qr(),Oi(),Vr(),WVe=(e,t)=>{}})),KVe,qVe=e((()=>{Wt(),R(),Gr(),qr(),bc(),Er(),Ta(),GVe(),hr(),KVe={date:()=>new Date().toLocaleDateString(),datetime:()=>
5993new Date().toLocaleString(),day:()=>new Date().getDate().toString().padStart(2,`0`),hour:()=>new Date().getHours().toString().padStart(2,`0`),iso:()=>new Date().toISOString(),locale:()=>Intl.DateTimeFormat().resolvedOptions().locale,minute:()=>new Date().getMinutes().toString().padStart(2,`0`),month:()=>(new Date().getMonth()+1).toString().padStart(2,`0`),second:()=>new Date().getSeconds().toString().padStart(2,`0`),time:()=>new Date().toLocaleTimeString(),timestamp:()=>Date.now().toString(),timezone:()=>Intl.DateTimeFormat().resolvedOptions().timeZone,weekday:()=>new Date().toLocaleDateString(`en-US`,{weekday:`long`}),year:()=>new Date().getFullYear().toString(),email:()=>ba.email(Or.getState())??``,nickname:()=>ba.nickName(Or.getState())??``,username:()=>ba.displayUserName(Or.getState())??ba.fullName(Or.getState())??``,random:()=>Math.floor(Math.random()*1e6+1).toString(),random_bool:()=>Math.random()>.5?`true`:`false`,random_float:()=>(Math.random()*100).toFixed(2),random_hex:()=>Math.floor(Math.random()*16777215).toString(16).padStart(6,`0`),random_int:()=>Math.floor(Math.random()*100+1).toString(),random_string:()=>Math.random().toString(36).slice(2,15),random_digit:()=>Math.floor(Math.random()*10).toString(),uuid:()=>z(),uuid_short:()=>z().split(`-`)[0],language:()=>typeof navigator<`u`?navigator.language:``,platform:()=>typeof navigator<`u`?navigator.platform:``,user_agent:()=>typeof navigator<`u`?navigator.userAgent:``,model:()=>Rr.currentAgentModel(jr.getState()),provider:()=>Rr.currentAgentModelProvider(jr.getState()),homePath:()=>pr.getContext().homePath??``,desktopPath:()=>pr.getContext().desktopPath??``,documentsPath:()=>pr.getContext().documentsPath??``,downloadsPath:()=>pr.getContext().downloadsPath??``,musicPath:()=>pr.getContext().musicPath??``,picturesPath:()=>pr.getContext().picturesPath??``,videosPath:()=>pr.getContext().videosPath??``,userDataPath:()=>pr.getContext().userDataPath??``,workingDirectory:()=>``}})),h7,JVe,YVe,XVe,ZVe=e((()=>{bc(),po(),Sie(),h7={activities:[],contexts:[],experiences:[],preferences:[]},JVe=()=>{let e=fo().persona;if(!(!e?.content&&!e?.summary))return{narrative:e.content,tagline:e.summary}},YVe=e=>{let t=e?.topicId??Q9().activeTopicId;if(!t)return h7;let n=fo();return wie.topicMemories(t)(n)??h7},XVe=(e,t)=>({activities:e.activities,contexts:e.contexts,experiences:e.experiences,persona:t,preferences:e.preferences})})),QVe,$Ve,eHe,tHe,nHe=e((()=>{Li(),Mi(),QVe=t(F()),eX(),IY(),f7(),$Ve=(0,QVe.default)(`context-engine:resolveClientSkills`),eHe=e=>{if(e.content)return e.resources&&Object.keys(e.resources).length>0?e.content+`
5994
5995`+Bi(e.name,e.resources):e.content},tHe=async(e,t)=>{let n=u7(),r=new Set(e??[]),i=new Set(t??[]),a=(n.builtinSkills||[]).filter(e=>!i.has(e.identifier)).map(e=>({activated:r.has(e.identifier)&&!!e.content,content:e.content,description:e.description,identifier:e.identifier,name:e.name})),o=await Promise.all((n.agentSkills||[]).filter(e=>!i.has(e.identifier)).map(async e=>{let t={description:e.description??``,identifier:e.identifier,name:e.name};if(!r.has(e.identifier)||e.zipFileHash)return t;
5995try{let r=n.agentSkillDetailMap?.[e.id]??await FY.getById(e.id),i=r&&eHe(r);return i?{...t,activated:!0,content:i}:t}catch(n){return $Ve(`Failed to load content for pinned skill %s: %O`,e.identifier,n),t}}));return new Nne({enableChecker:e=>XY(e.identifier),skills:[...a,...o]}).generate(e??[])}})),rHe,g7,_7,iHe=e((()=>{mi(),ei(),ic(),NG(),XG(),Kr(),UK(),Tq(),qJ(),Wt(),Li(),Mi(),Ne(),rHe=t(F()),vc(),qVe(),pa(),dt(),d6(),Gr(),qr(),s6(),N3(),Ba(),bc(),Oi(),f7(),d3(),lX(),ao(),ZVe(),nHe(),Pe(),g7=(0,rHe.default)(`context-engine:contextEngineering`),_7=async({messages:e=[],manifests:t,tools:n,model:r,provider:i,systemRole:a,inputTemplate:o,enableUserMemories:s,enableHistoryCount:c,historyCount:l,historySummary:u,agentBuilderContext:d,agentDocuments:f,agentId:p,disabledPluginIds:m,enableAgentMode:h,groupId:g,initialContext:_,plugins:v,stepContext:y,topicId:b,memoryContext:x})=>{g7(`tools: %o`,n);let S=n?.includes(`lobe-agent-builder`)??!1,C=n?.includes(`lobe-group-agent-builder`)??!1,w=n?.includes(`lobe-agent-management`)??!1;g7(`isAgentBuilderEnabled: %s`,S),g7(`isGroupAgentBuilderEnabled: %s`,C),g7(`isAgentManagementEnabled: %s`,w);let T;if(g){let e=o6(),t=M3.getGroupById(g)(e);if(t?.agents&&t.agents.length>0){let e={},n=[],r,i;for(let a of t.agents){let t=a.isSupervisor?`supervisor`:`participant`,o=a.title||`Untitled Agent`;e[a.id]={name:o,role:t},n.push({id:a.id,name:o,role:t}),p&&a.id===p&&(r=o,i=t)}T={agentMap:e,currentAgentId:p,currentAgentName:r,currentAgentRole:i,groupTitle:t.title||void 0,members:n,systemPrompt:t.content||void 0},g7(`agentGroup built: %o`,T)}}let E=Xr(),D=h??$r.currentChatConfig(E).enableAgentMode,O;if(C){let e=Q9().activeGroupId;if(e){let t=o6(),n=M3.getGroupById(e)(t);if(n){let t,r=[];if(n.supervisorAgentId){let e=Rr.getAgentConfigById(n.supervisorAgentId)(E);r=Je(e.plugins),t={model:e.model,plugins:r,provider:e.provider}}let i=u7(),a=[],o=PX.metaList(i),s=new Set(Vt.map(e=>e.identifier));for(let e of o)s.has(e.identifier)||a.push({description:e.meta?.description,enabled:r.includes(e.identifier),identifier:e.identifier,installed:!0,name:e.meta?.title||e.identifier,type:`builtin`});if(typeof window<`u`&&window.global_serverConfigStore?.getState()?.serverConfig?.enableComposio){let e=sX.getServers(i);for(let t of Vt){let n=e.find(e=>e.identifier===t.identifier);a.push({description:`LobeHub Mcp Server: ${t.label}`,enabled:r.includes(t.identifier),identifier:t.identifier,installed:!!n,name:t.label,type:`composio`})}}if(typeof window<`u`&&window.global_serverConfigStore?.getState()?.serverConfig?.enableLobehubSkill){let e=VX.getServers(i);for(let t of tn){let n=e.find(e=>e.identifier===t.id);a.push({description:`LobeHub Skill Provider: ${t.label}`,enabled:r.includes(t.id),identifier:t.id,installed:!!n,name:t.label,type:`lobehub-skill`})}}O={config:{openingMessage:n.config?.openingMessage||void 0,openingQuestions:n.config?.openingQuestions,systemPrompt:n.config?.systemPrompt||void 0},groupId:e,groupTitle:n.title||void 0,members:n.agents?.map(e=>({description:e.description||void 0,id:e.id,isSupervisor:e.isSupervisor,title:e.title||`Untitled Agent`})),officialTools:a,supervisorConfig:t},g7(`groupAgentBuilderContext built from activeGroupId: %o`,O)}}}let k=Rr.currentAgentFiles(E),A=Rr.currentAgentKnowledgeBases(E),j=k.filter(e=>e.enabled&&e.content).map(e=>({content:e.content,fileId:e.id,filename:e.name})),M=A.filter(e=>e.enabled).map(e=>({description:e.description,id:e.id,name:e.name})),N;s&&(N=XVe(YVe(),JVe()));let P=n?.includes(`lobe-agent`)??!1,F;if(P&&b)try{let e=await u6.listDocuments({topicId:b,type:sn});if(e.data.length>0){let t=e.data[0],n={completed:!1,context:t.content??void 0,createdAt:t.createdAt.toISOString(),description:t.description||``,goal:t.title||``,id:t.id,updatedAt:t.updatedAt.toISOString()},r=t.metadata?.todos;F={enabled:!0,plan:n,todos:r},g7(`Plan/Todo context resolved: plan=%s, todos=%o`,n.goal,r?.items?.length??0)}}catch(e){g7(`Failed to resolve plan/todo context:`,e)}let I=n?.includes(`lobe-creds`)??!1,L;if(I)try{L=((await q.market.creds.list.query())?.data??[]).map(e=>({description:e.description,key:e.key,name:e.name,type:e.type})),g7(`Creds context resolved: count=%d`,L?.length??0)}catch(e){g7(`Failed to resolve creds context:`,e)}let ee=``,R=typeof window<`u`&&window.global_serverConfigStore?.getState()?.serverConfig?.enableComposio;if(I&&R)try{let e=u7(),t=sX.getServers(e),n=new Set(m??[]),r=HG(t.filter(e=>e.status===tX.ACTIVE),n).map(e=>({identifier:e.identifier,name:e.label})),i=UG(Vt,new Set(r.map(e=>e.identifier)),n);ee=WG(r,i),g7(`Composio services context resolved: connected=%d, available=%d`,r.length,i.length)}catch(e){g7(`Failed to resolve Composio services context:`,e)}let te=s&&N?{enabled:s,memories:N}:void 0,z=new Set(n||[]),ne=z.has(Di),B;if(ne){let e=u7(),t=l3.availableToolsForDiscovery(e).filter(e=>!z.has(e.identifier));t.length>0&&(B={availableTools:t},g7(`Tool discovery config built, available tools count: %d`,t.length))}let V,H=$r.skillActivateMode(E)!==`manual`;if(H||w)try{let e=E.availableAgents??await ht.queryAgents({limit:12}),t=p?e.filter(e=>e.id!==p):e,n=t.length>10,r=t.slice(0,10).map(e=>({description:e.description??void 0,id:e.id,title:e.title??`Untitled`}));V={availableAgents:r,availableAgentsHasMore:n,...p&&{currentAgent:{id:p,title:Rr.getAgentMetaById(p)(E)?.title??void 0}}},g7(`availableAgents fetched: %d agents (hasMore=%s)`,r.length,n)}catch(e){g7(`Failed to fetch availableAgents: %O`,e)}if(w){let e=(za().enabledChatModelList||[]).slice(0,5).map(e=>({id:e.id,models:e.children.map(e=>({abilities:e.abilities,description:e.description,id:e.id,name:e.displayName||e.id})),name:e.name})),t=u7(),n=[],r=PX.allMetaList(t),i=new Set(Vt.map(e=>e.identifier)),a=new Set([`lobe-agent-management`,`lobe-agent-builder`,`lobe-group-agent-builder`,`lobe-page-agent`]);for(let e of r)i.has(e.identifier)||a.has(e.identifier)||n.push({description:e.meta?.description,identifier:e.identifier,name:e.meta?.title||e.identifier,type:`builtin`});if(typeof window<`u`&&window.global_serverConfigStore?.getState()?.serverConfig?.enableComposio)for(let e of Vt)n.push({description:e.description,identifier:e.identifier,name:e.label,type:`composio`});if(typeof window<`u`&&window.global_serverConfigStore?.getState()?.serverConfig?.enableLobehubSkill)for(let e of tn)n.push({description:e.description,identifier:e.id,name:e.label,type:`lobehub-skill`});V={...V,availablePlugins:n,availableProviders:e}
5995,g7(`agentManagementContext built: %d providers, %d plugins, %d agents`,V.availableProviders?.length??0,V.availablePlugins?.length??0,V.availableAgents?.length??0)}_?.mentionedAgents&&_.mentionedAgents.length>0&&(V={...V,mentionedAgents:_.mentionedAgents},g7(`mentionedAgents injected: %d agents`,_.mentionedAgents.length));let re=await lne(e,async e=>vi.getTopicById(e)(Q9())??null,async e=>{let{messageService:t}=await Ge(async()=>{let{messageService:e}=await import(`./message-D0HRzm1P.js`).then(e=>(e.t(),e.r));return{messageService:e}},__vite__mapDeps([4,1,5,6]));return(await t.getMessages({agentId:p,groupId:g,topicId:e})).map(e=>({content:typeof e.content==`string`?e.content:``,role:e.role}))})??[],ie;if(n?.includes(`lobe-web-onboarding`))try{let{userService:e}=await Ge(async()=>{let{userService:e}=await import(`./user-DQWC3jQX.js`).then(e=>(e.t(),e.r));return{userService:e}},__vite__mapDeps([28,1,5]));ie=await e.getOnboardingAgentContext(),g7(`Built onboarding context`)}catch(e){g7(`Failed to build onboarding context: %O`,e)}let ae;if(v){let e=await tHe(v,m);if(H)ae=e.skills;else{let t=new Set(v);ae=e.skills.filter(e=>t.has(e.identifier))}}let oe=new mne({enableHistoryCount:c,formatHistorySummary:_ne,historyCount:l,historySummary:u,inputTemplate:o,systemRole:a,capabilities:{isCanUseAudio:gie,isCanUseFC:_c,isCanUseVideo:co,isCanUseVision:oo},fileContext:{enabled:!0,includeFileUrl:!0},knowledge:{fileContents:j,knowledgeBases:M},agentDocuments:f,messages:e,model:r,modelDisplayName:vie(r,i),modelKnowledgeCutoff:xie(r,i),provider:i,initialContext:_,stepContext:y,selectedSkills:_?.selectedSkills,selectedTools:_?.selectedTools,enableAgentMode:D,skillsConfig:{enabledSkills:ae},toolDiscoveryConfig:B,toolsConfig:{disabledToolIdentifiers:n?.includes(`lobe-page-agent`)?void 0:[bq],manifests:t,tools:n},userMemory:te,variableGenerators:{...KVe,CREDS_LIST:()=>L?BG(L):``,COMPOSIO_SERVICES_LIST:()=>ee,session_date:()=>new Intl.DateTimeFormat(`en-US`,{day:`numeric`,month:`long`,weekday:`long`,year:`numeric`}).format(new Date),sandbox_enabled:()=>String(n?.includes(`lobe-cloud-sandbox`)??!1),sandbox_uploaded_files:()=>n?.includes(`lobe-cloud-sandbox`)?CG(Ite.currentUserFiles(Q9())):``,memory_effort:()=>te?x?.effort??``:``,agent_id:()=>p??``,agent_title:()=>p?Rr.getAgentMetaById(p)(E)?.title??``:``,agent_description:()=>p?Rr.getAgentMetaById(p)(E)?.description??``:``,topic_id:()=>b??``,topic_title:()=>b?vi.getTopicById(b)(Q9())?.title??``:``},...S&&{agentBuilderContext:d},...C&&{groupAgentBuilderContext:O},...V&&{agentManagementContext:V},...T&&{agentGroup:T},...F&&{planTodo:F},...re&&re.length>0&&{topicReferences:re},...ie&&{onboardingContext:ie}});g7(`Input messages count: %d`,e.length);let se=await oe.process();return g7(`Output messages count: %d`,se.messages.length),e.length>0&&se.messages.length===0&&g7(`WARNING: Messages were reduced to 0! Input messages: %o`,e.map(e=>({id:e.id,role:e.role}))),se.messages}})),v7,aHe=e((()=>{We(),so(),v7=({provider:e,runtimeProvider:t,payload:n})=>{let r={...n,...bie(e)};return Le.initializeWithProvider(t??e,{dangerouslyAllowBrowser:!0,...r,...n,providerId:e})}})),oHe,sHe,cHe,lHe,uHe,dHe=e((()=>{Tq(),Li(),oHe=t(F()),sHe=(0,oHe.default)(`lobe-mecha:tool-set-composer`),cHe=(e,t)=>{if(!t?.length)return e;let n=new Set(e.enabledToolIds),r=t.filter(e=>!n.has(e.identifier));if(r.length===0)return e;let i=r.flatMap(e=>vne(e)),a=e.tools?[...e.tools,...i]:i.length>0?i:void 0;return{enabledManifests:[...e.enabledManifests,...r],enabledToolIds:[...e.enabledToolIds,...r.map(e=>e.identifier)],tools:a}},lHe=(e,t)=>{if(t.scope!==`page`||!e.enabledToolIds.includes(`lobe-page-agent`)||t.isPageEditorReady)return e;sHe(`dropping %s: editor not mounted`,bq);let n=`${bq}____`,r=e.tools?.filter(e=>!e.function?.name?.startsWith(n));return{enabledManifests:e.enabledManifests.filter(e=>e.identifier!==bq),enabledToolIds:e.enabledToolIds.filter(e=>e!==bq),tools:r&&r.length>0?r:void 0}},uHe=({toolsDetailed:e,injectedManifests:t,context:n})=>lHe(cHe({enabledManifests:e.enabledManifests,enabledToolIds:e.enabledToolIds,tools:e.tools},t),n)})),y7=e((()=>{UVe(),iHe(),aHe(),Wre(),ZVe(),dHe()})),fHe=n({chatService:()=>b7}),pHe,mHe,b7,x7=e((()=>{ei(),Wt(),mc(),We(),Ne(),Zt(),Yne(),Qt(),gc(),vc(),Gr(),qr(),Ba(),bc(),f7(),d3(),Er(),Ta(),NVe(),LVe(),so(),lo(),ao(),y7(),Pe(),pHe=new Set([Vi.Azure,Vi.AzureAI,Vi.KimiCodingPlan,Vi.Qwen,Vi.Spark,Vi.Volcengine,Vi.VolcengineCodingPlan]),mHe=class{resolveAgentDocumentsTargetId=(e,t=[])=>t.includes(`lobe-agent-builder`)?Q9().activeAgentId||e||void 0:e||void 0;buildAssistantMessageContext=async({messages:e,agentId:t,groupId:n,topicId:r,resolvedAgentConfig:i,...a},o)=>
5995{let s=Lt({model:bt.model,stream:!0,...bt.params},a),c=HVe(t),{agentConfig:l,chatConfig:u,enabledManifests:d=[],enabledToolIds:f=[],plugins:p,tools:m}=i,h=hc(s.model,s.provider,c),g=Sa.memoryEnabled(_r()),_=u.memory?.enabled??g,v=Sa.currentMemorySettings(_r()),y=u.memory?.effort??v.effort??`medium`,b=u.enableAgentMode!==!1&&_c(s.model,s.provider),x=f.includes(Wr),S=this.resolveAgentDocumentsTargetId(c,f),C,w=S?Rr.getAgentDocumentsById(S)(Xr()):void 0;if(S&&w===void 0)try{w=await Xr().ensureAgentDocuments(S)}catch(e){console.error(`[ChatService] Failed to ensure agent documents:`,e)}if(x){let e=Q9().activeAgentId||``,t=Yr.getAgentBuilderContextById(e)(Xr()),n=Rr.getAgentConfigById(e)(Xr()),r=u7(),i=n?.plugins||[],a=[],o=PX.metaList(r),s=new Set(Vt.map(e=>e.identifier));for(let e of o)s.has(e.identifier)||a.push({description:e.meta?.description,enabled:i.includes(e.identifier),identifier:e.identifier,installed:!0,name:e.meta?.title||e.identifier,type:`builtin`});if(typeof window<`u`&&window.global_serverConfigStore?.getState()?.serverConfig?.enableComposio){let e=sX.getServers(r);for(let t of Vt){let n=e.find(e=>e.identifier===t.identifier);a.push({description:`LobeHub Mcp Server: ${t.label}`,enabled:i.includes(t.identifier),identifier:t.identifier,installed:!!n,name:t.label,type:`composio`})}}if(typeof window<`u`&&window.global_serverConfigStore?.getState()?.serverConfig?.enableLobehubSkill){let e=VX.getServers(r);for(let t of tn){let n=e.find(e=>e.identifier===t.id);a.push({description:`LobeHub Skill Provider: ${t.label}`,enabled:i.includes(t.id),identifier:t.id,installed:!!n,name:t.label,type:`lobehub-skill`})}}C={...t,officialTools:a}}let T=await _7({agentBuilderContext:C,agentDocuments:w,agentId:c,disabledPluginIds:Xe(l.plugins),enableAgentMode:b,enableHistoryCount:u.enableHistoryCount,enableUserMemories:_,groupId:n,historyCount:(u.historyCount??20)+1,initialContext:o?.initialContext,inputTemplate:u.inputTemplate,manifests:d,messages:e,model:s.model,plugins:p,provider:s.provider,sessionId:o?.trace?.sessionId,stepContext:o?.stepContext,systemRole:l.systemRole,tools:f,topicId:r,memoryContext:{effort:y}}),E=Hre({chatConfig:u,model:s.model,provider:s.provider});return{options:{...o,agentId:c,topicId:r},params:{...a,...E,enabledSearch:h.enabledSearch&&h.useModelSearch?!0:void 0,messages:T,stream:u.enableStreaming!==!1,tools:m}}};createAssistantMessage=async(e,t)=>{let n=await this.buildAssistantMessageContext(e,t);return this.getChatCompletion(n.params,n.options)};createAssistantMessageStream=async({params:e,abortController:t,onAbort:n,onMessageHandle:r,onErrorHandle:i,onFinish:a,metadata:o,trace:s,historySummary:c,initialContext:l,stepContext:u})=>{await this.createAssistantMessage(e,{historySummary:c,initialContext:l,onAbort:n,onErrorHandle:i,onFinish:a,onMessageHandle:r,metadata:o,signal:t?.signal,stepContext:u,trace:this.mapChatTrace(s)})};mapChatTrace=e=>this.mapTrace(e,fe.Chat);getChatCompletion=async(e,t)=>{let{agentId:n,metadata:r,signal:i,responseAnimation:a,topicId:o}=t??{},s=r?.trigger,{provider:c=Vi.OpenAI,...l}=e,u=l.model||bt.model,d=pHe.has(c)?mie(u,c):void 0,f=c===Vi.Azure&&O(u)||c===Vi.Spark;!f&&d&&(u=d);let p=Va.isProviderEnableResponseApi(c)(za())?`responses`:`chatCompletion`,m=$r.currentChatConfig(Xr());delete l.scope,delete l.forkedFromIdentifier;let h=Lt({model:bt.model,stream:m.enableStreaming!==!1,...bt.params},{...l,apiMode:p,...f&&d&&d!==u&&{deploymentName:d},model:u});h.temperature===null&&(h.temperature=void 0),h.top_p===null&&(h.top_p=void 0),h.presence_penalty===null&&(h.presence_penalty=void 0),h.frequency_penalty===null&&(h.frequency_penalty=void 0);let g=yie(c),_=hie(c),v;_&&(v=async()=>{try{return await this.fetchOnClient({payload:h,provider:c,runtimeProvider:g,signal:i})}catch(e){let{errorType:t=be.BadRequest,error:n,...r}=e,i=n||e;return console.error(`Route: [${c}] ${t}:`,i),MVe(t,{error:i,...r,provider:c})}});let y=await _ie({headers:{"Content-Type":`application/json`,...IVe({...t?.trace}),...n&&{"x-agent-id":n},...s&&{"x-lobechat-request-trigger":s},...o&&{"x-topic-id":o}},provider:c}),{getBusinessTrpcHeaders:b}=await Ge(async()=>{let{getBusinessTrpcHeaders:e}=await import(`./trpc-headers-BkKHL6Gq.js`);return{getBusinessTrpcHeaders:e}},__vite__mapDeps([69,1]));Object.assign(y,await b());let{DEFAULT_MODEL_PROVIDER_LIST:x}=await Ge(async()=>{let{DEFAULT_MODEL_PROVIDER_LIST:e}=await import(`../i18n/i18n-src-XaAKi_OQ.js`).then(e=>(e.Kt(),e.Jt));return{DEFAULT_MODEL_PROVIDER_LIST:e}},__vite__mapDeps([1,3])),S=x.find(e=>e.id===c),C=Ca.transitionMode(_r()),w=[S?.settings?.responseAnimation||{},C,a].reduce((e,t)=>
5995Lt(e,fc(t)),{});return pc(uo.chat(c),{body:JSON.stringify(h),fetcher:v,headers:y,method:`POST`,onAbort:t?.onAbort,onErrorHandle:t?.onErrorHandle,onFinish:t?.onFinish,onMessageHandle:t?.onMessageHandle,requestContext:{apiMode:p,fetchOnClient:_,model:u,provider:c},responseAnimation:w,signal:i})};fetchPresetTaskResult=async({params:e,onMessageHandle:t,onFinish:n,onError:r,onLoadingChange:i,abortController:a,trace:o})=>{let s=(e,t)=>{i?.(!1),!a?.signal.aborted&&(r?.(e,t),console.error(e))};i?.(!0);try{let r=await _7({messages:e.messages,model:e.model,provider:e.provider});await this.getChatCompletion({...e,messages:r},{onErrorHandle:e=>{s(Error(e.message),e)},onFinish:n,onMessageHandle:t,signal:a?.signal,trace:this.mapTrace(o,fe.SystemChain)}),i?.(!1)}catch(e){s(e)}};mapTrace=(e,t)=>{let n=Rr.currentAgentMeta(Xr()).tags||[];return Ca.telemetry(_r())?{...e,enabled:!0,tags:[t,...e?.tags||[],...n].filter(Boolean),userId:ba.userId(Or.getState())}:{...e,enabled:!1}};fetchOnClient=async e=>{if(!Or.getState().isSignedIn)throw xe.createError(be.InvalidAccessCode);let t=await v7({payload:e.payload,provider:e.provider,runtimeProvider:e.runtimeProvider}),n=e.payload;return t.chat(n,{signal:e.signal})}},b7=new mHe})),hHe,gHe,S7,_He,vHe,yHe,bHe,xHe,SHe,CHe=e((()=>{XG(),Mi(),IY(),f7(),hHe=/<skill\b([^>]*)\/>/g,gHe=/<action\b([^>]*)\/>/g,S7=(e,t)=>RegExp(`${t}="([^"]*)"`,`i`).exec(e)?.[1],_He=e=>{let t=[];for(let n of e.matchAll(hHe)){let e=n[1]||``,r=S7(e,`name`);r&&t.push({identifier:r,name:S7(e,`label`)||r})}for(let n of e.matchAll(gHe)){let e=n[1]||``;if(S7(e,`category`)!==`skill`)continue;let r=S7(e,`type`);r&&t.push({identifier:r,name:S7(e,`label`)||r})}return t},vHe=(e,t)=>{let n=[...t||[],..._He(e)],r=new Set;return n.reduce((e,t)=>!t.identifier||r.has(t.identifier)?e:(r.add(t.identifier),e.push(t),e),[])},yHe=e=>({description:e.description,key:e.key,name:e.name,type:e.type}),bHe=e=>({creds:(e||[]).map(yHe),settingsUrl:`/settings/credential`}),xHe=async(e,t)=>{let n=u7(),r=(n.builtinSkills||[]).find(t=>t.identifier===e.identifier);if(r){let e=r.content;if(r.identifier===`lobe-creds`){let n=bHe(t);e=VG(e,n)}return{content:e,identifier:r.identifier,name:r.name}}let i=(n.agentSkills||[]).find(t=>t.identifier===e.identifier),a=i&&n.agentSkillDetailMap?.[i.id]||(i?await FY.getById(i.id):void 0)||await FY.getByIdentifier(e.identifier);if(a?.content)return{content:a.resources&&Object.keys(a.resources).length>0?a.content+`
5996
5997`+Bi(a.name,a.resources):a.content,identifier:a.identifier,name:a.name}},SHe=async({message:e,selectedSkills:t,userCreds:n})=>{let r=vHe(e,t);return r.length===0?[]:await Promise.all(r.map(async e=>{let t=await xHe(e,n);return t?{...e,content:t.content}:e}))}})),wHe,THe,C7,EHe,DHe,OHe,kHe,AHe=e((()=>{f7(),wHe=/<tool\b([^>]*)\/>/g,THe=/<action\b([^>]*)\/>/g,C7=(e,t)=>RegExp(`${t}="([^"]*)"`,`i`).exec(e)?.[1],EHe=e=>{let t=[];for(let n of e.matchAll(wHe)){let e=n[1]||``,r=C7(e,`name`);r&&t.push({identifier:r,name:C7(e,`label`)||r})}for(let n of e.matchAll(THe)){let e=n[1]||``;if(C7(e,`category`)!==`tool`)continue;let r=C7(e,`type`);r&&t.push({identifier:r,name:C7(e,`label`)||r})}return t},DHe=(e,t)=>{let n=[...t||[],...EHe(e)],r=new Set;return n.reduce((e,t)=>!t.identifier||r.has(t.identifier)?e:(r.add(t.identifier),e.push(t),e),[])},OHe=e=>{let t=u7(),n=(t.builtinTools||[]).find(t=>t.manifest?.identifier===e);if(n?.manifest){let{manifest:e}=n,t=[];if(e.systemRole&&t.push(e.systemRole),e.api?.length>0){let n=e.api.map(e=>`- ${e.name}: ${e.description}`).join(`
5998`);t.push(`Available APIs:\n${n}`)}return t.join(`
5999
6000`)||void 0}let r=(t.installedPlugins||[]).find(t=>t.identifier===e);if(r?.manifest){let{manifest:e}=r,t=[];if(e.systemRole&&t.push(e.systemRole),e.api?.length>0){let n=e.api.map(e=>`- ${e.name}: ${e.description}`).join(`
6001`);t.push(`Available APIs:\n${n}`)}return t.join(`
6002
6003`)||void 0}},kHe=({message:e,selectedTools:t})=>DHe(e,t).map(e=>{let t=OHe(e.identifier);return t?{...e,content:t}:e})})),w7,jHe,MHe,T7,E7=e((()=>{w7=new Map,jHe=(e,t)=>{t.length===0?w7.delete(e):w7.set(e,[...t])},MHe=e=>{let t=w7.get(e);return w7.delete(e),t??[]},T7=e=>w7.get(e)??[]})),NHe,PHe,FHe,IHe,LHe=e((()=>{NHe=e=>e===`contextCompression`||e===`generateSummary`,PHe=e=>e.filter(e=>e.role!==`compressedGroup`).map(e=>
6003e.id).filter(Boolean),FHe=({agentId:e,content:t=`...`,groupId:n,id:r,threadId:i,topicId:a})=>{let o=Date.now();return{agentId:e,compressedMessages:[],content:t,createdAt:o,groupId:n??void 0,id:r,metadata:{expanded:!0},role:`compressedGroup`,threadId:i??void 0,topicId:a??void 0,updatedAt:o}},IHe=(e,t)=>e.some(e=>e.status!==`running`||!NHe(e.type)?!1:e.context.agentId===t.agentId&&(e.context.groupId??null)===(t.groupId??null)&&(e.context.threadId??null)===(t.threadId??null)&&(e.context.topicId??null)===(t.topicId??null))})),RHe=e((()=>{ni(),Mi(),Vee(),ro()})),zHe,BHe=e((()=>{zHe=async e=>{let{fetchTopicDetail:t,isHetero:n,storeTopic:r,topicId:i}=e;if(r)return r;if(!(!i||!n))try{return await t(i)??void 0}catch(e){console.error(`[resolveExistingTopicForRun] Failed to fetch topic detail:`,e);return}}})),VHe,HHe,UHe,WHe,D7,GHe,KHe=e((()=>{ic(),Wt(),Li(),_s(),Mi(),Ne(),R(),ure(),f(),Qr(),vr(),Ur(),hr(),dt(),sc(),x7(),CHe(),AHe(),Na(),Fa(),Gr(),qr(),s6(),E7(),Oi(),ys(),aNe(),qs(),ZOe(),si(),Ei(),Mte(),$Oe(),LHe(),wi(),Ti(),Vr(),Xa(),Xre(),A5(),Er(),po(),ja(),RHe(),qOe(),BHe(),Pe(),VHe=(e,t)=>!!t?.signal.aborted||e instanceof Error&&(e.name===`AbortError`||e.message.includes(`aborted`)||e.message.includes(`cancelled`)),HHe=()=>Object.assign(Error(`Compression cancelled`),{name:`AbortError`}),UHe=new Set(kte),WHe=(e,t,n)=>{if(!n)return e;let r=!1,i=e.map(e=>e.id===t?(r=!0,{...e,metadata:{...e.metadata??void 0,...n}}):e);return r?i:e},D7=(e,t,n)=>{let r=new Set(n),i=new Set(t.map(e=>e.id));return[...e.filter(e=>!r.has(e.id)&&!i.has(e.id)),...t]},GHe=class{#e;constructor(e,t,n){this.#e=t}#t=(e,t)=>{if(!e&&!t)return;let n=this.#e().topicDataMap[ai({agentId:e,groupId:t})];if(!n)return;let{excludeStatuses:r,excludeTriggers:i}=n;if(!(!r?.length&&!i?.length))return{...r?.length?{excludeStatuses:r}:{},...i?.length?{excludeTriggers:i}:{}}};sendMessage=async({message:e,editorData:t,files:n,forceRuntime:r,metadata:i,onlyAddUserMessage:a,context:s,contextSelections:c,messages:l,parentId:u,pageSelections:d,onTopicCreated:f})=>{let p=t,{executeClientAgent:m,mainInputEditor:h}=this.#e(),{agentId:g}=s,_=K0(p),v=q0(p),y=J0(p);zOe(ROe(p));let b=s.isNew&&s.scope===`thread`,x=b&&s.sourceMessageId&&s.threadType?{sourceMessageId:s.sourceMessageId,type:s.threadType}:void 0;if(!g)return;let S=Xr(),C=Rr.getAgentConfigById(g)(S),w=Yr.isWorkspaceAgentById(g)(S),T=w?_r().workspaceUserPreference.agentDeviceOverrides?.[g]:void 0,E=Lr(w,T),D=Qe(C?.agencyConfig,T),O=D?.heterogeneousProvider,k=vs({boundDeviceId:D?.boundDeviceId,executionTarget:D?.executionTarget,heterogeneousProvider:O,isGatewayMode:this.#e().isGatewayModeEnabled(g),isWorkspaceAgent:E,parentRuntime:r}),A=KOe({message:e,editorData:p,files:n,onlyAddUserMessage:a,context:s,messages:l,parentId:u,pageSelections:d,contextSelections:c});if(A.triggerCompression){let e={...s};e.topicId&&!IHe(Object.values(this.#e().operations),e)&&await this.executeCompression(e,``);return}let j=!1;if(A.forceNewTopic){let t=n&&n.length>0;if(!VOe(p)&&!t){await this.#e().switchTopic(null);return}if(s.topicId){let t=vi.getTopicById(s.topicId)(this.#e())?.title||``;e=`${`<refer_topic name="${t}" id="${s.topicId}" />`}\n${e}`,p=UOe(p,s.topicId,t),j=!0}s={...s,topicId:void 0}}let M=!1;s.groupId&&(M=j3.groupById(s.groupId)(o6())?.supervisorAgentId===g);let P=s.groupId?void 0:BOe(p),F=!s.groupId&&!P&&y.length>0,I=s.scope===`page`&&!s.documentId?k5.getCurrentDocId():void 0,L={...s,...b&&{threadId:void 0},...M&&{isSupervisor:!0,orchestrationRole:`supervisor`},...I?{documentId:I}:{}},ee=n?.map(e=>e.id);Hr.isLocalSystemEnabledById(g)(Xr());let R=[],te=i||c?.length||d?.length||R.length?{...i,...c?.length?{contextSelections:c}:void 0,...d?.length?{pageSelections:d}:void 0,...R.length?{localSystemToolSnapshots:R}:void 0}:void 0,z=await SHe({message:e,selectedSkills:_}),ne=kHe({message:e,selectedTools:v}),B=i?.trigger,V=B?{trigger:B}:void 0,H=!!ee&&ee.length>0;if(!e&&!H)return;let re=Aa(e).slice(0,80)||o(`defaultTitle`,{ns:`topic`}),ie=li(L),ae=(this.#e().operationsByContext[ie]||[]).map(e=>this.#e().operations[e]).find(e=>e&&UHe.has(e.type)&&e.status===`running`);if(ae){let t=(n??[]).map(e=>({id:e.id,mimeType:e.file?.type??``,name:e.file?.name??e.id,url:e.fileUrl||e.base64Url||e.previewUrl||``}));this.#e().enqueueMessage(ie,{id:ke(),content:e,editorData:p??void 0,files:ee,filesPreview:t.length>0?t:void 0,...r?{forceRuntime:r}:{},interruptMode:`soft`,metadata:te,createdAt:Date.now()},ae.id);return}if(a){await this.#e().addUserMessage({message:e,fileList:ee,metadata:te});return}let oe=li(s),se=j?[]:l??ui.getDisplayMessagesByKey(oe)(this.#e()),le=se.at(-1);
6003Cie.getState().setActiveMemoryContext({agent:Rr.getAgentMetaById(g)(Xr()),topic:vi.currentActiveTopic(this.#e()),latestUserMessage:le?.content,sendingMessage:e});let ue=j?void 0:u;!ue&&le&&(ue=ui.findLastMessageId(le.id)(this.#e()));let de=`tmp_`+ke(),fe=`tmp_`+ke(),{operationId:pe,abortController:me}=this.#e().startOperation({type:`sendMessage`,context:{...L,messageId:de},label:`Send Message`,metadata:{inThread:!!L.threadId}}),he=L.scope===`sub_agent`?`sub_agent`:`top_level`,ge=Ks(this.#e,{context:L,parentMessageId:ue??de,parentMessageType:`user`,runId:pe,runScope:he,runtimeType:k}),_e=n??[],ve=_e.filter(e=>e.file?.type?.startsWith(`image`)).map(e=>({id:e.id,url:e.fileUrl||e.base64Url||e.previewUrl||``,alt:e.file?.name||e.id})),ye=_e.filter(e=>e.file?.type?.startsWith(`video`)).map(e=>({id:e.id,url:e.fileUrl||e.base64Url||e.previewUrl||``,alt:e.file?.name||e.id}));this.#e().optimisticCreateTmpMessage({content:e,editorData:p??void 0,files:ee,role:`user`,agentId:L.agentId,topicId:L.topicId??void 0,threadId:L.threadId??void 0,imageList:ve.length>0?ve:void 0,videoList:ye.length>0?ye:void 0,metadata:te},{operationId:pe,tempMessageId:de}),this.#e().optimisticCreateTmpMessage({content:`...`,role:`assistant`,agentId:L.agentId,topicId:L.topicId??void 0,threadId:L.threadId??void 0,metadata:L.isSupervisor?{isSupervisor:!0,orchestrationRole:`supervisor`}:void 0},{operationId:pe,tempMessageId:fe}),this.#e().associateMessageWithOperation(de,pe),this.#e().associateMessageWithOperation(fe,pe);let be=await zHe({fetchTopicDetail:e=>Pa.getTopicDetail(e),isHetero:!!O,storeTopic:L.topicId?vi.getTopicById(L.topicId)(this.#e()):void 0,topicId:L.topicId}),xe=ur().gatewayDeviceInfo?.deviceId,Se=O?Ir(D,{clientExecutionAvailable:!1,isHetero:!0,workspaceScoped:E}):void 0,Ce=O&&(Se===`local`||Se===`device`||Se===`auto`)?{agencyConfig:D,currentDeviceId:xe,fallback:void 0,legacyAgentWorkingDirectory:S.localAgentWorkingDirectoryMap[g],workspaceScoped:E}:void 0,we=Ce?Uee(Ce):void 0,Te=Ce?yte(Ce):void 0,Ee=(O&&!Oo(O.type)?N:ce)(be?.metadata?.workingDirectoryConfig)??be?.metadata?.workingDirectory??we,De=be?.metadata?.workingDirectoryConfig??(be?.metadata?.workingDirectory?{path:be.metadata.workingDirectory}:Te),Oe=k===`gateway`&&!L.topicId&&L.agentId?T7(L.agentId):[],Ae=Oe.length>0?{repos:Oe,workingDirectory:Oe[0],workingDirectoryConfig:{path:Oe[0],repoType:`github`}}:Ee?{workingDirectory:Ee,...De?{workingDirectoryConfig:De}:{}}:void 0,je=!L.topicId&&!s.isolatedTopic?{id:`tmp_topic_${ke()}`,...Ae?{metadata:Ae}:{},title:re}:void 0,Me=!1,Ne=!1,Pe=L.groupId&&L.scope===`group`?void 0:L.agentId,Fe={agentId:Pe,groupId:L.groupId??void 0},Ie=(e,t,n,r)=>{this.#e().internal_dispatchTopic({...Fe,type:`addTopic`,value:{id:e,...r?{metadata:r}:{},...L.groupId?{}:{sessionId:L.agentId},title:t}},n)},Le=(e,t=je?.title)=>{if(!je||!Me){Ie(e,t||o(`defaultTitle`,{ns:`topic`}),`sendMessage/reconcileOptimisticTopic/add`,je?.metadata);return}this.#e().internal_replaceTopicId({...Fe,nextId:e,previousId:je.id,value:{...je.metadata?{metadata:je.metadata}:{},...L.groupId?{}:{sessionId:L.agentId},title:t||o(`defaultTitle`,{ns:`topic`})}}),Me=!1,Ne=!0},Re=e=>{!je||!Me||(this.#e().internal_updateTopicLoading(je.id,!1),this.#e().activeTopicId===je.id&&this.#e().switchTopic(null,{skipRefreshMessage:!0}),this.#e().internal_dispatchTopic({...Fe,type:`deleteTopic`,id:je.id},e),Me=!1)};je&&(Ie(je.id,je.title,`sendMessage/optimisticCreateTopic`,je.metadata),this.#e().internal_updateTopicLoading(je.id,!0),Me=!0);let ze=t??h?.getJSONState();if(this.#e().updateOperationMetadata(pe,{inputEditorTempState:ze,inputSendErrorMsg:void 0}),k===`hetero`&&O){let t;try{t=await oc.sendMessageInServer({agentId:L.agentId,groupId:L.groupId??void 0,newAssistantMessage:{provider:O.type},newTopic:L.topicId?void 0:{metadata:Ee?{workingDirectory:Ee,...De?{workingDirectoryConfig:De}:{}}:void 0,title:re,topicMessageIds:se.map(e=>e.id)},newUserMessage:{content:e,editorData:p,files:ee,metadata:te,contextSelections:c,pageSelections:d,parentId:ue},threadId:L.threadId??void 0,topicFilter:this.#t(Pe,L.groupId??void 0),topicPageSize:Ya.topicPageSize(Ja.getState()),topicId:L.topicId??void 0},me)}catch(e){console.error(`[HeterogeneousAgent] Failed to persist messages:`,e),this.#e().failOperation(pe,{message:e instanceof Error?e.message:`Unknown error`,type:`HeterogeneousAgentError`}),Re(`sendMessage/rollbackOptimisticTopic`);return}if(!t){Re(`sendMessage/rollbackOptimisticTopic`);return}let n=t.topicId??L.topicId,r=!!n&&L.scope!==`thread`,i={...L,...r?{isNew:!1}:{},topicId:n},a=t,l=li(i);this.#e().moveQueuedMessages(ie,l);let u=a.__isPartialMessages?D7(this.#e().messagesMap[l]||[],t.messages,[de,fe]):t.messages;if(this.#e().replaceMessages(u,{action:`sendMessage/serverResponse`,context:i}),t.isCreateNewTopic&&t.topicId){if(t.topics){je&&Me&&Le(t.topicId,re);let e=Ya.topicPageSize(Ja.getState());this.#e().internal_updateTopics(Pe,{groupId:L.groupId,items:t.topics.items,pageSize:e,total:t.topics.total})}else s.isolatedTopic||(Le(t.topicId,re),Promise.resolve(this.#e().refreshTopic()).catch(console.error));await this.#e().switchTopic(t.topicId,{clearNewKey:!0,skipRefreshMessage:!0})}this.#e().internal_dispatchMessage({ids:[de,fe],type:`deleteMessages`},{operationId:pe}),this.#e().completeOperation(pe),ge.afterUserMessagePersisted({assistantMessageId:t.assistantMessageId,context:i,isCreateNewTopic:t.isCreateNewTopic,operationId:pe,runId:pe,runScope:he,runtimeType:k,topicId:t.topicId}).catch(console.error),this.#e().updateOperationMetadata(pe,{inputEditorTempState:null});let{operationId:f}=this.#e().startOperation({context:i,label:`Heterogeneous Agent Execution`,metadata:{heterogeneousType:O.type},parentOperationId:pe,type:`execHeterogeneousAgent`});this.#e().associateMessageWithOperation(t.assistantMessageId,f);try{let{executeHeterogeneousAgent:n}=await Ge(async()=>{let{executeHeterogeneousAgent:e}=await import(`./heterogeneousAgentExecutor-BNR49jHj.js`);return{executeHeterogeneousAgent:e}},__vite__mapDeps([8,1,9,3,10,11,12,13,14,15,16,17,18,7,19,20,21,22,5,23,2,24,25,26,27,28,29,30,0,4,6])
6003),r=t.messages.find(e=>e.id===t.userMessageId),a=r?.imageList,s=r?.metadata,l=c?.length?c:s?.contextSelections,u=d?.length?d:s?.pageSelections,{cwdChanged:p,resumeSessionId:m}=Z0(((i.topicId?vi.getTopicById(i.topicId)(this.#e()):void 0)??be)?.metadata,Ee);p&&zr.info(o(`heteroAgent.resumeReset.cwdChanged`,{ns:`chat`})),await n(()=>this.#e(),{assistantMessageId:t.assistantMessageId,context:i,contextSelections:l,heterogeneousProvider:O,imageList:a?.length?a:void 0,message:e,operationId:f,pageSelections:u,resumeSessionId:m,workingDirectory:Ee,workingDirectoryConfig:De})}catch(e){console.error(`[HeterogeneousAgent] Execution failed:`,e),this.#e().failOperation(f,{message:e instanceof Error?e.message:`Unknown error`,type:`HeterogeneousAgentError`})}finally{je&&Ne&&t.topicId&&this.#e().internal_updateTopicLoading(t.topicId,!1)}return{assistantMessageId:t.assistantMessageId,userMessageId:t.userMessageId}}if(k===`gateway`&&!P)try{let t=await this.#e().executeGatewayAgent({context:L,fileIds:ee,message:e,metadata:V,parentOperationId:pe,optimisticTopic:je,selectedToolIds:v.length>0?v.map(e=>e.identifier):void 0,mentionedAgents:F?y:void 0,tempMessageIds:[fe]});return t.topicId?(je&&Me&&(this.#e().internal_updateTopicLoading(t.topicId,!1),Me=!1),ge.afterUserMessagePersisted({assistantMessageId:t.assistantMessageId,context:{...L,topicId:t.topicId},isCreateNewTopic:!L.topicId,operationId:pe,runId:pe,runScope:he,runtimeType:k,topicId:t.topicId}).catch(console.error)):Re(`sendMessage/rollbackOptimisticTopic`),{assistantMessageId:t.assistantMessageId,userMessageId:t.userMessageId}}catch(e){if(this.#e().operations[pe]?.status===`cancelled`){Re(`sendMessage/rollbackOptimisticTopic`);return}console.error(`[Gateway] Failed to start server-side agent:`,e),this.#e().failOperation(pe,{message:e instanceof Error?e.message:`Unknown error`,type:`GatewayError`}),Re(`sendMessage/rollbackOptimisticTopic`);return}let Be,Ve=e=>!!(e&&(e.isCreateNewTopic||!L.topicId&&e.topicId));try{let{model:t,provider:n}=Rr.getAgentConfigById(g)(Xr()),r=L.topicId,i=new Set,a=new Set;for(let e of se)if(e.role===`user`){for(let t of K0(e.editorData??void 0))i.add(t.identifier);for(let t of q0(e.editorData??void 0))a.add(t.identifier)}let o=z.filter(e=>!i.has(e.identifier)),l=ne.filter(e=>!a.has(e.identifier)),u=[gne(o),Cne(l)].filter(Boolean).join(`
6004`),m=u?`${e}\n\n${u}`:e;Be=await oc.sendMessageInServer({newUserMessage:{content:m,editorData:p,files:ee,metadata:te,contextSelections:c,pageSelections:d,parentId:ue},preloadMessages:void 0,topicId:r??void 0,topicFilter:this.#t(Pe,L.groupId??void 0),topicPageSize:Ya.topicPageSize(Ja.getState()),threadId:L.threadId??void 0,newThread:x?{sourceMessageId:x.sourceMessageId,type:x.type}:void 0,newTopic:r?void 0:{topicMessageIds:j?[]:se.map(e=>e.id),title:re},agentId:L.agentId,groupId:L.groupId??void 0,newAssistantMessage:{metadata:L.isSupervisor?{isSupervisor:!0,orchestrationRole:`supervisor`}:void 0,model:t,provider:n}},me);let h=Be,_=Be.topicId??L.topicId,v=Be.createdThreadId??L.threadId,y=Ve(Be);if(Be?.topics){if(_=Be.topicId,!s.isolatedTopic){je&&Me&&Be.topicId&&Le(Be.topicId,re);let e=Ya.topicPageSize(Ja.getState());this.#e().internal_updateTopics(Pe,{groupId:L.groupId,items:Be.topics.items,pageSize:e,total:Be.topics.total}),this.#e().updateOperationMetadata(pe,{createdTopicId:Be.topicId})}}else y&&Be.topicId&&!s.isolatedTopic?(Le(Be.topicId,re),this.#e().updateOperationMetadata(pe,{createdTopicId:Be.topicId}),Promise.resolve(this.#e().refreshTopic()).catch(console.error)):L.topicId&&this.#e().internal_dispatchTopic({type:`updateTopic`,id:L.topicId,value:{sortUpdatedAt:Date.now()}});Be.createdThreadId&&(this.#e().updateOperationMetadata(pe,{createdThreadId:Be.createdThreadId}),Hte.currentViewType(this.#e())===bi.Thread?this.#e().openThreadInPortal(Be.createdThreadId,s.sourceMessageId):this.#e().syncThreadInPortal(Be.createdThreadId,s.sourceMessageId),this.#e().refreshThreads());let b={...L,threadId:v,topicId:_},S=li(b);this.#e().moveQueuedMessages(ie,S);let C=WHe(Be.messages,Be.userMessageId,te);Be={...Be,messages:h.__isPartialMessages?D7(this.#e().messagesMap[S]||[],C,[de,fe]):C},this.#e().replaceMessages(Be.messages,{context:b,action:`sendMessage/serverResponse`}),y&&Be.topicId&&(s.isolatedTopic?await f?.(Be.topicId):await this.#e().switchTopic(Be.topicId,{clearNewKey:!0,skipRefreshMessage:!0}))}catch(t){if(console.error(t),Re(`sendMessage/rollbackOptimisticTopic`),this.#e().failOperation(pe,{type:t instanceof Error?t.name:`unknown_error`,message:t instanceof Error?t.message:`Unknown error`}),t instanceof mre&&!(t.message.includes(`aborted`)||t.name===`AbortError`)){this.#e().updateOperationMetadata(pe,{inputSendErrorMsg:t.message});let n=this.#e().operations[pe];n?.metadata.inputEditorTempState?this.#e().mainInputEditor?.setJSONState(n.metadata.inputEditorTempState):this.#e().mainInputEditor?.setDocument(`markdown`,e)}}finally{(Ve(Be)||!Be)&&this.#e().internal_dispatchMessage({type:`deleteMessages`,ids:[de,fe]},{operationId:pe})}if(Be&&this.#e().updateOperationMetadata(pe,{inputEditorTempState:null}),!Be){Re(`sendMessage/rollbackOptimisticTopic`);return}Re(`sendMessage/rollbackUnresolvedOptimisticTopic`),Be.topicId&&!Ne&&this.#e().internal_updateTopicLoading(Be.topicId,!0),ge.afterUserMessagePersisted({assistantMessageId:Be.assistantMessageId,context:L,isCreateNewTopic:Ve(Be),messages:Be.messages,operationId:pe,runId:pe,runScope:he,runtimeType:k,topicId:Be.topicId}).catch(console.error),this.#e().completeOperation(pe);let He={...L,topicId:Be.topicId??L.topicId,threadId:Be.createdThreadId??L.threadId};{let e=ui.getDisplayMessagesByKey(li(He))(this.#e()).flatMap(e=>{let t=[];
6004e.role===`tool`&&e.pluginIntervention?.status===`pending`&&t.push(e.id);let n=e.children?.flatMap(e=>(e.tools??[]).filter(e=>e.intervention?.status===`pending`&&e.result_msg_id).map(e=>e.result_msg_id))??[];return[...t,...n]});for(let t of e)this.#e().internal_dispatchMessage({id:t,type:`updateMessage`,value:{pluginIntervention:{status:`aborted`},content:`User bypassed this interaction by sending a message directly.`}}),Ma.updateMessagePlugin(t,{intervention:{status:`aborted`}},{agentId:He.agentId,groupId:He.groupId,threadId:He.threadId,topicId:He.topicId})}try{if(P)await this.#n({assistantMessageId:Be.assistantMessageId,context:He,directMentionRoute:P,inPortalThread:!!Be.createdThreadId,instruction:e,parentOperationId:pe});else{let e=ui.getDisplayMessagesByKey(li(He))(this.#e()),t=F?[rc()]:void 0;await m({context:He,initialContext:Q0(await e2(He),F||t?{initialContext:{...F?{mentionedAgents:y}:void 0,...t?{injectedManifests:t}:void 0},phase:`init`}:void 0),metadata:V,messages:e,parentMessageId:Be.assistantMessageId,parentMessageType:`assistant`,parentOperationId:pe,inPortalThread:!!Be.createdThreadId,skipCreateFirstMessage:!0,userMessageId:Be.userMessageId})}let t=ci.dbUserFiles(this.#e()).map(e=>e?.id).filter(Boolean);t.length>0&&await Xr().addFilesToAgent(t,!1)}catch(e){console.error(e)}finally{Be.topicId&&this.#e().internal_updateTopicLoading(Be.topicId,!1)}return{assistantMessageId:Be.assistantMessageId,createdThreadId:Be.createdThreadId,createdTopicId:Ve(Be)?Be.topicId:void 0,userMessageId:Be.userMessageId}};async#n({assistantMessageId:e,context:t,inPortalThread:n,directMentionRoute:r,instruction:i,parentOperationId:a}){let o=r.agent.id,s={agentId:o,instruction:i},c={apiName:Qs.callAgent,arguments:JSON.stringify(s),id:`call_agent_${ke()}`,identifier:Zs,source:`builtin`,type:`builtin`},l={agentId:o,instruction:i,mode:`speak`},u=`Called agent "${o}" to respond.`,{operationId:d}=this.#e().startOperation({context:{...t,messageId:e},label:`Direct Agent Mention`,metadata:{apiName:Qs.callAgent,targetAgentId:o,tool_call_id:c.id},parentOperationId:a,type:`toolCalling`});try{this.#e().internal_dispatchMessage({id:e,type:`updateMessage`,value:{content:``}},{operationId:d}),await this.#e().optimisticUpdateMessageContent(e,``,{tools:[c]},{operationId:d});let r=await this.#e().optimisticCreateMessage({agentId:t.agentId,content:u,groupId:t.groupId,parentId:e,plugin:c,pluginState:l,role:`tool`,threadId:t.threadId,tool_call_id:c.id,topicId:t.topicId??void 0},{operationId:d});if(!r)throw Error(`[directMentionRoute] Failed to create callAgent tool message for agentId: ${o}`);let a=await this.#r(o);if(a){await this.#e().optimisticUpdateMessageContent(r.id,a,void 0,{operationId:d}),this.#e().completeOperation(d);return}let s=ci.getDbMessagesByKey(li(t))(this.#e()),f=i.trim(),p=Date.now(),m=f?[...s,{content:`<speaker name="Supervisor" />\n${i}`,createdAt:p,id:`virtual_speak_instruction_${p}`,role:`user`,updatedAt:p}]:s,h=t.agentId?Rr.getAgentConfigById(t.agentId)(Xr()):void 0;await iNe({kind:`mention`,targetAgentId:o,instruction:i,parentMessageId:r.id},{conversationContext:t,boundDeviceId:h?.agencyConfig?.boundDeviceId,heterogeneousProvider:h?.agencyConfig?.heterogeneousProvider,inPortalThread:n,isGatewayMode:this.#e().isGatewayModeEnabled(t.agentId),isWorkspaceAgent:t.agentId?Yr.isWorkspaceAgentById(t.agentId)(Xr()):!1,messages:m,parentOperationId:d},this.#e()),this.#e().completeOperation(d)}catch(e){throw this.#e().failOperation(d,{type:`DirectMentionRouteError`,message:e instanceof Error?e.message:String(e)}),e}}async#r(e){if(!jr.getState().agentMap[e])try{let t=await ht.getAgentConfigById(e);if(!t)return`Agent "${e}" not found in your workspace. Please check the agent ID and try again.`;jr.getState().internal_dispatchAgentMap(e,t)}catch(t){return console.error(`[directMentionRoute] Failed to load agent config:`,t),`Failed to load agent "${e}": ${t.message}`}}executeCompression=async(e,t)=>{let{agentId:n,topicId:r}=e;if(!r)return;let i=li(e),a=PHe(ci.getDbMessagesByKey(i)(this.#e())||[]);if(a.length===0)return;let o=`tmp_compress_`+ke(),{abortController:s,operationId:c}=this.#e().startOperation({context:{...e,messageId:o},parentOperationId:t,type:`contextCompression`});this.#e().internal_dispatchMessage({id:o,type:`createMessage`,value:FHe({agentId:n,groupId:e.groupId,id:o,threadId:e.threadId,topicId:r})},{operationId:c});try{let{messageGroupId:t,messages:i,messagesToSummarize:o}=await Ma.createCompressionGroup({agentId:n,messageIds:a,topicId:r});this.#e().replaceMessages(i,{context:e}),this.#e().associateMessageWithOperation(t,c);let{model:l,provider:u}=Rr.getAgentConfigById(n)(Xr()),d=Qte(o),f=``;if(await b7.fetchPresetTaskResult({abortController:s,onMessageHandle:e=>{e.type===`text`&&(f+=e.text||``,this.#e().internal_dispatchMessage({id:t,type:`updateMessage`,value:{content:f}},{operationId:c}))},params:{...d,model:l,provider:u}}),s.signal.aborted)throw HHe();let p=await Ma.finalizeCompression({agentId:n,content:f,messageGroupId:t,topicId:r});p.messages&&this.#e().replaceMessages(p.messages,{context:e}),this.#e().completeOperation(c)}catch(e){if(VHe(e,s)){this.#e().internal_dispatchMessage({type:`deleteMessages`,ids:[o]},{operationId:c});return}console.error(`[/compact] Compression failed:`,e),this.#e().internal_dispatchMessage({type:`deleteMessages`,ids:[o]},{operationId:c}),this.#e().failOperation(c,{message:e instanceof Error?e.message:String(e),type:`compression_failed`})}}}})),qHe,JHe=e((()=>{Mi(),Ne(),x7(),Fa(),Er(),Ta(),qHe=class{#e;constructor(e,t,n){this.#e=t}internal_summaryHistory=async e=>{let t=this.#e().activeTopicId;if(e.length<=1||!t)return;let{model:n,provider:r}=wa.historyCompress(Or.getState()),i=``;await b7.fetchPresetTaskResult({onFinish:async e=>{i=e}
6004,params:{...Jte(e),model:n,provider:r,stream:!1},trace:{sessionId:this.#e().activeAgentId,topicId:this.#e().activeTopicId,traceName:Se.SummaryHistoryMessages}}),await Pa.updateTopic(t,{historySummary:i,metadata:{model:n,provider:r}}),await this.#e().refreshTopic(),await this.#e().refreshMessages()}}})),YHe,XHe,ZHe=e((()=>{YHe=t(le()),it(),XHe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}internal_toggleSearchWorkflow=(e,t)=>{this.#e().internal_toggleLoadingArrays(`searchWorkflowLoadingIds`,e,t)};internal_toggleToolCallingStreaming=(e,t)=>{let n=this.#e().toolCallingStreamIds,r=tt(n,n=>{t?n[e]=t:delete n[e]});(0,YHe.default)(n,r)||this.#t({toolCallingStreamIds:r},!1,`toggleToolCallingStreaming/${t?`start`:`end`}`)}}})),QHe,O7,k7,$He,A7,eUe,tUe,nUe=e((()=>{QHe=t(F()),it(),GVe(),e7(),Y5(),P8(),ae(),O7=(0,QHe.default)(`lobe-store:client-tool-execution`),k7=12e4,$He=500,A7=class extends Error{executionTimeoutMs;constructor(e){super(`Tool execution exceeded ${e}ms client deadline`),this.name=`ClientExecutorTimeoutError`,this.executionTimeoutMs=e}},eUe=e=>Math.max((typeof e==`number`&&e>0?e:k7)-$He,100),tUe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}internal_executeClientTool=async(e,t)=>{let{apiName:n,agentId:r,arguments:i,assistantMessageId:a,documentId:o,executionTimeoutMs:s,groupId:c,identifier:l,rootOperationId:u,scope:d,sourceMessageId:f,taskId:p,threadId:m,toolCallId:h,toolMessageId:g,topicId:_}=e,{localOperationId:v,operationId:y}=t;O7(`[internal_executeClientTool] start toolCallId=%s identifier=%s apiName=%s op=%s timeout=%dms`,h,l,n,y,s),this.#r(h,!0);let b=!1,x=e=>{if(b){O7(`[internal_executeClientTool] duplicate send ignored for toolCallId=%s`,h);return}b=!0;let t=this.#e().gatewayConnections[y];if(!t){O7(`[internal_executeClientTool] no gateway connection for op=%s toolCallId=%s — server will timeout`,y,h);return}t.client.sendToolResult(e)||O7(`[internal_executeClientTool] sendToolResult returned false (socket closed) for toolCallId=%s`,h)};try{let e={};if(i){let t=se(i);if(t===void 0){x({content:null,error:{message:`Failed to parse tool arguments: ${i.slice(0,200)}`,type:`arguments_parse_error`},success:!1,toolCallId:h});return}e=t??{}}let t=this.#e().operations[v??y];if(K5(l,n)){let i={agentId:r??t?.context?.agentId,anchorMessageId:a,documentId:o??t?.context?.documentId,groupId:c??t?.context?.groupId,messageId:g??h,operationId:y,rootOperationId:u??y,scope:d??t?.context?.scope,signal:t?.abortController?.signal,sourceMessageId:f??t?.context?.messageId,taskId:p,threadId:m??t?.context?.threadId,topicId:_??t?.context?.topicId,toolCallId:h,toolMessageId:g,workingDirectory:WVe(this.#e(),_??t?.context?.topicId)};O7(`[ClientToolCall] execute:start`,{agentId:i.agentId,apiName:n,documentId:i.documentId,identifier:l,operationId:y,scope:i.scope,toolCallId:h,topicId:i.topicId});let v=await this.#n(()=>q5(l,n,e,i),s,()=>t?.abortController?.abort());O7(`[ClientToolCall] execute:end`,{apiName:n,errorType:v.error?.type,identifier:l,operationId:y,success:v.success,toolCallId:h});let b=N8(h);v.error?x({content:v.content??v.error.message??null,error:{message:v.error.message,type:v.error.type},state:v.state,success:!1,toolCallId:h,workRegistration:b}):x({content:v.content??null,state:v.state,success:!!v.success,toolCallId:h,workRegistration:b});return}let b=await this.#n(()=>$5.invokeMcpToolCall({apiName:n,arguments:i,id:h,identifier:l,type:`default`},{signal:t?.abortController?.signal,topicId:t?.context?.topicId??void 0}).catch(e=>{O7(`[internal_executeClientTool] mcp invoke threw for %s/%s: %O`,l,n,e)}),s,()=>t?.abortController?.abort());if(!b){x({content:null,error:{message:`No client executor available for ${l}/${n}`,type:`executor_not_found`},success:!1,toolCallId:h});return}x({content:b.content??null,error:b.success?void 0:{message:b.error?.message??`MCP tool call failed`,type:b.error?.type},state:b.state,success:!!b.success,toolCallId:h})}catch(e){if(e instanceof A7){O7(`[internal_executeClientTool] timeout toolCallId=%s after %dms`,h,e.executionTimeoutMs),x({content:null,error:{message:`Tool exceeded ${e.executionTimeoutMs}ms deadline. Raise \`timeout\` in the next call's arguments if this is expected.`,type:`client_executor_timeout`},success:!1,toolCallId:h});return}let t=e;O7(`[internal_executeClientTool] unexpected error toolCallId=%s: %O`,h,t),x({content:null,error:{message:t?.message||`Unknown client tool execution error`,type:`client_tool_execution_error`},success:!1,toolCallId:h})}finally{b||(O7(`[internal_executeClientTool] no send observed for toolCallId=%s; emitting default failure`,h),x({content:null,error:{message:`Client tool execution finished without producing a result`,type:`client_executor_no_result`},success:!1,toolCallId:h})),N8(h),this.#r(h,!1)}};#n=async(e,t,n)=>{let r=eUe(t),i=t??k7,a;try{return await Promise.race([e(),new Promise((e,t)=>
6004{a=setTimeout(()=>{try{n()}catch(e){O7(`[raceAgainstDeadline] onTimeout threw: %O`,e)}t(new A7(i))},r)})])}finally{a&&clearTimeout(a)}};#r=(e,t)=>{this.#t(n=>({pendingClientToolExecutions:tt(n.pendingClientToolExecutions,n=>{t?n[e]=!0:delete n[e]})}),!1,`pendingClientTool/${t?`start`:`end`}`)}}}));function rUe(e,t){let n=e.api.map(e=>{let n=t.get(e.name);return n===Pi.disabled?{...e,description:`[TOOL DISABLED] The user has disabled this tool and it cannot be executed. Do NOT call this tool. If the user asks to perform this action, inform them that they have manually disabled "${e.name}" and can re-enable it in Settings > Connectors.`,humanIntervention:`required`}:n===Pi.needs_approval?{...e,humanIntervention:`required`}:e});return{...e,api:n}}var iUe=e((()=>{Ane()})),aUe,oUe=e((()=>{Ane(),aUe=e=>{let t=[];for(let n of e){if(!n.isEnabled)continue;let e=n.tools??[];if(e.length===0)continue;let r=e.map(e=>{let t=e.inputSchema??{properties:{},type:`object`};return e.permission===Pi.disabled?{description:`[TOOL DISABLED] The user has disabled this tool and it cannot be executed. Do NOT call this tool. If the user asks to perform this action, inform them that they have manually disabled "${e.toolName}" and can re-enable it in Settings > Connectors.`,humanIntervention:`required`,name:e.toolName,parameters:t}:{description:e.description??``,humanIntervention:e.permission===Pi.needs_approval?`required`:void 0,name:e.toolName,parameters:t}});t.push({api:r,identifier:n.identifier,meta:{avatar:`MCP_AVATAR`,description:`${n.name} connector with ${r.length} tools`,title:n.name},type:`mcp`})}return t}})),sUe,j7,cUe,M7,lUe=e((()=>{al(),NG(),iK(),ni(),sq(),zJ(),iY(),Li(),eX(),iUe(),Gr(),qr(),f7(),d3(),Ha(),Er(),Ta(),gc(),vc(),oUe(),sUe=e=>!!e&&typeof e==`object`&&Array.isArray(e.api),j7=(e,t)=>{let n=[],r=[];for(let t of e)sUe(t)?n.push(t):t&&r.push({identifier:t.identifier,reason:Array.isArray(t.api)?`unknown`:"missing `api` field (expected array)"});return r.length>0&&console.warn(`[toolEngineering] Dropped ${r.length} invalid manifest(s) from ${t}:`,r),n},cUe=(e={})=>{let{enableChecker:t,additionalManifests:n=[],defaultToolIds:r,disabledPluginIds:i=[],manifestContext:a}=e,o=u7(),s=aUe(Ua.customConnectors(o)),c=new Set(s.map(e=>e.identifier)),l=new Map(Ua.connectorList(o).map(e=>[e.identifier,new Map(e.tools.map(e=>[e.toolName,e.permission]))])),u=hZ.installedPluginManifestList(o).filter(e=>!c.has(e.identifier)).map(e=>{let t=l.get(e.identifier);return t&&t.size>0?rUe(e,t):e}),d=o.builtinTools.map(e=>a&&e.resolveManifest?e.resolveManifest(a):e.manifest).filter(e=>!!e),f=sX.composioAsLobeTools(o).map(e=>e.manifest).filter(Boolean),p=VX.lobehubSkillAsLobeTools(o).map(e=>e.manifest).filter(Boolean),m=[...j7(u,`installedPlugins`),...j7(d,`builtinTools`),...j7(f,`composio`),...j7(p,`lobehubSkills`),...j7(s,`connectors`),...j7(n,`additionalManifests`)];return new Dne({defaultToolIds:r,enableChecker:t,functionCallChecker:_c,manifestSchemas:i.length===0?m:m.filter(e=>!i.includes(e.identifier))})},M7=(e,t,n)=>{let r=hc(e.model,e.provider),i=Xr(),a=Rr.currentAgentPlugins(i),o=Rr.currentAgentDisabledPlugins(i),s=$r.currentChatConfig(i).enableAgentMode===!1||!_c(e.model,e.provider),c=Rr.hasEnabledKnowledgeBases(i),l=$r.currentChatConfig(i).memory?.enabled??Sa.memoryEnabled(Or.getState()),u=r.useApplicationBuiltinSearchTool,d={[nK.identifier]:c,[aq.identifier]:l,[LJ.identifier]:u},f={...t&&Object.fromEntries(t.map(e=>[e,!0])),...Object.fromEntries(a.map(e=>[e,!0])),...Object.fromEntries(YJ.map(e=>[e,!0])),[il.identifier]:$r.isLocalSystemEnabled(i)&&hre.enableInAppBrowser(Or.getState()),[jG.identifier]:$r.isCloudSandboxEnabled(i),[nK.identifier]:c,[Mr.identifier]:$r.isLocalSystemEnabled(i),[aq.identifier]:l,[LJ.identifier]:u};return cUe({defaultToolIds:s?QJ:JJ,disabledPluginIds:o,manifestContext:n,enableChecker:xne({allowExplicitActivation:!s,platformFilter:({pluginId:e})=>{let t=u7(),n=hZ.getInstalledPluginById(e)(t);if(!QY(e,{installedPlugins:n?[n]:t.installedPlugins}))return!1},rules:s?d:f})})}})),uUe,dUe,fUe,pUe=e((()=>{Mi(),Na(),uUe=e=>
6004e instanceof Error?e.message:typeof e==`string`?e:String(e),dUe=e=>e instanceof Error&&(e.name===`AbortError`||e.message.includes(`aborted`)||e.message.includes(`cancelled`)),fUe=class{get;messageKey;rootOperationId;activeCompression;constructor(e,t,n){this.get=e,this.messageKey=t,this.rootOperationId=n}async buildPrompt(e){return{messages:Qte(e.messages,e.existingSummary).messages}}async createGroup(e){let t=this.get(),n=t.operations[this.rootOperationId];if(!n)throw Error(`Operation not found: ${this.rootOperationId}`);let r=e.agentId??n.context.agentId;if(!r)throw Error(`Client context compression requires an agent id`);let i={...n.context,agentId:r,groupId:e.groupId??n.context.groupId,threadId:e.threadId??n.context.threadId,topicId:e.topicId},a=(t.dbMessagesMap[this.messageKey]??[]).findLast(e=>e.role===`assistant`),o=t.startOperation({context:{...i,messageId:a?.id},metadata:{messageCount:e.messageIds.length,startTime:Date.now()},parentOperationId:this.rootOperationId,type:`contextCompression`});this.activeCompression={compressionOperationId:o.operationId,parentMessageId:a?.id};let s;try{s=await Ma.createCompressionGroup({agentId:r,groupId:i.groupId,messageIds:e.messageIds,threadId:i.threadId,topicId:e.topicId}),this.activeCompression.messageGroupId=s.messageGroupId,t.replaceMessages(s.messages,{context:i});let n=t.startOperation({context:{...i,messageId:s.messageGroupId},parentOperationId:o.operationId,type:`generateSummary`});return this.activeCompression.summaryOperationId=n.operationId,o.abortController.signal.aborted&&n.abortController.abort(o.abortController.signal.reason),{messageGroupId:s.messageGroupId,messages:s.messages,messagesToSummarize:s.messagesToSummarize,signal:n.abortController.signal}}catch(n){if(s)try{let n=await Ma.cancelCompression({agentId:r,groupId:i.groupId,messageGroupId:s.messageGroupId,threadId:i.threadId,topicId:e.topicId});t.replaceMessages(n.messages,{context:i})}catch(e){console.error(`Failed to rollback client context compression`,e)}throw this.failActiveOperations(n),n}}async finalizeGroup(e){let t=this.getOperationContext(e),n=await Ma.finalizeCompression({agentId:t.agentId,content:e.content,groupId:t.groupId,messageGroupId:e.messageGroupId,sourceGroupIds:e.sourceGroupIds,threadId:t.threadId,topicId:e.topicId}),r=this.get();return n.messages&&r.replaceMessages(n.messages,{context:t}),this.activeCompression?.summaryOperationId&&r.completeOperation(this.activeCompression.summaryOperationId),this.activeCompression&&r.completeOperation(this.activeCompression.compressionOperationId,{groupId:e.messageGroupId,parentMessageId:this.activeCompression.parentMessageId}),n}async rollbackGroup(e){let t=this.getOperationContext(e);try{let n=await Ma.cancelCompression({agentId:t.agentId,groupId:t.groupId,messageGroupId:e.messageGroupId,threadId:t.threadId,topicId:e.topicId});return this.get().replaceMessages(n.messages,{context:t}),n}finally{this.failActiveOperations(e.error)}}updateGroup(e){let t=this.activeCompression?.summaryOperationId??this.activeCompression?.compressionOperationId??this.rootOperationId;this.get().internal_dispatchMessage({id:e.messageGroupId,type:`updateMessage`,value:{content:e.content}},{operationId:t})}failActiveOperations(e){if(!this.activeCompression)return;let t=this.get(),n=[this.activeCompression.summaryOperationId,this.activeCompression.compressionOperationId].filter(e=>!!e),r=dUe(e)||n.some(e=>!!t.operations[e]?.abortController.signal.aborted);for(let i of n){let n=t.operations[i];!n||n.status!==`running`||(r?t.cancelOperation(i,`Context compression cancelled`):t.failOperation(i,{message:uUe(e),type:i===this.activeCompression.summaryOperationId?`summary_generation_failed`:`compression_failed`}))}}getOperationContext(e){let t=this.get().operations[this.rootOperationId];if(!t)throw Error(`Operation not found: ${this.rootOperationId}`);let n=e.agentId??t.context.agentId;if(!n)throw Error(`Client context compression requires an agent id`);return{...t.context,agentId:n,groupId:e.groupId??t.context.groupId,threadId:e.threadId??t.context.threadId,topicId:e.topicId}}}})),mUe,hUe=e((()=>{Li(),Ne(),R(),x7(),mUe=class{context;constructor(e){this.context=e}async build(e){let t=this.context.get().operations[this.context.operationId];if(!t)throw Error(`Operation not found: ${this.context.operationId}`);let n=this.resolveAgentConfig(e),r=Object.fromEntries((n.enabledManifests??[]).map(e=>[e.identifier,e])),i={enabledToolIds:n.enabledToolIds??[],executorMap:e.state.operationToolSet?.executorMap,manifestMap:r,sourceMap:e.state.operationToolSet?.sourceMap??{},tools:n.tools??[]},a=new kne().resolve(i,{activatedTools:[],...e.state.forceFinish&&{deactivatedToolIds:[`*`]}},[],e.payload.allowedToolNames),o={...n,enabledManifests:Object.values(a.promptManifestMap),enabledToolIds:a.enabledToolIds,tools:a.tools.length>0?a.tools:void 0},{agentConfig:s}=o,{agentId:c,groupId:l,subAgentId:u,topicId:d}
6004=t.context,f=l&&u?u:c,p=e.payload.assistantMessageId,m=e.payload.messages.filter(e=>!p||e.id!==p),h=await b7.buildAssistantMessageContext({agentId:f||void 0,groupId:l,messages:m,model:e.model,provider:e.provider,resolvedAgentConfig:o,topicId:d??void 0,...s.params},{initialContext:this.context.runtimeContext?.initialContext,metadata:this.context.metadata,stepContext:this.context.runtimeContext?.stepContext,trace:b7.mapChatTrace({traceId:t.metadata?.traceId,topicId:d??void 0,traceName:Se.Conversation})}),{messages:g=[],..._}=h.params;return{messages:g,modelParameters:{options:h.options,params:_},preserveThinking:typeof h.params.preserveThinking==`boolean`?h.params.preserveThinking:void 0,replayAssistantReasoning:!0,resolvedTools:a}}resolveAgentConfig(e){let t=[...this.context.runtimeContext?.stepContext?.activatedToolIds??[],...e.state.activatedStepTools?.map(e=>e.id)??[]],n=[...new Set(t)];if(!n.length||!this.context.toolsEngine)return this.context.agentConfig;let r=this.context.toolsEngine.generateToolsDetailed({context:{isExplicitActivation:!0},model:e.model,provider:e.provider,skipDefaultTools:!0,toolIds:n});return r.tools?.length?{...this.context.agentConfig,enabledManifests:I([...this.context.agentConfig.enabledManifests??[],...r.enabledManifests],e=>e.identifier),enabledToolIds:[...new Set([...this.context.agentConfig.enabledToolIds??[],...r.enabledToolIds])],tools:I([...this.context.agentConfig.tools??[],...r.tools],e=>e.function.name)}:this.context.agentConfig}}})),gUe,N7,_Ue,vUe=e((()=>{R(),gUe=t(F()),Zt(),qte(),o2(),N7=(0,gUe.default)(`lobe-store:streaming-handler`),_Ue=class{context;callbacks;output=``;thinkingContent=``;thinkingStartAt;thinkingDuration;reasoningOperationId;reasoningParts=[];contentParts=[];isFunctionCall=!1;tools;uploadTasks=new Map;contentImageUploads=new Map;reasoningImageUploads=new Map;msgTraceId;finishType;throttledUpdateToolCalls;constructor(e,t){this.context=e,this.callbacks=t,this.throttledUpdateToolCalls=Bt(e=>{let t=this.callbacks.transformToolCalls(e);this.callbacks.onToolCallsUpdate(t)},300,{leading:!0,trailing:!0})}handleChunk(e){switch(e.type){case`text`:this.handleTextChunk(e);break;case`reasoning`:this.handleReasoningChunk(e);break;case`reasoning_part`:this.handleReasoningPartChunk(e);break;case`content_part`:this.handleContentPartChunk(e);break;case`tool_calls`:this.handleToolCallsChunk(e);break;case`grounding`:this.handleGroundingChunk(e);break;case`base64_image`:this.handleBase64ImageChunk(e);break;case`stop`:this.handleStopChunk();break}}async handleFinish(e){e.traceId&&(this.msgTraceId=e.traceId);let t=await this.waitForImageUploads();return await this.waitForMultimodalUploads(),this.processFinalToolCalls(e.toolCalls),this.buildFinalResult(e,t)}getOutput(){return this.output}getContentParts(){return[...this.contentParts]}getReasoningParts(){return[...this.reasoningParts]}getThinkingContent(){return this.thinkingContent}hasContentImages(){return this.contentParts.some(e=>e.type===`image`)}hasReasoningImages(){return this.reasoningParts.some(e=>e.type===`image`)}getThinkingDuration(){return this.thinkingDuration}getIsFunctionCall(){return this.isFunctionCall}getTools(){return this.tools}getTraceId(){return this.msgTraceId}getFinishType(){return this.finishType}handleTextChunk(e){this.output+=e.text,this.output=a2(this.output),this.endReasoningIfNeeded(),N7(`[text stream] messageId=%s, output length=%d, operationId=%s`,this.context.messageId,this.output.length,this.context.operationId),this.callbacks.onContentUpdate(this.output,this.buildReasoningState())}handleReasoningChunk(e){this.startReasoningIfNeeded(),this.thinkingContent+=e.text,this.callbacks.onReasoningUpdate({content:this.thinkingContent})}handleReasoningPartChunk(e){this.startReasoningIfNeeded(),e.partType===`text`?(this.appendTextToReasoningParts(e.content),this.thinkingContent+=e.content):e.partType===`image`&&e.mimeType&&this.appendImageToReasoningParts(e.content,e.mimeType);let t=this.reasoningParts.some(e=>e.type===`image`);this.callbacks.onReasoningUpdate(t?{isMultimodal:!0,tempDisplayContent:this.reasoningParts}:{content:this.thinkingContent})}handleContentPartChunk(e){this.endReasoningIfNeeded(),e.partType===`text`?(this.appendTextToContentParts(e.content),this.output+=e.content,this.output=a2(this.output)):e.partType===`image`&&e.mimeType&&this.appendImageToContentParts(e.content,e.mimeType),this.notifyContentPartUpdate()}handleToolCallsChunk(e){this.isFunctionCall=!0,this.callbacks.toggleToolCallingStreaming(this.context.messageId,e.isAnimationActives),this.throttledUpdateToolCalls(e.tool_calls),this.endReasoningIfNeeded()}handleGroundingChunk(e){let{grounding:t}=e;!t?.citations?.length&&!t?.imageResults?.length||this.callbacks.onGroundingUpdate(t)}handleBase64ImageChunk(e){this.callbacks.onImagesUpdate(e.images.map(e=>({alt:e.id,id:e.id,url:e.data})));let t=this.callbacks.uploadBase64Image(e.image.data);this.uploadTasks.set(e.image.id,t)}handleStopChunk(){this.endReasoningIfNeeded()}startReasoningIfNeeded(){this.thinkingStartAt||(this.thinkingStartAt=Date.now(),this.reasoningOperationId=this.callbacks.onReasoningStart())}endReasoningIfNeeded(){this.thinkingStartAt&&!this.thinkingDuration&&(this.thinkingDuration=Date.now()-this.thinkingStartAt,this.reasoningOperationId&&=(this.callbacks.onReasoningComplete(this.reasoningOperationId),void 0))}appendTextToReasoningParts(e){let t=this.reasoningParts.at(-1);t?.type===`text`?this.reasoningParts=[...this.reasoningParts.slice(0,-1),{text:t.text+e,type:`text`}]:this.reasoningParts=[...this.reasoningParts,{text:e,type:`text`}]}appendImageToReasoningParts(e,t){let n=`data:${t};base64,${e}`,r=this.reasoningParts.length;this.reasoningParts=[...this.reasoningParts,{image:n,type:`image`}];let i=this.callbacks.uploadBase64Image(n).then(e=>{let t=e?.url||n,i=[...this.reasoningParts];return i[r]={image:t,type:`image`},this.reasoningParts=i,t}).catch(e=>(console.error(`[reasoning_part] Image upload failed:`,e),n));this.reasoningImageUploads.set(r,i)}appendTextToContentParts(e){let t=this.contentParts.at(-1);t?.type===`text`?this.contentParts=[...this.contentParts.slice(0,-1),{text:t.text+e,type:`text`}]:this.contentParts=[...this.contentParts,{text:e,type:`text`}]}appendImageToContentParts(e,t){let n=`data:${t};base64,${e}`,r=this.contentParts.length;this.contentParts=[...this.contentParts,{image:n,type:`image`}];let i=this.callbacks.uploadBase64Image(n).then(e=>{let t=e?.url||n,i=[...this.contentParts];return i[r]={image:t,type:`image`},this.contentParts=i,t}).catch(e=>(console.error(`[content_part] Image upload failed:`,e),n));this.contentImageUploads.set(r,i)}notifyContentPartUpdate(){let e=this.contentParts.some(e=>e.type===`image`),t=this.reasoningParts.some(e=>e.type===`image`);this.callbacks.onContentUpdate(this.output,t?{duration:this.thinkingDuration,isMultimodal:!0,tempDisplayContent:this.reasoningParts}:this.thinkingContent?{content:this.thinkingContent,duration:this.thinkingDuration}:void 0,e?{isMultimodal:!0,tempDisplayContent:Ve(this.contentParts)}:void 0)}buildReasoningState(){if(this.thinkingContent)return{content:this.thinkingContent,duration:this.thinkingDuration}}async waitForImageUploads(){if(this.uploadTasks.size===0)return[];try{return(await Kte(Array.from(this.uploadTasks.values()),e=>e,{concurrency:5})).filter(e=>!!e.url)}catch(e){return console.error(`Error waiting for image uploads:`,e),[]}}async waitForMultimodalUploads(){await Promise.allSettled([...Array.from(this.contentImageUploads.values()),...Array.from(this.reasoningImageUploads.values())])}processFinalToolCalls(e){if(!e?.length)return;this.throttledUpdateToolCalls.flush(),this.callbacks.toggleToolCallingStreaming(this.context.messageId,void 0);let t=e.map(e=>({...e,function:{...e.function,arguments:e.function.arguments||`{}`}})),n=this.callbacks.transformToolCalls(t);if(n.length<t.length){let e=new Set(n.map(e=>e.id)),r=t.filter(t=>!e.has(t.id)).map(e=>e.function.name);
6004N7(`[processFinalToolCalls] unresolved tool_call names messageId=%s, operationId=%s, names=%o`,this.context.messageId,this.context.operationId,r)}this.tools=n,this.isFunctionCall=!0}buildFinalResult(e,t){let n=this.contentParts.some(e=>e.type===`image`),r=this.reasoningParts.some(e=>e.type===`image`),i=n?Ve(this.contentParts):this.output,a=this.thinkingDuration&&!isNaN(this.thinkingDuration)?this.thinkingDuration:void 0,o=e.reasoning?.signature,s;return r?s={content:Ve(this.reasoningParts),duration:a,isMultimodal:!0,signature:o}:this.thinkingContent?s={content:this.thinkingContent,duration:a,signature:o}:e.reasoning?.content&&(s={...e.reasoning,duration:a}),this.finishType=e.type,N7(`[handleFinish] messageId=%s, finishType=%s, operationId=%s`,this.context.messageId,e.type,this.context.operationId),{content:i,finishType:e.type,isFunctionCall:this.isFunctionCall,metadata:{finishType:e.type,imageList:t.length>0?t:void 0,isMultimodal:n||void 0,performance:e.speed,reasoning:s,search:e.grounding?.citations?.length||e.grounding?.imageResults?.length?e.grounding:void 0,usage:e.usage},toolCalls:e.toolCalls,tools:this.tools,traceId:this.msgTraceId,usage:e.usage}}}})),P7,yUe,F7,bUe,xUe,SUe,CUe,wUe,TUe=e((()=>{gi(),Pt(),We(),Ne(),f(),x7(),iie(),Ze(),vUe(),P7={noRetryProviders:[Rt]},yUe=Fte({errorCodeSpecs:Object.values(Ye),getErrorCodeSpec:H}),F7=e=>{if(e instanceof Error)return e;let t=e&&typeof e==`object`?e:void 0,n=typeof t?.message==`string`&&t.message||(typeof e==`string`?e:JSON.stringify(e)),r=Error(n||`LLM stream failed`);return t&&Object.assign(r,t),r},bUe=e=>{let t=e.body;if(t?.provider!==`google`)return;let n=t.context?.promptFeedback?.blockReason;if(typeof n==`string`)return n;let r=t.context?.finishReason;return typeof r==`string`?r:void 0},xUe=e=>{let t=bUe(e);if(!t)return e;let n=`response.GoogleAIBlockReason.${t}`,r=o(n,{defaultValue:e.message??``,ns:`error`}).trim();return!r||r===n?e:{...e,body:{...e.body&&typeof e.body==`object`?e.body:{},message:r},message:r}},SUe=(e,t)=>{let n=e&&typeof e==`object`?e:{},r=n.body&&typeof n.body==`object`?n.body:n;return xUe({...n,body:{...r,...t&&{traceId:t}},message:typeof n.message==`string`?n.message:e instanceof Error?e.message:String(e),type:n.errorType??n.type??be.UnknownChatFetchError})},CUe=class{get;operationId;session;constructor(e,t,n){this.get=e,this.operationId=t,this.session=n}classifyError(e){return yUe(e)}maxAttempts(e){return Ute(e,P7)}onError({error:e,interrupted:t}){if(t||!this.session.assistantMessageId)return;let n=SUe(e,this.get().operations[this.operationId]?.metadata?.traceId);e&&typeof e==`object`&&Object.assign(e,n),this.get().internal_dispatchMessage({id:this.session.assistantMessageId,type:`updateMessage`,value:{error:n}},{operationId:this.operationId})}onRetry(e){}resolveRetryBudget(e){return Nte(e,P7)}async waitForRetry(e){await w(e)}},wUe=class{context;retryPolicy;constructor(e){this.context=e,this.retryPolicy=new CUe(e.get,e.operationId,e.session)}async runAttempt(e){let t=this.context.get().operations[this.context.operationId];if(!t)throw Error(`Operation not found: ${this.context.operationId}`);let n=this.context.session.assistantMessageId;if(!n)throw Error(`Client call_llm stream started without a message id`);let{groupId:r,subAgentId:i,topicId:a}=t.context,o=r&&i?i:t.context.agentId,s=e.context.modelParameters;if(!s)throw Error(`Client call_llm requires prepared model parameters`);let c=(e.context.resolvedTools?.tools??[]).map(e=>e.function.name),l=new _Ue({agentId:o,groupId:r,messageId:n,operationId:this.context.operationId,topicId:a},{onContentUpdate:(e,t,r)=>{this.dispatchMessage(n,{content:e,reasoning:t,...r&&{metadata:{isMultimodal:r.isMultimodal,tempDisplayContent:r.tempDisplayContent}}})},onGroundingUpdate:e=>this.dispatchMessage(n,{search:e}),onImagesUpdate:e=>this.dispatchMessage(n,{imageList:e}),onReasoningComplete:e=>this.context.get().completeOperation(e),onReasoningStart:()=>{let{operationId:e}=this.context.get().startOperation({context:{...t.context,agentId:o,messageId:n},parentOperationId:this.context.operationId,type:`reasoning`});return this.context.get().associateMessageWithOperation(n,e),e},onReasoningUpdate:e=>this.dispatchMessage(n,{reasoning:e}),onToolCallsUpdate:e=>this.dispatchMessage(n,{tools:e}),toggleToolCallingStreaming:this.context.get().internal_toggleToolCallingStreaming,transformToolCalls:e=>this.context.get().internal_transformToolCalls(e,c),uploadBase64Image:e=>oie().uploadBase64FileWithProgress(e).then(e=>({alt:e?.filename||e?.id,id:e?.id,url:e?.url}))}),u,d={},f,p=!1,m=()=>{p||(p=!0,e.onFirstChunk?.())};try{await b7.getChatCompletion({...s.params,messages:e.context.messages,model:e.model,provider:e.provider},{...s.options,metadata:this.context.metadata,onErrorHandle:e=>{f=F7(e)},onFinish:async(e,{traceId:t,observationId:n,toolCalls:r,reasoning:i,grounding:a,usage:o,speed:s,type:c})=>{d={grounding:a,observationId:n,reasoning:i,speed:s,toolCalls:r,traceId:t,type:c,usage:o},u=await l.handleFinish(d)},onMessageHandle:async e=>{m(),l.handleChunk(e)},signal:t.abortController.signal})}catch(e){f=e}let h=t.abortController.signal.aborted||this.context.get().operations[this.context.operationId]?.status===`cancelled`;h&&!d.type&&(d.type=`abort`),h&&u&&!u.finishType&&(u={...u,finishType:`abort`,metadata:{...u.metadata,finishType:`abort`}}),u??=await l.handleFinish(d);let g=this.buildAttemptOutput(l,u,d);return f&&!h?{error:f,ok:!1,output:g}:he({content:g.content,hasGrounding:!!g.grounding,imageCount:g.imageList.length+ +!!g.hasContentImages,outputTokens:g.usage?.totalOutputTokens,reasoning:g.thinkingContent,toolCallCount:g.toolsCalling.length+g.toolCalls.length})&&!h?{error:new qe(void 0,{attempt:e.attempt,contentLength:g.content.length,cost:g.usage?.cost,finishReason:g.finishReason,imageCount:g.imageList.length,maxAttempts:e.maxAttempts,model:e.model,outputTokens:g.usage?.totalOutputTokens,provider:e.provider,reasoningLength:g.thinkingContent.length,toolCallCount:g.toolsCalling.length+g.toolCalls.length}),ok:!1,output:g}:{ok:!0,output:g}}async stream(e,t,n){let r=``,i=``,a,o;if(await b7.getChatCompletion(e,{onErrorHandle:e=>{o=F7(e),t?.onError?.(o)},onFinish:async(e,t)=>{r=e||r,i=t.reasoning?.content||i,a=t.usage},onMessageHandle:e=>{let n=e;t?.onChunk?.(n),n.type===`text`&&(r+=n.text,t?.onText?.(n.text)),n.type===`reasoning`&&(i+=n.text)},signal:n}),o)throw o;let s={content:r,reasoning:i,usage:a};return t?.onFinish?.(s),s}buildAttemptOutput(e,t,n){let r=e.getOutput(),i=e.getThinkingContent(),a=t.metadata.reasoning,o=!1;return(t.finishType===`end_turn`||t.finishType===`stop`)&&!r.trim()&&i.trim()&&!e.hasReasoningImages()&&!t.tools?.length&&!t.toolCalls?.length&&(r=i,i=``,a=void 0,o=!0),{answerSalvagedFromReasoning:o,content:r,contentParts:e.getContentParts(),finishReason:t.finishType,grounding:t.metadata.search??null,hasContentImages:e.hasContentImages(),hasReasoningImages:e.hasReasoningImages(),imageList:t.metadata.imageList??[],observationId:n.observationId??void 0,reasoning:a,reasoningParts:e.getReasoningParts(),speed:t.metadata.performance,thinkingContent:i,toolCalls:t.toolCalls??[],toolsCalling:t.tools??[],traceId:n.traceId??void 0,usage:t.usage}}
6004dispatchMessage(e,t){this.context.get().internal_dispatchMessage({id:e,type:`updateMessage`,value:t},{operationId:this.context.operationId})}}})),EUe,DUe=e((()=>{Ne(),R(),Na(),EUe=class{get;messageKey;operationId;constructor(e,t,n){this.get=e,this.messageKey=t,this.operationId=n}createAssistantMessage(e){let t=this.get().operations[this.operationId];if(!t)throw Error(`Operation not found: ${this.operationId}`);let{agentId:n,groupId:r,isSupervisor:i,scope:a,subAgentId:o,threadId:s,topicId:c}=t.context,l=o&&a!==`sub_agent`?o:n,u={...e.metadata,...i&&{isSupervisor:!0},...a===`sub_agent`&&o&&{scope:a,subAgentId:o}};return this.createMessage({...e,...l&&{agentId:l},...r&&{groupId:r},...Object.keys(u).length>0&&{metadata:u},...s&&{threadId:s},...c&&{topicId:c}})}createToolMessage(e){return this.createMessage(e)}createToolMessageForOperation(e,t){return this.createMessage(e,t)}async deleteMessage(e){await this.get().optimisticDeleteMessage(e,{operationId:this.operationId})}async findById(e){for(let t of this.getMessages()){if(t.id===e)return t;let n=t.compressedMessages?.find(t=>t.id===e);if(n)return n}}async query(e,t){return this.getMessages()}async update(e,t){let n=this.get(),r={operationId:this.operationId};n.internal_dispatchMessage({id:e,type:`updateMessage`,value:t},r),await this.persist([{id:e,type:`updateMessage`,value:t}])}async updatePluginState(e,t){this.get().internal_dispatchMessage({id:e,type:`updateMessage`,value:{pluginState:t}},{operationId:this.operationId}),await this.persist([{id:e,type:`updateToolMessage`,value:{pluginState:t}}])}async updateToolMessage(e,t){let n=this.get(),r={operationId:this.operationId},i=t.pluginError;n.internal_dispatchMessage({id:e,type:`updateMessage`,value:{content:t.content,metadata:t.metadata,pluginState:t.pluginState}},r),i!==void 0&&n.internal_dispatchMessage({id:e,type:`updateMessagePlugin`,value:{error:i}},r),await this.persist([{id:e,type:`updateToolMessage`,value:{...t,pluginError:i}}])}async createMessage(e,t=this.operationId){let n=this.get(),r=e.id??ke(),i={...e,id:r},a={operationId:t};n.internal_dispatchMessage({id:r,type:`createMessage`,value:{...i}},a);try{await this.persist([{message:i,type:`createMessage`}])}catch(t){let i=Error(`Failed to create ${e.role} message`,{cause:t});throw n.internal_dispatchMessage({id:r,type:`updateMessage`,value:{error:{body:t,message:i.message,type:be.CreateMessageError}}},a),i}return i}async persist(e){await Ma.batchMutateOrThrow(e)}getMessages(){return this.get().dbMessagesMap[this.messageKey]??[]}}})),OUe,kUe,AUe=e((()=>{Ne(),OUe=e=>{if(e&&typeof e==`object`){let t=e,n=t.errorType??t.type??be.UnknownChatFetchError;return{...t,body:t.body,message:typeof t.message==`string`?t.message:String(e),type:n}}return{body:e,message:e instanceof Error?e.message:String(e),type:be.UnknownChatFetchError}},kUe=class{get;operationId;session;constructor(e,t,n){this.get=e,this.operationId=t,this.session=n}async publishChunk(){}async publishError({error:e}){this.session.assistantMessageId&&this.get().internal_dispatchMessage({id:this.session.assistantMessageId,type:`updateMessage`,value:{error:OUe(e)}},{operationId:this.operationId})}async publishEvent(e){if(e.type===`stream_start`){let t=e.data.assistantMessage;if(!t?.id)return;this.session.assistantMessageId=t.id,this.get().associateMessageWithOperation(t.id,this.operationId);return}if(e.type===`stream_retry`){let t=e.data;this.get().updateOperationMetadata(this.operationId,{streamRetry:{attempt:t.attempt,delayMs:t.delayMs,error:t.errorType,maxAttempts:t.maxAttempts}});return}if(e.type===`stream_end`){this.get().updateOperationMetadata(this.operationId,{streamRetry:void 0});return}e.type===`visible_output_end`&&this.get().updateOperationMetadata(this.operationId,{visibleLoadingDone:!0})}}})),jUe,MUe,NUe,PUe,FUe,IUe=e((()=>{Wa(),jUe=18e5,MUe=3e3,NUe=e=>e instanceof Error?e.message:typeof e==`string`?e:`Unknown error`,PUe=(e,t)=>t.aborted?Promise.resolve():new Promise(n=>{let r=()=>{clearTimeout(i),n()},i=setTimeout(()=>{t.removeEventListener(`abort`,r),n()},e);t.addEventListener(`abort`,r,{once:!0})}),FUe=class{get;operationId;constructor(e,t){this.get=e,this.operationId=t}execSubAgent(e){return this.execute(e)}execVirtualSubAgent(e){return this.execute(e)}async execute(e){let t,n,r=()=>(n||=(async()=>
6004{if(t?.threadId)try{await Ga.interruptTask({threadId:t.threadId})}catch{}})(),n);try{if(t=await Ga.execSubAgentTask(e),!t.success)return{...t,error:t.error??`Sub-agent dispatch failed`,status:`failed`};let n=this.get().operations[this.operationId];if(!n)throw Error(`Operation not found: ${this.operationId}`);let i=n.abortController.signal,a=e.timeout??jUe,o=Date.now(),s=()=>void r();i.addEventListener(`abort`,s,{once:!0});try{for(;Date.now()-o<a;){let n=this.get().operations[this.operationId];if(i.aborted||n?.status===`cancelled`)return await r(),{...t,error:`Operation cancelled`,status:`cancelled`,success:!1};let s=await Ga.getSubAgentTaskStatus({threadId:t.threadId});if(i.aborted||this.get().operations[this.operationId]?.status===`cancelled`)return await r(),{...t,error:`Operation cancelled`,status:`cancelled`,success:!1};if(s.taskDetail&&this.get().internal_dispatchMessage({id:e.parentMessageId,type:`updateMessage`,value:{taskDetail:s.taskDetail}},{operationId:this.operationId}),s.status===`completed`)return{...t,result:s.result,status:`completed`,success:!0};if(s.status===`failed`)return{...t,error:s.error??`Unknown error`,status:`failed`,success:!1};if(s.status===`cancel`)return{...t,error:`Task was cancelled`,status:`cancelled`,success:!1};let c=a-(Date.now()-o);await PUe(Math.min(MUe,c),i)}return await r(),{...t,error:`Task timeout after ${a}ms`,status:`timed_out`,success:!1}}finally{i.removeEventListener(`abort`,s)}}catch(e){return t?.success&&await r(),{assistantMessageId:t?.assistantMessageId??``,error:NUe(e),operationId:t?.operationId??``,status:`failed`,success:!1,threadId:t?.threadId??``}}}}})),LUe,RUe,zUe=e((()=>{LUe=e=>typeof e==`number`&&Number.isFinite(e)?e:null,RUe=({cost:e,now:t=new Date,usage:n})=>({cumulativeCost:LUe(e?.total),cumulativeUsage:e||n?{capturedAt:t.toISOString(),cost:e??null,usage:n??null}:null})})),BUe,VUe,HUe,UUe=e((()=>{GBe(),BUe=t(F()),B6(),zUe(),VUe=(0,BUe.default)(`lobe-store:client-work-registration`),HUe=async({agentId:e,intent:t,rootOperationId:n,sourceMessageId:r,sourceToolCallId:i,sourceToolIdentifier:a,sourceToolName:o,state:s,threadId:c,topicId:l})=>{let u=RUe({cost:s.cost,usage:s.usage});try{await WBe(t,{deleteTaskWork:e=>z6.deleteTaskWork(e),handleSkillToolResult:e=>z6.handleSkillToolResult(e),registerDocument:e=>z6.registerDocument(e),registerTask:e=>z6.registerTask(e)},{agentId:e,...u,messageId:r,rootOperationId:n,threadId:c,toolCallId:i,toolIdentifier:a,toolName:o,topicId:l})}catch(e){VUe(`registerClientWorkFromIntent failed for toolCallId=%s: %O`,i,e)}}})),WUe,I7,GUe,KUe=e((()=>{B6(),P8(),UUe(),WUe={"lobe-web-browsing/craw":.002,"lobe-web-browsing/search":.001},I7=`Tool execution was cancelled by user.`,GUe=class{get;messageKey;operationId;messages;canRunClientTools=!0;maxRetries=0;constructor(e,t,n,r){this.get=e,this.messageKey=t,this.operationId=n,this.messages=r}getCost(e){return WUe[e]??0}async run(e,t){let n=this.get(),r=n.operations[this.operationId];if(!r)throw Error(`Operation not found: ${this.operationId}`);let i=r.context,a=n.dbMessagesMap[this.messageKey]??[],o=t.reuseExistingMessage?a.find(e=>e.id===t.parentMessageId):void 0,s=a.find(e=>e.id===t.parentMessageId&&e.role===`assistant`)??(o?.parentId?a.find(e=>e.id===o.parentId&&e.role===`assistant`):void 0)??(i.messageId?a.find(e=>e.id===i.messageId&&e.role===`assistant`):void 0)??a.findLast(e=>e.role===`assistant`),c=i.sourceMessageId??s?.parentId??(i.messageId===s?.id?void 0:i.messageId),l=i.subAgentId&&i.scope!==`sub_agent`?i.subAgentId:i.agentId,{operationId:u}=n.startOperation({context:{agentId:i.agentId,groupId:i.groupId,scope:i.scope,sourceMessageId:c,threadId:i.threadId,topicId:i.topicId,viewedTask:i.viewedTask},metadata:{apiName:e.apiName,identifier:e.identifier,startTime:Date.now(),tool_call_id:e.id},parentOperationId:this.operationId,type:`toolCalling`});try{let r=t.reuseExistingMessage?t.parentMessageId:await this.createToolMessage({assistantGroupId:s?.groupId??void 0,call:e,effectiveAgentId:l,parentMessageId:t.parentMessageId,toolOperationId:u});if(n.operations[u]?.abortController.signal.aborted)return this.createInterruptedExecution(r);let{operationId:i}=n.startOperation({context:{messageId:r},metadata:{startTime:Date.now(),tool_call_id:e.id},parentOperationId:u,type:`executeToolCall`});n.onOperationCancel(i,async()=>{await this.markMessageCancelled(r,i)});let a=performance.now(),o,c;try{o=await n.internal_invokeDifferentTypePlugin(r,e,t.stepContext)}finally{c=N8(e.id)}if(n.operations[i]?.abortController.signal.aborted)return this.createInterruptedExecution(r);n.completeOperation(i);let d=Math.round(performance.now()-a),f=this.normalizeResult(o,t.toolName,d);return f.success?n.completeOperation(u):n.failOperation(u,{message:this.errorMessage(f.error),type:`ToolExecutionError`}),o!=null&&(c&&(f.workRegistration=c),R6({apiName:e.apiName,identifier:e.identifier,result:f,succeeded:f.success,workRegistration:!!c})&&this.scheduleWorkRefresh()),{attempts:1,result:f,resultPersisted:o!=null,toolMessageId:r}}catch(e){throw n.failOperation(u,{message:this.errorMessage(e),type:`ToolExecutionError`}),e}}async registerWork(e){let t=this.get().operations[this.operationId]?.context;await HUe({agentId:t?.agentId,intent:e.intent,rootOperationId:this.operationId,sourceMessageId:e.sourceMessageId,sourceToolCallId:e.sourceToolCallId,sourceToolIdentifier:e.sourceToolIdentifier,sourceToolName:e.sourceToolName,state:e.state,threadId:t?.threadId,topicId:t?.topicId??void 0})}scheduleWorkRefresh(){let e=this.get(),t=e.operations[this.operationId];if(!t||t.metadata.workRefreshScheduled)return;e.updateOperationMetadata(this.operationId,{workRefreshScheduled:!0});let{threadId:n,topicId:r}=t.context;e.registerAfterCompletionCallback(this.operationId,()=>z6.refreshConversation(r??void 0,n))}async createToolMessage(e){let t=this.get(),n=t.operations[this.operationId].context,{operationId:r}=t.startOperation({context:{agentId:n.agentId,threadId:n.threadId,topicId:n.topicId},metadata:{startTime:Date.now(),tool_call_id:e.call.id},parentOperationId:e.toolOperationId,type:`createToolMessage`});t.onOperationCancel(r,async({metadata:e})=>{let t=await e?.createMessagePromise;t&&await this.markMessageCancelled(t.id,r)});let i={agentId:e.effectiveAgentId,content:``,groupId:e.assistantGroupId,parentId:e.parentMessageId,plugin:e.call,role:`tool`,threadId:n.threadId,tool_call_id:e.call.id,topicId:n.topicId??void 0},a=this.messages.createToolMessageForOperation(i,r);t.updateOperationMetadata(r,{createMessagePromise:a});let o;try{o=await a}catch(n){let i=n instanceof Error?n.message:`Failed to create tool message for tool_call_id: ${e.call.id}`;throw t.failOperation(r,{message:i,type:`CreateMessageError`}),n}return t.completeOperation(r),o.id}createInterruptedExecution(e){return{attempts:0,interrupted:!0,result:{content:I7,success:!1},resultPersisted:!0,toolMessageId:e}}errorMessage(e){if(e instanceof Error)return e.message;if(typeof e==`string`)return e;if(e&&typeof e==`object`){let t=e.message;if(typeof t==`string`)return t}return`Tool execution failed`}async markMessageCancelled(e,t){let n=this.get();await Promise.all([n.optimisticUpdateMessageContent(e,I7,void 0,{operationId:t}),n.optimisticUpdateMessagePlugin(e,{intervention:{status:`aborted`}},{operationId:t})])}normalizeResult(e,t,n){return e==null?{content:`Tool ${t} execution failed: no result returned`,error:{message:`Tool returned no result`,type:`ToolExecutionError`},executionTime:n,success:!1}:{...e,content:typeof e.content==`string`?e.content:JSON.stringify(e),executionTime:n,success:typeof e.success==`boolean`?e.success:!e.error}}}})),qUe,JUe=e((()=>{pUe(),hUe(),TUe(),DUe(),AUe(),IUe(),KUe(),qUe=e=>{let t=e.get().operations[e.operationId];if(!t)throw Error(`Operation not found: ${e.operationId}`);let{agentId:n,groupId:r,scope:i,subAgentId:a,threadId:o,topicId:s}=t.context,c=a&&i!==`sub_agent`?a:n,l=new EUe(e.get,e.messageKey,e.operationId),u={},d=new kUe(e.get,e.operationId,u);return{operation:{agentId:c??void 0,groupId:r??void 0,operationId:e.operationId,stepIndex:e.stepIndex,threadId:o??void 0,topicId:s??void 0},transports:{compression:new fUe(e.get,e.messageKey,e.operationId),context:new mUe({agentConfig:e.agentConfig,get:e.get,metadata:e.metadata,operationId:e.operationId,runtimeContext:e.runtimeContext,toolsEngine:e.toolsEngine}),llm:new wUe({get:e.get,metadata:e.metadata,operationId:e.operationId,session:u}),messages:l,operationStore:{clearRunningMark:async()=>{},loadState:async t=>e.get().operations[t]?.status===`cancelled`?{status:`interrupted`}:null}
6004,stream:d,subAgent:new FUe(e.get,e.operationId),tools:new GUe(e.get,e.messageKey,e.operationId,l)}}}})),YUe,XUe=e((()=>{gi(),JUe(),YUe=e=>Pte((t,n,r)=>qUe({agentConfig:e.agentConfig,get:e.get,metadata:e.metadata,messageKey:e.messageKey,operationId:e.operationId,runtimeContext:r,stepIndex:n.stepCount,toolsEngine:e.toolsEngine}))})),ZUe,L7,QUe,$Ue,eWe,tWe,nWe=e((()=>{gi(),UK(),ni(),Tq(),iY(),Wt(),Mi(),ZUe=t(F()),lUe(),Wa(),ao(),y7(),ro(),Na(),Gr(),qr(),Ra(),Are(),XUe(),Oi(),Es(),Ste(),zs(),wi(),Vr(),fte(),Z6(),A5(),Ta(),pte(),qs(),L7=(0,ZUe.default)(`lobe-store:streaming-executor`),QUe={pathScopeAudit:Kee({areAllPathsSafe:async({paths:e,resolveAgainstScope:t})=>!1})},$Ue=e=>{if(!e)return!1;let t=e=>e?e.type===`refer-topic`?!0:Array.isArray(e.children)?e.children.some(t):!1:!1;return t(e.root)},eWe=e=>({hasImages:e.some(e=>e.role===`user`&&!!e.imageList?.length),hasVideos:e.some(e=>e.role===`user`&&!!e.videoList?.length)}),tWe=class{#e;constructor(e,t,n){this.#e=t}internal_createAgentState=({messages:e,parentMessageId:t,agentId:n,disableTools:r,topicId:i,threadId:a,initialState:o,initialContext:s,operationId:c,subAgentId:l,isSubAgent:u,modelOverride:d})=>{let{activeAgentId:f,activeTopicId:p}=this.#e(),m=n||f,h=i===void 0?p:i,g=l||m,_=c?this.#e().operations[c]:void 0,v=_?.context.scope,y=_?.context.groupId,b=VVe({agentId:g||``,disableTools:r,groupId:y,isSubAgent:u,scope:v}),x=d&&b.agentConfig?{...b,agentConfig:{...b.agentConfig,...d}}:b,{agentConfig:S,plugins:C}=x,w=s?.initialContext?.selectedTools?.map(e=>e.identifier);if(!S||!S.model)throw Error(`[internal_createAgentState] Agent config not found or incomplete for agentId: ${g}, scope: ${v}`);let T=e.some(e=>$Ue(e.editorData)),E=eWe(e),D=Qee(),O=!!D&&nte.enableVisualUnderstanding(D)&&(E.hasImages&&!oo(S.model,S.provider)||E.hasVideos&&!co(S.model,S.provider)),k=[...new Set([...C||[],...T?[`lobe-topic-reference`]:[],...O?[yK.identifier]:[]])],A=k.length>0?k:void 0,j=w&&w.length>0?[...new Set([...k,...w])]:A;L7(`[internal_createAgentState] resolved plugins=%o, isSubAgent=%s, disableTools=%s, hasTopicReference=%s`,A,u,r,T);let M=M7({model:S.model,provider:S.provider},j,{isSubAgent:u,scope:v}),N=x.chatConfig?.skillActivateMode===`manual`,P=M.generateToolsDetailed({excludeDefaultToolIds:N?ZJ:void 0,model:S.model,provider:S.provider,skipDefaultTools:r||void 0,toolIds:j}),{enabledToolIds:F,enabledManifests:I,tools:L}=uHe({context:{isPageEditorReady:k5.isReady(),scope:v},injectedManifests:s?.initialContext?.injectedManifests,toolsDetailed:P}),ee=Object.fromEntries(I.map(e=>[e.identifier,e])),R={...x,enabledManifests:I,enabledToolIds:F,tools:L};L7(`[internal_createAgentState] toolManifestMap keys=%o, count=%d`,Object.keys(ee),Object.keys(ee).length);let te=_r(),z={approvalMode:xa.approvalMode(te),allowList:xa.allowList(te)},ne={compressionModel:{model:S.model,provider:S.provider},model:S.model,provider:S.provider},B=vi.currentTopicWorkingDirectory(this.#e()),V=ur().gatewayDeviceInfo?.deviceId,H=Rr.currentAgentWorkingDirectory(V)(Xr()),re=B??H,ie=o||yi.createInitialState({maxSteps:400,messages:e,metadata:{agentId:m,groupId:y,sessionId:m,scope:v,subAgentId:l,threadId:a,topicId:h,workingDirectory:re},modelRuntimeConfig:ne,operationId:c??m,operationToolSet:{enabledToolIds:F,manifestMap:ee,sourceMap:{},tools:P.tools??[]},toolManifestMap:ee,userInterventionConfig:z}),ae={...ie,metadata:{...ie.metadata,agentId:m,groupId:y,scope:v,subAgentId:l,threadId:a,topicId:h}},oe;if(v===`page`&&F.includes(`lobe-page-agent`))try{let e=k5.getPageContentContext(`both`);oe={pageEditor:{markdown:e.markdown||``,xml:e.xml||``,metadata:{title:e.metadata.title,charCount:e.metadata.charCount,lineCount:e.metadata.lineCount}}},L7(`[internal_createAgentState] Page Agent detected, injected initialContext.pageEditor with title: %s`,e.metadata.title)}catch(e){L7(`[internal_createAgentState] Failed to get page content context: %o`,e)}let se=_?.context.viewedTask;if(se)try{let e=Y6(),t;if(se.type===`list`)t=hne({defaultAssigneeAgentId:_.context.defaultTaskAssigneeAgentId,tasks:e.tasks,total:e.tasksTotal||e.tasks.length});else{let n=e.taskDetailMap[se.taskId];n&&(t=wne({defaultAssigneeAgentId:_.context.defaultTaskAssigneeAgentId,task:n}))}t&&(oe={...oe,taskManager:{contextPrompt:t}},L7(`[internal_createAgentState] injected taskManager context (route=%s)`,se.type))}catch(e){L7(`[internal_createAgentState] Failed to build task manager context: %o`,e)}let ce=oe||s?.initialContext?{...oe,...s?.initialContext}:void 0,le={model:S.model,parentMessageId:t,provider:S.provider},ue=s?.payload&&typeof s.payload==`object`?s.payload:void 0;return{agentConfig:R,context:s?{...s,payload:{...le,...ue},initialContext:ce}:{phase:`init`,payload:le,session:{sessionId:m,messageCount:e.length,status:ae.status,stepCount:0},initialContext:ce},state:ae,toolsEngine:M}};executeClientAgent=async e=>{let{disableTools:t,messages:n,parentMessageId:r,parentMessageType:i,context:a,isSubAgent:o}=e,{agentId:s,topicId:c,threadId:l,subAgentId:u,groupId:d,scope:f}=a,p=u||s,m=li(a),h=e.operationId;if(!h){let{operationId:t}=this.#e().startOperation({type:`execAgentRuntime`,context:{...a,...o?{isSubAgent:!0}:{},messageId:r},parentOperationId:e.parentOperationId,label:`AI Generation`,metadata:{inThread:e.inPortalThread||!1}});h=t,this.#e().associateMessageWithOperation(r,h)}L7(`[executeClientAgent] start, operationId: %s, agentId: %s, subAgentId: %s, scope: %s, effectiveAgentId: %s, topicId: %s, messageKey: %s, parentMessageId: %s, parentMessageType: %s, messages count: %d, disableTools: %s`,h,s,u,f,p,c,m,r,i,n.length,t),Ts({payload:{agentId:s,operationId:h,parentMessageId:r,parentMessageType:i,threadId:l??void 0,topicId:c??void 0,...i===`user`?{triggerMessageId:r}:{}},sourceId:`${h}:client:start`,sourceType:`client.runtime.start`}),c&&!o&&(this.#e().updateTopicStatus?.({agentId:s,groupId:d,...f===`group`||f===`group_agent`?{scope:f}:{},status:`running`,topicId:c}))?.catch(e=>{console.error(`[streamingExecutor] running status write failed:`,e)});let g=[...n];
6004await za().ensureAiProviderRuntimeStateReady();let{state:_,context:v,agentConfig:y,toolsEngine:b}=this.#e().internal_createAgentState({messages:g,parentMessageId:e.parentMessageId,agentId:s,disableTools:t,topicId:c,threadId:l??void 0,initialState:e.initialState,initialContext:e.initialContext,operationId:h,subAgentId:u,isSubAgent:o,modelOverride:e.modelOverride});e.skipCreateFirstMessage&&(_.pendingAssistantMessageId=e.parentMessageId,v.payload={...v.payload,assistantMessageId:e.parentMessageId});let{agentConfig:x}=y,S=x.model,C=x.provider,w={model:S,provider:C,compressionModel:{model:S,provider:C}};L7(`[executeClientAgent] Creating agent runtime with config`,w);let T=La.modelContextWindowTokens(S,C)(za()),E=new yi(new Lte({agentConfig:{maxSteps:1e3},compressionConfig:{enabled:x.chatConfig?.enableContextCompression??!0,maxWindowToken:T??void 0},dynamicInterventionAudits:QUe,operationId:`${m}/${e.parentMessageId}`,modelRuntimeConfig:w}),{executors:YUe({agentConfig:y,get:this.#e,metadata:e.metadata,messageKey:m,operationId:h,toolsEngine:b}),getOperation:e=>{let t=this.#e().operations[e];if(!t)throw Error(`Operation not found: ${e}`);return{abortController:t.abortController,context:t.context}},operationId:h}),D=_,O=v;L7(`[executeClientAgent] Agent runtime loop start, initial phase: %s`,O.phase);let k=m,A=0;for(;D.status!==`done`&&D.status!==`error`;){if(this.#e().operations[h]?.status===`cancelled`){L7(`[executeClientAgent] Operation cancelled, marking state as interrupted`),D={...D,status:`interrupted`},D=(await E.step(D,O)).newState,L7(`[executeClientAgent] Operation cancelled, stopping loop`);break}A++;let e=this.#e().dbMessagesMap[m]||[],t=bte(e),n=Ote(e)?.filter(e=>f===`page`||e!==`lobe-page-agent`),r=Bte({activatedSkills:Tte(e),activatedToolIds:n,hasQueuedMessages:(this.#e().queuedMessages[k]?.length??0)>0,todos:t});if(f===`page`&&O.initialContext?.pageEditor)try{r.stepPageEditor={xml:k5.getPageContentContext(`xml`).xml||``}}catch(e){L7(`[executeClientAgent] Failed to get page XML for step: %o`,e)}O={...O,stepContext:r},L7(`[executeClientAgent][step-%d]: phase=%s, status=%s, state.messages=%d, dbMessagesMap[%s]=%d, stepContext=%O`,A,O.phase,D.status,D.messages.length,m,e.length,r);let i=await E.step(D,O);L7(`[executeClientAgent] Step %d completed, events: %d, newStatus=%s, newState.messages=%d`,A,i.events.length,i.newState.status,i.newState.messages.length),i.nextContext?.phase&&[`sub_agents_batch_result`,`tools_batch_result`].includes(i.nextContext?.phase)&&(L7(`[executeClientAgent] ${i.nextContext?.phase} completed, refreshing messages to sync state`),await this.#e().refreshMessages(a));for(let e of i.events)switch(e.type){case`done`:L7(`[executeClientAgent] Received done event`);break;case`human_approve_required`:await Ls(this.#e,a),c&&(this.#e().updateTopicStatus?.({agentId:s,groupId:d,...a.scope===`group`||a.scope===`group_agent`?{scope:a.scope}:{},status:`waitingForHuman`,topicId:c}))?.catch(e=>{console.error(`[streamingExecutor] updateTopicStatus failed:`,e)});break;case`error`:{L7(`[executeClientAgent] Received error event: %o`,e.error);let t=(this.#e().messagesMap[m]||[]).findLast(e=>e.role===`assistant`);t&&await Ma.updateMessageError(t.id,e.error,{agentId:s,groupId:d,topicId:c});let n=this.#e().messagesMap[m]||[];this.#e().replaceMessages(n,{context:a});break}}if(D=i.newState,this.#e().operations[h]?.status===`cancelled`){L7(`[executeClientAgent] Operation cancelled after step %d, marking state as interrupted`,A),D={...D,status:`interrupted`};let e=i.nextContext||O;D=(await E.step(D,e)).newState,L7(`[executeClientAgent] Operation cancelled, stopping loop`);break}if(!i.nextContext){L7(`[executeClientAgent] No next context, stopping loop`);break}O={...i.nextContext,initialContext:O.initialContext}}L7(`[executeClientAgent] Agent runtime loop finished, final status: %s, total steps: %d`,D.status,A),await this.#e().refreshMessages(a);let j=f===`sub_agent`?`sub_agent`:`top_level`,M=Ks(this.#e,{context:a,parentMessageId:r,parentMessageType:i,runId:h,runScope:j,runtimeType:`client`}),N={context:a,operationId:h,runId:h,runScope:j,runtimeType:`client`};if(zte(D.status)){await M.onRunParked({...N,reason:D.status});return}let P={...N,runtimeStatus:D.status},{requeued:F}=await M.completeRun(P);if(!F)return await M.afterRunComplete(P),{cost:D.cost,model:S,provider:C??void 0,usage:D.usage}};runClientSubAgent=async e=>{let{agentId:t,topicId:n,instruction:r,description:i,inheritMessages:a,toolMessageId:o,parentOperationId:s}=e,c=`runClientSubAgent:${o}`;try{let e=await Ga.createClientTaskThread({agentId:t,instruction:r,parentMessageId:o,title:i,topicId:n});if(!e.success)return L7(`[%s] Failed to create client task thread`,c),{error:`Failed to create sub-agent thread`,result:`Failed to create sub-agent thread`,success:!1,threadId:``};
6004let{threadId:l,userMessageId:u,threadMessages:d}=e;L7(`[%s] Created thread %s, userMessage %s`,c,l,u),this.#e().refreshThreads();let f=s?this.#e().operations[s]?.context.workspaceSlug:void 0,p={agentId:t,isSubAgent:!0,scope:`thread`,threadId:l,topicId:n,...f?{workspaceSlug:f}:{}},{operationId:m}=this.#e().startOperation({context:p,metadata:{executionMode:`client`,startTime:Date.now(),taskDescription:i},parentOperationId:s,type:`execClientSubAgent`});this.#e().replaceMessages(d,{context:p});let h=[...d];a&&(h=[...(this.#e().dbMessagesMap[li({agentId:t,topicId:n})]||[]).filter(e=>e.role!==`task`),...h],this.#e().replaceMessages(h,{context:p}));let g=Rr.getAgentConfigById(t)(Xr()),_=await this.#e().executeClientAgent({context:p,isSubAgent:!0,messages:h,modelOverride:wt(g?.agencyConfig?.subagent),operationId:m,parentMessageId:u,parentMessageType:`user`,parentOperationId:s,userMessageId:u}),v=li(p),y=this.#e().dbMessagesMap[v]||[],b=y.findLast(e=>e.role===`assistant`)?.content||`Task completed`,x=y.filter(e=>e.role===`tool`).length,{usage:S,cost:C,model:w}=_||{},T=C?.total,E=S?.llm?.tokens?.input,D=S?.llm?.tokens?.output,O=S?.llm?.tokens?.total;return await Ga.updateClientTaskThreadStatus({completionReason:`done`,metadata:{totalCost:T,totalMessages:y.length,totalTokens:O,totalToolCalls:x},resultContent:b,threadId:l}),this.#e().completeOperation(m),L7(`[%s] Completed, result %d chars`,c,b.length),{model:w,result:b,success:!0,threadId:l,totalCost:T,totalInputTokens:E,totalOutputTokens:D,totalToolCalls:x,totalTokens:O}}catch(e){let t=e instanceof Error?e.message:`Unknown error`;return L7(`[%s] Error: %O`,c,e),{error:t,result:`Sub-agent execution failed: ${t}`,success:!1,threadId:``}}}}})),rWe,R7,iWe,aWe,oWe,sWe,cWe,lWe=e((()=>{rWe=3e4,R7=1e3,iWe=3e4,aWe=3,oWe=500,sWe=class{listeners=new Map;on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,...t){let n=this.listeners.get(e);if(n)for(let r of n)try{r(...t)}catch(t){console.error(`[AgentStreamClient] Error in ${e} listener:`,t)}}removeAllListeners(){this.listeners.clear()}},cWe=class extends sWe{ws=null;heartbeatTimer=null;reconnectTimer=null;reconnectDelay=R7;missedHeartbeats=0;_status=`disconnected`;intentionalDisconnect=!1;lastEventId=``;sessionEnded=!1;resumeBuffer=[];resumeMode=!1;resumeFlushTimer=null;gatewayUrl;operationId;autoReconnect;resumeOnConnect;token;constructor(e){super(),this.gatewayUrl=e.gatewayUrl,this.operationId=e.operationId,this.token=e.token,this.autoReconnect=e.autoReconnect??!0,this.resumeOnConnect=e.resumeOnConnect??!1}get connectionStatus(){return this._status}on(e,t){super.on(e,t)}off(e,t){super.off(e,t)}connect(){this._status===`connected`||this._status===`connecting`||(this.intentionalDisconnect=!1,this.sessionEnded=!1,this.doConnect())}disconnect(){this.intentionalDisconnect=!0,this.cleanup(),this.setStatus(`disconnected`),this.emit(`disconnected`)}sendInterrupt(){this.sendMessage({type:`interrupt`})}sendToolResult(e){return this.sendMessage({...e,type:`tool_result`})}updateToken(e){this.token=e}async reconnect(){this.cleanup(),this.intentionalDisconnect=!1,this.sessionEnded=!1,this.reconnectDelay=R7,this.doConnect()}doConnect(){this.clearReconnectTimer(),this.setStatus(`connecting`);try{let e=this.buildWsUrl(),t=new WebSocket(e);t.onopen=this.handleOpen,t.onmessage=this.handleMessage,t.onclose=this.handleClose,t.onerror=this.handleError,this.ws=t}catch(e){console.error(`[AgentStreamClient] Failed to create WebSocket:`,e),this.setStatus(`disconnected`),this.autoReconnect&&!this.sessionEnded&&this.scheduleReconnect()}}buildWsUrl(){return this.gatewayUrl.startsWith(`ws://`)||this.gatewayUrl.startsWith(`wss://`)?`${this.gatewayUrl.replace(/\/+$/,``)}/ws?operationId=${encodeURIComponent(this.operationId)}`:`${this.gatewayUrl.startsWith(`https`)?`wss`:`ws`}://${this.gatewayUrl.replace(/^https?:\/\//,``)}/ws?operationId=${encodeURIComponent(this.operationId)}`}handleOpen=()=>{this.reconnectDelay=R7,this.setStatus(`authenticating`),this.sendMessage({token:this.token,type:`auth`})};handleMessage=e=>{try{let t=JSON.parse(e.data);switch(t.type){case`auth_success`:this.setStatus(`connected`),this.startHeartbeat(),this.resumeOnConnect&&!this.lastEventId&&(this.resumeMode=!0,this.resumeBuffer=[]),this.sendMessage({lastEventId:this.lastEventId,type:`resume`,wantStatus:!0}
6004),this.emit(`connected`);break;case`auth_failed`:this.emit(`auth_failed`,t.reason),this.disconnect();break;case`auth_expired`:this.emit(`auth_expired`);break;case`heartbeat_ack`:this.missedHeartbeats=0;break;case`agent_event`:{let e=t.event;t.id&&(this.lastEventId=t.id);let n=(e.type===`agent_runtime_end`||e.type===`error`)&&(!e.operationId||e.operationId===this.operationId);if(this.resumeMode){this.resumeBuffer.push({event:e,id:t.id}),this.scheduleResumeFlush(),n&&(this.sessionEnded=!0,this.flushResumeBuffer(),this.disconnect());break}this.emit(`agent_event`,e),n&&(this.sessionEnded=!0,this.disconnect());break}case`resume_complete`:this.resumeFlushTimer&&=(clearTimeout(this.resumeFlushTimer),null),this.resumeMode&&this.flushResumeBuffer(),(t.status===`completed`||t.status===`error`||t.status===`interrupted`)&&(this.sessionEnded=!0,this.emit(`session_complete`),this.disconnect());break;case`session_complete`:this.sessionEnded=!0,this.resumeMode&&this.flushResumeBuffer(),this.emit(`session_complete`),this.disconnect();break}}catch(e){console.error(`[AgentStreamClient] Failed to parse message:`,e)}};handleClose=()=>{this.stopHeartbeat(),this.ws=null,!this.intentionalDisconnect&&this.autoReconnect&&!this.sessionEnded?(this.setStatus(`reconnecting`),this.scheduleReconnect()):this._status!==`disconnected`&&(this.setStatus(`disconnected`),this.emit(`disconnected`))};handleError=()=>{this.emit(`error`,Error(`WebSocket error for operation ${this.operationId}`))};startHeartbeat(){this.stopHeartbeat(),this.missedHeartbeats=0,this.heartbeatTimer=setInterval(()=>{if(this.missedHeartbeats++,this.missedHeartbeats>aWe){console.error(`[AgentStreamClient] Missed ${this.missedHeartbeats} heartbeat acks, forcing reconnect`),this.closeWebSocket(),this.stopHeartbeat(),this.autoReconnect&&!this.sessionEnded?(this.setStatus(`reconnecting`),this.scheduleReconnect()):(this.setStatus(`disconnected`),this.emit(`disconnected`));return}this.sendMessage({type:`heartbeat`})},rWe)}stopHeartbeat(){this.heartbeatTimer&&=(clearInterval(this.heartbeatTimer),null)}scheduleReconnect(){this.clearReconnectTimer();let e=this.reconnectDelay;this.emit(`reconnecting`,e),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.doConnect()},e),this.reconnectDelay=Math.min(this.reconnectDelay*2,iWe)}clearReconnectTimer(){this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null)}setStatus(e){this._status!==e&&(this._status=e,this.emit(`status_changed`,e))}scheduleResumeFlush(){this.resumeFlushTimer&&clearTimeout(this.resumeFlushTimer),this.resumeFlushTimer=setTimeout(()=>{this.flushResumeBuffer()},oWe)}flushResumeBuffer(){if(!this.resumeMode)return;this.resumeMode=!1,this.resumeFlushTimer&&=(clearTimeout(this.resumeFlushTimer),null);let e=new Set,t=[];for(let{event:n,id:r}of this.resumeBuffer){let i=r||`${n.type}_${n.stepIndex}_${n.timestamp}`;e.has(i)||(e.add(i),t.push(n))}this.resumeBuffer=[];for(let e of t)this.emit(`agent_event`,e)}sendMessage(e){return this.ws?.readyState===WebSocket.OPEN?(this.ws.send(JSON.stringify(e)),!0):!1}closeWebSocket(){this.ws&&=(this.ws.onopen=null,this.ws.onmessage=null,this.ws.onclose=null,this.ws.onerror=null,(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING)&&this.ws.close(1e3,`Client disconnect`),null)}cleanup(){this.stopHeartbeat(),this.clearReconnectTimer(),this.closeWebSocket(),this.resumeFlushTimer&&=(clearTimeout(this.resumeFlushTimer),null),this.resumeMode=!1,this.resumeBuffer=[]}}})),uWe=e((()=>{lWe()})),z7,dWe=e((()=>{z7=(e,t)=>typeof e!=`object`||!e?!1:e.data?.code===t})),fWe,B7,V7,H7,U7,W7,G7,pWe,mWe,K7,hWe,q7,gWe,_We,J7,Y7,vWe,yWe,bWe,X7,xWe=e((()=>{Ne(),Ie(),Na(),B6(),Es(),di(),zs(),wi(),Pe(),fWe=new Set([`interrupted`,`waiting_for_async_tool`]),B7=e=>!fWe.has(e??``),V7=async()=>(await Ge(()=>Promise.resolve().then(()=>(Y5(),JBe)),void 0)).getExecutor,H7=async(e,t,n)=>{let r=n?.skipWorks,i=await Ma.getMessages(r?{...t,skipWorks:r}:t);return e().replaceMessages(i,{context:t,preserveWorks:r}),i},U7=(e,t)=>t===`hetero`&&e.data?.skipMessageFetch===!0,W7=e=>Oe(e)?me(e.id):void 0,G7=e=>Oe(e)?me(e.result_msg_id):void 0,pWe=e=>Oe(e)&&e.chunkType===`tool_state`&&e.snapshotMode===`replace`&&typeof e.toolCallId==`string`&&e.toolCallId.length>0&&Number.isInteger(e.snapshotSeq)&&e.snapshotSeq>0&&Oe(e.pluginState),mWe=(e,t)=>
6004{if(!Array.isArray(t))return e;let n=new Map;for(let e of t){let t=W7(e),r=G7(e);t&&r&&n.set(t,r)}if(n.size===0)return e;let r=!1,i=e.map(e=>{let t=W7(e);if(!t||G7(e))return e;let i=n.get(t);return!i||!Oe(e)?e:(r=!0,{...e,result_msg_id:i})});return r?i:e},K7=e=>{let t=typeof e?.identifier==`string`?e.identifier:void 0,n=typeof e?.apiName==`string`?e.apiName:void 0;if(!t||!n)return;let r=e?.arguments;if(typeof r==`string`)try{r=JSON.parse(r)}catch{r={}}else r??={};let i=typeof e?.id==`string`?e.id:void 0;return{apiName:n,identifier:t,params:r,toolCallId:i}},hWe=async(e,t)=>{let n=e?.toolCalling,r=K7(n);if(!r)return;let i=(await V7())(r.identifier);i?.onBeforeCall&&await i.onBeforeCall({...r,topicId:t})},q7=e=>{if(!e||typeof e!=`object`)return;let t=e;return t.toolCalling&&typeof t.toolCalling==`object`?t.toolCalling:e},gWe=async(e,t)=>{let n=K7(q7(e?.payload));if(!n)return;let r=(await V7())(n.identifier);r?.onAfterCall&&await r.onAfterCall({...n,result:e?.result??{},topicId:t})},_We=(e,t)=>{if(!e?.length)return;let n=e.findIndex(e=>e.id===t);if(n!==-1)for(let t=n+1;t<e.length;t+=1){let n=e[t];if(n.role===`assistant`)return n.id}},J7=e=>typeof e==`string`||typeof e==`number`,Y7=e=>{if(!Oe(e))return;let t=me(e.message);if(t)return t;let n=e.error,r=me(n);if(r)return r;if(Oe(n)){let e=me(n.message);if(e)return e;let t=n.error;if(Oe(t)){let e=me(t.message);if(e)return e}}let i=e._responseBody,a=Y7(i);if(a)return a;let o=e.body;if(Oe(o)){let e=me(o.message);if(e)return e}},vWe=(e,t)=>t===void 0?e:`error`in e?Oe(e.error)&&Oe(t)?{...e,error:{...t,...e.error}}:e:{...e,error:t},yWe=(e,t)=>{let n=ve(e.body),r=ve(e._responseBody),i=ve(e.error),a=n??r??i??{},o=n===void 0&&e._responseBody!==void 0?vWe(a,e.error):a;return{...o,...e.budget===void 0||`budget`in o?{}:{budget:e.budget},...typeof e.provider==`string`&&!(`provider`in o)?{provider:e.provider}:{},...`message`in o?{}:{message:t}}},bWe=e=>{if(Oe(e)&&J7(e.type)){let t=typeof e.message==`string`&&e.message?e.message:Y7({body:e.body});return{...e,...t?{message:t}:{},type:e.type}}if(Oe(e)&&J7(e.errorType)){let t=Y7(e)||String(e.errorType);return{body:yWe(e,t),message:t,type:e.errorType}}let t=Y7(e)||`Unknown error`;return{body:{message:t},message:t,type:ze.AgentRuntimeError}},X7=(e,t)=>{let{context:n,operationId:r,runLifecycle:i}=t,a=t.gatewayOperationId??r,o=t.runtimeType??`gateway`,s={context:n,operationId:r,runId:r,runScope:n.scope===`sub_agent`?`sub_agent`:`top_level`,runtimeType:`gateway`},c={operationId:r},l=t.assistantMessageId,u,d=!1,f=``,p=``,m=0,h=0,g=new Map,_=new Map,v=new Map,y=new Set,b=!1,x,S=()=>
6004{if(x)return;let{operationId:t}=e().startOperation({context:{...n,messageId:l},parentOperationId:r,type:`reasoning`});e().associateMessageWithOperation(l,t),x=t},C=()=>{x&&=(e().completeOperation(x),void 0)},w=Promise.resolve(),T=e=>(w=w.then(e,e),w),E=t=>(e().dbMessagesMap[li(n)]??[]).findLast(e=>e.tool_call_id===t&&e.parentId===l),D=(t,n=!1)=>{let r=g.get(t);if(u||y.has(t))return!0;let i=E(t);if(!r||!i)return!1;let a=i.metadata?.heterogeneousToolStateOperationId===r.operationId&&typeof i.metadata.heterogeneousToolStateSeq==`number`?i.metadata.heterogeneousToolStateSeq:0,o=v.get(t)??0;return r.snapshotSeq<=a?(v.set(t,Math.max(o,a)),!0):!n&&r.snapshotSeq<=o?!0:(v.set(t,r.snapshotSeq),e().internal_dispatchMessage({id:i.id,metadata:{heterogeneousToolStateOperationId:r.operationId,heterogeneousToolStateSeq:r.snapshotSeq},type:`replaceMessagePluginState`,value:r.pluginState},c),!0)},O=(t,r,i=!1)=>{if(y.has(t.toolCallId))return;let o=r||a,s=g.get(t.toolCallId);if(!i){if(s?.operationId===o&&t.snapshotSeq<=s.snapshotSeq)return;g.set(t.toolCallId,{...t,operationId:o})}if(E(t.toolCallId)){T(()=>{D(t.toolCallId)});return}if(_.has(t.toolCallId))return;let c=!1,l=t.snapshotSeq,d=T(async()=>{E(t.toolCallId)||await H7(e,n,{skipWorks:!0}).catch(console.error),c=D(t.toolCallId,!0)}).finally(()=>{_.delete(t.toolCallId);let e=g.get(t.toolCallId);!c&&!u&&!y.has(t.toolCallId)&&e&&e.snapshotSeq>l&&O(e,e.operationId,!0)});_.set(t.toolCallId,d)};return t=>{if(!u&&!t.data?.subagent){if(t.type===`stream_chunk`&&pWe(t.data)){O(t.data,t.operationId);return}switch((t.type===`agent_runtime_end`||t.type===`error`)&&(u=t.type===`error`?`error`:`completed`),t.type){case`stream_start`:T(async()=>{let i=t.data,a=i?.assistantMessage?.id;if(a&&(l=a,e().associateMessageWithOperation(l,r),b=!0,!ci.getDbMessageById(a)(e()))){let t=i?.assistantMessage;t?.role?e().internal_dispatchMessage({id:a,type:`createMessage`,value:{agentId:t.agentId??n.agentId,content:``,groupId:t.groupId??void 0,model:t.model??i?.model,parentId:t.parentId??void 0,provider:t.provider??i?.provider,role:`assistant`,threadId:t.threadId??void 0,topicId:t.topicId??n.topicId??void 0}},c):await H7(e,n,{skipWorks:!0}).catch(console.error)}if(C(),f=``,p=``,e().updateOperationMetadata(r,{visibleLoadingDone:!1}),!a){let t=await H7(e,n,{skipWorks:!0}).catch(e=>{console.error(e)});if(i?.newStep){let n=_We(t,l);n&&(l=n,e().associateMessageWithOperation(l,r))}}Ts({payload:{agentId:n.agentId,...l?{anchorMessageId:l,assistantMessageId:l}:{},operationId:r,stepIndex:t.stepIndex,topicId:n.topicId??void 0},sourceId:`${r}:gateway:start:${t.stepIndex}`,sourceType:`client.gateway.stream_start`})});break;case`stream_chunk`:T(async()=>{let r=t.data;if(r){if(r.chunkType===`text`&&r.content){let t=r.snapshotMode===`replace`&&typeof r.snapshotSeq==`number`?r.snapshotSeq:void 0;t!==void 0&&t<=m||(C(),t===void 0?f+=r.content:(m=t,f=r.content),b=!0,e().internal_dispatchMessage({id:l,type:`updateMessage`,value:{content:f}},c))}if(r.chunkType===`reasoning`&&r.reasoning){let t=r.snapshotMode===`replace`&&typeof r.snapshotSeq==`number`?r.snapshotSeq:void 0;t!==void 0&&t<=h||(S(),t===void 0?p+=r.reasoning:(h=t,p=r.reasoning),b=!0,e().internal_dispatchMessage({id:l,type:`updateMessage`,value:{reasoning:{content:p}}},c))}if(r.chunkType===`tools_calling`&&r.toolsCalling){C(),b=!0;let t=mWe(r.toolsCalling,ci.getDbMessageById(l)(e())?.tools);e().internal_dispatchMessage({id:l,type:`updateMessage`,value:{tools:t}},c),e().internal_toggleToolCallingStreaming(l,t.map(()=>!0)),r.toolMessageIds&&await H7(e,n,{skipWorks:!0}).catch(console.error)}}});break;case`stream_end`:T(()=>{let n=me(ve(t.data)?.finalContent);n!==void 0&&(f=n,b=!0,e().internal_dispatchMessage({id:l,type:`updateMessage`,value:{content:f}},c)),e().internal_toggleToolCallingStreaming(l,void 0),C()});break;case`visible_output_end`:T(()=>{let t=ci.getDbMessageById(l)(e());!t||f&&!t.content||(e().internal_toggleToolCallingStreaming(l,void 0),C(),e().updateOperationMetadata(r,{visibleLoadingDone:!0}))});break;case`tool_start`:{let e=t.data,r=W7(e?.toolCalling)||(Oe(e)?me(e.toolCallId):void 0);r&&y.delete(r),T(async()=>{await hWe(e,n.topicId??void 0).catch(console.error)});break}case`step_start`:{let i=t.data;typeof t.stepIndex==`number`&&e().updateOperationMetadata(r,{stepCount:t.stepIndex+1}
6004),Array.isArray(i?.uiMessages)&&e().replaceMessages(i.uiMessages,{action:`gateway/step_start`,context:n,preserveWorks:!0}),i?.phase===`human_approval`&&i.requiresApproval&&i.pendingToolsCalling&&(Ls(e,n),n.topicId&&(e().updateTopicStatus?.({agentId:n.agentId,groupId:n.groupId,...n.scope===`group`||n.scope===`group_agent`?{scope:n.scope}:{},status:`waitingForHuman`,topicId:n.topicId}))?.catch(e=>{console.error(`[gatewayEventHandler] updateTopicStatus failed:`,e)}));break}case`tool_execute`:{let n=t.data;if(!n)break;e().internal_executeClientTool(n,{localOperationId:r,operationId:a});break}case`tool_end`:{let r=t.data,i=W7(q7(r?.payload))||(Oe(r)?me(r.toolCallId):void 0);i&&(y.add(i),g.delete(i)),T(async()=>{let i=U7(t,o)?Promise.resolve():H7(e,n,{skipWorks:!0}).catch(console.error),a=q7(r?.payload),s=r?.result;R6({apiName:typeof a?.apiName==`string`?a.apiName:void 0,identifier:typeof a?.identifier==`string`?a.identifier:void 0,result:s,succeeded:r?.isSuccess===!0,workRegistration:!!s?.workRegistration})&&(d=!0),await Promise.all([i,gWe(r,n.topicId??void 0).catch(console.error)])});break}case`step_complete`:{let i=t.data;if(i?.phase===`subagent_progress`){let n=t.data;n.toolMessageId&&T(()=>{e().internal_dispatchMessage({id:n.toolMessageId,key:`progress`,type:`updatePluginState`,value:{model:n.model,totalCost:n.totalCost,totalInputTokens:n.totalInputTokens,totalOutputTokens:n.totalOutputTokens,totalTokens:n.totalTokens,totalToolCalls:n.totalToolCalls}},c)});break}i?.phase===`execution_complete`&&T(async()=>{Ts({payload:{agentId:n.agentId,operationId:r,stepIndex:t.stepIndex,topicId:n.topicId??void 0},sourceId:`${r}:gateway:step_complete:${t.stepIndex}`,sourceType:`client.gateway.step_complete`}),U7(t,o)||await H7(e,n,{skipWorks:!0}).catch(console.error)});break}case`agent_runtime_end`:T(async()=>{let a=t.data;Ts({payload:{agentId:n.agentId,...l?{anchorMessageId:l,assistantMessageId:l}:{},operationId:r,topicId:n.topicId??void 0},sourceId:`${r}:gateway:runtime_end`,sourceType:`client.gateway.runtime_end`}),e().internal_toggleToolCallingStreaming(l,void 0),C();let c;if(Array.isArray(a?.uiMessages)?(c=a.uiMessages,e().replaceMessages(a.uiMessages,{action:`gateway/agent_runtime_end`,context:n})):(a?.reason===`interrupted`||a?.reason===`waiting_for_async_tool`)&&b||await H7(e,n).catch(console.error),o===`gateway`&&d&&await z6.refreshConversationViews(n.topicId,n.threadId).catch(console.error),o===`gateway`&&i){let e=B7(a?.reason)?`completed`:`cancelled`,{requeued:t}=await i.completeRun({...s,status:e});if(!t&&e===`completed`){let t=c?.findLast(e=>e.role===`assistant`)?.content;await i.afterRunComplete({...s,notification:{content:t||f},status:e})}}else{e().completeOperation(r);let t=e().operations[r];t?.context.agentId&&B7(a?.reason)&&e().markTopicUnread({agentId:t.context.agentId,groupId:t.context.groupId,topicId:t.context.topicId})}});break;case`notify_update`:T(async()=>{await H7(e,n).catch(console.error)});break;case`error`:T(async()=>{let a=bWe(t.data),u=a.message;Ts({payload:{agentId:n.agentId,errorMessage:u,operationId:r,topicId:n.topicId??void 0},sourceId:`${r}:gateway:error`,sourceType:`client.gateway.error`}),e().internal_toggleToolCallingStreaming(l,void 0),C(),o===`gateway`&&i?await i.completeRun({...s,status:`failed`}):e().completeOperation(r);let d=await Ma.updateMessageError(l,a,{agentId:n.agentId,groupId:n.groupId,threadId:n.threadId,topicId:n.topicId}).catch(console.error);d?.success&&d.messages?e().replaceMessages(d.messages,{context:n}):await H7(e,n).catch(console.error),e().internal_dispatchMessage({id:l,type:`updateMessage`,value:{error:a}},c)});break}}}}})),Z7,SWe=e((()=>{Z7=e=>{let{ownerOperationId:t,ownerHandler:n,createMemberHandler:r}=e,i=new Map;return e=>{let a=e.operationId||t;if(a===t){n(e);return}let o=i.get(a);o||(o=r(a),i.set(a,o)),o(e)}}})),CWe,wWe=e((()=>{wi(),CWe=(e,t)=>{let{context:n,ensureGroupHydrated:r,memberOperationId:i,parentOperationId:a}=t,o=li({agentId:n.agentId??``,groupId:n.groupId,scope:n.scope,threadId:n.threadId,topicId:n.topicId}),s,c,l=``,u=``,d=!1,f=t=>(e().dbMessagesMap[o]??[]).some(e=>e.id===t),p=t=>{!c||!s||f(c)&&e().internal_dispatchMessage({id:c,type:`updateMessage`,value:t},{operationId:s})},m=()=>{if(s)return;let{operationId:t}=e().startOperation({context:n,metadata:{serverOperationId:i},parentOperationId:a,type:`execServerAgentRuntime`});s=t};return t=>{if(!d)switch(t.type){case`stream_start`:{let n=t.data?.assistantMessage?.id;if(!n)break;m(),c=n,s&&e().associateMessageWithOperation(n,s),l=``,u=``,r().then(()=>{d||(l&&p({content:l}),u&&p({reasoning:{content:u}}))});break}case`stream_chunk`:{let e=t.data;if(!e)break;e.chunkType===`text`&&e.content&&(l+=e.content,p({content:l})),e.chunkType===`reasoning`&&e.reasoning&&(u+=e.reasoning,p({reasoning:{content:u}})),e.chunkType===`tools_calling`&&e.toolsCalling&&p({tools:e.toolsCalling});break}case`visible_output_end`:if(c){let t=(e().dbMessagesMap[o]??[]).find(e=>e.id===c);if(!t||l&&!t.content)break}s&&e().updateOperationMetadata(s,{visibleLoadingDone:!0});break;case`agent_runtime_end`:case`error`:d=!0,s&&e().completeOperation(s);break}}}})),TWe,EWe,DWe=e((()=>{uWe(),jt(),Wa(),ite(),Na(),Fa(),Gr(),qr(),E7(),Oi(),wi(),Ti(),Er(),Ta(),dWe(),qs(),xWe(),SWe(),wWe(
6004),TWe=async e=>{},EWe=class{#e;#t;createClient=e=>new cWe(e);constructor(e,t,n){this.#t=e,this.#e=t}connectToGateway=e=>{let{operationId:t,gatewayUrl:n,token:r,topicId:i,onEvent:a,onSessionComplete:o,resumeOnConnect:s}=e;this.disconnectFromGateway(t);let c=this.createClient({gatewayUrl:n,operationId:t,resumeOnConnect:s,token:r});this.#t(e=>({gatewayConnections:{...e.gatewayConnections,[t]:{client:c,status:`connecting`}}}),!1,`connectToGateway`),c.on(`status_changed`,e=>{this.#t(n=>{let r=n.gatewayConnections[t];return r?{gatewayConnections:{...n.gatewayConnections,[t]:{...r,status:e}}}:n},!1,`gateway/statusChanged`)});let l=!1,u=!1,d=!1,f=e=>{d||(d=!0,o?.({authFailed:e?.authFailed??!1,succeeded:u,terminalReceived:l}))};c.on(`agent_event`,e=>{let n=!e.operationId||e.operationId===t;n&&(e.type===`agent_runtime_end`||e.type===`error`)&&(l=!0),n&&e.type===`agent_runtime_end`&&B7(e.data?.reason)&&(u=!0),a?.(e)}),c.on(`session_complete`,()=>{this.internal_cleanupGatewayConnection(t),f()}),c.on(`disconnected`,()=>{this.internal_cleanupGatewayConnection(t),l&&f()}),c.on(`auth_failed`,e=>{console.error(`[Gateway] Auth failed for operation ${t}: ${e}`),this.internal_cleanupGatewayConnection(t),f({authFailed:!0})}),c.on(`auth_expired`,async()=>{try{let{token:e}=await Ga.refreshGatewayToken(i);c.updateToken(e),await c.reconnect()}catch(e){console.error(`[Gateway] Token refresh failed for operation ${t}:`,e),c.disconnect(),this.internal_cleanupGatewayConnection(t),f({authFailed:!0})}}),c.connect()};disconnectFromGateway=e=>{let t=this.#e().gatewayConnections[e];t&&(t.client.disconnect(),this.internal_cleanupGatewayConnection(e))};interruptGatewayAgent=e=>{let t=this.#e().gatewayConnections[e];t&&t.client.sendInterrupt()};getGatewayConnectionStatus=e=>this.#e().gatewayConnections[e]?.status;isGatewayModeEnabled=e=>{let t=window.global_serverConfigStore?.getState()?.serverConfig,n=Xr(),r=e??n.activeAgentId,i=r?Hr.getChatConfigById(r)(n).disableGatewayMode:void 0,a=Sa.defaultAgentConfig(Or.getState()).chatConfig?.disableGatewayMode,o=i??a;return!!t?.agentGatewayUrl&&!!t.enableGatewayMode&&o!==!0};executeGatewayAgent=async e=>{let{context:t,fileIds:n,message:r,metadata:i,onComplete:a,optimisticTopic:o,parentMessageId:s,parentOperationId:c,resumeApproval:l,resumeToolResult:u,selectedToolIds:d,mentionedAgents:f,tempMessageIds:p}=e,m=window.global_serverConfigStore.getState().serverConfig.agentGatewayUrl,h=!t.topicId,g=t.viewedTask?.type===`detail`?t.viewedTask.taskId:void 0,_=h&&t.agentId?T7(t.agentId):[],v=_.length>0?{repos:_,workingDirectory:_[0],workingDirectoryConfig:{path:_[0],repoType:`github`}}:h&&o?.metadata?.workingDirectory?{repos:o.metadata.repos,workingDirectory:o.metadata.workingDirectory,workingDirectoryConfig:o.metadata.workingDirectoryConfig}:void 0,y=c?this.#e().getOperationAbortSignal(c):void 0,b=await TWe(t.agentId),x={approvalMode:xa.approvalMode(Or.getState()),allowList:xa.allowList(Or.getState())},S=await Ga.execAgentTask({agentId:t.agentId,appContext:{agentDocumentId:t.agentDocumentId,defaultTaskAssigneeAgentId:t.defaultTaskAssigneeAgentId,documentId:t.documentId,...t.scope===`agent_builder`&&{editingAgentId:this.#e().activeAgentId??void 0},groupId:t.groupId,...v&&{initialTopicMetadata:v},orchestrationRole:t.orchestrationRole,scope:t.scope,taskId:g,threadId:t.threadId,topicId:t.topicId},deviceId:b,fileIds:n,mentionedAgents:f,parentMessageId:s,prompt:r,resumeApproval:l,resumeToolResult:u,selectedToolIds:d,trigger:i?.trigger,userInterventionConfig:x},{signal:y});if(y?.aborted)throw Ga.interruptTask({operationId:S.operationId}).catch(e=>console.error(`[Gateway] interruptTask after cancel failed:`,e)),y.reason??new DOMException(`Aborted`,`AbortError`);if(h&&S.topicId){if(t.agentId&&MHe(t.agentId),o){let e=o.metadata??v;this.#e().internal_replaceTopicId({agentId:t.agentId,groupId:t.groupId,nextId:S.topicId,previousId:o.id,value:{...e?{metadata:e}:{},...t.groupId?{}:{sessionId:t.agentId},title:o.title}})}try{let e={...t,topicId:S.topicId},n=await Ma.getMessages(e);this.#e().replaceMessages(n,{context:e})}catch{}if(await this.#e().switchTopic(S.topicId,{clearNewKey:!0,skipRefreshMessage:!0}),this.#e().refreshTopic().catch(e=>console.error(`[Gateway] refreshTopic after topic creation failed:`,e)),y?.aborted)throw Ga.interruptTask({operationId:S.operationId}).catch(e=>console.error(`[Gateway] interruptTask after cancel failed:`,e)),y.reason??new DOMException(`Aborted`,`AbortError`)}let C={...t,topicId:S.topicId};this.#e().moveQueuedMessages(li(t),li(C)),S.topicId&&this.#e().updateTopicStatus?.({agentId:t.agentId,groupId:t.groupId,status:`running`,topicId:S.topicId});let{operationId:w}=this.#e().startOperation({context:C,metadata:{serverOperationId:S.operationId}
6004,parentOperationId:c,type:`execServerAgentRuntime`});if(this.#e().associateMessageWithOperation(S.assistantMessageId,w),p?.length)for(let e of p)this.#e().associateMessageWithOperation(e,w);if(c&&this.#e().completeOperation(c),S.topicId){let e=vi.getTopicById(S.topicId)(this.#e()),t=e?.metadata?.runningOperation?.operationId;t&&t!==S.operationId&&(this.#e().internal_dispatchTopic({id:S.topicId,type:`updateTopic`,value:{metadata:{...e?.metadata,runningOperation:{assistantMessageId:S.assistantMessageId,operationId:S.operationId}}}}),this.disconnectFromGateway(t))}this.#e().onOperationCancel(w,async()=>{await Ga.interruptTask({operationId:S.operationId,topicId:S.topicId}).catch(e=>console.error(`[Gateway] interruptTask failed:`,e))});let T=X7(this.#e,{assistantMessageId:S.assistantMessageId,context:C,gatewayOperationId:S.operationId,operationId:w,runLifecycle:Ks(this.#e,{context:C,parentMessageId:S.assistantMessageId,parentMessageType:`assistant`,runId:w,runScope:C.scope===`sub_agent`?`sub_agent`:`top_level`,runtimeType:`gateway`})}),E=Z7({createMemberHandler:this.buildMemberHandlerFactory(C,w),ownerHandler:T,ownerOperationId:S.operationId});return this.#e().connectToGateway({gatewayUrl:m,onEvent:E,onSessionComplete:({succeeded:e,terminalReceived:t})=>{t||this.#e().completeOperation(w),S.topicId&&((this.#e().activeTopicId===S.topicId||!e)&&this.#e().updateTopicStatus?.({agentId:C.agentId,groupId:C.groupId,status:`active`,topicId:S.topicId}),Pa.updateTopicMetadata(S.topicId,{runningOperation:null}).catch(()=>{}),this.clearLocalRunningOperation({agentId:C.agentId,groupId:C.groupId,operationId:S.operationId,topicId:S.topicId})),a?.()},operationId:S.operationId,token:S.token||``,topicId:S.topicId}),S};reconnectToGatewayOperation=async e=>{let{assistantMessageId:t,operationId:n,topicId:r,scope:i,threadId:a}=e,o=window.global_serverConfigStore?.getState()?.serverConfig?.agentGatewayUrl;if(!o)return;let s=this.#e().gatewayConnections[n]?.status;if(s&&s!==`disconnected`)return;let c=vi.getTopicById(r)(this.#e())?.metadata?.runningOperation?.operationId;if(c&&c!==n)return;let l;try{({token:l}=await Ga.refreshGatewayToken(r))}catch(e){if(z7(e,`NOT_FOUND`)){this.clearLocalRunningOperation({operationId:n,topicId:r});return}throw e}let u=vi.getTopicById(r)(this.#e())?.metadata?.runningOperation?.operationId;if(u&&u!==n)return;let d={agentId:this.#e().activeAgentId,scope:i??`main`,threadId:a??null,topicId:r},f=Object.values(this.#e().messagesMap).flat().find(e=>e.id===t),p=f?.createdAt?new Date(f.createdAt).getTime():void 0,{operationId:m}=this.#e().startOperation({context:d,metadata:{serverOperationId:n,...Number.isFinite(p)?{startTime:p}:{}},type:`execServerAgentRuntime`});this.#e().associateMessageWithOperation(t,m),this.#e().onOperationCancel(m,async()=>{await Ga.interruptTask({operationId:n}).catch(e=>console.error(`[Gateway] interruptTask failed:`,e))});let h=X7(this.#e,{assistantMessageId:t,context:d,gatewayOperationId:n,operationId:m,runLifecycle:Ks(this.#e,{context:d,parentMessageId:t,parentMessageType:`assistant`,runId:m,runScope:d.scope===`sub_agent`?`sub_agent`:`top_level`,runtimeType:`gateway`})}),g=Z7({createMemberHandler:this.buildMemberHandlerFactory(d,m),ownerHandler:h,ownerOperationId:n});this.#e().connectToGateway({gatewayUrl:o,onEvent:g,onSessionComplete:({succeeded:e,terminalReceived:t,authFailed:i})=>{if(!t&&!i){this.#e().completeOperation(m);return}i&&this.#e().completeOperation(m),(this.#e().activeTopicId===r||!e)&&this.#e().updateTopicStatus?.({agentId:d.agentId,status:`active`,topicId:r}),Pa.updateTopicMetadata(r,{runningOperation:null}).catch(()=>{}),this.clearLocalRunningOperation({agentId:d.agentId,operationId:n,topicId:r})},operationId:n,resumeOnConnect:!0,token:l,topicId:r})};buildMemberHandlerFactory=(e,t)=>{let n,r=()=>(n||=Ma.getMessages(e).then(t=>{this.#e().replaceMessages(t,{context:e})}).catch(()=>{}),n);return n=>CWe(this.#e,{context:e,ensureGroupHydrated:r,memberOperationId:n,parentOperationId:t})};clearLocalRunningOperation=e=>{let{topicId:t,operationId:n,agentId:r,groupId:i}=e,a=this.#e(),o=ai({agentId:r??a.activeAgentId,groupId:i??a.activeGroupId}),s=a.topicDataMap[o]?.items?.find(e=>e.id===t);s?.metadata?.runningOperation?.operationId===n&&a.internal_dispatchTopic({agentId:r,groupId:i,id:t,type:`updateTopic`,value:{metadata:{...s.metadata,runningOperation:null}}})};internal_cleanupGatewayConnection=e=>{this.#t(t=>{let{[e]:n,...r}=t.gatewayConnections;return{gatewayConnections:r}},!1,`gateway/cleanup`)}}})),OWe,kWe=e((()=>{ft(),Lie(),KHe(),JHe(),ZHe(),nUe(),nWe(),DWe(),OWe=(...e)=>rt([new qHe(...e),new tUe(...e),new GHe(...e),new Js(...e),new EWe(...e),new tWe(...e),new XHe(...e)])})),AWe,Q7,jWe,MWe,NWe=e((()=>{kre(),AWe=t(F()),Q7=(0,AWe.default)(`lobe-agent-runtime:client`),jWe=class{baseUrl=`/api/agent`;createStreamConnection(e,t={}){let{includeHistory:n=!1,lastEventId:r=`0`,onEvent:i,onError:a,onConnect:o,onDisconnect:s}=t,c=new URLSearchParams({includeHistory:n.toString(),lastEventId:r,operationId:e}),l=new AbortController;return Ia(`${this.baseUrl}/stream?${c}`,{headers:{"Cache-Control":`no-cache`,"Last-Event-ID":r},onclose:()=>{Q7(`Stream connection closed for operation ${e}`),s?.()},onerror:t=>{console.error(`[AgentClientService] Stream error for operation ${e}:`,t),a?.(t instanceof Error?t:Error(`Stream connection error`))},onmessage:e=>{try{let t=JSON.parse(e.data);Q7(`Received event: ${e.event||`message`}`,e.data),i?.(t)}catch(e){console.error(`[AgentClientService] Failed to parse stream event:`,e),a?.(Error(`Failed to parse stream event`))}},onopen:async t=>{if(t.ok)Q7(`Stream connection opened for operation ${e}`),o?.();else throw Error(`Failed to open stream: ${t.status} ${t.statusText}`)},signal:l.signal}),l}},MWe=new jWe})),PWe=e((()=>{})),FWe,IWe,LWe=e((()=>{pa(),NWe(),PWe(),FWe=class{async handleHumanIntervention(e){return await q.aiAgent.processHumanIntervention.mutate({action:e.action,data:e.data,operationId:e.operationId,reason:e.reason,stepIndex:0})}},IWe=new FWe})),RWe,$7,e9,zWe,BWe=e((()=>{Wt(),R(),RWe=t(F()),pa(),LWe(),Dr(),$7=(0,RWe.default)(`store:chat:ai-agent:agentGroup`),e9=kr(`aiAgentGroup`),zWe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}sendGroupMessage=async({context:e,message:t,files:n}
6004)=>{if(!t.trim()&&(!n||n.length===0))return;let{agentId:r,groupId:i,topicId:a}=e;if(!r||!i){$7(`sendGroupMessage: missing agentId or groupId in context`);return}let{internal_handleAgentStreamEvent:o,optimisticCreateTmpMessage:s,startOperation:c}=this.#e();$7(`sendGroupMessage: agentId=%s, groupId=%s, message=%s`,r,i,t.slice(0,50)),this.#t({isCreatingMessage:!0},!1,e9(`sendGroupMessage/start`));let l=`tmp_`+ke(),u=`tmp_`+ke(),d=n?.map(e=>e.id),{operationId:f,abortController:p}=c({context:{...e,messageId:l},label:`Execute Server Agent`,type:`execServerAgentRuntime`});s({agentId:r,content:t,files:d,groupId:i,role:`user`,topicId:a??void 0},{operationId:f,tempMessageId:l}),s({agentId:r,content:`...`,groupId:i,role:`assistant`,topicId:a??void 0},{operationId:f,tempMessageId:u});try{let n=await q.aiAgent.execGroupAgent.mutate({agentId:r,files:d,groupId:i,message:t,topicId:a},{signal:p.signal});$7(`execGroupAgent result: operationId=%s, topicId=%s, success=%s`,n.operationId,n.topicId,n.success),n.topics&&this.#e().internal_updateTopics(r,{groupId:i,items:n.topics.items,pageSize:20,total:n.topics.total});let s={...e,topicId:n.topicId||a};if(n.messages&&this.#e().replaceMessages(n.messages,{action:e9(`sendGroupMessage/syncMessages`),context:s}),n.isCreateNewTopic&&n.topicId&&await this.#e().switchTopic(n.topicId,{clearNewKey:!0,skipRefreshMessage:!0}),n.messages&&this.#e().internal_dispatchMessage({ids:[l,u],type:`deleteMessages`},{operationId:f}),n.success===!1){$7(`Agent operation failed to start: %s`,n.error),this.#e().failOperation(f,{message:n.error||`Agent operation failed to start`,type:`AgentStartupError`});return}let c={assistantId:n.assistantMessageId,content:``,reasoning:``,tmpAssistantId:u};this.#e().startOperation({context:{...s,messageId:n.assistantMessageId},label:`Group Agent Stream`,operationId:n.operationId,parentOperationId:f,type:`groupAgentStream`}),this.#e().associateMessageWithOperation(n.assistantMessageId,f),this.#e().associateMessageWithOperation(n.assistantMessageId,n.operationId);let m=MWe.createStreamConnection(n.operationId,{includeHistory:!1,onConnect:()=>{$7(`Stream connected to %s`,n.operationId)},onDisconnect:()=>{$7(`Stream disconnected from %s`,n.operationId),this.#e().completeOperation(n.operationId),this.#e().completeOperation(f)},onError:e=>{$7(`Stream error for %s: %O`,n.operationId,e),this.#e().failOperation(n.operationId,{message:e.message,type:`AgentStreamError`}),c.assistantId&&this.#e().internal_handleAgentError(c.assistantId,e.message)},onEvent:async e=>{await o(n.operationId,e,c)}});this.#e().onOperationCancel(n.operationId,()=>{$7(`Cancelling SSE stream for operation %s`,n.operationId),m.abort()})}catch(e){e instanceof Error&&(e.name===`AbortError`||e.message.includes(`aborted`)||e.message.includes(`cancelled`))?($7(`sendGroupMessage aborted by user`),this.#e().internal_dispatchMessage({ids:[l,u],type:`deleteMessages`},{operationId:f})):($7(`sendGroupMessage failed: %O`,e),console.error(`Failed to send group message:`,e),this.#e().internal_dispatchMessage({ids:[l,u],type:`deleteMessages`},{operationId:f}),this.#e().failOperation(f,{message:e instanceof Error?e.message:`Unknown error`,type:`SendGroupMessageError`}))}finally{this.#t({isCreatingMessage:!1},!1,e9(`sendGroupMessage/end`))}}}})),VWe,t9,n9,HWe,r9,UWe,WWe=e((()=>{VWe=t(F()),Wa(),di(),wi(),t9=(0,VWe.default)(`lobe-store:group-orchestration-executors`),n9=e=>new Promise(t=>{setTimeout(t,e)}),HWe=e=>e.map((e,t)=>{let n=e.title??e.agentId,r=e.success?e.result??`Completed successfully.`:`Failed: ${e.error??`Unknown error`}`;return`${t+1}. ${n}\n${r}`}).join(`
6005
6006`),r9=({agentId:e,error:t,result:n,success:r})=>({agentId:e,...t===void 0?{}:{error:t},...n===void 0?{}:{result:n},success:r}),UWe=e=>{let{get:t,messageContext:n,orchestrationOperationId:r,supervisorAgentId:i}=e,a=li(n),o=()=>ci.getDbMessagesByKey(a)(t());return{call_supervisor:async(e,a)=>{let{supervisorAgentId:s}=e.payload,c=`${a.operationId}:call_supervisor`;t9(`[${c}] Starting supervisor agent: ${s}`);let l=o(),u=l.at(-1);return u?(await t().executeClientAgent({context:{...n,agentId:i,isSupervisor:!0},messages:l,parentMessageId:u.id,parentMessageType:u.role,parentOperationId:r}),t9(`[${c}] Supervisor agent finished`),{events:[{type:`supervisor_finished`}],newState:a,result:{payload:{decision:`finish`,params:{reason:`supervisor_completed_without_action`},skipCallSupervisor:!1},type:`supervisor_decided`}}):(t9(`[${c}] No messages found, cannot execute supervisor`),{events:[{type:`supervisor_finished`}],newState:{...a,status:`done`},result:void 0})},call_agent:async(e,i)=>{let{agentId:a,instruction:s}=e.payload,c=`${i.operationId}:call_agent`;t9(`[${c}] Calling agent: ${a}, instruction: ${s}`);let l=o(),u=l.at(-1);if(!u)return t9(`[${c}] No messages found, cannot execute agent`),{events:[{agentId:a,type:`agent_spoke`}],newState:i,result:{payload:{agentId:a,completed:!0},type:`agent_spoke`}};let d=Date.now(),f=s?[...l,{content:`<speaker name="Supervisor" />\n${s}`,createdAt:d,id:`virtual_speak_instruction_${d}`,role:`user`,updatedAt:d}]:l;return await t().executeClientAgent({context:{...n,subAgentId:a},messages:f,parentMessageId:u.id,parentMessageType:u.role,parentOperationId:r}),t9(`[${c}] Agent ${a} finished speaking`),{events:[{agentId:a,type:`agent_spoke`}],newState:i,result:{payload:{agentId:a,completed:!0},type:`agent_spoke`}}},parallel_call_agents:async(e,i)=>{let{agentIds:a,disableTools:s,instruction:c,toolMessageId:l}=e.payload,u=`${i.operationId}:parallel_call_agents`;t9(`[${u}] Broadcasting to agents: ${a.join(`, `)}, instruction: ${c}, toolMessageId: ${l}, disableTools: ${s}`);let d=o();if(d.length===0)return t9(`[${u}] No messages found, cannot execute agents`),{events:[{agentIds:a,type:`agents_broadcasted`}],newState:i,result:{payload:{agentIds:a,completed:!0},type:`agents_broadcasted`}};
6006let f=Date.now(),p=c?[...d,{content:`<speaker name="Supervisor" />\n${c}`,createdAt:f,id:`virtual_broadcast_instruction_${f}`,role:`user`,updatedAt:f}]:d;return await Promise.all(a.map(async e=>{await t().executeClientAgent({context:{...n,subAgentId:e},disableTools:s,messages:p,parentMessageId:l,parentMessageType:`tool`,parentOperationId:r})})),t9(`[${u}] All agents finished broadcasting`),{events:[{agentIds:a,type:`agents_broadcasted`}],newState:i,result:{payload:{agentIds:a,completed:!0},type:`agents_broadcasted`}}},delegate:async(e,i)=>{let{agentId:a,reason:s}=e.payload,c=`${i.operationId}:delegate`;t9(`[${c}] Delegating to agent: ${a}, reason: ${s}`);let l=o(),u=l.at(-1);return u?(await t().executeClientAgent({context:{...n,subAgentId:a},messages:l,parentMessageId:u.id,parentMessageType:u.role,parentOperationId:r}),t9(`[${c}] Delegated agent ${a} finished`),{events:[],newState:i,result:{payload:{agentId:a,completed:!0},type:`delegated`}}):(t9(`[${c}] No messages found, cannot delegate`),{events:[],newState:i,result:{payload:{agentId:a,completed:!0},type:`delegated`}})},exec_async_task:async(e,r)=>{let{agentId:i,instruction:a,timeout:o,title:s,toolMessageId:c}=e.payload,l=`${r.operationId}:exec_async_task`;t9(`[${l}] Executing async task for agent: ${i}, instruction: ${a}, timeout: ${o}`);let{groupId:u,topicId:d}=n;if(!u||!d)return t9(`[${l}] No valid context, cannot execute async task`,u,d),{events:[],newState:r,result:{payload:{agentId:i,error:`No valid context available`,success:!1},type:`task_completed`}};try{let e=c,n=await Ga.execSubAgentTask({agentId:i,groupId:u,instruction:a,parentMessageId:e,title:s,topicId:d});if(!n.success)return t9(`[${l}] Failed to create task: ${n.error}`),await t().optimisticUpdateMessageContent(e,`Task creation failed: ${n.error}`,void 0,{operationId:r.operationId}),{events:[],newState:r,result:{payload:{agentId:i,error:n.error,success:!1},type:`task_completed`}};t9(`[${l}] Task created with threadId: ${n.threadId}`);let f=o||18e5,p=Date.now();for(;Date.now()-p<f;){if(t().operations[r.operationId]?.status===`cancelled`)return console.warn(`[${l}] Operation cancelled, stopping polling`),{events:[],newState:{...r,status:`done`},result:{payload:{agentId:i,error:`Operation cancelled`,success:!1},type:`task_completed`}};let a=await Ga.getSubAgentTaskStatus({threadId:n.threadId});if(a.taskDetail&&(t().internal_dispatchMessage({id:e,type:`updateMessage`,value:{taskDetail:a.taskDetail}},{operationId:r.operationId}),t9(`[${l}] Updated source tool message with taskDetail`)),a.status===`completed`)return t9(`[${l}] Task completed successfully`),a.result&&await t().optimisticUpdateMessageContent(e,a.result,void 0,{operationId:r.operationId}),{events:[],newState:r,result:{payload:{agentId:i,result:a.result,success:!0},type:`task_completed`}};if(a.status===`failed`)return console.error(`[${l}] Task failed: ${a.error}`),await t().optimisticUpdateMessageContent(e,`Task failed: ${a.error}`,void 0,{operationId:r.operationId}),{events:[],newState:r,result:{payload:{agentId:i,error:a.error,success:!1},type:`task_completed`}};if(a.status===`cancel`)return t9(`[${l}] Task was cancelled`),await t().optimisticUpdateMessageContent(e,`Task was cancelled`,void 0,{operationId:r.operationId}),{events:[],newState:r,result:{payload:{agentId:i,error:`Task was cancelled`,success:!1},type:`task_completed`}};await n9(3e3)}return t9(`[${l}] Task timeout after ${f}ms`),await t().optimisticUpdateMessageContent(e,`Task timeout after ${f}ms`,void 0,{operationId:r.operationId}),{events:[],newState:r,result:{payload:{agentId:i,error:`Task timeout after ${f}ms`,success:!1},type:`task_completed`}}}catch(e){return t9(`[${l}] Error executing async task: ${e}`),{events:[],newState:r,result:{payload:{agentId:i,error:e instanceof Error?e.message:`Unknown error`,success:!1},type:`task_completed`}}}},exec_client_async_task:async(e,i)=>{let{agentId:a,instruction:o,title:s,toolMessageId:c}=e.payload,l=`${i.operationId}:exec_client_async_task`;t9(`[${l}] Executing client-side async task for agent: ${a}`);let{groupId:u,topicId:d}=n;if(!u||!d)return t9(`[${l}] No valid context, cannot execute client async task`),{events:[],newState:i,result:{payload:{agentId:a,error:`No valid context available`,success:!1},type:`task_completed`}};try{let e=c,f=await Ga.createClientGroupAgentTaskThread({groupId:u,instruction:o,parentMessageId:e,subAgentId:a,title:s,topicId:d});if(!f.success)return t9(`[${l}] Failed to create client task thread`),await t().optimisticUpdateMessageContent(e,`Failed to create task thread`,void 0,{operationId:i.operationId}),{events:[],newState:i,result:{payload:{agentId:a,error:`Failed to create client task thread`,success:!1},type:`task_completed`}};let{threadId:p,userMessageId:m,threadMessages:h,messages:g}=f;t9(`[${l}] Created thread: ${p}, userMessageId: ${m}, threadMessages: ${h.length}`);let _={agentId:a,groupId:u,topicId:d,threadId:p,scope:`thread`,workspaceSlug:n.workspaceSlug},{operationId:v}
6006=t().startOperation({type:`execClientSubAgent`,context:_,parentOperationId:r,metadata:{startTime:Date.now(),taskDescription:s,sourceMessageId:e,executionMode:`client`}}),y=li(n);t9(`[${l}] replaceMessages (main): messages=%d, key=%s, context=%O`,g.length,y,n),t().replaceMessages(g,{context:n});let b=li(_);t9(`[${l}] replaceMessages (thread): threadMessages=%d, key=%s, subContext=%O`,h.length,b,_),t().replaceMessages(h,{context:_}),t9(`[${l}] Starting client-side AgentRuntime execution`);let x=await t().executeClientAgent({context:_,messages:h,parentMessageId:m,parentMessageType:`user`,operationId:v,parentOperationId:r,isSubAgent:!0});t9(`[${l}] Client-side AgentRuntime execution completed`);let S=li(_),C=t().dbMessagesMap[S]||[],w=C.findLast(e=>e.role===`assistant`)?.content||`Task completed`;t9(`[${l}] Got result from sub-task: ${w.length} chars`);let T=C.filter(e=>e.role===`tool`).length,{usage:E,cost:D}=x||{};return await t().optimisticUpdateMessageContent(e,w,{metadata:{cost:D?.total,duration:E?.llm?.processingTimeMs,totalInputTokens:E?.llm?.tokens?.input,totalOutputTokens:E?.llm?.tokens?.output,totalTokens:E?.llm?.tokens?.total}},{operationId:i.operationId}),await Ga.updateClientTaskThreadStatus({threadId:p,completionReason:`done`,resultContent:w,metadata:{totalCost:D?.total,totalMessages:C.length,totalTokens:E?.llm?.tokens?.total,totalToolCalls:T}}),t().completeOperation(v),{events:[],newState:i,result:{payload:{agentId:a,result:w,success:!0},type:`task_completed`}}}catch(e){return t9(`[${l}] Error executing client async task: ${e}`),{events:[],newState:i,result:{payload:{agentId:a,error:e instanceof Error?e.message:`Unknown error`,success:!1},type:`task_completed`}}}},batch_exec_async_tasks:async(e,r)=>{let{tasks:i,toolMessageId:a}=e.payload,o=`${r.operationId}:batch_exec_async_tasks`;t9(`[${o}] Executing ${i.length} async tasks in parallel`);let{groupId:s,topicId:c}=n;if(!s||!c)return t9(`[${o}] No valid context, cannot execute async tasks`,s,c),{events:[],newState:r,result:{payload:{results:i.map(e=>({agentId:e.agentId,error:`No valid context available`,success:!1}))},type:`tasks_completed`}};let l=i.map(e=>({agentId:e.agentId,status:`pending`,instruction:e.instruction,timeout:e.timeout||18e5,title:e.title})),u=e=>l.map(t=>{let n=t.status===`running`?e:t.error;return{agentId:t.agentId,...n===void 0?{}:{error:n},...t.result===void 0?{}:{result:t.result},success:t.status===`completed`,...t.title===void 0?{}:{title:t.title}}}),d=async e=>{await t().optimisticUpdateMessageContent(a,HWe(e),void 0,{operationId:r.operationId})};await Promise.all(l.map(async(e,t)=>{if(e.status===`failed`)return;let n=`${o}:task-${t}`;try{let t=await Ga.execSubAgentTask({agentId:e.agentId,groupId:s,instruction:e.instruction,parentMessageId:a,title:e.title,topicId:c});t.success?(e.threadId=t.threadId,e.status=`running`,t9(`[${n}] Task started with threadId: ${e.threadId}`)):(e.status=`failed`,e.error=t.error,t9(`[${n}] Failed to start task: ${t.error}`))}catch(t){e.status=`failed`,e.error=t instanceof Error?t.message:`Unknown error`,console.error(`[${n}] Error starting task: ${t}`)}}));let f=Date.now(),p=Math.max(...l.map(e=>e.timeout));for(;Date.now()-f<p;){if(t().operations[r.operationId]?.status===`cancelled`){console.warn(`[${o}] Operation cancelled, stopping polling`);let e=u(`Operation cancelled`);return await d(e),{events:[],newState:{...r,status:`done`},result:{payload:{results:e.map(r9)},type:`tasks_completed`}}}let e=l.filter(e=>e.status===`running`);if(e.length===0)break;await Promise.all(e.map(async(e,n)=>{if(!e.threadId)return;let i=`${o}:task-${n}`;try{let n=await Ga.getSubAgentTaskStatus({threadId:e.threadId});switch(n.taskDetail&&t().internal_dispatchMessage({id:a,type:`updateMessage`,value:{taskDetail:n.taskDetail}},{operationId:r.operationId}),n.status){case`completed`:e.status=`completed`,e.result=n.result,t9(`[${i}] Task completed successfully`);break;case`failed`:e.status=`failed`,e.error=n.error,console.error(`[${i}] Task failed: ${n.error}`);break;case`cancel`:e.status=`failed`,e.error=`Task was cancelled`,t9(`[${i}] Task was cancelled`);break}e.status===`running`&&Date.now()-f>e.timeout&&(e.status=`failed`,e.error=`Task timeout after ${e.timeout}ms`,t9(`[${i}] Task timeout`))}catch(e){console.error(`[${i}] Error polling task status: ${e}`)}})),await n9(3e3)}for(let e of l)e.status===`running`&&(e.status=`failed`,e.error=`Task timeout after ${e.timeout}ms`);t9(`[${o}] All tasks completed`);let m=u();return await d(m),{events:[],newState:r,result:{payload:{results:m.map(r9)},type:`tasks_completed`}}}}}})),GWe=e((()=>{WWe()})),KWe,i9,qWe,JWe,YWe,XWe,ZWe=e((()=>{gi(),KWe=t(F()),Qi(),Wa(),s6(),N3(),GWe(),i9=(0,KWe.default)(`lobe-store:group-orchestration`),qWe=10,JWe=`
6006SWR_USE_POLLING_TASK_STATUS`,YWe=5e3,XWe=class{#e;constructor(e,t,n){this.#e=t}#t=e=>this.#e().activeGroupId||j3.groupBySupervisorAgentId(e)(o6())?.id;getGroupOrchestrationCallbacks=()=>({triggerSpeak:this.#e().triggerSpeak,triggerBroadcast:this.#e().triggerBroadcast,triggerDelegate:this.#e().triggerDelegate,triggerExecuteTask:this.#e().triggerExecuteTask,triggerExecuteTasks:this.#e().triggerExecuteTasks});triggerSpeak=async e=>{let{supervisorAgentId:t,agentId:n,instruction:r,skipCallSupervisor:i}=e;i9(`[triggerSpeak] Starting orchestration with speak: supervisorAgentId=%s, agentId=%s, instruction=%s, skipCallSupervisor=%s`,t,n,r,i);let a=this.#t(t);if(!a){i9(`[triggerSpeak] No active group, skipping`);return}await this.#e().internal_execGroupOrchestration({groupId:a,supervisorAgentId:t,topicId:this.#e().activeTopicId,initialResult:{type:`supervisor_decided`,payload:{decision:`speak`,params:{agentId:n,instruction:r},skipCallSupervisor:i}}})};triggerBroadcast=async e=>{let{supervisorAgentId:t,agentIds:n,instruction:r,skipCallSupervisor:i,toolMessageId:a}=e;i9(`[triggerBroadcast] Starting orchestration with broadcast: supervisorAgentId=%s, agentIds=%o, instruction=%s, skipCallSupervisor=%s, toolMessageId=%s`,t,n,r,i,a);let o=this.#t(t);if(!o){i9(`[triggerBroadcast] No active group, skipping`);return}await this.#e().internal_execGroupOrchestration({groupId:o,supervisorAgentId:t,topicId:this.#e().activeTopicId,initialResult:{type:`supervisor_decided`,payload:{decision:`broadcast`,params:{agentIds:n,instruction:r,toolMessageId:a},skipCallSupervisor:i}}})};triggerDelegate=async e=>{let{supervisorAgentId:t,agentId:n,reason:r}=e;i9(`[triggerDelegate] Starting orchestration with delegate: supervisorAgentId=%s, agentId=%s, reason=%s`,t,n,r);let i=this.#t(t);if(!i){i9(`[triggerDelegate] No active group, skipping`);return}await this.#e().internal_execGroupOrchestration({groupId:i,supervisorAgentId:t,topicId:this.#e().activeTopicId,initialResult:{type:`supervisor_decided`,payload:{decision:`delegate`,params:{agentId:n,reason:r},skipCallSupervisor:!1}}})};triggerExecuteTask=async e=>{let{supervisorAgentId:t,agentId:n,instruction:r,timeout:i,toolMessageId:a,skipCallSupervisor:o,runInClient:s}=e;i9(`[triggerExecuteTask] Starting orchestration with execute_task: supervisorAgentId=%s, agentId=%s, instruction=%s, timeout=%s, toolMessageId=%s, skipCallSupervisor=%s, runInClient=%s`,t,n,r,i,a,o,s);let c=this.#t(t);if(!c){i9(`[triggerExecuteTask] No active group, skipping`);return}await this.#e().internal_execGroupOrchestration({groupId:c,supervisorAgentId:t,topicId:this.#e().activeTopicId,initialResult:{type:`supervisor_decided`,payload:{decision:`execute_task`,params:{agentId:n,instruction:r,runInClient:s,timeout:i,toolMessageId:a},skipCallSupervisor:o??!1}}})};triggerExecuteTasks=async e=>{let{supervisorAgentId:t,tasks:n,toolMessageId:r,skipCallSupervisor:i}=e;i9(`[triggerExecuteTasks] Starting orchestration with execute_tasks: supervisorAgentId=%s, tasks=%d, toolMessageId=%s, skipCallSupervisor=%s`,t,n.length,r,i);let a=this.#t(t);if(!a){i9(`[triggerExecuteTasks] No active group, skipping`);return}await this.#e().internal_execGroupOrchestration({groupId:a,supervisorAgentId:t,topicId:this.#e().activeTopicId,initialResult:{type:`supervisor_decided`,payload:{decision:`execute_tasks`,params:{tasks:n,toolMessageId:r},skipCallSupervisor:i??!1}}})};internal_execGroupOrchestration=async e=>{let{groupId:t,topicId:n,initialResult:r,supervisorAgentId:i}=e;i9(`[internal_execGroupOrchestration] Starting orchestration for group: %s, supervisorAgentId: %s, initialResult: %s`,t,i,r.type);let{operationId:a}=this.#e().startOperation({type:`execAgentRuntime`,context:{groupId:t,topicId:n,agentId:i,scope:`group`},label:`Group Orchestration (${r.type})`});i9(`[internal_execGroupOrchestration] Created operation: %s`,a);let o={supervisorAgentId:i,maxRounds:qWe};i9(`[internal_execGroupOrchestration] Group config: %o`,o);let s=new fi(new Ate({supervisorAgentId:o.supervisorAgentId,maxRounds:o.maxRounds}),{executors:UWe({get:this.#e,messageContext:{agentId:i,groupId:t,scope:`group`,topicId:n},orchestrationOperationId:a,supervisorAgentId:o.supervisorAgentId}),operationId:a,getOperation:e=>{let t=this.#e().operations[e];if(!t)throw Error(`Operation not found: ${e}`);return{abortController:t.abortController,context:t.context}}}),c=fi.createInitialState({operationId:a});i9(`[internal_execGroupOrchestration] Starting orchestration loop with initial result: %s`,r.type);let l=r,u=0;for(;l&&c.status!==`done`&&c.status!==`error`;){if(this.#e().operations[a]?.status===`cancelled`){i9(`[internal_execGroupOrchestration] Operation cancelled, stopping loop`),c={...c,status:`done`};break}u++,i9(`[internal_execGroupOrchestration][step-%d]: result=%s, status=%s`,u,l.type,c.status);let e=await s.step(c,l);i9(`[internal_execGroupOrchestration] Step %d completed, events: %d, newStatus=%s, nextResult=%s`,u,e.events.length,e.newState.status,e.result?.type||`none`),c=e.newState,l=e.result}if(i9(`[internal_execGroupOrchestration] Orchestration loop finished, final status: %s, total steps: %d`,c.status,u),c.status===`done`){this.#e().completeOperation(a);let e=this.#e().operations[a];e?.context.agentId&&this.#e().markTopicUnread({agentId:e.context.agentId,groupId:e.context.groupId,topicId:e.context.topicId}),i9(`[internal_execGroupOrchestration] Operation completed successfully`)}else c.status===`error`&&(this.#e().failOperation(a,{type:`orchestration_error`,message:`Group orchestration execution failed`}),i9(`[internal_execGroupOrchestration] Operation failed`));return c};useEnablePollingTaskStatus=(e,t,n)=>Xi(n&&e&&t?[JWe,e]:null,async([,e])=>Ga.getSubAgentTaskStatus({threadId:e}),{revalidateOnFocus:!1,revalidateOnReconnect:!1,refreshInterval:e=>!e||e.status===`processing`?YWe:0,onSuccess:e=>{e&&t&&(this.#e().internal_dispatchMessage({id:t,type:`updateMessage`,value:{taskDetail:e.taskDetail,tasks:e.messages}}),(e.status===`completed`||e.status===`failed`)&&e.result!==void 0&&this.#e().internal_dispatchMessage({id:t,type:`updateMessage`,value:{content:e.result}}))}})}})),QWe,a9,$We,eGe=e((()=>{QWe=t(F()),LWe(),zs(),a9=(0,QWe.default)(`store:chat:ai-agent:runAgent`),$We=class{#e;constructor(e,t,n){this.#e=t}internal_cleanupAgentOperation=e=>{let t=this.#e().messageOperationMap[e];if(!t){a9(`No operation found for assistant message ${e}`);return}a9(`Cleaning up agent operation for ${e} (operationId: ${t})`),this.#e().cancelOperation(t,`Cleanup requested`)};internal_handleAgentError=(e,t)=>
6006{a9(`Agent error for ${e}: ${t}`);let n=this.#e().messageOperationMap[e];n&&this.#e().failOperation(n,{message:t,type:`AgentExecutionError`}),this.#e().internal_dispatchMessage({id:e,type:`updateMessage`,value:{error:{message:t,type:`UnknownError`}}}),this.#e().internal_cleanupAgentOperation(e)};internal_handleAgentStreamEvent=async(e,t,n)=>{let{internal_dispatchMessage:r}=this.#e(),i=this.#e().operations[e];if(!i){a9(`No operation found for ${e}, ignoring event ${t.type}`);return}this.#e().updateOperationMetadata(e,{lastEventId:t.timestamp.toString(),stepCount:t.stepIndex});let a=n.assistantId||n.tmpAssistantId;switch(a9(`assistantMessageId: ${a}`),t.type){case`connected`:a9(`Agent stream connected for ${a}`);break;case`heartbeat`:break;case`agent_runtime_init`:a9(`Agent runtime initialized for ${a}:`,t.data);break;case`agent_runtime_end`:{let{reason:n,reasonDetail:r,finalState:o,uiMessages:s}=t.data||{};a9(`Agent runtime ended for ${a}: reason=${n}, detail=${r}`),Array.isArray(s)&&(a9(`Replacing messages from agent_runtime_end uiMessages (${s.length} msgs)`),this.#e().replaceMessages(s,{context:i.context})),o&&this.#e().updateOperationMetadata(e,{finalStatus:o.status||n}),a9(`Stopping loading for completed agent runtime: ${a}`);break}case`stream_start`:if(n.assistantId){a9(`Stream started for ${n.assistantId} (message already synced from backend)`);break}a9(`Stream started for ${a}:`,t.data),r({id:n.tmpAssistantId,type:`deleteMessage`}),n.assistantId=t.data.assistantMessage.id,r({id:n.assistantId,type:`createMessage`,value:t.data.assistantMessage});break;case`stream_chunk`:{let{chunkType:e}=t.data||{};switch(e){case`text`:n.content+=t.data.content,a9(`Stream(${t.operationId}) chunk type=${e}: `,t.data.content),r({id:a,type:`updateMessage`,value:{content:n.content}});break;case`reasoning`:n.reasoning+=t.data.reasoning,a9(`Stream(${t.operationId}) chunk type=${e}: `,t.data.reasoning),r({id:a,type:`updateMessage`,value:{reasoning:{content:n.reasoning}}});break;case`tools_calling`:n.toolsCalling=t.data.toolsCalling,r({id:a,type:`updateMessage`,value:{tools:n.toolsCalling}});break}break}case`stream_end`:{let{finalContent:n,toolCalls:o,reasoning:s,imageList:c,grounding:l}=t.data||{};a9(`Stream ended for ${a}:`,{hasFinalContent:!!n,hasGrounding:!!l,hasImageList:!!(c&&c.length>0),hasReasoning:!!s,hasToolCalls:!!(o&&o.length>0)}),n!==void 0&&r({id:a,type:`updateMessage`,value:{content:n,...o&&o.length>0?{tools:o}:{},...s?{reasoning:s}:{},...c&&c.length>0?{imageList:c}:{},...l?{search:l}:{}}}),a9(`Stopping loading for ${a}`),await Rs(this.#e,{content:n,context:i.context});let u=this.#e().operations[e];u?.context.agentId&&this.#e().markTopicUnread({agentId:u.context.agentId,groupId:u.context.groupId,topicId:u.context.topicId});break}case`visible_output_end`:this.#e().updateOperationMetadata(e,{visibleLoadingDone:!0}),i.parentOperationId&&this.#e().updateOperationMetadata(i.parentOperationId,{visibleLoadingDone:!0});break;case`step_start`:{let{phase:n,toolCall:r,pendingToolsCalling:o,requiresApproval:s,uiMessages:c}=t.data||{};Array.isArray(c)&&(a9(`Replacing messages from step_start uiMessages (${c.length} msgs)`),this.#e().replaceMessages(c,{context:i.context})),n===`human_approval`&&s?(a9(`Human approval required for ${a}:`,o),this.#e().updateOperationMetadata(e,{needsHumanInput:!0,pendingApproval:o}),await Ls(this.#e,i.context),i.context.topicId&&(this.#e().updateTopicStatus?.({agentId:i.context.agentId,groupId:i.context.groupId,...i.context.scope===`group`||i.context.scope===`group_agent`?{scope:i.context.scope}:{},status:`waitingForHuman`,topicId:i.context.topicId}))?.catch(e=>{console.error(`[runAgent] updateTopicStatus failed:`,e)}),a9(`Stopping loading for human approval: ${a}`)):n===`tool_execution`&&r&&a9(`Tool execution started for ${a}: ${r.function?.name}`);break}case`step_complete`:{let{phase:n,result:r,executionTime:i,finalState:o}=t.data||{};n===`tool_execution`&&r?a9(`Tool execution completed for ${a} in ${i}ms:`,r):n===`execution_complete`&&o&&(a9(`Agent execution completed for ${a}:`,o),this.#e().updateOperationMetadata(e,{finalStatus:o.status}
6006),a9(`Stopping loading for completed agent: ${a}`));break}case`error`:{let{error:e,message:n,phase:r}=t.data||{};a9(`Error in ${r} for ${a}:`,e),this.#e().internal_handleAgentError(a,n||e||`Unknown agent error`);break}default:a9(`Handling event ${t.type} for ${a}:`,t);break}};internal_handleHumanIntervention=async(e,t,n)=>{let r=this.#e().messageOperationMap[e];if(!r){a9(`No operation found for assistant message ${e}`);return}let i=this.#e().operations[r];if(!i||!i.metadata.needsHumanInput){a9(`No human intervention needed for operation ${r}`);return}try{a9(`Handling human intervention ${t} for operation ${r}:`,n),await IWe.handleHumanIntervention({action:t,data:n,operationId:r}),this.#e().updateOperationMetadata(r,{needsHumanInput:!1,pendingApproval:void 0,pendingPrompt:void 0,pendingSelect:void 0}),a9(`Human intervention ${t} processed for operation ${r}`)}catch(t){a9(`Failed to handle human intervention for operation ${r}:`,t),this.#e().internal_handleAgentError(e,`Human intervention failed: ${t.message}`)}}}})),tGe,nGe=e((()=>{ft(),BWe(),ZWe(),eGe(),tGe=(...e)=>rt([new $We(...e),new zWe(...e),new XWe(...e)])}));function rGe(e,t){for(let n of e)if(t===n||n===`*`||n instanceof RegExp&&n.test(t))return!0;return!1}function iGe(e,t=globalThis,n=[`*`]){t.addEventListener(`message`,function r(i){if(!i||!i.data)return;if(!rGe(n,i.origin)){console.warn(`Invalid origin '${i.origin}' for comlink proxy`);return}let{id:a,type:o,path:s}=Object.assign({path:[]},i.data),c=(i.data.argumentList||[]).map(l9),l;try{let t=s.slice(0,-1).reduce((e,t)=>e[t],e),n=s.reduce((e,t)=>e[t],e);switch(o){case`GET`:l=n;break;case`SET`:t[s.slice(-1)[0]]=l9(i.data.value),l=!0;break;case`APPLY`:l=n.apply(t,c);break;case`CONSTRUCT`:l=mGe(new n(...c));break;case`ENDPOINT`:{let{port1:t,port2:n}=new MessageChannel;iGe(e,n),l=pGe(t,[t])}break;case`RELEASE`:l=void 0;break;default:return}}catch(e){l={value:e,[p9]:0}}Promise.resolve(l).catch(e=>({value:e,[p9]:0})).then(n=>{let[i,s]=c9(n);t.postMessage(Object.assign(Object.assign({},i),{id:a}),s),o===`RELEASE`&&(t.removeEventListener(`message`,r),oGe(t),f9 in e&&typeof e[f9]==`function`&&e[f9]())}).catch(e=>{let[n,r]=c9({value:TypeError(`Unserializable return value`),[p9]:0});t.postMessage(Object.assign(Object.assign({},n),{id:a}),r)})}),t.start&&t.start()}function aGe(e){return e.constructor.name===`MessagePort`}function oGe(e){aGe(e)&&e.close()}function sGe(e,t){let n=new Map;return e.addEventListener(`message`,function(e){let{data:t}=e;if(!t||!t.id)return;let r=n.get(t.id);if(r)try{r(t)}finally{n.delete(t.id)}}),s9(e,n,[],t)}function o9(e){if(e)throw Error(`Proxy has been released and is not useable`)}function cGe(e){return u9(e,new Map,{type:`RELEASE`}).then(()=>{oGe(e)})}function lGe(e,t){let n=(g9.get(t)||0)+1;g9.set(t,n),_9&&_9.register(e,t,e)}function uGe(e){_9&&_9.unregister(e)}function s9(e,t,n=[],r=function(){}){let i=!1,a=new Proxy(r,{get(r,o){if(o9(i),o===_Ge)return()=>{uGe(a),cGe(e),t.clear(),i=!0};if(o===`then`){if(n.length===0)return{then:()=>a};let r=u9(e,t,{type:`GET`,path:n.map(e=>e.toString())}).then(l9);return r.then.bind(r)}return s9(e,t,[...n,o])},set(r,a,o){o9(i);let[s,c]=c9(o);return u9(e,t,{type:`SET`,path:[...n,a].map(e=>e.toString()),value:s},c).then(l9)},apply(r,a,o){o9(i);let s=n[n.length-1];if(s===gGe)return u9(e,t,{type:`ENDPOINT`}).then(l9);if(s===`bind`)return s9(e,t,n.slice(0,-1));let[c,l]=fGe(o);return u9(e,t,{type:`APPLY`,path:n.map(e=>e.toString()),argumentList:c},l).then(l9)},construct(r,a){o9(i);let[o,s]=fGe(a);return u9(e,t,{type:`CONSTRUCT`,path:n.map(e=>e.toString()),argumentList:o},s).then(l9)}});return lGe(a,e),a}function dGe(e){return Array.prototype.concat.apply([],e)}function fGe(e){let t=e.map(c9);return[t.map(e=>e[0]),dGe(t.map(e=>e[1]))]}function pGe(e,t){return v9.set(e,t),e}function mGe(e){return Object.assign(e,{[d9]:!0})}function c9(e){for(let[t,n]of h9)if(n.canHandle(e)){let[r,i]=n.serialize(e);return[{type:`HANDLER`,name:t,value:r},i]}return[{type:`RAW`,value:e},v9.get(e)||[]]}function l9(e){switch(e.type){case`HANDLER`:return h9.get(e.name).deserialize(e.value);case`RAW`:return e.value}}function u9(e,t,n,r){return new Promise(i=>{let a=hGe();t.set(a,i),e.start&&e.start(),e.postMessage(Object.assign({id:a},n),r)})}function hGe(){return[,,,,].fill(0).map(()=>Math.floor(Math.random()*(2**53-1)).toString(16)).join(`-`)}var d9,gGe,_Ge,f9,p9,m9,h9,g9,_9,v9,vGe=e((()=>{d9=Symbol(`Comlink.proxy`),gGe=Symbol(`Comlink.endpoint`),_Ge=Symbol(`Comlink.releaseProxy`),f9=Symbol(`Comlink.finalizer`),p9=Symbol(`Comlink.thrown`),m9=e=>typeof e==`object`&&!!e||typeof e==`function`,h9=new Map([[`proxy`,{canHandle:e=>m9(e)&&e[d9],serialize(e){let{port1:t,port2:n}=new MessageChannel;return iGe(e,t),[n,[n]]},deserialize(e){return e.start(),sGe(e)}}],[`throw`,{canHandle:e=>m9(e)&&p9 in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(Error(e.value.message),e.value):e.value}}]]),g9=new WeakMap,_9=`FinalizationRegistry`in globalThis&&new FinalizationRegistry(e=>{let t=(g9.get(e)||0)-1;g9.set(e,t),t===0&&cGe(e)}),v9=new WeakMap})),yGe,bGe=e((()=>{vGe(),yGe=(()=>
6006{if(typeof Worker<`u`)return sGe(new Worker(new URL(`/assets/worker-Dt8VOL8K.js`,``+import.meta.url),{type:`module`}))})()})),xGe=e((()=>{})),SGe=e((()=>{bGe(),xGe()})),CGe,y9,wGe=e((()=>{yre(),qi(),CGe=()=>bre({clientPrefix:`NEXT_PUBLIC_`,client:{NEXT_PUBLIC_PYODIDE_INDEX_URL:Wi().url().optional(),NEXT_PUBLIC_PYODIDE_PIP_INDEX_URL:Wi().url().optional()},runtimeEnv:{NEXT_PUBLIC_PYODIDE_INDEX_URL:{}.NEXT_PUBLIC_PYODIDE_INDEX_URL,NEXT_PUBLIC_PYODIDE_PIP_INDEX_URL:{}.NEXT_PUBLIC_PYODIDE_PIP_INDEX_URL}}),y9=CGe()})),TGe,EGe,DGe=e((()=>{SGe(),wGe(),TGe=class{async runPython(e,t,n){if(typeof Worker>`u`)return;let r=await new yGe({pyodideIndexUrl:y9.NEXT_PUBLIC_PYODIDE_INDEX_URL,pypiIndexUrl:y9.NEXT_PUBLIC_PYODIDE_PIP_INDEX_URL});await r.init(),await r.installPackages(t.filter(e=>e!==``)),await r.uploadFiles(n);let i=await r.runPython(e);return{files:(await r.downloadFiles()).map(e=>({data:e,filename:e.name,previewUrl:URL.createObjectURL(e)})),...i}}},EGe=new TGe})),OGe,kGe,b9,AGe,jGe=e((()=>{NG(),OGe=t(F()),it(),qte(),Qi(),oa(),Tie(),DGe(),Oi(),Eie(),Dr(),kGe=kr(`codeInterpreter`),b9=(0,OGe.default)(`lobe-store:builtin-tool`),AGe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}python=async(e,t)=>{let n=this.#e().messageOperationMap[e],{operationId:r,abortController:i}=this.#e().startOperation({context:{messageId:e},metadata:{startTime:Date.now()},parentOperationId:n,type:`builtinToolInterpreter`});b9(`[python] messageId=%s, parentOpId=%s, interpreterOpId=%s, aborted=%s`,e,n,r,i.signal.aborted);let a={operationId:r};try{let n=[];for(let e of ci.dbUserMessages(this.#e())){for(let t of e.fileList??[]){if(t.inaccessible)continue;let e=await fetch(t.url).then(e=>e.blob());n.push(new File([e],t.name))}for(let t of e.imageList??[]){let e=await fetch(t.url).then(e=>e.blob());n.push(new File([e],t.alt))}for(let t of e.tools??[])if(t.identifier===`lobe-cloud-sandbox`){let e=ci.getDbMessageByToolCallId(t.id)(this.#e());if(e?.content){let t=JSON.parse(e.content);for(let e of t.files??[]){let t=await mo.getFile(e.fileId),r=await fetch(t.url).then(e=>e.blob());n.push(new File([r],e.filename))}}}}let i=await EGe.runPython(t.code,t.packages,n);return this.#e().completeOperation(r),i?.files?(await this.#e().optimisticUpdateMessageContent(e,JSON.stringify(i),void 0,a),await this.#e().uploadInterpreterFiles(e,i.files)):await this.#e().optimisticUpdateMessageContent(e,JSON.stringify(i),void 0,a),!0}catch(t){let n=t;if(b9(`[python] Error: messageId=%s, error=%s`,e,n.message),n.message.includes(`The user aborted a request.`)||n.name===`AbortError`){b9(`[python] Request aborted: messageId=%s`,e),this.#e().failOperation(r,{message:`User cancelled the request`,type:`UserAborted`});return}this.#e().failOperation(r,{message:n.message,type:`PluginServerError`}),await this.#e().optimisticUpdatePluginState(e,{error:t},a);return}};updateInterpreterFileItem=async(e,t)=>{let n=ci.getDbMessageById(e)(this.#e());if(!n)return;let r=JSON.parse(n.content);if(!r.files)return;let i=tt(r,t);await this.#e().optimisticUpdateMessageContent(e,JSON.stringify(i))};uploadInterpreterFiles=async(e,t)=>{let{updateInterpreterFileItem:n}=this.#e();t&&await Kte(t,async(t,r)=>{if(t.data)try{let i=await aie.getState().uploadWithProgress({file:t.data,skipCheckFileType:!0});i?.id&&await n(e,e=>{e.files?.[r]&&(e.files[r].fileId=i.id,e.files[r].previewUrl=void 0,e.files[r].data=void 0)})}catch(e){console.error(`Failed to upload CodeInterpreter file:`,e)}})};useFetchInterpreterFileItem=e=>Xi(e?sre.interpreterFile(e):null,async()=>{if(!e)return null;let t=await mo.getFile(e);return this.#t(tt(n=>{n.codeInterpreterFileMap||={},!n.codeInterpreterFileMap[e]&&(n.codeInterpreterFileMap[e]=t)}),!1,kGe(`useFetchInterpreterFileItem`)),t})}})),MGe,NGe=e((()=>{zJ(),Oi(),MGe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}togglePageContent=e=>{this.#t({activePageContentUrl:e})};triggerSearchAgain=async(e,t)=>{let n=ci.getDbMessageById(e)(this.#e());if(!n)return;let r=this.#e().messageOperationMap[e],i=r?{operationId:r}:void 0;await this.#e().optimisticUpdatePluginArguments(e,t,!1,i);let a={apiName:PJ.search,arguments:JSON.stringify(t),id:n.tool_call_id,identifier:LJ.identifier,type:`builtin`};await this.#e().invokeBuiltinTool(e,a)}}})),PGe,FGe=e((()=>{ft(),jGe(),NGe(),PGe=(...e)=>rt([new MGe(...e),new AGe(...e)])})),IGe,LGe,RGe,zGe=e((()=>{IGe=e=>e.filter(e=>(e.role===`user`||e.role===`assistant`)&&!!e.content?.trim()||e.role===`assistantGroup`&&!!e.children?.some(e=>!!e.content?.trim())),LGe=(e,t)=>
6006`**${e}**\n\n${t.trim()}`,RGe=(e,t)=>{let n=IGe(e).map(e=>{let n=e.role===`assistantGroup`?e.children?.map(e=>e.content?.trim()).filter(Boolean).join(`
6007
6008`)||``:e.content,r=e.role===`user`?`user`:`assistant`;return LGe(t.roleLabel(r),n)});return[t.header,...n].join(`
6009
6010---
6011
6012`)}})),BGe,VGe=e((()=>{dt(),Na(),Gr(),qr(),zGe(),BGe=class{#e;constructor(e,t,n){this.#e=t}forwardMessages=async({header:e,messages:t,note:n,onTopicCreated:r,roleLabel:i,targets:a})=>{if(a.length===0)return{failed:[],succeeded:[]};let o=RGe(t,{header:e,roleLabel:i}),s=n?.trim()?`${o}\n\n${n.trim()}`:o;return(await Promise.allSettled(a.map(async e=>{let{id:t}=e;if(!Rr.getAgentConfigById(t)(Xr())){let e=await ht.getAgentConfigById(t);if(!e)throw Error(`Forwarding target agent not found: ${t}`);Xr().internal_dispatchAgentMap(t,e)}let n=await this.#e().sendMessage({context:{agentId:t,isNew:!0,isolatedTopic:!0,scope:`main`},message:s,messages:[],onTopicCreated:t=>r?.(e,t)});if(!n?.createdTopicId)throw Error(`Forwarding did not create a topic for ${t}`);return{agentId:t,topicId:n.createdTopicId}}))).reduce((e,t,n)=>(t.status===`fulfilled`?e.succeeded.push(t.value):e.failed.push({agentId:a[n].id,error:t.reason}),e),{failed:[],succeeded:[]})};forwardTopic=async({sourceAgentId:e,topicId:t,...n})=>{let r=await Ma.getMessages({agentId:e,topicId:t});return this.forwardMessages({...n,messages:r})}}})),HGe,UGe,WGe=e((()=>{lo(),Er(),Ta(),HGe=class{request=async e=>{try{return fetch(uo.trace,{body:JSON.stringify(e),headers:{"Content-Type":`application/json`},method:`POST`})}catch(e){console.error(e)}};traceEvent=async e=>{if(Ca.telemetry(Or.getState()))return this.request(e)}},UGe=new HGe})),GGe,KGe,qGe,JGe=e((()=>{GGe=t(le()),f(),it(),Te(),KGe=e=>e&&(_t(e)?nt(e):e),qGe=(e,t)=>{switch(t.type){case`updateMessage`:return tt(e,e=>{let{id:n,value:r}=t,i=e.findIndex(e=>e.id===n);i>=0&&(e[i]=Ce(e[i],{...r,updatedAt:Date.now()}))});case`replaceMessagePluginState`:return tt(e,e=>{let{id:n,metadata:r,value:i}=t,a=e.find(e=>e.id===n);!a||a.role!==`tool`||(a.pluginState=i,r&&(a.metadata=Ce(a.metadata,r)),a.updatedAt=Date.now())});case`updateMessageExtra`:return tt(e,e=>{let{id:n,key:r,value:i}=t,a=e.find(e=>e.id===n);a&&(a.extra?a.extra[r]=i:a.extra={[r]:i},a.updatedAt=Date.now())});case`updateMessageMetadata`:return tt(e,e=>{let{id:n,value:r}=t,i=e.find(e=>e.id===n);i&&(i.metadata=Ce(i.metadata,r),i.updatedAt=Date.now())});case`updatePluginState`:return tt(e,e=>{let{id:n,key:r,value:i}=t,a=e.find(e=>e.id===n);if(!a)return;let o=KGe(a.pluginState),s;s=o?Ce(o,{[r]:i}):{[r]:i},!(0,GGe.default)(o,s)&&(a.pluginState=s,a.updatedAt=Date.now())});case`updateMessagePlugin`:return tt(e,e=>{let{id:n,value:r}=t,i=e.find(e=>e.id===n);!i||i.role!==`tool`||(i.plugin=Ce(i.plugin,r),i.updatedAt=Date.now())});case`addMessageTool`:return tt(e,e=>{let{id:n,value:r}=t,i=e.find(e=>e.id===n);if(!(!i||i.role!==`assistant`)){if(!i.tools)i.tools=[r];else{if(i.tools.findIndex(e=>e.id===r.id)>0)return;i.tools.push(r)}i.updatedAt=Date.now()}});case`deleteMessageTool`:return tt(e,e=>{let{id:n,tool_call_id:r}=t,i=e.find(e=>e.id===n);!i||i.role!==`assistant`||!i.tools||(i.tools=i.tools.filter(e=>e.id!==r),i.updatedAt=Date.now())});case`updateMessageTools`:return tt(e,e=>{let{id:n,value:r,tool_call_id:i}=t,a=e.find(e=>e.id===n);if(!a||a.role!==`assistant`||!a.tools)return;let o=a.tools.findIndex(e=>e.id===i);o<0||(a.tools[o]=Ce(a.tools[o],r),a.updatedAt=Date.now())});case`createMessage`:return tt(e,e=>{let{value:n,id:r}=t;e.push({...n,createdAt:Date.now(),id:r,updatedAt:Date.now()})});case`updateMessages`:return t.value;case`deleteMessage`:return tt(e,e=>{let{id:n}=t,r=e.findIndex(e=>e.id===n);r>=0&&e.splice(r,1)});case`deleteMessages`:return tt(e,e=>{let{ids:n}=t;return e.filter(e=>!n.includes(e.id))});default:throw Error(p.t(`errors.unimplementedType`,{ns:`common`}))}}})),x9,YGe=e((()=>{x9=e=>{let t=new Map;for(let n of e)t.set(n.id,n);let n;for(let r of e){if(r.role!==`tool`||!r.tool_call_id||!r.parentId)continue;let e=t.get(r.parentId);if(!e||e.role!==`assistant`||(e.tools??[]).some(e=>e.id===r.tool_call_id))continue;let i={apiName:r.plugin?.apiName??``,arguments:r.plugin?.arguments??`{}`,id:r.tool_call_id,identifier:r.plugin?.identifier??``,result_msg_id:r.id,type:r.plugin?.type??`default`};n??=new Map;let a=n.get(r.parentId);a?a.push(i):n.set(r.parentId,[i])}return n?e.map(e=>{let t=n.get(e.id);return t?{...e,tools:[...e.tools??[],...t]}:e}):e}})),XGe,ZGe,QGe,$Ge,eKe=e((()=>
6012{g0(),XGe=t(F()),ZGe=t(le()),WGe(),Oi(),wi(),JGe(),YGe(),QGe=(0,XGe.default)(`lobe-store:message-internals`),$Ge=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}internal_dispatchMessage=(e,t)=>{let n=this.#e().internal_getConversationContext(t);QGe(`[internal_dispatchMessage] context: agentId=%s, topicId=%s, threadId=%s, scope=%s`,n.agentId,n.topicId,n.threadId,n.scope);let r=li(n),i=x9(qGe(this.#e().dbMessagesMap[r]||[],e)),a={...this.#e().dbMessagesMap,[r]:i};if((0,ZGe.default)(a,this.#e().dbMessagesMap))return;let{flatList:o}=h0(i),s={...this.#e().messagesMap,[r]:o};this.#t({dbMessagesMap:a,messagesMap:s},!1,{payload:e,type:`dispatchMessage/${e.type}`})};internal_traceMessage=async(e,t)=>{let n=ui.getDisplayMessageById(e)(this.#e());if(!n)return;let r=n?.traceId,i=n?.observationId;r&&n?.role===`assistant`&&UGe.traceEvent({content:n.content,observationId:i,traceId:r,...t}).catch()}}})),tKe,nKe=e((()=>{Ne(),R(),Na(),di(),tKe=class{#e;constructor(e,t,n){this.#e=t}optimisticCreateMessage=async(e,t)=>{let{optimisticCreateTmpMessage:n,internal_dispatchMessage:r,replaceMessages:i}=this.#e(),a=t?.tempMessageId;a||=n(e,t);try{let n=await Ma.createMessage(e),r=this.#e().internal_getConversationContext(t);return i(n.messages,{context:r}),n}catch(e){r({id:a,type:`updateMessage`,value:{error:{body:e,message:e.message,type:be.CreateMessageError}}},t)}};optimisticCreateTmpMessage=(e,t)=>{let{internal_dispatchMessage:n}=this.#e(),r=t?.tempMessageId||`tmp_`+ke();return n({id:r,type:`createMessage`,value:e},t),r};optimisticDeleteMessage=async(e,t)=>{this.#e().internal_dispatchMessage({id:e,type:`deleteMessage`},t);let n=this.#e().internal_getConversationContext(t),r=await Ma.removeMessage(e,n);r?.success&&r.messages&&this.#e().replaceMessages(r.messages,{context:n})};optimisticDeleteMessages=async(e,t)=>{this.#e().internal_dispatchMessage({ids:e,type:`deleteMessages`},t);let n=this.#e().internal_getConversationContext(t),r=await Ma.removeMessages(e,n);r?.success&&r.messages&&this.#e().replaceMessages(r.messages,{context:n})};optimisticUpdateMessageContent=async(e,t,n,r)=>{let{internal_dispatchMessage:i,refreshMessages:a,replaceMessages:o}=this.#e();n?.tools?i({id:e,type:`updateMessage`,value:{tools:n?.tools}},r):i({id:e,type:`updateMessage`,value:{content:t,metadata:n?.metadata}},r);let s=this.#e().internal_getConversationContext(r),c=await Ma.updateMessage(e,{content:t,imageList:n?.imageList,metadata:n?.metadata,model:n?.model,provider:n?.provider,reasoning:n?.reasoning,search:n?.search,tools:n?.tools},s);c&&c.success&&c.messages?o(c.messages,{action:`optimisticUpdateMessageContent`,context:s}):await a()};optimisticUpdateMessageError=async(e,t,n)=>{this.#e().internal_dispatchMessage({id:e,type:`updateMessage`,value:{error:t}},n);let r=this.#e().internal_getConversationContext(n),i=await Ma.updateMessage(e,{error:t},r);i?.success&&i.messages?this.#e().replaceMessages(i.messages,{context:r}):await this.#e().refreshMessages()};optimisticUpdateMessageMetadata=async(e,t,n)=>{let{internal_dispatchMessage:r,refreshMessages:i,replaceMessages:a}=this.#e();r({id:e,type:`updateMessageMetadata`,value:t},n);let o=this.#e().internal_getConversationContext(n),s=await Ma.updateMessageMetadata(e,t,o);s?.success&&s.messages?a(s.messages,{context:o}):await i()};optimisticUpdateMessagePlugin=async(e,t,n)=>{let{internal_dispatchMessage:r,replaceMessages:i}=this.#e(),a=ci.getDbMessageById(e)(this.#e());r({id:e,type:`updateMessagePlugin`,value:t},n),a?.parentId&&a.tool_call_id&&r({id:a.parentId,type:`updateMessageTools`,tool_call_id:a.tool_call_id,value:t},n);let o=this.#e().internal_getConversationContext(n),s=await Ma.updateMessagePlugin(e,t,o);s?.success&&s.messages&&i(s.messages,{context:o})};optimisticUpdateMessagePluginError=async(e,t,n)=>{let r=this.#e().internal_getConversationContext(n),i=await Ma.updateMessagePluginError(e,t,r);i?.success&&i.messages&&this.#e().replaceMessages(i.messages,{context:r})};optimisticUpdateMessageRAG=async(e,t,n)=>{let r=this.#e().internal_getConversationContext(n),i=await Ma.updateMessageRAG(e,t,r);i?.success&&i.messages&&this.#e().replaceMessages(i.messages,{context:r})}}})),S9,C9,rKe=e((()=>{Wt(),f(),it(),S9=e=>{e.returnValue=p.t(`beforeUnload.confirmLeave`,{ns:`chat`})},C9=(e,t,n)=>tt(e,e=>
6012{if(n)e.includes(t)||e.push(t);else{let n=e.indexOf(t);n>=0&&e.splice(n,1)}})})),iKe,aKe,oKe,sKe=e((()=>{Ne(),Pn(),iKe=t(le()),Na(),Fa(),Dr(),Oi(),rKe(),aKe=kr(`m`),oKe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}addAIMessage=async()=>{let{optimisticCreateMessage:e,updateMessageInput:t,activeTopicId:n,activeAgentId:r,activeThreadId:i,activeGroupId:a,inputMessage:o}=this.#e();r&&await e({content:o,role:`assistant`,agentId:r,topicId:n,threadId:i,groupId:a,parentId:ui.lastDisplayMessageId(this.#e())})&&t(``)};addUserMessage=async({message:e,fileList:t,metadata:n})=>{let{optimisticCreateMessage:r,updateMessageInput:i,activeTopicId:a,activeAgentId:o,activeThreadId:s,activeGroupId:c}=this.#e();o&&await r({content:e,files:t,role:`user`,agentId:o,topicId:a,threadId:s,groupId:c,parentId:ui.lastDisplayMessageId(this.#e()),...n?{metadata:n}:{}})&&i(``)};deleteAssistantMessage=async(e,t)=>{let n=ci.getDbMessageById(e)(this.#e());if(!n)return;let r=[n.id];if(n.tools){let e=ci.activeDbMessages(this.#e()),t=n.tools.flatMap(t=>e.filter(e=>e.tool_call_id===t.id).map(e=>e.id));r=r.concat(t)}await this.#e().optimisticDeleteMessages(r,t)};deleteMessage=async(e,t)=>{let n=ui.getDisplayMessageById(e)(this.#e());if(!n)return;let r=[n.id];if(n.role===`assistantGroup`&&n.children){let e=n.children.map(e=>e.id);r=r.concat(e);let t=n.children.flatMap(e=>e.tools?e.tools.filter(e=>e.result?.id).map(e=>e.result.id):[]);r=r.concat(t)}await this.#e().optimisticDeleteMessages(r,t)};deleteDBMessage=async e=>{let t=ci.getDbMessageById(e)(this.#e());if(!t)return;let n=[t.id];this.#e().internal_dispatchMessage({type:`deleteMessages`,ids:n});let r=this.#e().internal_getConversationContext(),i=await Ma.removeMessages(n,r);i?.success&&i.messages&&this.#e().replaceMessages(i.messages,{context:r})};deleteToolMessage=async e=>{let t=ci.getDbMessageById(e)(this.#e());if(!t||t.role!==`tool`)return;let n=this.#e().messageOperationMap[e],r=n?{operationId:n}:void 0;await Promise.all([this.#e().optimisticDeleteMessage(e,r),(async()=>{t.parentId&&await this.#e().optimisticRemoveToolFromAssistantMessage(t.parentId,t.tool_call_id,r)})()])};clearMessage=async()=>{let{activeAgentId:e,activeTopicId:t,activeGroupId:n,refreshTopic:r,switchTopic:i}=this.#e();n?await Ma.removeMessagesByGroup(n,t):await Ma.removeMessagesByAssistant(e,t),t&&await Pa.removeTopic(t),await r(),this.#e().replaceMessages([]),i(null)};copyMessage=async(e,t)=>{await wn(t),this.#e().internal_traceMessage(e,{eventType:we.CopyMessage})};toggleMessageEditing=(e,t)=>{this.#t({messageEditingIds:C9(this.#e().messageEditingIds,e,t)},!1,`toggleMessageEditing`)};updateMessageInput=e=>{(0,iKe.default)(e,this.#e().inputMessage)||this.#t({inputMessage:e},!1,aKe(`updateMessageInput`,e))};modifyMessageContent=async(e,t,n)=>{this.#e().internal_traceMessage(e,{eventType:we.ModifyMessage,nextContent:t}),await this.#e().optimisticUpdateMessageContent(e,t,void 0,n)};toggleMessageCollapsed=async(e,t,n)=>{let r=ui.getDisplayMessageById(e)(this.#e());if(!r)return;let i=t??!r.metadata?.collapsed;await this.#e().optimisticUpdateMessageMetadata(e,{collapsed:i},n)};toggleInspectExpanded=async(e,t,n)=>{let r=ci.getDbMessageById(e)(this.#e());if(!r)return;let i=t??!r.metadata?.inspectExpanded;await this.#e().optimisticUpdateMessageMetadata(e,{inspectExpanded:i},n)}}})),cKe,lKe,w9,uKe,dKe,fKe=e((()=>{g0(),cKe=t(F()),lKe=t(le()),Qi(),oa(),Na(),k0(),Ai(),wi(),YGe(),w9=new Set,uKe=(0,cKe.default)(`lobe-client:message-query`),dKe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}revalidateMessages=async e=>{let t=e?.agentId??this.#e().activeAgentId,n=e?.topicId===void 0?this.#e().activeTopicId:e.topicId,r=e?.groupId===void 0?this.#e().activeGroupId:e.groupId,i=e?.threadId===void 0?this.#e().activeThreadId:e.threadId;T0({agentId:t,groupId:r,threadId:i,topicId:n})||await Zi(x0({agentId:t,groupId:r,threadId:i,topicId:n}))};refreshMessages=async e=>{let t=e?.agentId??this.#e().activeAgentId,n=e?.topicId===void 0?this.#e().activeTopicId:e.topicId;UDe(e=>e.agentId===t&&e.topicId===n),await Zi(e=>ta(e,e=>e.agentId===t&&e.topicId===n))};prefetchMessages=async e=>{if(!e.agentId||!e.topicId)return;let t=S0(e);if(pi.isAgentRuntimeRunningByContext(e)(this.#e())||T0(e)||w9.has(t))return;w9.add(t);let n=O0(e,Ma.getMessages).then(t=>(this.#e().replaceMessages(t,{action:`prefetchMessages`,context:e}),t));try{await Zi(x0(e),n,{revalidate:!1}),await n}catch(e){uKe(`Failed to warm the message cache: %O`,e)}finally{w9.delete(t)}};replaceMessages=(e,t)=>{let n;n=t?.context?{...t.context,agentId:t.context.agentId??this.#e().activeAgentId,topicId:t.context.topicId===void 0?this.#e().activeTopicId:t.context.topicId}:t?.operationId?this.#e().internal_getConversationContext(t):{agentId:this.#e().activeAgentId,groupId:this.#e().activeGroupId,threadId:this.#e().activeThreadI
6012d,topicId:this.#e().activeTopicId};let r=li(n),i=e;if(t?.preserveWorks){let t=new Map((this.#e().dbMessagesMap[r]??[]).filter(e=>e.works?.length).map(e=>[e.id,e.works]));t.size>0&&(i=e.map(e=>!e.works&&t.has(e.id)?{...e,works:t.get(e.id)}:e))}let a=x9(i),o={...this.#e().dbMessagesMap,[r]:a};if(this.#n(n,r,a,t?.action),(0,lKe.default)(o,this.#e().dbMessagesMap))return;let{flatList:s}=h0(a);this.#t({dbMessagesMap:o,messagesMap:{...this.#e().messagesMap,[r]:s}},!1,t?.action??`replaceMessages`)};#n=(e,t,n,r)=>{!e.agentId||!e.topicId||pi.isAgentRuntimeRunningByContext(e)(this.#e())||r===`useFetchMessages`||r===`prefetchMessages`||t===li({agentId:e.agentId,groupId:e.groupId,scope:e.threadId?`thread`:e.groupId?`group`:`main`,threadId:e.threadId,topicId:e.topicId})&&Zi(x0(e),n,{revalidate:!1})};useFetchMessages=(e,t)=>{let{skipFetch:n,revalidateOnFocus:r}=t??{};return $i(!n&&e.agentId&&e.topicId?x0(e):null,()=>O0(e,Ma.getMessages),{...E0(e),onData:t=>{!t||!e.topicId||this.#e().replaceMessages(t,{action:`useFetchMessages`,context:e})},...r!==void 0&&{revalidateOnFocus:r}})}}})),pKe,mKe=e((()=>{rKe(),pKe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}internal_toggleLoadingArrays=(e,t,n,r)=>{let i=`${e}AbortController`;if(t){window.addEventListener(`beforeunload`,S9);let a=new AbortController;return this.#t({[i]:a,[e]:C9(this.#e()[e],n,t)},!1,r),a}else n?this.#t({[i]:void 0,[e]:C9(this.#e()[e],n,t)},!1,r):this.#t({[i]:void 0,[e]:[]},!1,r),window.removeEventListener(`beforeunload`,S9)}}})),hKe,gKe=e((()=>{ft(),eKe(),nKe(),sKe(),fKe(),mKe(),hKe=(...e)=>rt([new oKe(...e),new tKe(...e),new dKe(...e),new pKe(...e),new $Ge(...e)])})),_Ke,T9,E9,D9,vKe,yKe=e((()=>{R(),_Ke=t(F()),it(),wi(),Ti(),e6(),Dr(),si(),T9=kr(`operation`),E9=(0,_Ke.default)(`lobe-store:operation`),D9=(e,t)=>(e??null)===(t??null),vKe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}internal_getConversationContext=e=>{if(e?.operationId){let t=this.#e().operations[e.operationId];if(!t)E9(`[internal_getConversationContext] WARNING: Operation not found, falling back to global state: %s`,e.operationId),console.warn(`[internal_getConversationContext] operation not found, using global state:`,e.operationId);else{let{agentId:n,topicId:r,threadId:i,scope:a,isNew:o,groupId:s,documentId:c}=t.context;return E9(`[internal_getConversationContext] get from operation %s: agentId=%s, topicId=%s, threadId=%s, scope=%s, groupId=%s, documentId=%s`,e.operationId,n,r,i,a,s,c),{...t.context,agentId:n}}}let t=this.#e().activeAgentId,n=this.#e().activeGroupId,r=this.#e().activeTopicId,i=this.#e().activeThreadId;return E9(`[internal_getConversationContext] use global state: `,{agentId:t,topicId:r,threadId:i,groupId:n}),{agentId:t,topicId:r,threadId:i,groupId:n}};startOperation=e=>{let{type:t,context:n,parentOperationId:r,label:i,description:a,metadata:o,operationId:s}=e,c=s||`op_${ke()}`,l=n||{};if(r){let e=this.#e().operations[r];e&&(l={...e.context,...n},E9(`[startOperation] inherit context from parent %s: %o`,r,l))}E9(`[startOperation] create operation %s (type=%s, context=%o)`,c,t,l);let u=new AbortController,d={id:c,type:t,status:`running`,context:l,abortController:u,metadata:{startTime:Date.now(),...o},parentOperationId:r,childOperationIds:[],label:i,description:a};return this.#t(tt(e=>{if(e.operations[c]=d,e.operationsByType[t]||(e.operationsByType[t]=[]),e.operationsByType[t].push(c),l.messageId&&(e.operationsByMessage[l.messageId]||(e.operationsByMessage[l.messageId]=[]),e.operationsByMessage[l.messageId].push(c),e.messageOperationMap[l.messageId]=c),l.agentId){let t=li(l);e.operationsByContext[t]||(e.operationsByContext[t]=[]),e.operationsByContext[t].push(c)}r&&e.operations[r]&&(e.operations[r].childOperationIds||(e.operations[r].childOperationIds=[]),e.operations[r].childOperationIds.push(c))}),!1,T9(`startOperation/${t}/${c}`)),r||this.#e().cleanupCompletedOperations(3e4),{operationId:c,abortController:u}};updateOperationMetadata=(e,t)=>{let n=this.#e().operations[e];t.isAborting&&E9(`[updateOperationMetadata] Setting isAborting=true for operation %s (type=%s)`,e,n?.type),this.#t(tt(n=>{let r=n.operations[e];r&&(r.metadata={...r.metadata,...t})}),!1,T9(`updateOperationMetadata/${e}`))};updateOperationStatus=(e,t,n)=>{this.#t(tt(r=>{let i=r.operations[e];i&&(i.status=t,n&&(i.metadata={...i.metadata,...n}))}),!1,T9(`updateOperationStatus/${e}/${t}`))};updateOperationProgress=(e,t,n)=>{this.#t(tt(r=>{let i=r.operations[e];i&&(i.metadata.progress={current:t,total:n??i.metadata.progress?.total??t,percentage:n?Math.round(t/n*100):void 0})}),!1,T9(`updateOperationProgress/${e}`))};completeOperation=(e,t)=>{let n=this.#e().operations[e];n&&E9(`[completeOperation] operation %s (type=%s) completed, duration=%dms`,e,n.type,Date.now()-n.metadata.startTime),this.#t(tt(n=>{let r=n.operations[e];if(!r)return;let i=Date.now();r.status!==`cancelled`&&(r.status=`completed`),r.metadata.endTime=i,r.metadata.duration=i-r.metadata.startTime,t&&(r.metadata={...r.metadata,...t})}),!1,T9(`completeOperation/${e}`))};getOperationAbortSignal=e=>{let t=this.#e().operations[e];if(!t)throw Error(`[getOperationAbortSignal] Operation not found: ${e}`);return t.abortController.signal};onOperationCancel=(e,t)=>
6012{this.#t(tt(n=>{let r=n.operations[e];if(!r){E9(`[onOperationCancel] WARNING: Operation not found: %s`,e);return}r.onCancelHandler=t,E9(`[onOperationCancel] registered cancel handler for %s (type=%s)`,e,r.type)}),!1,T9(`onOperationCancel/${e}`))};registerAfterCompletionCallback=(e,t)=>{this.#t(tt(n=>{let r=n.operations[e];if(!r){E9(`[registerAfterCompletionCallback] WARNING: Operation not found: %s`,e);return}r.metadata.runtimeHooks||(r.metadata.runtimeHooks={}),r.metadata.runtimeHooks.afterCompletionCallbacks||(r.metadata.runtimeHooks.afterCompletionCallbacks=[]),r.metadata.runtimeHooks.afterCompletionCallbacks.push(t),E9(`[registerAfterCompletionCallback] registered callback for %s (type=%s), total callbacks: %d`,e,r.type,r.metadata.runtimeHooks.afterCompletionCallbacks.length)}),!1,T9(`registerAfterCompletionCallback/${e}`))};cancelOperation=(e,t=`User cancelled`)=>{let n=this.#e().operations[e];if(!n){E9(`[cancelOperation] operation not found: %s`,e);return}if(n.status===`cancelled`||n.status===`completed`){E9(`[cancelOperation] operation %s already %s, skipping`,e,n.status);return}E9(`[cancelOperation] cancelling operation %s (type=%s), reason: %s`,e,n.type,t);try{n.abortController.abort(t)}catch{}if(oi.includes(n.type)&&this.#e().updateOperationMetadata(e,{isAborting:!0}),n.onCancelHandler){E9(`[cancelOperation] calling cancel handler for %s (type=%s)`,e,n.type);let r={operationId:e,type:n.type,reason:t,metadata:n.metadata};try{Promise.resolve(n.onCancelHandler(r)).catch(t=>{E9(`[cancelOperation] cancel handler error for %s: %O`,e,t)})}catch(t){E9(`[cancelOperation] cancel handler synchronous error for %s: %O`,e,t)}}this.#t(tt(n=>{let r=n.operations[e];if(!r)return;let i=Date.now();r.status=`cancelled`,r.metadata.endTime=i,r.metadata.duration=i-r.metadata.startTime,r.metadata.cancelReason=t}),!1,T9(`cancelOperation/${e}`)),n.childOperationIds&&n.childOperationIds.length>0&&(E9(`[cancelOperation] cancelling %d child operations`,n.childOperationIds.length),n.childOperationIds.forEach(e=>{this.#e().cancelOperation(e,`Parent operation cancelled`)}))};failOperation=(e,t)=>{let n=this.#e().operations[e];n&&E9(`[failOperation] operation %s (type=%s) failed: %s`,e,n.type,t.message),this.#t(tt(n=>{let r=n.operations[e];if(!r)return;let i=Date.now();r.status=`failed`,r.metadata.endTime=i,r.metadata.duration=i-r.metadata.startTime,r.metadata.error=t}),!1,T9(`failOperation/${e}`))};cancelOperations=(e,t=`Batch cancelled`)=>{let n=Object.values(this.#e().operations),r=[];return n.forEach(t=>{if(t.status!==`running`)return;let n=!0;if(e.type){let r=Array.isArray(e.type)?e.type:[e.type];n&&=r.includes(t.type)}if(e.status){let r=Array.isArray(e.status)?e.status:[e.status];n&&=r.includes(t.status)}e.agentId!==void 0&&(n&&=t.context.agentId===e.agentId),e.topicId!==void 0&&(n&&=D9(t.context.topicId,e.topicId)),e.messageId!==void 0&&(n&&=t.context.messageId===e.messageId),e.threadId!==void 0&&(n&&=D9(t.context.threadId,e.threadId)),e.groupId!==void 0&&(n&&=t.context.groupId===e.groupId),e.agentId!==void 0&&(n&&=t.context.agentId===e.agentId),n&&r.push(t.id)}),r.forEach(e=>{this.#e().cancelOperation(e,t)}),r};cancelAllOperations=(e=`Cancel all operations`)=>{Object.values(this.#e().operations).forEach(t=>{t.status===`running`&&this.#e().cancelOperation(t.id,e)})};cleanupCompletedOperations=(e=6e4)=>{let t=Date.now(),n=[];return Object.values(this.#e().operations).forEach(r=>{let i=r.status===`completed`||r.status===`cancelled`||r.status===`failed`,a=r.metadata.endTime&&t-r.metadata.endTime>e;i&&a&&n.push(r.id)}),n.length===0?0:(this.#t(tt(e=>{n.forEach(t=>{let n=e.operations[t];if(!n)return;delete e.operations[t];let r=e.operationsByType[n.type];if(r&&(e.operationsByType[n.type]=r.filter(e=>e!==t)),n.context.messageId){let r=e.operationsByMessage[n.context.messageId];r&&(e.operationsByMessage[n.context.messageId]=r.filter(e=>e!==t))}if(n.context.agentId){let r=li(n.context),i=e.operationsByContext[r];i&&(e.operationsByContext[r]=i.filter(e=>e!==t))}if(n.parentOperationId&&e.operations[n.parentOperationId]){let r=e.operations[n.parentOperationId];r.childOperationIds&&=r.childOperationIds.filter(e=>e!==t)}for(let[n,r]of Object.entries(e.messageOperationMap))r===t&&delete e.messageOperationMap[n]})}),!1,T9(`cleanupCompletedOperations/count=${n.length}`)),E9(`[cleanupCompletedOperations] cleaned up %d operations`,n.length),n.length)};associateMessageWithOperation=(e,t)=>{this.#t(tt(n=>{n.messageOperationMap[e]=t,n.operationsByMessage[e]||(n.operationsByMessage[e]=[]),n.operationsByMessage[e].includes(t)||n.operationsByMessage[e].push(t)}),!1,T9(`associateMessageWithOperation/${e}/${t}`))};markTopicUnread=({agentId:e,groupId:t,topicId:n})=>{n&&this.#e().activeTopicId!==n&&this.#e().updateTopicStatus?.({agentId:e,groupId:t??void 0,status:`unread`,topicId:n})?.then(()=>{$3().refreshAgentList?.()})};markTopicRead=({agentId:e,groupId:t,topicId:n})=>{if(!n)return;let r=ai({agentId:e??this.#e().activeAgentId,groupId:t??this.#e().activeGroupId});this.#e().topicDataMap[r]?.items?.find(e=>e.id===n)?.status===`unread`&&this.#e().updateTopicStatus?.({agentId:e,groupId:t??void 0,status:`active`,topicId:n})?.then(()=>{$3().refreshAgentList?.()})};
6012enqueueMessage=(e,t,n)=>{E9(`[enqueueMessage] contextKey=%s, messageId=%s, mode=%s`,e,t.id,t.interruptMode),this.#t(tt(n=>{let r=n.queuedMessages[e]??[];r.push(t),n.queuedMessages[e]=r}),!1,T9(`enqueueMessage/${e}`)),t.interruptMode===`hard`&&n&&this.#e().operations[n]?.status===`running`&&(E9(`[enqueueMessage] Hard interrupt, cancelling operation %s`,n),this.#e().cancelOperation(n,`hard_interrupt`))};drainQueuedMessages=e=>{let t=this.#e().queuedMessages[e];if(!t||t.length===0)return[];let n=[...t];return this.#t(tt(t=>{t.queuedMessages[e]=[]}),!1,T9(`drainQueuedMessages/${e}`)),E9(`[drainQueuedMessages] contextKey=%s, drained %d`,e,n.length),n};moveQueuedMessages=(e,t)=>{if(e===t)return;let n=this.#e().queuedMessages[e];!n||n.length===0||(this.#t(tt(n=>{let r=n.queuedMessages[e];if(!r||r.length===0)return;let i=n.queuedMessages[t]??[];n.queuedMessages[t]=[...i,...r],n.queuedMessages[e]=[]}),!1,T9(`moveQueuedMessages/${e}/${t}`)),E9(`[moveQueuedMessages] fromContextKey=%s, toContextKey=%s, moved %d`,e,t,n.length))};removeQueuedMessage=(e,t)=>{this.#t(tt(n=>{let r=n.queuedMessages[e];if(!r)return;let i=r.findIndex(e=>e.id===t);i>=0&&r.splice(i,1)}),!1,T9(`removeQueuedMessage/${e}/${t}`))};clearMessageQueue=e=>{this.#t(tt(t=>{delete t.queuedMessages[e]}),!1,T9(`clearMessageQueue/${e}`))}}})),bKe,xKe=e((()=>{iY(),Li(),f7(),d3(),bKe=class{constructor(e,t,n){}internal_transformToolCalls=(e,t)=>{let n=new one,r=l7.getState(),i={},a={},o=hZ.installedPlugins(r);for(let e of o)e.manifest&&(i[e.identifier]=e.manifest,a[e.identifier]=`mcp`);for(let e of tY)e.manifest&&(i[e.identifier]=e.manifest,a[e.identifier]=`builtin`);let s=sX.composioAsLobeTools(r);for(let e of s)e.manifest&&(i[e.identifier]=e.manifest,a[e.identifier]=`composio`);let c=VX.lobehubSkillAsLobeTools(r);for(let e of c)e.manifest&&(i[e.identifier]=e.manifest,a[e.identifier]=`lobehubSkill`);return n.resolve(e,i,t).map(e=>{let t=i[e.identifier],n=new une(t).parse(e.apiName,e.arguments);return{...e,arguments:JSON.stringify(n),source:a[e.identifier]}})}}})),SKe,CKe,wKe=e((()=>{SKe=t(le()),Na(),Te(),ae(),di(),CKe=class{#e;constructor(e,t,n){this.#e=t}optimisticUpdatePluginState=async(e,t,n)=>{let{replaceMessages:r,internal_getConversationContext:i}=this.#e();this.#e().internal_dispatchMessage({id:e,type:`updateMessage`,value:{pluginState:t}},n);let a=i(n),o=await Ma.updateMessagePluginState(e,t,a);o?.success&&o.messages&&r(o.messages,{context:a})};optimisticUpdatePluginArguments=async(e,t,n=!1,r)=>{let{refreshMessages:i}=this.#e(),a=ui.getDisplayMessageById(e)(this.#e());if(!a||!a?.tool_call_id)return;let o=ui.getDisplayMessageById(a?.parentId||``)(this.#e()),s=a?.plugin?.arguments,c=se(s||``),l=n?t:Ce(c||{},t);(0,SKe.default)(c,l)||(this.#e().internal_dispatchMessage({id:e,type:`updateMessagePlugin`,value:{arguments:JSON.stringify(l)}},r),o&&=(this.#e().internal_dispatchMessage({id:o.id,type:`updateMessageTools`,tool_call_id:a?.tool_call_id,value:{arguments:JSON.stringify(l)}},r),ui.getDisplayMessageById(o?.id)(this.#e())),await Promise.all([Ma.updateMessagePluginArguments(e,l),(async()=>{o&&await Ma.updateMessage(o.id,{tools:o?.tools})})()]),await i())};optimisticUpdatePlugin=async(e,t,n)=>{let{replaceMessages:r,internal_getConversationContext:i}=this.#e();this.#e().internal_dispatchMessage({id:e,type:`updateMessagePlugin`,value:t},n);let a=i(n),o=await Ma.updateMessagePlugin(e,t,a);o?.success&&o.messages&&r(o.messages,{context:a})};optimisticAddToolToAssistantMessage=async(e,t,n)=>{let r=ui.getDisplayMessageById(e)(this.#e());if(!r)return;let{internal_dispatchMessage:i,internal_refreshToUpdateMessageTools:a}=this.#e();i({type:`addMessageTool`,value:t,id:r.id},n),await a(e,n)};optimisticRemoveToolFromAssistantMessage=async(e,t,n)=>{let r=ui.getDisplayMessageById(e)(this.#e());if(!r||!t)return;let{internal_dispatchMessage:i,internal_refreshToUpdateMessageTools:a}=this.#e();i({type:`deleteMessageTool`,tool_call_id:t,id:r.id},n),await a(e,n)};optimisticUpdatePluginError=async(e,t,n)=>{let{replaceMessages:r,internal_getConversationContext:i}=this.#e();this.#e().internal_dispatchMessage({id:e,type:`updateMessage`,value:{error:t}},n);let a=i(n),o=await Ma.updateMessage(e,{error:t},a);o?.success&&o.messages&&r(o.messages,{context:a})};internal_refreshToUpdateMessageTools=async(e,t)=>{let n=ci.getDbMessageById(e)(this.#e());if(!n||!n.tools)return;let{replaceMessages:r,internal_getConversationContext:i}=this.#e(),a=i(t),o=await Ma.updateMessage(e,{tools:n.tools},a);o?.success&&o.messages&&r(o.messages,{context:a})};optimisticUpdateToolMessage=async(e,t,n)=>{let{internal_dispatchMessage:r}=this.#e(),{content:i,metadata:a,pluginState:o,pluginError:s}=t;r({id:e,type:`updateMessage`,value:{pluginState:o,content:i,metadata:a}}
6012,n),s!==void 0&&r({id:e,type:`updateMessagePlugin`,value:{error:s}},n),await Ma.batchMutateOrThrow([{id:e,type:`updateToolMessage`,value:{content:i,metadata:a,pluginError:s,pluginState:o}}])}}}));function TKe(e,t){let n=t??25e3;if(!e||e.length<=n)return e;let r=n,i=e.charCodeAt(r-1);return i>=55296&&i<=56319&&--r,e.slice(0,r)+`\n\n[Content truncated: ${(e.length-r).toLocaleString()} characters omitted to prevent context overflow. Original length: ${e.length.toLocaleString()} characters]`}var EKe,DKe=e((()=>{EKe=new Set([`lobe-agent-documents`])})),O9,OKe=e((()=>{pa(),DKe(),O9=async({agentId:e,content:t,identifier:n,limit:r,toolCallId:i,topicId:a})=>{if(n&&EKe.has(n))return t;if(!t||!i||!a)return TKe(t,r);try{return(await q.aiChat.archiveToolResult.mutate({agentId:e,content:t,identifier:n,limit:r,toolCallId:i,topicId:a})).content}catch{return TKe(t,r)}}})),kKe=e((()=>{yKe(),bo(),Ai(),si()})),k9,AKe,jKe,MKe=e((()=>{Ne(),f7(),P8(),ae(),k9=e=>({content:e,error:{message:e},state:{},success:!1}),AKe=async(e,t)=>{let n=e.identifier;if(!(l7.getState().composioServers||[]).find(e=>e.identifier===n))return k9(`Composio server not found: ${n}`);let r=se(e.arguments)||{},i=await l7.getState().callComposioTool({identifier:n,toolArgs:r,toolSlug:e.apiName});if(!i.success)return k9(i.error||`Composio tool execution failed`);let a=i.data;return a?{content:a.content,error:a.state?.isError?a.state:void 0,state:a.state,success:a.success}:k9(`Composio tool returned empty result`)},jKe=async(e,t)=>{let n=e.identifier,r=se(e.arguments)||{},i=await l7.getState().callLobehubSkillTool({args:r,provider:n,toolName:e.apiName,topicId:t?.topicId});if(!i.success)return k9(i.error||`LobeHub Skill tool ${n} ${e.apiName} execution failed`);D(n)&&M8(t?.sourceToolCallId,{args:r,data:i.data,provider:n,toolName:e.apiName,type:`skill`});let a=typeof i.data==`string`?i.data:JSON.stringify(i.data);return{content:a,error:void 0,state:{content:[{text:a,type:`text`}]},success:!0}}})),NKe,A9,PKe,FKe=e((()=>{NKe=t(F()),e7(),Na(),OKe(),kKe(),f7(),d3(),Y5(),ae(),di(),MKe(),Pe(),A9=(0,NKe.default)(`lobe-store:plugin-types`),PKe=class{#e;constructor(e,t,n){this.#e=t}invokeBuiltinTool=async(e,t,n)=>{let r=t.source;if(!r){let e=l7.getState();sX.composioAsLobeTools(e).some(e=>e.identifier===t.identifier)?r=`composio`:VX.lobehubSkillAsLobeTools(e).some(e=>e.identifier===t.identifier)&&(r=`lobehubSkill`)}if(r===`composio`)return await this.#e().invokeComposioTypePlugin(e,{...t,source:r});if(r===`lobehubSkill`)return await this.#e().invokeLobehubSkillTypePlugin(e,{...t,source:r});let i=se(t.arguments);if(!i)return{error:`Invalid arguments`,success:!1};if(K5(t.identifier,t.apiName)){let{optimisticUpdateToolMessage:r,registerAfterCompletionCallback:a}=this.#e(),o=this.#e().messageOperationMap[e],s=o?this.#e().operations[o]:void 0,c=o?{operationId:o}:void 0,l=o?pi.findRootRuntimeOperation(o)(this.#e()):void 0,u=l?.id,d=l?.context??s?.context,f=s?.context?.agentId??d?.agentId,p=s?.context?.groupId??d?.groupId,m=s?.context?.documentId??d?.documentId,h=s?.context?.scope??d?.scope,g=s?.context?.viewedTask??d?.viewedTask,_=g?.type===`detail`?g.taskId:void 0,v=s?.context?.topicId??d?.topicId,y=s?.context?.threadId??d?.threadId,b=ci.getDbMessageById(e)(this.#e())?.parentId??d?.messageId,x=s?.context?.isSubAgent??d?.isSubAgent??!1;if(t.identifier===`lobe-agent-builder`){let e=this.#e().activeAgentId;e&&(f=e)}if(!p&&t.identifier===`lobe-group-agent-builder`){let{getChatGroupStoreState:e}=await Ge(async()=>{let{getChatGroupStoreState:e}=await Promise.resolve().then(()=>(s6(),qPe));return{getChatGroupStoreState:e}},void 0);p=e().activeGroupId}let S=this.#e().getGroupOrchestrationCallbacks?.(),C=u??o,w={run:e=>!f||!v?Promise.resolve({error:`No agent context available for sub-agent execution`,result:`No agent context available for sub-agent execution`,success:!1,threadId:``}):this.#e().runClientSubAgent({...e,agentId:f,parentOperationId:C,topicId:v})},T=u?e=>{a(u,e)}:void 0;A9(`[invokeBuiltinTool] Using Tool Store executor: %s/%s, messageId=%s, agentId=%s, groupId=%s, hasGroupOrchestration=%s, rootRuntimeOp=%s, stepContext=%O`,t.identifier,t.apiName,e,f,p,!!S,u,!!n),A9(`[BuiltinToolCall] invoke:start`,{agentId:f,apiName:t.apiName,documentId:m,identifier:t.identifier,messageId:e,operationId:o,rootRuntimeOperationId:u,isSubAgent:x,scope:h,taskId:_,threadId:y,topicId:v});let E=await l7.getState().invokeBuiltinTool(t.identifier,t.apiName,i,{agentId:f,anchorMessageId:b,documentId:m,groupId:p,groupOrchestration:S,isSubAgent:x,messageId:e,operationId:o,registerAfterCompletion:T,rootOperationId:u??o,scope:h,signal:s?.abortController?.signal,sourceMessageId:s?.context?.sourceMessageId??d?.sourceMessageId??d?.messageId,stepContext:n,subAgent:w,taskId:_,threadId:y,toolCallId:t.id,toolMessageId:e,topicId:v});A9(`[BuiltinToolCall] invoke:end`,{apiName:t.apiName,errorType:E.error?.type,identifier:t.identifier,messageId:e,operationId:o,success:E.success});let D=E.content||E.error?.message||``;return await r(e,{content:await O9({agentId:f,content:D,identifier:t.identifier,toolCallId:t.id,topicId:v}),metadata:E.metadata,pluginError:E.error?{body:E.error.body,message:E.error.message,type:E.error.type}:void 0,pluginState:E.state},c),E.stop&&A9(`[invokeBuiltinTool] Executor returned stop=true, stopping execution`),E}return console.error(`[invokeBuiltinTool] No executor found for: ${t.identifier}/${t.apiName}`),{content:`Tool ${t.identifier}/${t.apiName} is not available`,error:{type:`ToolNotFound`,message:`No executor found`},success:!1}};invokeComposioTypePlugin=async(e,t)=>this.#e().internal_invokeRemoteToolPlugin(e,t,AKe,`invokeComposioTypePlugin`);invokeLobehubSkillTypePlugin=async(e,t)=>this.#e().internal_invokeRemoteToolPlugin(e,t,jKe,`invokeLobehubSkillTypePlugin`);invokeMCPTypePlugin=async(e,t)=>{let n,r=ci.getDbMessageById(e)(this.#e()),i=this.#e().messageOperationMap[e],a=(i?this.#e().operations[i]:void 0)?.abortController;A9(`[invokeMCPTypePlugin] messageId=%s, tool=%s, operationId=%s, aborted=%s`,e,t.apiName,i,a?.signal.aborted);try{let e=await $5.invokeMcpToolCall(t,{signal:a?.signal,topicId:r?.topicId});e&&(n=e)}catch(n){if(console.error(n),n.message.includes(`The user aborted a request.`))A9(`[invokeMCPTypePlugin] Request aborted: messageId=%s, tool=%s`,e,t.apiName);else{let t=await Ma.updateMessageError(e,n,{agentId:r?.agentId,topicId:r?.topicId});t?.success&&t.messages&&this.#e().replaceMessages(t.messages,{context:{agentId:r?.agentId||``,topicId:r?.topicId}})}}if(!n)return;let o=n.content||n.error?.message||``,s=await O9({agentId:r?.agentId,content:o,identifier:t.identifier,toolCallId:t.id,topicId:r?.topicId}),c=i?{operationId:i}:void 0;return await this.#e().optimisticUpdateToolMessage(e,{content:s,pluginError:n.success?void 0:n.error,pluginState:n.success?n.state:void 0},c),s};internal_invokeRemoteToolPlugin=async(e,t,n,r)=>{let i,a=ci.getDbMessageById(e)(this.#e()),o=this.#e().messageOperationMap[e],s=(o?this.#e().operations[o]:void 0)?.abortController;A9(`[%s] messageId=%s, tool=%s, operationId=%s, aborted=%s`,r,e,t.apiName,o,s?.signal.aborted);try{i=await n(t,{sourceToolCallId:t.id,topicId:a?.topicId})}catch(n){if(console.error(`[${r}] Error:`,n),n.message.includes(`aborted`))A9(`[%s] Request aborted: messageId=%s, tool=%s`,r,e,t.apiName);else{let t=await Ma.updateMessageError(e,n,{agentId:a?.agentId,topicId:a?.topicId});t?.success&&t.messages&&this.#e().replaceMessages(t.messages,{context:{agentId:a?.agentId,topicId:a?.topicId}})}}if(!i)return;let c=i.content||i.error?.message||``,l=await O9({agentId:a?.agentId,content:c,identifier:t.identifier,toolCallId:t.id,topicId:a?.topicId}),u=o?{operationId:o}:void 0;return await this.#e().optimisticUpdateToolMessage(e,{content:l,pluginError:i.success?void 0:i.error,pluginState:i.success?i.state:void 0},u),l}}})),IKe,LKe=e((()=>{di(),IKe=class{#e;constructor(e,t,n){this.#e=t}
6012reInvokeToolMessage=async e=>{let t=ui.getDisplayMessageById(e)(this.#e());if(!t||t.role!==`tool`||!t.plugin)return;let n=this.#e().messageOperationMap[e],r=n?{operationId:n}:void 0;t.pluginError&&this.#e().optimisticUpdateMessagePluginError(e,null,r);let i={...t.plugin,id:t.tool_call_id};await this.#e().internal_invokeDifferentTypePlugin(e,i)};internal_invokeDifferentTypePlugin=async(e,t,n)=>{switch(t.type){case`mcp`:return await this.#e().invokeMCPTypePlugin(e,t);default:return await this.#e().invokeBuiltinTool(e,t,n)}}}})),RKe,zKe=e((()=>{Na(),di(),RKe=class{#e;constructor(e,t,n){this.#e=t}createAssistantMessageByPlugin=async(e,t)=>{let n=ci.getDbMessageById(t)(this.#e()),r={content:e,parentId:t,role:`assistant`,agentId:n?.agentId??this.#e().activeAgentId,topicId:n?.topicId===void 0?this.#e().activeTopicId:n.topicId},i=await Ma.createMessage(r);this.#e().replaceMessages(i.messages,{context:{agentId:r.agentId,topicId:r.topicId}})}}})),BKe,VKe=e((()=>{ft(),xKe(),wKe(),FKe(),LKe(),zKe(),BKe=(...e)=>rt([new IKe(...e),new CKe(...e),new PKe(...e),new RKe(...e),new bKe(...e)])})),HKe,UKe,WKe,j9,GKe=e((()=>{pa(),ro(),HKe=(e,t)=>{let n=Uint8Array.from(globalThis.atob(e),e=>e.charCodeAt(0));return new Blob([n],{type:t})},UKe=e=>{switch(e.type){case`image`:return{blob:HKe(e.base64,e.contentType),contentType:e.contentType,type:`image`};case`text`:return e;default:return e}},WKe=class{async getProjectFileIndex({deviceId:e,scope:t}){return e?await q.device.getProjectFileIndex.query({deviceId:e,scope:t})??void 0:no.getProjectFileIndex({scope:t})}async searchProjectFiles({deviceId:e,limit:t,query:n,scope:r}){return e?await q.device.searchProjectFiles.query({deviceId:e,limit:t,query:n,scope:r})??void 0:no.searchProjectFiles({limit:t,query:n,scope:r})}async getLocalFilePreview({deviceId:e,...t}){if(e){let n=await q.device.getLocalFilePreview.query({accept:t.accept,deviceId:e,path:t.path,workingDirectory:t.workingDirectory});if(!n.success||!n.preview)throw Error(n.error||`Missing local file preview`);if(t.accept===`image`&&n.preview.type!==`image`)throw Error(`Unsupported local file preview type`);return UKe(n.preview)}return no.getLocalFilePreview(t)}async moveProjectFiles({deviceId:e,items:t,workingDirectory:n}){return e?q.device.moveProjectFiles.mutate({deviceId:e,items:t,workingDirectory:n}):no.moveLocalFiles({items:t})}async renameProjectFile({deviceId:e,newName:t,path:n,workingDirectory:r}){return e?q.device.renameProjectFile.mutate({deviceId:e,newName:t,path:n,workingDirectory:r}):no.renameLocalFile({newName:t,path:n})}async writeProjectFile({content:e,deviceId:t,path:n,workingDirectory:r}){return t?q.device.writeProjectFile.mutate({content:e,deviceId:t,path:n,workingDirectory:r}):no.writeFile({content:e,path:n})}},j9=new WKe})),M9,N9,P9,F9,KKe,I9,L9,R9,z9,B9,V9,H9,U9,qKe,JKe=e((()=>{GKe(),ji(),Wte(),Ei(),M9=e=>e.at(-1)?.type??null,N9=(e,t)=>{let n=e.findIndex(e=>_i(e)===t);return n>=0?n:e.findIndex(e=>e.filePath===t)},P9=(e,t)=>
6012t?e.find(e=>_i(e)===t)??e.find(e=>e.filePath===t):void 0,F9=e=>Si(e.workingDirectory),KKe=(e,t)=>e.filter(e=>F9(e)===t),I9=e=>{let t=vi.currentTopicWorkingDirectory(e);return t?Si(t):void 0},L9=({openLocalFiles:e,state:t,target:n})=>{let r=I9(t),i=F9(n),a=!!r&&(n.allowExternalFilePreview||i===r);return!r||!a?{files:KKe(e,i),scopeKey:i}:{files:e.filter(e=>e.allowExternalFilePreview||F9(e)===r),scopeKey:r}},R9=(e,t)=>{let n=F9(t),r=I9(e);return t.allowExternalFilePreview&&r?r:n},z9=(e,t,n)=>P9(e,t)??(n?e.find(e=>e.filePath===n):void 0),B9=(e,t,n,r,i)=>P9(e,n?.[t])??z9(e,r,i),V9=(e,t,n)=>{let r={...e};return n?r[t]=_i(n):delete r[t],r},H9=(e,t,n)=>{let r=new Set(t.map(_i)),i=new Set(n.map(_i));return e.filter(e=>{let t=_i(e);return!r.has(t)||i.has(t)})},U9=({activeLocalFileId:e,activeLocalFilePath:t,nextScopeActiveFile:n,nextOpenLocalFiles:r,openLocalFiles:i})=>{let a=z9(i,e,t),o=a&&r.some(e=>_i(e)===_i(a));return!a||o?{activeLocalFileId:e,activeLocalFilePath:t}:{activeLocalFileId:n?_i(n):void 0,activeLocalFilePath:n?.filePath}},qKe=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}clearPortalStack=()=>{this.#t({portalStack:[],showPortal:!1},!1,`clearPortalStack`)};closeArtifact=()=>{let{portalStack:e}=this.#e();M9(e)===bi.Artifact&&this.#e().popPortalView()};closeDocument=()=>{let{portalStack:e}=this.#e();M9(e)===bi.Document&&this.#e().popPortalView()};closeFilePreview=()=>{let{portalStack:e}=this.#e();M9(e)===bi.FilePreview&&this.#e().popPortalView()};closeLocalFile=()=>{let{portalStack:e}=this.#e();M9(e)===bi.LocalFile&&this.#e().popPortalView()};closeLocalFileTab=e=>{let{activeLocalFileId:t,activeLocalFileIdsByScope:n,activeLocalFilePath:r,dirtyLocalFileContents:i,openLocalFiles:a}=this.#e(),o=N9(a,e);if(o===-1)return;let s=a[o],c=_i(s),{files:l,scopeKey:u}=L9({openLocalFiles:a,state:this.#e(),target:s}),d=N9(l,c),f=a.filter((e,t)=>t!==o),p=l.filter((e,t)=>t!==d),m=B9(l,u,n,t,r),h=m&&_i(m)===c?p[d]??p[d-1]:m,g=U9({activeLocalFileId:t,activeLocalFilePath:r,nextOpenLocalFiles:f,nextScopeActiveFile:h,openLocalFiles:a}),_=i;if(c in i){let{[c]:e,...t}=i;_=t}this.#t({activeLocalFileId:g.activeLocalFileId,activeLocalFileIdsByScope:V9(n,u,h),activeLocalFilePath:g.activeLocalFilePath,dirtyLocalFileContents:_,openLocalFiles:f},!1,`closeLocalFileTab`),p.length===0&&this.#e().closeLocalFile()};closeLeftLocalFileTabs=e=>{let{activeLocalFileId:t,activeLocalFileIdsByScope:n,activeLocalFilePath:r,openLocalFiles:i}=this.#e(),a=N9(i,e);if(a<0)return;let o=i[a],{files:s,scopeKey:c}=L9({openLocalFiles:i,state:this.#e(),target:o}),l=N9(s,_i(o));if(l<=0)return;let u=s.slice(l),d=H9(i,s,u),f=B9(s,c,n,t,r),p=f?_i(f):void 0,m=_i(o),h=P9(u,u.some(e=>_i(e)===p)?p:m),g=U9({activeLocalFileId:t,activeLocalFilePath:r,nextOpenLocalFiles:d,nextScopeActiveFile:h,openLocalFiles:i});this.#t({activeLocalFileId:g.activeLocalFileId,activeLocalFileIdsByScope:V9(n,c,h),activeLocalFilePath:g.activeLocalFilePath,openLocalFiles:d},!1,`closeLeftLocalFileTabs`)};closeOtherLocalFileTabs=e=>{let{activeLocalFileIdsByScope:t,openLocalFiles:n}=this.#e(),r=P9(n,e);if(!r)return;let{files:i,scopeKey:a}=L9({openLocalFiles:n,state:this.#e(),target:r}),o=_i(r),s={...r,id:o},c=H9(n,i,[s]);this.#t({activeLocalFileId:o,activeLocalFileIdsByScope:V9(t,a,s),activeLocalFilePath:r.filePath,openLocalFiles:c},!1,`closeOtherLocalFileTabs`)};closeRightLocalFileTabs=e=>{let{activeLocalFileId:t,activeLocalFileIdsByScope:n,activeLocalFilePath:r,openLocalFiles:i}=this.#e(),a=N9(i,e);if(a<0)return;let o=i[a],{files:s,scopeKey:c}=L9({openLocalFiles:i,state:this.#e(),target:o}),l=N9(s,_i(o));if(l<0||l>=s.length-1)return;let u=s.slice(0,l+1),d=H9(i,s,u),f=B9(s,c,n,t,r),p=f?_i(f):void 0,m=_i(o),h=P9(u,u.some(e=>_i(e)===p)?p:m),g=U9({activeLocalFileId:t,activeLocalFilePath:r,nextOpenLocalFiles:d,nextScopeActiveFile:h,openLocalFiles:i});this.#t({activeLocalFileId:g.activeLocalFileId,activeLocalFileIdsByScope:V9(n,c,h),activeLocalFilePath:g.activeLocalFilePath,openLocalFiles:d},!1,`closeRightLocalFileTabs`)};closeMessageDetail=()=>{let{portalStack:e}=this.#e();M9(e)===bi.MessageDetail&&this.#e().popPortalView()};closeNotebook=()=>{let{portalStack:e}=this.#e();M9(e)===bi.Notebook&&this.#e().popPortalView()};closeTaskDetail=()=>{let{portalStack:e}=this.#e();M9(e)===bi.TaskDetail&&this.#e().popPortalView()};closeToolUI=()=>{let{portalStack:e}=this.#e();M9(e)===bi.ToolUI&&this.#e().popPortalView()};goBack=()=>{this.#e().popPortalView()};goHome=()=>{this.#t({portalStack:[{type:bi.Home}],showPortal:!0},!1,`goHome`)};openArtifact=e=>{this.#e().pushPortalView({artifact:e,type:bi.Artifact})};openAgentDetail=e=>{this.#e().pushPortalView({agentId:e,type:bi.AgentDetail})};openDocument=(e,t)=>
6012{this.#e().pushPortalView({agentDocumentId:t,documentId:e,type:bi.Document})};openFilePreview=e=>{this.#e().pushPortalView({file:e,type:bi.FilePreview})};openLocalFile=({allowExternalFilePreview:e,deviceId:t,filePath:n,workingDirectory:r})=>{let{activeLocalFileIdsByScope:i,openLocalFiles:a}=this.#e(),o=xi({deviceId:t,filePath:n,workingDirectory:r}),s=a.some(e=>_i(e)===o),c={...e===void 0?{}:{allowExternalFilePreview:e},...t?{deviceId:t}:{},filePath:n,id:o,workingDirectory:r},l=R9(this.#e(),c),u=s?a.map(e=>_i(e)===o?c:e):[...a,c];this.#t({activeLocalFileId:o,activeLocalFileIdsByScope:V9(i,l,c),activeLocalFilePath:n,openLocalFiles:u},!1,`openLocalFile`),this.#e().pushPortalView({type:bi.LocalFile})};setActiveLocalFile=e=>{let{activeLocalFileIdsByScope:t,openLocalFiles:n}=this.#e(),r=P9(n,e),i=r?R9(this.#e(),r):void 0;this.#t({activeLocalFileId:r?_i(r):e,activeLocalFileIdsByScope:i?V9(t,i,r):t,activeLocalFilePath:r?.filePath??e},!1,`setActiveLocalFile`)};setLocalFileBuffer=(e,t)=>{let{dirtyLocalFileContents:n}=this.#e();if(t===void 0){if(!(e in n))return;let{[e]:t,...r}=n;this.#t({dirtyLocalFileContents:r},!1,`setLocalFileBuffer/clear`);return}n[e]!==t&&this.#t({dirtyLocalFileContents:{...n,[e]:t}},!1,`setLocalFileBuffer`)};saveLocalFile=async({deviceId:e,filePath:t,workingDirectory:n})=>{let{dirtyLocalFileContents:r}=this.#e(),i=r[xi({deviceId:e,filePath:t,workingDirectory:n})];if(i===void 0)return;let a=await j9.writeProjectFile({content:i,deviceId:e,path:t,workingDirectory:n});if(!a.success)throw Error(a.error||`Failed to save file`);return i};openAcceptance=e=>{this.#e().pushPortalView({acceptanceId:e,type:bi.Acceptance})};openMessageDetail=e=>{this.#e().pushPortalView({messageId:e,type:bi.MessageDetail})};openNotebook=()=>{this.#e().pushPortalView({type:bi.Notebook})};openTaskDetail=e=>{this.#e().pushPortalView({taskId:e,type:bi.TaskDetail})};openToolUI=(e,t,n)=>{this.#e().pushPortalView({identifier:t,messageId:e,params:n,type:bi.ToolUI})};openVerifyResult=(e,t)=>{this.#e().pushPortalView({checkItemId:t,operationId:e,type:bi.VerifyResult})};openVerifyReport=e=>{this.#e().pushPortalView({runId:e,type:bi.VerifyReport})};popPortalView=()=>{let{portalStack:e}=this.#e();e.length<=1?this.#t({portalStack:[],showPortal:!1},!1,`popPortalView/close`):this.#t({portalStack:e.slice(0,-1)},!1,`popPortalView`)};pushPortalView=e=>{let{portalStack:t}=this.#e();t.at(-1)?.type===e.type?this.#t({portalStack:[...t.slice(0,-1),e],showPortal:!0},!1,`pushPortalView/replace`):this.#t({portalStack:[...t,e],showPortal:!0},!1,`pushPortalView`)};replacePortalView=e=>{let{portalStack:t}=this.#e();t.length===0?this.#t({portalStack:[e],showPortal:!0},!1,`replacePortalView/push`):this.#t({portalStack:[...t.slice(0,-1),e],showPortal:!0},!1,`replacePortalView`)};toggleNotebook=e=>{let{portalStack:t}=this.#e(),n=M9(t)===bi.Notebook;e??!n?this.#e().openNotebook():this.#e().closeNotebook()}}}));async function W9(e,t){let n=await ga(e,t);return`data`in n?n.data:n}var YKe,G9,XKe=e((()=>{Et(),ha(),YKe=class{getThreads=e=>W9(`/app/front-hub/threads?topicId=${encodeURIComponent(e)}`);createThreadWithMessage=async({message:e,...t})=>({messageId:``,threadId:await this.createThread(t)});createThread=async e=>(await W9(`/app/front-hub/threads`,{method:`POST`,body:JSON.stringify(e)})).id;updateThread=async(e,t)=>W9(`/app/front-hub/threads/${e}`,{method:`PATCH`,body:JSON.stringify({value:t})});removeThread=async e=>W9(`/app/front-hub/threads/${e}`,{method:`DELETE`});toDbSessionId=e=>e===`inbox`?null:e},G9=new YKe})),ZKe,QKe=e((()=>{it(),ZKe=(e=[],t)=>{switch(t.type){case`updateThread`:return tt(e,e=>{let{value:n,id:r}=t,i=e.findIndex(e=>e.id===r);i!==-1&&(e[i]={...e[i],...n,updatedAt:new Date})});case`deleteThread`:return tt(e,e=>{let n=e.findIndex(e=>e.id===t.id);n!==-1&&e.splice(n,1)});default:return e}}})),K9,q9,$Ke,eqe=e((()=>{Wt(),Mi(),K9=t(le()),Qi(),oa(),x7(),XKe(),Oi(),wi(),Er(),Ta(),Te(),Dr(),Ei(),QKe(),Vte(),q9=kr(`thd`),$Ke=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}updateThreadInputMessage=e=>{(0,K9.default)(e,this.#e().threadInputMessage)||this.#t({threadInputMessage:e},!1,q9(`updateThreadInputMessage`,e))};openThreadCreator=e=>{let{activeAgentId:t,activeGroupId:n,activeTopicId:r,newThreadMode:i,replaceMessages:a}=this.#e(),o=li({agentId:t,groupId:n,topicId:r}),s=jte((this.#e().messagesMap[o]||[]).filter(e=>!e.threadId),e,i);s.length>0&&a(s,{action:`initThreadMessages`,context:{agentId:t,isNew:!0,scope:`thread`,topicId:r}}),this.#t({threadStartMessageId:e,portalThreadId:void 0,startToForkThread:!0},!1,`openThreadCreator`),this.#e().pushPortalView({type:bi.Thread,startMessageId:e})};openThreadInPortal=(e,t)=>{this.#t({portalThreadId:e,threadStartMessageId:t,startToForkThread:!1},!1,`openThreadInPortal`),this.#e().pushPortalView({type:bi.Thread,threadId:e,startMessageId:t??void 0})};syncThreadInPortal=(e,t)=>{this.#t({portalThreadId:e,startToForkThread:!1,threadStartMessageId:t},!1,`syncThreadInPortal`)};closeThreadPortal=()=>{this.#t({threadStartMessageId:void 0,portalThreadId:void 0,startToForkThread:void 0},!1,`closeThreadPortal`),this.#e().clearPortalStack()};createThread=async({message:e,sourceMessageId:t,topicId:n,type:r})=>{this.#t({isCreatingThread:!0},!1,q9(`creatingThread/start`));let i=await G9.createThreadWithMessage({topicId:n,sourceMessageId:t,type:r,message:e});return this.#t({isCreatingThread:!1},!1,q9(`creatingThread/end`)),i};useFetchThreads=(e,t)=>Xi(e&&t?la.list(t):null,async([,e])=>G9.getThreads(e),{onSuccess:e=>{let n={...this.#e().threadMaps,[t]:e};this.#e().threadsInit&&(0,K9.default)(n,this.#e().threadMaps)||this.#t({threadMaps:n,threadsInit:!0},!1,q9(`useFetchThreads(success)`,{topicId:t}))}});refreshThreads=async()=>{let e=this.#e().activeTopicId;if(e)return Zi(la.list(e))};removeThread=async e=>{await G9.removeThread(e),await this.#e().refreshThreads(),this.#e().activeThreadI
6012d===e&&this.#t({activeThreadId:void 0})};switchThread=async e=>{this.#t({activeThreadId:e},!1,q9(`toggleTopic`))};updateThreadTitle=async(e,t)=>{await this.#e().internal_updateThread(e,{title:t})};summaryThreadTitle=async(e,t)=>{let{internal_updateThreadTitleInSummary:n,internal_updateThreadLoading:r}=this.#e(),i=Ci.currentPortalThread(this.#e());if(!i)return;n(e,`...`);let a=``,o=wa.thread(Or.getState());await b7.fetchPresetTaskResult({onError:()=>{n(e,i.title)},onFinish:async t=>{await this.#e().internal_updateThread(e,{title:t})},onLoadingChange:t=>{r(e,t)},onMessageHandle:t=>{switch(t.type){case`text`:a+=t.text}n(e,a)},params:Ce(o,Yte(t,Ca.currentResponseLanguage(Or.getState())))})};internal_updateThreadTitleInSummary=(e,t)=>{this.#e().internal_dispatchThread({type:`updateThread`,id:e,value:{title:t}},`updateThreadTitleInSummary`)};internal_updateThreadLoading=(e,t)=>{this.#t(n=>t?{threadLoadingIds:[...n.threadLoadingIds,e]}:{threadLoadingIds:n.threadLoadingIds.filter(t=>t!==e)},!1,q9(`updateThreadLoading`))};internal_updateThread=async(e,t)=>{this.#e().internal_dispatchThread({type:`updateThread`,id:e,value:t}),this.#e().internal_updateThreadLoading(e,!0),await G9.updateThread(e,t),await this.#e().refreshThreads(),this.#e().internal_updateThreadLoading(e,!1)};internal_dispatchThread=(e,t)=>{let n=ZKe(Ci.currentTopicThreads(this.#e()),e),r={...this.#e().threadMaps,[this.#e().activeTopicId]:n};(0,K9.default)(r,this.#e().threadMaps)||this.#t({threadMaps:r},!1,t??q9(`dispatchThread/${e.type}`))}}})),tqe,J9,nqe=e((()=>{tqe=t(le()),it(),J9=(e=[],t)=>{switch(t.type){case`addTopic`:return tt(e,e=>(e.unshift({...t.value,createdAt:Date.now(),favorite:!1,id:t.value.id??Date.now().toString(),sessionId:t.value.sessionId||void 0,sortUpdatedAt:Date.now(),updatedAt:Date.now()}),e.sort((e,t)=>Number(t.favorite)-Number(e.favorite))));case`updateTopic`:return tt(e,e=>{let{value:n,id:r}=t,i=e.findIndex(e=>e.id===r);if(i!==-1){let t=e[i],r={...t,...n};(0,tqe.default)(nt(t),r)||(e[i]={...r,updatedAt:new Date})}});case`replaceTopicId`:return tt(e,e=>{let{value:n,id:r,nextId:i}=t,a=e.findIndex(e=>e.id===r),o=e.findIndex(e=>e.id===i);if(a===-1)return;let s=e[a],c=o===-1?void 0:e[o];e[a]={...s,...c,...n,id:i,sortUpdatedAt:Date.now(),updatedAt:Date.now()},o!==-1&&o!==a&&e.splice(o,1)});case`deleteTopic`:return tt(e,e=>{let n=e.findIndex(e=>e.id===t.id);n!==-1&&e.splice(n,1)});default:return e}}})),Y9,X9,rqe,iqe,aqe,oqe=e((()=>{Mi(),Ne(),Y9=t(le()),f(),s(),Qr(),$t(),Qi(),oa(),x7(),ka(),Na(),Fa(),X3(),Ti(),Ns(),Xa(),e6(),Er(),Ta(),Te(),Dr(),di(),nqe(),ji(),X9=kr(`t`),rqe=7200*1e3,iqe=500,aqe=class{#e;#t;#n=0;#r=!1;constructor(e,t,n){this.#t=e,this.#e=t}#i=(e,t)=>{let n=ks(t??vi.getTopicById(e)(this.#e())?.metadata);if(!n)return;let{activeAgentId:r}=this.#e();if(!r)return;let i=Os(r);if(Ds(i))return{branch:n.branch,deviceId:i.deviceId,path:n.path,pullRequestNumber:n.pullRequestNumber,topicId:e}};closeAllTopicsDrawer=()=>{this.#t({allTopicsDrawerOpen:!1},!1,X9(`closeAllTopicsDrawer`))};openAllTopicsDrawer=()=>{this.#t({allTopicsDrawerOpen:!0},!1,X9(`openAllTopicsDrawer`))};openNewTopicOrSaveTopic=async()=>{let{switchTopic:e,saveToTopic:t,refreshMessages:n,activeTopicId:r}=this.#e();if(r)e(null);else{if(vi.isNewTopicSendInFlight(this.#e()))return;await t(),n()}};createTopic=async e=>{let{activeAgentId:t,internal_createTopic:n}=this.#e(),r=ui.activeDisplayMessages(this.#e());this.#t({creatingTopic:!0},!1,X9(`creatingTopic/start`));let i=await n({title:o(`defaultTitle`,{ns:`topic`}),messages:r.map(e=>e.id),sessionId:e||t});return this.#t({creatingTopic:!1},!1,X9(`creatingTopic/end`)),i};saveToTopic=async e=>{let t=ui.activeDisplayMessages(this.#e());if(t.length===0)return;let{activeAgentId:n,summaryTopicTitle:r,internal_createTopic:i}=this.#e(),a=await i({title:o(`defaultTitle`,{ns:`topic`}),messages:t.map(e=>e.id),sessionId:e||n});return this.#e().internal_updateTopicLoading(a,!0),r(a,t).catch(e=>{console.error(`[saveToTopic] Failed to summarize topic title:`,e)}).finally(()=>{this.#e().internal_updateTopicLoading(a,!1)}),a};duplicateTopic=async e=>{let{refreshTopic:t,switchTopic:n}=this.#e(),r=vi.getTopicById(e)(this.#e());if(!r)return;
6012let i=o(`duplicateTitle`,{ns:`chat`,title:r?.title});zr.loading({content:o(`duplicateLoading`,{ns:`topic`}),key:`duplicateTopic`,duration:0});let a=await Pa.cloneTopic(e,i);await t(),zr.destroy(`duplicateTopic`),zr.success(o(`duplicateSuccess`,{ns:`topic`})),await n(a)};importTopic=async e=>{let{activeAgentId:t,activeGroupId:n,refreshTopic:r,switchTopic:i}=this.#e();if(t){zr.loading({content:o(`importLoading`,{ns:`topic`}),duration:0,key:`importTopic`});try{let a=await Pa.importTopic({agentId:t,data:e,groupId:n});return await r(),zr.destroy(`importTopic`),zr.success(o(`importSuccess`,{count:a.messageCount,ns:`topic`})),await i(a.topicId),a.topicId}catch(e){zr.destroy(`importTopic`),zr.error(o(`importError`,{ns:`topic`})),console.error(`[importTopic] Failed:`,e);return}}};summaryTopicTitle=async(e,t)=>{let{internal_updateTopicTitleInSummary:n,internal_updateTopicLoading:r}=this.#e(),i=vi.getTopicById(e)(this.#e());if(!i)return;let a=!i.title||i.title===`...`;a&&n(e,`...`);let o=``,s=wa.topic(Or.getState());await b7.fetchPresetTaskResult({onError:()=>{a&&n(e,i.title)},onFinish:async t=>{await this.#e().internal_updateTopic(e,{title:t})},onLoadingChange:t=>{r(e,t)},onMessageHandle:t=>{switch(t.type){case`text`:o+=t.text}a&&n(e,o)},params:Ce(s,Yte(t,Ca.currentResponseLanguage(Or.getState()))),trace:this.#e().getCurrentTracePayload({traceName:Se.SummaryTopicTitle,topicId:e})})};markTopicCompleted=async e=>{await this.#e().internal_updateTopic(e,{completedAt:new Date,status:`completed`})};unmarkTopicCompleted=async e=>{await this.#e().internal_updateTopic(e,{completedAt:null,status:`active`})};favoriteTopic=async(e,t)=>{let{activeAgentId:n}=this.#e();await this.#e().internal_updateTopic(e,{favorite:t}),n&&await Zi(lre.topicsWithJobInfo(n),n=>{if(!Array.isArray(n))return n;let r=!1,i=n.map(n=>{let i=!1,a=Array.isArray(n.topics)?n.topics.map(n=>n.id!==e||n.favorite===t?n:(i=!0,r=!0,{...n,favorite:t})):[];return i?{...n,topics:a}:n});return r?i:n},{revalidate:!1})};updateTopicMetadata=async(e,t)=>{let n=vi.getTopicById(e)(this.#e());if(!n)return;let r={...n.metadata,...t};this.#e().internal_dispatchTopic({type:`updateTopic`,id:e,value:{metadata:r}}),this.#e().internal_updateTopicLoading(e,!0),await Pa.updateTopicMetadata(e,t),await this.#e().refreshTopic(),this.#e().internal_updateTopicLoading(e,!1)};updateTopicTitle=async(e,t)=>{await this.#e().internal_updateTopic(e,{title:t})};#a=new Map;#o=(e,t)=>{let n=e;if(this.#a.size>0&&(n=n.map(e=>{let t=this.#a.get(e.id);return t?t.expiresAt<=Date.now()||e.status===t.status?(this.#a.delete(e.id),e):{...e,status:t.status}:e})),t&&t.length>0){let e=t.filter(e=>e.id.startsWith(`tmp_topic_`));if(e.length>0){let t=new Set(n.map(e=>e.id)),r=e.filter(e=>!t.has(e.id));r.length>0&&(n=[...r,...n])}}return n};updateTopicStatus=async e=>{let{topicId:t,status:n,agentId:r,groupId:i,scope:a}=e,o=this.#e(),s=ai({agentId:a?r:r??o.activeAgentId,groupId:a?i:i??o.activeGroupId,scope:a});if(o.topicDataMap[s]?.items?.find(e=>e.id===t)?.status===n)return;let c=n===`completed`?{completedAt:new Date,status:n}:{status:n};this.#a.set(t,{expiresAt:Date.now()+15e3,status:n}),o.internal_dispatchTopic({type:`updateTopic`,id:t,value:c,agentId:r,groupId:i,scope:a}),await Pa.updateTopic(t,c).catch(e=>{console.error(`[updateTopicStatus] persist failed:`,e),this.#a.delete(t)})};#s=e=>{let t=typeof e.updatedAt==`number`?e.updatedAt:new Date(e.updatedAt).getTime();return Number.isFinite(t)?t:void 0};#c=e=>Object.values(this.#e().operations).some(t=>t.status!==`running`||t.metadata.isAborting||t.abortController.signal.aborted?!1:t.context.topicId===e);#l=e=>{let t=e.groupId??void 0;return t?{groupId:t,scope:`group`}:{agentId:e.agentId??void 0}};#u=async(e,t)=>{if(!e.metadata?.runningOperation)return;let n=ai(t),r=this.#e().topicDataMap[n]?.items.find(t=>t.id===e.id)?.metadata??e.metadata;await Pa.updateTopicMetadata(e.id,{runningOperation:null}),this.#e().internal_dispatchTopic({...t,id:e.id,type:`updateTopic`,value:{metadata:{...r,runningOperation:null}}})};cleanupStaleRunningTopics=async()=>{if(this.#r)return 0;this.#r=!0;try{let e=await Pa.queryTopics({pageSize:iqe,statuses:[`running`]}
6012),t=Date.now(),n=e.filter(e=>{let n=this.#s(e);return!n||t-n<=rqe?!1:!this.#c(e.id)}),r=(await Promise.all(n.map(async e=>{try{let t=this.#l(e);return await this.#u(e,t),await this.updateTopicStatus({...t,status:`active`,topicId:e.id}),!0}catch(e){return console.error(`[cleanupStaleRunningTopics] retire stale topic failed:`,e),!1}}))).filter(Boolean).length;return r>0&&$3().refreshAgentList?.(),r}catch(e){return console.error(`[cleanupStaleRunningTopics] failed:`,e),0}finally{this.#r=!1}};useFetchTopicLinkedPullRequest=(e,t)=>{let n=e?this.#i(e,t):void 0;return $i(n?ia.gitLinkedPR(n.deviceId??`local`,n.path,n.branch,n.pullRequestNumber):null,n?()=>Oa.getLinkedPullRequest({branch:n.branch,deviceId:n.deviceId,path:n.path,pullRequestNumber:n.pullRequestNumber}):null,{dedupingInterval:60*1e3,focusThrottleInterval:60*1e3,onData:e=>{n&&this.#e().internal_updateTopicLinkedPullRequest(n,e).catch(e=>{console.error(`[useFetchTopicLinkedPullRequest] sync failed:`,e)})},revalidateOnFocus:!0,shouldRetryOnError:!1})};autoRenameTopicTitle=async e=>{let{activeAgentId:t,summaryTopicTitle:n,internal_updateTopicLoading:r}=this.#e();r(e,!0),await n(e,await Ma.getMessages({agentId:t,topicId:e})),r(e,!1)};useFetchTopics=(e,{agentId:t,excludeStatuses:n,excludeTriggers:r,groupId:i,pageSize:a,isInbox:o,sortBy:s,withDetails:c}={})=>{let l=a||20,u=r&&r.length>0?r:void 0,d=n&&n.length>0?n:void 0,f=ai({agentId:t,groupId:i}),p=!!(i||t);return $i(e&&p?sa.list(f,{isInbox:o,pageSize:l,...u?{excludeTriggers:u}:{},...d?{excludeStatuses:d}:{},...s?{sortBy:s}:{},...c?{withDetails:!0}:{}}):null,async()=>{if(!t&&!i)return{items:[],total:0};let e=this.#e().topicDataMap[f],n=e?.pageSize,r=(e?.items?.length||0)>0&&typeof n==`number`&&l>n;r&&this.#e().internal_updateTopicData(f,{isExpandingPageSize:!0});let a=await Pa.getTopics({agentId:t,current:0,excludeStatuses:d,excludeTriggers:u,groupId:i,isInbox:o,pageSize:l,sortBy:s,withDetails:c});return r&&this.#e().internal_updateTopicData(f,{isExpandingPageSize:!1}),a},{onData:e=>{if(!p)return;let{total:t}=e,n=this.#e().topicDataMap[f],r=this.#o(e.items,n?.items),i=!!n&&n.currentPage>0&&n.pageSize===l&&!!n.isInbox==!!o&&(0,Y9.default)(n.excludeStatuses,d)&&(0,Y9.default)(n.excludeTriggers,u),a=i?(()=>{let e=Math.min(n.items.length,t),i=new Set(r.map(e=>e.id));return[...r,...n.items.filter(e=>!i.has(e.id))].slice(0,e)})():r,s=t>a.length;n&&(0,Y9.default)(a,n.items)&&n.total===t&&(0,Y9.default)(n.excludeStatuses,d)&&(0,Y9.default)(n.excludeTriggers,u)||this.#t({topicDataMap:{...this.#e().topicDataMap,[f]:{currentPage:i?n.currentPage:0,excludeStatuses:d,excludeTriggers:u,hasMore:s,isInbox:!!o,isExpandingPageSize:!1,isLoadingMore:!1,loadMoreError:void 0,items:a,pageSize:l,total:t,withDetails:c}}},!1,X9(`useFetchTopics(onData)`,{containerKey:f}))}})};useFetchAgentTopicsView=(e,{agentId:t,pageSize:n,withDetails:r}={})=>{let i=n||30,a=ai({agentId:t}),o=!!t;return $i(e&&o?sa.agentView(a,{pageSize:i,...r?{withDetails:!0}:{}}):null,async()=>t?Pa.getTopics({agentId:t,current:0,pageSize:i,withDetails:r}):{items:[],total:0},{onData:e=>{if(!o)return;let{total:t}=e,n=this.#e().agentTopicsViewMap[a],s=this.#o(e.items,n?.items),c=!!n&&n.currentPage>0&&n.pageSize===i,l=c?(()=>{let e=Math.min(n.items.length,t),r=new Set(s.map(e=>e.id));return[...s,...n.items.filter(e=>!r.has(e.id))].slice(0,e)})():s,u=t>l.length;n&&(0,Y9.default)(l,n.items)&&n.total===t||this.#t({agentTopicsViewMap:{...this.#e().agentTopicsViewMap,[a]:{currentPage:c?n.currentPage:0,hasMore:u,isExpandingPageSize:!1,isLoadingMore:!1,loadMoreError:void 0,items:l,pageSize:i,total:t,withDetails:r}}},!1,X9(`useFetchAgentTopicsView(onData)`,{containerKey:a}))}})};loadMoreAgentTopicsView=async()=>{let{activeAgentId:e,agentTopicsViewMap:t}=this.#e();if(!e)return;let n=ai({agentId:e}),r=t[n];if(!r||r.isLoadingMore)return;let i=(r.currentPage||0)+1,a=r.pageSize,o=r.withDetails;this.#t({agentTopicsViewMap:{...t,[n]:{...r,isLoadingMore:!0,loadMoreError:void 0}}},!1,X9(`loadMoreAgentTopicsView(start)`));try{let t=await Pa.getTopics({agentId:e,current:i,pageSize:a,withDetails:o}),s=[...r.items,...t.items],c=t.total>s.length;this.#t({agentTopicsViewMap:{...this.#e().agentTopicsViewMap,[n]:{...r,currentPage:i,hasMore:c,isLoadingMore:!1,loadMoreError:void 0,items:s,total:t.total}}},!1,X9(`loadMoreAgentTopicsView(success)`))}catch(e){this.#t({agentTopicsViewMap:{...this.#e().agentTopicsViewMap,[n]:{...this.#e().agentTopicsViewMap[n],isLoadingMore:!1,loadMoreError:e}}},!1,X9(`loadMoreAgentTopicsView(error)`))}};refreshAgentTopicsView=async()=>{let{activeAgentId:e}=this.#e();if(!e)return;let t=ai({agentId:e});await Zi(e=>Array.isArray(e)&&e[0]===sa.agentView.root&&e[1]===t)};loadMoreTopics=async()=>{let{activeAgentId:e,activeGroupId:t,topicDataMap:n}=this.#e(),r=ai({agentId:e,groupId:t}),i=n[r];if(!e&&!t||i?.isLoadingMore)return;let a=(i?.currentPage||0)+1;this.#t({topicDataMap:{...n,[r]:{...i,isLoadingMore:!0,loadMoreError:void 0}}},!1,X9(`loadMoreTopics(start)`));
6012try{let n=Ja.getState().status.topicPageSize||20,o=i?.excludeTriggers,s=i?.excludeStatuses,c=i?.withDetails,l=await Pa.getTopics({agentId:e,current:a,excludeStatuses:s,excludeTriggers:o,groupId:t,pageSize:n,withDetails:c}),u=[...i?.items||[],...l.items],d=l.total>u.length;this.#t({topicDataMap:{...this.#e().topicDataMap,[r]:{currentPage:a,excludeStatuses:s,excludeTriggers:o,hasMore:d,isInbox:i?.isInbox,isLoadingMore:!1,loadMoreError:void 0,items:u,pageSize:n,total:l.total,withDetails:c}}},!1,X9(`loadMoreTopics(success)`))}catch(e){this.#t({topicDataMap:{...this.#e().topicDataMap,[r]:{...this.#e().topicDataMap[r],isLoadingMore:!1,loadMoreError:e}}},!1,X9(`loadMoreTopics(error)`))}};useSearchTopics=(e,{agentId:t,groupId:n}={})=>m(e?sa.search(e,t,n):null,([,e,t,n])=>Pa.searchTopics(e,t,n),{onSuccess:t=>{this.#t({searchTopics:this.#o(t),isSearchingTopic:!1},!1,X9(`useSearchTopics(success)`,{keywords:e}))}});switchTopic=async(e,t)=>{let n=t??{},r=++this.#n,{activeAgentId:i,activeGroupId:a}=this.#e(),o=!e||n.clearNewKey;if(o&&this.#e().clearPortalStack(),o&&i){let e=n.scope??(a?`group`:`main`);this.#e().replaceMessages([],{context:{agentId:i,groupId:a,scope:e,topicId:null},action:X9(`clearNewKeyData`)})}this.#t({activeTopicId:e||null,activeThreadId:void 0},!1,X9(`toggleTopic`)),i&&this.#e().markTopicRead({agentId:i,topicId:e??null}),!n.skipRefreshMessage&&(await Promise.resolve(),r===this.#n&&await this.#e().revalidateMessages())};removeSessionTopics=async(e=`own`)=>{let{switchTopic:t,activeAgentId:n,refreshTopic:r}=this.#e();n&&(await Pa.removeTopicsByAgentId(n,e),await r(),Y3(e=>e.agentId===n),t(null))};removeGroupTopics=async(e,t=`own`)=>{let{switchTopic:n,refreshTopic:r}=this.#e();await Pa.removeTopicsByGroupId(e,t),await r(),Y3(t=>t.groupId===e),n(null)};removeAllTopics=async()=>{let{refreshTopic:e}=this.#e();await Pa.removeAllTopic(),await e(),Y3(()=>!0)};removeTopic=async(e,t)=>{let{activeAgentId:n,activeGroupId:r,activeTopicId:i,switchTopic:a,refreshTopic:o}=this.#e();!n&&!r||(await Pa.removeTopic(e,t),this.#e().internal_dispatchTopic({type:`deleteTopic`,id:e},`removeTopic`),await o(),Y3(t=>t.topicId===e),i===e&&a(null))};removeUnstarredTopic=async e=>{let{refreshTopic:t,switchTopic:n}=this.#e(),r=vi.currentUnFavTopics(this.#e()),i=ba.userId(Or.getState()),a=r.filter(t=>!e?.onlyOwn||!!i&&t.userId===i).map(e=>e.id);await Pa.batchRemoveTopics(a),await t();let o=new Set(a);Y3(e=>!!e.topicId&&o.has(e.topicId)),n(null)};batchMoveTopicsToAgent=async(e,t)=>{if(e.length===0)return;let{activeTopicId:n,switchTopic:r,refreshTopic:i}=this.#e();await Pa.batchMoveTopics(e,t),e.forEach(e=>this.#e().internal_dispatchTopic({type:`deleteTopic`,id:e},`batchMoveTopicsToAgent`)),await i();let a=new Set(e);Y3(e=>!!e.topicId&&a.has(e.topicId)),n&&e.includes(n)&&r(null)};internal_updateTopicTitleInSummary=(e,t)=>{this.#e().internal_dispatchTopic({type:`updateTopic`,id:e,value:{title:t}},`updateTopicTitleInSummary`)};refreshTopic=async()=>{let{activeAgentId:e,activeGroupId:t}=this.#e(),n=ai({agentId:e,groupId:t}),r=e?ai({agentId:e}):null;await Zi(e=>Array.isArray(e)&&(e[0]===sa.list.root&&typeof e[1]==`string`&&e[1]===n||e[0]===sa.agentView.root&&r!==null&&e[1]===r))};internal_updateTopicLoading=(e,t)=>
6012{this.#t(n=>{let r=n.topicLoadingIdCounts[e]??+!!n.topicLoadingIds.includes(e),i={...n.topicLoadingIdCounts};return t?(i[e]=r+1,{topicLoadingIdCounts:i,topicLoadingIds:n.topicLoadingIds.includes(e)?n.topicLoadingIds:[...n.topicLoadingIds,e]}):r>1?(i[e]=r-1,{topicLoadingIdCounts:i,topicLoadingIds:n.topicLoadingIds}):(delete i[e],{topicLoadingIdCounts:i,topicLoadingIds:n.topicLoadingIds.filter(t=>t!==e)})},!1,X9(`updateTopicLoading`))};internal_replaceTopicId=e=>{let{agentId:t,groupId:n,nextId:r,previousId:i,value:a}=e;this.#e().internal_dispatchTopic({agentId:t,groupId:n,id:i,nextId:r,type:`replaceTopicId`,value:a},X9(`replaceTopicId`)),this.#t(e=>{let t=e.topicLoadingIdCounts[i]??0,n=e.topicLoadingIdCounts[r]??0,a={...e.topicLoadingIdCounts};delete a[i],(t>0||n>0)&&(a[r]=t+n);let o=Array.from(new Set(e.topicLoadingIds.map(e=>e===i?r:e)));return{activeTopicId:e.activeTopicId===i?r:e.activeTopicId,topicLoadingIdCounts:a,topicLoadingIds:o}},!1,X9(`replaceTopicId/loading`))};internal_updateTopic=async(e,t)=>{this.#e().internal_dispatchTopic({type:`updateTopic`,id:e,value:t}),this.#e().internal_updateTopicLoading(e,!0);try{await Pa.updateTopic(e,t),await this.#e().refreshTopic()}finally{this.#e().internal_updateTopicLoading(e,!1)}};internal_updateTopicLinkedPullRequest=async(e,t)=>{if(!As(t))return;let n=vi.getTopicById(e.topicId)(this.#e());if(!n)return;let r=ks(n.metadata);if(!r||r.branch!==e.branch||r.path!==e.path||r.pullRequestNumber!==e.pullRequestNumber)return;let i=js(t);if(!i||r.pullRequestNumber!==void 0&&i.pullRequest?.number!==r.pullRequestNumber)return;let a=Ms({branch:r.branch,currentConfig:r.currentConfig,github:i,path:r.path,upstream:t?.upstream});if(!(0,Y9.default)(r.currentConfig,a)){this.#e().internal_dispatchTopic({id:e.topicId,type:`updateTopic`,value:{metadata:{...n.metadata,workingDirectoryConfig:a}}},X9(`refreshTopicLinkedPullRequest`));try{await Pa.updateTopicMetadata(e.topicId,{workingDirectoryConfig:a}),await this.#e().refreshTopic()}catch(e){throw await this.#e().refreshTopic(),e}}};internal_createTopic=async e=>{let t=Date.now().toString();this.#e().internal_dispatchTopic({type:`addTopic`,value:{...e,id:t}},`internal_createTopic`),this.#e().internal_updateTopicLoading(t,!0);let n=await Pa.createTopic(e);return this.#e().internal_updateTopicLoading(t,!1),this.#e().internal_updateTopicLoading(n,!0),await this.#e().refreshTopic(),this.#e().internal_updateTopicLoading(n,!1),n};internal_dispatchTopic=(e,t)=>{let{activeAgentId:n,activeGroupId:r}=this.#e(),i=ai({agentId:e.scope?e.agentId:e.agentId??n,groupId:e.scope?e.groupId:e.groupId??r,scope:e.scope}),a=this.#e().topicDataMap[i],o=J9(a?.items,e),s=this.#e().agentTopicsViewMap,c=s[i],l=c?J9(c.items,e):void 0,u=c?!(0,Y9.default)(l,c.items):!1,d=!(0,Y9.default)(o,a?.items);if(!d&&!u)return;let f=a?.total??a?.items?.length??0,p=e.type===`addTopic`?f+1:e.type===`deleteTopic`?Math.max(o.length,f-1):f,m={};if(d&&(m.topicDataMap={...this.#e().topicDataMap,[i]:{...a,currentPage:a?.currentPage??0,hasMore:p>o.length,isInbox:a?.isInbox,items:o,total:p}}),u&&c&&l){let t=c.total??c.items?.length??0,n=e.type===`addTopic`?t+1:e.type===`deleteTopic`?Math.max(l.length,t-1):t;m.agentTopicsViewMap={...s,[i]:{...c,hasMore:n>l.length,items:l,total:n}}}this.#t(m,!1,t??X9(`dispatchTopic/${e.type}`))};internal_updateTopics=(e,t)=>{let{total:n,pageSize:r,currentPage:i=0,append:a=!1,groupId:o}=t,s=ai({agentId:e,groupId:o}),c=this.#e().topicDataMap[s],l=this.#o(t.items,a?void 0:c?.items),u=a?[...c?.items||[],...l]:l;this.#t({topicDataMap:{...this.#e().topicDataMap,[s]:{currentPage:i,excludeStatuses:c?.excludeStatuses,excludeTriggers:c?.excludeTriggers,hasMore:n>u.length,isInbox:c?.isInbox,isExpandingPageSize:!1,isLoadingMore:!1,items:u,pageSize:r,total:n}}},!1,X9(`internal_updateTopics`,{key:s,append:a}))};internal_updateTopicData=(e,t)=>{let n=this.#e().topicDataMap[e];n&&this.#t({topicDataMap:{...this.#e().topicDataMap,[e]:{...n,...t}}},!1,X9(`internal_updateTopicData`,{key:e,data:t}))}}})),sqe,cqe=e((()=>{Mi(),Ne(),R(),_re(),x7(),Na(),Oi(),Er(),Ta(),sqe=class{#e;constructor(e,t,n){this.#e=t}clearTranslate=async e=>{await this.#e().updateMessageTranslate(e,!1)};getCurrentTracePayload=e=>({sessionId:this.#e().activeAgentId,topicId:this.#e().activeTopicId,...e});translateMessage=async(e,t)=>{let{updateMessageTranslate:n,internal_dispatchMessage:r}=this.#e(),i=ci.getDbMessageById(e)(this.#e());if(!i)return;let a=wa.translation(Or.getState());await n(e,{content:``,from:``,to:t});let{operationId:o}=this.#e().startOperation({context:{agentId:i.agentId,messageId:e,sessionId:i.sessionId,topicId:i.topicId},label:`Translating message`,type:`translate`});this.#e().associateMessageWithOperation(e,o);try{let s=``,c=``;b7.fetchPresetTaskResult({onFinish:async r=>{r&&vre.includes(r)&&(c=r),await n(e,{content:s,from:c,to:t})},params:Ce(a,Xte(i.content)),trace:this.#e().getCurrentTracePayload({traceName:Se.LanguageDetect})}),await b7.fetchPresetTaskResult({onFinish:async r=>{await n(e,{content:r,from:c,to:t}),this.#e().completeOperation(o)},onMessageHandle:n=>{switch(n.type){case`text`:s+=n.text,r({id:e,key:`translate`,type:`updateMessageExtra`,value:{content:s,from:c,to:t}},{operationId:o});break}},params:Ce(a,jne(i.content,t)),trace:this.#e().getCurrentTracePayload({traceName:Se.Translator})})}catch(e){throw this.#e().failOperation(o,{message:e instanceof Error?e.message:String(e),type:`TranslateError`}),e}};updateMessageTranslate=async(e,t)=>{this.#e().internal_dispatchMessage({id:e,key:`translate`,type:`updateMessageExtra`,value:t===!1?void 0:t}),await Ma.updateMessageTranslate(e,t)}}})),lqe,uqe=e((()=>{Na(),lqe=class{#e;constructor(e,t,n){this.#e=t}clearTTS=async e=>{await this.#e().updateMessageTTS(e,!1)};ttsMessage=async(e,t={})=>{await this.#e().updateMessageTTS(e,t)};updateMessageTTS=async(e,t)=>{this.#e().internal_dispatchMessage({id:e,key:`tts`,type:`updateMessageExtra`,value:t===!1?void 0:t}),await Ma.updateMessageTTS(e,t)}}})),dqe,fqe,pqe,Z9,Q9,$9=e((()=>{x(),y(),d(),gt(),at(),ft(),ct(),Nie(),kWe(),nGe(),FGe(),VGe(),gKe(),yKe(),VKe(),JKe(),eqe(
6012),oqe(),cqe(),uqe(),dqe=class extends pt{resetActionName=`resetChatStore`},fqe=(...e)=>({...Co,...rt([hKe(...e),new BGe(...e),new $Ke(...e),OWe(...e),new aqe(...e),new sqe(...e),new lqe(...e),PGe(...e),BKe(...e),new qKe(...e),new vKe(...e),tGe(...e),new dqe(...e)])}),pqe=lt(`chat`),Z9=b()(g(pqe(fqe)),l),mt(`chat`,Z9),Q9=()=>Z9.getState()}));export{xze as $,jG as $a,AJ as $i,A0 as $n,Eo as $o,PZ as $r,S3 as $t,N5 as A,tq as Aa,JY as Ai,Yke as An,oc as Ao,pTe as Ar,KPe as At,Nze as B,gK as Ba,qJ as Bi,nke as Bn,Ls as Bo,GQ as Br,CPe as Bt,u7 as C,_q as Ca,sX as Ci,MAe as Cn,kc as Co,S$ as Cr,wFe as Ct,q5 as D,aq as Da,$Y as Di,m2 as Dn,mc as Do,DTe as Dr,dFe as Dt,Y5 as E,sq as Ea,nX as Ei,EAe as En,bc as Eo,m$ as Er,fFe as Et,A5 as F,KK as Fa,oY as Fi,s2 as Fn,Qs as Fo,ZQ as Fr,Q3 as Ft,kze as G,nK as Ga,UJ as Gi,kOe as Gn,gs as Go,_Q as Gr,gPe as Gt,w5 as H,_K as Ha,KJ as Hi,XOe as Hn,Ss as Ho,VQ as Hr,H3 as Ht,k5 as I,JK as Ia,dY as Ii,a2 as In,$s as Io,sTe as Ir,Y3 as It,v5 as J,tK as Ja,RJ as Ji,R0 as Jn,Jo,dQ as Jr,M3 as Jt,Dze as K,rK as Ka,zJ as Ki,H0 as Kn,ms as Ko,vQ as Kr,P3 as Kt,Aze as L,UK as La,tY as Li,o2 as Ln,Ks as Lo,JQ as Lr,X3 as Lt,_Be as M,YK as Ma,IY as Mi,u2 as Mn,ic as Mo,n$ as Mr,e6 as Mt,Jze as N,XK as Na,MY as Ni,Wke as Nn,ec as No,r$ as Nr,$3 as Nt,J5 as O,oq as Oa,eX as Oi,bAe as On,cc as Oo,CTe as Or,s6 as Ot,j5 as P,qK as Pa,NY as Pi,wke as Pn,tc as Po,dTe as Pr,LPe as Pt,bze as Q,NG as Qa,kJ as Qi,tOe as Qn,wo as Qo,GZ as Qr,x3 as Qt,T5 as R,yK as Ra,iY as Ri,tke as Rn,qs as Ro,oTe as Rr,APe as Rt,f7 as S,gq as Sa,lX as Si,h2 as Sn,Soe as So,C$ as Sr,j6 as St,l7 as T,fq as Ta,tX as Ti,OAe as Tn,yc as To,h$ as Tr,f6 as Tt,jze as U,vK as Ua,HJ as Ui,YOe as Un,_s as Uo,bQ as Ur,V3 as Ut,Mze as V,hK as Va,GJ as Vi,X0 as Vn,xs as Vo,BQ as Vr,G3 as Vt,Fze as W,iK as Wa,VJ as Wi,JOe as Wn,hs as Wo,OQ as Wr,_Pe as Wt,Cze as X,JG as Xa,FJ as Xi,eOe as Xn,Ao as Xo,oQ as Xr,j3 as Xt,wze as Y,XG as Ya,PJ as Yi,z0 as Yn,qo as Yo,aQ as Yr,N3 as Yt,Sze as Z,YG as Za,jJ as Zi,j0 as Zn,jo as Zo,IZ as Zr,PNe as Zt,b7 as _,Aq as _a,BX as _i,IAe as _n,Yc as _o,z$ as _r,X6 as _t,GKe as a,aJ as aa,CZ as ai,DMe as an,cG as ao,v0 as ar,eze as at,aHe as b,Cq as ba,PX as bi,AAe as bn,ese as bo,O$ as br,z6 as bt,xWe as c,tJ as ca,_Z as ci,CMe as cn,il as co,uDe as cr,G8 as ct,z7 as d,Wq as da,hZ as di,Ije as dn,rl as do,tEe as dr,$Re as dt,TJ as ea,FZ as ei,d3 as en,MG as eo,JDe as er,To as es,mze as et,M7 as f,Uq as fa,nZ as fi,Aje as fn,mse as fo,$$ as fr,U8 as ft,jHe as g,Nq as ga,zX as gi,oje as gn,ose as go,B$ as gr,Z6 as gt,E7 as h,Mq as ha,VX as hi,N2 as hn,Xc as ho,H$ as hr,IRe as ht,G9 as i,cJ as ia,OZ as ii,kMe as in,uG as io,y0 as ir,q8 as it,gBe as j,ZK as ja,FY as ji,d2 as jn,sc as jo,mTe as jr,a6 as jt,hBe as k,eq as ka,qY as ki,p2 as kn,lc as ko,wTe as kr,o6 as kt,B7 as l,nJ as la,yZ as li,r4 as ln,Cse as lo,pEe as lr,XRe as lt,T7 as m,Hq as ma,HX as mi,kje as mn,pse as mo,YTe as mr,L8 as mt,Z9 as n,vJ as na,kZ as ni,l3 as nn,DG as no,k0 as nr,Oo as ns,tze as nt,j9 as o,rJ as oa,wZ as oi,OMe as on,lG as oo,DDe as or,K8 as ot,lUe as p,Rq as pa,tZ as pi,Z2 as pn,Qc as po,U$ as pr,R8 as pt,Oze as q,eK as qa,LJ as qi,OOe as qn,ps as qo,uQ as qr,F3 as qt,XKe as r,sJ as ra,TZ as ri,FMe as rn,OG as ro,_0 as rr,Y8 as rt,X7 as s,iJ as sa,vZ as si,SMe as sn,al as so,lDe as sr,W8 as st,$9 as t,_J as ta,EZ as ti,u3 as tn,kG as to,S0 as tr,ko as ts,hze as tt,dWe as u,Gq as ua,gZ as ui,n4 as un,nl as uo,c1 as ur,QRe as ut,x7 as v,jq as va,LX as vi,LAe as vn,rse as vo,I$ as vr,J6 as vt,d7 as w,dq as wa,cX as wi,DAe as wn,Oc as wo,x$ as wr,CFe as wt,v7 as x,wq as xa,FX as xi,NAe as xn,xoe as xo,j$ as xr,M6 as xt,y7 as y,Tq as ya,RX as yi,jAe as yn,Jc as yo,GTe as yr,B6 as yt,Pze as z,bK as za,ZJ as zi,eke as zn,zs as zo,WQ as zr,J3 as zt};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.