@nextclaw/ui 0.9.13 → 0.9.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/assets/ChannelsList-Cu_hLbps.js +1 -0
  3. package/dist/assets/{ChatPage-B9dHVmrV.js → ChatPage-Dmpau_7n.js} +2 -2
  4. package/dist/assets/{DocBrowser-S-1-qnZQ.js → DocBrowser-C3ijFxFF.js} +1 -1
  5. package/dist/assets/{LogoBadge-t1JzzCtI.js → LogoBadge-BgjXmBcw.js} +1 -1
  6. package/dist/assets/{MarketplacePage-CzIHYJpM.js → MarketplacePage-CAIdEiw8.js} +1 -1
  7. package/dist/assets/{McpMarketplacePage-BTJdjNQ1.js → McpMarketplacePage-DPtH1xcY.js} +1 -1
  8. package/dist/assets/ModelConfig-D-pqArCg.js +1 -0
  9. package/dist/assets/{ProvidersList-BOQArFRk.js → ProvidersList-DnWsJqMQ.js} +1 -1
  10. package/dist/assets/{RemoteAccessPage-CYNQ53xu.js → RemoteAccessPage-BrXq-x0-.js} +1 -1
  11. package/dist/assets/{RuntimeConfig-B0B73pye.js → RuntimeConfig-UE9VaFO7.js} +1 -1
  12. package/dist/assets/{SearchConfig-CKy2QkAP.js → SearchConfig-CP-RM3V3.js} +1 -1
  13. package/dist/assets/{SecretsConfig-BpZLUu88.js → SecretsConfig-CfN_bazs.js} +1 -1
  14. package/dist/assets/{SessionsConfig-CoFI6Fa2.js → SessionsConfig-CgkKzKGv.js} +1 -1
  15. package/dist/assets/{chat-message-D3jZIASl.js → chat-message-CGL3sMsS.js} +1 -1
  16. package/dist/assets/index-D4alkESd.js +8 -0
  17. package/dist/assets/{label-BOvIOmQx.js → label-CbOSodIL.js} +1 -1
  18. package/dist/assets/{page-layout-PG3cwSpz.js → page-layout-BtDnyNLf.js} +1 -1
  19. package/dist/assets/{popover-BB-kINz7.js → popover-DGlUjPQc.js} +1 -1
  20. package/dist/assets/{security-config-Bb6l-viE.js → security-config-D6Bs1yoK.js} +1 -1
  21. package/dist/assets/{skeleton-CLSc5FYO.js → skeleton-BLV99JbX.js} +1 -1
  22. package/dist/assets/{status-dot-Behu7kDZ.js → status-dot-C8vM3IN1.js} +1 -1
  23. package/dist/assets/{switch-CvNG9775.js → switch-AuwUiga3.js} +1 -1
  24. package/dist/assets/{tabs-custom-CUdBQO_7.js → tabs-custom-CTS7SaFG.js} +1 -1
  25. package/dist/assets/{useConfirmDialog-CLLe2uIJ.js → useConfirmDialog-DrMAdNfN.js} +1 -1
  26. package/dist/index.html +1 -1
  27. package/dist/logos/weixin.svg +5 -0
  28. package/package.json +3 -3
  29. package/public/logos/weixin.svg +5 -0
  30. package/src/api/config.ts +4 -2
  31. package/src/components/chat/chat-stream/transport.ts +42 -2
  32. package/src/components/config/ChannelForm.tsx +1 -122
  33. package/src/components/config/ChannelsList.test.tsx +127 -0
  34. package/src/components/config/ChannelsList.tsx +2 -1
  35. package/src/components/config/ModelConfig.tsx +1 -4
  36. package/src/components/config/channel-form-fields.ts +131 -0
  37. package/src/lib/i18n.channels.ts +52 -0
  38. package/src/lib/i18n.ts +2 -43
  39. package/src/lib/logos.ts +1 -0
  40. package/src/transport/app-client.ts +6 -22
  41. package/src/transport/local.transport.ts +4 -3
  42. package/src/transport/remote.transport.ts +7 -2
  43. package/src/transport/sse-stream.test.ts +54 -0
  44. package/src/transport/sse-stream.ts +3 -17
  45. package/dist/assets/ChannelsList-bROKR37R.js +0 -1
  46. package/dist/assets/ModelConfig-BD4o3Kna.js +0 -1
  47. package/dist/assets/index-CmGwUgcl.js +0 -8
  48. package/src/components/config/ModelConfig.test.tsx +0 -78
@@ -1,4 +1,4 @@
1
- var qa=Object.defineProperty;var Wa=(e,t,n)=>t in e?qa(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var _=(e,t,n)=>Wa(e,typeof t!="symbol"?t+"":t,n);import{r as k,j as h,ae as Ga,v as Xt,X as Qa,af as Xa,f as Ya,e as Br,t as Ja,c as Za,y as el,z as tl,h as yi,I as nl,i as ar,n as rl,o as xi,V as sl,q as bi,s as il,w as ol,k as Si,l as al,m as ki,a as ll,ag as ul,B as lr,G as ur,ah as cl,ai as dl,aj as hl,F as fl,ak as pl,al as gl,Z as vi,am as wi,an as Ci,ao as ml,ap as yl,aq as xl,ar as bl,as as Sl,at as kl,d as Yt,a4 as Jt,au as vl,A as cr,_ as $r,av as wl,a0 as Cl,a3 as Tl,a1 as Il,a2 as Ml,aw as jn,ax as Dn,ay as _n,az as Mt,M as Rl,aA as Ti,aB as El,aC as Al,aD as Ll,aE as Ii,aF as Mi,u as Nl}from"./vendor-TJ2hy_Lv.js";import{u as dr}from"./useConfirmDialog-CLLe2uIJ.js";import{i as Pl,t as I,u as Ri,a as Ei,j as jl,k as Dl,l as _l,m as Ol,c as xe,I as hr,B as He,n as Zt,o as Ai,p as On,q as Fl,r as zl,s as fr,v as Bl,T as Kr,L as Ur,w as $l,S as Fn,e as zn,g as Bn,h as St,x as Kl,y as Ul,z as Vl,A as Hl,f as ql,C as Wl,E as Gl,F as Ql,G as en,H as Xl,J as Yl,K as Li,M as Jl,N as Zl,O as eu,P as tu}from"./index-CmGwUgcl.js";import{b as nu,a as ru,S as su,s as iu,c as Vr,e as Hr}from"./chat-message-D3jZIASl.js";import{u as Ni,T as ou,a as au,b as lu,c as uu,P as cu,R as du,d as hu,e as fu,C as Pi,M as pu}from"./MarketplacePage-CzIHYJpM.js";import{b as ji,c as Di,r as _i}from"./provider-models-BOeNnjk9.js";import{R as gu,A as mu,P as yu,C as Oi,T as xu,a as bu,b as Su,c as ku}from"./popover-BB-kINz7.js";import{P as vu,a as wu}from"./page-layout-PG3cwSpz.js";import"./tabs-custom-CUdBQO_7.js";import"./skeleton-CLSc5FYO.js";import"./marketplace-localization-Dk31LJJJ.js";const Cu="ncp";function qr(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="legacy"||t==="ncp"?t:null}function Fi(e){const t=qr(new URLSearchParams(e).get("chatChain"));return t||(qr(void 0)??Cu)}function Tu(e){var v;const{view:t,selectedSessionKey:n,activeBackendRunId:r,isLocallyRunning:s,resumeRun:i}=e,[o,a]=k.useState(null),l=k.useRef(!1),u=k.useRef(new Map),c=k.useRef(new Map),d=k.useRef(new Map),p=k.useRef(r),f=k.useRef(new Set);k.useEffect(()=>{n&&f.current.add(n)},[n]),k.useEffect(()=>{n&&s&&f.current.delete(n)},[s,n]);const m=Pl(t==="chat"?{states:["queued","running"],limit:200,syncActiveStates:!0,isLocallyRunning:s}:void 0),y=k.useMemo(()=>{var C;return nu(((C=m.data)==null?void 0:C.runs)??[])},[(v=m.data)==null?void 0:v.runs]),b=k.useMemo(()=>{const C=ru(y);if(o){const A=y.get(o.sessionKey)??null;A&&(!o.runId||A.runId===o.runId)&&C.delete(o.sessionKey)}return C},[y,o]),g=k.useMemo(()=>{if(!n)return null;const C=y.get(n)??null;return(!C||!o||o.sessionKey!==n?!1:!o.runId||C.runId===o.runId)?null:C},[y,n,o]);return k.useEffect(()=>{r&&(p.current=r)},[r]),k.useEffect(()=>{if(t!=="chat"||!n||!g||!f.current.has(n)||s||r===g.runId||u.current.get(n)===g.runId)return;const A=c.current.get(n);if(A&&A===g.runId)return;const P=d.current.get(n);if(typeof P=="number"){const T=Date.parse(g.requestedAt??"");if(Number.isFinite(T)){if(T<=P+2e3)return}else if(Date.now()-P<=8e3)return}u.current.set(n,g.runId),f.current.delete(n),i(g)},[r,g,s,i,n,t]),k.useEffect(()=>{if(!n){u.current.clear(),c.current.clear(),d.current.clear(),f.current.clear();return}y.has(n)||(u.current.delete(n),c.current.delete(n),d.current.delete(n))},[y,n]),k.useEffect(()=>{var A,P,T;const C=l.current;if(l.current=s,!s&&C&&n){const F=((A=p.current)==null?void 0:A.trim())||((T=(P=y.get(n))==null?void 0:P.runId)==null?void 0:T.trim());F&&c.current.set(n,F),d.current.set(n,Date.now()),a({sessionKey:n,...F?{runId:F}:{}}),m.refetch()}},[y,s,n,m]),k.useEffect(()=>{if(!o)return;const C=y.get(o.sessionKey)??null;if(!C){a(null);return}o.runId&&C.runId!==o.runId&&a(null)},[y,o]),k.useEffect(()=>{s&&(o==null?void 0:o.sessionKey)===n&&a(null)},[s,n,o]),{sessionRunStatusByKey:b}}const Ee="native";function Fe(e){return typeof e!="string"?Ee:e.trim().toLowerCase()||Ee}function lt(e,t){return e==="native"?I("chatSessionTypeNative"):e.trim().split(/[-_]+/g).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")||e}function Iu(e){var n;const t=new Map;for(const r of e){const s=Fe(r.value);t.set(s,{value:s,label:((n=r.label)==null?void 0:n.trim())||lt(s),ready:r.ready??!0,reason:r.reason??null,reasonMessage:r.reasonMessage??null,supportedModels:r.supportedModels,recommendedModel:r.recommendedModel??null,cta:r.cta??null})}return t.has(Ee)||t.set(Ee,{value:Ee,label:lt(Ee),ready:!0,reason:null,reasonMessage:null,supportedModels:void 0,recommendedModel:null,cta:null}),Array.from(t.values()).sort((r,s)=>r.value===Ee?-1:s.value===Ee?1:r.value.localeCompare(s.value))}function zi(e){const{selectedSession:t,selectedSessionKey:n,pendingSessionType:r,setPendingSessionType:s,sessionTypesData:i}=e,o=k.useMemo(()=>Iu((i==null?void 0:i.options)??[]),[i==null?void 0:i.options]),a=k.useMemo(()=>{const b=[...o],g=Fe(t==null?void 0:t.sessionType);return b.some(v=>v.value===g)||b.push({value:g,label:lt(g),ready:!0,reason:null,reasonMessage:null,supportedModels:void 0,recommendedModel:null,cta:null}),b.sort((v,C)=>v.value===Ee?-1:C.value===Ee?1:v.value.localeCompare(C.value))},[o,t==null?void 0:t.sessionType]),l=k.useMemo(()=>Fe((i==null?void 0:i.defaultType)??Ee),[i==null?void 0:i.defaultType]),u=k.useRef(null),c=k.useMemo(()=>Fe((t==null?void 0:t.sessionType)??r??l),[l,r,t==null?void 0:t.sessionType]),d=k.useMemo(()=>a.find(b=>b.value===c)??null,[c,a]);k.useEffect(()=>{if(n)return;const b=typeof r=="string"?r.trim():"",g=Fe(r);(b.length===0||u.current===g||u.current===null&&g===Ee)&&(u.current=l,g!==l&&s(l))},[l,r,n,s]);const p=!n||!!(t!=null&&t.sessionTypeMutable),f=k.useMemo(()=>new Set(o.map(b=>b.value)),[o]),m=k.useMemo(()=>t&&!f.has(Fe(t.sessionType))?!0:(d==null?void 0:d.ready)===!1,[f,t,d==null?void 0:d.ready]),y=k.useMemo(()=>{var b;return t&&!f.has(Fe(t.sessionType))?`${lt(c)} ${I("chatSessionTypeUnavailableSuffix")}`:(d==null?void 0:d.ready)===!1?((b=d.reasonMessage)==null?void 0:b.trim())||`${d.label} setup required`:null},[f,t,c,d]);return{sessionTypeOptions:a,selectedSessionTypeOption:d,defaultSessionType:l,selectedSessionType:c,canEditSessionType:p,sessionTypeUnavailable:m,sessionTypeUnavailableMessage:y}}function Wr(e){return(e==null?void 0:e.trim().toLowerCase())||"native"}function Mu(e,t){if(typeof t!="string")return!1;const n=t.trim();return n?e.some(r=>r.value===n):!1}function Ru(e,t){return typeof t=="string"&&e.includes(t)}function Eu(e){return e.length===0?null:e.includes("off")?"off":e[0]??null}function Bi(e){const{currentValue:t,selectedSessionPreferredValue:n,fallbackPreferredValue:r,defaultValue:s,isValueSupported:i,firstAvailableValue:o,preferSessionPreferredValue:a=!1,preserveCurrentValueOnSessionChange:l=!1}=e;return i(t)&&(!a||l)?t:i(n)?n:i(r)?r:i(s)?s:o}function Au(e){var n;const{modelOptions:t}=e;return t.length===0?"":Bi({currentValue:e.currentSelectedModel,selectedSessionPreferredValue:e.selectedSessionPreferredModel,fallbackPreferredValue:e.fallbackPreferredModel,defaultValue:e.defaultModel,isValueSupported:r=>Mu(t,r),firstAvailableValue:((n=t[0])==null?void 0:n.value)??"",preferSessionPreferredValue:e.preferSessionPreferredModel,preserveCurrentValueOnSessionChange:e.preserveCurrentSelectedModelOnSessionChange})}function Lu(e){const{supportedThinkingLevels:t}=e;return t.length===0?null:Bi({currentValue:e.currentSelectedThinkingLevel,selectedSessionPreferredValue:e.selectedSessionPreferredThinking,fallbackPreferredValue:e.fallbackPreferredThinking,defaultValue:e.defaultThinkingLevel,isValueSupported:n=>Ru(t,n),firstAvailableValue:Eu(t)??"off",preferSessionPreferredValue:e.preferSessionPreferredThinking,preserveCurrentValueOnSessionChange:e.preserveCurrentSelectedThinkingOnSessionChange})}function $i(e){const t=Wr(e.sessionType);let n,r=Number.NEGATIVE_INFINITY;for(const s of e.sessions){if(s.key===e.selectedSessionKey||Wr(s.sessionType)!==t)continue;const i=e.readPreference(s);if(i==null)continue;const o=Date.parse(s.updatedAt),a=Number.isFinite(o)?o:Number.NEGATIVE_INFINITY;(n===void 0||a>r)&&(n=i,r=a)}return n}function Ki(e){return $i({sessions:e.sessions,selectedSessionKey:e.selectedSessionKey,sessionType:e.sessionType,readPreference:t=>{var r;return((r=t.preferredModel)==null?void 0:r.trim())||void 0}})}function Ui(e){return $i({sessions:e.sessions,selectedSessionKey:e.selectedSessionKey,sessionType:e.sessionType,readPreference:t=>t.preferredThinking??void 0})}function Vi(e){const{isPreferenceAvailable:t,emptyValue:n,selectedSessionKey:r,selectedSessionExists:s=!1,setValue:i,resolveValue:o}=e,a=k.useRef(void 0),l=k.useRef(o);k.useEffect(()=>{l.current=o},[o]),k.useEffect(()=>{const u=a.current!==r;if(!t){i(n),a.current=r;return}i(c=>l.current({currentValue:c,sessionChanged:u,preserveCurrentValueOnSessionChange:u&&!!r&&!s})),a.current=r},[n,t,s,r,i])}function Hi(e){const{modelOptions:t,selectedSessionKey:n,selectedSessionExists:r=!1,selectedSessionPreferredModel:s,fallbackPreferredModel:i,defaultModel:o,setSelectedModel:a}=e;Vi({isPreferenceAvailable:t.length>0,emptyValue:"",selectedSessionKey:n,selectedSessionExists:r,setValue:a,resolveValue:({currentValue:l,sessionChanged:u,preserveCurrentValueOnSessionChange:c})=>Au({currentSelectedModel:l,modelOptions:t,selectedSessionPreferredModel:s,fallbackPreferredModel:i,defaultModel:o,preferSessionPreferredModel:u,preserveCurrentSelectedModelOnSessionChange:c})})}function qi(e){const{supportedThinkingLevels:t,selectedSessionKey:n,selectedSessionExists:r=!1,selectedSessionPreferredThinking:s,fallbackPreferredThinking:i,defaultThinkingLevel:o,setSelectedThinkingLevel:a}=e;Vi({isPreferenceAvailable:t.length>0,emptyValue:null,selectedSessionKey:n,selectedSessionExists:r,setValue:a,resolveValue:({currentValue:l,sessionChanged:u,preserveCurrentValueOnSessionChange:c})=>Lu({currentSelectedThinkingLevel:l,supportedThinkingLevels:t,selectedSessionPreferredThinking:s,fallbackPreferredThinking:i,defaultThinkingLevel:o,preferSessionPreferredThinking:u,preserveCurrentSelectedThinkingOnSessionChange:c})})}function Nu(e){var A,P,T,F,B,z;const t=Ri(),n=Ei(),r=jl({q:e.query.trim()||void 0,limit:120,activeMinutes:0}),s=Ni("skill"),i=Dl({sessionKey:e.selectedSessionKey,agentId:e.selectedAgentId}),o=_l(e.selectedSessionKey,300),a=Ol(),l=(t.isFetched||t.isSuccess)&&(n.isFetched||n.isSuccess),u=k.useMemo(()=>{const w=ji({meta:n.data,config:t.data,onlyConfigured:!0}),D=new Set,N=[];for(const $ of w)for(const O of $.models){const R=Di($.prefix,O);!R||D.has(R)||(D.add(R),N.push({value:R,modelLabel:O,providerLabel:$.displayName,thinkingCapability:_i($.modelThinking,O,$.aliases)}))}return N.sort(($,O)=>{const R=$.providerLabel.localeCompare(O.providerLabel);return R!==0?R:$.modelLabel.localeCompare(O.modelLabel)})},[n.data,t.data]),c=k.useMemo(()=>{var w;return((w=r.data)==null?void 0:w.sessions)??[]},[(A=r.data)==null?void 0:A.sessions]),d=k.useMemo(()=>{var w;return((w=s.data)==null?void 0:w.records)??[]},[(P=s.data)==null?void 0:P.records]),p=k.useMemo(()=>c.find(w=>w.key===e.selectedSessionKey)??null,[e.selectedSessionKey,c]),f=zi({selectedSession:p,selectedSessionKey:e.selectedSessionKey,pendingSessionType:e.pendingSessionType,setPendingSessionType:e.setPendingSessionType,sessionTypesData:a.data}),m=k.useMemo(()=>Ki({sessions:c,selectedSessionKey:e.selectedSessionKey,sessionType:f.selectedSessionType}),[e.selectedSessionKey,f.selectedSessionType,c]),y=k.useMemo(()=>u.find(w=>w.value===e.currentSelectedModel),[u,e.currentSelectedModel]),b=k.useMemo(()=>{var w;return((w=y==null?void 0:y.thinkingCapability)==null?void 0:w.supported)??[]},[(T=y==null?void 0:y.thinkingCapability)==null?void 0:T.supported]),g=k.useMemo(()=>{var w;return((w=y==null?void 0:y.thinkingCapability)==null?void 0:w.default)??null},[(F=y==null?void 0:y.thinkingCapability)==null?void 0:F.default]),v=k.useMemo(()=>Ui({sessions:c,selectedSessionKey:e.selectedSessionKey,sessionType:f.selectedSessionType}),[e.selectedSessionKey,f.selectedSessionType,c]);Hi({modelOptions:u,selectedSessionKey:e.selectedSessionKey,selectedSessionExists:!!p,selectedSessionPreferredModel:p==null?void 0:p.preferredModel,fallbackPreferredModel:m,defaultModel:(B=t.data)==null?void 0:B.agents.defaults.model,setSelectedModel:e.setSelectedModel}),qi({supportedThinkingLevels:b,selectedSessionKey:e.selectedSessionKey,selectedSessionExists:!!p,selectedSessionPreferredThinking:(p==null?void 0:p.preferredThinking)??null,fallbackPreferredThinking:v??null,defaultThinkingLevel:g,setSelectedThinkingLevel:e.setSelectedThinkingLevel});const C=k.useMemo(()=>{var w;return((w=o.data)==null?void 0:w.messages)??[]},[(z=o.data)==null?void 0:z.messages]);return{configQuery:t,configMetaQuery:n,sessionsQuery:r,installedSkillsQuery:s,chatCapabilitiesQuery:i,historyQuery:o,sessionTypesQuery:a,isProviderStateResolved:l,modelOptions:u,sessions:c,skillRecords:d,selectedSession:p,historyMessages:C,...f}}function Wi(e){if(e.label&&e.label.trim())return e.label.trim();const t=e.key.split(":");return t[t.length-1]||e.key}const Pu={connected:{dotClass:"bg-emerald-500"},disconnected:{dotClass:"h-2.5 w-2.5 rounded-full border border-gray-400 bg-transparent"},connecting:{dotClass:"text-amber-600"}};function ju({status:e,className:t}){const n=Pu[e],r=e==="connected"?I("connected"):e==="disconnected"?I("disconnected"):I("connecting");return h.jsx(ou,{delayDuration:250,children:h.jsxs(au,{children:[h.jsx(lu,{asChild:!0,children:h.jsx("span",{role:"status","aria-label":r,className:xe("inline-flex h-5 w-5 items-center justify-center",t),children:e==="connecting"?h.jsx(Ga,{className:xe("h-3 w-3 animate-spin",n.dotClass)}):h.jsx("span",{className:xe(e==="connected"?"h-2 w-2 rounded-full":"",n.dotClass)})})}),h.jsx(uu,{side:"bottom",className:"text-xs",children:r})]})})}function Du(e){const{session:t,active:n,runStatus:r,sessionTypeLabel:s,title:i,isEditing:o,draftLabel:a,isSaving:l,onSelect:u,onStartEditing:c,onDraftLabelChange:d,onSave:p,onCancel:f}=e;return h.jsx("div",{className:xe("w-full rounded-xl px-3 py-2 text-left transition-all text-[13px]",n?"bg-gray-200 text-gray-900 font-semibold shadow-sm":"text-gray-700 hover:bg-gray-200/60 hover:text-gray-900"),children:o?h.jsxs("div",{className:"space-y-2",children:[h.jsx(hr,{value:a,onChange:m=>d(m.target.value),onKeyDown:m=>{m.key==="Enter"?(m.preventDefault(),p()):m.key==="Escape"&&(m.preventDefault(),f())},placeholder:I("sessionsLabelPlaceholder"),className:"h-8 rounded-lg border-gray-300 bg-white text-xs",autoFocus:!0,disabled:l}),h.jsxs("div",{className:"flex items-center justify-between gap-2",children:[h.jsx("div",{className:"min-w-0 text-[11px] text-gray-400 truncate",children:t.key}),h.jsxs("div",{className:"flex items-center gap-1",children:[h.jsx(He,{type:"button",size:"icon",variant:"ghost",className:"h-7 w-7 rounded-lg text-gray-500 hover:bg-white hover:text-gray-900",onClick:()=>void p(),disabled:l,"aria-label":I("save"),children:h.jsx(Xt,{className:"h-3.5 w-3.5"})}),h.jsx(He,{type:"button",size:"icon",variant:"ghost",className:"h-7 w-7 rounded-lg text-gray-500 hover:bg-white hover:text-gray-900",onClick:f,disabled:l,"aria-label":I("cancel"),children:h.jsx(Qa,{className:"h-3.5 w-3.5"})})]})]})]}):h.jsxs("div",{className:"group/session relative",children:[h.jsxs("button",{type:"button",onClick:u,className:"w-full text-left",children:[h.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_0.875rem] items-center gap-1.5 pr-8",children:[h.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[h.jsx("span",{className:"truncate font-medium",children:i}),s?h.jsx("span",{className:xe("shrink-0 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none",n?"border-gray-300 bg-white/80 text-gray-700":"border-gray-200 bg-gray-100 text-gray-500"),children:s}):null]}),h.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:r?h.jsx(su,{status:r}):null})]}),h.jsx("div",{className:"mt-0.5 text-[11px] text-gray-400 truncate",children:t.key}),h.jsxs("div",{className:"mt-0.5 text-[11px] text-gray-400 truncate",children:[t.messageCount," · ",Zt(t.updatedAt)]})]}),h.jsx("button",{type:"button",onClick:m=>{m.stopPropagation(),c()},className:xe("absolute right-0 top-0 inline-flex h-7 w-7 items-center justify-center rounded-lg text-gray-400 transition-all hover:bg-white hover:text-gray-900",n?"opacity-100":"opacity-0 group-hover/session:opacity-100 group-focus-within/session:opacity-100"),"aria-label":I("edit"),children:h.jsx(Xa,{className:"h-3.5 w-3.5"})})]})})}function _u(){const e=Ya();return async t=>{try{t.chatChain==="ncp"?(await Ai(t.sessionKey,{label:t.label}),e.invalidateQueries({queryKey:["ncp-sessions"]}),e.invalidateQueries({queryKey:["ncp-session-messages",t.sessionKey]})):(await On(t.sessionKey,{label:t.label}),e.invalidateQueries({queryKey:["sessions"]}),e.invalidateQueries({queryKey:["session-history",t.sessionKey]})),Br.success(I("configSavedApplied"))}catch(n){throw Br.error(I("configSaveFailed")+": "+(n instanceof Error?n.message:String(n))),n}}}const Gi=k.createContext(null);function Qi({presenter:e,children:t}){return h.jsx(Gi.Provider,{value:e,children:t})}function pr(){const e=k.useContext(Gi);if(!e)throw new Error("usePresenter must be used inside ChatPresenterProvider");return e}const Ou=e=>`[data-item-index="${e}"]`;function Xi(e){const t=e.getItemSelector??Ou;k.useEffect(()=>{if(!e.isEnabled||e.itemCount===0)return;const n=e.containerRef.current;if(!n)return;const r=n.querySelector(t(e.activeIndex));r==null||r.scrollIntoView({block:"nearest",inline:"nearest"})},[t,e.activeIndex,e.containerRef,e.isEnabled,e.itemCount])}function Fu(){const e=k.useRef(null),[t,n]=k.useState(null);return k.useEffect(()=>{const r=e.current;if(!r||typeof ResizeObserver>"u")return;const s=()=>{n(r.getBoundingClientRect().width)};s();const i=new ResizeObserver(()=>s());return i.observe(r),()=>i.disconnect()},[]),{elementRef:e,width:t}}function de(...e){return Ja(Za(e))}const Yi=k.forwardRef(({className:e,type:t,...n},r)=>h.jsx("input",{type:t,className:de("flex h-9 w-full rounded-xl border border-gray-200/80 bg-white px-3.5 py-2 text-sm text-gray-900 file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-300 placeholder:font-normal focus:outline-none focus:ring-1 focus:ring-primary/40 focus:border-primary/40 transition-colors disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,...n}));Yi.displayName="ChatInput";const zu=gu,Bu=xu,$u=mu,Ji=k.forwardRef(({className:e,sideOffset:t=8,align:n="start",...r},s)=>h.jsx(yu,{children:h.jsx(Oi,{ref:s,sideOffset:t,align:n,className:de("z-[var(--z-popover,50)] w-72 overflow-hidden rounded-2xl border border-gray-200/50 bg-white p-4 shadow-lg animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));Ji.displayName=Oi.displayName;const Ku=el,Uu=tl,Zi=k.forwardRef(({className:e,children:t,...n},r)=>h.jsxs(yi,{ref:r,className:de("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-xl border border-gray-200/80 bg-white px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/40 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,h.jsx(nl,{asChild:!0,children:h.jsx(ar,{className:"h-4 w-4 opacity-50"})})]}));Zi.displayName=yi.displayName;const eo=k.forwardRef(({className:e,...t},n)=>h.jsx(Si,{ref:n,className:de("flex cursor-default items-center justify-center py-1",e),...t,children:h.jsx(al,{className:"h-4 w-4"})}));eo.displayName=Si.displayName;const to=k.forwardRef(({className:e,...t},n)=>h.jsx(ki,{ref:n,className:de("flex cursor-default items-center justify-center py-1",e),...t,children:h.jsx(ar,{className:"h-4 w-4"})}));to.displayName=ki.displayName;const no=k.forwardRef(({className:e,children:t,position:n="popper",...r},s)=>h.jsx(rl,{children:h.jsxs(xi,{ref:s,className:de("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md bg-white text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[h.jsx(eo,{}),h.jsx(sl,{className:de("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),h.jsx(to,{})]})}));no.displayName=xi.displayName;const ro=k.forwardRef(({className:e,children:t,...n},r)=>h.jsxs(bi,{ref:r,className:de("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-gray-100 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 hover:bg-gray-100",e),...n,children:[h.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:h.jsx(il,{children:h.jsx(Xt,{className:"h-4 w-4"})})}),h.jsx(ol,{children:t})]}));ro.displayName=bi.displayName;const Vu=cu,Hu=du,qu=hu,so=k.forwardRef(({className:e,sideOffset:t=4,...n},r)=>h.jsx(fu,{children:h.jsx(Pi,{ref:r,sideOffset:t,className:de("z-[var(--z-tooltip)] overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})}));so.displayName=Pi.displayName;const Rt={Popover:zu,PopoverAnchor:$u,PopoverContent:Ji,PopoverTrigger:Bu,Input:Yi,Select:Ku,SelectContent:no,SelectItem:ro,SelectTrigger:Zi,SelectValue:Uu,Tooltip:Hu,TooltipContent:so,TooltipProvider:Vu,TooltipTrigger:qu},Wu=680,Gu=.82,Qu=560;function Xu(e){const{Popover:t,PopoverAnchor:n,PopoverContent:r}=Rt,{elementRef:s,width:i}=Fu(),o=k.useRef(null),{isOpen:a,isLoading:l,items:u,activeIndex:c,activeItem:d,texts:p,onSelectItem:f,onOpenChange:m,onSetActiveIndex:y}=e,b=k.useMemo(()=>{if(i)return Math.min(i>Qu?i*Gu:i,Wu)},[i]);return Xi({containerRef:o,activeIndex:c,itemCount:u.length,isEnabled:a&&!l,getItemSelector:g=>`[data-slash-index="${g}"]`}),h.jsxs(t,{open:a,onOpenChange:m,children:[h.jsx(n,{asChild:!0,children:h.jsx("div",{ref:s,className:"pointer-events-none absolute bottom-full left-3 right-3 h-0"})}),h.jsx(r,{side:"top",align:"start",sideOffset:10,className:"z-[70] max-w-[calc(100vw-1.5rem)] overflow-hidden rounded-2xl border border-gray-200 bg-white/95 p-0 shadow-2xl backdrop-blur-md",onOpenAutoFocus:g=>g.preventDefault(),style:b?{width:`${b}px`}:void 0,children:h.jsxs("div",{className:"grid min-h-[240px] grid-cols-[minmax(220px,300px)_minmax(0,1fr)]",children:[h.jsx("div",{ref:o,role:"listbox","aria-label":p.slashSectionLabel,className:"custom-scrollbar max-h-[320px] overflow-y-auto border-r border-gray-200 p-2.5",children:l?h.jsx("div",{className:"p-2 text-xs text-gray-500",children:p.slashLoadingLabel}):h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"mb-2 px-2 text-[11px] font-semibold uppercase tracking-wide text-gray-500",children:p.slashSectionLabel}),u.length===0?h.jsx("div",{className:"px-2 text-xs text-gray-400",children:p.slashEmptyLabel}):h.jsx("div",{className:"space-y-1",children:u.map((g,v)=>{const C=v===c;return h.jsxs("button",{type:"button",role:"option","aria-selected":C,"data-slash-index":v,onMouseEnter:()=>y(v),onClick:()=>f(g),className:`flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left transition ${C?"bg-gray-100 text-gray-900":"text-gray-700 hover:bg-gray-50"}`,children:[h.jsx("span",{className:"truncate text-xs font-semibold",children:g.title}),h.jsx("span",{className:"truncate text-xs text-gray-500",children:g.subtitle})]},g.key)})})]})}),h.jsx("div",{className:"max-w-[320px] p-3.5",children:d?h.jsxs("div",{className:"space-y-3",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"inline-flex rounded-full bg-primary/10 px-2 py-0.5 text-[11px] font-semibold text-primary",children:d.subtitle}),h.jsx("span",{className:"text-sm font-semibold text-gray-900",children:d.title})]}),h.jsx("p",{className:"text-xs leading-5 text-gray-600",children:d.description}),h.jsx("div",{className:"space-y-1",children:d.detailLines.map(g=>h.jsx("div",{className:"rounded-md bg-gray-50 px-2 py-1 text-[11px] text-gray-600",children:g},g))}),h.jsx("div",{className:"pt-1 text-[11px] text-gray-500",children:p.slashSkillHintLabel})]}):h.jsx("div",{className:"text-xs text-gray-500",children:p.slashHintLabel})})]})})]})}const Yu=ll("inline-flex items-center justify-center whitespace-nowrap rounded-full text-sm font-medium ring-offset-background transition-all duration-fast focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary-600 active:bg-primary-700 shadow-sm",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-gray-200 bg-white hover:bg-gray-50 hover:text-gray-800 text-gray-600",secondary:"bg-gray-100 text-gray-700 hover:bg-gray-200/80",ghost:"hover:bg-gray-100/80 hover:text-gray-800",link:"text-primary underline-offset-4 hover:underline",primary:"bg-primary text-primary-foreground hover:bg-primary-600 active:bg-primary-700 shadow-sm",subtle:"bg-gray-100 text-gray-600 hover:bg-gray-200/80","primary-outline":"border border-primary/30 text-primary hover:bg-primary hover:text-primary-foreground"},size:{default:"h-9 px-4 py-2",sm:"h-8 px-3 text-xs",lg:"h-11 px-5 text-[14px]",xl:"h-12 px-6 text-[15px]",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),$t=k.forwardRef(({className:e,variant:t,size:n,...r},s)=>h.jsx("button",{className:de(Yu({variant:t,size:n,className:e})),ref:s,...r}));$t.displayName="ChatButton";function Gr(){return h.jsx("span",{"aria-hidden":"true","data-testid":"chat-stop-icon",className:"block h-3 w-3 rounded-[2px] bg-gray-700 shadow-[inset_0_0_0_1px_rgba(17,24,39,0.06)]"})}function Ju(e){var i;const{Tooltip:t,TooltipContent:n,TooltipProvider:r,TooltipTrigger:s}=Rt;return h.jsxs("div",{className:"flex flex-col items-end gap-1",children:[(i=e.sendError)!=null&&i.trim()?h.jsx("div",{className:"max-w-[420px] text-right text-[11px] text-red-600",children:e.sendError}):null,h.jsx("div",{className:"flex items-center gap-2",children:e.isSending?e.canStopGeneration?h.jsx($t,{size:"icon",variant:"outline",className:"h-8 w-8 rounded-full","aria-label":e.stopButtonLabel,onClick:()=>void e.onStop(),disabled:e.stopDisabled,children:h.jsx(Gr,{})}):h.jsx(r,{children:h.jsxs(t,{children:[h.jsx(s,{asChild:!0,children:h.jsx("span",{children:h.jsx($t,{size:"icon",variant:"outline",className:"h-8 w-8 rounded-full","aria-label":e.stopButtonLabel,disabled:!0,children:h.jsx(Gr,{})})})}),h.jsx(n,{side:"top",children:h.jsx("p",{className:"text-xs",children:e.stopHint})})]})}):h.jsx($t,{size:"icon",className:"h-8 w-8 rounded-full","aria-label":e.sendButtonLabel,onClick:()=>void e.onSend(),disabled:e.sendDisabled,children:h.jsx(ul,{className:"h-5 w-5"})})})]})}function Zu(e,t){const n=t.trim().toLowerCase();return n?e.filter(r=>[r.label,r.key,r.description].filter(i=>typeof i=="string"&&i.trim().length>0).join(" ").toLowerCase().includes(n)):e}function ec(e){const{Input:t,Popover:n,PopoverContent:r,PopoverTrigger:s}=Rt,{picker:i}=e,o=k.useRef(null),a=k.useId(),[l,u]=k.useState(""),[c,d]=k.useState(0),p=k.useMemo(()=>new Set(i.selectedKeys),[i.selectedKeys]),f=i.selectedKeys.length,m=k.useMemo(()=>Zu(i.options,l),[i.options,l]);k.useEffect(()=>{d(0)},[l]),k.useEffect(()=>{d(g=>m.length===0?0:Math.min(g,m.length-1))},[m.length]),Xi({containerRef:o,activeIndex:c,itemCount:m.length,isEnabled:m.length>0,getItemSelector:g=>`[data-skill-index="${g}"]`});const y=g=>{if(p.has(g)){i.onSelectedKeysChange(i.selectedKeys.filter(v=>v!==g));return}i.onSelectedKeysChange([...i.selectedKeys,g])},b=g=>{if(m.length!==0){if(g.key==="ArrowDown"){g.preventDefault(),d(v=>Math.min(v+1,m.length-1));return}if(g.key==="ArrowUp"){g.preventDefault(),d(v=>Math.max(v-1,0));return}if(g.key==="Enter"){g.preventDefault();const v=m[c];v&&y(v.key)}}};return h.jsxs(n,{children:[h.jsx(s,{asChild:!0,children:h.jsxs("button",{type:"button","aria-haspopup":"listbox",className:"inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium text-gray-600 transition-colors hover:bg-gray-100 hover:text-gray-900",children:[h.jsx(lr,{className:"h-4 w-4"}),h.jsx("span",{children:i.title}),f>0?h.jsx("span",{className:"ml-0.5 flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-primary/10 text-[10px] font-semibold text-primary",children:f}):null]})}),h.jsxs(r,{side:"top",align:"start",className:"w-[360px] p-0",children:[h.jsxs("div",{className:"space-y-2 border-b border-gray-100 px-4 py-3",children:[h.jsx("div",{className:"text-sm font-semibold text-gray-900",children:i.title}),h.jsxs("div",{className:"relative",children:[h.jsx(ur,{className:"pointer-events-none absolute left-3 top-2.5 h-3.5 w-3.5 text-gray-400"}),h.jsx(t,{value:l,onChange:g=>u(g.target.value),onKeyDown:b,placeholder:i.searchPlaceholder,role:"combobox","aria-controls":a,"aria-expanded":"true","aria-autocomplete":"list","aria-activedescendant":m[c]?`${a}-option-${c}`:void 0,className:"h-8 rounded-lg pl-8 text-xs"})]})]}),h.jsx("div",{ref:o,id:a,role:"listbox","aria-multiselectable":"true",className:"custom-scrollbar max-h-[320px] overflow-y-auto",children:i.isLoading?h.jsx("div",{className:"p-4 text-xs text-gray-500",children:i.loadingLabel}):m.length===0?h.jsx("div",{className:"p-4 text-center text-xs text-gray-500",children:i.emptyLabel}):h.jsx("div",{className:"py-1",children:m.map((g,v)=>{const C=p.has(g.key),A=v===c;return h.jsxs("button",{type:"button",id:`${a}-option-${v}`,role:"option","aria-selected":C,"data-skill-index":v,onClick:()=>y(g.key),onMouseEnter:()=>d(v),className:`flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors ${A?"bg-gray-50":"hover:bg-gray-50"}`,children:[h.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-gray-100 text-gray-500",children:h.jsx(cl,{className:"h-4 w-4"})}),h.jsxs("div",{className:"min-w-0 flex-1",children:[h.jsxs("div",{className:"flex items-center gap-1.5",children:[h.jsx("span",{className:"truncate text-sm text-gray-900",children:g.label}),g.badgeLabel?h.jsx("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary",children:g.badgeLabel}):null]}),h.jsx("div",{className:"mt-0.5 truncate text-xs text-gray-500",children:g.description||g.key})]}),h.jsx("div",{className:"ml-3 shrink-0",children:h.jsx("span",{className:C?"inline-flex h-5 w-5 items-center justify-center rounded-full bg-primary text-white":"inline-flex h-5 w-5 items-center justify-center rounded-full border border-gray-300 bg-white",children:C?h.jsx(Xt,{className:"h-3 w-3"}):null})})]},g.key)})})}),i.manageHref&&i.manageLabel?h.jsx("div",{className:"border-t border-gray-100 px-4 py-2.5",children:h.jsxs("a",{href:i.manageHref,className:"inline-flex items-center gap-1.5 text-xs font-medium text-primary transition-colors hover:text-primary/80",children:[i.manageLabel,h.jsx(dl,{className:"h-3 w-3"})]})}):null]})]})}function io({icon:e}){return e==="sparkles"?h.jsx(fl,{className:"h-3.5 w-3.5 shrink-0 text-primary"}):e==="brain"?h.jsx(pl,{className:"h-3.5 w-3.5 shrink-0 text-gray-500"}):null}function tc({icon:e}){return e==="paperclip"?h.jsx(hl,{className:"h-4 w-4"}):h.jsx(io,{icon:e})}function nc(e){return e==="model"?"min-w-[220px]":e==="session-type"?"min-w-[140px]":e==="thinking"?"min-w-[150px]":""}function rc(e){return e==="model"?"w-[320px]":e==="session-type"?"w-[220px]":e==="thinking"?"w-[180px]":""}function sc({item:e}){const{Select:t,SelectContent:n,SelectItem:r,SelectTrigger:s,SelectValue:i}=Rt;return h.jsxs(t,{value:e.value,onValueChange:e.onValueChange,disabled:e.disabled,children:[h.jsx(s,{className:`h-8 w-auto rounded-lg border-0 bg-transparent px-3 text-xs font-medium text-gray-600 shadow-none hover:bg-gray-100 focus:ring-0 ${nc(e.key)}`,children:e.selectedLabel?h.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-left",children:[h.jsx(io,{icon:e.icon}),h.jsx("span",{className:"truncate text-xs font-semibold text-gray-700",children:e.selectedLabel})]}):e.loading?h.jsx("div",{className:"h-3 w-24 animate-pulse rounded bg-gray-200"}):h.jsx(i,{placeholder:e.placeholder})}),h.jsxs(n,{className:rc(e.key),children:[e.options.length===0?e.loading?h.jsxs("div",{className:"space-y-2 px-3 py-2",children:[h.jsx("div",{className:"h-3 w-36 animate-pulse rounded bg-gray-200"}),h.jsx("div",{className:"h-3 w-28 animate-pulse rounded bg-gray-200"}),h.jsx("div",{className:"h-3 w-32 animate-pulse rounded bg-gray-200"})]}):e.emptyLabel?h.jsx("div",{className:"px-3 py-2 text-xs text-gray-500",children:e.emptyLabel}):null:null,e.options.map(o=>h.jsx(r,{value:o.value,className:"py-2",children:o.description?h.jsxs("div",{className:"flex min-w-0 flex-col gap-0.5",children:[h.jsx("span",{className:"truncate text-xs font-semibold text-gray-800",children:o.label}),h.jsx("span",{className:"truncate text-[11px] text-gray-500",children:o.description})]}):h.jsx("span",{className:"truncate text-xs font-semibold text-gray-800",children:o.label})},o.value))]})]})}function ic(e){var i;const{Tooltip:t,TooltipContent:n,TooltipProvider:r,TooltipTrigger:s}=Rt;return h.jsxs("div",{className:"flex items-center justify-between px-3 pb-3",children:[h.jsxs("div",{className:"flex items-center gap-1",children:[e.skillPicker?h.jsx(ec,{picker:e.skillPicker}):null,e.selects.map(o=>h.jsx(sc,{item:o},o.key)),(i=e.accessories)==null?void 0:i.map(o=>{const a=h.jsxs("button",{type:"button",className:`inline-flex items-center rounded-lg py-1.5 text-xs font-medium text-gray-600 transition-colors hover:bg-gray-100 hover:text-gray-900 disabled:cursor-not-allowed disabled:text-gray-400 ${o.iconOnly?"h-8 w-8 justify-center px-0":"gap-1.5 px-3"}`,onClick:o.onClick,disabled:o.disabled,"aria-label":o.label,children:[h.jsx(tc,{icon:o.icon}),o.iconOnly?null:h.jsx("span",{children:o.label})]});if(!o.tooltip)return h.jsx("div",{children:a},o.key);const l=o.disabled?h.jsx("span",{className:"inline-flex",children:a}):a;return h.jsx(r,{children:h.jsxs(t,{children:[h.jsx(s,{asChild:!0,children:l}),h.jsx(n,{side:"top",children:h.jsx("p",{className:"text-xs",children:o.tooltip})})]})},o.key)})]}),h.jsx(Ju,{...e.actions})]})}const oc="";function oo(){return`composer-${Math.random().toString(36).slice(2,10)}`}function Ct(e=""){return{id:oo(),type:"text",text:e}}function gr(e){return{id:oo(),type:"token",tokenKind:e.tokenKind,tokenKey:e.tokenKey,label:e.label}}function Et(e){return e.type==="text"?e.text.length:1}function mr(){return[Ct("")]}function ac(e){return[Ct(e)]}function ut(e){const t=[];for(const n of e){if(n.type==="text"){if(n.text.length===0)continue;const r=t[t.length-1];if((r==null?void 0:r.type)==="text"){t[t.length-1]={...r,text:r.text+n.text};continue}}t.push(n)}return t.length===0?mr():t}function lc(e){return e.map(t=>t.type==="text"?t.text:oc).join("")}function uc(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}function yr(e,t){const n=[],r=new Set;for(const s of e)s.type!=="token"||s.tokenKind!==t||r.has(s.tokenKey)||(r.add(s.tokenKey),n.push(s.tokenKey));return n}function cc(e,t,n,r){const s=Math.max(0,n-t),i=Math.max(0,t+e.text.length-r),o=[];return s>0&&o.push({...e,text:e.text.slice(0,s)}),i>0&&o.push({...e,text:e.text.slice(e.text.length-i)}),o}function dc(e,t,n,r){return t<=n||e>=r}function hc(e,t,n,r,s){return!n&&r>=s?(e.push(...t),!0):n}function fc(e,t,n,r,s,i,o){const a=cc(t,n,r,s);a[0]&&e.push(a[0]);let l=o;return l||(e.push(...i),l=!0),a[1]&&e.push(a[1]),l}function pc(e,t,n,r,s,i){return!r&&s<=i?(e.push(...n),!0):(e.push(t),r)}function un(e,t,n,r){const s=Math.max(0,t),i=Math.max(s,n),o=[];let a=0,l=!1;for(const u of e){const c=Et(u),d=a,p=a+c;if(dc(d,p,s,i)){l=hc(o,r,l,d,i),o.push(u),a=p;continue}u.type==="text"?l=fc(o,u,d,s,i,r,l):l=pc(o,u,r,l,s,d),a=p}return l||o.push(...r),ut(o)}function ao(e,t){return ut(e.filter(n=>n.type!=="token"||!t(n)))}function gc(e,t){if(!t||t.start!==t.end)return null;const n=lc(e),r=t.end,s=n.slice(0,r),i=/(?:^|\s)\/([^\s\uFFFC]*)$/.exec(s);if(!i)return null;const o=r-i[0].length+(i[0].startsWith("/")?0:1);return{query:(i[1]??"").trim().toLowerCase(),start:o,end:r}}function mc(e,t,n){return e?e.start<n&&e.end>t:!1}function lo(e){const t=new Map;let n=0;for(const r of e)t.set(r.id,n),n+=Et(r);return t}function uo(e,t){let n=t;for(;n&&n.parentNode!==e;)n=n.parentNode;return n?Array.prototype.indexOf.call(e.childNodes,n):e.childNodes.length}function yc(e,t,n){if(e instanceof HTMLElement){const r=e.dataset.composerNodeId;if(r)return n.find(s=>s.id===r)}return n[t]}function co(e,t,n){let r=0;for(let s=0;s<n;s+=1){const i=yc(e.childNodes[s],s,t);i&&(r+=Et(i))}return r}function xc(e,t,n,r){var a;const s=uo(e,t),i=co(e,r,s),o=r[s];return(o==null?void 0:o.type)==="text"?i+Math.min(n,o.text.length):i+Math.min(n,((a=t.textContent)==null?void 0:a.length)??0)}function bc(e,t,n,r,s){return n.type==="text"?e.nodeType===Node.TEXT_NODE?r+Math.min(t,n.text.length):e===s?r+(t>0?n.text.length:0):r+n.text.length:e===s?r+(t>0?1:0):r+1}function $n(e,t,n,r,s){var u;if(t===e)return co(e,r,n);if(t.nodeType===Node.TEXT_NODE&&t.parentNode===e)return xc(e,t,n,r);const i=t instanceof HTMLElement?t.closest("[data-composer-node-id]"):((u=t.parentElement)==null?void 0:u.closest("[data-composer-node-id]"))??null;if(!(i instanceof HTMLElement)){const c=uo(e,t);return $n(e,e,c,r,s)}const o=i.dataset.composerNodeId;if(!o)return 0;const a=r.find(c=>c.id===o),l=s.get(o)??0;return a?bc(t,n,a,l,i):l}function ho(e,t){const n=window.getSelection();if(!n||n.rangeCount===0)return null;const r=n.getRangeAt(0);if(!e.contains(r.startContainer)||!e.contains(r.endContainer))return null;const s=lo(t),i=$n(e,r.startContainer,r.startOffset,t,s),o=$n(e,r.endContainer,r.endOffset,t,s);return{start:Math.min(i,o),end:Math.max(i,o)}}function Sc(e,t,n){if(!n)return;const r=window.getSelection();if(!r)return;const s=l=>{let u=0;for(let c=0;c<t.length;c+=1){const d=t[c],p=Et(d),f=u,m=u+p,y=e.childNodes[c];if(!y){u=m;continue}if(d.type==="text"){if(l<=m)return{container:y.firstChild??y,offset:Math.max(0,Math.min(l-f,d.text.length))}}else{if(l<=f)return{container:e,offset:c};if(l<=m)return{container:e,offset:c+1}}u=m}return{container:e,offset:e.childNodes.length}},i=s(n.start),o=s(n.end),a=document.createRange();a.setStart(i.container,i.offset),a.setEnd(o.container,o.offset),r.removeAllRanges(),r.addRange(a)}function kc(e){const t=[];for(const n of Array.from(e.childNodes)){if(n.nodeType===Node.TEXT_NODE){t.push(Ct(n.textContent??""));continue}if(!(n instanceof HTMLElement))continue;if(n.dataset.composerNodeType==="token"){const i=n.dataset.composerTokenKind,o=n.dataset.composerTokenKey,a=n.dataset.composerLabel;i&&o&&a&&t.push({id:n.dataset.composerNodeId??gr({tokenKind:i,tokenKey:o,label:a}).id,type:"token",tokenKind:i,tokenKey:o,label:a});continue}const s=n.textContent??"";t.push({id:n.dataset.composerNodeId??Ct(s).id,type:"text",text:s})}return ut(t)}function Qr(e){const t=kc(e);return{nodes:t,selection:ho(e,t)}}class vc{constructor(){this.nodes=mr(),this.selection=null,this.sync=(t,n)=>(this.nodes=ut(t),this.selection=n,this.getSnapshot()),this.setSelection=t=>(this.selection=t,this.getSnapshot()),this.replaceDocument=(t,n)=>(this.nodes=ut(t),this.selection=n,this.getSnapshot()),this.insertText=t=>{const n=this.selection??{start:0,end:0};this.nodes=un(this.nodes,n.start,n.end,[Ct(t)]);const r=n.start+t.length;return this.selection={start:r,end:r},this.getSnapshot()},this.insertSkillToken=(t,n)=>{var a,l;if(this.getSelectedSkillKeys().includes(t))return this.getSnapshot();const r=this.getSlashTrigger(),s=this.getDocumentLength(),i=(r==null?void 0:r.start)??((a=this.selection)==null?void 0:a.start)??s,o=(r==null?void 0:r.end)??((l=this.selection)==null?void 0:l.end)??i;return this.nodes=un(this.nodes,i,o,[gr({tokenKind:"skill",tokenKey:t,label:n})]),this.selection={start:i+1,end:i+1},this.getSnapshot()},this.syncSelectedSkills=(t,n)=>{const r=this.getSelectedSkillKeys(),s=new Map(n.map(a=>[a.key,a])),i=t.find(a=>!r.includes(a));if(i){const a=s.get(i);return this.insertSkillToken(i,(a==null?void 0:a.label)??i)}const o=r.find(a=>!t.includes(a));return o&&(this.nodes=ao(this.nodes,a=>a.tokenKind==="skill"&&a.tokenKey===o)),this.getSnapshot()},this.deleteContent=t=>{const n=this.getDocumentLength(),r=this.selection??{start:n,end:n};let s=r.start,i=r.end;if(r.start===r.end)if(t==="backward"&&r.start>0)s=r.start-1;else if(t==="forward")i=r.end+1;else return this.getSnapshot();return this.nodes=un(this.nodes,s,i,[]),this.selection={start:s,end:s},this.getSnapshot()},this.getSnapshot=()=>({nodes:this.nodes,selection:this.selection,nodeStartMap:lo(this.nodes),documentLength:this.getDocumentLength(),selectedSkillKeys:this.getSelectedSkillKeys(),slashTrigger:this.getSlashTrigger()}),this.getDocumentLength=()=>this.nodes.reduce((t,n)=>t+Et(n),0),this.getSelectedSkillKeys=()=>yr(this.nodes,"skill"),this.getSlashTrigger=()=>gc(this.nodes,this.selection)}}function wc(e){const{key:t,shiftKey:n,isComposing:r,isSlashMenuOpen:s,slashItemCount:i,activeSlashIndex:o,isSending:a,canStopGeneration:l}=e;if(s&&i>0){if(t==="ArrowDown")return{type:"move-slash-index",index:(o+1)%i};if(t==="ArrowUp")return{type:"move-slash-index",index:(o-1+i)%i};if(t==="Enter"&&!n||t==="Tab")return{type:"insert-active-slash-item"}}return t==="Escape"?s?{type:"close-slash"}:a&&l?{type:"stop-generation"}:{type:"noop"}:t==="Enter"&&n?{type:"insert-line-break"}:t==="Enter"?{type:"send-message"}:!r&&(t==="Backspace"||t==="Delete")?{type:"delete-content",direction:t==="Backspace"?"backward":"forward"}:{type:"noop"}}const Xr="http://www.w3.org/2000/svg";class Cc{constructor(){this.render=(t,n)=>{if(!t)return;const r=document.createDocumentFragment();for(const s of n.nodes){const i=s.type==="text"?this.createTextNodeElement(s):this.createTokenNodeElement(s,n.selectedRange,n.nodeStartMap);i&&r.appendChild(i)}t.replaceChildren(r)},this.createTextNodeElement=t=>{if(t.text.length===0)return null;const n=document.createElement("span");return n.dataset.composerNodeId=t.id,n.dataset.composerNodeType="text",n.textContent=t.text,n},this.createTokenNodeElement=(t,n,r)=>{const s=r.get(t.id)??0,i=mc(n,s,s+1),o=document.createElement("span");o.contentEditable="false",o.dataset.composerNodeId=t.id,o.dataset.composerNodeType="token",o.dataset.composerTokenKind=t.tokenKind,o.dataset.composerTokenKey=t.tokenKey,o.dataset.composerLabel=t.label,o.className=["mx-[2px]","inline-flex","h-6","max-w-full","items-center","gap-1","rounded-md","border","px-1.5","align-baseline","text-[11px]","font-medium","transition",i?"border-primary/30 bg-primary/18 text-primary":"border-primary/12 bg-primary/8 text-primary"].join(" "),o.append(this.createTokenIcon(t.tokenKind));const a=document.createElement("span");return a.className="truncate",a.textContent=t.label,o.append(a),o},this.createTokenIcon=t=>{const n=document.createElement("span");return n.className="inline-flex h-3 w-3 shrink-0 items-center justify-center text-primary/70",n.append(t==="file"?this.createFileIcon():this.createSkillIcon()),n},this.createSkillIcon=()=>this.createSvgIcon([{tag:"path",attrs:{d:"M8.5 2.75 2.75 6l5.75 3.25L14.25 6 8.5 2.75Z"}},{tag:"path",attrs:{d:"M2.75 10 8.5 13.25 14.25 10"}},{tag:"path",attrs:{d:"M2.75 6v4l5.75 3.25V9.25L2.75 6Z"}},{tag:"path",attrs:{d:"M14.25 6v4L8.5 13.25V9.25L14.25 6Z"}}]),this.createFileIcon=()=>this.createSvgIcon([{tag:"path",attrs:{d:"M5.25 2.75h4.5L13 6v7.25A1.75 1.75 0 0 1 11.25 15h-6.5A1.75 1.75 0 0 1 3 13.25v-8.75A1.75 1.75 0 0 1 4.75 2.75Z"}},{tag:"path",attrs:{d:"M9.75 2.75V6H13"}},{tag:"path",attrs:{d:"M5.75 8.75h4.5"}},{tag:"path",attrs:{d:"M5.75 10.75h4.5"}}]),this.createSvgIcon=t=>{const n=document.createElementNS(Xr,"svg");n.setAttribute("viewBox","0 0 16 16"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.25"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("class","h-3 w-3");for(const r of t){const s=document.createElementNS(Xr,r.tag);for(const[i,o]of Object.entries(r.attrs))s.setAttribute(i,o);n.append(s)}return n}}}const Yr=188;class Tc{constructor(t){this.controller=t,this.surfaceRenderer=new Cc,this.sync=(n,r)=>this.controller.sync(n,r),this.syncSelectionFromRoot=n=>this.controller.setSelection(ho(n,this.controller.getSnapshot().nodes)),this.restoreSelectionIfFocused=(n,r)=>{!n||document.activeElement!==n||Sc(n,this.controller.getSnapshot().nodes,r)},this.syncViewport=n=>{n&&(n.style.maxHeight=`${Yr}px`,n.style.overflowY=n.scrollHeight>Yr?"auto":"hidden")},this.renderSurface=n=>{this.surfaceRenderer.render(n.root,{nodes:n.snapshot.nodes,selectedRange:n.selectedRange,nodeStartMap:n.snapshot.nodeStartMap})},this.insertSlashItem=(n,r)=>{n.value&&r(this.controller.insertSkillToken(n.value,n.title))},this.syncSelectedSkills=(n,r,s)=>{s(this.controller.syncSelectedSkills(n,r))},this.handleBeforeInput=n=>{const{event:r,disabled:s,isComposing:i,commitSnapshot:o}=n,a=r.nativeEvent;s||i||a.isComposing||!(a.inputType==="insertText"||a.inputType==="insertReplacementText")||!a.data||(r.preventDefault(),o(this.controller.insertText(a.data)))},this.handleInput=n=>{const{event:r,isComposing:s,commitSnapshot:i}=n,o=r.nativeEvent;if(s||o.isComposing)return;const a=r.currentTarget,l=Qr(a);i(this.controller.replaceDocument(l.nodes,l.selection))},this.handleCompositionEnd=n=>{const{event:r,commitSnapshot:s}=n,i=r.currentTarget,o=Qr(i);s(this.controller.replaceDocument(o.nodes,o.selection))},this.handleKeyDown=n=>{const{event:r,slashItems:s,activeSlashIndex:i,activeSlashItem:o,actions:a,commitSnapshot:l,insertSkillToken:u,onSlashActiveIndexChange:c,onSlashQueryChange:d,onSlashOpenChange:p}=n,f=this.controller.getSnapshot(),m=wc({key:r.key,shiftKey:r.shiftKey,isComposing:r.nativeEvent.isComposing,isSlashMenuOpen:f.slashTrigger!==null,slashItemCount:s.length,activeSlashIndex:i,isSending:a.isSending,canStopGeneration:a.canStopGeneration});if(m.type!=="noop"){if(r.preventDefault(),m.type==="move-slash-index"){c(m.index);return}if(m.type==="insert-active-slash-item"){o&&u(o.value??o.key,o.title);return}if(m.type==="close-slash"){d==null||d(null),p(!1);return}if(m.type==="stop-generation"){a.onStop();return}if(m.type==="insert-line-break"){l(this.controller.insertText(`
1
+ var qa=Object.defineProperty;var Wa=(e,t,n)=>t in e?qa(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var _=(e,t,n)=>Wa(e,typeof t!="symbol"?t+"":t,n);import{r as k,j as h,ae as Ga,v as Xt,X as Qa,af as Xa,f as Ya,e as Br,t as Ja,c as Za,y as el,z as tl,h as yi,I as nl,i as ar,n as rl,o as xi,V as sl,q as bi,s as il,w as ol,k as Si,l as al,m as ki,a as ll,ag as ul,B as lr,G as ur,ah as cl,ai as dl,aj as hl,F as fl,ak as pl,al as gl,Z as vi,am as wi,an as Ci,ao as ml,ap as yl,aq as xl,ar as bl,as as Sl,at as kl,d as Yt,a4 as Jt,au as vl,A as cr,_ as $r,av as wl,a0 as Cl,a3 as Tl,a1 as Il,a2 as Ml,aw as jn,ax as Dn,ay as _n,az as Mt,M as Rl,aA as Ti,aB as El,aC as Al,aD as Ll,aE as Ii,aF as Mi,u as Nl}from"./vendor-TJ2hy_Lv.js";import{u as dr}from"./useConfirmDialog-DrMAdNfN.js";import{i as Pl,t as I,u as Ri,a as Ei,j as jl,k as Dl,l as _l,m as Ol,c as xe,I as hr,B as He,n as Zt,o as Ai,p as On,q as Fl,r as zl,s as fr,v as Bl,T as Kr,L as Ur,w as $l,S as Fn,e as zn,g as Bn,h as St,x as Kl,y as Ul,z as Vl,A as Hl,f as ql,C as Wl,E as Gl,F as Ql,G as en,H as Xl,J as Yl,K as Li,M as Jl,N as Zl,O as eu,P as tu}from"./index-D4alkESd.js";import{b as nu,a as ru,S as su,s as iu,c as Vr,e as Hr}from"./chat-message-CGL3sMsS.js";import{u as Ni,T as ou,a as au,b as lu,c as uu,P as cu,R as du,d as hu,e as fu,C as Pi,M as pu}from"./MarketplacePage-CAIdEiw8.js";import{b as ji,c as Di,r as _i}from"./provider-models-BOeNnjk9.js";import{R as gu,A as mu,P as yu,C as Oi,T as xu,a as bu,b as Su,c as ku}from"./popover-DGlUjPQc.js";import{P as vu,a as wu}from"./page-layout-BtDnyNLf.js";import"./tabs-custom-CTS7SaFG.js";import"./skeleton-BLV99JbX.js";import"./marketplace-localization-Dk31LJJJ.js";const Cu="ncp";function qr(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="legacy"||t==="ncp"?t:null}function Fi(e){const t=qr(new URLSearchParams(e).get("chatChain"));return t||(qr(void 0)??Cu)}function Tu(e){var v;const{view:t,selectedSessionKey:n,activeBackendRunId:r,isLocallyRunning:s,resumeRun:i}=e,[o,a]=k.useState(null),l=k.useRef(!1),u=k.useRef(new Map),c=k.useRef(new Map),d=k.useRef(new Map),p=k.useRef(r),f=k.useRef(new Set);k.useEffect(()=>{n&&f.current.add(n)},[n]),k.useEffect(()=>{n&&s&&f.current.delete(n)},[s,n]);const m=Pl(t==="chat"?{states:["queued","running"],limit:200,syncActiveStates:!0,isLocallyRunning:s}:void 0),y=k.useMemo(()=>{var C;return nu(((C=m.data)==null?void 0:C.runs)??[])},[(v=m.data)==null?void 0:v.runs]),b=k.useMemo(()=>{const C=ru(y);if(o){const A=y.get(o.sessionKey)??null;A&&(!o.runId||A.runId===o.runId)&&C.delete(o.sessionKey)}return C},[y,o]),g=k.useMemo(()=>{if(!n)return null;const C=y.get(n)??null;return(!C||!o||o.sessionKey!==n?!1:!o.runId||C.runId===o.runId)?null:C},[y,n,o]);return k.useEffect(()=>{r&&(p.current=r)},[r]),k.useEffect(()=>{if(t!=="chat"||!n||!g||!f.current.has(n)||s||r===g.runId||u.current.get(n)===g.runId)return;const A=c.current.get(n);if(A&&A===g.runId)return;const P=d.current.get(n);if(typeof P=="number"){const T=Date.parse(g.requestedAt??"");if(Number.isFinite(T)){if(T<=P+2e3)return}else if(Date.now()-P<=8e3)return}u.current.set(n,g.runId),f.current.delete(n),i(g)},[r,g,s,i,n,t]),k.useEffect(()=>{if(!n){u.current.clear(),c.current.clear(),d.current.clear(),f.current.clear();return}y.has(n)||(u.current.delete(n),c.current.delete(n),d.current.delete(n))},[y,n]),k.useEffect(()=>{var A,P,T;const C=l.current;if(l.current=s,!s&&C&&n){const F=((A=p.current)==null?void 0:A.trim())||((T=(P=y.get(n))==null?void 0:P.runId)==null?void 0:T.trim());F&&c.current.set(n,F),d.current.set(n,Date.now()),a({sessionKey:n,...F?{runId:F}:{}}),m.refetch()}},[y,s,n,m]),k.useEffect(()=>{if(!o)return;const C=y.get(o.sessionKey)??null;if(!C){a(null);return}o.runId&&C.runId!==o.runId&&a(null)},[y,o]),k.useEffect(()=>{s&&(o==null?void 0:o.sessionKey)===n&&a(null)},[s,n,o]),{sessionRunStatusByKey:b}}const Ee="native";function Fe(e){return typeof e!="string"?Ee:e.trim().toLowerCase()||Ee}function lt(e,t){return e==="native"?I("chatSessionTypeNative"):e.trim().split(/[-_]+/g).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")||e}function Iu(e){var n;const t=new Map;for(const r of e){const s=Fe(r.value);t.set(s,{value:s,label:((n=r.label)==null?void 0:n.trim())||lt(s),ready:r.ready??!0,reason:r.reason??null,reasonMessage:r.reasonMessage??null,supportedModels:r.supportedModels,recommendedModel:r.recommendedModel??null,cta:r.cta??null})}return t.has(Ee)||t.set(Ee,{value:Ee,label:lt(Ee),ready:!0,reason:null,reasonMessage:null,supportedModels:void 0,recommendedModel:null,cta:null}),Array.from(t.values()).sort((r,s)=>r.value===Ee?-1:s.value===Ee?1:r.value.localeCompare(s.value))}function zi(e){const{selectedSession:t,selectedSessionKey:n,pendingSessionType:r,setPendingSessionType:s,sessionTypesData:i}=e,o=k.useMemo(()=>Iu((i==null?void 0:i.options)??[]),[i==null?void 0:i.options]),a=k.useMemo(()=>{const b=[...o],g=Fe(t==null?void 0:t.sessionType);return b.some(v=>v.value===g)||b.push({value:g,label:lt(g),ready:!0,reason:null,reasonMessage:null,supportedModels:void 0,recommendedModel:null,cta:null}),b.sort((v,C)=>v.value===Ee?-1:C.value===Ee?1:v.value.localeCompare(C.value))},[o,t==null?void 0:t.sessionType]),l=k.useMemo(()=>Fe((i==null?void 0:i.defaultType)??Ee),[i==null?void 0:i.defaultType]),u=k.useRef(null),c=k.useMemo(()=>Fe((t==null?void 0:t.sessionType)??r??l),[l,r,t==null?void 0:t.sessionType]),d=k.useMemo(()=>a.find(b=>b.value===c)??null,[c,a]);k.useEffect(()=>{if(n)return;const b=typeof r=="string"?r.trim():"",g=Fe(r);(b.length===0||u.current===g||u.current===null&&g===Ee)&&(u.current=l,g!==l&&s(l))},[l,r,n,s]);const p=!n||!!(t!=null&&t.sessionTypeMutable),f=k.useMemo(()=>new Set(o.map(b=>b.value)),[o]),m=k.useMemo(()=>t&&!f.has(Fe(t.sessionType))?!0:(d==null?void 0:d.ready)===!1,[f,t,d==null?void 0:d.ready]),y=k.useMemo(()=>{var b;return t&&!f.has(Fe(t.sessionType))?`${lt(c)} ${I("chatSessionTypeUnavailableSuffix")}`:(d==null?void 0:d.ready)===!1?((b=d.reasonMessage)==null?void 0:b.trim())||`${d.label} setup required`:null},[f,t,c,d]);return{sessionTypeOptions:a,selectedSessionTypeOption:d,defaultSessionType:l,selectedSessionType:c,canEditSessionType:p,sessionTypeUnavailable:m,sessionTypeUnavailableMessage:y}}function Wr(e){return(e==null?void 0:e.trim().toLowerCase())||"native"}function Mu(e,t){if(typeof t!="string")return!1;const n=t.trim();return n?e.some(r=>r.value===n):!1}function Ru(e,t){return typeof t=="string"&&e.includes(t)}function Eu(e){return e.length===0?null:e.includes("off")?"off":e[0]??null}function Bi(e){const{currentValue:t,selectedSessionPreferredValue:n,fallbackPreferredValue:r,defaultValue:s,isValueSupported:i,firstAvailableValue:o,preferSessionPreferredValue:a=!1,preserveCurrentValueOnSessionChange:l=!1}=e;return i(t)&&(!a||l)?t:i(n)?n:i(r)?r:i(s)?s:o}function Au(e){var n;const{modelOptions:t}=e;return t.length===0?"":Bi({currentValue:e.currentSelectedModel,selectedSessionPreferredValue:e.selectedSessionPreferredModel,fallbackPreferredValue:e.fallbackPreferredModel,defaultValue:e.defaultModel,isValueSupported:r=>Mu(t,r),firstAvailableValue:((n=t[0])==null?void 0:n.value)??"",preferSessionPreferredValue:e.preferSessionPreferredModel,preserveCurrentValueOnSessionChange:e.preserveCurrentSelectedModelOnSessionChange})}function Lu(e){const{supportedThinkingLevels:t}=e;return t.length===0?null:Bi({currentValue:e.currentSelectedThinkingLevel,selectedSessionPreferredValue:e.selectedSessionPreferredThinking,fallbackPreferredValue:e.fallbackPreferredThinking,defaultValue:e.defaultThinkingLevel,isValueSupported:n=>Ru(t,n),firstAvailableValue:Eu(t)??"off",preferSessionPreferredValue:e.preferSessionPreferredThinking,preserveCurrentValueOnSessionChange:e.preserveCurrentSelectedThinkingOnSessionChange})}function $i(e){const t=Wr(e.sessionType);let n,r=Number.NEGATIVE_INFINITY;for(const s of e.sessions){if(s.key===e.selectedSessionKey||Wr(s.sessionType)!==t)continue;const i=e.readPreference(s);if(i==null)continue;const o=Date.parse(s.updatedAt),a=Number.isFinite(o)?o:Number.NEGATIVE_INFINITY;(n===void 0||a>r)&&(n=i,r=a)}return n}function Ki(e){return $i({sessions:e.sessions,selectedSessionKey:e.selectedSessionKey,sessionType:e.sessionType,readPreference:t=>{var r;return((r=t.preferredModel)==null?void 0:r.trim())||void 0}})}function Ui(e){return $i({sessions:e.sessions,selectedSessionKey:e.selectedSessionKey,sessionType:e.sessionType,readPreference:t=>t.preferredThinking??void 0})}function Vi(e){const{isPreferenceAvailable:t,emptyValue:n,selectedSessionKey:r,selectedSessionExists:s=!1,setValue:i,resolveValue:o}=e,a=k.useRef(void 0),l=k.useRef(o);k.useEffect(()=>{l.current=o},[o]),k.useEffect(()=>{const u=a.current!==r;if(!t){i(n),a.current=r;return}i(c=>l.current({currentValue:c,sessionChanged:u,preserveCurrentValueOnSessionChange:u&&!!r&&!s})),a.current=r},[n,t,s,r,i])}function Hi(e){const{modelOptions:t,selectedSessionKey:n,selectedSessionExists:r=!1,selectedSessionPreferredModel:s,fallbackPreferredModel:i,defaultModel:o,setSelectedModel:a}=e;Vi({isPreferenceAvailable:t.length>0,emptyValue:"",selectedSessionKey:n,selectedSessionExists:r,setValue:a,resolveValue:({currentValue:l,sessionChanged:u,preserveCurrentValueOnSessionChange:c})=>Au({currentSelectedModel:l,modelOptions:t,selectedSessionPreferredModel:s,fallbackPreferredModel:i,defaultModel:o,preferSessionPreferredModel:u,preserveCurrentSelectedModelOnSessionChange:c})})}function qi(e){const{supportedThinkingLevels:t,selectedSessionKey:n,selectedSessionExists:r=!1,selectedSessionPreferredThinking:s,fallbackPreferredThinking:i,defaultThinkingLevel:o,setSelectedThinkingLevel:a}=e;Vi({isPreferenceAvailable:t.length>0,emptyValue:null,selectedSessionKey:n,selectedSessionExists:r,setValue:a,resolveValue:({currentValue:l,sessionChanged:u,preserveCurrentValueOnSessionChange:c})=>Lu({currentSelectedThinkingLevel:l,supportedThinkingLevels:t,selectedSessionPreferredThinking:s,fallbackPreferredThinking:i,defaultThinkingLevel:o,preferSessionPreferredThinking:u,preserveCurrentSelectedThinkingOnSessionChange:c})})}function Nu(e){var A,P,T,F,B,z;const t=Ri(),n=Ei(),r=jl({q:e.query.trim()||void 0,limit:120,activeMinutes:0}),s=Ni("skill"),i=Dl({sessionKey:e.selectedSessionKey,agentId:e.selectedAgentId}),o=_l(e.selectedSessionKey,300),a=Ol(),l=(t.isFetched||t.isSuccess)&&(n.isFetched||n.isSuccess),u=k.useMemo(()=>{const w=ji({meta:n.data,config:t.data,onlyConfigured:!0}),D=new Set,N=[];for(const $ of w)for(const O of $.models){const R=Di($.prefix,O);!R||D.has(R)||(D.add(R),N.push({value:R,modelLabel:O,providerLabel:$.displayName,thinkingCapability:_i($.modelThinking,O,$.aliases)}))}return N.sort(($,O)=>{const R=$.providerLabel.localeCompare(O.providerLabel);return R!==0?R:$.modelLabel.localeCompare(O.modelLabel)})},[n.data,t.data]),c=k.useMemo(()=>{var w;return((w=r.data)==null?void 0:w.sessions)??[]},[(A=r.data)==null?void 0:A.sessions]),d=k.useMemo(()=>{var w;return((w=s.data)==null?void 0:w.records)??[]},[(P=s.data)==null?void 0:P.records]),p=k.useMemo(()=>c.find(w=>w.key===e.selectedSessionKey)??null,[e.selectedSessionKey,c]),f=zi({selectedSession:p,selectedSessionKey:e.selectedSessionKey,pendingSessionType:e.pendingSessionType,setPendingSessionType:e.setPendingSessionType,sessionTypesData:a.data}),m=k.useMemo(()=>Ki({sessions:c,selectedSessionKey:e.selectedSessionKey,sessionType:f.selectedSessionType}),[e.selectedSessionKey,f.selectedSessionType,c]),y=k.useMemo(()=>u.find(w=>w.value===e.currentSelectedModel),[u,e.currentSelectedModel]),b=k.useMemo(()=>{var w;return((w=y==null?void 0:y.thinkingCapability)==null?void 0:w.supported)??[]},[(T=y==null?void 0:y.thinkingCapability)==null?void 0:T.supported]),g=k.useMemo(()=>{var w;return((w=y==null?void 0:y.thinkingCapability)==null?void 0:w.default)??null},[(F=y==null?void 0:y.thinkingCapability)==null?void 0:F.default]),v=k.useMemo(()=>Ui({sessions:c,selectedSessionKey:e.selectedSessionKey,sessionType:f.selectedSessionType}),[e.selectedSessionKey,f.selectedSessionType,c]);Hi({modelOptions:u,selectedSessionKey:e.selectedSessionKey,selectedSessionExists:!!p,selectedSessionPreferredModel:p==null?void 0:p.preferredModel,fallbackPreferredModel:m,defaultModel:(B=t.data)==null?void 0:B.agents.defaults.model,setSelectedModel:e.setSelectedModel}),qi({supportedThinkingLevels:b,selectedSessionKey:e.selectedSessionKey,selectedSessionExists:!!p,selectedSessionPreferredThinking:(p==null?void 0:p.preferredThinking)??null,fallbackPreferredThinking:v??null,defaultThinkingLevel:g,setSelectedThinkingLevel:e.setSelectedThinkingLevel});const C=k.useMemo(()=>{var w;return((w=o.data)==null?void 0:w.messages)??[]},[(z=o.data)==null?void 0:z.messages]);return{configQuery:t,configMetaQuery:n,sessionsQuery:r,installedSkillsQuery:s,chatCapabilitiesQuery:i,historyQuery:o,sessionTypesQuery:a,isProviderStateResolved:l,modelOptions:u,sessions:c,skillRecords:d,selectedSession:p,historyMessages:C,...f}}function Wi(e){if(e.label&&e.label.trim())return e.label.trim();const t=e.key.split(":");return t[t.length-1]||e.key}const Pu={connected:{dotClass:"bg-emerald-500"},disconnected:{dotClass:"h-2.5 w-2.5 rounded-full border border-gray-400 bg-transparent"},connecting:{dotClass:"text-amber-600"}};function ju({status:e,className:t}){const n=Pu[e],r=e==="connected"?I("connected"):e==="disconnected"?I("disconnected"):I("connecting");return h.jsx(ou,{delayDuration:250,children:h.jsxs(au,{children:[h.jsx(lu,{asChild:!0,children:h.jsx("span",{role:"status","aria-label":r,className:xe("inline-flex h-5 w-5 items-center justify-center",t),children:e==="connecting"?h.jsx(Ga,{className:xe("h-3 w-3 animate-spin",n.dotClass)}):h.jsx("span",{className:xe(e==="connected"?"h-2 w-2 rounded-full":"",n.dotClass)})})}),h.jsx(uu,{side:"bottom",className:"text-xs",children:r})]})})}function Du(e){const{session:t,active:n,runStatus:r,sessionTypeLabel:s,title:i,isEditing:o,draftLabel:a,isSaving:l,onSelect:u,onStartEditing:c,onDraftLabelChange:d,onSave:p,onCancel:f}=e;return h.jsx("div",{className:xe("w-full rounded-xl px-3 py-2 text-left transition-all text-[13px]",n?"bg-gray-200 text-gray-900 font-semibold shadow-sm":"text-gray-700 hover:bg-gray-200/60 hover:text-gray-900"),children:o?h.jsxs("div",{className:"space-y-2",children:[h.jsx(hr,{value:a,onChange:m=>d(m.target.value),onKeyDown:m=>{m.key==="Enter"?(m.preventDefault(),p()):m.key==="Escape"&&(m.preventDefault(),f())},placeholder:I("sessionsLabelPlaceholder"),className:"h-8 rounded-lg border-gray-300 bg-white text-xs",autoFocus:!0,disabled:l}),h.jsxs("div",{className:"flex items-center justify-between gap-2",children:[h.jsx("div",{className:"min-w-0 text-[11px] text-gray-400 truncate",children:t.key}),h.jsxs("div",{className:"flex items-center gap-1",children:[h.jsx(He,{type:"button",size:"icon",variant:"ghost",className:"h-7 w-7 rounded-lg text-gray-500 hover:bg-white hover:text-gray-900",onClick:()=>void p(),disabled:l,"aria-label":I("save"),children:h.jsx(Xt,{className:"h-3.5 w-3.5"})}),h.jsx(He,{type:"button",size:"icon",variant:"ghost",className:"h-7 w-7 rounded-lg text-gray-500 hover:bg-white hover:text-gray-900",onClick:f,disabled:l,"aria-label":I("cancel"),children:h.jsx(Qa,{className:"h-3.5 w-3.5"})})]})]})]}):h.jsxs("div",{className:"group/session relative",children:[h.jsxs("button",{type:"button",onClick:u,className:"w-full text-left",children:[h.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_0.875rem] items-center gap-1.5 pr-8",children:[h.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[h.jsx("span",{className:"truncate font-medium",children:i}),s?h.jsx("span",{className:xe("shrink-0 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none",n?"border-gray-300 bg-white/80 text-gray-700":"border-gray-200 bg-gray-100 text-gray-500"),children:s}):null]}),h.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:r?h.jsx(su,{status:r}):null})]}),h.jsx("div",{className:"mt-0.5 text-[11px] text-gray-400 truncate",children:t.key}),h.jsxs("div",{className:"mt-0.5 text-[11px] text-gray-400 truncate",children:[t.messageCount," · ",Zt(t.updatedAt)]})]}),h.jsx("button",{type:"button",onClick:m=>{m.stopPropagation(),c()},className:xe("absolute right-0 top-0 inline-flex h-7 w-7 items-center justify-center rounded-lg text-gray-400 transition-all hover:bg-white hover:text-gray-900",n?"opacity-100":"opacity-0 group-hover/session:opacity-100 group-focus-within/session:opacity-100"),"aria-label":I("edit"),children:h.jsx(Xa,{className:"h-3.5 w-3.5"})})]})})}function _u(){const e=Ya();return async t=>{try{t.chatChain==="ncp"?(await Ai(t.sessionKey,{label:t.label}),e.invalidateQueries({queryKey:["ncp-sessions"]}),e.invalidateQueries({queryKey:["ncp-session-messages",t.sessionKey]})):(await On(t.sessionKey,{label:t.label}),e.invalidateQueries({queryKey:["sessions"]}),e.invalidateQueries({queryKey:["session-history",t.sessionKey]})),Br.success(I("configSavedApplied"))}catch(n){throw Br.error(I("configSaveFailed")+": "+(n instanceof Error?n.message:String(n))),n}}}const Gi=k.createContext(null);function Qi({presenter:e,children:t}){return h.jsx(Gi.Provider,{value:e,children:t})}function pr(){const e=k.useContext(Gi);if(!e)throw new Error("usePresenter must be used inside ChatPresenterProvider");return e}const Ou=e=>`[data-item-index="${e}"]`;function Xi(e){const t=e.getItemSelector??Ou;k.useEffect(()=>{if(!e.isEnabled||e.itemCount===0)return;const n=e.containerRef.current;if(!n)return;const r=n.querySelector(t(e.activeIndex));r==null||r.scrollIntoView({block:"nearest",inline:"nearest"})},[t,e.activeIndex,e.containerRef,e.isEnabled,e.itemCount])}function Fu(){const e=k.useRef(null),[t,n]=k.useState(null);return k.useEffect(()=>{const r=e.current;if(!r||typeof ResizeObserver>"u")return;const s=()=>{n(r.getBoundingClientRect().width)};s();const i=new ResizeObserver(()=>s());return i.observe(r),()=>i.disconnect()},[]),{elementRef:e,width:t}}function de(...e){return Ja(Za(e))}const Yi=k.forwardRef(({className:e,type:t,...n},r)=>h.jsx("input",{type:t,className:de("flex h-9 w-full rounded-xl border border-gray-200/80 bg-white px-3.5 py-2 text-sm text-gray-900 file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-300 placeholder:font-normal focus:outline-none focus:ring-1 focus:ring-primary/40 focus:border-primary/40 transition-colors disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,...n}));Yi.displayName="ChatInput";const zu=gu,Bu=xu,$u=mu,Ji=k.forwardRef(({className:e,sideOffset:t=8,align:n="start",...r},s)=>h.jsx(yu,{children:h.jsx(Oi,{ref:s,sideOffset:t,align:n,className:de("z-[var(--z-popover,50)] w-72 overflow-hidden rounded-2xl border border-gray-200/50 bg-white p-4 shadow-lg animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));Ji.displayName=Oi.displayName;const Ku=el,Uu=tl,Zi=k.forwardRef(({className:e,children:t,...n},r)=>h.jsxs(yi,{ref:r,className:de("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-xl border border-gray-200/80 bg-white px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/40 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,h.jsx(nl,{asChild:!0,children:h.jsx(ar,{className:"h-4 w-4 opacity-50"})})]}));Zi.displayName=yi.displayName;const eo=k.forwardRef(({className:e,...t},n)=>h.jsx(Si,{ref:n,className:de("flex cursor-default items-center justify-center py-1",e),...t,children:h.jsx(al,{className:"h-4 w-4"})}));eo.displayName=Si.displayName;const to=k.forwardRef(({className:e,...t},n)=>h.jsx(ki,{ref:n,className:de("flex cursor-default items-center justify-center py-1",e),...t,children:h.jsx(ar,{className:"h-4 w-4"})}));to.displayName=ki.displayName;const no=k.forwardRef(({className:e,children:t,position:n="popper",...r},s)=>h.jsx(rl,{children:h.jsxs(xi,{ref:s,className:de("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md bg-white text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[h.jsx(eo,{}),h.jsx(sl,{className:de("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),h.jsx(to,{})]})}));no.displayName=xi.displayName;const ro=k.forwardRef(({className:e,children:t,...n},r)=>h.jsxs(bi,{ref:r,className:de("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-gray-100 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 hover:bg-gray-100",e),...n,children:[h.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:h.jsx(il,{children:h.jsx(Xt,{className:"h-4 w-4"})})}),h.jsx(ol,{children:t})]}));ro.displayName=bi.displayName;const Vu=cu,Hu=du,qu=hu,so=k.forwardRef(({className:e,sideOffset:t=4,...n},r)=>h.jsx(fu,{children:h.jsx(Pi,{ref:r,sideOffset:t,className:de("z-[var(--z-tooltip)] overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})}));so.displayName=Pi.displayName;const Rt={Popover:zu,PopoverAnchor:$u,PopoverContent:Ji,PopoverTrigger:Bu,Input:Yi,Select:Ku,SelectContent:no,SelectItem:ro,SelectTrigger:Zi,SelectValue:Uu,Tooltip:Hu,TooltipContent:so,TooltipProvider:Vu,TooltipTrigger:qu},Wu=680,Gu=.82,Qu=560;function Xu(e){const{Popover:t,PopoverAnchor:n,PopoverContent:r}=Rt,{elementRef:s,width:i}=Fu(),o=k.useRef(null),{isOpen:a,isLoading:l,items:u,activeIndex:c,activeItem:d,texts:p,onSelectItem:f,onOpenChange:m,onSetActiveIndex:y}=e,b=k.useMemo(()=>{if(i)return Math.min(i>Qu?i*Gu:i,Wu)},[i]);return Xi({containerRef:o,activeIndex:c,itemCount:u.length,isEnabled:a&&!l,getItemSelector:g=>`[data-slash-index="${g}"]`}),h.jsxs(t,{open:a,onOpenChange:m,children:[h.jsx(n,{asChild:!0,children:h.jsx("div",{ref:s,className:"pointer-events-none absolute bottom-full left-3 right-3 h-0"})}),h.jsx(r,{side:"top",align:"start",sideOffset:10,className:"z-[70] max-w-[calc(100vw-1.5rem)] overflow-hidden rounded-2xl border border-gray-200 bg-white/95 p-0 shadow-2xl backdrop-blur-md",onOpenAutoFocus:g=>g.preventDefault(),style:b?{width:`${b}px`}:void 0,children:h.jsxs("div",{className:"grid min-h-[240px] grid-cols-[minmax(220px,300px)_minmax(0,1fr)]",children:[h.jsx("div",{ref:o,role:"listbox","aria-label":p.slashSectionLabel,className:"custom-scrollbar max-h-[320px] overflow-y-auto border-r border-gray-200 p-2.5",children:l?h.jsx("div",{className:"p-2 text-xs text-gray-500",children:p.slashLoadingLabel}):h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"mb-2 px-2 text-[11px] font-semibold uppercase tracking-wide text-gray-500",children:p.slashSectionLabel}),u.length===0?h.jsx("div",{className:"px-2 text-xs text-gray-400",children:p.slashEmptyLabel}):h.jsx("div",{className:"space-y-1",children:u.map((g,v)=>{const C=v===c;return h.jsxs("button",{type:"button",role:"option","aria-selected":C,"data-slash-index":v,onMouseEnter:()=>y(v),onClick:()=>f(g),className:`flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left transition ${C?"bg-gray-100 text-gray-900":"text-gray-700 hover:bg-gray-50"}`,children:[h.jsx("span",{className:"truncate text-xs font-semibold",children:g.title}),h.jsx("span",{className:"truncate text-xs text-gray-500",children:g.subtitle})]},g.key)})})]})}),h.jsx("div",{className:"max-w-[320px] p-3.5",children:d?h.jsxs("div",{className:"space-y-3",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"inline-flex rounded-full bg-primary/10 px-2 py-0.5 text-[11px] font-semibold text-primary",children:d.subtitle}),h.jsx("span",{className:"text-sm font-semibold text-gray-900",children:d.title})]}),h.jsx("p",{className:"text-xs leading-5 text-gray-600",children:d.description}),h.jsx("div",{className:"space-y-1",children:d.detailLines.map(g=>h.jsx("div",{className:"rounded-md bg-gray-50 px-2 py-1 text-[11px] text-gray-600",children:g},g))}),h.jsx("div",{className:"pt-1 text-[11px] text-gray-500",children:p.slashSkillHintLabel})]}):h.jsx("div",{className:"text-xs text-gray-500",children:p.slashHintLabel})})]})})]})}const Yu=ll("inline-flex items-center justify-center whitespace-nowrap rounded-full text-sm font-medium ring-offset-background transition-all duration-fast focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary-600 active:bg-primary-700 shadow-sm",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-gray-200 bg-white hover:bg-gray-50 hover:text-gray-800 text-gray-600",secondary:"bg-gray-100 text-gray-700 hover:bg-gray-200/80",ghost:"hover:bg-gray-100/80 hover:text-gray-800",link:"text-primary underline-offset-4 hover:underline",primary:"bg-primary text-primary-foreground hover:bg-primary-600 active:bg-primary-700 shadow-sm",subtle:"bg-gray-100 text-gray-600 hover:bg-gray-200/80","primary-outline":"border border-primary/30 text-primary hover:bg-primary hover:text-primary-foreground"},size:{default:"h-9 px-4 py-2",sm:"h-8 px-3 text-xs",lg:"h-11 px-5 text-[14px]",xl:"h-12 px-6 text-[15px]",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),$t=k.forwardRef(({className:e,variant:t,size:n,...r},s)=>h.jsx("button",{className:de(Yu({variant:t,size:n,className:e})),ref:s,...r}));$t.displayName="ChatButton";function Gr(){return h.jsx("span",{"aria-hidden":"true","data-testid":"chat-stop-icon",className:"block h-3 w-3 rounded-[2px] bg-gray-700 shadow-[inset_0_0_0_1px_rgba(17,24,39,0.06)]"})}function Ju(e){var i;const{Tooltip:t,TooltipContent:n,TooltipProvider:r,TooltipTrigger:s}=Rt;return h.jsxs("div",{className:"flex flex-col items-end gap-1",children:[(i=e.sendError)!=null&&i.trim()?h.jsx("div",{className:"max-w-[420px] text-right text-[11px] text-red-600",children:e.sendError}):null,h.jsx("div",{className:"flex items-center gap-2",children:e.isSending?e.canStopGeneration?h.jsx($t,{size:"icon",variant:"outline",className:"h-8 w-8 rounded-full","aria-label":e.stopButtonLabel,onClick:()=>void e.onStop(),disabled:e.stopDisabled,children:h.jsx(Gr,{})}):h.jsx(r,{children:h.jsxs(t,{children:[h.jsx(s,{asChild:!0,children:h.jsx("span",{children:h.jsx($t,{size:"icon",variant:"outline",className:"h-8 w-8 rounded-full","aria-label":e.stopButtonLabel,disabled:!0,children:h.jsx(Gr,{})})})}),h.jsx(n,{side:"top",children:h.jsx("p",{className:"text-xs",children:e.stopHint})})]})}):h.jsx($t,{size:"icon",className:"h-8 w-8 rounded-full","aria-label":e.sendButtonLabel,onClick:()=>void e.onSend(),disabled:e.sendDisabled,children:h.jsx(ul,{className:"h-5 w-5"})})})]})}function Zu(e,t){const n=t.trim().toLowerCase();return n?e.filter(r=>[r.label,r.key,r.description].filter(i=>typeof i=="string"&&i.trim().length>0).join(" ").toLowerCase().includes(n)):e}function ec(e){const{Input:t,Popover:n,PopoverContent:r,PopoverTrigger:s}=Rt,{picker:i}=e,o=k.useRef(null),a=k.useId(),[l,u]=k.useState(""),[c,d]=k.useState(0),p=k.useMemo(()=>new Set(i.selectedKeys),[i.selectedKeys]),f=i.selectedKeys.length,m=k.useMemo(()=>Zu(i.options,l),[i.options,l]);k.useEffect(()=>{d(0)},[l]),k.useEffect(()=>{d(g=>m.length===0?0:Math.min(g,m.length-1))},[m.length]),Xi({containerRef:o,activeIndex:c,itemCount:m.length,isEnabled:m.length>0,getItemSelector:g=>`[data-skill-index="${g}"]`});const y=g=>{if(p.has(g)){i.onSelectedKeysChange(i.selectedKeys.filter(v=>v!==g));return}i.onSelectedKeysChange([...i.selectedKeys,g])},b=g=>{if(m.length!==0){if(g.key==="ArrowDown"){g.preventDefault(),d(v=>Math.min(v+1,m.length-1));return}if(g.key==="ArrowUp"){g.preventDefault(),d(v=>Math.max(v-1,0));return}if(g.key==="Enter"){g.preventDefault();const v=m[c];v&&y(v.key)}}};return h.jsxs(n,{children:[h.jsx(s,{asChild:!0,children:h.jsxs("button",{type:"button","aria-haspopup":"listbox",className:"inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium text-gray-600 transition-colors hover:bg-gray-100 hover:text-gray-900",children:[h.jsx(lr,{className:"h-4 w-4"}),h.jsx("span",{children:i.title}),f>0?h.jsx("span",{className:"ml-0.5 flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-primary/10 text-[10px] font-semibold text-primary",children:f}):null]})}),h.jsxs(r,{side:"top",align:"start",className:"w-[360px] p-0",children:[h.jsxs("div",{className:"space-y-2 border-b border-gray-100 px-4 py-3",children:[h.jsx("div",{className:"text-sm font-semibold text-gray-900",children:i.title}),h.jsxs("div",{className:"relative",children:[h.jsx(ur,{className:"pointer-events-none absolute left-3 top-2.5 h-3.5 w-3.5 text-gray-400"}),h.jsx(t,{value:l,onChange:g=>u(g.target.value),onKeyDown:b,placeholder:i.searchPlaceholder,role:"combobox","aria-controls":a,"aria-expanded":"true","aria-autocomplete":"list","aria-activedescendant":m[c]?`${a}-option-${c}`:void 0,className:"h-8 rounded-lg pl-8 text-xs"})]})]}),h.jsx("div",{ref:o,id:a,role:"listbox","aria-multiselectable":"true",className:"custom-scrollbar max-h-[320px] overflow-y-auto",children:i.isLoading?h.jsx("div",{className:"p-4 text-xs text-gray-500",children:i.loadingLabel}):m.length===0?h.jsx("div",{className:"p-4 text-center text-xs text-gray-500",children:i.emptyLabel}):h.jsx("div",{className:"py-1",children:m.map((g,v)=>{const C=p.has(g.key),A=v===c;return h.jsxs("button",{type:"button",id:`${a}-option-${v}`,role:"option","aria-selected":C,"data-skill-index":v,onClick:()=>y(g.key),onMouseEnter:()=>d(v),className:`flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors ${A?"bg-gray-50":"hover:bg-gray-50"}`,children:[h.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-gray-100 text-gray-500",children:h.jsx(cl,{className:"h-4 w-4"})}),h.jsxs("div",{className:"min-w-0 flex-1",children:[h.jsxs("div",{className:"flex items-center gap-1.5",children:[h.jsx("span",{className:"truncate text-sm text-gray-900",children:g.label}),g.badgeLabel?h.jsx("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary",children:g.badgeLabel}):null]}),h.jsx("div",{className:"mt-0.5 truncate text-xs text-gray-500",children:g.description||g.key})]}),h.jsx("div",{className:"ml-3 shrink-0",children:h.jsx("span",{className:C?"inline-flex h-5 w-5 items-center justify-center rounded-full bg-primary text-white":"inline-flex h-5 w-5 items-center justify-center rounded-full border border-gray-300 bg-white",children:C?h.jsx(Xt,{className:"h-3 w-3"}):null})})]},g.key)})})}),i.manageHref&&i.manageLabel?h.jsx("div",{className:"border-t border-gray-100 px-4 py-2.5",children:h.jsxs("a",{href:i.manageHref,className:"inline-flex items-center gap-1.5 text-xs font-medium text-primary transition-colors hover:text-primary/80",children:[i.manageLabel,h.jsx(dl,{className:"h-3 w-3"})]})}):null]})]})}function io({icon:e}){return e==="sparkles"?h.jsx(fl,{className:"h-3.5 w-3.5 shrink-0 text-primary"}):e==="brain"?h.jsx(pl,{className:"h-3.5 w-3.5 shrink-0 text-gray-500"}):null}function tc({icon:e}){return e==="paperclip"?h.jsx(hl,{className:"h-4 w-4"}):h.jsx(io,{icon:e})}function nc(e){return e==="model"?"min-w-[220px]":e==="session-type"?"min-w-[140px]":e==="thinking"?"min-w-[150px]":""}function rc(e){return e==="model"?"w-[320px]":e==="session-type"?"w-[220px]":e==="thinking"?"w-[180px]":""}function sc({item:e}){const{Select:t,SelectContent:n,SelectItem:r,SelectTrigger:s,SelectValue:i}=Rt;return h.jsxs(t,{value:e.value,onValueChange:e.onValueChange,disabled:e.disabled,children:[h.jsx(s,{className:`h-8 w-auto rounded-lg border-0 bg-transparent px-3 text-xs font-medium text-gray-600 shadow-none hover:bg-gray-100 focus:ring-0 ${nc(e.key)}`,children:e.selectedLabel?h.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-left",children:[h.jsx(io,{icon:e.icon}),h.jsx("span",{className:"truncate text-xs font-semibold text-gray-700",children:e.selectedLabel})]}):e.loading?h.jsx("div",{className:"h-3 w-24 animate-pulse rounded bg-gray-200"}):h.jsx(i,{placeholder:e.placeholder})}),h.jsxs(n,{className:rc(e.key),children:[e.options.length===0?e.loading?h.jsxs("div",{className:"space-y-2 px-3 py-2",children:[h.jsx("div",{className:"h-3 w-36 animate-pulse rounded bg-gray-200"}),h.jsx("div",{className:"h-3 w-28 animate-pulse rounded bg-gray-200"}),h.jsx("div",{className:"h-3 w-32 animate-pulse rounded bg-gray-200"})]}):e.emptyLabel?h.jsx("div",{className:"px-3 py-2 text-xs text-gray-500",children:e.emptyLabel}):null:null,e.options.map(o=>h.jsx(r,{value:o.value,className:"py-2",children:o.description?h.jsxs("div",{className:"flex min-w-0 flex-col gap-0.5",children:[h.jsx("span",{className:"truncate text-xs font-semibold text-gray-800",children:o.label}),h.jsx("span",{className:"truncate text-[11px] text-gray-500",children:o.description})]}):h.jsx("span",{className:"truncate text-xs font-semibold text-gray-800",children:o.label})},o.value))]})]})}function ic(e){var i;const{Tooltip:t,TooltipContent:n,TooltipProvider:r,TooltipTrigger:s}=Rt;return h.jsxs("div",{className:"flex items-center justify-between px-3 pb-3",children:[h.jsxs("div",{className:"flex items-center gap-1",children:[e.skillPicker?h.jsx(ec,{picker:e.skillPicker}):null,e.selects.map(o=>h.jsx(sc,{item:o},o.key)),(i=e.accessories)==null?void 0:i.map(o=>{const a=h.jsxs("button",{type:"button",className:`inline-flex items-center rounded-lg py-1.5 text-xs font-medium text-gray-600 transition-colors hover:bg-gray-100 hover:text-gray-900 disabled:cursor-not-allowed disabled:text-gray-400 ${o.iconOnly?"h-8 w-8 justify-center px-0":"gap-1.5 px-3"}`,onClick:o.onClick,disabled:o.disabled,"aria-label":o.label,children:[h.jsx(tc,{icon:o.icon}),o.iconOnly?null:h.jsx("span",{children:o.label})]});if(!o.tooltip)return h.jsx("div",{children:a},o.key);const l=o.disabled?h.jsx("span",{className:"inline-flex",children:a}):a;return h.jsx(r,{children:h.jsxs(t,{children:[h.jsx(s,{asChild:!0,children:l}),h.jsx(n,{side:"top",children:h.jsx("p",{className:"text-xs",children:o.tooltip})})]})},o.key)})]}),h.jsx(Ju,{...e.actions})]})}const oc="";function oo(){return`composer-${Math.random().toString(36).slice(2,10)}`}function Ct(e=""){return{id:oo(),type:"text",text:e}}function gr(e){return{id:oo(),type:"token",tokenKind:e.tokenKind,tokenKey:e.tokenKey,label:e.label}}function Et(e){return e.type==="text"?e.text.length:1}function mr(){return[Ct("")]}function ac(e){return[Ct(e)]}function ut(e){const t=[];for(const n of e){if(n.type==="text"){if(n.text.length===0)continue;const r=t[t.length-1];if((r==null?void 0:r.type)==="text"){t[t.length-1]={...r,text:r.text+n.text};continue}}t.push(n)}return t.length===0?mr():t}function lc(e){return e.map(t=>t.type==="text"?t.text:oc).join("")}function uc(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}function yr(e,t){const n=[],r=new Set;for(const s of e)s.type!=="token"||s.tokenKind!==t||r.has(s.tokenKey)||(r.add(s.tokenKey),n.push(s.tokenKey));return n}function cc(e,t,n,r){const s=Math.max(0,n-t),i=Math.max(0,t+e.text.length-r),o=[];return s>0&&o.push({...e,text:e.text.slice(0,s)}),i>0&&o.push({...e,text:e.text.slice(e.text.length-i)}),o}function dc(e,t,n,r){return t<=n||e>=r}function hc(e,t,n,r,s){return!n&&r>=s?(e.push(...t),!0):n}function fc(e,t,n,r,s,i,o){const a=cc(t,n,r,s);a[0]&&e.push(a[0]);let l=o;return l||(e.push(...i),l=!0),a[1]&&e.push(a[1]),l}function pc(e,t,n,r,s,i){return!r&&s<=i?(e.push(...n),!0):(e.push(t),r)}function un(e,t,n,r){const s=Math.max(0,t),i=Math.max(s,n),o=[];let a=0,l=!1;for(const u of e){const c=Et(u),d=a,p=a+c;if(dc(d,p,s,i)){l=hc(o,r,l,d,i),o.push(u),a=p;continue}u.type==="text"?l=fc(o,u,d,s,i,r,l):l=pc(o,u,r,l,s,d),a=p}return l||o.push(...r),ut(o)}function ao(e,t){return ut(e.filter(n=>n.type!=="token"||!t(n)))}function gc(e,t){if(!t||t.start!==t.end)return null;const n=lc(e),r=t.end,s=n.slice(0,r),i=/(?:^|\s)\/([^\s\uFFFC]*)$/.exec(s);if(!i)return null;const o=r-i[0].length+(i[0].startsWith("/")?0:1);return{query:(i[1]??"").trim().toLowerCase(),start:o,end:r}}function mc(e,t,n){return e?e.start<n&&e.end>t:!1}function lo(e){const t=new Map;let n=0;for(const r of e)t.set(r.id,n),n+=Et(r);return t}function uo(e,t){let n=t;for(;n&&n.parentNode!==e;)n=n.parentNode;return n?Array.prototype.indexOf.call(e.childNodes,n):e.childNodes.length}function yc(e,t,n){if(e instanceof HTMLElement){const r=e.dataset.composerNodeId;if(r)return n.find(s=>s.id===r)}return n[t]}function co(e,t,n){let r=0;for(let s=0;s<n;s+=1){const i=yc(e.childNodes[s],s,t);i&&(r+=Et(i))}return r}function xc(e,t,n,r){var a;const s=uo(e,t),i=co(e,r,s),o=r[s];return(o==null?void 0:o.type)==="text"?i+Math.min(n,o.text.length):i+Math.min(n,((a=t.textContent)==null?void 0:a.length)??0)}function bc(e,t,n,r,s){return n.type==="text"?e.nodeType===Node.TEXT_NODE?r+Math.min(t,n.text.length):e===s?r+(t>0?n.text.length:0):r+n.text.length:e===s?r+(t>0?1:0):r+1}function $n(e,t,n,r,s){var u;if(t===e)return co(e,r,n);if(t.nodeType===Node.TEXT_NODE&&t.parentNode===e)return xc(e,t,n,r);const i=t instanceof HTMLElement?t.closest("[data-composer-node-id]"):((u=t.parentElement)==null?void 0:u.closest("[data-composer-node-id]"))??null;if(!(i instanceof HTMLElement)){const c=uo(e,t);return $n(e,e,c,r,s)}const o=i.dataset.composerNodeId;if(!o)return 0;const a=r.find(c=>c.id===o),l=s.get(o)??0;return a?bc(t,n,a,l,i):l}function ho(e,t){const n=window.getSelection();if(!n||n.rangeCount===0)return null;const r=n.getRangeAt(0);if(!e.contains(r.startContainer)||!e.contains(r.endContainer))return null;const s=lo(t),i=$n(e,r.startContainer,r.startOffset,t,s),o=$n(e,r.endContainer,r.endOffset,t,s);return{start:Math.min(i,o),end:Math.max(i,o)}}function Sc(e,t,n){if(!n)return;const r=window.getSelection();if(!r)return;const s=l=>{let u=0;for(let c=0;c<t.length;c+=1){const d=t[c],p=Et(d),f=u,m=u+p,y=e.childNodes[c];if(!y){u=m;continue}if(d.type==="text"){if(l<=m)return{container:y.firstChild??y,offset:Math.max(0,Math.min(l-f,d.text.length))}}else{if(l<=f)return{container:e,offset:c};if(l<=m)return{container:e,offset:c+1}}u=m}return{container:e,offset:e.childNodes.length}},i=s(n.start),o=s(n.end),a=document.createRange();a.setStart(i.container,i.offset),a.setEnd(o.container,o.offset),r.removeAllRanges(),r.addRange(a)}function kc(e){const t=[];for(const n of Array.from(e.childNodes)){if(n.nodeType===Node.TEXT_NODE){t.push(Ct(n.textContent??""));continue}if(!(n instanceof HTMLElement))continue;if(n.dataset.composerNodeType==="token"){const i=n.dataset.composerTokenKind,o=n.dataset.composerTokenKey,a=n.dataset.composerLabel;i&&o&&a&&t.push({id:n.dataset.composerNodeId??gr({tokenKind:i,tokenKey:o,label:a}).id,type:"token",tokenKind:i,tokenKey:o,label:a});continue}const s=n.textContent??"";t.push({id:n.dataset.composerNodeId??Ct(s).id,type:"text",text:s})}return ut(t)}function Qr(e){const t=kc(e);return{nodes:t,selection:ho(e,t)}}class vc{constructor(){this.nodes=mr(),this.selection=null,this.sync=(t,n)=>(this.nodes=ut(t),this.selection=n,this.getSnapshot()),this.setSelection=t=>(this.selection=t,this.getSnapshot()),this.replaceDocument=(t,n)=>(this.nodes=ut(t),this.selection=n,this.getSnapshot()),this.insertText=t=>{const n=this.selection??{start:0,end:0};this.nodes=un(this.nodes,n.start,n.end,[Ct(t)]);const r=n.start+t.length;return this.selection={start:r,end:r},this.getSnapshot()},this.insertSkillToken=(t,n)=>{var a,l;if(this.getSelectedSkillKeys().includes(t))return this.getSnapshot();const r=this.getSlashTrigger(),s=this.getDocumentLength(),i=(r==null?void 0:r.start)??((a=this.selection)==null?void 0:a.start)??s,o=(r==null?void 0:r.end)??((l=this.selection)==null?void 0:l.end)??i;return this.nodes=un(this.nodes,i,o,[gr({tokenKind:"skill",tokenKey:t,label:n})]),this.selection={start:i+1,end:i+1},this.getSnapshot()},this.syncSelectedSkills=(t,n)=>{const r=this.getSelectedSkillKeys(),s=new Map(n.map(a=>[a.key,a])),i=t.find(a=>!r.includes(a));if(i){const a=s.get(i);return this.insertSkillToken(i,(a==null?void 0:a.label)??i)}const o=r.find(a=>!t.includes(a));return o&&(this.nodes=ao(this.nodes,a=>a.tokenKind==="skill"&&a.tokenKey===o)),this.getSnapshot()},this.deleteContent=t=>{const n=this.getDocumentLength(),r=this.selection??{start:n,end:n};let s=r.start,i=r.end;if(r.start===r.end)if(t==="backward"&&r.start>0)s=r.start-1;else if(t==="forward")i=r.end+1;else return this.getSnapshot();return this.nodes=un(this.nodes,s,i,[]),this.selection={start:s,end:s},this.getSnapshot()},this.getSnapshot=()=>({nodes:this.nodes,selection:this.selection,nodeStartMap:lo(this.nodes),documentLength:this.getDocumentLength(),selectedSkillKeys:this.getSelectedSkillKeys(),slashTrigger:this.getSlashTrigger()}),this.getDocumentLength=()=>this.nodes.reduce((t,n)=>t+Et(n),0),this.getSelectedSkillKeys=()=>yr(this.nodes,"skill"),this.getSlashTrigger=()=>gc(this.nodes,this.selection)}}function wc(e){const{key:t,shiftKey:n,isComposing:r,isSlashMenuOpen:s,slashItemCount:i,activeSlashIndex:o,isSending:a,canStopGeneration:l}=e;if(s&&i>0){if(t==="ArrowDown")return{type:"move-slash-index",index:(o+1)%i};if(t==="ArrowUp")return{type:"move-slash-index",index:(o-1+i)%i};if(t==="Enter"&&!n||t==="Tab")return{type:"insert-active-slash-item"}}return t==="Escape"?s?{type:"close-slash"}:a&&l?{type:"stop-generation"}:{type:"noop"}:t==="Enter"&&n?{type:"insert-line-break"}:t==="Enter"?{type:"send-message"}:!r&&(t==="Backspace"||t==="Delete")?{type:"delete-content",direction:t==="Backspace"?"backward":"forward"}:{type:"noop"}}const Xr="http://www.w3.org/2000/svg";class Cc{constructor(){this.render=(t,n)=>{if(!t)return;const r=document.createDocumentFragment();for(const s of n.nodes){const i=s.type==="text"?this.createTextNodeElement(s):this.createTokenNodeElement(s,n.selectedRange,n.nodeStartMap);i&&r.appendChild(i)}t.replaceChildren(r)},this.createTextNodeElement=t=>{if(t.text.length===0)return null;const n=document.createElement("span");return n.dataset.composerNodeId=t.id,n.dataset.composerNodeType="text",n.textContent=t.text,n},this.createTokenNodeElement=(t,n,r)=>{const s=r.get(t.id)??0,i=mc(n,s,s+1),o=document.createElement("span");o.contentEditable="false",o.dataset.composerNodeId=t.id,o.dataset.composerNodeType="token",o.dataset.composerTokenKind=t.tokenKind,o.dataset.composerTokenKey=t.tokenKey,o.dataset.composerLabel=t.label,o.className=["mx-[2px]","inline-flex","h-6","max-w-full","items-center","gap-1","rounded-md","border","px-1.5","align-baseline","text-[11px]","font-medium","transition",i?"border-primary/30 bg-primary/18 text-primary":"border-primary/12 bg-primary/8 text-primary"].join(" "),o.append(this.createTokenIcon(t.tokenKind));const a=document.createElement("span");return a.className="truncate",a.textContent=t.label,o.append(a),o},this.createTokenIcon=t=>{const n=document.createElement("span");return n.className="inline-flex h-3 w-3 shrink-0 items-center justify-center text-primary/70",n.append(t==="file"?this.createFileIcon():this.createSkillIcon()),n},this.createSkillIcon=()=>this.createSvgIcon([{tag:"path",attrs:{d:"M8.5 2.75 2.75 6l5.75 3.25L14.25 6 8.5 2.75Z"}},{tag:"path",attrs:{d:"M2.75 10 8.5 13.25 14.25 10"}},{tag:"path",attrs:{d:"M2.75 6v4l5.75 3.25V9.25L2.75 6Z"}},{tag:"path",attrs:{d:"M14.25 6v4L8.5 13.25V9.25L14.25 6Z"}}]),this.createFileIcon=()=>this.createSvgIcon([{tag:"path",attrs:{d:"M5.25 2.75h4.5L13 6v7.25A1.75 1.75 0 0 1 11.25 15h-6.5A1.75 1.75 0 0 1 3 13.25v-8.75A1.75 1.75 0 0 1 4.75 2.75Z"}},{tag:"path",attrs:{d:"M9.75 2.75V6H13"}},{tag:"path",attrs:{d:"M5.75 8.75h4.5"}},{tag:"path",attrs:{d:"M5.75 10.75h4.5"}}]),this.createSvgIcon=t=>{const n=document.createElementNS(Xr,"svg");n.setAttribute("viewBox","0 0 16 16"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.25"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("class","h-3 w-3");for(const r of t){const s=document.createElementNS(Xr,r.tag);for(const[i,o]of Object.entries(r.attrs))s.setAttribute(i,o);n.append(s)}return n}}}const Yr=188;class Tc{constructor(t){this.controller=t,this.surfaceRenderer=new Cc,this.sync=(n,r)=>this.controller.sync(n,r),this.syncSelectionFromRoot=n=>this.controller.setSelection(ho(n,this.controller.getSnapshot().nodes)),this.restoreSelectionIfFocused=(n,r)=>{!n||document.activeElement!==n||Sc(n,this.controller.getSnapshot().nodes,r)},this.syncViewport=n=>{n&&(n.style.maxHeight=`${Yr}px`,n.style.overflowY=n.scrollHeight>Yr?"auto":"hidden")},this.renderSurface=n=>{this.surfaceRenderer.render(n.root,{nodes:n.snapshot.nodes,selectedRange:n.selectedRange,nodeStartMap:n.snapshot.nodeStartMap})},this.insertSlashItem=(n,r)=>{n.value&&r(this.controller.insertSkillToken(n.value,n.title))},this.syncSelectedSkills=(n,r,s)=>{s(this.controller.syncSelectedSkills(n,r))},this.handleBeforeInput=n=>{const{event:r,disabled:s,isComposing:i,commitSnapshot:o}=n,a=r.nativeEvent;s||i||a.isComposing||!(a.inputType==="insertText"||a.inputType==="insertReplacementText")||!a.data||(r.preventDefault(),o(this.controller.insertText(a.data)))},this.handleInput=n=>{const{event:r,isComposing:s,commitSnapshot:i}=n,o=r.nativeEvent;if(s||o.isComposing)return;const a=r.currentTarget,l=Qr(a);i(this.controller.replaceDocument(l.nodes,l.selection))},this.handleCompositionEnd=n=>{const{event:r,commitSnapshot:s}=n,i=r.currentTarget,o=Qr(i);s(this.controller.replaceDocument(o.nodes,o.selection))},this.handleKeyDown=n=>{const{event:r,slashItems:s,activeSlashIndex:i,activeSlashItem:o,actions:a,commitSnapshot:l,insertSkillToken:u,onSlashActiveIndexChange:c,onSlashQueryChange:d,onSlashOpenChange:p}=n,f=this.controller.getSnapshot(),m=wc({key:r.key,shiftKey:r.shiftKey,isComposing:r.nativeEvent.isComposing,isSlashMenuOpen:f.slashTrigger!==null,slashItemCount:s.length,activeSlashIndex:i,isSending:a.isSending,canStopGeneration:a.canStopGeneration});if(m.type!=="noop"){if(r.preventDefault(),m.type==="move-slash-index"){c(m.index);return}if(m.type==="insert-active-slash-item"){o&&u(o.value??o.key,o.title);return}if(m.type==="close-slash"){d==null||d(null),p(!1);return}if(m.type==="stop-generation"){a.onStop();return}if(m.type==="insert-line-break"){l(this.controller.insertText(`
2
2
  `));return}if(m.type==="send-message"){a.onSend();return}m.type==="delete-content"&&l(this.controller.deleteContent(m.direction))}},this.handlePaste=n=>{const{event:r,commitSnapshot:s}=n,i=r.clipboardData.getData("text/plain");i&&(r.preventDefault(),s(this.controller.insertText(i)))},this.handleBlur=n=>{const{setSelectedRange:r,onSlashQueryChange:s,onSlashOpenChange:i}=n;r(null),s==null||s(null),i(!1)}}}class Ic{constructor(){this.controller=new vc,this.viewController=new Tc(this.controller),this.rootElement=null,this.selection=null,this.selectedRange=null,this.snapshot=this.controller.getSnapshot(),this.config=null,this.isComposing=!1,this.bindRootElement=t=>{this.rootElement=t},this.update=t=>(this.config=t,this.snapshot=this.viewController.sync(t.nodes,this.selectedRange),{snapshot:this.snapshot,selectedRange:this.selectedRange,bindRootElement:this.bindRootElement,handleBeforeInput:this.handleBeforeInput,handleInput:this.handleInput,handleCompositionStart:this.handleCompositionStart,handleCompositionEnd:this.handleCompositionEnd,handleKeyDown:this.handleKeyDown,handlePaste:this.handlePaste,handleBlur:this.handleBlur,syncSelectionState:this.syncSelectionState,imperativeHandle:this.createHandle()}),this.createHandle=()=>({insertSlashItem:t=>{this.viewController.insertSlashItem(t,this.commitSnapshot)},syncSelectedSkills:(t,n)=>{this.viewController.syncSelectedSkills(t,n,this.commitSnapshot)}}),this.restoreDomAfterCommit=()=>{this.isComposing||this.viewController.restoreSelectionIfFocused(this.rootElement,this.selection)},this.renderSurface=()=>{this.isComposing||this.viewController.renderSurface({root:this.rootElement,snapshot:this.snapshot,selectedRange:this.selectedRange})},this.syncViewport=()=>{this.viewController.syncViewport(this.rootElement)},this.syncSelectionState=()=>{if(!this.rootElement||this.isComposing)return;const t=this.viewController.syncSelectionFromRoot(this.rootElement);this.selection=t.selection,this.selectedRange=t.selection,this.syncSlashState(t),this.requestRender()},this.handleBeforeInput=t=>{this.viewController.handleBeforeInput({event:t,disabled:this.requireConfig().disabled,isComposing:this.isComposing,commitSnapshot:this.commitSnapshot})},this.handleInput=t=>{this.viewController.handleInput({event:t,isComposing:this.isComposing,commitSnapshot:this.commitSnapshot})},this.handleCompositionStart=()=>{this.isComposing=!0},this.handleCompositionEnd=t=>{this.isComposing=!1,this.viewController.handleCompositionEnd({event:t,commitSnapshot:this.commitSnapshot})},this.handleKeyDown=t=>{const n=this.requireConfig(),r=n.slashItems[n.activeSlashIndex]??null;this.viewController.handleKeyDown({event:t,slashItems:n.slashItems,activeSlashIndex:n.activeSlashIndex,activeSlashItem:r,actions:n.actions,commitSnapshot:this.commitSnapshot,insertSkillToken:this.insertSkillToken,onSlashActiveIndexChange:n.onSlashActiveIndexChange,onSlashQueryChange:n.onSlashQueryChange,onSlashOpenChange:n.onSlashOpenChange})},this.handlePaste=t=>{this.viewController.handlePaste({event:t,commitSnapshot:this.commitSnapshot})},this.handleBlur=()=>{const t=this.requireConfig();this.isComposing=!1,this.viewController.handleBlur({setSelectedRange:this.setSelectedRange,onSlashQueryChange:t.onSlashQueryChange,onSlashOpenChange:t.onSlashOpenChange})},this.setSelectedRange=t=>{this.selectedRange=t,this.selection=t,this.requestRender()},this.commitSnapshot=t=>{const n=this.requireConfig();this.selection=t.selection,this.selectedRange=t.selection,this.snapshot=t,n.onNodesChange(t.nodes),this.syncSlashState(t)},this.insertSkillToken=(t,n)=>{this.commitSnapshot(this.controller.insertSkillToken(t,n))},this.syncSlashState=t=>{var r,s;const n=this.requireConfig();(s=n.onSlashQueryChange)==null||s.call(n,((r=t.slashTrigger)==null?void 0:r.query)??null),n.onSlashOpenChange(t.slashTrigger!==null)},this.requestRender=()=>{this.requireConfig().requestRender()},this.requireConfig=()=>{if(!this.config)throw new Error("ChatComposerRuntime is not configured.");return this.config}}}const Mc=k.forwardRef(function(t,n){const{nodes:r,placeholder:s,disabled:i,slashItems:o,actions:a,onNodesChange:l,onSlashQueryChange:u,onSlashOpenChange:c,onSlashActiveIndexChange:d,activeSlashIndex:p}=t,[f,m]=k.useState(0),[y]=k.useState(()=>new Ic),{snapshot:b,bindRootElement:g,handleBeforeInput:v,handleInput:C,handleCompositionStart:A,handleCompositionEnd:P,handleKeyDown:T,handlePaste:F,handleBlur:B,syncSelectionState:z,imperativeHandle:w}=y.update({nodes:r,disabled:i,slashItems:o,actions:a,onNodesChange:l,onSlashQueryChange:u,onSlashOpenChange:c,onSlashActiveIndexChange:d,activeSlashIndex:p,requestRender:()=>m(D=>D+1)});return k.useImperativeHandle(n,()=>w,[w]),k.useLayoutEffect(()=>{y.renderSurface(),y.restoreDomAfterCommit(),y.syncViewport()},[y,b.nodes,b.nodeStartMap,f]),h.jsx("div",{className:"px-4 py-2.5",children:h.jsx("div",{className:"min-h-[60px]",children:h.jsx("div",{ref:g,contentEditable:!i,suppressContentEditableWarning:!0,role:"textbox","aria-multiline":"true","data-placeholder":s,onBeforeInput:v,onInput:C,onCompositionStart:A,onCompositionEnd:P,onKeyDown:T,onKeyUp:z,onMouseUp:z,onFocus:z,onBlur:B,onPaste:F,className:"min-h-7 max-h-[188px] w-full overflow-y-auto whitespace-pre-wrap break-words bg-transparent py-0.5 text-sm leading-6 text-gray-800 outline-none empty:before:pointer-events-none empty:before:text-gray-400 empty:before:content-[attr(data-placeholder)]"})})})});function Rc({hint:e}){if(!e)return null;if(e.loading)return h.jsx("div",{className:"px-4 pb-2",children:h.jsxs("div",{className:"inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-gray-50 px-3 py-2",children:[h.jsx("span",{className:"h-3 w-28 animate-pulse rounded bg-gray-200"}),h.jsx("span",{className:"h-3 w-16 animate-pulse rounded bg-gray-200"})]})});const t=e.tone==="warning"?"border-amber-200 bg-amber-50 text-amber-800":"border-gray-200 bg-gray-50 text-gray-700";return h.jsx("div",{className:"px-4 pb-2",children:h.jsxs("div",{className:`inline-flex items-center gap-2 rounded-lg px-3 py-1.5 text-xs ${t}`,children:[e.text?h.jsx("span",{children:e.text}):null,e.actionLabel&&e.onAction?h.jsx("button",{type:"button",onClick:e.onAction,className:"font-semibold underline-offset-2 hover:underline",children:e.actionLabel}):null]})})}function Ec(e){const t=k.useRef(null),[n,r]=k.useState(null),[s,i]=k.useState(0),o=n!==null,a=e.slashMenu.items[s]??null;k.useEffect(()=>{i(u=>e.slashMenu.items.length===0?0:Math.min(u,e.slashMenu.items.length-1))},[e.slashMenu.items.length]),k.useEffect(()=>{n!==null&&i(0)},[n]);const l=k.useMemo(()=>e.toolbar.skillPicker?{...e.toolbar,skillPicker:{...e.toolbar.skillPicker,onSelectedKeysChange:u=>{var c,d;(d=t.current)==null||d.syncSelectedSkills(u,((c=e.toolbar.skillPicker)==null?void 0:c.options)??[])}}}:e.toolbar,[e.toolbar]);return h.jsx("div",{className:"border-t border-gray-200/80 bg-white p-4",children:h.jsx("div",{className:"mx-auto w-full max-w-[min(1120px,100%)]",children:h.jsxs("div",{className:"overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-card",children:[h.jsxs("div",{className:"relative",children:[h.jsx(Mc,{ref:t,nodes:e.composer.nodes,placeholder:e.composer.placeholder,disabled:e.composer.disabled,slashItems:e.slashMenu.items,actions:e.toolbar.actions,activeSlashIndex:s,onNodesChange:e.composer.onNodesChange,onSlashQueryChange:u=>{var c,d;r(u),(d=(c=e.composer).onSlashQueryChange)==null||d.call(c,u)},onSlashOpenChange:u=>{u||r(null)},onSlashActiveIndexChange:i}),h.jsx(Xu,{isOpen:o,isLoading:e.slashMenu.isLoading,items:e.slashMenu.items,activeIndex:s,activeItem:a,texts:e.slashMenu.texts,onSelectItem:u=>{var c;(c=t.current)==null||c.insertSlashItem(u)},onOpenChange:u=>{u||r(null)},onSetActiveIndex:i})]}),h.jsx(Rc,{hint:e.hint}),h.jsx(ic,{...l})]})})})}function cn({role:e}){return e==="user"?h.jsx("div",{"data-testid":"chat-message-avatar-user",className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-white shadow-sm",children:h.jsx(gl,{className:"h-4 w-4"})}):e==="tool"?h.jsx("div",{"data-testid":"chat-message-avatar-tool",className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-amber-100 text-amber-700 shadow-sm",children:h.jsx(vi,{className:"h-4 w-4"})}):h.jsx("div",{"data-testid":"chat-message-avatar-assistant",className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-gray-200/80 bg-gray-900 text-white shadow-sm",children:h.jsx(wi,{className:"h-4 w-4"})})}function Ac(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const Lc=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Nc=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Pc={};function Jr(e,t){return(Pc.jsx?Nc:Lc).test(e)}const jc=/[ \t\n\f\r]/g;function Dc(e){return typeof e=="object"?e.type==="text"?Zr(e.value):!1:Zr(e)}function Zr(e){return e.replace(jc,"")===""}class At{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}At.prototype.normal={};At.prototype.property={};At.prototype.space=void 0;function fo(e,t){const n={},r={};for(const s of e)Object.assign(n,s.property),Object.assign(r,s.normal);return new At(n,r,t)}function Kn(e){return e.toLowerCase()}class ve{constructor(t,n){this.attribute=n,this.property=t}}ve.prototype.attribute="";ve.prototype.booleanish=!1;ve.prototype.boolean=!1;ve.prototype.commaOrSpaceSeparated=!1;ve.prototype.commaSeparated=!1;ve.prototype.defined=!1;ve.prototype.mustUseProperty=!1;ve.prototype.number=!1;ve.prototype.overloadedBoolean=!1;ve.prototype.property="";ve.prototype.spaceSeparated=!1;ve.prototype.space=void 0;let _c=0;const q=tt(),le=tt(),Un=tt(),L=tt(),te=tt(),at=tt(),Te=tt();function tt(){return 2**++_c}const Vn=Object.freeze(Object.defineProperty({__proto__:null,boolean:q,booleanish:le,commaOrSpaceSeparated:Te,commaSeparated:at,number:L,overloadedBoolean:Un,spaceSeparated:te},Symbol.toStringTag,{value:"Module"})),dn=Object.keys(Vn);class xr extends ve{constructor(t,n,r,s){let i=-1;if(super(t,n),es(this,"space",s),typeof r=="number")for(;++i<dn.length;){const o=dn[i];es(this,dn[i],(r&Vn[o])===Vn[o])}}}xr.prototype.defined=!0;function es(e,t,n){n&&(e[t]=n)}function dt(e){const t={},n={};for(const[r,s]of Object.entries(e.properties)){const i=new xr(r,e.transform(e.attributes||{},r),s,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(i.mustUseProperty=!0),t[r]=i,n[Kn(r)]=r,n[Kn(i.attribute)]=r}return new At(t,n,e.space)}const po=dt({properties:{ariaActiveDescendant:null,ariaAtomic:le,ariaAutoComplete:null,ariaBusy:le,ariaChecked:le,ariaColCount:L,ariaColIndex:L,ariaColSpan:L,ariaControls:te,ariaCurrent:null,ariaDescribedBy:te,ariaDetails:null,ariaDisabled:le,ariaDropEffect:te,ariaErrorMessage:null,ariaExpanded:le,ariaFlowTo:te,ariaGrabbed:le,ariaHasPopup:null,ariaHidden:le,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:te,ariaLevel:L,ariaLive:null,ariaModal:le,ariaMultiLine:le,ariaMultiSelectable:le,ariaOrientation:null,ariaOwns:te,ariaPlaceholder:null,ariaPosInSet:L,ariaPressed:le,ariaReadOnly:le,ariaRelevant:null,ariaRequired:le,ariaRoleDescription:te,ariaRowCount:L,ariaRowIndex:L,ariaRowSpan:L,ariaSelected:le,ariaSetSize:L,ariaSort:null,ariaValueMax:L,ariaValueMin:L,ariaValueNow:L,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function go(e,t){return t in e?e[t]:t}function mo(e,t){return go(e,t.toLowerCase())}const Oc=dt({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:at,acceptCharset:te,accessKey:te,action:null,allow:null,allowFullScreen:q,allowPaymentRequest:q,allowUserMedia:q,alt:null,as:null,async:q,autoCapitalize:null,autoComplete:te,autoFocus:q,autoPlay:q,blocking:te,capture:null,charSet:null,checked:q,cite:null,className:te,cols:L,colSpan:null,content:null,contentEditable:le,controls:q,controlsList:te,coords:L|at,crossOrigin:null,data:null,dateTime:null,decoding:null,default:q,defer:q,dir:null,dirName:null,disabled:q,download:Un,draggable:le,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:q,formTarget:null,headers:te,height:L,hidden:Un,high:L,href:null,hrefLang:null,htmlFor:te,httpEquiv:te,id:null,imageSizes:null,imageSrcSet:null,inert:q,inputMode:null,integrity:null,is:null,isMap:q,itemId:null,itemProp:te,itemRef:te,itemScope:q,itemType:te,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:q,low:L,manifest:null,max:null,maxLength:L,media:null,method:null,min:null,minLength:L,multiple:q,muted:q,name:null,nonce:null,noModule:q,noValidate:q,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:q,optimum:L,pattern:null,ping:te,placeholder:null,playsInline:q,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:q,referrerPolicy:null,rel:te,required:q,reversed:q,rows:L,rowSpan:L,sandbox:te,scope:null,scoped:q,seamless:q,selected:q,shadowRootClonable:q,shadowRootDelegatesFocus:q,shadowRootMode:null,shape:null,size:L,sizes:null,slot:null,span:L,spellCheck:le,src:null,srcDoc:null,srcLang:null,srcSet:null,start:L,step:null,style:null,tabIndex:L,target:null,title:null,translate:null,type:null,typeMustMatch:q,useMap:null,value:le,width:L,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:te,axis:null,background:null,bgColor:null,border:L,borderColor:null,bottomMargin:L,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:q,declare:q,event:null,face:null,frame:null,frameBorder:null,hSpace:L,leftMargin:L,link:null,longDesc:null,lowSrc:null,marginHeight:L,marginWidth:L,noResize:q,noHref:q,noShade:q,noWrap:q,object:null,profile:null,prompt:null,rev:null,rightMargin:L,rules:null,scheme:null,scrolling:le,standby:null,summary:null,text:null,topMargin:L,valueType:null,version:null,vAlign:null,vLink:null,vSpace:L,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:q,disableRemotePlayback:q,prefix:null,property:null,results:L,security:null,unselectable:null},space:"html",transform:mo}),Fc=dt({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Te,accentHeight:L,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:L,amplitude:L,arabicForm:null,ascent:L,attributeName:null,attributeType:null,azimuth:L,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:L,by:null,calcMode:null,capHeight:L,className:te,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:L,diffuseConstant:L,direction:null,display:null,dur:null,divisor:L,dominantBaseline:null,download:q,dx:null,dy:null,edgeMode:null,editable:null,elevation:L,enableBackground:null,end:null,event:null,exponent:L,externalResourcesRequired:null,fill:null,fillOpacity:L,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:at,g2:at,glyphName:at,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:L,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:L,horizOriginX:L,horizOriginY:L,id:null,ideographic:L,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:L,k:L,k1:L,k2:L,k3:L,k4:L,kernelMatrix:Te,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:L,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:L,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:L,overlineThickness:L,paintOrder:null,panose1:null,path:null,pathLength:L,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:te,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:L,pointsAtY:L,pointsAtZ:L,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Te,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Te,rev:Te,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Te,requiredFeatures:Te,requiredFonts:Te,requiredFormats:Te,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:L,specularExponent:L,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:L,strikethroughThickness:L,string:null,stroke:null,strokeDashArray:Te,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:L,strokeOpacity:L,strokeWidth:null,style:null,surfaceScale:L,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Te,tabIndex:L,tableValues:null,target:null,targetX:L,targetY:L,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Te,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:L,underlineThickness:L,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:L,values:null,vAlphabetic:L,vMathematical:L,vectorEffect:null,vHanging:L,vIdeographic:L,version:null,vertAdvY:L,vertOriginX:L,vertOriginY:L,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:L,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:go}),yo=dt({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),xo=dt({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:mo}),bo=dt({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),zc={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},Bc=/[A-Z]/g,ts=/-[a-z]/g,$c=/^data[-\w.:]+$/i;function Kc(e,t){const n=Kn(t);let r=t,s=ve;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&$c.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(ts,Vc);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!ts.test(i)){let o=i.replace(Bc,Uc);o.charAt(0)!=="-"&&(o="-"+o),t="data"+o}}s=xr}return new s(r,t)}function Uc(e){return"-"+e.toLowerCase()}function Vc(e){return e.charAt(1).toUpperCase()}const Hc=fo([po,Oc,yo,xo,bo],"html"),br=fo([po,Fc,yo,xo,bo],"svg");function qc(e){return e.join(" ").trim()}var rt={},hn,ns;function Wc(){if(ns)return hn;ns=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,r=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,s=/^:\s*/,i=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,o=/^[;\s]*/,a=/^\s+|\s+$/g,l=`
3
3
  `,u="/",c="*",d="",p="comment",f="declaration";function m(b,g){if(typeof b!="string")throw new TypeError("First argument must be a string");if(!b)return[];g=g||{};var v=1,C=1;function A(O){var R=O.match(t);R&&(v+=R.length);var U=O.lastIndexOf(l);C=~U?O.length-U:C+O.length}function P(){var O={line:v,column:C};return function(R){return R.position=new T(O),z(),R}}function T(O){this.start=O,this.end={line:v,column:C},this.source=g.source}T.prototype.content=b;function F(O){var R=new Error(g.source+":"+v+":"+C+": "+O);if(R.reason=O,R.filename=g.source,R.line=v,R.column=C,R.source=b,!g.silent)throw R}function B(O){var R=O.exec(b);if(R){var U=R[0];return A(U),b=b.slice(U.length),R}}function z(){B(n)}function w(O){var R;for(O=O||[];R=D();)R!==!1&&O.push(R);return O}function D(){var O=P();if(!(u!=b.charAt(0)||c!=b.charAt(1))){for(var R=2;d!=b.charAt(R)&&(c!=b.charAt(R)||u!=b.charAt(R+1));)++R;if(R+=2,d===b.charAt(R-1))return F("End of comment missing");var U=b.slice(2,R-2);return C+=2,A(U),b=b.slice(R),C+=2,O({type:p,comment:U})}}function N(){var O=P(),R=B(r);if(R){if(D(),!B(s))return F("property missing ':'");var U=B(i),E=O({type:f,property:y(R[0].replace(e,d)),value:U?y(U[0].replace(e,d)):d});return B(o),E}}function $(){var O=[];w(O);for(var R;R=N();)R!==!1&&(O.push(R),w(O));return O}return z(),$()}function y(b){return b?b.replace(a,d):d}return hn=m,hn}var rs;function Gc(){if(rs)return rt;rs=1;var e=rt&&rt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(rt,"__esModule",{value:!0}),rt.default=n;const t=e(Wc());function n(r,s){let i=null;if(!r||typeof r!="string")return i;const o=(0,t.default)(r),a=typeof s=="function";return o.forEach(l=>{if(l.type!=="declaration")return;const{property:u,value:c}=l;a?s(u,c,l):c&&(i=i||{},i[u]=c)}),i}return rt}var gt={},ss;function Qc(){if(ss)return gt;ss=1,Object.defineProperty(gt,"__esModule",{value:!0}),gt.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,r=/^-(webkit|moz|ms|o|khtml)-/,s=/^-(ms)-/,i=function(u){return!u||n.test(u)||e.test(u)},o=function(u,c){return c.toUpperCase()},a=function(u,c){return"".concat(c,"-")},l=function(u,c){return c===void 0&&(c={}),i(u)?u:(u=u.toLowerCase(),c.reactCompat?u=u.replace(s,a):u=u.replace(r,a),u.replace(t,o))};return gt.camelCase=l,gt}var mt,is;function Xc(){if(is)return mt;is=1;var e=mt&&mt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}},t=e(Gc()),n=Qc();function r(s,i){var o={};return!s||typeof s!="string"||(0,t.default)(s,function(a,l){a&&l&&(o[(0,n.camelCase)(a,i)]=l)}),o}return r.default=r,mt=r,mt}var Yc=Xc();const Jc=Ci(Yc),So=ko("end"),Sr=ko("start");function ko(e){return t;function t(n){const r=n&&n.position&&n.position[e]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function Zc(e){const t=Sr(e),n=So(e);if(t&&n)return{start:t,end:n}}function kt(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?os(e.position):"start"in e||"end"in e?os(e):"line"in e||"column"in e?Hn(e):""}function Hn(e){return as(e&&e.line)+":"+as(e&&e.column)}function os(e){return Hn(e&&e.start)+"-"+Hn(e&&e.end)}function as(e){return e&&typeof e=="number"?e:1}class me extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let s="",i={},o=!1;if(n&&("line"in n&&"column"in n?i={place:n}:"start"in n&&"end"in n?i={place:n}:"type"in n?i={ancestors:[n],place:n.position}:i={...n}),typeof t=="string"?s=t:!i.cause&&t&&(o=!0,s=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof r=="string"){const l=r.indexOf(":");l===-1?i.ruleId=r:(i.source=r.slice(0,l),i.ruleId=r.slice(l+1))}if(!i.place&&i.ancestors&&i.ancestors){const l=i.ancestors[i.ancestors.length-1];l&&(i.place=l.position)}const a=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=a?a.column:void 0,this.fatal=void 0,this.file="",this.message=s,this.line=a?a.line:void 0,this.name=kt(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=o&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}me.prototype.file="";me.prototype.name="";me.prototype.reason="";me.prototype.message="";me.prototype.stack="";me.prototype.column=void 0;me.prototype.line=void 0;me.prototype.ancestors=void 0;me.prototype.cause=void 0;me.prototype.fatal=void 0;me.prototype.place=void 0;me.prototype.ruleId=void 0;me.prototype.source=void 0;const kr={}.hasOwnProperty,ed=new Map,td=/[A-Z]/g,nd=new Set(["table","tbody","thead","tfoot","tr"]),rd=new Set(["td","th"]),vo="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function sd(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=hd(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=dd(n,t.jsx,t.jsxs)}const s={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?br:Hc,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=wo(s,e,void 0);return i&&typeof i!="string"?i:s.create(e,s.Fragment,{children:i||void 0},void 0)}function wo(e,t,n){if(t.type==="element")return id(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return od(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return ld(e,t,n);if(t.type==="mdxjsEsm")return ad(e,t);if(t.type==="root")return ud(e,t,n);if(t.type==="text")return cd(e,t)}function id(e,t,n){const r=e.schema;let s=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(s=br,e.schema=s),e.ancestors.push(t);const i=To(e,t.tagName,!1),o=fd(e,t);let a=wr(e,t);return nd.has(t.tagName)&&(a=a.filter(function(l){return typeof l=="string"?!Dc(l):!0})),Co(e,o,i,t),vr(o,a),e.ancestors.pop(),e.schema=r,e.create(t,i,o,n)}function od(e,t){if(t.data&&t.data.estree&&e.evaluater){const r=t.data.estree.body[0];return r.type,e.evaluater.evaluateExpression(r.expression)}Tt(e,t.position)}function ad(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Tt(e,t.position)}function ld(e,t,n){const r=e.schema;let s=r;t.name==="svg"&&r.space==="html"&&(s=br,e.schema=s),e.ancestors.push(t);const i=t.name===null?e.Fragment:To(e,t.name,!0),o=pd(e,t),a=wr(e,t);return Co(e,o,i,t),vr(o,a),e.ancestors.pop(),e.schema=r,e.create(t,i,o,n)}function ud(e,t,n){const r={};return vr(r,wr(e,t)),e.create(t,e.Fragment,r,n)}function cd(e,t){return t.value}function Co(e,t,n,r){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=r)}function vr(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function dd(e,t,n){return r;function r(s,i,o,a){const u=Array.isArray(o.children)?n:t;return a?u(i,o,a):u(i,o)}}function hd(e,t){return n;function n(r,s,i,o){const a=Array.isArray(i.children),l=Sr(r);return t(s,i,o,a,{columnNumber:l?l.column-1:void 0,fileName:e,lineNumber:l?l.line:void 0},void 0)}}function fd(e,t){const n={};let r,s;for(s in t.properties)if(s!=="children"&&kr.call(t.properties,s)){const i=gd(e,s,t.properties[s]);if(i){const[o,a]=i;e.tableCellAlignToStyle&&o==="align"&&typeof a=="string"&&rd.has(t.tagName)?r=a:n[o]=a}}if(r){const i=n.style||(n.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function pd(e,t){const n={};for(const r of t.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&e.evaluater){const i=r.data.estree.body[0];i.type;const o=i.expression;o.type;const a=o.properties[0];a.type,Object.assign(n,e.evaluater.evaluateExpression(a.argument))}else Tt(e,t.position);else{const s=r.name;let i;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&e.evaluater){const a=r.value.data.estree.body[0];a.type,i=e.evaluater.evaluateExpression(a.expression)}else Tt(e,t.position);else i=r.value===null?!0:r.value;n[s]=i}return n}function wr(e,t){const n=[];let r=-1;const s=e.passKeys?new Map:ed;for(;++r<t.children.length;){const i=t.children[r];let o;if(e.passKeys){const l=i.type==="element"?i.tagName:i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement"?i.name:void 0;if(l){const u=s.get(l)||0;o=l+"-"+u,s.set(l,u+1)}}const a=wo(e,i,o);a!==void 0&&n.push(a)}return n}function gd(e,t,n){const r=Kc(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=r.commaSeparated?Ac(n):qc(n)),r.property==="style"){let s=typeof n=="object"?n:md(e,String(n));return e.stylePropertyNameCase==="css"&&(s=yd(s)),["style",s]}return[e.elementAttributeNameCase==="react"&&r.space?zc[r.property]||r.property:r.attribute,n]}}function md(e,t){try{return Jc(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const r=n,s=new me("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:r,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw s.file=e.filePath||void 0,s.url=vo+"#cannot-parse-style-attribute",s}}function To(e,t,n){let r;if(!n)r={type:"Literal",value:t};else if(t.includes(".")){const s=t.split(".");let i=-1,o;for(;++i<s.length;){const a=Jr(s[i])?{type:"Identifier",name:s[i]}:{type:"Literal",value:s[i]};o=o?{type:"MemberExpression",object:o,property:a,computed:!!(i&&a.type==="Literal"),optional:!1}:a}r=o}else r=Jr(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(r.type==="Literal"){const s=r.value;return kr.call(e.components,s)?e.components[s]:s}if(e.evaluater)return e.evaluater.evaluateExpression(r);Tt(e)}function Tt(e,t){const n=new me("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw n.file=e.filePath||void 0,n.url=vo+"#cannot-handle-mdx-estrees-without-createevaluater",n}function yd(e){const t={};let n;for(n in e)kr.call(e,n)&&(t[xd(n)]=e[n]);return t}function xd(e){let t=e.replace(td,bd);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function bd(e){return"-"+e.toLowerCase()}const fn={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},Sd={};function Cr(e,t){const n=Sd,r=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,s=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return Io(e,r,s)}function Io(e,t,n){if(kd(e)){if("value"in e)return e.type==="html"&&!n?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return ls(e.children,t,n)}return Array.isArray(e)?ls(e,t,n):""}function ls(e,t,n){const r=[];let s=-1;for(;++s<e.length;)r[s]=Io(e[s],t,n);return r.join("")}function kd(e){return!!(e&&typeof e=="object")}const us=document.createElement("i");function Tr(e){const t="&"+e+";";us.innerHTML=t;const n=us.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function Ie(e,t,n,r){const s=e.length;let i=0,o;if(t<0?t=-t>s?0:s+t:t=t>s?s:t,n=n>0?n:0,r.length<1e4)o=Array.from(r),o.unshift(t,n),e.splice(...o);else for(n&&e.splice(t,n);i<r.length;)o=r.slice(i,i+1e4),o.unshift(t,0),e.splice(...o),i+=1e4,t+=1e4}function Ae(e,t){return e.length>0?(Ie(e,e.length,0,t),e):t}const cs={}.hasOwnProperty;function Mo(e){const t={};let n=-1;for(;++n<e.length;)vd(t,e[n]);return t}function vd(e,t){let n;for(n in t){const s=(cs.call(e,n)?e[n]:void 0)||(e[n]={}),i=t[n];let o;if(i)for(o in i){cs.call(s,o)||(s[o]=[]);const a=i[o];wd(s[o],Array.isArray(a)?a:a?[a]:[])}}}function wd(e,t){let n=-1;const r=[];for(;++n<t.length;)(t[n].add==="after"?e:r).push(t[n]);Ie(e,0,0,r)}function Ro(e,t){const n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function Pe(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const be=Xe(/[A-Za-z]/),ge=Xe(/[\dA-Za-z]/),Cd=Xe(/[#-'*+\--9=?A-Z^-~]/);function Ht(e){return e!==null&&(e<32||e===127)}const qn=Xe(/\d/),Td=Xe(/[\dA-Fa-f]/),Id=Xe(/[!-/:-@[-`{-~]/);function K(e){return e!==null&&e<-2}function ee(e){return e!==null&&(e<0||e===32)}function Q(e){return e===-2||e===-1||e===32}const tn=Xe(new RegExp("\\p{P}|\\p{S}","u")),et=Xe(/\s/);function Xe(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function ht(e){const t=[];let n=-1,r=0,s=0;for(;++n<e.length;){const i=e.charCodeAt(n);let o="";if(i===37&&ge(e.charCodeAt(n+1))&&ge(e.charCodeAt(n+2)))s=2;else if(i<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(i))||(o=String.fromCharCode(i));else if(i>55295&&i<57344){const a=e.charCodeAt(n+1);i<56320&&a>56319&&a<57344?(o=String.fromCharCode(i,a),s=1):o="�"}else o=String.fromCharCode(i);o&&(t.push(e.slice(r,n),encodeURIComponent(o)),r=n+s+1,o=""),s&&(n+=s,s=0)}return t.join("")+e.slice(r)}function J(e,t,n,r){const s=r?r-1:Number.POSITIVE_INFINITY;let i=0;return o;function o(l){return Q(l)?(e.enter(n),a(l)):t(l)}function a(l){return Q(l)&&i++<s?(e.consume(l),a):(e.exit(n),t(l))}}const Md={tokenize:Rd};function Rd(e){const t=e.attempt(this.parser.constructs.contentInitial,r,s);let n;return t;function r(a){if(a===null){e.consume(a);return}return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),J(e,t,"linePrefix")}function s(a){return e.enter("paragraph"),i(a)}function i(a){const l=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=l),n=l,o(a)}function o(a){if(a===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(a);return}return K(a)?(e.consume(a),e.exit("chunkText"),i):(e.consume(a),o)}}const Ed={tokenize:Ad},ds={tokenize:Ld};function Ad(e){const t=this,n=[];let r=0,s,i,o;return a;function a(C){if(r<n.length){const A=n[r];return t.containerState=A[1],e.attempt(A[0].continuation,l,u)(C)}return u(C)}function l(C){if(r++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,s&&v();const A=t.events.length;let P=A,T;for(;P--;)if(t.events[P][0]==="exit"&&t.events[P][1].type==="chunkFlow"){T=t.events[P][1].end;break}g(r);let F=A;for(;F<t.events.length;)t.events[F][1].end={...T},F++;return Ie(t.events,P+1,0,t.events.slice(A)),t.events.length=F,u(C)}return a(C)}function u(C){if(r===n.length){if(!s)return p(C);if(s.currentConstruct&&s.currentConstruct.concrete)return m(C);t.interrupt=!!(s.currentConstruct&&!s._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(ds,c,d)(C)}function c(C){return s&&v(),g(r),p(C)}function d(C){return t.parser.lazy[t.now().line]=r!==n.length,o=t.now().offset,m(C)}function p(C){return t.containerState={},e.attempt(ds,f,m)(C)}function f(C){return r++,n.push([t.currentConstruct,t.containerState]),p(C)}function m(C){if(C===null){s&&v(),g(0),e.consume(C);return}return s=s||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:s,contentType:"flow",previous:i}),y(C)}function y(C){if(C===null){b(e.exit("chunkFlow"),!0),g(0),e.consume(C);return}return K(C)?(e.consume(C),b(e.exit("chunkFlow")),r=0,t.interrupt=void 0,a):(e.consume(C),y)}function b(C,A){const P=t.sliceStream(C);if(A&&P.push(null),C.previous=i,i&&(i.next=C),i=C,s.defineSkip(C.start),s.write(P),t.parser.lazy[C.start.line]){let T=s.events.length;for(;T--;)if(s.events[T][1].start.offset<o&&(!s.events[T][1].end||s.events[T][1].end.offset>o))return;const F=t.events.length;let B=F,z,w;for(;B--;)if(t.events[B][0]==="exit"&&t.events[B][1].type==="chunkFlow"){if(z){w=t.events[B][1].end;break}z=!0}for(g(r),T=F;T<t.events.length;)t.events[T][1].end={...w},T++;Ie(t.events,B+1,0,t.events.slice(F)),t.events.length=T}}function g(C){let A=n.length;for(;A-- >C;){const P=n[A];t.containerState=P[1],P[0].exit.call(t,e)}n.length=C}function v(){s.write([null]),i=void 0,s=void 0,t.containerState._closeFlow=void 0}}function Ld(e,t,n){return J(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ct(e){if(e===null||ee(e)||et(e))return 1;if(tn(e))return 2}function nn(e,t,n){const r=[];let s=-1;for(;++s<e.length;){const i=e[s].resolveAll;i&&!r.includes(i)&&(t=i(t,n),r.push(i))}return t}const Wn={name:"attention",resolveAll:Nd,tokenize:Pd};function Nd(e,t){let n=-1,r,s,i,o,a,l,u,c;for(;++n<e.length;)if(e[n][0]==="enter"&&e[n][1].type==="attentionSequence"&&e[n][1]._close){for(r=n;r--;)if(e[r][0]==="exit"&&e[r][1].type==="attentionSequence"&&e[r][1]._open&&t.sliceSerialize(e[r][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[r][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[r][1].end.offset-e[r][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;l=e[r][1].end.offset-e[r][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const d={...e[r][1].end},p={...e[n][1].start};hs(d,-l),hs(p,l),o={type:l>1?"strongSequence":"emphasisSequence",start:d,end:{...e[r][1].end}},a={type:l>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:p},i={type:l>1?"strongText":"emphasisText",start:{...e[r][1].end},end:{...e[n][1].start}},s={type:l>1?"strong":"emphasis",start:{...o.start},end:{...a.end}},e[r][1].end={...o.start},e[n][1].start={...a.end},u=[],e[r][1].end.offset-e[r][1].start.offset&&(u=Ae(u,[["enter",e[r][1],t],["exit",e[r][1],t]])),u=Ae(u,[["enter",s,t],["enter",o,t],["exit",o,t],["enter",i,t]]),u=Ae(u,nn(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),u=Ae(u,[["exit",i,t],["enter",a,t],["exit",a,t],["exit",s,t]]),e[n][1].end.offset-e[n][1].start.offset?(c=2,u=Ae(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):c=0,Ie(e,r-1,n-r+3,u),n=r+u.length-c-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function Pd(e,t){const n=this.parser.constructs.attentionMarkers.null,r=this.previous,s=ct(r);let i;return o;function o(l){return i=l,e.enter("attentionSequence"),a(l)}function a(l){if(l===i)return e.consume(l),a;const u=e.exit("attentionSequence"),c=ct(l),d=!c||c===2&&s||n.includes(l),p=!s||s===2&&c||n.includes(r);return u._open=!!(i===42?d:d&&(s||!p)),u._close=!!(i===42?p:p&&(c||!d)),t(l)}}function hs(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const jd={name:"autolink",tokenize:Dd};function Dd(e,t,n){let r=0;return s;function s(f){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),i}function i(f){return be(f)?(e.consume(f),o):f===64?n(f):u(f)}function o(f){return f===43||f===45||f===46||ge(f)?(r=1,a(f)):u(f)}function a(f){return f===58?(e.consume(f),r=0,l):(f===43||f===45||f===46||ge(f))&&r++<32?(e.consume(f),a):(r=0,u(f))}function l(f){return f===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.exit("autolink"),t):f===null||f===32||f===60||Ht(f)?n(f):(e.consume(f),l)}function u(f){return f===64?(e.consume(f),c):Cd(f)?(e.consume(f),u):n(f)}function c(f){return ge(f)?d(f):n(f)}function d(f){return f===46?(e.consume(f),r=0,c):f===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.exit("autolink"),t):p(f)}function p(f){if((f===45||ge(f))&&r++<63){const m=f===45?p:d;return e.consume(f),m}return n(f)}}const Lt={partial:!0,tokenize:_d};function _d(e,t,n){return r;function r(i){return Q(i)?J(e,s,"linePrefix")(i):s(i)}function s(i){return i===null||K(i)?t(i):n(i)}}const Eo={continuation:{tokenize:Fd},exit:zd,name:"blockQuote",tokenize:Od};function Od(e,t,n){const r=this;return s;function s(o){if(o===62){const a=r.containerState;return a.open||(e.enter("blockQuote",{_container:!0}),a.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(o),e.exit("blockQuoteMarker"),i}return n(o)}function i(o){return Q(o)?(e.enter("blockQuotePrefixWhitespace"),e.consume(o),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(o))}}function Fd(e,t,n){const r=this;return s;function s(o){return Q(o)?J(e,i,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o):i(o)}function i(o){return e.attempt(Eo,t,n)(o)}}function zd(e){e.exit("blockQuote")}const Ao={name:"characterEscape",tokenize:Bd};function Bd(e,t,n){return r;function r(i){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(i),e.exit("escapeMarker"),s}function s(i){return Id(i)?(e.enter("characterEscapeValue"),e.consume(i),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(i)}}const Lo={name:"characterReference",tokenize:$d};function $d(e,t,n){const r=this;let s=0,i,o;return a;function a(d){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(d),e.exit("characterReferenceMarker"),l}function l(d){return d===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(d),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),i=31,o=ge,c(d))}function u(d){return d===88||d===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(d),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),i=6,o=Td,c):(e.enter("characterReferenceValue"),i=7,o=qn,c(d))}function c(d){if(d===59&&s){const p=e.exit("characterReferenceValue");return o===ge&&!Tr(r.sliceSerialize(p))?n(d):(e.enter("characterReferenceMarker"),e.consume(d),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return o(d)&&s++<i?(e.consume(d),c):n(d)}}const fs={partial:!0,tokenize:Ud},ps={concrete:!0,name:"codeFenced",tokenize:Kd};function Kd(e,t,n){const r=this,s={partial:!0,tokenize:P};let i=0,o=0,a;return l;function l(T){return u(T)}function u(T){const F=r.events[r.events.length-1];return i=F&&F[1].type==="linePrefix"?F[2].sliceSerialize(F[1],!0).length:0,a=T,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),c(T)}function c(T){return T===a?(o++,e.consume(T),c):o<3?n(T):(e.exit("codeFencedFenceSequence"),Q(T)?J(e,d,"whitespace")(T):d(T))}function d(T){return T===null||K(T)?(e.exit("codeFencedFence"),r.interrupt?t(T):e.check(fs,y,A)(T)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),p(T))}function p(T){return T===null||K(T)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),d(T)):Q(T)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),J(e,f,"whitespace")(T)):T===96&&T===a?n(T):(e.consume(T),p)}function f(T){return T===null||K(T)?d(T):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),m(T))}function m(T){return T===null||K(T)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),d(T)):T===96&&T===a?n(T):(e.consume(T),m)}function y(T){return e.attempt(s,A,b)(T)}function b(T){return e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),g}function g(T){return i>0&&Q(T)?J(e,v,"linePrefix",i+1)(T):v(T)}function v(T){return T===null||K(T)?e.check(fs,y,A)(T):(e.enter("codeFlowValue"),C(T))}function C(T){return T===null||K(T)?(e.exit("codeFlowValue"),v(T)):(e.consume(T),C)}function A(T){return e.exit("codeFenced"),t(T)}function P(T,F,B){let z=0;return w;function w(R){return T.enter("lineEnding"),T.consume(R),T.exit("lineEnding"),D}function D(R){return T.enter("codeFencedFence"),Q(R)?J(T,N,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(R):N(R)}function N(R){return R===a?(T.enter("codeFencedFenceSequence"),$(R)):B(R)}function $(R){return R===a?(z++,T.consume(R),$):z>=o?(T.exit("codeFencedFenceSequence"),Q(R)?J(T,O,"whitespace")(R):O(R)):B(R)}function O(R){return R===null||K(R)?(T.exit("codeFencedFence"),F(R)):B(R)}}}function Ud(e,t,n){const r=this;return s;function s(o){return o===null?n(o):(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),i)}function i(o){return r.parser.lazy[r.now().line]?n(o):t(o)}}const pn={name:"codeIndented",tokenize:Hd},Vd={partial:!0,tokenize:qd};function Hd(e,t,n){const r=this;return s;function s(u){return e.enter("codeIndented"),J(e,i,"linePrefix",5)(u)}function i(u){const c=r.events[r.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?o(u):n(u)}function o(u){return u===null?l(u):K(u)?e.attempt(Vd,o,l)(u):(e.enter("codeFlowValue"),a(u))}function a(u){return u===null||K(u)?(e.exit("codeFlowValue"),o(u)):(e.consume(u),a)}function l(u){return e.exit("codeIndented"),t(u)}}function qd(e,t,n){const r=this;return s;function s(o){return r.parser.lazy[r.now().line]?n(o):K(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),s):J(e,i,"linePrefix",5)(o)}function i(o){const a=r.events[r.events.length-1];return a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?t(o):K(o)?s(o):n(o)}}const Wd={name:"codeText",previous:Qd,resolve:Gd,tokenize:Xd};function Gd(e){let t=e.length-4,n=3,r,s;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r<t;)if(e[r][1].type==="codeTextData"){e[n][1].type="codeTextPadding",e[t][1].type="codeTextPadding",n+=2,t-=2;break}}for(r=n-1,t++;++r<=t;)s===void 0?r!==t&&e[r][1].type!=="lineEnding"&&(s=r):(r===t||e[r][1].type==="lineEnding")&&(e[s][1].type="codeTextData",r!==s+2&&(e[s][1].end=e[r-1][1].end,e.splice(s+2,r-s-2),t-=r-s-2,r=s+2),s=void 0);return e}function Qd(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Xd(e,t,n){let r=0,s,i;return o;function o(d){return e.enter("codeText"),e.enter("codeTextSequence"),a(d)}function a(d){return d===96?(e.consume(d),r++,a):(e.exit("codeTextSequence"),l(d))}function l(d){return d===null?n(d):d===32?(e.enter("space"),e.consume(d),e.exit("space"),l):d===96?(i=e.enter("codeTextSequence"),s=0,c(d)):K(d)?(e.enter("lineEnding"),e.consume(d),e.exit("lineEnding"),l):(e.enter("codeTextData"),u(d))}function u(d){return d===null||d===32||d===96||K(d)?(e.exit("codeTextData"),l(d)):(e.consume(d),u)}function c(d){return d===96?(e.consume(d),s++,c):s===r?(e.exit("codeTextSequence"),e.exit("codeText"),t(d)):(i.type="codeTextData",u(d))}}class Yd{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,n){const r=n??Number.POSITIVE_INFINITY;return r<this.left.length?this.left.slice(t,r):t>this.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){const s=n||0;this.setCursor(Math.trunc(t));const i=this.right.splice(this.right.length-s,Number.POSITIVE_INFINITY);return r&&yt(this.left,r),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),yt(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),yt(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const n=this.left.splice(t,Number.POSITIVE_INFINITY);yt(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);yt(this.left,n.reverse())}}}function yt(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function No(e){const t={};let n=-1,r,s,i,o,a,l,u;const c=new Yd(e);for(;++n<c.length;){for(;n in t;)n=t[n];if(r=c.get(n),n&&r[1].type==="chunkFlow"&&c.get(n-1)[1].type==="listItemPrefix"&&(l=r[1]._tokenizer.events,i=0,i<l.length&&l[i][1].type==="lineEndingBlank"&&(i+=2),i<l.length&&l[i][1].type==="content"))for(;++i<l.length&&l[i][1].type!=="content";)l[i][1].type==="chunkText"&&(l[i][1]._isInFirstContentOfListItem=!0,i++);if(r[0]==="enter")r[1].contentType&&(Object.assign(t,Jd(c,n)),n=t[n],u=!0);else if(r[1]._container){for(i=n,s=void 0;i--;)if(o=c.get(i),o[1].type==="lineEnding"||o[1].type==="lineEndingBlank")o[0]==="enter"&&(s&&(c.get(s)[1].type="lineEndingBlank"),o[1].type="lineEnding",s=i);else if(!(o[1].type==="linePrefix"||o[1].type==="listItemIndent"))break;s&&(r[1].end={...c.get(s)[1].start},a=c.slice(s,n),a.unshift(r),c.splice(s,n-s+1,a))}}return Ie(e,0,Number.POSITIVE_INFINITY,c.slice(0)),!u}function Jd(e,t){const n=e.get(t)[1],r=e.get(t)[2];let s=t-1;const i=[];let o=n._tokenizer;o||(o=r.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(o._contentTypeTextTrailing=!0));const a=o.events,l=[],u={};let c,d,p=-1,f=n,m=0,y=0;const b=[y];for(;f;){for(;e.get(++s)[1]!==f;);i.push(s),f._tokenizer||(c=r.sliceStream(f),f.next||c.push(null),d&&o.defineSkip(f.start),f._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(c),f._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),d=f,f=f.next}for(f=n;++p<a.length;)a[p][0]==="exit"&&a[p-1][0]==="enter"&&a[p][1].type===a[p-1][1].type&&a[p][1].start.line!==a[p][1].end.line&&(y=p+1,b.push(y),f._tokenizer=void 0,f.previous=void 0,f=f.next);for(o.events=[],f?(f._tokenizer=void 0,f.previous=void 0):b.pop(),p=b.length;p--;){const g=a.slice(b[p],b[p+1]),v=i.pop();l.push([v,v+g.length-1]),e.splice(v,2,g)}for(l.reverse(),p=-1;++p<l.length;)u[m+l[p][0]]=m+l[p][1],m+=l[p][1]-l[p][0]-1;return u}const Zd={resolve:th,tokenize:nh},eh={partial:!0,tokenize:rh};function th(e){return No(e),e}function nh(e,t){let n;return r;function r(a){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),s(a)}function s(a){return a===null?i(a):K(a)?e.check(eh,o,i)(a):(e.consume(a),s)}function i(a){return e.exit("chunkContent"),e.exit("content"),t(a)}function o(a){return e.consume(a),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,s}}function rh(e,t,n){const r=this;return s;function s(o){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),J(e,i,"linePrefix")}function i(o){if(o===null||K(o))return n(o);const a=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes("codeIndented")&&a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?t(o):e.interrupt(r.parser.constructs.flow,n,t)(o)}}function Po(e,t,n,r,s,i,o,a,l){const u=l||Number.POSITIVE_INFINITY;let c=0;return d;function d(g){return g===60?(e.enter(r),e.enter(s),e.enter(i),e.consume(g),e.exit(i),p):g===null||g===32||g===41||Ht(g)?n(g):(e.enter(r),e.enter(o),e.enter(a),e.enter("chunkString",{contentType:"string"}),y(g))}function p(g){return g===62?(e.enter(i),e.consume(g),e.exit(i),e.exit(s),e.exit(r),t):(e.enter(a),e.enter("chunkString",{contentType:"string"}),f(g))}function f(g){return g===62?(e.exit("chunkString"),e.exit(a),p(g)):g===null||g===60||K(g)?n(g):(e.consume(g),g===92?m:f)}function m(g){return g===60||g===62||g===92?(e.consume(g),f):f(g)}function y(g){return!c&&(g===null||g===41||ee(g))?(e.exit("chunkString"),e.exit(a),e.exit(o),e.exit(r),t(g)):c<u&&g===40?(e.consume(g),c++,y):g===41?(e.consume(g),c--,y):g===null||g===32||g===40||Ht(g)?n(g):(e.consume(g),g===92?b:y)}function b(g){return g===40||g===41||g===92?(e.consume(g),y):y(g)}}function jo(e,t,n,r,s,i){const o=this;let a=0,l;return u;function u(f){return e.enter(r),e.enter(s),e.consume(f),e.exit(s),e.enter(i),c}function c(f){return a>999||f===null||f===91||f===93&&!l||f===94&&!a&&"_hiddenFootnoteSupport"in o.parser.constructs?n(f):f===93?(e.exit(i),e.enter(s),e.consume(f),e.exit(s),e.exit(r),t):K(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),c):(e.enter("chunkString",{contentType:"string"}),d(f))}function d(f){return f===null||f===91||f===93||K(f)||a++>999?(e.exit("chunkString"),c(f)):(e.consume(f),l||(l=!Q(f)),f===92?p:d)}function p(f){return f===91||f===92||f===93?(e.consume(f),a++,d):d(f)}}function Do(e,t,n,r,s,i){let o;return a;function a(p){return p===34||p===39||p===40?(e.enter(r),e.enter(s),e.consume(p),e.exit(s),o=p===40?41:p,l):n(p)}function l(p){return p===o?(e.enter(s),e.consume(p),e.exit(s),e.exit(r),t):(e.enter(i),u(p))}function u(p){return p===o?(e.exit(i),l(o)):p===null?n(p):K(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),J(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),c(p))}function c(p){return p===o||p===null||K(p)?(e.exit("chunkString"),u(p)):(e.consume(p),p===92?d:c)}function d(p){return p===o||p===92?(e.consume(p),c):c(p)}}function vt(e,t){let n;return r;function r(s){return K(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),n=!0,r):Q(s)?J(e,r,n?"linePrefix":"lineSuffix")(s):t(s)}}const sh={name:"definition",tokenize:oh},ih={partial:!0,tokenize:ah};function oh(e,t,n){const r=this;let s;return i;function i(f){return e.enter("definition"),o(f)}function o(f){return jo.call(r,e,a,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function a(f){return s=Pe(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),l):n(f)}function l(f){return ee(f)?vt(e,u)(f):u(f)}function u(f){return Po(e,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function c(f){return e.attempt(ih,d,d)(f)}function d(f){return Q(f)?J(e,p,"whitespace")(f):p(f)}function p(f){return f===null||K(f)?(e.exit("definition"),r.parser.defined.push(s),t(f)):n(f)}}function ah(e,t,n){return r;function r(a){return ee(a)?vt(e,s)(a):n(a)}function s(a){return Do(e,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(a)}function i(a){return Q(a)?J(e,o,"whitespace")(a):o(a)}function o(a){return a===null||K(a)?t(a):n(a)}}const lh={name:"hardBreakEscape",tokenize:uh};function uh(e,t,n){return r;function r(i){return e.enter("hardBreakEscape"),e.consume(i),s}function s(i){return K(i)?(e.exit("hardBreakEscape"),t(i)):n(i)}}const ch={name:"headingAtx",resolve:dh,tokenize:hh};function dh(e,t){let n=e.length-2,r=3,s,i;return e[r][1].type==="whitespace"&&(r+=2),n-2>r&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&e[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(s={type:"atxHeadingText",start:e[r][1].start,end:e[n][1].end},i={type:"chunkText",start:e[r][1].start,end:e[n][1].end,contentType:"text"},Ie(e,r,n-r+1,[["enter",s,t],["enter",i,t],["exit",i,t],["exit",s,t]])),e}function hh(e,t,n){let r=0;return s;function s(c){return e.enter("atxHeading"),i(c)}function i(c){return e.enter("atxHeadingSequence"),o(c)}function o(c){return c===35&&r++<6?(e.consume(c),o):c===null||ee(c)?(e.exit("atxHeadingSequence"),a(c)):n(c)}function a(c){return c===35?(e.enter("atxHeadingSequence"),l(c)):c===null||K(c)?(e.exit("atxHeading"),t(c)):Q(c)?J(e,a,"whitespace")(c):(e.enter("atxHeadingText"),u(c))}function l(c){return c===35?(e.consume(c),l):(e.exit("atxHeadingSequence"),a(c))}function u(c){return c===null||c===35||ee(c)?(e.exit("atxHeadingText"),a(c)):(e.consume(c),u)}}const fh=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],gs=["pre","script","style","textarea"],ph={concrete:!0,name:"htmlFlow",resolveTo:yh,tokenize:xh},gh={partial:!0,tokenize:Sh},mh={partial:!0,tokenize:bh};function yh(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function xh(e,t,n){const r=this;let s,i,o,a,l;return u;function u(S){return c(S)}function c(S){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(S),d}function d(S){return S===33?(e.consume(S),p):S===47?(e.consume(S),i=!0,y):S===63?(e.consume(S),s=3,r.interrupt?t:x):be(S)?(e.consume(S),o=String.fromCharCode(S),b):n(S)}function p(S){return S===45?(e.consume(S),s=2,f):S===91?(e.consume(S),s=5,a=0,m):be(S)?(e.consume(S),s=4,r.interrupt?t:x):n(S)}function f(S){return S===45?(e.consume(S),r.interrupt?t:x):n(S)}function m(S){const he="CDATA[";return S===he.charCodeAt(a++)?(e.consume(S),a===he.length?r.interrupt?t:N:m):n(S)}function y(S){return be(S)?(e.consume(S),o=String.fromCharCode(S),b):n(S)}function b(S){if(S===null||S===47||S===62||ee(S)){const he=S===47,we=o.toLowerCase();return!he&&!i&&gs.includes(we)?(s=1,r.interrupt?t(S):N(S)):fh.includes(o.toLowerCase())?(s=6,he?(e.consume(S),g):r.interrupt?t(S):N(S)):(s=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(S):i?v(S):C(S))}return S===45||ge(S)?(e.consume(S),o+=String.fromCharCode(S),b):n(S)}function g(S){return S===62?(e.consume(S),r.interrupt?t:N):n(S)}function v(S){return Q(S)?(e.consume(S),v):w(S)}function C(S){return S===47?(e.consume(S),w):S===58||S===95||be(S)?(e.consume(S),A):Q(S)?(e.consume(S),C):w(S)}function A(S){return S===45||S===46||S===58||S===95||ge(S)?(e.consume(S),A):P(S)}function P(S){return S===61?(e.consume(S),T):Q(S)?(e.consume(S),P):C(S)}function T(S){return S===null||S===60||S===61||S===62||S===96?n(S):S===34||S===39?(e.consume(S),l=S,F):Q(S)?(e.consume(S),T):B(S)}function F(S){return S===l?(e.consume(S),l=null,z):S===null||K(S)?n(S):(e.consume(S),F)}function B(S){return S===null||S===34||S===39||S===47||S===60||S===61||S===62||S===96||ee(S)?P(S):(e.consume(S),B)}function z(S){return S===47||S===62||Q(S)?C(S):n(S)}function w(S){return S===62?(e.consume(S),D):n(S)}function D(S){return S===null||K(S)?N(S):Q(S)?(e.consume(S),D):n(S)}function N(S){return S===45&&s===2?(e.consume(S),U):S===60&&s===1?(e.consume(S),E):S===62&&s===4?(e.consume(S),ae):S===63&&s===3?(e.consume(S),x):S===93&&s===5?(e.consume(S),se):K(S)&&(s===6||s===7)?(e.exit("htmlFlowData"),e.check(gh,ie,$)(S)):S===null||K(S)?(e.exit("htmlFlowData"),$(S)):(e.consume(S),N)}function $(S){return e.check(mh,O,ie)(S)}function O(S){return e.enter("lineEnding"),e.consume(S),e.exit("lineEnding"),R}function R(S){return S===null||K(S)?$(S):(e.enter("htmlFlowData"),N(S))}function U(S){return S===45?(e.consume(S),x):N(S)}function E(S){return S===47?(e.consume(S),o="",W):N(S)}function W(S){if(S===62){const he=o.toLowerCase();return gs.includes(he)?(e.consume(S),ae):N(S)}return be(S)&&o.length<8?(e.consume(S),o+=String.fromCharCode(S),W):N(S)}function se(S){return S===93?(e.consume(S),x):N(S)}function x(S){return S===62?(e.consume(S),ae):S===45&&s===2?(e.consume(S),x):N(S)}function ae(S){return S===null||K(S)?(e.exit("htmlFlowData"),ie(S)):(e.consume(S),ae)}function ie(S){return e.exit("htmlFlow"),t(S)}}function bh(e,t,n){const r=this;return s;function s(o){return K(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),i):n(o)}function i(o){return r.parser.lazy[r.now().line]?n(o):t(o)}}function Sh(e,t,n){return r;function r(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),e.attempt(Lt,t,n)}}const kh={name:"htmlText",tokenize:vh};function vh(e,t,n){const r=this;let s,i,o;return a;function a(x){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(x),l}function l(x){return x===33?(e.consume(x),u):x===47?(e.consume(x),P):x===63?(e.consume(x),C):be(x)?(e.consume(x),B):n(x)}function u(x){return x===45?(e.consume(x),c):x===91?(e.consume(x),i=0,m):be(x)?(e.consume(x),v):n(x)}function c(x){return x===45?(e.consume(x),f):n(x)}function d(x){return x===null?n(x):x===45?(e.consume(x),p):K(x)?(o=d,E(x)):(e.consume(x),d)}function p(x){return x===45?(e.consume(x),f):d(x)}function f(x){return x===62?U(x):x===45?p(x):d(x)}function m(x){const ae="CDATA[";return x===ae.charCodeAt(i++)?(e.consume(x),i===ae.length?y:m):n(x)}function y(x){return x===null?n(x):x===93?(e.consume(x),b):K(x)?(o=y,E(x)):(e.consume(x),y)}function b(x){return x===93?(e.consume(x),g):y(x)}function g(x){return x===62?U(x):x===93?(e.consume(x),g):y(x)}function v(x){return x===null||x===62?U(x):K(x)?(o=v,E(x)):(e.consume(x),v)}function C(x){return x===null?n(x):x===63?(e.consume(x),A):K(x)?(o=C,E(x)):(e.consume(x),C)}function A(x){return x===62?U(x):C(x)}function P(x){return be(x)?(e.consume(x),T):n(x)}function T(x){return x===45||ge(x)?(e.consume(x),T):F(x)}function F(x){return K(x)?(o=F,E(x)):Q(x)?(e.consume(x),F):U(x)}function B(x){return x===45||ge(x)?(e.consume(x),B):x===47||x===62||ee(x)?z(x):n(x)}function z(x){return x===47?(e.consume(x),U):x===58||x===95||be(x)?(e.consume(x),w):K(x)?(o=z,E(x)):Q(x)?(e.consume(x),z):U(x)}function w(x){return x===45||x===46||x===58||x===95||ge(x)?(e.consume(x),w):D(x)}function D(x){return x===61?(e.consume(x),N):K(x)?(o=D,E(x)):Q(x)?(e.consume(x),D):z(x)}function N(x){return x===null||x===60||x===61||x===62||x===96?n(x):x===34||x===39?(e.consume(x),s=x,$):K(x)?(o=N,E(x)):Q(x)?(e.consume(x),N):(e.consume(x),O)}function $(x){return x===s?(e.consume(x),s=void 0,R):x===null?n(x):K(x)?(o=$,E(x)):(e.consume(x),$)}function O(x){return x===null||x===34||x===39||x===60||x===61||x===96?n(x):x===47||x===62||ee(x)?z(x):(e.consume(x),O)}function R(x){return x===47||x===62||ee(x)?z(x):n(x)}function U(x){return x===62?(e.consume(x),e.exit("htmlTextData"),e.exit("htmlText"),t):n(x)}function E(x){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),W}function W(x){return Q(x)?J(e,se,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(x):se(x)}function se(x){return e.enter("htmlTextData"),o(x)}}const Ir={name:"labelEnd",resolveAll:Ih,resolveTo:Mh,tokenize:Rh},wh={tokenize:Eh},Ch={tokenize:Ah},Th={tokenize:Lh};function Ih(e){let t=-1;const n=[];for(;++t<e.length;){const r=e[t][1];if(n.push(e[t]),r.type==="labelImage"||r.type==="labelLink"||r.type==="labelEnd"){const s=r.type==="labelImage"?4:2;r.type="data",t+=s}}return e.length!==n.length&&Ie(e,0,e.length,n),e}function Mh(e,t){let n=e.length,r=0,s,i,o,a;for(;n--;)if(s=e[n][1],i){if(s.type==="link"||s.type==="labelLink"&&s._inactive)break;e[n][0]==="enter"&&s.type==="labelLink"&&(s._inactive=!0)}else if(o){if(e[n][0]==="enter"&&(s.type==="labelImage"||s.type==="labelLink")&&!s._balanced&&(i=n,s.type!=="labelLink")){r=2;break}}else s.type==="labelEnd"&&(o=n);const l={type:e[i][1].type==="labelLink"?"link":"image",start:{...e[i][1].start},end:{...e[e.length-1][1].end}},u={type:"label",start:{...e[i][1].start},end:{...e[o][1].end}},c={type:"labelText",start:{...e[i+r+2][1].end},end:{...e[o-2][1].start}};return a=[["enter",l,t],["enter",u,t]],a=Ae(a,e.slice(i+1,i+r+3)),a=Ae(a,[["enter",c,t]]),a=Ae(a,nn(t.parser.constructs.insideSpan.null,e.slice(i+r+4,o-3),t)),a=Ae(a,[["exit",c,t],e[o-2],e[o-1],["exit",u,t]]),a=Ae(a,e.slice(o+1)),a=Ae(a,[["exit",l,t]]),Ie(e,i,e.length,a),e}function Rh(e,t,n){const r=this;let s=r.events.length,i,o;for(;s--;)if((r.events[s][1].type==="labelImage"||r.events[s][1].type==="labelLink")&&!r.events[s][1]._balanced){i=r.events[s][1];break}return a;function a(p){return i?i._inactive?d(p):(o=r.parser.defined.includes(Pe(r.sliceSerialize({start:i.end,end:r.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(p),e.exit("labelMarker"),e.exit("labelEnd"),l):n(p)}function l(p){return p===40?e.attempt(wh,c,o?c:d)(p):p===91?e.attempt(Ch,c,o?u:d)(p):o?c(p):d(p)}function u(p){return e.attempt(Th,c,d)(p)}function c(p){return t(p)}function d(p){return i._balanced=!0,n(p)}}function Eh(e,t,n){return r;function r(d){return e.enter("resource"),e.enter("resourceMarker"),e.consume(d),e.exit("resourceMarker"),s}function s(d){return ee(d)?vt(e,i)(d):i(d)}function i(d){return d===41?c(d):Po(e,o,a,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(d)}function o(d){return ee(d)?vt(e,l)(d):c(d)}function a(d){return n(d)}function l(d){return d===34||d===39||d===40?Do(e,u,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(d):c(d)}function u(d){return ee(d)?vt(e,c)(d):c(d)}function c(d){return d===41?(e.enter("resourceMarker"),e.consume(d),e.exit("resourceMarker"),e.exit("resource"),t):n(d)}}function Ah(e,t,n){const r=this;return s;function s(a){return jo.call(r,e,i,o,"reference","referenceMarker","referenceString")(a)}function i(a){return r.parser.defined.includes(Pe(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(a):n(a)}function o(a){return n(a)}}function Lh(e,t,n){return r;function r(i){return e.enter("reference"),e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),s}function s(i){return i===93?(e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),e.exit("reference"),t):n(i)}}const Nh={name:"labelStartImage",resolveAll:Ir.resolveAll,tokenize:Ph};function Ph(e,t,n){const r=this;return s;function s(a){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(a),e.exit("labelImageMarker"),i}function i(a){return a===91?(e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelImage"),o):n(a)}function o(a){return a===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(a):t(a)}}const jh={name:"labelStartLink",resolveAll:Ir.resolveAll,tokenize:Dh};function Dh(e,t,n){const r=this;return s;function s(o){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelLink"),i}function i(o){return o===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(o):t(o)}}const gn={name:"lineEnding",tokenize:_h};function _h(e,t){return n;function n(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),J(e,t,"linePrefix")}}const Kt={name:"thematicBreak",tokenize:Oh};function Oh(e,t,n){let r=0,s;return i;function i(u){return e.enter("thematicBreak"),o(u)}function o(u){return s=u,a(u)}function a(u){return u===s?(e.enter("thematicBreakSequence"),l(u)):r>=3&&(u===null||K(u))?(e.exit("thematicBreak"),t(u)):n(u)}function l(u){return u===s?(e.consume(u),r++,l):(e.exit("thematicBreakSequence"),Q(u)?J(e,a,"whitespace")(u):a(u))}}const ke={continuation:{tokenize:$h},exit:Uh,name:"list",tokenize:Bh},Fh={partial:!0,tokenize:Vh},zh={partial:!0,tokenize:Kh};function Bh(e,t,n){const r=this,s=r.events[r.events.length-1];let i=s&&s[1].type==="linePrefix"?s[2].sliceSerialize(s[1],!0).length:0,o=0;return a;function a(f){const m=r.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(m==="listUnordered"?!r.containerState.marker||f===r.containerState.marker:qn(f)){if(r.containerState.type||(r.containerState.type=m,e.enter(m,{_container:!0})),m==="listUnordered")return e.enter("listItemPrefix"),f===42||f===45?e.check(Kt,n,u)(f):u(f);if(!r.interrupt||f===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),l(f)}return n(f)}function l(f){return qn(f)&&++o<10?(e.consume(f),l):(!r.interrupt||o<2)&&(r.containerState.marker?f===r.containerState.marker:f===41||f===46)?(e.exit("listItemValue"),u(f)):n(f)}function u(f){return e.enter("listItemMarker"),e.consume(f),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||f,e.check(Lt,r.interrupt?n:c,e.attempt(Fh,p,d))}function c(f){return r.containerState.initialBlankLine=!0,i++,p(f)}function d(f){return Q(f)?(e.enter("listItemPrefixWhitespace"),e.consume(f),e.exit("listItemPrefixWhitespace"),p):n(f)}function p(f){return r.containerState.size=i+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(f)}}function $h(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(Lt,s,i);function s(a){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,J(e,t,"listItemIndent",r.containerState.size+1)(a)}function i(a){return r.containerState.furtherBlankLines||!Q(a)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,o(a)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(zh,t,o)(a))}function o(a){return r.containerState._closeFlow=!0,r.interrupt=void 0,J(e,e.attempt(ke,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a)}}function Kh(e,t,n){const r=this;return J(e,s,"listItemIndent",r.containerState.size+1);function s(i){const o=r.events[r.events.length-1];return o&&o[1].type==="listItemIndent"&&o[2].sliceSerialize(o[1],!0).length===r.containerState.size?t(i):n(i)}}function Uh(e){e.exit(this.containerState.type)}function Vh(e,t,n){const r=this;return J(e,s,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function s(i){const o=r.events[r.events.length-1];return!Q(i)&&o&&o[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const ms={name:"setextUnderline",resolveTo:Hh,tokenize:qh};function Hh(e,t){let n=e.length,r,s,i;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){r=n;break}e[n][1].type==="paragraph"&&(s=n)}else e[n][1].type==="content"&&e.splice(n,1),!i&&e[n][1].type==="definition"&&(i=n);const o={type:"setextHeading",start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[s][1].type="setextHeadingText",i?(e.splice(s,0,["enter",o,t]),e.splice(i+1,0,["exit",e[r][1],t]),e[r][1].end={...e[i][1].end}):e[r][1]=o,e.push(["exit",o,t]),e}function qh(e,t,n){const r=this;let s;return i;function i(u){let c=r.events.length,d;for(;c--;)if(r.events[c][1].type!=="lineEnding"&&r.events[c][1].type!=="linePrefix"&&r.events[c][1].type!=="content"){d=r.events[c][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||d)?(e.enter("setextHeadingLine"),s=u,o(u)):n(u)}function o(u){return e.enter("setextHeadingLineSequence"),a(u)}function a(u){return u===s?(e.consume(u),a):(e.exit("setextHeadingLineSequence"),Q(u)?J(e,l,"lineSuffix")(u):l(u))}function l(u){return u===null||K(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const Wh={tokenize:Gh};function Gh(e){const t=this,n=e.attempt(Lt,r,e.attempt(this.parser.constructs.flowInitial,s,J(e,e.attempt(this.parser.constructs.flow,s,e.attempt(Zd,s)),"linePrefix")));return n;function r(i){if(i===null){e.consume(i);return}return e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function s(i){if(i===null){e.consume(i);return}return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const Qh={resolveAll:Oo()},Xh=_o("string"),Yh=_o("text");function _o(e){return{resolveAll:Oo(e==="text"?Jh:void 0),tokenize:t};function t(n){const r=this,s=this.parser.constructs[e],i=n.attempt(s,o,a);return o;function o(c){return u(c)?i(c):a(c)}function a(c){if(c===null){n.consume(c);return}return n.enter("data"),n.consume(c),l}function l(c){return u(c)?(n.exit("data"),i(c)):(n.consume(c),l)}function u(c){if(c===null)return!0;const d=s[c];let p=-1;if(d)for(;++p<d.length;){const f=d[p];if(!f.previous||f.previous.call(r,r.previous))return!0}return!1}}}function Oo(e){return t;function t(n,r){let s=-1,i;for(;++s<=n.length;)i===void 0?n[s]&&n[s][1].type==="data"&&(i=s,s++):(!n[s]||n[s][1].type!=="data")&&(s!==i+2&&(n[i][1].end=n[s-1][1].end,n.splice(i+2,s-i-2),s=i+2),i=void 0);return e?e(n,r):n}}function Jh(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type==="lineEnding")&&e[n-1][1].type==="data"){const r=e[n-1][1],s=t.sliceStream(r);let i=s.length,o=-1,a=0,l;for(;i--;){const u=s[i];if(typeof u=="string"){for(o=u.length;u.charCodeAt(o-1)===32;)a++,o--;if(o)break;o=-1}else if(u===-2)l=!0,a++;else if(u!==-1){i++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(a=0),a){const u={type:n===e.length||l||a<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:i?o:r.start._bufferIndex+o,_index:r.start._index+i,line:r.end.line,column:r.end.column-a,offset:r.end.offset-a},end:{...r.end}};r.end={...u.start},r.start.offset===r.end.offset?Object.assign(r,u):(e.splice(n,0,["enter",u,t],["exit",u,t]),n+=2)}n++}return e}const Zh={42:ke,43:ke,45:ke,48:ke,49:ke,50:ke,51:ke,52:ke,53:ke,54:ke,55:ke,56:ke,57:ke,62:Eo},ef={91:sh},tf={[-2]:pn,[-1]:pn,32:pn},nf={35:ch,42:Kt,45:[ms,Kt],60:ph,61:ms,95:Kt,96:ps,126:ps},rf={38:Lo,92:Ao},sf={[-5]:gn,[-4]:gn,[-3]:gn,33:Nh,38:Lo,42:Wn,60:[jd,kh],91:jh,92:[lh,Ao],93:Ir,95:Wn,96:Wd},of={null:[Wn,Qh]},af={null:[42,95]},lf={null:[]},uf=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:af,contentInitial:ef,disable:lf,document:Zh,flow:nf,flowInitial:tf,insideSpan:of,string:rf,text:sf},Symbol.toStringTag,{value:"Module"}));function cf(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const s={},i=[];let o=[],a=[];const l={attempt:F(P),check:F(T),consume:v,enter:C,exit:A,interrupt:F(T,{interrupt:!0})},u={code:null,containerState:{},defineSkip:y,events:[],now:m,parser:e,previous:null,sliceSerialize:p,sliceStream:f,write:d};let c=t.tokenize.call(u,l);return t.resolveAll&&i.push(t),u;function d(D){return o=Ae(o,D),b(),o[o.length-1]!==null?[]:(B(t,0),u.events=nn(i,u.events,u),u.events)}function p(D,N){return hf(f(D),N)}function f(D){return df(o,D)}function m(){const{_bufferIndex:D,_index:N,line:$,column:O,offset:R}=r;return{_bufferIndex:D,_index:N,line:$,column:O,offset:R}}function y(D){s[D.line]=D.column,w()}function b(){let D;for(;r._index<o.length;){const N=o[r._index];if(typeof N=="string")for(D=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===D&&r._bufferIndex<N.length;)g(N.charCodeAt(r._bufferIndex));else g(N)}}function g(D){c=c(D)}function v(D){K(D)?(r.line++,r.column=1,r.offset+=D===-3?2:1,w()):D!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===o[r._index].length&&(r._bufferIndex=-1,r._index++)),u.previous=D}function C(D,N){const $=N||{};return $.type=D,$.start=m(),u.events.push(["enter",$,u]),a.push($),$}function A(D){const N=a.pop();return N.end=m(),u.events.push(["exit",N,u]),N}function P(D,N){B(D,N.from)}function T(D,N){N.restore()}function F(D,N){return $;function $(O,R,U){let E,W,se,x;return Array.isArray(O)?ie(O):"tokenize"in O?ie([O]):ae(O);function ae(oe){return pe;function pe(Se){const Me=Se!==null&&oe[Se],Re=Se!==null&&oe.null,je=[...Array.isArray(Me)?Me:Me?[Me]:[],...Array.isArray(Re)?Re:Re?[Re]:[]];return ie(je)(Se)}}function ie(oe){return E=oe,W=0,oe.length===0?U:S(oe[W])}function S(oe){return pe;function pe(Se){return x=z(),se=oe,oe.partial||(u.currentConstruct=oe),oe.name&&u.parser.constructs.disable.null.includes(oe.name)?we():oe.tokenize.call(N?Object.assign(Object.create(u),N):u,l,he,we)(Se)}}function he(oe){return D(se,x),R}function we(oe){return x.restore(),++W<E.length?S(E[W]):U}}}function B(D,N){D.resolveAll&&!i.includes(D)&&i.push(D),D.resolve&&Ie(u.events,N,u.events.length-N,D.resolve(u.events.slice(N),u)),D.resolveTo&&(u.events=D.resolveTo(u.events,u))}function z(){const D=m(),N=u.previous,$=u.currentConstruct,O=u.events.length,R=Array.from(a);return{from:O,restore:U};function U(){r=D,u.previous=N,u.currentConstruct=$,u.events.length=O,a=R,w()}}function w(){r.line in s&&r.column<2&&(r.column=s[r.line],r.offset+=s[r.line]-1)}}function df(e,t){const n=t.start._index,r=t.start._bufferIndex,s=t.end._index,i=t.end._bufferIndex;let o;if(n===s)o=[e[n].slice(r,i)];else{if(o=e.slice(n,s),r>-1){const a=o[0];typeof a=="string"?o[0]=a.slice(r):o.shift()}i>0&&o.push(e[s].slice(0,i))}return o}function hf(e,t){let n=-1;const r=[];let s;for(;++n<e.length;){const i=e[n];let o;if(typeof i=="string")o=i;else switch(i){case-5:{o="\r";break}case-4:{o=`
4
4
  `;break}case-3:{o=`\r
@@ -34,7 +34,7 @@ var qa=Object.defineProperty;var Wa=(e,t,n)=>t in e?qa(e,t,{enumerable:!0,config
34
34
  `)?h.jsx("code",{...i,className:de("chat-inline-code",r),children:s}):h.jsx(uy,{className:r,texts:e.texts,children:s})}}),[e.texts]);return h.jsx("div",{className:de("chat-markdown",t?"chat-markdown-user":"chat-markdown-assistant"),children:h.jsx($p,{skipHtml:!0,remarkPlugins:[ey],components:n,children:dy(e.text)})})}function py(e){return h.jsxs("details",{className:"mt-3",open:!0,children:[h.jsx("summary",{className:de("cursor-pointer text-xs",e.isUser?"text-primary-100":"text-gray-500"),children:e.label}),h.jsx("pre",{className:de("mt-2 whitespace-pre-wrap break-words rounded-lg p-2 text-[11px]",e.isUser?"bg-primary-700/60":"bg-gray-100"),children:e.text})]})}const Vs=220;function gy(e){const t=e.toLowerCase();return t.includes("exec")||t.includes("shell")||t.includes("command")?h.jsx(yl,{className:"h-3.5 w-3.5"}):t.includes("search")?h.jsx(ur,{className:"h-3.5 w-3.5"}):t.includes("fetch")||t.includes("http")||t.includes("web")?h.jsx(xl,{className:"h-3.5 w-3.5"}):t.includes("read")||t.includes("file")?h.jsx(bl,{className:"h-3.5 w-3.5"}):t.includes("message")||t.includes("send")?h.jsx(Sl,{className:"h-3.5 w-3.5"}):t.includes("cron")||t.includes("schedule")?h.jsx(kl,{className:"h-3.5 w-3.5"}):h.jsx(vi,{className:"h-3.5 w-3.5"})}function my({card:e}){var i;const t=((i=e.output)==null?void 0:i.trim())??"",n=t.length>Vs||t.includes(`
35
35
  `),r=n?`${t.slice(0,Vs)}...`:t,s=e.kind==="result"||e.hasResult;return h.jsxs("div",{className:"rounded-xl border border-amber-200/80 bg-amber-50/60 px-3 py-2.5",children:[h.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs font-semibold text-amber-800",children:[gy(e.toolName),h.jsx("span",{children:e.titleLabel}),h.jsx("span",{className:"font-mono text-[11px] text-amber-900/80",children:e.toolName})]}),e.summary?h.jsx("div",{className:"mt-1 break-words font-mono text-[11px] text-amber-800/90",children:e.summary}):null,s?h.jsx("div",{className:"mt-2",children:t?n?h.jsxs("details",{className:"group",children:[h.jsx("summary",{className:"cursor-pointer text-[11px] text-amber-700",children:e.outputLabel}),h.jsx("pre",{className:"mt-2 whitespace-pre-wrap break-words rounded-lg border border-amber-200 bg-amber-100/40 p-2 text-[11px] text-amber-900",children:t})]}):h.jsx("pre",{className:"rounded-lg border border-amber-200 bg-amber-100/40 p-2 text-[11px] whitespace-pre-wrap break-words text-amber-900",children:r}):h.jsx("div",{className:"text-[11px] text-amber-700/80",children:e.emptyLabel})}):null]})}function yy(e){return h.jsxs("div",{className:"rounded-lg border border-gray-200 bg-gray-50 px-2.5 py-2 text-xs text-gray-600",children:[h.jsxs("div",{className:"font-semibold text-gray-700",children:[e.label,": ",e.rawType]}),e.text?h.jsx("pre",{className:"mt-1 whitespace-pre-wrap break-words text-[11px] text-gray-500",children:e.text}):null]})}function xy(e){const{message:t,texts:n}=e,{role:r}=t,s=r==="user";return h.jsx("div",{className:de("inline-block w-fit max-w-full rounded-2xl border px-4 py-3 shadow-sm",s?"border-primary bg-primary text-white":r==="assistant"?"border-gray-200 bg-white text-gray-900":"border-orange-200/80 bg-orange-50/70 text-gray-900"),children:h.jsx("div",{className:"space-y-2",children:t.parts.map((i,o)=>i.type==="markdown"?h.jsx(fy,{text:i.text,role:r,texts:n},`markdown-${o}`):i.type==="reasoning"?h.jsx(py,{label:i.label,text:i.text,isUser:s},`reasoning-${o}`):i.type==="tool-card"?h.jsx("div",{className:"mt-0.5",children:h.jsx(my,{card:i.card})},`tool-${o}`):i.type==="unknown"?h.jsx(yy,{label:i.label,rawType:i.rawType,text:i.text},`unknown-${o}`):null)})})}function by(e){return h.jsxs("div",{className:de("px-1 text-[11px] leading-4 text-gray-400",e.isUser?"text-right":"text-left"),children:[e.roleLabel," · ",e.timestampLabel]})}const Sy=/\u200B|\u200C|\u200D|\u2060|\uFEFF/g;function ky(e){const t=e.trim();return t?t.replace(Sy,"").trim().length>0:!1}function vy(e){return e.parts.some(t=>t.type==="markdown"||t.type==="reasoning"?ky(t.text):!0)}function wy(e){const t=e.messages.filter(vy),n=t.some(r=>r.role==="assistant"&&(r.status==="streaming"||r.status==="pending"));return h.jsxs("div",{className:de("space-y-5",e.className),children:[t.map(r=>{const s=r.role==="user";return h.jsxs("div",{className:de("flex gap-3",s?"justify-end":"justify-start"),children:[s?null:h.jsx(cn,{role:r.role}),h.jsxs("div",{className:de("w-fit max-w-[92%] space-y-2",s&&"flex flex-col items-end"),children:[h.jsx(xy,{message:r,texts:e.texts}),h.jsx(by,{roleLabel:r.roleLabel,timestampLabel:r.timestampLabel,isUser:s})]}),s?h.jsx(cn,{role:r.role}):null]},r.id)}),e.isSending&&!n?h.jsxs("div",{className:"flex justify-start gap-3",children:[h.jsx(cn,{role:"assistant"}),h.jsx("div",{className:"rounded-2xl border border-gray-200 bg-white px-4 py-3 text-sm text-gray-500 shadow-sm",children:e.texts.typingLabel})]}):null]})}const Cy=10;function Hs(e){e.scrollTop=e.scrollHeight}function Ty(e){const t=k.useRef(!0),n=k.useRef(!1),r=k.useRef(null),s=k.useRef(!1),i=k.useCallback(()=>{if(n.current){n.current=!1;return}const o=e.scrollRef.current;if(!o)return;const a=o.scrollHeight-o.scrollTop-o.clientHeight;t.current=a<=(e.stickyThresholdPx??Cy)},[e.scrollRef,e.stickyThresholdPx]);return k.useEffect(()=>{r.current!==e.resetKey&&(r.current=e.resetKey,t.current=!0,s.current=!0)},[e.resetKey]),k.useLayoutEffect(()=>{if(!s.current||e.isLoading||!e.hasContent)return;const o=e.scrollRef.current;o&&(s.current=!1,n.current=!0,Hs(o))},[e.hasContent,e.isLoading,e.scrollRef]),k.useLayoutEffect(()=>{if(!t.current||!e.hasContent)return;const o=e.scrollRef.current;o&&(n.current=!0,Hs(o))},[e.contentVersion,e.hasContent,e.scrollRef]),{onScroll:i}}function _r(){return mr()}function xa(e){return ac(e)}function ba(e){return uc(e)}function Sa(e){return yr(e,"skill")}function ka(e,t,n){const r=new Set(t),s=ao(e,l=>l.tokenKind==="skill"&&!r.has(l.tokenKey)),i=yr(s,"skill"),o=new Map(n.map(l=>[l.spec,l])),a=t.filter(l=>!i.includes(l)).map(l=>{var u;return gr({tokenKind:"skill",tokenKey:l,label:((u=o.get(l))==null?void 0:u.label)||l})});return a.length===0?s:ut([...s,...a])}const Iy={isProviderStateResolved:!1,composerNodes:_r(),draft:"",pendingSessionType:"native",defaultSessionType:"native",canStopGeneration:!1,stopDisabledReason:null,sendError:null,isSending:!1,modelOptions:[],selectedModel:"",selectedThinkingLevel:null,sessionTypeOptions:[],selectedSessionType:void 0,stopSupported:!1,stopReason:void 0,canEditSessionType:!1,sessionTypeUnavailable:!1,skillRecords:[],isSkillsLoading:!1,selectedSkills:[]},H=Yt(e=>({snapshot:Iy,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))})),My={sessionRunStatusByKey:new Map,isLocallyRunning:!1,activeBackendRunId:null},Zn=Yt(e=>({snapshot:My,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))})),Ry={sessions:[],selectedSessionKey:null,selectedAgentId:"main",query:"",isLoading:!1},re=Yt(e=>({snapshot:Ry,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))}));function Ey(e){const t=new Date,n=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime(),r=n-864e5,s=n-7*864e5,i=[],o=[],a=[],l=[];for(const c of e){const d=new Date(c.updatedAt).getTime();d>=n?i.push(c):d>=r?o.push(c):d>=s?a.push(c):l.push(c)}const u=[];return i.length>0&&u.push({label:I("chatSidebarToday"),sessions:i}),o.length>0&&u.push({label:I("chatSidebarYesterday"),sessions:o}),a.length>0&&u.push({label:I("chatSidebarPrevious7Days"),sessions:a}),l.length>0&&u.push({label:I("chatSidebarOlder"),sessions:l}),u}function Ay(e){if(e.label&&e.label.trim())return e.label.trim();const t=e.key.split(":");return t[t.length-1]||e.key}function Ly(e,t){const n=e.trim().toLowerCase();if(!n||n==="native")return null;const r=t.find(s=>s.value.trim().toLowerCase()===n);return r!=null&&r.label.trim()?r.label.trim():n.split(/[-_]+/g).filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")}function Ny(e){var t;return e.ready===!1?((t=e.reasonMessage)==null?void 0:t.trim())||I("statusSetup"):I("statusReady")}const Py=[{target:"/cron",label:()=>I("chatSidebarScheduledTasks"),icon:cr},{target:"/skills",label:()=>I("chatSidebarSkills"),icon:lr}];function jy(){var R,U;const e=pr(),t=Fl(),n=Jt(),[r,s]=k.useState(!1),[i,o]=k.useState(null),[a,l]=k.useState(""),[u,c]=k.useState(null),d=H(E=>E.snapshot),p=re(E=>E.snapshot),f=Zn(E=>E.snapshot),m=zl(E=>E.connectionStatus),{language:y,setLanguage:b}=fr(),{theme:g,setTheme:v}=Bl(),C=_u(),A=Fi(n.search),P=I(((R=Kr.find(E=>E.value===g))==null?void 0:R.labelKey)??"themeWarm"),T=((U=Ur.find(E=>E.value===y))==null?void 0:U.label)??y,F=k.useMemo(()=>Ey(p.sessions),[p.sessions]),B=d.defaultSessionType||"native",z=k.useMemo(()=>d.sessionTypeOptions.filter(E=>E.value!==B),[B,d.sessionTypeOptions]),w=E=>{y!==E&&(b(E),window.location.reload())},D=(E,W)=>{const{sessions:se}=re.getState().snapshot;re.getState().setSnapshot({sessions:se.map(x=>x.key===E?{...x,...W?{label:W}:{label:void 0}}:x)})},N=E=>{var W;o(E.key),l(((W=E.label)==null?void 0:W.trim())??"")},$=()=>{o(null),l(""),c(null)},O=async E=>{var x;const W=a.trim(),se=((x=E.label)==null?void 0:x.trim())??"";if(W===se){$();return}c(E.key);try{await C({chatChain:A,sessionKey:E.key,label:W||null}),D(E.key,W||void 0),$()}catch{c(null)}};return h.jsxs("aside",{className:"w-[280px] shrink-0 flex flex-col h-full bg-secondary border-r border-gray-200/60",children:[h.jsx("div",{className:"px-5 pt-5 pb-3",children:h.jsx($l,{className:"flex items-center gap-2.5 min-w-0",suffix:h.jsx(ju,{status:m})})}),h.jsx("div",{className:"px-4 pb-3",children:h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsxs(He,{variant:"primary",className:xe("min-w-0 rounded-xl",z.length>0?"flex-1 rounded-r-md":"w-full"),onClick:()=>{s(!1),e.chatSessionListManager.createSession(B)},children:[h.jsx(vl,{className:"h-4 w-4 mr-2"}),I("chatSidebarNewTask")]}),z.length>0?h.jsxs(bu,{open:r,onOpenChange:s,children:[h.jsx(Su,{asChild:!0,children:h.jsx(He,{variant:"primary",size:"icon",className:"h-9 w-10 shrink-0 rounded-xl rounded-l-md","aria-label":I("chatSessionTypeLabel"),children:h.jsx(ar,{className:"h-4 w-4"})})}),h.jsxs(ku,{align:"end",className:"w-64 p-2",children:[h.jsx("div",{className:"px-2 py-1 text-[11px] font-medium uppercase tracking-wider text-gray-400",children:I("chatSessionTypeLabel")}),h.jsx("div",{className:"mt-1 space-y-1",children:z.map(E=>h.jsxs("button",{type:"button",onClick:()=>{e.chatSessionListManager.createSession(E.value),s(!1)},className:"w-full rounded-xl px-3 py-2 text-left transition-colors hover:bg-gray-100",children:[h.jsxs("div",{className:"flex items-center justify-between gap-3",children:[h.jsx("div",{className:"text-[13px] font-medium text-gray-900",children:E.label}),h.jsx("span",{className:xe("shrink-0 rounded-full px-2 py-0.5 text-[10px] font-semibold",E.ready===!1?"bg-amber-100 text-amber-800":"bg-emerald-100 text-emerald-700"),children:E.ready===!1?I("statusSetup"):I("statusReady")})]}),h.jsx("div",{className:"mt-0.5 text-[11px] text-gray-500",children:Ny(E)})]},E.value))})]})]}):null]})}),h.jsx("div",{className:"px-4 pb-3",children:h.jsxs("div",{className:"relative",children:[h.jsx(ur,{className:"h-3.5 w-3.5 absolute left-3 top-2.5 text-gray-400"}),h.jsx(hr,{value:p.query,onChange:E=>e.chatSessionListManager.setQuery(E.target.value),placeholder:I("chatSidebarSearchPlaceholder"),className:"pl-8 h-9 rounded-lg text-xs"})]})}),h.jsx("div",{className:"px-3 pb-2",children:h.jsx("ul",{className:"space-y-0.5",children:Py.map(E=>{const W=E.icon;return h.jsx("li",{children:h.jsx($r,{to:E.target,className:({isActive:se})=>xe("group w-full flex items-center gap-3 px-3 py-2 rounded-xl text-[13px] font-medium transition-all duration-150",se?"bg-gray-200 text-gray-900 font-semibold shadow-sm":"text-gray-600 hover:bg-gray-200/60 hover:text-gray-900"),children:({isActive:se})=>h.jsxs(h.Fragment,{children:[h.jsx(W,{className:xe("h-4 w-4 transition-colors",se?"text-gray-900":"text-gray-500 group-hover:text-gray-800")}),h.jsx("span",{children:E.label()})]})})},E.target)})})}),h.jsx("div",{className:"mx-4 border-t border-gray-200/60"}),h.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto custom-scrollbar px-3 py-2",children:p.isLoading?h.jsx("div",{className:"text-xs text-gray-500 p-3",children:I("sessionsLoading")}):F.length===0?h.jsxs("div",{className:"p-4 text-center",children:[h.jsx(wl,{className:"h-6 w-6 mx-auto mb-2 text-gray-300"}),h.jsx("div",{className:"text-xs text-gray-500",children:I("sessionsEmpty")})]}):h.jsx("div",{className:"space-y-3",children:F.map(E=>h.jsxs("div",{children:[h.jsx("div",{className:"px-2 py-1 text-[11px] font-medium text-gray-400 uppercase tracking-wider",children:E.label}),h.jsx("div",{className:"space-y-0.5",children:E.sessions.map(W=>{const se=p.selectedSessionKey===W.key,x=f.sessionRunStatusByKey.get(W.key),ae=Ly(W.sessionType,d.sessionTypeOptions),ie=i===W.key,S=u===W.key;return h.jsx(Du,{session:W,active:se,runStatus:x,sessionTypeLabel:ae,title:Ay(W),isEditing:ie,draftLabel:a,isSaving:S,onSelect:()=>e.chatSessionListManager.selectSession(W.key),onStartEditing:()=>N(W),onDraftLabelChange:l,onSave:()=>O(W),onCancel:$},W.key)})})]},E.label))})}),h.jsxs("div",{className:"px-3 py-3 border-t border-gray-200/60 space-y-0.5",children:[h.jsx($r,{to:"/settings",className:({isActive:E})=>xe("group w-full flex items-center gap-2.5 px-3 py-2 rounded-xl text-[13px] font-medium transition-all duration-150",E?"bg-gray-200 text-gray-900 font-semibold shadow-sm":"text-gray-600 hover:bg-gray-200/60 hover:text-gray-900"),children:({isActive:E})=>h.jsxs(h.Fragment,{children:[h.jsx(Cl,{className:xe("h-4 w-4 transition-colors",E?"text-gray-900":"text-gray-500 group-hover:text-gray-800")}),h.jsx("span",{children:I("settings")})]})}),h.jsxs("button",{onClick:()=>t.open(void 0,{kind:"docs",newTab:!0,title:"Docs"}),className:"w-full flex items-center gap-2.5 px-3 py-2 rounded-xl text-[13px] font-medium transition-all duration-150 text-gray-600 hover:bg-gray-200/60 hover:text-gray-800",children:[h.jsx(Tl,{className:"h-4 w-4 text-gray-400"}),h.jsx("span",{children:I("docBrowserHelp")})]}),h.jsxs(Fn,{value:g,onValueChange:E=>v(E),children:[h.jsxs(zn,{className:"w-full h-auto rounded-xl border-0 bg-transparent shadow-none px-3 py-2 text-[13px] font-medium text-gray-600 hover:bg-gray-200/60 focus:ring-0",children:[h.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[h.jsx(Il,{className:"h-4 w-4 text-gray-400"}),h.jsx("span",{children:I("theme")})]}),h.jsx("span",{className:"ml-auto text-[11px] text-gray-500",children:P})]}),h.jsx(Bn,{children:Kr.map(E=>h.jsx(St,{value:E.value,className:"text-xs",children:I(E.labelKey)},E.value))})]}),h.jsxs(Fn,{value:y,onValueChange:E=>w(E),children:[h.jsxs(zn,{className:"w-full h-auto rounded-xl border-0 bg-transparent shadow-none px-3 py-2 text-[13px] font-medium text-gray-600 hover:bg-gray-200/60 focus:ring-0",children:[h.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[h.jsx(Ml,{className:"h-4 w-4 text-gray-400"}),h.jsx("span",{children:I("language")})]}),h.jsx("span",{className:"ml-auto text-[11px] text-gray-500",children:T})]}),h.jsx(Bn,{children:Ur.map(E=>h.jsx(St,{value:E.value,className:"text-xs",children:E.label},E.value))})]})]})]})}const _e={exactSpec:1200,exactLabel:1150,prefixSpec:1e3,prefixLabel:950,prefixToken:900,containsSpec:800,containsLabel:760,containsDescription:500,subsequence:300,fallback:1};function Ot(e){return(e??"").trim().toLowerCase()}function qs(e,t){if(!e||!t)return!1;let n=0;for(const r of t)if(r===e[n]&&(n+=1,n>=e.length))return!0;return!1}function Dy(e,t){const n=Ot(t);if(!n)return _e.fallback;const r=Ot(e.key),s=Ot(e.label||e.key),i=Ot(`${e.descriptionZh??""} ${e.description??""}`),o=s.split(/[\s/_-]+/).filter(Boolean);return r===n?_e.exactSpec:s===n?_e.exactLabel:r.startsWith(n)?_e.prefixSpec:s.startsWith(n)?_e.prefixLabel:o.some(a=>a.startsWith(n))?_e.prefixToken:r.includes(n)?_e.containsSpec:s.includes(n)?_e.containsLabel:i.includes(n)?_e.containsDescription:qs(n,s)||qs(n,r)?_e.subsequence:0}function _y(e,t,n){const r=new Intl.Collator(void 0,{sensitivity:"base",numeric:!0});return e.map((s,i)=>({record:s,order:i,score:Dy(s,t)})).filter(s=>s.score>0).sort((s,i)=>{if(i.score!==s.score)return i.score-s.score;const o=(s.record.label||s.record.key).trim(),a=(i.record.label||i.record.key).trim(),l=r.compare(o,a);return l!==0?l:s.order-i.order}).map(({record:s})=>({key:`skill:${s.key}`,title:s.label||s.key,subtitle:n.slashSkillSubtitle,description:(s.descriptionZh??s.description??"").trim()||n.noSkillDescription,detailLines:[`${n.slashSkillSpecLabel}: ${s.key}`],value:s.key}))}function Oy(e){return e.map(t=>({key:t.key,label:t.label,description:t.descriptionZh||t.description||"",badgeLabel:t.badgeLabel}))}function Fy(e){return{title:e.texts.title,searchPlaceholder:e.texts.searchPlaceholder,emptyLabel:e.texts.emptyLabel,loadingLabel:e.texts.loadingLabel,isLoading:e.isLoading,manageLabel:e.texts.manageLabel,manageHref:"/marketplace/skills",options:Oy(e.skillRecords),selectedKeys:e.selectedSkills,onSelectedKeysChange:e.onSelectedKeysChange}}function zy(e){return!e.isModelOptionsLoading&&!e.isModelOptionsEmpty?null:e.isModelOptionsLoading?{tone:"neutral",loading:!0}:{tone:"warning",text:e.texts.noModelOptionsLabel,actionLabel:e.texts.configureProviderLabel,onAction:e.onGoToProviders}}function By(e){const t=e.modelOptions.find(n=>n.value===e.selectedModel);return{key:"model",value:e.hasModelOptions?e.selectedModel:void 0,placeholder:e.texts.modelSelectPlaceholder,selectedLabel:t?`${t.providerLabel}/${t.modelLabel}`:void 0,icon:"sparkles",options:e.modelOptions.map(n=>({value:n.value,label:n.modelLabel,description:n.providerLabel})),disabled:!e.hasModelOptions,loading:e.isModelOptionsLoading,emptyLabel:e.texts.modelNoOptionsLabel,onValueChange:e.onValueChange}}function $y(e){const t=[];for(const n of["off",...e])t.includes(n)||t.push(n);return t}function Ky(e){if(e.supportedLevels.length===0)return null;const t=$y(e.supportedLevels),n=t.includes("off")?"off":t[0],r=e.selectedThinkingLevel&&t.includes(e.selectedThinkingLevel)&&e.selectedThinkingLevel||e.defaultThinkingLevel&&t.includes(e.defaultThinkingLevel)&&e.defaultThinkingLevel||n;return{key:"thinking",value:r,placeholder:e.texts.thinkingLabels[r],selectedLabel:e.texts.thinkingLabels[r],icon:"brain",options:t.map(s=>({value:s,label:e.texts.thinkingLabels[s]})),onValueChange:s=>e.onValueChange(s)}}function Uy(){return{off:I("chatThinkingLevelOff"),minimal:I("chatThinkingLevelMinimal"),low:I("chatThinkingLevelLow"),medium:I("chatThinkingLevelMedium"),high:I("chatThinkingLevelHigh"),adaptive:I("chatThinkingLevelAdaptive"),xhigh:I("chatThinkingLevelXhigh")}}function Vy(e,t){return e.map(n=>({key:n.spec,label:n.label||n.spec,description:n.description,descriptionZh:n.descriptionZh,badgeLabel:n.origin==="builtin"?t:void 0}))}function Hy(e){return e.map(t=>({value:t.value,modelLabel:t.modelLabel,providerLabel:t.providerLabel,thinkingCapability:t.thinkingCapability?{supported:t.thinkingCapability.supported,default:t.thinkingCapability.default??null}:null}))}function qy(){var P;const e=pr(),{language:t}=fr(),n=H(T=>T.snapshot),[r,s]=k.useState(null),i=k.useMemo(()=>I("chatSkillsPickerOfficial"),[t]),o=k.useMemo(()=>({slashSkillSubtitle:I("chatSlashTypeSkill"),slashSkillSpecLabel:I("chatSlashSkillSpec"),noSkillDescription:I("chatSkillsPickerNoDescription")}),[t]),a=k.useMemo(()=>Vy(n.skillRecords,i),[n.skillRecords,i]),l=k.useMemo(()=>Hy(n.modelOptions),[n.modelOptions]),u=l.length>0,c=!n.isProviderStateResolved&&!u,d=n.isProviderStateResolved&&!u,p=(c||d)&&!n.isSending||n.sessionTypeUnavailable,f=c?"":u?I("chatInputPlaceholder"):I("chatModelNoOptions"),m=k.useMemo(()=>_y(a,r??"",o),[r,a,o]),y=l.find(T=>T.value===n.selectedModel),b=y==null?void 0:y.thinkingCapability,g=(b==null?void 0:b.supported)??[],v=n.stopDisabledReason==="__preparing__"?I("chatStopPreparing"):((P=n.stopDisabledReason)==null?void 0:P.trim())||I("chatStopUnavailable"),C=[By({modelOptions:l,selectedModel:n.selectedModel,isModelOptionsLoading:c,hasModelOptions:u,onValueChange:e.chatInputManager.selectModel,texts:{modelSelectPlaceholder:I("chatSelectModel"),modelNoOptionsLabel:I("chatModelNoOptions")}}),Ky({supportedLevels:g,selectedThinkingLevel:n.selectedThinkingLevel,defaultThinkingLevel:(b==null?void 0:b.default)??null,onValueChange:T=>e.chatInputManager.selectThinkingLevel(T),texts:{thinkingLabels:Uy()}})].filter(T=>T!==null),A=Fy({skillRecords:a,selectedSkills:n.selectedSkills,isLoading:n.isSkillsLoading,onSelectedKeysChange:e.chatInputManager.selectSkills,texts:{title:I("chatSkillsPickerTitle"),searchPlaceholder:I("chatSkillsPickerSearchPlaceholder"),emptyLabel:I("chatSkillsPickerEmpty"),loadingLabel:I("sessionsLoading"),manageLabel:I("chatSkillsPickerManage")}});return h.jsx(Ec,{composer:{nodes:n.composerNodes,placeholder:f,disabled:p,onNodesChange:e.chatInputManager.setComposerNodes,onSlashQueryChange:s},slashMenu:{isLoading:n.isSkillsLoading,items:m,texts:{slashLoadingLabel:I("chatSlashLoading"),slashSectionLabel:I("chatSlashSectionSkills"),slashEmptyLabel:I("chatSlashNoResult"),slashHintLabel:I("chatSlashHint"),slashSkillHintLabel:I("chatSlashSkillHint")}},hint:zy({isModelOptionsLoading:c,isModelOptionsEmpty:d,onGoToProviders:e.chatInputManager.goToProviders,texts:{noModelOptionsLabel:I("chatModelNoOptions"),configureProviderLabel:I("chatGoConfigureProvider")}}),toolbar:{selects:C,accessories:[{key:"attach",label:I("chatInputAttach"),icon:"paperclip",iconOnly:!0,disabled:!0,tooltip:I("chatInputAttachComingSoon")}],skillPicker:A,actions:{sendError:n.sendError,isSending:n.isSending,canStopGeneration:n.canStopGeneration,sendDisabled:n.draft.trim().length===0||!u||n.sessionTypeUnavailable,stopDisabled:!n.canStopGeneration,stopHint:v,sendButtonLabel:I("chatSend"),stopButtonLabel:I("chatStop"),onSend:e.chatInputManager.send,onStop:e.chatInputManager.stop}}})}function We(e){return typeof e=="function"}function va(e){var t=function(r){Error.call(r),r.stack=new Error().stack},n=e(t);return n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n}var Rn=va(function(e){return function(n){e(this),this.message=n?n.length+` errors occurred during unsubscription:
36
36
  `+n.map(function(r,s){return s+1+") "+r.toString()}).join(`
37
- `):"",this.name="UnsubscriptionError",this.errors=n}});function er(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var an=(function(){function e(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var t,n,r,s,i;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=jn(o),l=a.next();!l.done;l=a.next()){var u=l.value;u.remove(this)}}catch(y){t={error:y}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}else o.remove(this);var c=this.initialTeardown;if(We(c))try{c()}catch(y){i=y instanceof Rn?y.errors:[y]}var d=this._finalizers;if(d){this._finalizers=null;try{for(var p=jn(d),f=p.next();!f.done;f=p.next()){var m=f.value;try{Ws(m)}catch(y){i=i??[],y instanceof Rn?i=Dn(Dn([],_n(i)),_n(y.errors)):i.push(y)}}}catch(y){r={error:y}}finally{try{f&&!f.done&&(s=p.return)&&s.call(p)}finally{if(r)throw r.error}}}if(i)throw new Rn(i)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)Ws(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(t)}},e.prototype._hasParent=function(t){var n=this._parentage;return n===t||Array.isArray(n)&&n.includes(t)},e.prototype._addParent=function(t){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(t),n):n?[n,t]:t},e.prototype._removeParent=function(t){var n=this._parentage;n===t?this._parentage=null:Array.isArray(n)&&er(n,t)},e.prototype.remove=function(t){var n=this._finalizers;n&&er(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e})(),wa=an.EMPTY;function Ca(e){return e instanceof an||e&&"closed"in e&&We(e.remove)&&We(e.add)&&We(e.unsubscribe)}function Ws(e){We(e)?e():e.unsubscribe()}var Wy={Promise:void 0},Gy={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setTimeout.apply(void 0,Dn([e,t],_n(n)))},clearTimeout:function(e){return clearTimeout(e)},delegate:void 0};function Qy(e){Gy.setTimeout(function(){throw e})}function Gs(){}function Ut(e){e()}var Ta=(function(e){Mt(t,e);function t(n){var r=e.call(this)||this;return r.isStopped=!1,n?(r.destination=n,Ca(n)&&n.add(r)):r.destination=Jy,r}return t.create=function(n,r,s){return new tr(n,r,s)},t.prototype.next=function(n){this.isStopped||this._next(n)},t.prototype.error=function(n){this.isStopped||(this.isStopped=!0,this._error(n))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(n){this.destination.next(n)},t.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t})(an),Xy=(function(){function e(t){this.partialObserver=t}return e.prototype.next=function(t){var n=this.partialObserver;if(n.next)try{n.next(t)}catch(r){Ft(r)}},e.prototype.error=function(t){var n=this.partialObserver;if(n.error)try{n.error(t)}catch(r){Ft(r)}else Ft(t)},e.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(n){Ft(n)}},e})(),tr=(function(e){Mt(t,e);function t(n,r,s){var i=e.call(this)||this,o;return We(n)||!n?o={next:n??void 0,error:r??void 0,complete:s??void 0}:o=n,i.destination=new Xy(o),i}return t})(Ta);function Ft(e){Qy(e)}function Yy(e){throw e}var Jy={closed:!0,next:Gs,error:Yy,complete:Gs},Zy=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function ex(e){return e}function tx(e){return e.length===0?ex:e.length===1?e[0]:function(n){return e.reduce(function(r,s){return s(r)},n)}}var Qt=(function(){function e(t){t&&(this._subscribe=t)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(t,n,r){var s=this,i=rx(t)?t:new tr(t,n,r);return Ut(function(){var o=s,a=o.operator,l=o.source;i.add(a?a.call(i,l):l?s._subscribe(i):s._trySubscribe(i))}),i},e.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(n){t.error(n)}},e.prototype.forEach=function(t,n){var r=this;return n=Qs(n),new n(function(s,i){var o=new tr({next:function(a){try{t(a)}catch(l){i(l),o.unsubscribe()}},error:i,complete:s});r.subscribe(o)})},e.prototype._subscribe=function(t){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(t)},e.prototype[Zy]=function(){return this},e.prototype.pipe=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return tx(t)(this)},e.prototype.toPromise=function(t){var n=this;return t=Qs(t),new t(function(r,s){var i;n.subscribe(function(o){return i=o},function(o){return s(o)},function(){return r(i)})})},e.create=function(t){return new e(t)},e})();function Qs(e){var t;return(t=e??Wy.Promise)!==null&&t!==void 0?t:Promise}function nx(e){return e&&We(e.next)&&We(e.error)&&We(e.complete)}function rx(e){return e&&e instanceof Ta||nx(e)&&Ca(e)}var sx=va(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Ve=(function(e){Mt(t,e);function t(){var n=e.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return t.prototype.lift=function(n){var r=new Xs(this,this);return r.operator=n,r},t.prototype._throwIfClosed=function(){if(this.closed)throw new sx},t.prototype.next=function(n){var r=this;Ut(function(){var s,i;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var o=jn(r.currentObservers),a=o.next();!a.done;a=o.next()){var l=a.value;l.next(n)}}catch(u){s={error:u}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(s)throw s.error}}}})},t.prototype.error=function(n){var r=this;Ut(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var s=r.observers;s.length;)s.shift().error(n)}})},t.prototype.complete=function(){var n=this;Ut(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var r=n.observers;r.length;)r.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(n){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,n)},t.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},t.prototype._innerSubscribe=function(n){var r=this,s=this,i=s.hasError,o=s.isStopped,a=s.observers;return i||o?wa:(this.currentObservers=null,a.push(n),new an(function(){r.currentObservers=null,er(a,n)}))},t.prototype._checkFinalizedStatuses=function(n){var r=this,s=r.hasError,i=r.thrownError,o=r.isStopped;s?n.error(i):o&&n.complete()},t.prototype.asObservable=function(){var n=new Qt;return n.source=this,n},t.create=function(n,r){return new Xs(n,r)},t})(Qt),Xs=(function(e){Mt(t,e);function t(n,r){var s=e.call(this)||this;return s.destination=n,s.source=r,s}return t.prototype.next=function(n){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.next)===null||s===void 0||s.call(r,n)},t.prototype.error=function(n){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.error)===null||s===void 0||s.call(r,n)},t.prototype.complete=function(){var n,r;(r=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||r===void 0||r.call(n)},t.prototype._subscribe=function(n){var r,s;return(s=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&s!==void 0?s:wa},t})(Ve),it=(function(e){Mt(t,e);function t(n){var r=e.call(this)||this;return r._value=n,r}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(n){var r=e.prototype._subscribe.call(this,n);return!r.closed&&n.next(this._value),r},t.prototype.getValue=function(){var n=this,r=n.hasError,s=n.thrownError,i=n._value;if(r)throw s;return this._throwIfClosed(),i},t.prototype.next=function(n){e.prototype.next.call(this,this._value=n)},t})(Ve);const fe=[];for(let e=0;e<256;++e)fe.push((e+256).toString(16).slice(1));function ix(e,t=0){return(fe[e[t+0]]+fe[e[t+1]]+fe[e[t+2]]+fe[e[t+3]]+"-"+fe[e[t+4]]+fe[e[t+5]]+"-"+fe[e[t+6]]+fe[e[t+7]]+"-"+fe[e[t+8]]+fe[e[t+9]]+"-"+fe[e[t+10]]+fe[e[t+11]]+fe[e[t+12]]+fe[e[t+13]]+fe[e[t+14]]+fe[e[t+15]]).toLowerCase()}let En;const ox=new Uint8Array(16);function ax(){if(!En){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");En=crypto.getRandomValues.bind(crypto)}return En(ox)}const lx=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Ys={randomUUID:lx};function nr(e,t,n){var s;if(Ys.randomUUID&&!e)return Ys.randomUUID();e=e||{};const r=e.random??((s=e.rng)==null?void 0:s.call(e))??ax();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,ix(r)}var ue=(e=>(e.CALL="call",e.RESULT="result",e.PARTIAL_CALL="partial-call",e.ERROR="error",e.CANCELLED="cancelled",e))(ue||{}),X=(e=>(e.TEXT_START="TEXT_START",e.TEXT_DELTA="TEXT_DELTA",e.TEXT_END="TEXT_END",e.TOOL_CALL_START="TOOL_CALL_START",e.TOOL_CALL_ARGS="TOOL_CALL_ARGS",e.TOOL_CALL_ARGS_DELTA="TOOL_CALL_ARGS_DELTA",e.TOOL_CALL_END="TOOL_CALL_END",e.TOOL_CALL_RESULT="TOOL_CALL_RESULT",e.RUN_STARTED="RUN_STARTED",e.RUN_FINISHED="RUN_FINISHED",e.RUN_ERROR="RUN_ERROR",e.RUN_METADATA="RUN_METADATA",e.REASONING_START="REASONING_START",e.REASONING_DELTA="REASONING_DELTA",e.REASONING_END="REASONING_END",e))(X||{});function ux(e){return!e||e.remoteStopCapable&&e.remoteRunId?null:e.remoteStopCapable?"__preparing__":e.remoteStopReason??""}const cx=e=>{try{return JSON.parse(e)}catch{return}},Js=e=>({toolCallId:e.id,toolName:e.function.name,args:e.function.arguments,parsedArgs:cx(e.function.arguments),status:ue.CALL});function dx(e,t){const n={error:"tool_call_interrupted",note:"User continued before tool produced a result."};return e.map(r=>{var s;return(s=r.parts)!=null&&s.length?{...r,parts:r.parts.map(i=>{if(i.type!=="tool-invocation"||![ue.CALL,ue.PARTIAL_CALL].includes(i.toolInvocation.status))return i;let o;if(typeof i.toolInvocation.args=="string")try{o=JSON.parse(i.toolInvocation.args)}catch{return{...i,toolInvocation:{...i.toolInvocation,args:JSON.stringify({}),parsedArgs:o,status:ue.RESULT,result:{error:"invalid_args",raw:i.toolInvocation.args}}}}return{...i,toolInvocation:{...i.toolInvocation,args:i.toolInvocation.args,parsedArgs:o,status:ue.RESULT,result:n}}})}:r})}function rr(e){if(e instanceof DOMException&&e.name==="AbortError")return!0;if(e instanceof Error){if(e.name==="AbortError")return!0;const t=e.message.toLowerCase();return t.includes("aborted")||t.includes("abort")}return!1}function Zs(e){if(e instanceof Error){const n=e.message.trim();if(n)return n}return String(e??"").trim()||"Failed to send message"}function ei(e,t){return{id:`local-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,role:"assistant",parts:[{type:"text",text:e}],meta:{source:"local",status:(t==null?void 0:t.status)??"final",sessionKey:t==null?void 0:t.sessionKey,timestamp:new Date().toISOString()}}}class hx{constructor(t){_(this,"currentMessageId");_(this,"currentReasoningMessageId");_(this,"currentReasoningContent","");_(this,"currentToolCallId");_(this,"currentToolCallMessageId");_(this,"currentToolCallName");_(this,"currentToolCallArgs","");_(this,"emittedToolCallIds",new Set);this.sessionManager=t}findAssistantMessageById(t){const n=t==null?void 0:t.trim();return n?this.sessionManager.getMessages().find(s=>s.role==="assistant"&&s.id===n)??null:null}findAssistantMessageByToolCallId(t){var r;if(!t)return null;const n=this.sessionManager.getMessages();for(let s=n.length-1;s>=0;s-=1){const i=n[s];if(i.role!=="assistant")continue;if((r=i.parts)==null?void 0:r.some(a=>a.type==="tool-invocation"&&a.toolInvocation.toolCallId===t))return i}return null}findAssistantMessageForCurrentTool(t){var r;const n=this.findAssistantMessageById(this.currentToolCallMessageId);return(r=n==null?void 0:n.parts)!=null&&r.some(s=>s.type==="tool-invocation"&&s.toolInvocation.toolCallId===t)?n:this.findAssistantMessageByToolCallId(t)}reset(){this.currentMessageId=void 0,this.currentReasoningMessageId=void 0,this.currentReasoningContent="",this.currentToolCallId=void 0,this.currentToolCallMessageId=void 0,this.currentToolCallName=void 0,this.currentToolCallArgs="",this.emittedToolCallIds.clear()}emitToolCallEvents(){const t=this.sessionManager.getMessages();for(const n of t)if(!(n.role!=="assistant"||!n.parts))for(const r of n.parts){if(r.type!=="tool-invocation")continue;const s=r.toolInvocation;s.status===ue.CALL&&!this.emittedToolCallIds.has(s.toolCallId)&&(this.emittedToolCallIds.add(s.toolCallId),this.sessionManager.toolCall$.next({toolCall:{id:s.toolCallId,type:"function",function:{name:s.toolName,arguments:s.args}}}))}}handleEvent(t){switch(t.type){case X.RUN_STARTED:break;case X.TEXT_START:this.handleTextStart(t);break;case X.TEXT_DELTA:this.handleTextContent(t);break;case X.TEXT_END:this.handleTextEnd();break;case X.REASONING_START:this.handleReasoningStart(t);break;case X.REASONING_DELTA:this.handleReasoningContent(t);break;case X.REASONING_END:this.handleReasoningEnd();break;case X.TOOL_CALL_START:this.handleToolCallStart(t);break;case X.TOOL_CALL_ARGS_DELTA:this.handleToolCallArgsDelta(t);break;case X.TOOL_CALL_ARGS:this.handleToolCallArgs(t);break;case X.TOOL_CALL_END:this.handleToolCallEnd(),this.emitToolCallEvents();break;case X.TOOL_CALL_RESULT:this.handleToolCallResult(t);break}}handleTextStart(t){this.currentMessageId=t.messageId}appendTextDelta(t,n){const r=[...t.parts||[]],s=r[r.length-1];return s&&s.type==="text"?{...t,parts:[...r.slice(0,-1),{type:"text",text:`${s.text}${n}`}]}:{...t,parts:[...r,{type:"text",text:n}]}}handleTextContent(t){if(!t.delta||this.currentMessageId!==t.messageId)return;const r=this.sessionManager.getMessages().find(s=>s.role==="assistant"&&s.id===this.currentMessageId);r?this.sessionManager.updateMessage(this.appendTextDelta(r,t.delta)):this.sessionManager.addMessages([{id:this.currentMessageId,role:"assistant",parts:[{type:"text",text:t.delta}]}])}handleTextEnd(){this.currentMessageId=void 0}updateReasoningPart(t,n){var i;const r=[...t.parts||[]];let s=-1;for(let o=r.length-1;o>=0;o-=1)if(((i=r[o])==null?void 0:i.type)==="reasoning"){s=o;break}return s>=0?{...t,parts:[...r.slice(0,s),{type:"reasoning",reasoning:n,details:[]},...r.slice(s+1)]}:{...t,parts:[...r,{type:"reasoning",reasoning:n,details:[]}]}}handleReasoningStart(t){this.currentReasoningMessageId=t.messageId,this.currentReasoningContent=""}handleReasoningContent(t){if(!t.delta||this.currentReasoningMessageId!==t.messageId)return;this.currentReasoningContent+=t.delta;const n=this.currentReasoningContent,r=this.currentReasoningMessageId,i=this.sessionManager.getMessages().find(o=>o.role==="assistant"&&o.id===r);i?this.sessionManager.updateMessage(this.updateReasoningPart(i,n)):this.sessionManager.addMessages([{id:r,role:"assistant",parts:[{type:"reasoning",reasoning:n,details:[]}]}])}handleReasoningEnd(){this.currentReasoningMessageId=void 0,this.currentReasoningContent=""}handleToolCallStart(t){var l;this.currentToolCallId=t.toolCallId,this.currentToolCallName=t.toolName,this.currentToolCallArgs="",this.currentToolCallMessageId=t.messageId;const n={type:"tool-invocation",toolInvocation:{status:ue.PARTIAL_CALL,toolCallId:this.currentToolCallId,toolName:this.currentToolCallName,args:""}},r=this.sessionManager.getMessages(),s=(l=t.messageId)==null?void 0:l.trim(),i=this.findAssistantMessageById(s);if(i){this.currentToolCallMessageId=i.id;const u=i.parts.find(c=>c.type==="tool-invocation"&&c.toolInvocation.toolCallId===this.currentToolCallId);if(u&&u.type==="tool-invocation"){this.currentToolCallArgs=u.toolInvocation.args;return}this.sessionManager.updateMessage({...i,parts:[...i.parts||[],n]});return}if(s){this.currentToolCallMessageId=s,this.sessionManager.addMessages([{id:s,role:"assistant",parts:[n]}]);return}const o=this.findAssistantMessageByToolCallId(this.currentToolCallId);if(o){this.currentToolCallMessageId=o.id;const u=o.parts.find(c=>c.type==="tool-invocation"&&c.toolInvocation.toolCallId===this.currentToolCallId);this.currentToolCallArgs=(u==null?void 0:u.type)==="tool-invocation"?u.toolInvocation.args:"";return}const a=r[r.length-1];if(a&&a.role==="assistant")this.currentToolCallMessageId=a.id,this.sessionManager.updateMessage({...a,parts:[...a.parts||[],n]});else{const u=nr();this.currentToolCallMessageId=u,this.sessionManager.addMessages([{id:u,role:"assistant",parts:[n]}])}}handleToolCallArgsDelta(t){var s;if(this.currentToolCallId!==t.toolCallId)return;this.currentToolCallArgs+=t.argsDelta;const n=this.findAssistantMessageForCurrentTool(t.toolCallId);if(!n||n.role!=="assistant"||!((s=n.parts)!=null&&s.length))return;const r=[...n.parts];for(let i=r.length-1;i>=0;i--){const o=r[i];if(o.type==="tool-invocation"&&o.toolInvocation.toolCallId===t.toolCallId){let a;try{a=JSON.parse(this.currentToolCallArgs)}catch{}r[i]={...o,toolInvocation:{...o.toolInvocation,status:ue.PARTIAL_CALL,args:this.currentToolCallArgs,parsedArgs:a}};break}}this.sessionManager.updateMessage({...n,parts:r})}handleToolCallArgs(t){this.currentToolCallId===t.toolCallId&&(this.currentToolCallArgs=t.args,this.handleToolCallArgsDelta({type:X.TOOL_CALL_ARGS_DELTA,toolCallId:t.toolCallId,argsDelta:""}))}handleToolCallEnd(){var t;if(!(!this.currentToolCallId||!this.currentToolCallName)){try{const n={id:this.currentToolCallId,type:"function",function:{name:this.currentToolCallName,arguments:this.currentToolCallArgs}},r=this.findAssistantMessageForCurrentTool(this.currentToolCallId);if(r&&r.role==="assistant"){const s=[...r.parts||[]];for(let i=s.length-1;i>=0;i--){const o=s[i];if(o.type==="tool-invocation"&&o.toolInvocation.toolCallId===this.currentToolCallId){s[i]={...o,toolInvocation:{...Js(n),status:ue.CALL}};break}}this.sessionManager.updateMessage({...r,parts:s})}else{const s=((t=this.currentToolCallMessageId)==null?void 0:t.trim())||nr();this.sessionManager.addMessages([{id:s,role:"assistant",parts:[{type:"tool-invocation",toolInvocation:{...Js(n),status:ue.CALL}}]}])}}catch{}this.currentToolCallId=void 0,this.currentToolCallMessageId=void 0,this.currentToolCallName=void 0,this.currentToolCallArgs=""}}handleToolCallResult(t){this.sessionManager.addToolResult({toolCallId:t.toolCallId,result:t.content,status:ue.RESULT})}}class fx{constructor(){_(this,"disposables",[]);_(this,"addDisposable",t=>{this.disposables.push(t)});_(this,"dispose",()=>{this.disposables.forEach(t=>t()),this.disposables=[]})}}class px extends fx{constructor(n=null,r){super();_(this,"_messages$",new it([]));_(this,"messages$");_(this,"threadId$",new it(null));_(this,"isAgentResponding$",new it(!1));_(this,"activeRun$",new it(null));_(this,"lastError$",new it(null));_(this,"isAwaitingResponse$",new it(!1));_(this,"runCompleted$",new Ve);_(this,"runError$",new Ve);_(this,"runMetadata$",new Ve);_(this,"activeSubscription",null);_(this,"addMessagesEvent$",new Ve);_(this,"updateMessageEvent$",new Ve);_(this,"setMessagesEvent$",new Ve);_(this,"toolCall$",new Ve);_(this,"eventHandler",new hx(this));_(this,"runIdCounter",0);_(this,"metadataParsers");_(this,"callbacks");_(this,"getMessages",()=>this._messages$.getValue());_(this,"setMessages",n=>{this._messages$.next(n),this.setMessagesEvent$.next({messages:n})});_(this,"handleEvent",n=>{this.eventHandler.handleEvent(n)});_(this,"setCallbacks",n=>{this.callbacks=n});_(this,"reset",()=>{this.abortAgentRun(),this._messages$.next([]),this.eventHandler.reset(),this.threadId$.next(null),this.isAgentResponding$.next(!1),this.activeRun$.next(null),this.lastError$.next(null),this.isAwaitingResponse$.next(!1),this.runIdCounter+=1});_(this,"addMessages",n=>{const s=[...this.getMessages()];for(const i of n){const o=s.findIndex(a=>a.id===i.id);o>=0?s[o]=i:s.push(i)}this._messages$.next(s),this.addMessagesEvent$.next({messages:n}),this.isAwaitingResponse$.getValue()&&n.some(i=>i.role==="assistant")&&this.isAwaitingResponse$.next(!1)});_(this,"removeMessages",n=>{n.length!==0&&this._messages$.next(this.getMessages().filter(r=>!n.includes(r.id)))});_(this,"updateMessage",n=>{this._messages$.next(this.getMessages().map(r=>r.id===n.id?n:r)),this.updateMessageEvent$.next({message:n}),this.isAwaitingResponse$.getValue()&&n.role==="assistant"&&this.isAwaitingResponse$.next(!1)});_(this,"addToolResult",(n,r)=>{const s=this.getMessages().find(o=>o.parts.find(a=>a.type==="tool-invocation"&&a.toolInvocation.toolCallId===n.toolCallId));if(!s)return;const i={...s,parts:s.parts.map(o=>o.type==="tool-invocation"&&o.toolInvocation.toolCallId===n.toolCallId?{...o,toolInvocation:{...o.toolInvocation,result:n.result??void 0,status:n.status,error:n.error??void 0,cancelled:n.cancelled??void 0}}:o)};this.updateMessage(i)});_(this,"send",async n=>{(this.activeRun$.getValue()||this.activeSubscription)&&this.abortAgentRun(),this.lastError$.next(null);const r=n.message.trim();r&&(this.addMessages([{id:nr(),role:"user",parts:[{type:"text",text:r}]}]),await this.runAgent({metadata:n.metadata,sessionId:n.sessionId,agentId:n.agentId,stopCapable:n.stopCapable,stopReason:n.stopReason,sourceMessage:r,restoreDraftOnError:n.restoreDraftOnError}))});_(this,"resume",async n=>{var o,a;const r=(o=n.remoteRunId)==null?void 0:o.trim(),s=(a=n.sessionId)==null?void 0:a.trim();if(!r)return;const i=this.activeRun$.getValue();(i==null?void 0:i.remoteRunId)!==r&&(i||(this.lastError$.next(null),await this.runAgent({metadata:n.metadata,sessionId:s,agentId:n.agentId,stopCapable:n.stopCapable,stopReason:n.stopReason})))});_(this,"stop",async()=>{var s,i;const n=this.activeRun$.getValue();if(!n)return;const r=n.sessionId;this.abortAgentRun(),r&&await((i=(s=this.callbacks).onRunSettled)==null?void 0:i.call(s,{sourceSessionId:r}))});_(this,"handleAgentResponse",n=>{this.activeSubscription&&this.activeSubscription.unsubscribe(),this.activeSubscription=n.subscribe(r=>{var s,i,o,a,l,u,c,d,p;if(r.type===X.RUN_METADATA){const f=r,m=this.activeRun$.getValue(),y=((s=f.runId)==null?void 0:s.trim())||(m?`ui-${m.localRunId}`:"");this.metadataParsers&&m&&this.isMatchingRun(m,y)&&this.processRunMetadata(m,f.metadata),this.runMetadata$.next({runId:y,metadata:f.metadata});return}if(this.handleEvent(r),r.type===X.RUN_FINISHED){this.isAgentResponding$.next(!1),this.isAwaitingResponse$.next(!1),this.activeSubscription=null;const f=this.activeRun$.getValue(),m=((i=r.runId)==null?void 0:i.trim())||(f?`ui-${f.localRunId}`:"");if(!f||!this.isMatchingRun(f,m))return;const y=f.sessionId;this.activeRun$.next(null),y&&((a=(o=this.callbacks).onRunSettled)==null||a.call(o,{sourceSessionId:y}))}else if(r.type===X.RUN_ERROR){this.isAgentResponding$.next(!1),this.isAwaitingResponse$.next(!1),this.activeSubscription=null;const f=this.activeRun$.getValue(),m=((l=r.runId)==null?void 0:l.trim())||(f?`ui-${f.localRunId}`:""),y=rr(r.error);if(this.runError$.next({runId:m,error:r.error,isAbort:y}),!f||!this.isMatchingRun(f,m)){this.activeRun$.next(null);return}const b=f.sessionId;if(y){this.activeRun$.next(null),b&&((c=(u=this.callbacks).onRunSettled)==null||c.call(u,{sourceSessionId:b}));return}const g=Zs(r.error);this.lastError$.next(g),this.activeRun$.next(null),b&&this.addMessages([ei(g,{sessionKey:b,status:"error"})]),(p=(d=this.callbacks).onRunError)==null||p.call(d,{error:g,sourceMessage:f.sourceMessage,restoreDraft:f.restoreDraftOnError})}})});_(this,"abortAgentRun",()=>{var n,r,s;(s=(n=this.agentProvider)==null?void 0:(r=n.agent).abortRun)==null||s.call(r),this.activeSubscription&&(this.activeSubscription.unsubscribe(),this.activeSubscription=null,this.isAgentResponding$.next(!1),this.isAwaitingResponse$.next(!1)),this.activeRun$.next(null)});_(this,"runAgent",async n=>{var o,a,l,u;if(!this.agentProvider)return;(this.activeRun$.getValue()||this.activeSubscription)&&this.abortAgentRun();const r=++this.runIdCounter,s=`ui-${r}`,i={localRunId:r,sessionId:n==null?void 0:n.sessionId,...n!=null&&n.agentId?{agentId:n.agentId}:{},remoteStopCapable:!!(n!=null&&n.stopCapable),...n!=null&&n.stopReason?{remoteStopReason:n.stopReason}:{},sourceMessage:n==null?void 0:n.sourceMessage,restoreDraftOnError:n==null?void 0:n.restoreDraftOnError};this.activeRun$.next(i),this.isAgentResponding$.next(!0),this.isAwaitingResponse$.next(!0);try{const c=dx(this.getMessages()),d=typeof(n==null?void 0:n.threadId)=="string"&&n.threadId.trim()?n.threadId:this.threadId$.getValue()??"",p=await this.agentProvider.agent.run({threadId:d,runId:s,messages:c,tools:this.agentProvider.getToolDefs(),context:this.agentProvider.getContexts(),...n!=null&&n.metadata?{metadata:n.metadata}:{}});this.handleAgentResponse(p)}catch(c){const d=rr(c);d?console.info("Agent run aborted"):console.error("Error running agent:",c),this.isAgentResponding$.next(!1),this.isAwaitingResponse$.next(!1);const p=this.activeRun$.getValue();if(this.activeRun$.next(null),this.runError$.next({runId:s,error:c,isAbort:d}),!d&&p){const f=Zs(c);this.lastError$.next(f),p.sessionId&&this.addMessages([ei(f,{sessionKey:p.sessionId,status:"error"})]),(a=(o=this.callbacks).onRunError)==null||a.call(o,{error:f,sourceMessage:p.sourceMessage,restoreDraft:p.restoreDraftOnError})}else d&&(p!=null&&p.sessionId)&&((u=(l=this.callbacks).onRunSettled)==null||u.call(l,{sourceSessionId:p.sessionId}))}});_(this,"processRunMetadata",(n,r)=>{if(!this.metadataParsers)return;const s=this.metadataParsers.parseReady(r);if(s){this.applyReadyMetadata(n,s);return}const i=this.metadataParsers.parseFinal(r);i&&this.applyFinalMetadata(n,i)});_(this,"applyReadyMetadata",(n,r)=>{var i,o,a,l,u;const s={...n};(i=r.remoteRunId)!=null&&i.trim()&&(s.remoteRunId=r.remoteRunId.trim()),typeof r.stopCapable=="boolean"&&(s.remoteStopCapable=r.stopCapable),(o=r.stopReason)!=null&&o.trim()&&(s.remoteStopReason=r.stopReason.trim()),(a=r.sessionId)!=null&&a.trim()&&(s.sessionId=r.sessionId.trim(),(u=(l=this.callbacks).onSessionChanged)==null||u.call(l,s.sessionId)),this.activeRun$.next(s)});_(this,"applyFinalMetadata",(n,r)=>{var o,a,l,u;const s=n.sessionId,i=r.sessionId;i&&i!==s&&((a=(o=this.callbacks).onSessionChanged)==null||a.call(o,i)),this.activeRun$.next(null),s&&((u=(l=this.callbacks).onRunSettled)==null||u.call(l,{sourceSessionId:s,resultSessionId:i}))});_(this,"isMatchingRun",(n,r)=>r.trim()?r===`ui-${n.localRunId}`:!1);_(this,"connectToolExecutor",()=>{const n=this.toolCall$.subscribe(async({toolCall:r})=>{var i;const s=(i=this.agentProvider)==null?void 0:i.getToolExecutor(r.function.name);if(s)try{const o=JSON.parse(r.function.arguments),a=await s(o);this.addToolResult({toolCallId:r.id,result:a,status:ue.RESULT}),this.runAgent()}catch(o){console.error("[AgentChatController] handleAddToolResult error",o),this.addToolResult({toolCallId:r.id,error:o instanceof Error?o.message:String(o),status:ue.ERROR}),this.runAgent()}});return()=>n.unsubscribe()});this.agentProvider=n;const{initialMessages:s=[],metadataParsers:i,callbacks:o={}}=r||{};this.metadataParsers=i??null,this.callbacks=o,this._messages$.next(s),this.messages$=this._messages$.asObservable(),this.agentProvider&&this.addDisposable(this.connectToolExecutor())}}const gx=/\u200B|\u200C|\u200D|\u2060|\uFEFF/g;function mx(e){return typeof e=="object"&&e!==null}function yx(e){return e.type==="text"&&typeof e.text=="string"}function xx(e){return e.type==="reasoning"&&typeof e.reasoning=="string"}function bx(e){return e.type!=="tool-invocation"||!mx(e.toolInvocation)?!1:typeof e.toolInvocation.toolName=="string"}function Sx(e){var n;const t=(n=e.meta)==null?void 0:n.timestamp;return t&&Number.isFinite(Date.parse(t))?t:new Date().toISOString()}function kx(e,t){return e==="user"?t.user:e==="assistant"?t.assistant:e==="tool"?t.tool:e==="system"?t.system:t.fallback}function vx(e){return e==="user"||e==="assistant"||e==="tool"||e==="system"?e:"message"}function wx(e,t){return{kind:e.kind,toolName:e.name,summary:e.detail,output:e.text,hasResult:!!e.hasResult,titleLabel:e.kind==="call"?t.toolCallLabel:t.toolResultLabel,outputLabel:t.toolOutputLabel,emptyLabel:t.toolNoOutputLabel}}function ti(e){const t=e.trim();return t&&t.replace(gx,"").trim()?t:null}function Cx(e){return e.uiMessages.map(t=>{var n;return{id:t.id,role:vx(t.role),roleLabel:kx(t.role,e.texts.roleLabels),timestampLabel:e.formatTimestamp(Sx(t)),status:(n=t.meta)==null?void 0:n.status,parts:t.parts.map(r=>{if(yx(r)){const s=ti(r.text);return s?{type:"markdown",text:s}:null}if(xx(r)){const s=ti(r.reasoning);return s?{type:"reasoning",text:s,label:e.texts.reasoningLabel}:null}if(bx(r)){const s=r.toolInvocation,i=iu(s.parsedArgs??s.args),o=typeof s.error=="string"&&s.error.trim()?s.error.trim():s.result!=null?Vr(s.result).trim():"",a=s.status==="result"||s.status==="error"||s.status==="cancelled",l={kind:a?"result":"call",name:s.toolName,detail:i,text:o||void 0,callId:s.toolCallId||void 0,hasResult:a};return{type:"tool-card",card:wx(l,e.texts)}}return{type:"unknown",label:e.texts.unknownPartLabel,rawType:typeof r.type=="string"?r.type:"unknown",text:Vr(r)}}).filter(r=>r!==null)}})}function Tx(e){const{language:t}=fr(),n=k.useMemo(()=>e.uiMessages.map(s=>{var i,o;return{id:s.id,role:s.role,meta:{timestamp:(i=s.meta)==null?void 0:i.timestamp,status:(o=s.meta)==null?void 0:o.status},parts:s.parts}}),[e.uiMessages]),r=k.useMemo(()=>Cx({uiMessages:n,formatTimestamp:s=>Zt(s,t),texts:{roleLabels:{user:I("chatRoleUser"),assistant:I("chatRoleAssistant"),tool:I("chatRoleTool"),system:I("chatRoleSystem"),fallback:I("chatRoleMessage")},reasoningLabel:I("chatReasoning"),toolCallLabel:I("chatToolCall"),toolResultLabel:I("chatToolResult"),toolNoOutputLabel:I("chatToolNoOutput"),toolOutputLabel:I("chatToolOutput"),unknownPartLabel:I("chatUnknownPart")}}),[t,n]);return h.jsx(wy,{messages:r,isSending:e.isSending,hasAssistantDraft:e.uiMessages.some(s=>{var i,o;return s.role==="assistant"&&(((i=s.meta)==null?void 0:i.status)==="streaming"||((o=s.meta)==null?void 0:o.status)==="pending")}),className:e.className,texts:{copyCodeLabel:I("chatCodeCopy"),copiedCodeLabel:I("chatCodeCopied"),typingLabel:I("chatTyping")}})}const Ix=[{icon:Rl,titleKey:"chatWelcomeCapability1Title",descKey:"chatWelcomeCapability1Desc"},{icon:lr,titleKey:"chatWelcomeCapability2Title",descKey:"chatWelcomeCapability2Desc"},{icon:cr,titleKey:"chatWelcomeCapability3Title",descKey:"chatWelcomeCapability3Desc"}];function Mx({onCreateSession:e}){return h.jsx("div",{className:"h-full flex items-center justify-center p-8",children:h.jsxs("div",{className:"max-w-lg w-full text-center",children:[h.jsx("div",{className:"mx-auto mb-6 h-16 w-16 rounded-2xl bg-primary/10 flex items-center justify-center",children:h.jsx(wi,{className:"h-8 w-8 text-primary"})}),h.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:I("chatWelcomeTitle")}),h.jsx("p",{className:"text-sm text-gray-500 mb-8",children:I("chatWelcomeSubtitle")}),h.jsx("div",{className:"grid grid-cols-3 gap-3",children:Ix.map(t=>{const n=t.icon;return h.jsxs("button",{onClick:e,className:"rounded-2xl border border-gray-200 bg-white p-4 text-left shadow-card hover:shadow-card-hover transition-shadow cursor-pointer",children:[h.jsx("div",{className:"h-9 w-9 rounded-xl bg-primary/8 flex items-center justify-center mb-3",children:h.jsx(n,{className:"h-4.5 w-4.5 text-primary"})}),h.jsx("div",{className:"text-sm font-semibold text-gray-900 mb-1",children:I(t.titleKey)}),h.jsx("div",{className:"text-[11px] text-gray-500 leading-relaxed",children:I(t.descKey)})]},t.titleKey)})})]})})}const Rx={isProviderStateResolved:!1,modelOptions:[],sessionTypeUnavailable:!1,sessionTypeUnavailableMessage:null,sessionTypeLabel:null,selectedSessionKey:null,sessionDisplayName:void 0,canDeleteSession:!1,isDeletePending:!1,threadRef:null,isHistoryLoading:!1,uiMessages:[],isSending:!1,isAwaitingAssistantOutput:!1},qe=Yt(e=>({snapshot:Rx,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))}));function Ex(){return h.jsxs("section",{className:"flex-1 min-h-0 flex flex-col overflow-hidden bg-gradient-to-b from-gray-50/60 to-white",children:[h.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto custom-scrollbar",children:h.jsx("div",{className:"mx-auto w-full max-w-[min(1120px,100%)] px-6 py-5",children:h.jsxs("div",{className:"space-y-4",children:[h.jsx("div",{className:"h-6 w-48 animate-pulse rounded bg-gray-200"}),h.jsx("div",{className:"h-24 w-[78%] animate-pulse rounded-2xl bg-gray-200/80"}),h.jsx("div",{className:"h-20 w-[62%] animate-pulse rounded-2xl bg-gray-200/80"}),h.jsx("div",{className:"h-28 w-[84%] animate-pulse rounded-2xl bg-gray-200/80"})]})})}),h.jsx("div",{className:"border-t border-gray-200/80 bg-white p-4",children:h.jsx("div",{className:"mx-auto w-full max-w-[min(1120px,100%)]",children:h.jsxs("div",{className:"rounded-2xl border border-gray-200 bg-white shadow-card p-4",children:[h.jsx("div",{className:"h-16 w-full animate-pulse rounded-xl bg-gray-200/80"}),h.jsxs("div",{className:"mt-3 flex items-center justify-between",children:[h.jsx("div",{className:"h-8 w-36 animate-pulse rounded-lg bg-gray-200/80"}),h.jsx("div",{className:"h-8 w-20 animate-pulse rounded-lg bg-gray-200/80"})]})]})})})]})}function Ax(){var d;const e=pr(),t=qe(p=>p.snapshot),n=k.useRef(null),r=t.threadRef??n,s=!!(t.selectedSessionKey||t.sessionTypeLabel),i=t.sessionDisplayName||t.selectedSessionKey||I("chatSidebarNewTask"),o=!t.selectedSessionKey&&t.uiMessages.length===0&&!t.isSending,a=t.modelOptions.length>0,l=t.isProviderStateResolved&&!a,u=t.isHistoryLoading&&t.uiMessages.length===0&&!t.isSending&&!t.isAwaitingAssistantOutput,{onScroll:c}=Ty({scrollRef:r,resetKey:t.selectedSessionKey,isLoading:t.isHistoryLoading,hasContent:t.uiMessages.length>0,contentVersion:t.uiMessages});return t.isProviderStateResolved?h.jsxs("section",{className:"flex-1 min-h-0 flex flex-col overflow-hidden bg-gradient-to-b from-gray-50/60 to-white",children:[h.jsxs("div",{className:xe("px-5 border-b border-gray-200/60 bg-white/80 backdrop-blur-sm flex items-center justify-between shrink-0 overflow-hidden transition-all duration-200",s?"py-3 opacity-100":"h-0 py-0 opacity-0 border-b-0"),children:[h.jsxs("div",{className:"min-w-0 flex-1 flex items-center gap-2",children:[h.jsx("span",{className:"text-sm font-medium text-gray-700 truncate",children:i}),t.sessionTypeLabel?h.jsx("span",{className:"shrink-0 rounded-full border border-gray-200 bg-gray-100 px-2 py-0.5 text-[11px] font-medium text-gray-600",children:t.sessionTypeLabel}):null]}),t.selectedSessionKey?h.jsx(He,{variant:"ghost",size:"icon",className:"rounded-lg shrink-0 text-gray-400 hover:text-destructive",onClick:e.chatThreadManager.deleteSession,disabled:!t.canDeleteSession||t.isDeletePending,children:h.jsx(Ti,{className:"h-4 w-4"})}):null]}),l&&h.jsxs("div",{className:"px-5 py-2.5 border-b border-amber-200/70 bg-amber-50/70 flex items-center justify-between gap-3 shrink-0",children:[h.jsx("span",{className:"text-xs text-amber-800",children:I("chatModelNoOptions")}),h.jsx("button",{type:"button",onClick:e.chatThreadManager.goToProviders,className:"text-xs font-semibold text-amber-900 underline-offset-2 hover:underline",children:I("chatGoConfigureProvider")})]}),t.sessionTypeUnavailable&&((d=t.sessionTypeUnavailableMessage)==null?void 0:d.trim())&&h.jsx("div",{className:"px-5 py-2.5 border-b border-amber-200/70 bg-amber-50/70 shrink-0",children:h.jsx("span",{className:"text-xs text-amber-800",children:t.sessionTypeUnavailableMessage})}),h.jsx("div",{ref:r,onScroll:c,className:"flex-1 min-h-0 overflow-y-auto custom-scrollbar",children:o?h.jsx(Mx,{onCreateSession:e.chatThreadManager.createSession}):u?h.jsx("div",{className:"h-full"}):t.uiMessages.length===0?h.jsx("div",{className:"px-5 py-5 text-sm text-gray-500",children:I("chatNoMessages")}):h.jsx("div",{className:"mx-auto w-full max-w-[min(1120px,100%)] px-6 py-5",children:h.jsx(Tx,{uiMessages:t.uiMessages,isSending:t.isSending&&t.isAwaitingAssistantOutput})})}),h.jsx(qy,{})]}):h.jsx(Ex,{})}function ni(e){return Zt(e??void 0)}function Lx(e){return typeof e!="number"||!Number.isFinite(e)?"-":Zt(new Date(e))}function Nx(e){if(typeof e!="number"||!Number.isFinite(e))return"-";const t=Math.round(e/1e3);if(t<60)return`${t}s`;const n=Math.round(t/60);if(n<60)return`${n}m`;const r=Math.round(n/60);return r<24?`${r}h`:`${Math.round(r/24)}d`}function Px(e){const t=e.schedule;return t.kind==="cron"?t.expr?`cron ${t.expr}`:"cron":t.kind==="every"?`every ${Nx(t.everyMs)}`:t.kind==="at"?`at ${Lx(t.atMs)}`:"-"}function jx(e){if(!e.payload.deliver)return"-";const t=e.payload.channel??"-",n=e.payload.to??"-";return`${t}:${n}`}function Dx(e,t){const n=t.trim().toLowerCase();return n?[e.id,e.name,e.payload.message,e.payload.channel??"",e.payload.to??""].join(" ").toLowerCase().includes(n):!0}function _x(e,t){return t==="all"?!0:t==="enabled"?e.enabled:!e.enabled}function Ox(){var m;const[e,t]=k.useState(""),[n,r]=k.useState("all"),s=Kl({all:!0}),i=Ul(),o=Vl(),a=Hl(),{confirm:l,ConfirmDialog:u}=dr(),c=k.useMemo(()=>{var b;return(((b=s.data)==null?void 0:b.jobs)??[]).filter(g=>Dx(g,e)).filter(g=>_x(g,n))},[s.data,e,n]),d=async y=>{await l({title:`${I("cronDeleteConfirm")}?`,description:y.name?`${y.name} (${y.id})`:y.id,variant:"destructive",confirmLabel:I("delete")})&&i.mutate({id:y.id})},p=async y=>{const b=!y.enabled;await l({title:b?`${I("cronEnableConfirm")}?`:`${I("cronDisableConfirm")}?`,description:y.name?`${y.name} (${y.id})`:y.id,variant:b?"default":"destructive",confirmLabel:b?I("cronEnable"):I("cronDisable")})&&o.mutate({id:y.id,enabled:b})},f=async y=>{const b=!y.enabled;await l({title:b?`${I("cronRunForceConfirm")}?`:`${I("cronRunConfirm")}?`,description:y.name?`${y.name} (${y.id})`:y.id,confirmLabel:I("cronRunNow")})&&a.mutate({id:y.id,force:b})};return h.jsxs(vu,{fullHeight:!0,children:[h.jsx(wu,{title:I("cronPageTitle"),description:I("cronPageDescription"),actions:h.jsx(He,{variant:"ghost",size:"icon",className:"h-9 w-9 rounded-lg text-gray-400 hover:text-gray-700 hover:bg-gray-100",onClick:()=>s.refetch(),children:h.jsx(El,{className:xe("h-4 w-4",s.isFetching&&"animate-spin")})})}),h.jsx("div",{className:"mb-6",children:h.jsxs("div",{className:"flex flex-wrap gap-3 items-center",children:[h.jsxs("div",{className:"relative flex-1 min-w-[240px]",children:[h.jsx(hr,{value:e,onChange:y=>t(y.target.value),placeholder:I("cronSearchPlaceholder"),className:"pl-9"}),h.jsx(cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400"})]}),h.jsx("div",{className:"min-w-[180px]",children:h.jsxs(Fn,{value:n,onValueChange:y=>r(y),children:[h.jsx(zn,{className:"w-full",children:h.jsx(ql,{placeholder:I("cronStatusLabel")})}),h.jsxs(Bn,{children:[h.jsx(St,{value:"all",children:I("cronStatusAll")}),h.jsx(St,{value:"enabled",children:I("cronStatusEnabled")}),h.jsx(St,{value:"disabled",children:I("cronStatusDisabled")})]})]})}),h.jsxs("div",{className:"text-xs text-gray-500 ml-auto",children:[I("cronTotalLabel"),": ",((m=s.data)==null?void 0:m.total)??0," / ",c.length]})]})}),h.jsx("div",{className:"flex-1 overflow-auto custom-scrollbar",children:s.isLoading?h.jsx("div",{className:"text-sm text-gray-400 p-4 text-center",children:I("cronLoading")}):c.length===0?h.jsx("div",{className:"text-sm text-gray-400 p-4 text-center",children:I("cronEmpty")}):h.jsx("div",{className:"space-y-4",children:c.map(y=>h.jsx(Wl,{className:"border border-gray-200",children:h.jsx(Gl,{className:"pt-5 pb-5",children:h.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[h.jsxs("div",{className:"min-w-[220px] flex-1",children:[h.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[h.jsx("span",{className:"text-sm font-semibold text-gray-900",children:y.name||y.id}),h.jsx("span",{className:"text-[10px] font-semibold px-2 py-0.5 rounded-full bg-gray-100 text-gray-500",children:y.id}),h.jsx("span",{className:xe("text-[10px] font-semibold px-2 py-0.5 rounded-full",y.enabled?"bg-emerald-50 text-emerald-700":"bg-gray-100 text-gray-500"),children:y.enabled?I("enabled"):I("disabled")}),y.deleteAfterRun&&h.jsx("span",{className:"text-[10px] font-semibold px-2 py-0.5 rounded-full bg-amber-50 text-amber-700",children:I("cronOneShot")})]}),h.jsxs("div",{className:"mt-2 text-xs text-gray-500",children:[I("cronScheduleLabel"),": ",Px(y)]}),h.jsx("div",{className:"mt-2 text-sm text-gray-700 whitespace-pre-wrap break-words",children:y.payload.message}),h.jsxs("div",{className:"mt-2 text-xs text-gray-500",children:[I("cronDeliverTo"),": ",jx(y)]})]}),h.jsxs("div",{className:"min-w-[220px] text-xs text-gray-500 space-y-2",children:[h.jsxs("div",{children:[h.jsxs("span",{className:"font-medium text-gray-700",children:[I("cronNextRun"),":"]})," ",ni(y.state.nextRunAt)]}),h.jsxs("div",{children:[h.jsxs("span",{className:"font-medium text-gray-700",children:[I("cronLastRun"),":"]})," ",ni(y.state.lastRunAt)]}),h.jsxs("div",{children:[h.jsxs("span",{className:"font-medium text-gray-700",children:[I("cronLastStatus"),":"]})," ",y.state.lastStatus??"-"]}),y.state.lastError&&h.jsx("div",{className:"text-[11px] text-red-500 break-words",children:y.state.lastError})]}),h.jsxs("div",{className:"flex items-start gap-2 flex-wrap justify-end",children:[h.jsxs(He,{variant:"subtle",size:"sm",onClick:()=>f(y),className:"gap-1",children:[h.jsx(Al,{className:"h-3.5 w-3.5"}),I("cronRunNow")]}),h.jsxs(He,{variant:y.enabled?"outline":"primary",size:"sm",onClick:()=>p(y),className:"gap-1",children:[h.jsx(Ll,{className:"h-3.5 w-3.5"}),y.enabled?I("cronDisable"):I("cronEnable")]}),h.jsxs(He,{variant:"destructive",size:"sm",onClick:()=>d(y),className:"gap-1",children:[h.jsx(Ti,{className:"h-3.5 w-3.5"}),I("delete")]})]})]})})},y.id))})}),h.jsx(u,{})]})}function Ia(e){const{view:t,routeSessionKey:n,selectedSessionKey:r,selectedAgentId:s,setSelectedSessionKey:i,setSelectedAgentId:o,selectedSessionKeyRef:a,resetStreamState:l,resolveAgentIdFromSessionKey:u}=e;k.useEffect(()=>{if(t==="chat"){if(n){r!==n&&i(n);return}r!==null&&(i(null),l())}},[l,n,r,i,t]),k.useEffect(()=>{const c=r?u(r):null;c&&s!==c&&o(c)},[u,s,r,o]),k.useEffect(()=>{a.current=r},[r,a])}function Ma({view:e,confirmDialog:t}){return h.jsxs("div",{className:"h-full flex",children:[h.jsx(jy,{}),e==="chat"?h.jsx(Ax,{}):h.jsx("section",{className:"flex-1 min-h-0 overflow-hidden bg-gradient-to-b from-gray-50/60 to-white",children:e==="cron"?h.jsx("div",{className:"h-full overflow-auto custom-scrollbar",children:h.jsx("div",{className:"mx-auto w-full max-w-[min(1120px,100%)] px-6 py-5",children:h.jsx(Ox,{})})}):h.jsx("div",{className:"h-full overflow-hidden",children:h.jsx("div",{className:"mx-auto flex h-full min-h-0 w-full max-w-[min(1120px,100%)] flex-col px-6 py-5",children:h.jsx(pu,{forcedType:"skills"})})})}),t]})}const sr="sid_";function Ra(e){var r;const t=/^agent:([^:]+):/i.exec(e.trim());if(!t)return null;const n=(r=t[1])==null?void 0:r.trim();return n||null}function Fx(e){const t=Math.random().toString(36).slice(2,8);return`agent:${e}:ui:direct:web-${Date.now().toString(36)}${t}`}function zx(e){const t=new TextEncoder().encode(e);let n="";for(const s of t)n+=String.fromCharCode(s);const r=btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"");return`${sr}${r}`}function Bx(e){if(!e.startsWith(sr))return null;const t=e.slice(sr.length).replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4===0?"":"=".repeat(4-t.length%4);try{const r=atob(t+n),s=Uint8Array.from(r,i=>i.charCodeAt(0));return new TextDecoder().decode(s)}catch{return null}}function Ea(e){if(!e)return null;const t=Bx(e);if(t)return t;try{return decodeURIComponent(e)}catch{return e}}function $x(e){return`/chat/${zx(e)}`}function Kx(e){const t=e.trim();return t.length>0?t:null}function Ux(e){return e??null}class Aa{constructor(t){this.updateSession=t,this.inFlight=null,this.queued=null,this.syncSelectedSessionPreferences=()=>{const n=H.getState().snapshot,s=re.getState().snapshot.selectedSessionKey;s&&this.enqueue({sessionKey:s,patch:{preferredModel:Kx(n.selectedModel),preferredThinking:Ux(n.selectedThinkingLevel)}})}}enqueue(t){this.queued=t,!this.inFlight&&this.startFlush()}startFlush(){this.inFlight=this.flush().catch(t=>{console.error(`Failed to sync chat session preferences: ${String(t)}`)}).finally(()=>{this.inFlight=null,this.queued&&this.startFlush()})}async flush(){for(;this.queued;){const t=this.queued;this.queued=null,await this.updateSession(t.sessionKey,t.patch)}}}class Vx{constructor(t,n){this.uiManager=t,this.streamActionsManager=n,this.sessionPreferenceSync=new Aa(On),this.hasSnapshotChanges=r=>{const s=H.getState().snapshot;for(const[i,o]of Object.entries(r))if(!Object.is(s[i],o))return!0;return!1},this.resolveUpdateValue=(r,s)=>typeof s=="function"?s(r):s,this.isSameStringArray=(r,s)=>r.length===s.length&&r.every((i,o)=>i===s[o]),this.syncComposerSnapshot=r=>{H.getState().setSnapshot({composerNodes:r,draft:ba(r),selectedSkills:Sa(r)})},this.syncSnapshot=r=>{if(this.hasSnapshotChanges(r)&&(H.getState().setSnapshot(r),Object.prototype.hasOwnProperty.call(r,"modelOptions")||Object.prototype.hasOwnProperty.call(r,"selectedModel")||Object.prototype.hasOwnProperty.call(r,"selectedThinkingLevel"))){const{selectedModel:s}=H.getState().snapshot;this.reconcileThinkingForModel(s)}},this.setDraft=r=>{const s=H.getState().snapshot.draft,i=this.resolveUpdateValue(s,r);i!==s&&this.syncComposerSnapshot(xa(i))},this.setComposerNodes=r=>{const s=H.getState().snapshot.composerNodes,i=this.resolveUpdateValue(s,r);Object.is(i,s)||this.syncComposerSnapshot(i)},this.setPendingSessionType=r=>{const s=H.getState().snapshot.pendingSessionType,i=this.resolveUpdateValue(s,r);i!==s&&H.getState().setSnapshot({pendingSessionType:i})},this.send=async()=>{const r=H.getState().snapshot,s=re.getState().snapshot,i=r.draft.trim();if(!i)return;const{selectedSkills:o,composerNodes:a}=r,l=!!s.selectedSessionKey,u=s.selectedSessionKey??Fx(s.selectedAgentId);l||this.uiManager.goToSession(u,{replace:!0}),this.setComposerNodes(_r()),await this.streamActionsManager.sendMessage({message:i,sessionKey:u,agentId:s.selectedAgentId,sessionType:r.selectedSessionType,model:r.selectedModel||void 0,thinkingLevel:r.selectedThinkingLevel??void 0,stopSupported:r.stopSupported,stopReason:r.stopReason,requestedSkills:o,restoreDraftOnError:!0,composerNodes:a})},this.stop=async()=>{await this.streamActionsManager.stopCurrentRun()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.setSelectedModel=r=>{const s=H.getState().snapshot.selectedModel,i=this.resolveUpdateValue(s,r);i!==s&&(H.getState().setSnapshot({selectedModel:i}),this.reconcileThinkingForModel(i))},this.setSelectedThinkingLevel=r=>{const s=H.getState().snapshot.selectedThinkingLevel,i=this.resolveUpdateValue(s,r);i!==s&&H.getState().setSnapshot({selectedThinkingLevel:i})},this.selectSessionType=r=>{const s=Fe(r);H.getState().setSnapshot({selectedSessionType:s,pendingSessionType:s}),this.syncRemoteSessionType(s)},this.setSelectedSkills=r=>{const s=H.getState().snapshot,{selectedSkills:i}=s,o=this.resolveUpdateValue(i,r);this.isSameStringArray(o,i)||this.syncComposerSnapshot(ka(s.composerNodes,o,s.skillRecords))},this.selectModel=r=>{this.setSelectedModel(r),this.sessionPreferenceSync.syncSelectedSessionPreferences()},this.selectThinkingLevel=r=>{this.setSelectedThinkingLevel(r),this.sessionPreferenceSync.syncSelectedSessionPreferences()},this.selectSkills=r=>{this.setSelectedSkills(r)},this.syncRemoteSessionType=async r=>{const s=re.getState().snapshot,{selectedSessionKey:i}=s;if(!i)return;const o=s.sessions.find(a=>a.key===i);o!=null&&o.sessionTypeMutable&&Fe(o.sessionType)!==r&&await On(i,{sessionType:r})}}resolveThinkingForModel(t,n){const r=t==null?void 0:t.thinkingCapability;return!r||r.supported.length===0?null:n==="off"?"off":n&&r.supported.includes(n)?n:r.default&&r.supported.includes(r.default)?r.default:"off"}reconcileThinkingForModel(t){const n=H.getState().snapshot,r=n.modelOptions.find(o=>o.value===t),{selectedThinkingLevel:s}=n,i=this.resolveThinkingForModel(r,s);i!==s&&H.getState().setSnapshot({selectedThinkingLevel:i})}}const Hx={parseReady:e=>e.driver!=="nextbot-stream"||e.kind!=="ready"?null:{remoteRunId:typeof e.backendRunId=="string"?e.backendRunId:void 0,sessionId:typeof e.sessionKey=="string"?e.sessionKey:void 0,stopCapable:typeof e.stopSupported=="boolean"?e.stopSupported:void 0,stopReason:typeof e.stopReason=="string"?e.stopReason:void 0},parseFinal:e=>e.driver!=="nextbot-stream"||e.kind!=="final"?null:{sessionId:typeof e.sessionKey=="string"?e.sessionKey:void 0,hasOutput:!!e.hasAssistantSessionEvent}};function qx(e,t){return{driver:"nextbot-stream",mode:"send",payload:e,requestedSkills:t}}function Wx(e){const t=Number.isFinite(e.eventCount)&&e.eventCount>0?Math.max(0,Math.trunc(e.eventCount)):void 0;return{driver:"nextbot-stream",mode:"resume",runId:e.runId,...typeof t=="number"?{fromEventIndex:t}:{},sessionKey:e.sessionKey,...e.agentId?{agentId:e.agentId}:{},stopSupported:e.stopSupported,...e.stopReason?{stopReason:e.stopReason}:{}}}function Gx(e,t){if(e===t)return!0;if(e.size!==t.size)return!1;for(const[n,r]of e.entries())if(!Object.is(r,t.get(n)))return!1;return!0}class La{constructor(){this.syncSnapshot=t=>{const n=Zn.getState().snapshot,r=t.sessionRunStatusByKey;(!r||Gx(n.sessionRunStatusByKey,r))&&(t.isLocallyRunning===void 0||Object.is(n.isLocallyRunning,t.isLocallyRunning))&&(t.activeBackendRunId===void 0||Object.is(n.activeBackendRunId,t.activeBackendRunId))||Zn.getState().setSnapshot(t)}}}class Na{constructor(t,n){this.uiManager=t,this.streamActionsManager=n,this.hasSnapshotChanges=r=>{const s=re.getState().snapshot;for(const[i,o]of Object.entries(r))if(!Object.is(s[i],o))return!0;return!1},this.resolveUpdateValue=(r,s)=>typeof s=="function"?s(r):s,this.syncSnapshot=r=>{this.hasSnapshotChanges(r)&&re.getState().setSnapshot(r)},this.setSelectedAgentId=r=>{const s=re.getState().snapshot.selectedAgentId,i=this.resolveUpdateValue(s,r);i!==s&&re.getState().setSnapshot({selectedAgentId:i})},this.setSelectedSessionKey=r=>{const s=re.getState().snapshot.selectedSessionKey,i=this.resolveUpdateValue(s,r);i!==s&&re.getState().setSnapshot({selectedSessionKey:i})},this.createSession=r=>{const{snapshot:s}=H.getState(),{defaultSessionType:i}=s,o=i||"native",a=typeof r=="string"&&r.trim().length>0?r.trim():o;this.streamActionsManager.resetStreamState(),this.setSelectedSessionKey(null),H.getState().setSnapshot({pendingSessionType:a}),this.uiManager.goToChatRoot()},this.selectSession=r=>{this.setSelectedSessionKey(r),this.uiManager.goToSession(r)},this.setQuery=r=>{const s=re.getState().snapshot.query,i=this.resolveUpdateValue(s,r);i!==s&&re.getState().setSnapshot({query:i})}}}const An=async()=>{},ri=()=>{};class Pa{constructor(){this.actions={sendMessage:An,stopCurrentRun:An,resumeRun:An,resetStreamState:ri,applyHistoryMessages:ri},this.bind=t=>{this.actions={...this.actions,...t}},this.sendMessage=t=>this.actions.sendMessage(t),this.stopCurrentRun=()=>this.actions.stopCurrentRun(),this.resumeRun=t=>this.actions.resumeRun(t),this.resetStreamState=()=>this.actions.resetStreamState(),this.applyHistoryMessages=(t,n)=>this.actions.applyHistoryMessages(t,n)}}const Qx=async()=>{};class Xx{constructor(t,n,r){this.uiManager=t,this.sessionListManager=n,this.streamActionsManager=r,this.actions={refetchSessions:Qx},this.bindActions=s=>{this.actions={...this.actions,...s}},this.hasSnapshotChanges=s=>{const i=qe.getState().snapshot;for(const[o,a]of Object.entries(s))if(!Object.is(i[o],a))return!0;return!1},this.syncSnapshot=s=>{this.hasSnapshotChanges(s)&&qe.getState().setSnapshot(s)},this.deleteSession=()=>{this.deleteCurrentSession()},this.createSession=()=>{this.sessionListManager.createSession()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.deleteCurrentSession=async()=>{const{snapshot:{selectedSessionKey:s}}=re.getState();if(!(!s||!await this.uiManager.confirm({title:I("chatDeleteSessionConfirm"),variant:"destructive",confirmLabel:I("delete")}))){qe.getState().setSnapshot({isDeletePending:!0});try{await Ql(s),this.streamActionsManager.resetStreamState(),re.getState().setSnapshot({selectedSessionKey:null}),this.uiManager.goToChatRoot({replace:!0}),await this.actions.refetchSessions()}finally{qe.getState().setSnapshot({isDeletePending:!1})}}}}}const Yx=async e=>!1;class ja{constructor(){this.state={pathname:""},this.actions={navigate:null,confirm:Yx},this.syncState=t=>{this.state={...this.state,...t}},this.bindActions=t=>{this.actions={...this.actions,...t}},this.confirm=async t=>this.actions.confirm(t),this.navigateTo=(t,n)=>{this.actions.navigate&&(this.state.pathname===t&&!(n!=null&&n.replace)||(this.actions.navigate(t,n),this.state.pathname=t))},this.goToProviders=()=>{this.navigateTo("/providers")},this.goToChatRoot=t=>{this.navigateTo("/chat",t)},this.goToSession=(t,n)=>{this.navigateTo($x(t),n)}}}function Jx(e){return e.delta?e.started?[{type:X.TEXT_DELTA,messageId:e.messageId,delta:e.delta}]:[{type:X.TEXT_START,messageId:e.messageId},{type:X.TEXT_DELTA,messageId:e.messageId,delta:e.delta}]:[]}function Zx(e){return!1}function eb(e){var n,r;return((r=(n=e.message)==null?void 0:n.role)==null?void 0:r.toLowerCase().trim())==="assistant"}function tb(e){var o;const{event:t,messageId:n}=e,r=t.message;if(!r)return[];const s=(o=r.role)==null?void 0:o.toLowerCase().trim();if(!s)return[];const i=[];if(typeof r.reasoning_content=="string"&&r.reasoning_content.trim()&&(i.push({type:X.REASONING_START,messageId:n}),i.push({type:X.REASONING_DELTA,messageId:n,delta:r.reasoning_content.trim()}),i.push({type:X.REASONING_END,messageId:n})),Array.isArray(r.tool_calls))for(let a=0;a<r.tool_calls.length;a+=1){const l=r.tool_calls[a];if(!l||typeof l!="object")continue;const u=l,c=u.function,d=typeof c=="object"&&c?c:null,p=typeof t.seq=="number"?String(t.seq):"unknown",f=typeof u.id=="string"?u.id:`tool-${p}-${a}`,m=typeof(d==null?void 0:d.name)=="string"?d.name:typeof u.name=="string"?u.name:"tool",y=(d==null?void 0:d.arguments)??u.arguments??"",b=typeof y=="string"?y:JSON.stringify(y??{});i.push({type:X.TOOL_CALL_START,messageId:n,toolCallId:f,toolName:m}),i.push({type:X.TOOL_CALL_ARGS,toolCallId:f,args:b}),i.push({type:X.TOOL_CALL_END,toolCallId:f})}if(s==="tool"||s==="tool_result"||s==="toolresult"||s==="function"){const a=typeof r.tool_call_id=="string"?r.tool_call_id.trim():"";a&&i.push({type:X.TOOL_CALL_RESULT,toolCallId:a,content:r.content})}return i}function Da(){return`stream-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function nb(e,t){const n={};return e.sessionType&&(n.session_type=e.sessionType),e.thinkingLevel&&(n.thinking=e.thinkingLevel),t.length>0&&(n.requested_skills=t),{message:e.message,...e.runId?{runId:e.runId}:{},sessionKey:e.sessionKey,agentId:e.agentId,...e.model?{model:e.model}:{},...Object.keys(n).length>0?{metadata:n}:{},channel:"ui",chatId:"web-ui"}}async function rb(e){let t="";const r=await en.openStream({method:"POST",path:"/api/chat/turn/stream",body:nb(e.item,e.requestedSkills),signal:e.signal,onEvent:s=>{if(s.name==="ready"){const i=s.payload??{};typeof i.sessionKey=="string"&&i.sessionKey.trim()&&(t=i.sessionKey),e.onReady(i);return}if(s.name==="delta"){e.onDelta(s.payload??{delta:""});return}s.name==="session_event"&&e.onSessionEvent({data:s.payload})}}).finished;return{sessionKey:typeof(r==null?void 0:r.sessionKey)=="string"&&r.sessionKey.trim()?r.sessionKey:t,reply:typeof(r==null?void 0:r.reply)=="string"?r.reply:""}}async function sb(e){let t="";const n=new URLSearchParams;typeof e.fromEventIndex=="number"&&n.set("fromEventIndex",String(Math.max(0,Math.trunc(e.fromEventIndex))));const r=`/api/chat/runs/${encodeURIComponent(e.runId)}/stream`+(n.size>0?`?${n.toString()}`:""),i=await en.openStream({method:"GET",path:r,signal:e.signal,onEvent:o=>{if(o.name==="ready"){const a=o.payload??{};typeof a.sessionKey=="string"&&a.sessionKey.trim()&&(t=a.sessionKey),e.onReady(a);return}if(o.name==="delta"){e.onDelta(o.payload??{delta:""});return}o.name==="session_event"&&e.onSessionEvent({data:o.payload})}}).finished;return{sessionKey:typeof(i==null?void 0:i.sessionKey)=="string"&&i.sessionKey.trim()?i.sessionKey:t,reply:typeof(i==null?void 0:i.reply)=="string"?i.reply:""}}async function ib(e){var t;if(e.backendStopSupported)try{const n=new Set,r=(t=e.backendRunId)==null?void 0:t.trim();if(r&&(n.add(r),await Ln(r)))return;const s=await ob(e);for(const i of s){if(n.has(i))continue;if(n.add(i),await Ln(i))return}if(r&&await Ln(r))return}catch{}}async function Ln(e){const t=e.trim();if(!t)return!1;try{return(await Xl({runId:t})).stopped===!0}catch{return!1}}async function ob(e){var s;const t=(s=e.sessionKey)==null?void 0:s.trim();if(!t)return[];const n=8,r=120;for(let i=0;i<n;i+=1){const o=await ab(e,t);if(o.length>0)return o;i<n-1&&await lb(r)}return[]}async function ab(e,t){try{const n=await Yl({sessionKey:t,states:["queued","running"],limit:50}),r=n.runs.filter(s=>{var i;return((i=s.runId)==null?void 0:i.trim())&&s.sessionKey===t&&s.agentId===e.agentId}).map(s=>s.runId.trim());return r.length>0?r:n.runs.filter(s=>{var i;return((i=s.runId)==null?void 0:i.trim())&&s.sessionKey===t}).map(s=>s.runId.trim())}catch{return[]}}function lb(e){return new Promise(t=>{window.setTimeout(t,e)})}function _a(e){if(!Array.isArray(e))return[];const t=new Set;for(const n of e){const r=n.trim();r&&t.add(r)}return[...t]}function ub(e){var y;const t=new Set(["tool","tool_result","toolresult","function"]),n=[];let r=0,s=0,i=null;const o=(b,g)=>(r+=1,`history-${b}-${g||"unknown"}-${r}`),a=b=>{const g=typeof b=="string"?b:JSON.stringify(b??{});try{return{args:g,parsedArgs:JSON.parse(g)}}catch{return{args:g}}},l=(b,g)=>{for(let v=b.length-1;v>=0;v-=1){const C=b[v];if(C.type==="tool-invocation"&&C.toolInvocation.toolCallId===g)return v}return-1},u=b=>i?(i={...i,meta:{...i.meta,timestamp:b}},i):(s+=1,i={id:`history-assistant-${s}-${b||"unknown"}`,role:"assistant",parts:[],meta:{source:"history",status:"final",timestamp:b}},i),c=()=>{i&&(i.parts.length>0&&n.push(i),i=null)},d=(b,g)=>{if(!g)return;const v=u(b);v.parts=[...v.parts,{type:"text",text:g}]},p=(b,g)=>{if(!g)return;const v=u(b);v.parts=[...v.parts,{type:"reasoning",reasoning:g,details:[]}]},f=b=>{const g=u(b.timestamp),v=l(g.parts,b.toolCallId),C={type:"tool-invocation",toolInvocation:{status:ue.CALL,toolCallId:b.toolCallId,toolName:b.toolName,args:b.args,parsedArgs:b.parsedArgs}};if(v>=0){g.parts=[...g.parts.slice(0,v),C,...g.parts.slice(v+1)];return}g.parts=[...g.parts,C]},m=b=>{if(!b.toolCallId)return;const g=u(b.timestamp),v=l(g.parts,b.toolCallId);if(v<0){g.parts=[...g.parts,{type:"tool-invocation",toolInvocation:{status:ue.RESULT,toolCallId:b.toolCallId,toolName:b.toolName,args:"{}",parsedArgs:void 0,result:b.result}}];return}const C=g.parts[v];C.type==="tool-invocation"&&(g.parts=[...g.parts.slice(0,v),{...C,toolInvocation:{...C.toolInvocation,status:ue.RESULT,result:b.result}},...g.parts.slice(v+1)])};for(const b of e){const g=(y=b.role)==null?void 0:y.toLowerCase().trim();if(!g)continue;const v=b.timestamp;if(g==="user"||g==="system"||g==="data"){c();const C=Hr(b.content).trim();if(!C)continue;n.push({id:o(g,v),role:g,parts:[{type:"text",text:C}],meta:{source:"history",status:"final",timestamp:v}});continue}if(g==="assistant"){const C=Hr(b.content).trim();if(C&&d(v,C),typeof b.reasoning_content=="string"&&b.reasoning_content.trim()&&p(v,b.reasoning_content.trim()),Array.isArray(b.tool_calls))for(const A of b.tool_calls){if(!A||typeof A!="object")continue;const P=A,T=P.function,F=typeof T=="object"&&T?T:null,B=typeof P.id=="string"?P.id.trim():"";if(!B)continue;const z=typeof(F==null?void 0:F.name)=="string"?F.name:typeof P.name=="string"?P.name:"tool",w=a((F==null?void 0:F.arguments)??P.arguments??"");f({timestamp:v,toolCallId:B,toolName:z,args:w.args,parsedArgs:w.parsedArgs})}continue}if(t.has(g)){const C=typeof b.tool_call_id=="string"?b.tool_call_id.trim():"",A=typeof b.name=="string"&&b.name.trim()?b.name.trim():"tool";m({timestamp:v,toolCallId:C,toolName:A,result:b.content})}}return c(),n}function cb(){const e=Date.now().toString(36),t=Math.random().toString(36).slice(2,10);return`run-${e}-${t}`}function db(e){const t=e.metadata;if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t;if(n.driver!=="nextbot-stream")return null;const r=n.mode;if(r==="send"){const s=n.payload;if(!s||typeof s!="object"||Array.isArray(s))return null;const i=Array.isArray(n.requestedSkills)?n.requestedSkills.filter(o=>typeof o=="string"):[];return{driver:"nextbot-stream",mode:"send",payload:s,requestedSkills:i}}if(r==="resume"){const s=typeof n.runId=="string"?n.runId.trim():"";if(!s)return null;const i=typeof n.fromEventIndex=="number"&&Number.isFinite(n.fromEventIndex)?Math.max(0,Math.trunc(n.fromEventIndex)):void 0,o=typeof n.sessionKey=="string"?n.sessionKey.trim():"",a=typeof n.agentId=="string"?n.agentId.trim():"",l=typeof n.stopSupported=="boolean"?n.stopSupported:void 0,u=typeof n.stopReason=="string"?n.stopReason.trim():"";return{driver:"nextbot-stream",mode:"resume",runId:s,...typeof i=="number"?{fromEventIndex:i}:{},...o?{sessionKey:o}:{},...a?{agentId:a}:{},...typeof l=="boolean"?{stopSupported:l}:{},...u?{stopReason:u}:{}}}return null}function hb(e){var t;if(e.mode==="send"){const n=((t=e.payload.runId)==null?void 0:t.trim())||"";return{localRunId:0,sessionKey:e.payload.sessionKey,...e.payload.agentId?{agentId:e.payload.agentId}:{},...n?{backendRunId:n}:{},backendStopSupported:!!e.payload.stopSupported,...e.payload.stopReason?{backendStopReason:e.payload.stopReason}:{}}}return{localRunId:0,sessionKey:e.sessionKey??"",...e.agentId?{agentId:e.agentId}:{},backendRunId:e.runId,backendStopSupported:!!e.stopSupported,...e.stopReason?{backendStopReason:e.stopReason}:{}}}function fb(e){var n;return e.mode!=="send"||((n=e.payload.runId)==null?void 0:n.trim())?e:{...e,payload:{...e.payload,runId:cb()}}}function pb(e,t){var n,r,s;e.backendRunId=((n=t.runId)==null?void 0:n.trim())||e.backendRunId,e.backendStopSupported=typeof t.stopSupported=="boolean"?t.stopSupported:e.backendStopSupported,(r=t.stopReason)!=null&&r.trim()&&(e.backendStopReason=t.stopReason.trim()),(s=t.sessionKey)!=null&&s.trim()&&(e.sessionKey=t.sessionKey.trim())}function gb(){return{deltaMessageId:Da(),deltaStarted:!1,deltaClosed:!1,hasAssistantSessionEvent:!1,hasAssistantOutput:!1}}function mb(e){var t,n,r;return{driver:"nextbot-stream",kind:"ready",...(t=e.sessionKey)!=null&&t.trim()?{sessionKey:e.sessionKey.trim()}:{},...(n=e.runId)!=null&&n.trim()?{backendRunId:e.runId.trim()}:{},...typeof e.stopSupported=="boolean"?{stopSupported:e.stopSupported}:{},...(r=e.stopReason)!=null&&r.trim()?{stopReason:e.stopReason.trim()}:{},...e.requestedAt?{requestedAt:e.requestedAt}:{}}}function yb(e,t){return{driver:"nextbot-stream",kind:"final",sessionKey:e.sessionKey,reply:e.reply,hasAssistantSessionEvent:t}}function si(e,t,n){e({type:X.RUN_METADATA,runId:t,metadata:n})}function ii(e,t){!e.deltaStarted||e.deltaClosed||(t({type:X.TEXT_END,messageId:e.deltaMessageId}),e.deltaClosed=!0)}function xb(e,t,n){const r=Jx({messageId:e.deltaMessageId,delta:n.delta,started:e.deltaStarted});r.length>0&&(e.deltaStarted=!0,e.deltaClosed=!1,e.hasAssistantOutput=!0);for(const s of r)t(s)}function bb(e,t,n){Zx(n.data),eb(n.data)&&(e.hasAssistantSessionEvent=!0);for(const r of tb({event:n.data,messageId:e.deltaMessageId}))t(r)}function Sb(e,t,n){const r=n.trim();if(e.hasAssistantOutput||!r)return;const s=Da();t({type:X.TEXT_START,messageId:s}),t({type:X.TEXT_DELTA,messageId:s,delta:r}),t({type:X.TEXT_END,messageId:s})}class kb{constructor(){this.activeAbortController=null,this.activeRunState=null,this.buildMissingMetadataObservable=t=>new Qt(n=>{n.next({type:X.RUN_ERROR,runId:t,error:"nextbot runtime metadata is required"}),n.complete()}),this.openRunStream=t=>{const{metadata:n,signal:r,onReady:s,onDelta:i,onSessionEvent:o}=t;return n.mode==="send"?rb({item:n.payload,requestedSkills:n.requestedSkills,signal:r,onReady:s,onDelta:i,onSessionEvent:o}):sb({runId:n.runId,fromEventIndex:n.fromEventIndex,signal:r,onReady:s,onDelta:i,onSessionEvent:o})},this.finalizeRunState=(t,n)=>{this.activeAbortController===t&&(this.activeAbortController=null),this.activeRunState===n&&(this.activeRunState=null)},this.createRunObservable=({metadata:t,clientRunId:n,abortController:r,runState:s})=>new Qt(i=>{const o=gb();let a=!1;const l=c=>{a||i.next(c)};return l({type:X.RUN_STARTED,runId:n}),this.openRunStream({metadata:t,signal:r.signal,onReady:c=>{this.activeRunState&&pb(this.activeRunState,c),si(l,n,mb(c))},onDelta:c=>{xb(o,l,c)},onSessionEvent:c=>{bb(o,l,c)}}).then(c=>{ii(o,l),Sb(o,l,c.reply),si(l,n,yb(c,o.hasAssistantSessionEvent)),l({type:X.RUN_FINISHED,runId:n}),i.complete()}).catch(c=>{ii(o,l),rr(c)||l({type:X.RUN_ERROR,runId:n,error:c instanceof Error?c.message:String(c)}),i.complete()}).finally(()=>{this.finalizeRunState(r,s)}),()=>{a=!0,r.abort(),this.activeAbortController===r&&(this.activeAbortController=null)}}),this.abortRun=()=>{var n;const t=this.activeRunState;t!=null&&t.backendStopSupported&&ib(t),(n=this.activeAbortController)==null||n.abort(),this.activeAbortController=null,this.activeRunState=null},this.run=t=>{const n=db(t),r=typeof t.runId=="string"&&t.runId.trim()?t.runId:`run-${Date.now()}`;if(!n)return this.buildMissingMetadataObservable(r);const s=fb(n);this.abortRun();const i=new AbortController;this.activeAbortController=i;const o=hb(s);return this.activeRunState=o,this.createRunObservable({metadata:s,clientRunId:r,abortController:i,runState:o})}}}class vb{constructor(){this.chatUiManager=new ja,this.runtimeAgent=new kb,this.chatController=new px({agent:this.runtimeAgent,getToolDefs:()=>[],getContexts:()=>[],getToolExecutor:()=>{}},{metadataParsers:Hx}),this.chatStreamActionsManager=new Pa,this.chatInputManager=new Vx(this.chatUiManager,this.chatStreamActionsManager),this.chatSessionListManager=new Na(this.chatUiManager,this.chatStreamActionsManager),this.chatRunStatusManager=new La,this.chatThreadManager=new Xx(this.chatUiManager,this.chatSessionListManager,this.chatStreamActionsManager)}}function zt(e){const[t,n]=k.useState(e.getValue());return k.useEffect(()=>{const r=e.subscribe(n);return()=>r.unsubscribe()},[e]),t}function wb(e,t){const[n,r]=k.useState(t);return k.useEffect(()=>{const s=e.subscribe(r);return()=>s.unsubscribe()},[e]),n}function Cb(e,t){const n=k.useRef(e);k.useEffect(()=>{n.current=e});const r=k.useRef(null);k.useEffect(()=>{t.setCallbacks({onRunSettled:async({sourceSessionId:g,resultSessionId:v})=>{const C=n.current;await C.refetchSessions();const A=C.selectedSessionKeyRef.current;(!A||A===g||v&&A===v)&&await C.refetchHistory()},onRunError:({sourceMessage:g,restoreDraft:v})=>{v&&n.current.setDraft(C=>C.trim().length===0&&g?g:C)},onSessionChanged:g=>{n.current.setSelectedSessionKey(v=>v===g?v:g)}})},[t]);const s=wb(t.messages$,t.getMessages()),i=zt(t.isAgentResponding$),o=zt(t.isAwaitingResponse$),a=zt(t.activeRun$),l=zt(t.lastError$),u=(a==null?void 0:a.remoteRunId)??null,c=ux(a),d=!!(a&&(c===null||a.remoteStopCapable&&!u)),p=k.useCallback(async g=>{const v=_a(g.requestedSkills),C=qx(g,v);await t.send({message:g.message,sessionId:g.sessionKey,agentId:g.agentId,metadata:C,restoreDraftOnError:g.restoreDraftOnError,stopCapable:g.stopSupported,stopReason:g.stopReason})},[t]),f=k.useCallback(async g=>{var P,T;const v=(P=g.runId)==null?void 0:P.trim(),C=(T=g.sessionKey)==null?void 0:T.trim();if(!v||!C)return;const A=Wx(g);await t.resume({remoteRunId:v,sessionId:C,agentId:g.agentId,metadata:A,stopCapable:g.stopSupported,stopReason:g.stopReason})},[t]),m=k.useCallback(async()=>{await t.stop()},[t]),y=k.useCallback(()=>{r.current=null,t.reset()},[t]),b=k.useCallback((g,v)=>{if(!!(t.activeRun$.getValue()||t.isAgentResponding$.getValue()))return;const A=n.current.selectedSessionKeyRef.current;if(A!==r.current&&(r.current=A,t.getMessages().length>0&&t.setMessages([])),!A){t.getMessages().length>0&&t.setMessages([]);return}v!=null&&v.isLoading&&g.length===0||t.setMessages(ub(g))},[t]);return{uiMessages:s,isSending:i,isAwaitingAssistantOutput:o,canStopCurrentRun:d,stopDisabledReason:c,lastSendError:l,activeBackendRunId:u,sendMessage:p,stopCurrentRun:m,resumeRun:f,resetStreamState:y,applyHistoryMessages:b}}function Tb({view:e}){var Re,je,Ye;const[t]=k.useState(()=>new vb),n=re(ce=>ce.snapshot.query),r=re(ce=>ce.snapshot.selectedSessionKey),s=re(ce=>ce.snapshot.selectedAgentId),i=H(ce=>ce.snapshot.pendingSessionType),o=H(ce=>ce.snapshot.selectedModel),{confirm:a,ConfirmDialog:l}=dr(),u=Jt(),c=Ii(),{sessionId:d}=Mi(),p=k.useRef(null),f=k.useRef(r),m=k.useMemo(()=>Ea(d),[d]),{sessionsQuery:y,installedSkillsQuery:b,chatCapabilitiesQuery:g,historyQuery:v,isProviderStateResolved:C,modelOptions:A,sessions:P,skillRecords:T,selectedSession:F,historyMessages:B,sessionTypeOptions:z,defaultSessionType:w,selectedSessionType:D,canEditSessionType:N,sessionTypeUnavailable:$,sessionTypeUnavailableMessage:O}=Nu({query:n,selectedSessionKey:r,selectedAgentId:s,currentSelectedModel:o,pendingSessionType:i,setPendingSessionType:t.chatInputManager.setPendingSessionType,setSelectedModel:t.chatInputManager.setSelectedModel,setSelectedThinkingLevel:t.chatInputManager.setSelectedThinkingLevel}),{uiMessages:R,isSending:U,isAwaitingAssistantOutput:E,canStopCurrentRun:W,stopDisabledReason:se,lastSendError:x,activeBackendRunId:ae,sendMessage:ie,stopCurrentRun:S,resumeRun:he,resetStreamState:we,applyHistoryMessages:oe}=Cb({selectedSessionKeyRef:f,setSelectedSessionKey:t.chatSessionListManager.setSelectedSessionKey,setDraft:t.chatInputManager.setDraft,setComposerNodes:t.chatInputManager.setComposerNodes,refetchSessions:y.refetch,refetchHistory:v.refetch},t.chatController);k.useEffect(()=>{t.chatStreamActionsManager.bind({sendMessage:ie,stopCurrentRun:S,resumeRun:he,resetStreamState:we,applyHistoryMessages:oe})},[oe,t,we,he,ie,S]);const{sessionRunStatusByKey:pe}=Tu({view:e,selectedSessionKey:r,activeBackendRunId:ae,isLocallyRunning:U||!!ae,resumeRun:t.chatStreamActionsManager.resumeRun});Ia({view:e,routeSessionKey:m,selectedSessionKey:r,selectedAgentId:s,setSelectedSessionKey:t.chatSessionListManager.setSelectedSessionKey,setSelectedAgentId:t.chatSessionListManager.setSelectedAgentId,selectedSessionKeyRef:f,resetStreamState:t.chatStreamActionsManager.resetStreamState,resolveAgentIdFromSessionKey:Ra}),k.useEffect(()=>{t.chatStreamActionsManager.applyHistoryMessages(B,{isLoading:v.isLoading})},[B,v.isLoading,t]),k.useEffect(()=>{t.chatUiManager.syncState({pathname:u.pathname}),t.chatUiManager.bindActions({navigate:c,confirm:a})},[a,u.pathname,c,t]);const Se=F?Wi(F):void 0,Me=((Re=z.find(ce=>ce.value===D))==null?void 0:Re.label)??lt(D);return k.useEffect(()=>{t.chatThreadManager.bindActions({refetchSessions:y.refetch})},[t,y.refetch]),k.useEffect(()=>{var ce,G;t.chatInputManager.syncSnapshot({isProviderStateResolved:C,defaultSessionType:w,canStopGeneration:W,stopDisabledReason:se,stopSupported:((ce=g.data)==null?void 0:ce.stopSupported)??!1,stopReason:(G=g.data)==null?void 0:G.stopReason,sendError:x,isSending:U,modelOptions:A,sessionTypeOptions:z,selectedSessionType:D,canEditSessionType:N,sessionTypeUnavailable:$,skillRecords:T,isSkillsLoading:b.isLoading}),t.chatSessionListManager.syncSnapshot({sessions:P,query:n,isLoading:y.isLoading}),t.chatRunStatusManager.syncSnapshot({sessionRunStatusByKey:pe,isLocallyRunning:U||!!ae,activeBackendRunId:ae}),t.chatThreadManager.syncSnapshot({isProviderStateResolved:C,modelOptions:A,sessionTypeUnavailable:$,sessionTypeUnavailableMessage:O,sessionTypeLabel:Me,selectedSessionKey:r,sessionDisplayName:Se,canDeleteSession:!!F,threadRef:p,isHistoryLoading:v.isLoading,uiMessages:R,isSending:U,isAwaitingAssistantOutput:E})},[ae,N,W,Se,Me,(je=g.data)==null?void 0:je.stopReason,(Ye=g.data)==null?void 0:Ye.stopSupported,w,v.isLoading,b.isLoading,E,C,U,x,A.length,A,t,n,F,r,D,pe,z,$,O,P,y.isLoading,T,se,p,R]),h.jsx(Qi,{presenter:t,children:h.jsx(Ma,{view:e,confirmDialog:h.jsx(l,{})})})}var ne=(e=>(e.EndpointReady="endpoint.ready",e.EndpointError="endpoint.error",e.MessageRequest="message.request",e.MessageStreamRequest="message.stream-request",e.MessageSent="message.sent",e.MessageAccepted="message.accepted",e.MessageIncoming="message.incoming",e.MessageCompleted="message.completed",e.MessageFailed="message.failed",e.MessageAbort="message.abort",e.MessageTextStart="message.text-start",e.MessageTextDelta="message.text-delta",e.MessageTextEnd="message.text-end",e.MessageReasoningStart="message.reasoning-start",e.MessageReasoningDelta="message.reasoning-delta",e.MessageReasoningEnd="message.reasoning-end",e.MessageToolCallStart="message.tool-call-start",e.MessageToolCallArgs="message.tool-call-args",e.MessageToolCallArgsDelta="message.tool-call-args-delta",e.MessageToolCallEnd="message.tool-call-end",e.MessageToolCallResult="message.tool-call-result",e.MessageRead="message.read",e.MessageDelivered="message.delivered",e.MessageRecalled="message.recalled",e.MessageReaction="message.reaction",e.RunStarted="run.started",e.RunFinished="run.finished",e.RunError="run.error",e.RunMetadata="run.metadata",e.TypingStart="typing.start",e.TypingEnd="typing.end",e.PresenceUpdated="presence.updated",e))(ne||{}),oi=/\[\[\s*reply_to_current\s*\]\]/gi,ai=/\[\[\s*reply_to\s*:\s*([^\]]+?)\s*\]\]/i;function ir(e){if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0}function Ib(e,t){var i;let n=e,r;oi.test(n)&&(r=ir(t),n=n.replace(oi,"").trim());const s=(i=n.match(ai))==null?void 0:i[1];return s&&(r=ir(s),n=n.replace(ai,"").trim()),r?{content:n,replyTo:r}:{content:n}}function Mb(e,t=e.id){if(e.role!=="assistant")return{...e,parts:[...e.parts],metadata:e.metadata?{...e.metadata}:void 0};const n=e.parts.findIndex(c=>c.type==="text"),r=e.metadata?{...e.metadata}:void 0,s=ir(r==null?void 0:r.reply_to);if(n<0)return{...e,parts:[...e.parts],metadata:r};const i=e.parts[n];if(!i||i.type!=="text")return{...e,parts:[...e.parts],metadata:r};const{content:o,replyTo:a}=Ib(i.text,t),l=a??s,u=e.parts.flatMap((c,d)=>d!==n||c.type!=="text"?[c]:o.length===0?[]:[{...c,text:o}]);return l?{...e,parts:u,metadata:{...r,reply_to:l}}:{...e,parts:u,metadata:r}}function li(e){const t=e.split(/\r?\n/);let n="message";const r=[];for(const s of t){const i=s.trimEnd();if(!(!i||i.startsWith(":"))){if(i.startsWith("event:")){n=i.slice(6).trim()||"message";continue}i.startsWith("data:")&&r.push(i.slice(5).trimStart())}}return r.length===0?null:{event:n,data:r.join(`
37
+ `):"",this.name="UnsubscriptionError",this.errors=n}});function er(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var an=(function(){function e(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var t,n,r,s,i;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=jn(o),l=a.next();!l.done;l=a.next()){var u=l.value;u.remove(this)}}catch(y){t={error:y}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}else o.remove(this);var c=this.initialTeardown;if(We(c))try{c()}catch(y){i=y instanceof Rn?y.errors:[y]}var d=this._finalizers;if(d){this._finalizers=null;try{for(var p=jn(d),f=p.next();!f.done;f=p.next()){var m=f.value;try{Ws(m)}catch(y){i=i??[],y instanceof Rn?i=Dn(Dn([],_n(i)),_n(y.errors)):i.push(y)}}}catch(y){r={error:y}}finally{try{f&&!f.done&&(s=p.return)&&s.call(p)}finally{if(r)throw r.error}}}if(i)throw new Rn(i)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)Ws(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(t)}},e.prototype._hasParent=function(t){var n=this._parentage;return n===t||Array.isArray(n)&&n.includes(t)},e.prototype._addParent=function(t){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(t),n):n?[n,t]:t},e.prototype._removeParent=function(t){var n=this._parentage;n===t?this._parentage=null:Array.isArray(n)&&er(n,t)},e.prototype.remove=function(t){var n=this._finalizers;n&&er(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e})(),wa=an.EMPTY;function Ca(e){return e instanceof an||e&&"closed"in e&&We(e.remove)&&We(e.add)&&We(e.unsubscribe)}function Ws(e){We(e)?e():e.unsubscribe()}var Wy={Promise:void 0},Gy={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setTimeout.apply(void 0,Dn([e,t],_n(n)))},clearTimeout:function(e){return clearTimeout(e)},delegate:void 0};function Qy(e){Gy.setTimeout(function(){throw e})}function Gs(){}function Ut(e){e()}var Ta=(function(e){Mt(t,e);function t(n){var r=e.call(this)||this;return r.isStopped=!1,n?(r.destination=n,Ca(n)&&n.add(r)):r.destination=Jy,r}return t.create=function(n,r,s){return new tr(n,r,s)},t.prototype.next=function(n){this.isStopped||this._next(n)},t.prototype.error=function(n){this.isStopped||(this.isStopped=!0,this._error(n))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(n){this.destination.next(n)},t.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t})(an),Xy=(function(){function e(t){this.partialObserver=t}return e.prototype.next=function(t){var n=this.partialObserver;if(n.next)try{n.next(t)}catch(r){Ft(r)}},e.prototype.error=function(t){var n=this.partialObserver;if(n.error)try{n.error(t)}catch(r){Ft(r)}else Ft(t)},e.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(n){Ft(n)}},e})(),tr=(function(e){Mt(t,e);function t(n,r,s){var i=e.call(this)||this,o;return We(n)||!n?o={next:n??void 0,error:r??void 0,complete:s??void 0}:o=n,i.destination=new Xy(o),i}return t})(Ta);function Ft(e){Qy(e)}function Yy(e){throw e}var Jy={closed:!0,next:Gs,error:Yy,complete:Gs},Zy=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function ex(e){return e}function tx(e){return e.length===0?ex:e.length===1?e[0]:function(n){return e.reduce(function(r,s){return s(r)},n)}}var Qt=(function(){function e(t){t&&(this._subscribe=t)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(t,n,r){var s=this,i=rx(t)?t:new tr(t,n,r);return Ut(function(){var o=s,a=o.operator,l=o.source;i.add(a?a.call(i,l):l?s._subscribe(i):s._trySubscribe(i))}),i},e.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(n){t.error(n)}},e.prototype.forEach=function(t,n){var r=this;return n=Qs(n),new n(function(s,i){var o=new tr({next:function(a){try{t(a)}catch(l){i(l),o.unsubscribe()}},error:i,complete:s});r.subscribe(o)})},e.prototype._subscribe=function(t){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(t)},e.prototype[Zy]=function(){return this},e.prototype.pipe=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return tx(t)(this)},e.prototype.toPromise=function(t){var n=this;return t=Qs(t),new t(function(r,s){var i;n.subscribe(function(o){return i=o},function(o){return s(o)},function(){return r(i)})})},e.create=function(t){return new e(t)},e})();function Qs(e){var t;return(t=e??Wy.Promise)!==null&&t!==void 0?t:Promise}function nx(e){return e&&We(e.next)&&We(e.error)&&We(e.complete)}function rx(e){return e&&e instanceof Ta||nx(e)&&Ca(e)}var sx=va(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Ve=(function(e){Mt(t,e);function t(){var n=e.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return t.prototype.lift=function(n){var r=new Xs(this,this);return r.operator=n,r},t.prototype._throwIfClosed=function(){if(this.closed)throw new sx},t.prototype.next=function(n){var r=this;Ut(function(){var s,i;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var o=jn(r.currentObservers),a=o.next();!a.done;a=o.next()){var l=a.value;l.next(n)}}catch(u){s={error:u}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(s)throw s.error}}}})},t.prototype.error=function(n){var r=this;Ut(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var s=r.observers;s.length;)s.shift().error(n)}})},t.prototype.complete=function(){var n=this;Ut(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var r=n.observers;r.length;)r.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(n){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,n)},t.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},t.prototype._innerSubscribe=function(n){var r=this,s=this,i=s.hasError,o=s.isStopped,a=s.observers;return i||o?wa:(this.currentObservers=null,a.push(n),new an(function(){r.currentObservers=null,er(a,n)}))},t.prototype._checkFinalizedStatuses=function(n){var r=this,s=r.hasError,i=r.thrownError,o=r.isStopped;s?n.error(i):o&&n.complete()},t.prototype.asObservable=function(){var n=new Qt;return n.source=this,n},t.create=function(n,r){return new Xs(n,r)},t})(Qt),Xs=(function(e){Mt(t,e);function t(n,r){var s=e.call(this)||this;return s.destination=n,s.source=r,s}return t.prototype.next=function(n){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.next)===null||s===void 0||s.call(r,n)},t.prototype.error=function(n){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.error)===null||s===void 0||s.call(r,n)},t.prototype.complete=function(){var n,r;(r=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||r===void 0||r.call(n)},t.prototype._subscribe=function(n){var r,s;return(s=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&s!==void 0?s:wa},t})(Ve),it=(function(e){Mt(t,e);function t(n){var r=e.call(this)||this;return r._value=n,r}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(n){var r=e.prototype._subscribe.call(this,n);return!r.closed&&n.next(this._value),r},t.prototype.getValue=function(){var n=this,r=n.hasError,s=n.thrownError,i=n._value;if(r)throw s;return this._throwIfClosed(),i},t.prototype.next=function(n){e.prototype.next.call(this,this._value=n)},t})(Ve);const fe=[];for(let e=0;e<256;++e)fe.push((e+256).toString(16).slice(1));function ix(e,t=0){return(fe[e[t+0]]+fe[e[t+1]]+fe[e[t+2]]+fe[e[t+3]]+"-"+fe[e[t+4]]+fe[e[t+5]]+"-"+fe[e[t+6]]+fe[e[t+7]]+"-"+fe[e[t+8]]+fe[e[t+9]]+"-"+fe[e[t+10]]+fe[e[t+11]]+fe[e[t+12]]+fe[e[t+13]]+fe[e[t+14]]+fe[e[t+15]]).toLowerCase()}let En;const ox=new Uint8Array(16);function ax(){if(!En){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");En=crypto.getRandomValues.bind(crypto)}return En(ox)}const lx=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Ys={randomUUID:lx};function nr(e,t,n){var s;if(Ys.randomUUID&&!e)return Ys.randomUUID();e=e||{};const r=e.random??((s=e.rng)==null?void 0:s.call(e))??ax();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,ix(r)}var ue=(e=>(e.CALL="call",e.RESULT="result",e.PARTIAL_CALL="partial-call",e.ERROR="error",e.CANCELLED="cancelled",e))(ue||{}),X=(e=>(e.TEXT_START="TEXT_START",e.TEXT_DELTA="TEXT_DELTA",e.TEXT_END="TEXT_END",e.TOOL_CALL_START="TOOL_CALL_START",e.TOOL_CALL_ARGS="TOOL_CALL_ARGS",e.TOOL_CALL_ARGS_DELTA="TOOL_CALL_ARGS_DELTA",e.TOOL_CALL_END="TOOL_CALL_END",e.TOOL_CALL_RESULT="TOOL_CALL_RESULT",e.RUN_STARTED="RUN_STARTED",e.RUN_FINISHED="RUN_FINISHED",e.RUN_ERROR="RUN_ERROR",e.RUN_METADATA="RUN_METADATA",e.REASONING_START="REASONING_START",e.REASONING_DELTA="REASONING_DELTA",e.REASONING_END="REASONING_END",e))(X||{});function ux(e){return!e||e.remoteStopCapable&&e.remoteRunId?null:e.remoteStopCapable?"__preparing__":e.remoteStopReason??""}const cx=e=>{try{return JSON.parse(e)}catch{return}},Js=e=>({toolCallId:e.id,toolName:e.function.name,args:e.function.arguments,parsedArgs:cx(e.function.arguments),status:ue.CALL});function dx(e,t){const n={error:"tool_call_interrupted",note:"User continued before tool produced a result."};return e.map(r=>{var s;return(s=r.parts)!=null&&s.length?{...r,parts:r.parts.map(i=>{if(i.type!=="tool-invocation"||![ue.CALL,ue.PARTIAL_CALL].includes(i.toolInvocation.status))return i;let o;if(typeof i.toolInvocation.args=="string")try{o=JSON.parse(i.toolInvocation.args)}catch{return{...i,toolInvocation:{...i.toolInvocation,args:JSON.stringify({}),parsedArgs:o,status:ue.RESULT,result:{error:"invalid_args",raw:i.toolInvocation.args}}}}return{...i,toolInvocation:{...i.toolInvocation,args:i.toolInvocation.args,parsedArgs:o,status:ue.RESULT,result:n}}})}:r})}function rr(e){if(e instanceof DOMException&&e.name==="AbortError")return!0;if(e instanceof Error){if(e.name==="AbortError")return!0;const t=e.message.toLowerCase();return t.includes("aborted")||t.includes("abort")}return!1}function Zs(e){if(e instanceof Error){const n=e.message.trim();if(n)return n}return String(e??"").trim()||"Failed to send message"}function ei(e,t){return{id:`local-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,role:"assistant",parts:[{type:"text",text:e}],meta:{source:"local",status:(t==null?void 0:t.status)??"final",sessionKey:t==null?void 0:t.sessionKey,timestamp:new Date().toISOString()}}}class hx{constructor(t){_(this,"currentMessageId");_(this,"currentReasoningMessageId");_(this,"currentReasoningContent","");_(this,"currentToolCallId");_(this,"currentToolCallMessageId");_(this,"currentToolCallName");_(this,"currentToolCallArgs","");_(this,"emittedToolCallIds",new Set);this.sessionManager=t}findAssistantMessageById(t){const n=t==null?void 0:t.trim();return n?this.sessionManager.getMessages().find(s=>s.role==="assistant"&&s.id===n)??null:null}findAssistantMessageByToolCallId(t){var r;if(!t)return null;const n=this.sessionManager.getMessages();for(let s=n.length-1;s>=0;s-=1){const i=n[s];if(i.role!=="assistant")continue;if((r=i.parts)==null?void 0:r.some(a=>a.type==="tool-invocation"&&a.toolInvocation.toolCallId===t))return i}return null}findAssistantMessageForCurrentTool(t){var r;const n=this.findAssistantMessageById(this.currentToolCallMessageId);return(r=n==null?void 0:n.parts)!=null&&r.some(s=>s.type==="tool-invocation"&&s.toolInvocation.toolCallId===t)?n:this.findAssistantMessageByToolCallId(t)}reset(){this.currentMessageId=void 0,this.currentReasoningMessageId=void 0,this.currentReasoningContent="",this.currentToolCallId=void 0,this.currentToolCallMessageId=void 0,this.currentToolCallName=void 0,this.currentToolCallArgs="",this.emittedToolCallIds.clear()}emitToolCallEvents(){const t=this.sessionManager.getMessages();for(const n of t)if(!(n.role!=="assistant"||!n.parts))for(const r of n.parts){if(r.type!=="tool-invocation")continue;const s=r.toolInvocation;s.status===ue.CALL&&!this.emittedToolCallIds.has(s.toolCallId)&&(this.emittedToolCallIds.add(s.toolCallId),this.sessionManager.toolCall$.next({toolCall:{id:s.toolCallId,type:"function",function:{name:s.toolName,arguments:s.args}}}))}}handleEvent(t){switch(t.type){case X.RUN_STARTED:break;case X.TEXT_START:this.handleTextStart(t);break;case X.TEXT_DELTA:this.handleTextContent(t);break;case X.TEXT_END:this.handleTextEnd();break;case X.REASONING_START:this.handleReasoningStart(t);break;case X.REASONING_DELTA:this.handleReasoningContent(t);break;case X.REASONING_END:this.handleReasoningEnd();break;case X.TOOL_CALL_START:this.handleToolCallStart(t);break;case X.TOOL_CALL_ARGS_DELTA:this.handleToolCallArgsDelta(t);break;case X.TOOL_CALL_ARGS:this.handleToolCallArgs(t);break;case X.TOOL_CALL_END:this.handleToolCallEnd(),this.emitToolCallEvents();break;case X.TOOL_CALL_RESULT:this.handleToolCallResult(t);break}}handleTextStart(t){this.currentMessageId=t.messageId}appendTextDelta(t,n){const r=[...t.parts||[]],s=r[r.length-1];return s&&s.type==="text"?{...t,parts:[...r.slice(0,-1),{type:"text",text:`${s.text}${n}`}]}:{...t,parts:[...r,{type:"text",text:n}]}}handleTextContent(t){if(!t.delta||this.currentMessageId!==t.messageId)return;const r=this.sessionManager.getMessages().find(s=>s.role==="assistant"&&s.id===this.currentMessageId);r?this.sessionManager.updateMessage(this.appendTextDelta(r,t.delta)):this.sessionManager.addMessages([{id:this.currentMessageId,role:"assistant",parts:[{type:"text",text:t.delta}]}])}handleTextEnd(){this.currentMessageId=void 0}updateReasoningPart(t,n){var i;const r=[...t.parts||[]];let s=-1;for(let o=r.length-1;o>=0;o-=1)if(((i=r[o])==null?void 0:i.type)==="reasoning"){s=o;break}return s>=0?{...t,parts:[...r.slice(0,s),{type:"reasoning",reasoning:n,details:[]},...r.slice(s+1)]}:{...t,parts:[...r,{type:"reasoning",reasoning:n,details:[]}]}}handleReasoningStart(t){this.currentReasoningMessageId=t.messageId,this.currentReasoningContent=""}handleReasoningContent(t){if(!t.delta||this.currentReasoningMessageId!==t.messageId)return;this.currentReasoningContent+=t.delta;const n=this.currentReasoningContent,r=this.currentReasoningMessageId,i=this.sessionManager.getMessages().find(o=>o.role==="assistant"&&o.id===r);i?this.sessionManager.updateMessage(this.updateReasoningPart(i,n)):this.sessionManager.addMessages([{id:r,role:"assistant",parts:[{type:"reasoning",reasoning:n,details:[]}]}])}handleReasoningEnd(){this.currentReasoningMessageId=void 0,this.currentReasoningContent=""}handleToolCallStart(t){var l;this.currentToolCallId=t.toolCallId,this.currentToolCallName=t.toolName,this.currentToolCallArgs="",this.currentToolCallMessageId=t.messageId;const n={type:"tool-invocation",toolInvocation:{status:ue.PARTIAL_CALL,toolCallId:this.currentToolCallId,toolName:this.currentToolCallName,args:""}},r=this.sessionManager.getMessages(),s=(l=t.messageId)==null?void 0:l.trim(),i=this.findAssistantMessageById(s);if(i){this.currentToolCallMessageId=i.id;const u=i.parts.find(c=>c.type==="tool-invocation"&&c.toolInvocation.toolCallId===this.currentToolCallId);if(u&&u.type==="tool-invocation"){this.currentToolCallArgs=u.toolInvocation.args;return}this.sessionManager.updateMessage({...i,parts:[...i.parts||[],n]});return}if(s){this.currentToolCallMessageId=s,this.sessionManager.addMessages([{id:s,role:"assistant",parts:[n]}]);return}const o=this.findAssistantMessageByToolCallId(this.currentToolCallId);if(o){this.currentToolCallMessageId=o.id;const u=o.parts.find(c=>c.type==="tool-invocation"&&c.toolInvocation.toolCallId===this.currentToolCallId);this.currentToolCallArgs=(u==null?void 0:u.type)==="tool-invocation"?u.toolInvocation.args:"";return}const a=r[r.length-1];if(a&&a.role==="assistant")this.currentToolCallMessageId=a.id,this.sessionManager.updateMessage({...a,parts:[...a.parts||[],n]});else{const u=nr();this.currentToolCallMessageId=u,this.sessionManager.addMessages([{id:u,role:"assistant",parts:[n]}])}}handleToolCallArgsDelta(t){var s;if(this.currentToolCallId!==t.toolCallId)return;this.currentToolCallArgs+=t.argsDelta;const n=this.findAssistantMessageForCurrentTool(t.toolCallId);if(!n||n.role!=="assistant"||!((s=n.parts)!=null&&s.length))return;const r=[...n.parts];for(let i=r.length-1;i>=0;i--){const o=r[i];if(o.type==="tool-invocation"&&o.toolInvocation.toolCallId===t.toolCallId){let a;try{a=JSON.parse(this.currentToolCallArgs)}catch{}r[i]={...o,toolInvocation:{...o.toolInvocation,status:ue.PARTIAL_CALL,args:this.currentToolCallArgs,parsedArgs:a}};break}}this.sessionManager.updateMessage({...n,parts:r})}handleToolCallArgs(t){this.currentToolCallId===t.toolCallId&&(this.currentToolCallArgs=t.args,this.handleToolCallArgsDelta({type:X.TOOL_CALL_ARGS_DELTA,toolCallId:t.toolCallId,argsDelta:""}))}handleToolCallEnd(){var t;if(!(!this.currentToolCallId||!this.currentToolCallName)){try{const n={id:this.currentToolCallId,type:"function",function:{name:this.currentToolCallName,arguments:this.currentToolCallArgs}},r=this.findAssistantMessageForCurrentTool(this.currentToolCallId);if(r&&r.role==="assistant"){const s=[...r.parts||[]];for(let i=s.length-1;i>=0;i--){const o=s[i];if(o.type==="tool-invocation"&&o.toolInvocation.toolCallId===this.currentToolCallId){s[i]={...o,toolInvocation:{...Js(n),status:ue.CALL}};break}}this.sessionManager.updateMessage({...r,parts:s})}else{const s=((t=this.currentToolCallMessageId)==null?void 0:t.trim())||nr();this.sessionManager.addMessages([{id:s,role:"assistant",parts:[{type:"tool-invocation",toolInvocation:{...Js(n),status:ue.CALL}}]}])}}catch{}this.currentToolCallId=void 0,this.currentToolCallMessageId=void 0,this.currentToolCallName=void 0,this.currentToolCallArgs=""}}handleToolCallResult(t){this.sessionManager.addToolResult({toolCallId:t.toolCallId,result:t.content,status:ue.RESULT})}}class fx{constructor(){_(this,"disposables",[]);_(this,"addDisposable",t=>{this.disposables.push(t)});_(this,"dispose",()=>{this.disposables.forEach(t=>t()),this.disposables=[]})}}class px extends fx{constructor(n=null,r){super();_(this,"_messages$",new it([]));_(this,"messages$");_(this,"threadId$",new it(null));_(this,"isAgentResponding$",new it(!1));_(this,"activeRun$",new it(null));_(this,"lastError$",new it(null));_(this,"isAwaitingResponse$",new it(!1));_(this,"runCompleted$",new Ve);_(this,"runError$",new Ve);_(this,"runMetadata$",new Ve);_(this,"activeSubscription",null);_(this,"addMessagesEvent$",new Ve);_(this,"updateMessageEvent$",new Ve);_(this,"setMessagesEvent$",new Ve);_(this,"toolCall$",new Ve);_(this,"eventHandler",new hx(this));_(this,"runIdCounter",0);_(this,"metadataParsers");_(this,"callbacks");_(this,"getMessages",()=>this._messages$.getValue());_(this,"setMessages",n=>{this._messages$.next(n),this.setMessagesEvent$.next({messages:n})});_(this,"handleEvent",n=>{this.eventHandler.handleEvent(n)});_(this,"setCallbacks",n=>{this.callbacks=n});_(this,"reset",()=>{this.abortAgentRun(),this._messages$.next([]),this.eventHandler.reset(),this.threadId$.next(null),this.isAgentResponding$.next(!1),this.activeRun$.next(null),this.lastError$.next(null),this.isAwaitingResponse$.next(!1),this.runIdCounter+=1});_(this,"addMessages",n=>{const s=[...this.getMessages()];for(const i of n){const o=s.findIndex(a=>a.id===i.id);o>=0?s[o]=i:s.push(i)}this._messages$.next(s),this.addMessagesEvent$.next({messages:n}),this.isAwaitingResponse$.getValue()&&n.some(i=>i.role==="assistant")&&this.isAwaitingResponse$.next(!1)});_(this,"removeMessages",n=>{n.length!==0&&this._messages$.next(this.getMessages().filter(r=>!n.includes(r.id)))});_(this,"updateMessage",n=>{this._messages$.next(this.getMessages().map(r=>r.id===n.id?n:r)),this.updateMessageEvent$.next({message:n}),this.isAwaitingResponse$.getValue()&&n.role==="assistant"&&this.isAwaitingResponse$.next(!1)});_(this,"addToolResult",(n,r)=>{const s=this.getMessages().find(o=>o.parts.find(a=>a.type==="tool-invocation"&&a.toolInvocation.toolCallId===n.toolCallId));if(!s)return;const i={...s,parts:s.parts.map(o=>o.type==="tool-invocation"&&o.toolInvocation.toolCallId===n.toolCallId?{...o,toolInvocation:{...o.toolInvocation,result:n.result??void 0,status:n.status,error:n.error??void 0,cancelled:n.cancelled??void 0}}:o)};this.updateMessage(i)});_(this,"send",async n=>{(this.activeRun$.getValue()||this.activeSubscription)&&this.abortAgentRun(),this.lastError$.next(null);const r=n.message.trim();r&&(this.addMessages([{id:nr(),role:"user",parts:[{type:"text",text:r}]}]),await this.runAgent({metadata:n.metadata,sessionId:n.sessionId,agentId:n.agentId,stopCapable:n.stopCapable,stopReason:n.stopReason,sourceMessage:r,restoreDraftOnError:n.restoreDraftOnError}))});_(this,"resume",async n=>{var o,a;const r=(o=n.remoteRunId)==null?void 0:o.trim(),s=(a=n.sessionId)==null?void 0:a.trim();if(!r)return;const i=this.activeRun$.getValue();(i==null?void 0:i.remoteRunId)!==r&&(i||(this.lastError$.next(null),await this.runAgent({metadata:n.metadata,sessionId:s,agentId:n.agentId,stopCapable:n.stopCapable,stopReason:n.stopReason})))});_(this,"stop",async()=>{var s,i;const n=this.activeRun$.getValue();if(!n)return;const r=n.sessionId;this.abortAgentRun(),r&&await((i=(s=this.callbacks).onRunSettled)==null?void 0:i.call(s,{sourceSessionId:r}))});_(this,"handleAgentResponse",n=>{this.activeSubscription&&this.activeSubscription.unsubscribe(),this.activeSubscription=n.subscribe(r=>{var s,i,o,a,l,u,c,d,p;if(r.type===X.RUN_METADATA){const f=r,m=this.activeRun$.getValue(),y=((s=f.runId)==null?void 0:s.trim())||(m?`ui-${m.localRunId}`:"");this.metadataParsers&&m&&this.isMatchingRun(m,y)&&this.processRunMetadata(m,f.metadata),this.runMetadata$.next({runId:y,metadata:f.metadata});return}if(this.handleEvent(r),r.type===X.RUN_FINISHED){this.isAgentResponding$.next(!1),this.isAwaitingResponse$.next(!1),this.activeSubscription=null;const f=this.activeRun$.getValue(),m=((i=r.runId)==null?void 0:i.trim())||(f?`ui-${f.localRunId}`:"");if(!f||!this.isMatchingRun(f,m))return;const y=f.sessionId;this.activeRun$.next(null),y&&((a=(o=this.callbacks).onRunSettled)==null||a.call(o,{sourceSessionId:y}))}else if(r.type===X.RUN_ERROR){this.isAgentResponding$.next(!1),this.isAwaitingResponse$.next(!1),this.activeSubscription=null;const f=this.activeRun$.getValue(),m=((l=r.runId)==null?void 0:l.trim())||(f?`ui-${f.localRunId}`:""),y=rr(r.error);if(this.runError$.next({runId:m,error:r.error,isAbort:y}),!f||!this.isMatchingRun(f,m)){this.activeRun$.next(null);return}const b=f.sessionId;if(y){this.activeRun$.next(null),b&&((c=(u=this.callbacks).onRunSettled)==null||c.call(u,{sourceSessionId:b}));return}const g=Zs(r.error);this.lastError$.next(g),this.activeRun$.next(null),b&&this.addMessages([ei(g,{sessionKey:b,status:"error"})]),(p=(d=this.callbacks).onRunError)==null||p.call(d,{error:g,sourceMessage:f.sourceMessage,restoreDraft:f.restoreDraftOnError})}})});_(this,"abortAgentRun",()=>{var n,r,s;(s=(n=this.agentProvider)==null?void 0:(r=n.agent).abortRun)==null||s.call(r),this.activeSubscription&&(this.activeSubscription.unsubscribe(),this.activeSubscription=null,this.isAgentResponding$.next(!1),this.isAwaitingResponse$.next(!1)),this.activeRun$.next(null)});_(this,"runAgent",async n=>{var o,a,l,u;if(!this.agentProvider)return;(this.activeRun$.getValue()||this.activeSubscription)&&this.abortAgentRun();const r=++this.runIdCounter,s=`ui-${r}`,i={localRunId:r,sessionId:n==null?void 0:n.sessionId,...n!=null&&n.agentId?{agentId:n.agentId}:{},remoteStopCapable:!!(n!=null&&n.stopCapable),...n!=null&&n.stopReason?{remoteStopReason:n.stopReason}:{},sourceMessage:n==null?void 0:n.sourceMessage,restoreDraftOnError:n==null?void 0:n.restoreDraftOnError};this.activeRun$.next(i),this.isAgentResponding$.next(!0),this.isAwaitingResponse$.next(!0);try{const c=dx(this.getMessages()),d=typeof(n==null?void 0:n.threadId)=="string"&&n.threadId.trim()?n.threadId:this.threadId$.getValue()??"",p=await this.agentProvider.agent.run({threadId:d,runId:s,messages:c,tools:this.agentProvider.getToolDefs(),context:this.agentProvider.getContexts(),...n!=null&&n.metadata?{metadata:n.metadata}:{}});this.handleAgentResponse(p)}catch(c){const d=rr(c);d?console.info("Agent run aborted"):console.error("Error running agent:",c),this.isAgentResponding$.next(!1),this.isAwaitingResponse$.next(!1);const p=this.activeRun$.getValue();if(this.activeRun$.next(null),this.runError$.next({runId:s,error:c,isAbort:d}),!d&&p){const f=Zs(c);this.lastError$.next(f),p.sessionId&&this.addMessages([ei(f,{sessionKey:p.sessionId,status:"error"})]),(a=(o=this.callbacks).onRunError)==null||a.call(o,{error:f,sourceMessage:p.sourceMessage,restoreDraft:p.restoreDraftOnError})}else d&&(p!=null&&p.sessionId)&&((u=(l=this.callbacks).onRunSettled)==null||u.call(l,{sourceSessionId:p.sessionId}))}});_(this,"processRunMetadata",(n,r)=>{if(!this.metadataParsers)return;const s=this.metadataParsers.parseReady(r);if(s){this.applyReadyMetadata(n,s);return}const i=this.metadataParsers.parseFinal(r);i&&this.applyFinalMetadata(n,i)});_(this,"applyReadyMetadata",(n,r)=>{var i,o,a,l,u;const s={...n};(i=r.remoteRunId)!=null&&i.trim()&&(s.remoteRunId=r.remoteRunId.trim()),typeof r.stopCapable=="boolean"&&(s.remoteStopCapable=r.stopCapable),(o=r.stopReason)!=null&&o.trim()&&(s.remoteStopReason=r.stopReason.trim()),(a=r.sessionId)!=null&&a.trim()&&(s.sessionId=r.sessionId.trim(),(u=(l=this.callbacks).onSessionChanged)==null||u.call(l,s.sessionId)),this.activeRun$.next(s)});_(this,"applyFinalMetadata",(n,r)=>{var o,a,l,u;const s=n.sessionId,i=r.sessionId;i&&i!==s&&((a=(o=this.callbacks).onSessionChanged)==null||a.call(o,i)),this.activeRun$.next(null),s&&((u=(l=this.callbacks).onRunSettled)==null||u.call(l,{sourceSessionId:s,resultSessionId:i}))});_(this,"isMatchingRun",(n,r)=>r.trim()?r===`ui-${n.localRunId}`:!1);_(this,"connectToolExecutor",()=>{const n=this.toolCall$.subscribe(async({toolCall:r})=>{var i;const s=(i=this.agentProvider)==null?void 0:i.getToolExecutor(r.function.name);if(s)try{const o=JSON.parse(r.function.arguments),a=await s(o);this.addToolResult({toolCallId:r.id,result:a,status:ue.RESULT}),this.runAgent()}catch(o){console.error("[AgentChatController] handleAddToolResult error",o),this.addToolResult({toolCallId:r.id,error:o instanceof Error?o.message:String(o),status:ue.ERROR}),this.runAgent()}});return()=>n.unsubscribe()});this.agentProvider=n;const{initialMessages:s=[],metadataParsers:i,callbacks:o={}}=r||{};this.metadataParsers=i??null,this.callbacks=o,this._messages$.next(s),this.messages$=this._messages$.asObservable(),this.agentProvider&&this.addDisposable(this.connectToolExecutor())}}const gx=/\u200B|\u200C|\u200D|\u2060|\uFEFF/g;function mx(e){return typeof e=="object"&&e!==null}function yx(e){return e.type==="text"&&typeof e.text=="string"}function xx(e){return e.type==="reasoning"&&typeof e.reasoning=="string"}function bx(e){return e.type!=="tool-invocation"||!mx(e.toolInvocation)?!1:typeof e.toolInvocation.toolName=="string"}function Sx(e){var n;const t=(n=e.meta)==null?void 0:n.timestamp;return t&&Number.isFinite(Date.parse(t))?t:new Date().toISOString()}function kx(e,t){return e==="user"?t.user:e==="assistant"?t.assistant:e==="tool"?t.tool:e==="system"?t.system:t.fallback}function vx(e){return e==="user"||e==="assistant"||e==="tool"||e==="system"?e:"message"}function wx(e,t){return{kind:e.kind,toolName:e.name,summary:e.detail,output:e.text,hasResult:!!e.hasResult,titleLabel:e.kind==="call"?t.toolCallLabel:t.toolResultLabel,outputLabel:t.toolOutputLabel,emptyLabel:t.toolNoOutputLabel}}function ti(e){const t=e.trim();return t&&t.replace(gx,"").trim()?t:null}function Cx(e){return e.uiMessages.map(t=>{var n;return{id:t.id,role:vx(t.role),roleLabel:kx(t.role,e.texts.roleLabels),timestampLabel:e.formatTimestamp(Sx(t)),status:(n=t.meta)==null?void 0:n.status,parts:t.parts.map(r=>{if(yx(r)){const s=ti(r.text);return s?{type:"markdown",text:s}:null}if(xx(r)){const s=ti(r.reasoning);return s?{type:"reasoning",text:s,label:e.texts.reasoningLabel}:null}if(bx(r)){const s=r.toolInvocation,i=iu(s.parsedArgs??s.args),o=typeof s.error=="string"&&s.error.trim()?s.error.trim():s.result!=null?Vr(s.result).trim():"",a=s.status==="result"||s.status==="error"||s.status==="cancelled",l={kind:a?"result":"call",name:s.toolName,detail:i,text:o||void 0,callId:s.toolCallId||void 0,hasResult:a};return{type:"tool-card",card:wx(l,e.texts)}}return{type:"unknown",label:e.texts.unknownPartLabel,rawType:typeof r.type=="string"?r.type:"unknown",text:Vr(r)}}).filter(r=>r!==null)}})}function Tx(e){const{language:t}=fr(),n=k.useMemo(()=>e.uiMessages.map(s=>{var i,o;return{id:s.id,role:s.role,meta:{timestamp:(i=s.meta)==null?void 0:i.timestamp,status:(o=s.meta)==null?void 0:o.status},parts:s.parts}}),[e.uiMessages]),r=k.useMemo(()=>Cx({uiMessages:n,formatTimestamp:s=>Zt(s,t),texts:{roleLabels:{user:I("chatRoleUser"),assistant:I("chatRoleAssistant"),tool:I("chatRoleTool"),system:I("chatRoleSystem"),fallback:I("chatRoleMessage")},reasoningLabel:I("chatReasoning"),toolCallLabel:I("chatToolCall"),toolResultLabel:I("chatToolResult"),toolNoOutputLabel:I("chatToolNoOutput"),toolOutputLabel:I("chatToolOutput"),unknownPartLabel:I("chatUnknownPart")}}),[t,n]);return h.jsx(wy,{messages:r,isSending:e.isSending,hasAssistantDraft:e.uiMessages.some(s=>{var i,o;return s.role==="assistant"&&(((i=s.meta)==null?void 0:i.status)==="streaming"||((o=s.meta)==null?void 0:o.status)==="pending")}),className:e.className,texts:{copyCodeLabel:I("chatCodeCopy"),copiedCodeLabel:I("chatCodeCopied"),typingLabel:I("chatTyping")}})}const Ix=[{icon:Rl,titleKey:"chatWelcomeCapability1Title",descKey:"chatWelcomeCapability1Desc"},{icon:lr,titleKey:"chatWelcomeCapability2Title",descKey:"chatWelcomeCapability2Desc"},{icon:cr,titleKey:"chatWelcomeCapability3Title",descKey:"chatWelcomeCapability3Desc"}];function Mx({onCreateSession:e}){return h.jsx("div",{className:"h-full flex items-center justify-center p-8",children:h.jsxs("div",{className:"max-w-lg w-full text-center",children:[h.jsx("div",{className:"mx-auto mb-6 h-16 w-16 rounded-2xl bg-primary/10 flex items-center justify-center",children:h.jsx(wi,{className:"h-8 w-8 text-primary"})}),h.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:I("chatWelcomeTitle")}),h.jsx("p",{className:"text-sm text-gray-500 mb-8",children:I("chatWelcomeSubtitle")}),h.jsx("div",{className:"grid grid-cols-3 gap-3",children:Ix.map(t=>{const n=t.icon;return h.jsxs("button",{onClick:e,className:"rounded-2xl border border-gray-200 bg-white p-4 text-left shadow-card hover:shadow-card-hover transition-shadow cursor-pointer",children:[h.jsx("div",{className:"h-9 w-9 rounded-xl bg-primary/8 flex items-center justify-center mb-3",children:h.jsx(n,{className:"h-4.5 w-4.5 text-primary"})}),h.jsx("div",{className:"text-sm font-semibold text-gray-900 mb-1",children:I(t.titleKey)}),h.jsx("div",{className:"text-[11px] text-gray-500 leading-relaxed",children:I(t.descKey)})]},t.titleKey)})})]})})}const Rx={isProviderStateResolved:!1,modelOptions:[],sessionTypeUnavailable:!1,sessionTypeUnavailableMessage:null,sessionTypeLabel:null,selectedSessionKey:null,sessionDisplayName:void 0,canDeleteSession:!1,isDeletePending:!1,threadRef:null,isHistoryLoading:!1,uiMessages:[],isSending:!1,isAwaitingAssistantOutput:!1},qe=Yt(e=>({snapshot:Rx,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))}));function Ex(){return h.jsxs("section",{className:"flex-1 min-h-0 flex flex-col overflow-hidden bg-gradient-to-b from-gray-50/60 to-white",children:[h.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto custom-scrollbar",children:h.jsx("div",{className:"mx-auto w-full max-w-[min(1120px,100%)] px-6 py-5",children:h.jsxs("div",{className:"space-y-4",children:[h.jsx("div",{className:"h-6 w-48 animate-pulse rounded bg-gray-200"}),h.jsx("div",{className:"h-24 w-[78%] animate-pulse rounded-2xl bg-gray-200/80"}),h.jsx("div",{className:"h-20 w-[62%] animate-pulse rounded-2xl bg-gray-200/80"}),h.jsx("div",{className:"h-28 w-[84%] animate-pulse rounded-2xl bg-gray-200/80"})]})})}),h.jsx("div",{className:"border-t border-gray-200/80 bg-white p-4",children:h.jsx("div",{className:"mx-auto w-full max-w-[min(1120px,100%)]",children:h.jsxs("div",{className:"rounded-2xl border border-gray-200 bg-white shadow-card p-4",children:[h.jsx("div",{className:"h-16 w-full animate-pulse rounded-xl bg-gray-200/80"}),h.jsxs("div",{className:"mt-3 flex items-center justify-between",children:[h.jsx("div",{className:"h-8 w-36 animate-pulse rounded-lg bg-gray-200/80"}),h.jsx("div",{className:"h-8 w-20 animate-pulse rounded-lg bg-gray-200/80"})]})]})})})]})}function Ax(){var d;const e=pr(),t=qe(p=>p.snapshot),n=k.useRef(null),r=t.threadRef??n,s=!!(t.selectedSessionKey||t.sessionTypeLabel),i=t.sessionDisplayName||t.selectedSessionKey||I("chatSidebarNewTask"),o=!t.selectedSessionKey&&t.uiMessages.length===0&&!t.isSending,a=t.modelOptions.length>0,l=t.isProviderStateResolved&&!a,u=t.isHistoryLoading&&t.uiMessages.length===0&&!t.isSending&&!t.isAwaitingAssistantOutput,{onScroll:c}=Ty({scrollRef:r,resetKey:t.selectedSessionKey,isLoading:t.isHistoryLoading,hasContent:t.uiMessages.length>0,contentVersion:t.uiMessages});return t.isProviderStateResolved?h.jsxs("section",{className:"flex-1 min-h-0 flex flex-col overflow-hidden bg-gradient-to-b from-gray-50/60 to-white",children:[h.jsxs("div",{className:xe("px-5 border-b border-gray-200/60 bg-white/80 backdrop-blur-sm flex items-center justify-between shrink-0 overflow-hidden transition-all duration-200",s?"py-3 opacity-100":"h-0 py-0 opacity-0 border-b-0"),children:[h.jsxs("div",{className:"min-w-0 flex-1 flex items-center gap-2",children:[h.jsx("span",{className:"text-sm font-medium text-gray-700 truncate",children:i}),t.sessionTypeLabel?h.jsx("span",{className:"shrink-0 rounded-full border border-gray-200 bg-gray-100 px-2 py-0.5 text-[11px] font-medium text-gray-600",children:t.sessionTypeLabel}):null]}),t.selectedSessionKey?h.jsx(He,{variant:"ghost",size:"icon",className:"rounded-lg shrink-0 text-gray-400 hover:text-destructive",onClick:e.chatThreadManager.deleteSession,disabled:!t.canDeleteSession||t.isDeletePending,children:h.jsx(Ti,{className:"h-4 w-4"})}):null]}),l&&h.jsxs("div",{className:"px-5 py-2.5 border-b border-amber-200/70 bg-amber-50/70 flex items-center justify-between gap-3 shrink-0",children:[h.jsx("span",{className:"text-xs text-amber-800",children:I("chatModelNoOptions")}),h.jsx("button",{type:"button",onClick:e.chatThreadManager.goToProviders,className:"text-xs font-semibold text-amber-900 underline-offset-2 hover:underline",children:I("chatGoConfigureProvider")})]}),t.sessionTypeUnavailable&&((d=t.sessionTypeUnavailableMessage)==null?void 0:d.trim())&&h.jsx("div",{className:"px-5 py-2.5 border-b border-amber-200/70 bg-amber-50/70 shrink-0",children:h.jsx("span",{className:"text-xs text-amber-800",children:t.sessionTypeUnavailableMessage})}),h.jsx("div",{ref:r,onScroll:c,className:"flex-1 min-h-0 overflow-y-auto custom-scrollbar",children:o?h.jsx(Mx,{onCreateSession:e.chatThreadManager.createSession}):u?h.jsx("div",{className:"h-full"}):t.uiMessages.length===0?h.jsx("div",{className:"px-5 py-5 text-sm text-gray-500",children:I("chatNoMessages")}):h.jsx("div",{className:"mx-auto w-full max-w-[min(1120px,100%)] px-6 py-5",children:h.jsx(Tx,{uiMessages:t.uiMessages,isSending:t.isSending&&t.isAwaitingAssistantOutput})})}),h.jsx(qy,{})]}):h.jsx(Ex,{})}function ni(e){return Zt(e??void 0)}function Lx(e){return typeof e!="number"||!Number.isFinite(e)?"-":Zt(new Date(e))}function Nx(e){if(typeof e!="number"||!Number.isFinite(e))return"-";const t=Math.round(e/1e3);if(t<60)return`${t}s`;const n=Math.round(t/60);if(n<60)return`${n}m`;const r=Math.round(n/60);return r<24?`${r}h`:`${Math.round(r/24)}d`}function Px(e){const t=e.schedule;return t.kind==="cron"?t.expr?`cron ${t.expr}`:"cron":t.kind==="every"?`every ${Nx(t.everyMs)}`:t.kind==="at"?`at ${Lx(t.atMs)}`:"-"}function jx(e){if(!e.payload.deliver)return"-";const t=e.payload.channel??"-",n=e.payload.to??"-";return`${t}:${n}`}function Dx(e,t){const n=t.trim().toLowerCase();return n?[e.id,e.name,e.payload.message,e.payload.channel??"",e.payload.to??""].join(" ").toLowerCase().includes(n):!0}function _x(e,t){return t==="all"?!0:t==="enabled"?e.enabled:!e.enabled}function Ox(){var m;const[e,t]=k.useState(""),[n,r]=k.useState("all"),s=Kl({all:!0}),i=Ul(),o=Vl(),a=Hl(),{confirm:l,ConfirmDialog:u}=dr(),c=k.useMemo(()=>{var b;return(((b=s.data)==null?void 0:b.jobs)??[]).filter(g=>Dx(g,e)).filter(g=>_x(g,n))},[s.data,e,n]),d=async y=>{await l({title:`${I("cronDeleteConfirm")}?`,description:y.name?`${y.name} (${y.id})`:y.id,variant:"destructive",confirmLabel:I("delete")})&&i.mutate({id:y.id})},p=async y=>{const b=!y.enabled;await l({title:b?`${I("cronEnableConfirm")}?`:`${I("cronDisableConfirm")}?`,description:y.name?`${y.name} (${y.id})`:y.id,variant:b?"default":"destructive",confirmLabel:b?I("cronEnable"):I("cronDisable")})&&o.mutate({id:y.id,enabled:b})},f=async y=>{const b=!y.enabled;await l({title:b?`${I("cronRunForceConfirm")}?`:`${I("cronRunConfirm")}?`,description:y.name?`${y.name} (${y.id})`:y.id,confirmLabel:I("cronRunNow")})&&a.mutate({id:y.id,force:b})};return h.jsxs(vu,{fullHeight:!0,children:[h.jsx(wu,{title:I("cronPageTitle"),description:I("cronPageDescription"),actions:h.jsx(He,{variant:"ghost",size:"icon",className:"h-9 w-9 rounded-lg text-gray-400 hover:text-gray-700 hover:bg-gray-100",onClick:()=>s.refetch(),children:h.jsx(El,{className:xe("h-4 w-4",s.isFetching&&"animate-spin")})})}),h.jsx("div",{className:"mb-6",children:h.jsxs("div",{className:"flex flex-wrap gap-3 items-center",children:[h.jsxs("div",{className:"relative flex-1 min-w-[240px]",children:[h.jsx(hr,{value:e,onChange:y=>t(y.target.value),placeholder:I("cronSearchPlaceholder"),className:"pl-9"}),h.jsx(cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400"})]}),h.jsx("div",{className:"min-w-[180px]",children:h.jsxs(Fn,{value:n,onValueChange:y=>r(y),children:[h.jsx(zn,{className:"w-full",children:h.jsx(ql,{placeholder:I("cronStatusLabel")})}),h.jsxs(Bn,{children:[h.jsx(St,{value:"all",children:I("cronStatusAll")}),h.jsx(St,{value:"enabled",children:I("cronStatusEnabled")}),h.jsx(St,{value:"disabled",children:I("cronStatusDisabled")})]})]})}),h.jsxs("div",{className:"text-xs text-gray-500 ml-auto",children:[I("cronTotalLabel"),": ",((m=s.data)==null?void 0:m.total)??0," / ",c.length]})]})}),h.jsx("div",{className:"flex-1 overflow-auto custom-scrollbar",children:s.isLoading?h.jsx("div",{className:"text-sm text-gray-400 p-4 text-center",children:I("cronLoading")}):c.length===0?h.jsx("div",{className:"text-sm text-gray-400 p-4 text-center",children:I("cronEmpty")}):h.jsx("div",{className:"space-y-4",children:c.map(y=>h.jsx(Wl,{className:"border border-gray-200",children:h.jsx(Gl,{className:"pt-5 pb-5",children:h.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[h.jsxs("div",{className:"min-w-[220px] flex-1",children:[h.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[h.jsx("span",{className:"text-sm font-semibold text-gray-900",children:y.name||y.id}),h.jsx("span",{className:"text-[10px] font-semibold px-2 py-0.5 rounded-full bg-gray-100 text-gray-500",children:y.id}),h.jsx("span",{className:xe("text-[10px] font-semibold px-2 py-0.5 rounded-full",y.enabled?"bg-emerald-50 text-emerald-700":"bg-gray-100 text-gray-500"),children:y.enabled?I("enabled"):I("disabled")}),y.deleteAfterRun&&h.jsx("span",{className:"text-[10px] font-semibold px-2 py-0.5 rounded-full bg-amber-50 text-amber-700",children:I("cronOneShot")})]}),h.jsxs("div",{className:"mt-2 text-xs text-gray-500",children:[I("cronScheduleLabel"),": ",Px(y)]}),h.jsx("div",{className:"mt-2 text-sm text-gray-700 whitespace-pre-wrap break-words",children:y.payload.message}),h.jsxs("div",{className:"mt-2 text-xs text-gray-500",children:[I("cronDeliverTo"),": ",jx(y)]})]}),h.jsxs("div",{className:"min-w-[220px] text-xs text-gray-500 space-y-2",children:[h.jsxs("div",{children:[h.jsxs("span",{className:"font-medium text-gray-700",children:[I("cronNextRun"),":"]})," ",ni(y.state.nextRunAt)]}),h.jsxs("div",{children:[h.jsxs("span",{className:"font-medium text-gray-700",children:[I("cronLastRun"),":"]})," ",ni(y.state.lastRunAt)]}),h.jsxs("div",{children:[h.jsxs("span",{className:"font-medium text-gray-700",children:[I("cronLastStatus"),":"]})," ",y.state.lastStatus??"-"]}),y.state.lastError&&h.jsx("div",{className:"text-[11px] text-red-500 break-words",children:y.state.lastError})]}),h.jsxs("div",{className:"flex items-start gap-2 flex-wrap justify-end",children:[h.jsxs(He,{variant:"subtle",size:"sm",onClick:()=>f(y),className:"gap-1",children:[h.jsx(Al,{className:"h-3.5 w-3.5"}),I("cronRunNow")]}),h.jsxs(He,{variant:y.enabled?"outline":"primary",size:"sm",onClick:()=>p(y),className:"gap-1",children:[h.jsx(Ll,{className:"h-3.5 w-3.5"}),y.enabled?I("cronDisable"):I("cronEnable")]}),h.jsxs(He,{variant:"destructive",size:"sm",onClick:()=>d(y),className:"gap-1",children:[h.jsx(Ti,{className:"h-3.5 w-3.5"}),I("delete")]})]})]})})},y.id))})}),h.jsx(u,{})]})}function Ia(e){const{view:t,routeSessionKey:n,selectedSessionKey:r,selectedAgentId:s,setSelectedSessionKey:i,setSelectedAgentId:o,selectedSessionKeyRef:a,resetStreamState:l,resolveAgentIdFromSessionKey:u}=e;k.useEffect(()=>{if(t==="chat"){if(n){r!==n&&i(n);return}r!==null&&(i(null),l())}},[l,n,r,i,t]),k.useEffect(()=>{const c=r?u(r):null;c&&s!==c&&o(c)},[u,s,r,o]),k.useEffect(()=>{a.current=r},[r,a])}function Ma({view:e,confirmDialog:t}){return h.jsxs("div",{className:"h-full flex",children:[h.jsx(jy,{}),e==="chat"?h.jsx(Ax,{}):h.jsx("section",{className:"flex-1 min-h-0 overflow-hidden bg-gradient-to-b from-gray-50/60 to-white",children:e==="cron"?h.jsx("div",{className:"h-full overflow-auto custom-scrollbar",children:h.jsx("div",{className:"mx-auto w-full max-w-[min(1120px,100%)] px-6 py-5",children:h.jsx(Ox,{})})}):h.jsx("div",{className:"h-full overflow-hidden",children:h.jsx("div",{className:"mx-auto flex h-full min-h-0 w-full max-w-[min(1120px,100%)] flex-col px-6 py-5",children:h.jsx(pu,{forcedType:"skills"})})})}),t]})}const sr="sid_";function Ra(e){var r;const t=/^agent:([^:]+):/i.exec(e.trim());if(!t)return null;const n=(r=t[1])==null?void 0:r.trim();return n||null}function Fx(e){const t=Math.random().toString(36).slice(2,8);return`agent:${e}:ui:direct:web-${Date.now().toString(36)}${t}`}function zx(e){const t=new TextEncoder().encode(e);let n="";for(const s of t)n+=String.fromCharCode(s);const r=btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"");return`${sr}${r}`}function Bx(e){if(!e.startsWith(sr))return null;const t=e.slice(sr.length).replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4===0?"":"=".repeat(4-t.length%4);try{const r=atob(t+n),s=Uint8Array.from(r,i=>i.charCodeAt(0));return new TextDecoder().decode(s)}catch{return null}}function Ea(e){if(!e)return null;const t=Bx(e);if(t)return t;try{return decodeURIComponent(e)}catch{return e}}function $x(e){return`/chat/${zx(e)}`}function Kx(e){const t=e.trim();return t.length>0?t:null}function Ux(e){return e??null}class Aa{constructor(t){this.updateSession=t,this.inFlight=null,this.queued=null,this.syncSelectedSessionPreferences=()=>{const n=H.getState().snapshot,s=re.getState().snapshot.selectedSessionKey;s&&this.enqueue({sessionKey:s,patch:{preferredModel:Kx(n.selectedModel),preferredThinking:Ux(n.selectedThinkingLevel)}})}}enqueue(t){this.queued=t,!this.inFlight&&this.startFlush()}startFlush(){this.inFlight=this.flush().catch(t=>{console.error(`Failed to sync chat session preferences: ${String(t)}`)}).finally(()=>{this.inFlight=null,this.queued&&this.startFlush()})}async flush(){for(;this.queued;){const t=this.queued;this.queued=null,await this.updateSession(t.sessionKey,t.patch)}}}class Vx{constructor(t,n){this.uiManager=t,this.streamActionsManager=n,this.sessionPreferenceSync=new Aa(On),this.hasSnapshotChanges=r=>{const s=H.getState().snapshot;for(const[i,o]of Object.entries(r))if(!Object.is(s[i],o))return!0;return!1},this.resolveUpdateValue=(r,s)=>typeof s=="function"?s(r):s,this.isSameStringArray=(r,s)=>r.length===s.length&&r.every((i,o)=>i===s[o]),this.syncComposerSnapshot=r=>{H.getState().setSnapshot({composerNodes:r,draft:ba(r),selectedSkills:Sa(r)})},this.syncSnapshot=r=>{if(this.hasSnapshotChanges(r)&&(H.getState().setSnapshot(r),Object.prototype.hasOwnProperty.call(r,"modelOptions")||Object.prototype.hasOwnProperty.call(r,"selectedModel")||Object.prototype.hasOwnProperty.call(r,"selectedThinkingLevel"))){const{selectedModel:s}=H.getState().snapshot;this.reconcileThinkingForModel(s)}},this.setDraft=r=>{const s=H.getState().snapshot.draft,i=this.resolveUpdateValue(s,r);i!==s&&this.syncComposerSnapshot(xa(i))},this.setComposerNodes=r=>{const s=H.getState().snapshot.composerNodes,i=this.resolveUpdateValue(s,r);Object.is(i,s)||this.syncComposerSnapshot(i)},this.setPendingSessionType=r=>{const s=H.getState().snapshot.pendingSessionType,i=this.resolveUpdateValue(s,r);i!==s&&H.getState().setSnapshot({pendingSessionType:i})},this.send=async()=>{const r=H.getState().snapshot,s=re.getState().snapshot,i=r.draft.trim();if(!i)return;const{selectedSkills:o,composerNodes:a}=r,l=!!s.selectedSessionKey,u=s.selectedSessionKey??Fx(s.selectedAgentId);l||this.uiManager.goToSession(u,{replace:!0}),this.setComposerNodes(_r()),await this.streamActionsManager.sendMessage({message:i,sessionKey:u,agentId:s.selectedAgentId,sessionType:r.selectedSessionType,model:r.selectedModel||void 0,thinkingLevel:r.selectedThinkingLevel??void 0,stopSupported:r.stopSupported,stopReason:r.stopReason,requestedSkills:o,restoreDraftOnError:!0,composerNodes:a})},this.stop=async()=>{await this.streamActionsManager.stopCurrentRun()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.setSelectedModel=r=>{const s=H.getState().snapshot.selectedModel,i=this.resolveUpdateValue(s,r);i!==s&&(H.getState().setSnapshot({selectedModel:i}),this.reconcileThinkingForModel(i))},this.setSelectedThinkingLevel=r=>{const s=H.getState().snapshot.selectedThinkingLevel,i=this.resolveUpdateValue(s,r);i!==s&&H.getState().setSnapshot({selectedThinkingLevel:i})},this.selectSessionType=r=>{const s=Fe(r);H.getState().setSnapshot({selectedSessionType:s,pendingSessionType:s}),this.syncRemoteSessionType(s)},this.setSelectedSkills=r=>{const s=H.getState().snapshot,{selectedSkills:i}=s,o=this.resolveUpdateValue(i,r);this.isSameStringArray(o,i)||this.syncComposerSnapshot(ka(s.composerNodes,o,s.skillRecords))},this.selectModel=r=>{this.setSelectedModel(r),this.sessionPreferenceSync.syncSelectedSessionPreferences()},this.selectThinkingLevel=r=>{this.setSelectedThinkingLevel(r),this.sessionPreferenceSync.syncSelectedSessionPreferences()},this.selectSkills=r=>{this.setSelectedSkills(r)},this.syncRemoteSessionType=async r=>{const s=re.getState().snapshot,{selectedSessionKey:i}=s;if(!i)return;const o=s.sessions.find(a=>a.key===i);o!=null&&o.sessionTypeMutable&&Fe(o.sessionType)!==r&&await On(i,{sessionType:r})}}resolveThinkingForModel(t,n){const r=t==null?void 0:t.thinkingCapability;return!r||r.supported.length===0?null:n==="off"?"off":n&&r.supported.includes(n)?n:r.default&&r.supported.includes(r.default)?r.default:"off"}reconcileThinkingForModel(t){const n=H.getState().snapshot,r=n.modelOptions.find(o=>o.value===t),{selectedThinkingLevel:s}=n,i=this.resolveThinkingForModel(r,s);i!==s&&H.getState().setSnapshot({selectedThinkingLevel:i})}}const Hx={parseReady:e=>e.driver!=="nextbot-stream"||e.kind!=="ready"?null:{remoteRunId:typeof e.backendRunId=="string"?e.backendRunId:void 0,sessionId:typeof e.sessionKey=="string"?e.sessionKey:void 0,stopCapable:typeof e.stopSupported=="boolean"?e.stopSupported:void 0,stopReason:typeof e.stopReason=="string"?e.stopReason:void 0},parseFinal:e=>e.driver!=="nextbot-stream"||e.kind!=="final"?null:{sessionId:typeof e.sessionKey=="string"?e.sessionKey:void 0,hasOutput:!!e.hasAssistantSessionEvent}};function qx(e,t){return{driver:"nextbot-stream",mode:"send",payload:e,requestedSkills:t}}function Wx(e){const t=Number.isFinite(e.eventCount)&&e.eventCount>0?Math.max(0,Math.trunc(e.eventCount)):void 0;return{driver:"nextbot-stream",mode:"resume",runId:e.runId,...typeof t=="number"?{fromEventIndex:t}:{},sessionKey:e.sessionKey,...e.agentId?{agentId:e.agentId}:{},stopSupported:e.stopSupported,...e.stopReason?{stopReason:e.stopReason}:{}}}function Gx(e,t){if(e===t)return!0;if(e.size!==t.size)return!1;for(const[n,r]of e.entries())if(!Object.is(r,t.get(n)))return!1;return!0}class La{constructor(){this.syncSnapshot=t=>{const n=Zn.getState().snapshot,r=t.sessionRunStatusByKey;(!r||Gx(n.sessionRunStatusByKey,r))&&(t.isLocallyRunning===void 0||Object.is(n.isLocallyRunning,t.isLocallyRunning))&&(t.activeBackendRunId===void 0||Object.is(n.activeBackendRunId,t.activeBackendRunId))||Zn.getState().setSnapshot(t)}}}class Na{constructor(t,n){this.uiManager=t,this.streamActionsManager=n,this.hasSnapshotChanges=r=>{const s=re.getState().snapshot;for(const[i,o]of Object.entries(r))if(!Object.is(s[i],o))return!0;return!1},this.resolveUpdateValue=(r,s)=>typeof s=="function"?s(r):s,this.syncSnapshot=r=>{this.hasSnapshotChanges(r)&&re.getState().setSnapshot(r)},this.setSelectedAgentId=r=>{const s=re.getState().snapshot.selectedAgentId,i=this.resolveUpdateValue(s,r);i!==s&&re.getState().setSnapshot({selectedAgentId:i})},this.setSelectedSessionKey=r=>{const s=re.getState().snapshot.selectedSessionKey,i=this.resolveUpdateValue(s,r);i!==s&&re.getState().setSnapshot({selectedSessionKey:i})},this.createSession=r=>{const{snapshot:s}=H.getState(),{defaultSessionType:i}=s,o=i||"native",a=typeof r=="string"&&r.trim().length>0?r.trim():o;this.streamActionsManager.resetStreamState(),this.setSelectedSessionKey(null),H.getState().setSnapshot({pendingSessionType:a}),this.uiManager.goToChatRoot()},this.selectSession=r=>{this.setSelectedSessionKey(r),this.uiManager.goToSession(r)},this.setQuery=r=>{const s=re.getState().snapshot.query,i=this.resolveUpdateValue(s,r);i!==s&&re.getState().setSnapshot({query:i})}}}const An=async()=>{},ri=()=>{};class Pa{constructor(){this.actions={sendMessage:An,stopCurrentRun:An,resumeRun:An,resetStreamState:ri,applyHistoryMessages:ri},this.bind=t=>{this.actions={...this.actions,...t}},this.sendMessage=t=>this.actions.sendMessage(t),this.stopCurrentRun=()=>this.actions.stopCurrentRun(),this.resumeRun=t=>this.actions.resumeRun(t),this.resetStreamState=()=>this.actions.resetStreamState(),this.applyHistoryMessages=(t,n)=>this.actions.applyHistoryMessages(t,n)}}const Qx=async()=>{};class Xx{constructor(t,n,r){this.uiManager=t,this.sessionListManager=n,this.streamActionsManager=r,this.actions={refetchSessions:Qx},this.bindActions=s=>{this.actions={...this.actions,...s}},this.hasSnapshotChanges=s=>{const i=qe.getState().snapshot;for(const[o,a]of Object.entries(s))if(!Object.is(i[o],a))return!0;return!1},this.syncSnapshot=s=>{this.hasSnapshotChanges(s)&&qe.getState().setSnapshot(s)},this.deleteSession=()=>{this.deleteCurrentSession()},this.createSession=()=>{this.sessionListManager.createSession()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.deleteCurrentSession=async()=>{const{snapshot:{selectedSessionKey:s}}=re.getState();if(!(!s||!await this.uiManager.confirm({title:I("chatDeleteSessionConfirm"),variant:"destructive",confirmLabel:I("delete")}))){qe.getState().setSnapshot({isDeletePending:!0});try{await Ql(s),this.streamActionsManager.resetStreamState(),re.getState().setSnapshot({selectedSessionKey:null}),this.uiManager.goToChatRoot({replace:!0}),await this.actions.refetchSessions()}finally{qe.getState().setSnapshot({isDeletePending:!1})}}}}}const Yx=async e=>!1;class ja{constructor(){this.state={pathname:""},this.actions={navigate:null,confirm:Yx},this.syncState=t=>{this.state={...this.state,...t}},this.bindActions=t=>{this.actions={...this.actions,...t}},this.confirm=async t=>this.actions.confirm(t),this.navigateTo=(t,n)=>{this.actions.navigate&&(this.state.pathname===t&&!(n!=null&&n.replace)||(this.actions.navigate(t,n),this.state.pathname=t))},this.goToProviders=()=>{this.navigateTo("/providers")},this.goToChatRoot=t=>{this.navigateTo("/chat",t)},this.goToSession=(t,n)=>{this.navigateTo($x(t),n)}}}function Jx(e){return e.delta?e.started?[{type:X.TEXT_DELTA,messageId:e.messageId,delta:e.delta}]:[{type:X.TEXT_START,messageId:e.messageId},{type:X.TEXT_DELTA,messageId:e.messageId,delta:e.delta}]:[]}function Zx(e){return!1}function eb(e){var n,r;return((r=(n=e.message)==null?void 0:n.role)==null?void 0:r.toLowerCase().trim())==="assistant"}function tb(e){var o;const{event:t,messageId:n}=e,r=t.message;if(!r)return[];const s=(o=r.role)==null?void 0:o.toLowerCase().trim();if(!s)return[];const i=[];if(typeof r.reasoning_content=="string"&&r.reasoning_content.trim()&&(i.push({type:X.REASONING_START,messageId:n}),i.push({type:X.REASONING_DELTA,messageId:n,delta:r.reasoning_content.trim()}),i.push({type:X.REASONING_END,messageId:n})),Array.isArray(r.tool_calls))for(let a=0;a<r.tool_calls.length;a+=1){const l=r.tool_calls[a];if(!l||typeof l!="object")continue;const u=l,c=u.function,d=typeof c=="object"&&c?c:null,p=typeof t.seq=="number"?String(t.seq):"unknown",f=typeof u.id=="string"?u.id:`tool-${p}-${a}`,m=typeof(d==null?void 0:d.name)=="string"?d.name:typeof u.name=="string"?u.name:"tool",y=(d==null?void 0:d.arguments)??u.arguments??"",b=typeof y=="string"?y:JSON.stringify(y??{});i.push({type:X.TOOL_CALL_START,messageId:n,toolCallId:f,toolName:m}),i.push({type:X.TOOL_CALL_ARGS,toolCallId:f,args:b}),i.push({type:X.TOOL_CALL_END,toolCallId:f})}if(s==="tool"||s==="tool_result"||s==="toolresult"||s==="function"){const a=typeof r.tool_call_id=="string"?r.tool_call_id.trim():"";a&&i.push({type:X.TOOL_CALL_RESULT,toolCallId:a,content:r.content})}return i}function Da(){return`stream-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function nb(e,t){const n={};return e.sessionType&&(n.session_type=e.sessionType),e.thinkingLevel&&(n.thinking=e.thinkingLevel),t.length>0&&(n.requested_skills=t),{message:e.message,...e.runId?{runId:e.runId}:{},sessionKey:e.sessionKey,agentId:e.agentId,...e.model?{model:e.model}:{},...Object.keys(n).length>0?{metadata:n}:{},channel:"ui",chatId:"web-ui"}}async function rb(e){let t="",n=null;const s=await en.openStream({method:"POST",path:"/api/chat/turn/stream",body:nb(e.item,e.requestedSkills),signal:e.signal,onEvent:i=>{var o;if(i.name==="ready"){const a=i.payload??{};typeof a.sessionKey=="string"&&a.sessionKey.trim()&&(t=a.sessionKey),e.onReady(a);return}if(i.name==="delta"){e.onDelta(i.payload??{delta:""});return}if(i.name==="session_event"){e.onSessionEvent({data:i.payload});return}if(i.name==="final"){const a=i.payload??{};n={sessionKey:typeof a.sessionKey=="string"&&a.sessionKey.trim()?a.sessionKey:t,reply:typeof a.reply=="string"?a.reply:""};return}if(i.name==="error"){const a=i.payload??{};throw new Error(((o=a.message)==null?void 0:o.trim())||"chat stream failed")}}}).finished;return n!==null?n:{sessionKey:typeof(s==null?void 0:s.sessionKey)=="string"&&s.sessionKey.trim()?s.sessionKey:t,reply:typeof(s==null?void 0:s.reply)=="string"?s.reply:""}}async function sb(e){let t="",n=null;const r=new URLSearchParams;typeof e.fromEventIndex=="number"&&r.set("fromEventIndex",String(Math.max(0,Math.trunc(e.fromEventIndex))));const s=`/api/chat/runs/${encodeURIComponent(e.runId)}/stream`+(r.size>0?`?${r.toString()}`:""),o=await en.openStream({method:"GET",path:s,signal:e.signal,onEvent:a=>{var l;if(a.name==="ready"){const u=a.payload??{};typeof u.sessionKey=="string"&&u.sessionKey.trim()&&(t=u.sessionKey),e.onReady(u);return}if(a.name==="delta"){e.onDelta(a.payload??{delta:""});return}if(a.name==="session_event"){e.onSessionEvent({data:a.payload});return}if(a.name==="final"){const u=a.payload??{};n={sessionKey:typeof u.sessionKey=="string"&&u.sessionKey.trim()?u.sessionKey:t,reply:typeof u.reply=="string"?u.reply:""};return}if(a.name==="error"){const u=a.payload??{};throw new Error(((l=u.message)==null?void 0:l.trim())||"chat stream failed")}}}).finished;return n!==null?n:{sessionKey:typeof(o==null?void 0:o.sessionKey)=="string"&&o.sessionKey.trim()?o.sessionKey:t,reply:typeof(o==null?void 0:o.reply)=="string"?o.reply:""}}async function ib(e){var t;if(e.backendStopSupported)try{const n=new Set,r=(t=e.backendRunId)==null?void 0:t.trim();if(r&&(n.add(r),await Ln(r)))return;const s=await ob(e);for(const i of s){if(n.has(i))continue;if(n.add(i),await Ln(i))return}if(r&&await Ln(r))return}catch{}}async function Ln(e){const t=e.trim();if(!t)return!1;try{return(await Xl({runId:t})).stopped===!0}catch{return!1}}async function ob(e){var s;const t=(s=e.sessionKey)==null?void 0:s.trim();if(!t)return[];const n=8,r=120;for(let i=0;i<n;i+=1){const o=await ab(e,t);if(o.length>0)return o;i<n-1&&await lb(r)}return[]}async function ab(e,t){try{const n=await Yl({sessionKey:t,states:["queued","running"],limit:50}),r=n.runs.filter(s=>{var i;return((i=s.runId)==null?void 0:i.trim())&&s.sessionKey===t&&s.agentId===e.agentId}).map(s=>s.runId.trim());return r.length>0?r:n.runs.filter(s=>{var i;return((i=s.runId)==null?void 0:i.trim())&&s.sessionKey===t}).map(s=>s.runId.trim())}catch{return[]}}function lb(e){return new Promise(t=>{window.setTimeout(t,e)})}function _a(e){if(!Array.isArray(e))return[];const t=new Set;for(const n of e){const r=n.trim();r&&t.add(r)}return[...t]}function ub(e){var y;const t=new Set(["tool","tool_result","toolresult","function"]),n=[];let r=0,s=0,i=null;const o=(b,g)=>(r+=1,`history-${b}-${g||"unknown"}-${r}`),a=b=>{const g=typeof b=="string"?b:JSON.stringify(b??{});try{return{args:g,parsedArgs:JSON.parse(g)}}catch{return{args:g}}},l=(b,g)=>{for(let v=b.length-1;v>=0;v-=1){const C=b[v];if(C.type==="tool-invocation"&&C.toolInvocation.toolCallId===g)return v}return-1},u=b=>i?(i={...i,meta:{...i.meta,timestamp:b}},i):(s+=1,i={id:`history-assistant-${s}-${b||"unknown"}`,role:"assistant",parts:[],meta:{source:"history",status:"final",timestamp:b}},i),c=()=>{i&&(i.parts.length>0&&n.push(i),i=null)},d=(b,g)=>{if(!g)return;const v=u(b);v.parts=[...v.parts,{type:"text",text:g}]},p=(b,g)=>{if(!g)return;const v=u(b);v.parts=[...v.parts,{type:"reasoning",reasoning:g,details:[]}]},f=b=>{const g=u(b.timestamp),v=l(g.parts,b.toolCallId),C={type:"tool-invocation",toolInvocation:{status:ue.CALL,toolCallId:b.toolCallId,toolName:b.toolName,args:b.args,parsedArgs:b.parsedArgs}};if(v>=0){g.parts=[...g.parts.slice(0,v),C,...g.parts.slice(v+1)];return}g.parts=[...g.parts,C]},m=b=>{if(!b.toolCallId)return;const g=u(b.timestamp),v=l(g.parts,b.toolCallId);if(v<0){g.parts=[...g.parts,{type:"tool-invocation",toolInvocation:{status:ue.RESULT,toolCallId:b.toolCallId,toolName:b.toolName,args:"{}",parsedArgs:void 0,result:b.result}}];return}const C=g.parts[v];C.type==="tool-invocation"&&(g.parts=[...g.parts.slice(0,v),{...C,toolInvocation:{...C.toolInvocation,status:ue.RESULT,result:b.result}},...g.parts.slice(v+1)])};for(const b of e){const g=(y=b.role)==null?void 0:y.toLowerCase().trim();if(!g)continue;const v=b.timestamp;if(g==="user"||g==="system"||g==="data"){c();const C=Hr(b.content).trim();if(!C)continue;n.push({id:o(g,v),role:g,parts:[{type:"text",text:C}],meta:{source:"history",status:"final",timestamp:v}});continue}if(g==="assistant"){const C=Hr(b.content).trim();if(C&&d(v,C),typeof b.reasoning_content=="string"&&b.reasoning_content.trim()&&p(v,b.reasoning_content.trim()),Array.isArray(b.tool_calls))for(const A of b.tool_calls){if(!A||typeof A!="object")continue;const P=A,T=P.function,F=typeof T=="object"&&T?T:null,B=typeof P.id=="string"?P.id.trim():"";if(!B)continue;const z=typeof(F==null?void 0:F.name)=="string"?F.name:typeof P.name=="string"?P.name:"tool",w=a((F==null?void 0:F.arguments)??P.arguments??"");f({timestamp:v,toolCallId:B,toolName:z,args:w.args,parsedArgs:w.parsedArgs})}continue}if(t.has(g)){const C=typeof b.tool_call_id=="string"?b.tool_call_id.trim():"",A=typeof b.name=="string"&&b.name.trim()?b.name.trim():"tool";m({timestamp:v,toolCallId:C,toolName:A,result:b.content})}}return c(),n}function cb(){const e=Date.now().toString(36),t=Math.random().toString(36).slice(2,10);return`run-${e}-${t}`}function db(e){const t=e.metadata;if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t;if(n.driver!=="nextbot-stream")return null;const r=n.mode;if(r==="send"){const s=n.payload;if(!s||typeof s!="object"||Array.isArray(s))return null;const i=Array.isArray(n.requestedSkills)?n.requestedSkills.filter(o=>typeof o=="string"):[];return{driver:"nextbot-stream",mode:"send",payload:s,requestedSkills:i}}if(r==="resume"){const s=typeof n.runId=="string"?n.runId.trim():"";if(!s)return null;const i=typeof n.fromEventIndex=="number"&&Number.isFinite(n.fromEventIndex)?Math.max(0,Math.trunc(n.fromEventIndex)):void 0,o=typeof n.sessionKey=="string"?n.sessionKey.trim():"",a=typeof n.agentId=="string"?n.agentId.trim():"",l=typeof n.stopSupported=="boolean"?n.stopSupported:void 0,u=typeof n.stopReason=="string"?n.stopReason.trim():"";return{driver:"nextbot-stream",mode:"resume",runId:s,...typeof i=="number"?{fromEventIndex:i}:{},...o?{sessionKey:o}:{},...a?{agentId:a}:{},...typeof l=="boolean"?{stopSupported:l}:{},...u?{stopReason:u}:{}}}return null}function hb(e){var t;if(e.mode==="send"){const n=((t=e.payload.runId)==null?void 0:t.trim())||"";return{localRunId:0,sessionKey:e.payload.sessionKey,...e.payload.agentId?{agentId:e.payload.agentId}:{},...n?{backendRunId:n}:{},backendStopSupported:!!e.payload.stopSupported,...e.payload.stopReason?{backendStopReason:e.payload.stopReason}:{}}}return{localRunId:0,sessionKey:e.sessionKey??"",...e.agentId?{agentId:e.agentId}:{},backendRunId:e.runId,backendStopSupported:!!e.stopSupported,...e.stopReason?{backendStopReason:e.stopReason}:{}}}function fb(e){var n;return e.mode!=="send"||((n=e.payload.runId)==null?void 0:n.trim())?e:{...e,payload:{...e.payload,runId:cb()}}}function pb(e,t){var n,r,s;e.backendRunId=((n=t.runId)==null?void 0:n.trim())||e.backendRunId,e.backendStopSupported=typeof t.stopSupported=="boolean"?t.stopSupported:e.backendStopSupported,(r=t.stopReason)!=null&&r.trim()&&(e.backendStopReason=t.stopReason.trim()),(s=t.sessionKey)!=null&&s.trim()&&(e.sessionKey=t.sessionKey.trim())}function gb(){return{deltaMessageId:Da(),deltaStarted:!1,deltaClosed:!1,hasAssistantSessionEvent:!1,hasAssistantOutput:!1}}function mb(e){var t,n,r;return{driver:"nextbot-stream",kind:"ready",...(t=e.sessionKey)!=null&&t.trim()?{sessionKey:e.sessionKey.trim()}:{},...(n=e.runId)!=null&&n.trim()?{backendRunId:e.runId.trim()}:{},...typeof e.stopSupported=="boolean"?{stopSupported:e.stopSupported}:{},...(r=e.stopReason)!=null&&r.trim()?{stopReason:e.stopReason.trim()}:{},...e.requestedAt?{requestedAt:e.requestedAt}:{}}}function yb(e,t){return{driver:"nextbot-stream",kind:"final",sessionKey:e.sessionKey,reply:e.reply,hasAssistantSessionEvent:t}}function si(e,t,n){e({type:X.RUN_METADATA,runId:t,metadata:n})}function ii(e,t){!e.deltaStarted||e.deltaClosed||(t({type:X.TEXT_END,messageId:e.deltaMessageId}),e.deltaClosed=!0)}function xb(e,t,n){const r=Jx({messageId:e.deltaMessageId,delta:n.delta,started:e.deltaStarted});r.length>0&&(e.deltaStarted=!0,e.deltaClosed=!1,e.hasAssistantOutput=!0);for(const s of r)t(s)}function bb(e,t,n){Zx(n.data),eb(n.data)&&(e.hasAssistantSessionEvent=!0);for(const r of tb({event:n.data,messageId:e.deltaMessageId}))t(r)}function Sb(e,t,n){const r=n.trim();if(e.hasAssistantOutput||!r)return;const s=Da();t({type:X.TEXT_START,messageId:s}),t({type:X.TEXT_DELTA,messageId:s,delta:r}),t({type:X.TEXT_END,messageId:s})}class kb{constructor(){this.activeAbortController=null,this.activeRunState=null,this.buildMissingMetadataObservable=t=>new Qt(n=>{n.next({type:X.RUN_ERROR,runId:t,error:"nextbot runtime metadata is required"}),n.complete()}),this.openRunStream=t=>{const{metadata:n,signal:r,onReady:s,onDelta:i,onSessionEvent:o}=t;return n.mode==="send"?rb({item:n.payload,requestedSkills:n.requestedSkills,signal:r,onReady:s,onDelta:i,onSessionEvent:o}):sb({runId:n.runId,fromEventIndex:n.fromEventIndex,signal:r,onReady:s,onDelta:i,onSessionEvent:o})},this.finalizeRunState=(t,n)=>{this.activeAbortController===t&&(this.activeAbortController=null),this.activeRunState===n&&(this.activeRunState=null)},this.createRunObservable=({metadata:t,clientRunId:n,abortController:r,runState:s})=>new Qt(i=>{const o=gb();let a=!1;const l=c=>{a||i.next(c)};return l({type:X.RUN_STARTED,runId:n}),this.openRunStream({metadata:t,signal:r.signal,onReady:c=>{this.activeRunState&&pb(this.activeRunState,c),si(l,n,mb(c))},onDelta:c=>{xb(o,l,c)},onSessionEvent:c=>{bb(o,l,c)}}).then(c=>{ii(o,l),Sb(o,l,c.reply),si(l,n,yb(c,o.hasAssistantSessionEvent)),l({type:X.RUN_FINISHED,runId:n}),i.complete()}).catch(c=>{ii(o,l),rr(c)||l({type:X.RUN_ERROR,runId:n,error:c instanceof Error?c.message:String(c)}),i.complete()}).finally(()=>{this.finalizeRunState(r,s)}),()=>{a=!0,r.abort(),this.activeAbortController===r&&(this.activeAbortController=null)}}),this.abortRun=()=>{var n;const t=this.activeRunState;t!=null&&t.backendStopSupported&&ib(t),(n=this.activeAbortController)==null||n.abort(),this.activeAbortController=null,this.activeRunState=null},this.run=t=>{const n=db(t),r=typeof t.runId=="string"&&t.runId.trim()?t.runId:`run-${Date.now()}`;if(!n)return this.buildMissingMetadataObservable(r);const s=fb(n);this.abortRun();const i=new AbortController;this.activeAbortController=i;const o=hb(s);return this.activeRunState=o,this.createRunObservable({metadata:s,clientRunId:r,abortController:i,runState:o})}}}class vb{constructor(){this.chatUiManager=new ja,this.runtimeAgent=new kb,this.chatController=new px({agent:this.runtimeAgent,getToolDefs:()=>[],getContexts:()=>[],getToolExecutor:()=>{}},{metadataParsers:Hx}),this.chatStreamActionsManager=new Pa,this.chatInputManager=new Vx(this.chatUiManager,this.chatStreamActionsManager),this.chatSessionListManager=new Na(this.chatUiManager,this.chatStreamActionsManager),this.chatRunStatusManager=new La,this.chatThreadManager=new Xx(this.chatUiManager,this.chatSessionListManager,this.chatStreamActionsManager)}}function zt(e){const[t,n]=k.useState(e.getValue());return k.useEffect(()=>{const r=e.subscribe(n);return()=>r.unsubscribe()},[e]),t}function wb(e,t){const[n,r]=k.useState(t);return k.useEffect(()=>{const s=e.subscribe(r);return()=>s.unsubscribe()},[e]),n}function Cb(e,t){const n=k.useRef(e);k.useEffect(()=>{n.current=e});const r=k.useRef(null);k.useEffect(()=>{t.setCallbacks({onRunSettled:async({sourceSessionId:g,resultSessionId:v})=>{const C=n.current;await C.refetchSessions();const A=C.selectedSessionKeyRef.current;(!A||A===g||v&&A===v)&&await C.refetchHistory()},onRunError:({sourceMessage:g,restoreDraft:v})=>{v&&n.current.setDraft(C=>C.trim().length===0&&g?g:C)},onSessionChanged:g=>{n.current.setSelectedSessionKey(v=>v===g?v:g)}})},[t]);const s=wb(t.messages$,t.getMessages()),i=zt(t.isAgentResponding$),o=zt(t.isAwaitingResponse$),a=zt(t.activeRun$),l=zt(t.lastError$),u=(a==null?void 0:a.remoteRunId)??null,c=ux(a),d=!!(a&&(c===null||a.remoteStopCapable&&!u)),p=k.useCallback(async g=>{const v=_a(g.requestedSkills),C=qx(g,v);await t.send({message:g.message,sessionId:g.sessionKey,agentId:g.agentId,metadata:C,restoreDraftOnError:g.restoreDraftOnError,stopCapable:g.stopSupported,stopReason:g.stopReason})},[t]),f=k.useCallback(async g=>{var P,T;const v=(P=g.runId)==null?void 0:P.trim(),C=(T=g.sessionKey)==null?void 0:T.trim();if(!v||!C)return;const A=Wx(g);await t.resume({remoteRunId:v,sessionId:C,agentId:g.agentId,metadata:A,stopCapable:g.stopSupported,stopReason:g.stopReason})},[t]),m=k.useCallback(async()=>{await t.stop()},[t]),y=k.useCallback(()=>{r.current=null,t.reset()},[t]),b=k.useCallback((g,v)=>{if(!!(t.activeRun$.getValue()||t.isAgentResponding$.getValue()))return;const A=n.current.selectedSessionKeyRef.current;if(A!==r.current&&(r.current=A,t.getMessages().length>0&&t.setMessages([])),!A){t.getMessages().length>0&&t.setMessages([]);return}v!=null&&v.isLoading&&g.length===0||t.setMessages(ub(g))},[t]);return{uiMessages:s,isSending:i,isAwaitingAssistantOutput:o,canStopCurrentRun:d,stopDisabledReason:c,lastSendError:l,activeBackendRunId:u,sendMessage:p,stopCurrentRun:m,resumeRun:f,resetStreamState:y,applyHistoryMessages:b}}function Tb({view:e}){var Re,je,Ye;const[t]=k.useState(()=>new vb),n=re(ce=>ce.snapshot.query),r=re(ce=>ce.snapshot.selectedSessionKey),s=re(ce=>ce.snapshot.selectedAgentId),i=H(ce=>ce.snapshot.pendingSessionType),o=H(ce=>ce.snapshot.selectedModel),{confirm:a,ConfirmDialog:l}=dr(),u=Jt(),c=Ii(),{sessionId:d}=Mi(),p=k.useRef(null),f=k.useRef(r),m=k.useMemo(()=>Ea(d),[d]),{sessionsQuery:y,installedSkillsQuery:b,chatCapabilitiesQuery:g,historyQuery:v,isProviderStateResolved:C,modelOptions:A,sessions:P,skillRecords:T,selectedSession:F,historyMessages:B,sessionTypeOptions:z,defaultSessionType:w,selectedSessionType:D,canEditSessionType:N,sessionTypeUnavailable:$,sessionTypeUnavailableMessage:O}=Nu({query:n,selectedSessionKey:r,selectedAgentId:s,currentSelectedModel:o,pendingSessionType:i,setPendingSessionType:t.chatInputManager.setPendingSessionType,setSelectedModel:t.chatInputManager.setSelectedModel,setSelectedThinkingLevel:t.chatInputManager.setSelectedThinkingLevel}),{uiMessages:R,isSending:U,isAwaitingAssistantOutput:E,canStopCurrentRun:W,stopDisabledReason:se,lastSendError:x,activeBackendRunId:ae,sendMessage:ie,stopCurrentRun:S,resumeRun:he,resetStreamState:we,applyHistoryMessages:oe}=Cb({selectedSessionKeyRef:f,setSelectedSessionKey:t.chatSessionListManager.setSelectedSessionKey,setDraft:t.chatInputManager.setDraft,setComposerNodes:t.chatInputManager.setComposerNodes,refetchSessions:y.refetch,refetchHistory:v.refetch},t.chatController);k.useEffect(()=>{t.chatStreamActionsManager.bind({sendMessage:ie,stopCurrentRun:S,resumeRun:he,resetStreamState:we,applyHistoryMessages:oe})},[oe,t,we,he,ie,S]);const{sessionRunStatusByKey:pe}=Tu({view:e,selectedSessionKey:r,activeBackendRunId:ae,isLocallyRunning:U||!!ae,resumeRun:t.chatStreamActionsManager.resumeRun});Ia({view:e,routeSessionKey:m,selectedSessionKey:r,selectedAgentId:s,setSelectedSessionKey:t.chatSessionListManager.setSelectedSessionKey,setSelectedAgentId:t.chatSessionListManager.setSelectedAgentId,selectedSessionKeyRef:f,resetStreamState:t.chatStreamActionsManager.resetStreamState,resolveAgentIdFromSessionKey:Ra}),k.useEffect(()=>{t.chatStreamActionsManager.applyHistoryMessages(B,{isLoading:v.isLoading})},[B,v.isLoading,t]),k.useEffect(()=>{t.chatUiManager.syncState({pathname:u.pathname}),t.chatUiManager.bindActions({navigate:c,confirm:a})},[a,u.pathname,c,t]);const Se=F?Wi(F):void 0,Me=((Re=z.find(ce=>ce.value===D))==null?void 0:Re.label)??lt(D);return k.useEffect(()=>{t.chatThreadManager.bindActions({refetchSessions:y.refetch})},[t,y.refetch]),k.useEffect(()=>{var ce,G;t.chatInputManager.syncSnapshot({isProviderStateResolved:C,defaultSessionType:w,canStopGeneration:W,stopDisabledReason:se,stopSupported:((ce=g.data)==null?void 0:ce.stopSupported)??!1,stopReason:(G=g.data)==null?void 0:G.stopReason,sendError:x,isSending:U,modelOptions:A,sessionTypeOptions:z,selectedSessionType:D,canEditSessionType:N,sessionTypeUnavailable:$,skillRecords:T,isSkillsLoading:b.isLoading}),t.chatSessionListManager.syncSnapshot({sessions:P,query:n,isLoading:y.isLoading}),t.chatRunStatusManager.syncSnapshot({sessionRunStatusByKey:pe,isLocallyRunning:U||!!ae,activeBackendRunId:ae}),t.chatThreadManager.syncSnapshot({isProviderStateResolved:C,modelOptions:A,sessionTypeUnavailable:$,sessionTypeUnavailableMessage:O,sessionTypeLabel:Me,selectedSessionKey:r,sessionDisplayName:Se,canDeleteSession:!!F,threadRef:p,isHistoryLoading:v.isLoading,uiMessages:R,isSending:U,isAwaitingAssistantOutput:E})},[ae,N,W,Se,Me,(je=g.data)==null?void 0:je.stopReason,(Ye=g.data)==null?void 0:Ye.stopSupported,w,v.isLoading,b.isLoading,E,C,U,x,A.length,A,t,n,F,r,D,pe,z,$,O,P,y.isLoading,T,se,p,R]),h.jsx(Qi,{presenter:t,children:h.jsx(Ma,{view:e,confirmDialog:h.jsx(l,{})})})}var ne=(e=>(e.EndpointReady="endpoint.ready",e.EndpointError="endpoint.error",e.MessageRequest="message.request",e.MessageStreamRequest="message.stream-request",e.MessageSent="message.sent",e.MessageAccepted="message.accepted",e.MessageIncoming="message.incoming",e.MessageCompleted="message.completed",e.MessageFailed="message.failed",e.MessageAbort="message.abort",e.MessageTextStart="message.text-start",e.MessageTextDelta="message.text-delta",e.MessageTextEnd="message.text-end",e.MessageReasoningStart="message.reasoning-start",e.MessageReasoningDelta="message.reasoning-delta",e.MessageReasoningEnd="message.reasoning-end",e.MessageToolCallStart="message.tool-call-start",e.MessageToolCallArgs="message.tool-call-args",e.MessageToolCallArgsDelta="message.tool-call-args-delta",e.MessageToolCallEnd="message.tool-call-end",e.MessageToolCallResult="message.tool-call-result",e.MessageRead="message.read",e.MessageDelivered="message.delivered",e.MessageRecalled="message.recalled",e.MessageReaction="message.reaction",e.RunStarted="run.started",e.RunFinished="run.finished",e.RunError="run.error",e.RunMetadata="run.metadata",e.TypingStart="typing.start",e.TypingEnd="typing.end",e.PresenceUpdated="presence.updated",e))(ne||{}),oi=/\[\[\s*reply_to_current\s*\]\]/gi,ai=/\[\[\s*reply_to\s*:\s*([^\]]+?)\s*\]\]/i;function ir(e){if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0}function Ib(e,t){var i;let n=e,r;oi.test(n)&&(r=ir(t),n=n.replace(oi,"").trim());const s=(i=n.match(ai))==null?void 0:i[1];return s&&(r=ir(s),n=n.replace(ai,"").trim()),r?{content:n,replyTo:r}:{content:n}}function Mb(e,t=e.id){if(e.role!=="assistant")return{...e,parts:[...e.parts],metadata:e.metadata?{...e.metadata}:void 0};const n=e.parts.findIndex(c=>c.type==="text"),r=e.metadata?{...e.metadata}:void 0,s=ir(r==null?void 0:r.reply_to);if(n<0)return{...e,parts:[...e.parts],metadata:r};const i=e.parts[n];if(!i||i.type!=="text")return{...e,parts:[...e.parts],metadata:r};const{content:o,replyTo:a}=Ib(i.text,t),l=a??s,u=e.parts.flatMap((c,d)=>d!==n||c.type!=="text"?[c]:o.length===0?[]:[{...c,text:o}]);return l?{...e,parts:u,metadata:{...r,reply_to:l}}:{...e,parts:u,metadata:r}}function li(e){const t=e.split(/\r?\n/);let n="message";const r=[];for(const s of t){const i=s.trimEnd();if(!(!i||i.startsWith(":"))){if(i.startsWith("event:")){n=i.slice(6).trim()||"message";continue}i.startsWith("data:")&&r.push(i.slice(5).trimStart())}}return r.length===0?null:{event:n,data:r.join(`
38
38
  `)}}async function*Rb(e){const t=e.getReader(),n=new TextDecoder;let r="";try{for(;;){const{value:i,done:o}=await t.read();if(o)break;r+=n.decode(i,{stream:!0});const{frames:a,rest:l}=ui(r);r=l;for(const u of a)yield u}r+=n.decode();const{frames:s}=ui(r,!0);for(const i of s)yield i}finally{t.releaseLock()}}function ui(e,t=!1){const n=e.split(/\r?\n\r?\n/),r=n.pop()??"",s=[];for(const i of n){const o=li(i);o&&s.push(o)}if(t&&r.trim()){const i=li(r);return i&&s.push(i),{frames:s,rest:""}}return{frames:s,rest:r}}var ci="/ncp/agent",Eb="ncp-http-agent-client",Oa=class extends Error{constructor(t,n=!1){super(t.message);_(this,"ncpError");_(this,"alreadyPublished");this.name=`NcpHttpAgentClientError(${t.code})`,this.ncpError=t,this.alreadyPublished=n}};function Ab(e){const t=e.trim();if(!t)throw new Error("NcpHttpAgentClient requires a non-empty baseUrl.");return new URL(t)}function Lb(e){if(e)return e;if(typeof globalThis.fetch=="function")return globalThis.fetch.bind(globalThis);throw new Error("No fetch implementation found. Pass options.fetchImpl explicitly.")}function Nb(e){const t=(e??ci).trim();if(!t)return ci;const n=t.startsWith("/")?t:`/${t}`;return n.endsWith("/")?n.slice(0,-1):n}async function di(e){try{return(await e.text()).trim()}catch{return""}}function hi(e){if(Fa(e))return e.ncpError;if(Pb(e))return e;const t=e instanceof Error?e.message:String(e??"Unknown error");return{code:za(void 0),message:t,...e instanceof Error&&e.stack?{details:{stack:e.stack}}:{}}}function Nn(e,t={}){return new Oa(e,t.alreadyPublished??!1)}function Pb(e){return Or(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Or(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Fa(e){return e instanceof Oa}var jb={"config-error":"config-error","auth-error":"auth-error","runtime-error":"runtime-error","timeout-error":"timeout-error","abort-error":"abort-error"};function za(e){if(!e)return"runtime-error";const t=jb[e];if(t)return t;const n=e.toLowerCase();return n.includes("timeout")?"timeout-error":n.includes("abort")||n.includes("cancel")?"abort-error":n.includes("auth")?"auth-error":n.includes("config")?"config-error":"runtime-error"}function Db(e){const t=Ba(e);return!t||typeof t.type!="string"||!t.type.trim()?null:t}function _b(e){const t=Ba(e);if(!t)return{code:"runtime-error",message:e||"Unknown stream error."};const n=typeof t.code=="string"?t.code:void 0,r=za(n),s=Or(t.details)?t.details:{};return n&&n!==r&&(s.originalCode=n),{code:r,message:typeof t.message=="string"&&t.message?t.message:"Unknown stream error.",...Object.keys(s).length>0?{details:s}:{}}}function Ba(e){try{const t=JSON.parse(e);return Or(t)?t:null}catch{return null}}var Ob=["text","file","source","step-start","reasoning","tool-invocation","card","rich-text","action","extension"],Fb=class{constructor(e){_(this,"manifest");_(this,"baseUrl");_(this,"basePath");_(this,"fetchImpl");_(this,"defaultHeaders");_(this,"subscribers",new Set);_(this,"activeControllers",new Set);_(this,"started",!1);var t;this.baseUrl=Ab(e.baseUrl),this.basePath=Nb(e.basePath),this.fetchImpl=Lb(e.fetchImpl),this.defaultHeaders=e.headers??{},this.manifest={endpointKind:"custom",endpointId:((t=e.endpointId)==null?void 0:t.trim())||Eb,version:"0.1.0",supportsStreaming:!0,supportsAbort:!0,supportsProactiveMessages:!1,supportsLiveSessionStream:!0,supportedPartTypes:Ob,expectedLatency:"seconds",metadata:{transport:"http+sse",scope:"agent"}}}async start(){this.started||(this.started=!0,this.publish({type:ne.EndpointReady}))}async stop(){if(this.started){this.started=!1;for(const e of this.activeControllers)e.abort();this.activeControllers.clear()}}async emit(e){switch(e.type){case"message.request":await this.send(e.payload);return;case"message.stream-request":await this.stream(e.payload);return;case"message.abort":await this.abort(e.payload);return;default:this.publish(e);return}}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}async send(e){await this.ensureStarted(),await this.streamRequest({path:"/send",method:"POST",body:e})}async stream(e){await this.ensureStarted();const t=new URLSearchParams({sessionId:e.sessionId});await this.streamRequest({path:`/stream?${t.toString()}`,method:"GET"})}async abort(e){await this.ensureStarted();const t=new AbortController;this.activeControllers.add(t);try{const n=await this.fetchImpl(this.resolveUrl("/abort"),{method:"POST",headers:{...this.defaultHeaders,"content-type":"application/json",accept:"application/json"},body:JSON.stringify(e),signal:t.signal});if(!n.ok)throw new Error(`Abort request failed with HTTP ${n.status}: ${await di(n)}`)}catch(n){if(t.signal.aborted)return;const r=hi(n);throw this.publish({type:ne.EndpointError,payload:r}),Nn(r)}finally{this.activeControllers.delete(t)}}async ensureStarted(){this.started||await this.start()}publish(e){for(const t of this.subscribers)t(e)}resolveUrl(e){return new URL(`${this.basePath}${e}`,this.baseUrl)}async streamRequest(e){const t=new AbortController;this.activeControllers.add(t);try{const n=await this.fetchImpl(this.resolveUrl(e.path),{method:e.method,headers:{...this.defaultHeaders,accept:"text/event-stream",...e.body!==void 0?{"content-type":"application/json"}:{}},body:e.body===void 0?void 0:JSON.stringify(e.body),signal:t.signal});if(!n.ok)throw new Error(`NCP stream request failed with HTTP ${n.status}: ${await di(n)}`);if(!n.body)throw new Error("NCP stream response has no body.");for await(const r of Rb(n.body)){if(t.signal.aborted)return;this.handleSseFrame(r)}}catch(n){if(t.signal.aborted)return;if(Fa(n))throw n;const r=hi(n);throw this.publish({type:ne.EndpointError,payload:r}),Nn(r)}finally{this.activeControllers.delete(t)}}handleSseFrame(e){if(e.event==="ncp-event"){const t=Db(e.data);if(!t){this.publish({type:ne.EndpointError,payload:{code:"runtime-error",message:"Received malformed ncp-event frame."}});return}this.publish(t);return}if(e.event==="error"){const t=_b(e.data);throw this.publish({type:ne.EndpointError,payload:t}),Nn(t,{alreadyPublished:!0})}}};function Vt(e){return{...e,parts:[...e.parts],metadata:e.metadata?{...e.metadata}:void 0}}function Pn(e){return Vt(Mb(e))}function zb(e){var n;const t=(n=e.error)==null?void 0:n.trim();return{code:"runtime-error",message:t&&t.length>0?t:"Agent run failed.",details:{sessionId:e.sessionId,messageId:e.messageId,threadId:e.threadId,runId:e.runId}}}function Bb(e,t){return t.trim()?e.id.startsWith("tool-")?!0:e.parts.some(n=>n.type==="tool-invocation"):!1}function $b(e,t,n){for(const[r,s]of e)s===t&&e.set(r,n)}function Bt(e,t,n){for(const[r,s]of e)s===n&&(e.delete(r),t.delete(r))}function or(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r.type==="tool-invocation"&&r.toolCallId===t)return r}return null}function fi(e,t){const n=or(e,t);return(n==null?void 0:n.toolName)??null}function bt(e,t){const n=[...e];for(let r=n.length-1;r>=0;r-=1){const s=n[r];if(s.type==="tool-invocation"&&s.toolCallId===t.toolCallId)return n[r]={...s,...t},n}return n.push(t),n}var Kb="assistant",Ub=class{constructor(){_(this,"messages",[]);_(this,"streamingMessage",null);_(this,"error",null);_(this,"activeRun",null);_(this,"listeners",new Set);_(this,"toolCallMessageIdByCallId",new Map);_(this,"toolCallArgsRawByCallId",new Map);_(this,"snapshotCache",null);_(this,"snapshotVersion",-1);_(this,"stateVersion",0)}getSnapshot(){if(this.snapshotCache&&this.snapshotVersion===this.stateVersion)return this.snapshotCache;const e={messages:this.messages.map(t=>Vt(t)),streamingMessage:this.streamingMessage?Vt(this.streamingMessage):null,error:this.error?{...this.error,details:this.error.details?{...this.error.details}:void 0}:null,activeRun:this.activeRun?{...this.activeRun}:null};return this.snapshotCache=e,this.snapshotVersion=this.stateVersion,e}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}reset(){this.messages.length===0&&!this.streamingMessage&&!this.error&&!this.activeRun&&this.toolCallMessageIdByCallId.size===0&&this.toolCallArgsRawByCallId.size===0||(this.messages=[],this.streamingMessage=null,this.error=null,this.activeRun=null,this.toolCallMessageIdByCallId.clear(),this.toolCallArgsRawByCallId.clear(),this.stateVersion+=1,this.notifyListeners())}hydrate(e){this.messages=e.messages.map(t=>Pn(t)),this.streamingMessage=null,this.error=null,this.activeRun=e.activeRun?{...e.activeRun,sessionId:e.activeRun.sessionId??e.sessionId,abortDisabledReason:e.activeRun.abortDisabledReason??null}:null,this.toolCallMessageIdByCallId.clear(),this.toolCallArgsRawByCallId.clear(),this.stateVersion+=1,this.notifyListeners()}async dispatch(e){const t=this.stateVersion;switch(e.type){case ne.MessageSent:this.handleMessageSent(e.payload);break;case ne.MessageAbort:this.handleMessageAbort(e.payload);break;case ne.MessageTextStart:this.handleMessageTextStart(e.payload);break;case ne.MessageTextDelta:this.handleMessageTextDelta(e.payload);break;case ne.MessageTextEnd:this.handleMessageTextEnd(e.payload);break;case ne.MessageReasoningStart:this.handleMessageReasoningStart(e.payload);break;case ne.MessageReasoningDelta:this.handleMessageReasoningDelta(e.payload);break;case ne.MessageReasoningEnd:this.handleMessageReasoningEnd(e.payload);break;case ne.MessageToolCallStart:this.handleMessageToolCallStart(e.payload);break;case ne.MessageToolCallArgs:this.handleMessageToolCallArgs(e.payload);break;case ne.MessageToolCallArgsDelta:this.handleMessageToolCallArgsDelta(e.payload);break;case ne.MessageToolCallEnd:this.handleMessageToolCallEnd(e.payload);break;case ne.MessageToolCallResult:this.handleMessageToolCallResult(e.payload);break;case ne.RunStarted:this.handleRunStarted(e.payload);break;case ne.RunFinished:this.handleRunFinished(e.payload);break;case ne.RunError:this.handleRunError(e.payload);break;case ne.RunMetadata:this.handleRunMetadata(e.payload);break;case ne.EndpointError:this.handleEndpointError(e.payload);break}this.stateVersion!==t&&this.notifyListeners()}handleMessageSent(e){this.upsertMessage(e.message),this.setError(null)}handleMessageAbort(e){var n;const t=(n=e.messageId)==null?void 0:n.trim();if(this.clearActiveRun(),this.setError(null),this.streamingMessage&&(!t||this.streamingMessage.id===t)){const r=this.streamingMessage.id;this.upsertMessage({...this.streamingMessage,status:"final"}),this.replaceStreamingMessage(null),t?Bt(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,t):Bt(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,r)}}handleMessageTextStart(e){this.ensureStreamingMessage(e.sessionId,e.messageId,"streaming"),this.setError(null)}handleMessageTextDelta(e){if(!e.delta)return;const t=this.ensureStreamingMessage(e.sessionId,e.messageId,"streaming"),n=[...t.parts],r=n[n.length-1];(r==null?void 0:r.type)==="text"?n[n.length-1]={type:"text",text:`${r.text}${e.delta}`}:n.push({type:"text",text:e.delta}),this.replaceStreamingMessage({...t,parts:n,status:"streaming"})}handleMessageTextEnd(e){var t;((t=this.streamingMessage)==null?void 0:t.id)===e.messageId&&this.streamingMessage.status==="streaming"&&this.replaceStreamingMessage({...this.streamingMessage,status:"pending"})}handleMessageReasoningStart(e){this.ensureStreamingMessage(e.sessionId,e.messageId,"streaming")}handleMessageReasoningDelta(e){if(!e.delta)return;const t=this.ensureStreamingMessage(e.sessionId,e.messageId,"streaming"),n=[...t.parts],r=n[n.length-1];(r==null?void 0:r.type)==="reasoning"?n[n.length-1]={type:"reasoning",text:`${r.text}${e.delta}`}:n.push({type:"reasoning",text:e.delta}),this.replaceStreamingMessage({...t,parts:n,status:"streaming"})}handleMessageReasoningEnd(e){var t;(t=this.streamingMessage)==null||t.id,e.messageId}handleMessageToolCallStart(e){const t=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId,e.messageId);this.toolCallArgsRawByCallId.set(e.toolCallId,"");const n=bt(t.parts,{type:"tool-invocation",toolCallId:e.toolCallId,toolName:e.toolName,state:"partial-call",args:""});this.replaceStreamingMessage({...t,parts:n,status:"streaming"}),this.setError(null)}handleMessageToolCallArgs(e){this.toolCallArgsRawByCallId.set(e.toolCallId,e.args),this.applyToolCallArgs(e.sessionId,e.toolCallId,e.args)}handleMessageToolCallArgsDelta(e){const n=`${this.toolCallArgsRawByCallId.get(e.toolCallId)??""}${e.delta}`;this.toolCallArgsRawByCallId.set(e.toolCallId,n),this.applyToolCallArgs(e.sessionId,e.toolCallId,n,e.messageId)}handleMessageToolCallEnd(e){const t=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId),n=this.toolCallArgsRawByCallId.get(e.toolCallId)??"",r=bt(t.parts,{type:"tool-invocation",toolCallId:e.toolCallId,toolName:fi(t.parts,e.toolCallId)??"unknown",state:"call",args:n});this.replaceStreamingMessage({...t,parts:r,status:"streaming"})}handleMessageToolCallResult(e){if(!this.updateMessageContainingToolCall(e.toolCallId,(n,r)=>{const s={type:"tool-invocation",toolCallId:e.toolCallId,toolName:r.toolName,state:"result",args:r.args,result:e.content};return bt(n.parts,s)})){const n=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId),r=bt(n.parts,{type:"tool-invocation",toolCallId:e.toolCallId,toolName:"unknown",state:"result",result:e.content});this.replaceStreamingMessage({...n,parts:r,status:"streaming"})}}handleRunStarted(e){this.setError(null),this.activeRun={runId:e.runId??null,sessionId:e.sessionId},this.stateVersion+=1}handleRunFinished(e){if(this.streamingMessage){const t={...this.streamingMessage,status:"final"};this.upsertMessage(t),this.replaceStreamingMessage(null),Bt(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,t.id)}this.setError(null),this.clearActiveRun()}handleRunError(e){if(this.streamingMessage){const t={...this.streamingMessage,status:"error"};this.upsertMessage(t),this.replaceStreamingMessage(null),Bt(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,t.id)}this.setError(zb(e)),this.clearActiveRun()}handleRunMetadata(e){var n,r;const t=e.metadata;if((t==null?void 0:t.kind)==="ready"){const s=t;this.activeRun={runId:s.runId??((n=this.activeRun)==null?void 0:n.runId)??null,sessionId:s.sessionId??((r=this.activeRun)==null?void 0:r.sessionId),abortDisabledReason:s.supportsAbort===!1?s.abortDisabledReason??"Unsupported":null},this.stateVersion+=1}else(t==null?void 0:t.kind)==="final"&&this.clearActiveRun()}handleEndpointError(e){this.setError(e)}applyToolCallArgs(e,t,n,r){const s=this.resolveToolCallTargetMessage(e,t,r),i=fi(s.parts,t)??"unknown",o=bt(s.parts,{type:"tool-invocation",toolCallId:t,toolName:i,state:"partial-call",args:n});this.replaceStreamingMessage({...s,parts:o,status:"streaming"})}ensureStreamingMessage(e,t,n){var o;if(((o=this.streamingMessage)==null?void 0:o.id)===t){if(this.streamingMessage.status===n)return this.streamingMessage;const a={...this.streamingMessage,status:n};return this.replaceStreamingMessage(a),a}const r=this.messages.findIndex(a=>a.id===t);if(r>=0){const a=Vt(this.messages[r]),l=[...this.messages];l.splice(r,1),this.messages=l,this.stateVersion+=1;const u={...a,sessionId:e,status:n};return this.replaceStreamingMessage(u),u}const s=this.streamingMessage;if(s&&s.id!==t&&s.sessionId===e&&Bb(s,t)){const a={...s,id:t,sessionId:e,status:n};return $b(this.toolCallMessageIdByCallId,s.id,t),this.replaceStreamingMessage(a),a}const i={id:t,sessionId:e,role:Kb,status:n,parts:[],timestamp:new Date().toISOString()};return this.replaceStreamingMessage(i),i}resolveToolCallTargetMessage(e,t,n){var s;const r=(n==null?void 0:n.trim())||this.toolCallMessageIdByCallId.get(t)||((s=this.streamingMessage)==null?void 0:s.id)||`tool-${t}`;return this.toolCallMessageIdByCallId.set(t,r),this.ensureStreamingMessage(e,r,"streaming")}updateMessageContainingToolCall(e,t){if(this.streamingMessage){const n=or(this.streamingMessage.parts,e);if(n){const r=t(this.streamingMessage,n);return this.replaceStreamingMessage({...this.streamingMessage,parts:r}),!0}}for(let n=this.messages.length-1;n>=0;n-=1){const r=this.messages[n],s=or(r.parts,e);if(!s)continue;const i=[...this.messages];return i[n]={...r,parts:t(r,s)},this.messages=i,this.stateVersion+=1,!0}return!1}upsertMessage(e){const t=Pn(e),n=this.messages.findIndex(s=>s.id===t.id);if(n<0){this.messages=[...this.messages,t],this.stateVersion+=1;return}const r=[...this.messages];r[n]=t,this.messages=r,this.stateVersion+=1}replaceStreamingMessage(e){!e&&!this.streamingMessage||(this.streamingMessage=e?Pn(e):null,this.stateVersion+=1)}setError(e){var n,r,s,i;((n=this.error)==null?void 0:n.code)===(e==null?void 0:e.code)&&((r=this.error)==null?void 0:r.message)===(e==null?void 0:e.message)&&((s=this.error)==null?void 0:s.details)===(e==null?void 0:e.details)&&((i=this.error)==null?void 0:i.cause)===(e==null?void 0:e.cause)||(this.error=e?{...e,details:e.details?{...e.details}:void 0}:null,this.stateVersion+=1)}clearActiveRun(){this.activeRun&&(this.activeRun=null,this.stateVersion+=1)}notifyListeners(){const e=this.getSnapshot();for(const t of this.listeners)t(e)}};function Vb(e,t){const n="payload"in e?e.payload:null;return!n||typeof n!="object"||!("sessionId"in n)||typeof n.sessionId!="string"?!0:n.sessionId===t}function Hb(e){return e.parts.some(t=>t.type==="text"||t.type==="rich-text"||t.type==="reasoning"?t.text.trim().length>0:!0)}function qb(e,t){if(typeof e=="string"){const n=e.trim();return n?{sessionId:t,message:{id:`user-${Date.now().toString(36)}`,sessionId:t,role:"user",status:"final",parts:[{type:"text",text:n}],timestamp:new Date().toISOString()}}:null}return Hb(e.message)?{...e,sessionId:e.sessionId,message:{...e.message,sessionId:e.message.sessionId||e.sessionId}}:null}function Wb(e,t){return{sessionId:e,messages:t.messages,activeRun:t.activeRun}}function Gb(e){const t=k.useRef();return(!t.current||t.current.sessionId!==e)&&(t.current={sessionId:e,manager:new Ub}),t.current.manager}function Qb({sessionId:e,client:t,manager:n}){var p;const r=k.useSyncExternalStore(f=>n.subscribe(()=>f()),()=>n.getSnapshot(),()=>n.getSnapshot()),[s,i]=k.useState(!1);k.useEffect(()=>{i(!1)},[e]),k.useEffect(()=>{const f=t.subscribe(m=>{Vb(m,e)&&n.dispatch(m)});return()=>{f(),t.stop()}},[t,n,e]);const o=r.streamingMessage?[...r.messages,r.streamingMessage]:r.messages,a=((p=r.activeRun)==null?void 0:p.runId)??null,l=!!r.activeRun;return{snapshot:r,visibleMessages:o,activeRunId:a,isRunning:l,isSending:s,send:async f=>{if(s||l)return;const m=qb(f,e);if(!m)return;i(!0);const y=n.getSnapshot();await n.dispatch({type:ne.MessageSent,payload:{sessionId:e,message:m.message,metadata:m.metadata}});try{await t.send(m)}catch(b){throw n.hydrate(Wb(e,y)),b}finally{i(!1)}},abort:async()=>{r.activeRun&&await t.abort({sessionId:e})},streamRun:async()=>{r.activeRun&&await t.stream({sessionId:e})}}}function pi(e){return e instanceof Error?e:new Error(String(e))}function Xb({sessionId:e,client:t,loadSeed:n,autoResumeRunningSession:r=!0}){const s=Gb(e),i=Qb({sessionId:e,client:t,manager:s}),[o,a]=k.useState(!0),[l,u]=k.useState(null),c=k.useRef({requestId:0,controller:null}),d=k.useCallback(async()=>{var m;(m=c.current.controller)==null||m.abort();const p=new AbortController,f=c.current.requestId+1;c.current={requestId:f,controller:p},await t.stop(),s.reset(),u(null),a(!0);try{const y=await n(e,p.signal);if(p.signal.aborted||c.current.requestId!==f)return;s.hydrate({sessionId:e,messages:y.messages,activeRun:y.status==="running"?{runId:null,sessionId:e,abortDisabledReason:null}:null}),u(null),a(!1),y.status==="running"&&r&&t.stream({sessionId:e}).catch(b=>{c.current.requestId===f&&u(pi(b))})}catch(y){if(p.signal.aborted||c.current.requestId!==f)return;u(pi(y)),a(!1)}finally{c.current.controller===p&&(c.current.controller=null)}},[r,t,n,s,e]);return k.useEffect(()=>(d(),()=>{var p;(p=c.current.controller)==null||p.abort(),c.current.controller=null}),[d]),{...i,isHydrating:o,hydrateError:l,reloadSeed:d}}function Yb(){return async(e,t)=>{const n=Jb(e,t);if(eS(n))return tS(n);try{const r=await en.request({method:n.method,path:n.path,...n.body!==void 0?{body:n.body}:{}});return new Response(JSON.stringify(r??{}),{status:200,headers:{"content-type":"application/json"}})}catch(r){return new Response(r instanceof Error?r.message:String(r),{status:500,headers:{"content-type":"text/plain; charset=utf-8"}})}}}function Jb(e,t){const n=e instanceof Request?e:null,r=new URL(typeof e=="string"?e:e instanceof URL?e.toString():e.url,Li),s=new Headers((t==null?void 0:t.headers)??(n==null?void 0:n.headers));return{method:((t==null?void 0:t.method)??(n==null?void 0:n.method)??"GET").toUpperCase(),path:`${r.pathname}${r.search}`,body:Zb(t==null?void 0:t.body),signal:(t==null?void 0:t.signal)??(n==null?void 0:n.signal)??void 0,headers:s}}function Zb(e){if(e!=null){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}}function eS(e){var n;return(((n=e.headers.get("accept"))==null?void 0:n.toLowerCase())??"").includes("text/event-stream")}function tS(e){const t=new TextEncoder;let n=null;const r=new ReadableStream({start(s){n=en.openStream({method:e.method==="GET"?"GET":"POST",path:e.path,...e.body!==void 0?{body:e.body}:{},signal:e.signal,onEvent:i=>{s.enqueue(t.encode(gi(i.name,i.payload)))}}),n.finished.then(()=>{s.close()}).catch(i=>{s.enqueue(t.encode(gi("error",{message:i instanceof Error?i.message:String(i)}))),s.close()})},cancel(){n==null||n.cancel()}});return new Response(r,{status:200,headers:{"content-type":"text/event-stream"}})}function gi(e,t){const n=t===void 0?"":JSON.stringify(t);return`event: ${e}
39
39
  data: ${n}
40
40