nextclaw 0.17.0 → 0.17.1

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 (22) hide show
  1. package/dist/cli/index.d.ts +1 -1
  2. package/dist/cli/index.js +9472 -11370
  3. package/dist/index.d.ts +1 -1
  4. package/dist/index.js +1 -1
  5. package/package.json +7 -8
  6. package/ui-dist/assets/{ChannelsList-NKNKsf1J.js → ChannelsList-BXuFNDBh.js} +1 -1
  7. package/ui-dist/assets/{ChatPage-p23OnnEI.js → ChatPage-CEuFBJgC.js} +2 -2
  8. package/ui-dist/assets/MarketplacePage-BGPF2sDu.js +1 -0
  9. package/ui-dist/assets/{MarketplacePage-CRNvxtvx.js → MarketplacePage-CNeXwz7q.js} +1 -1
  10. package/ui-dist/assets/{McpMarketplacePage-Cu7GmCcc.js → McpMarketplacePage-BGv2wwuk.js} +1 -1
  11. package/ui-dist/assets/{ModelConfig-CEpx9fro.js → ModelConfig-CoNm556G.js} +1 -1
  12. package/ui-dist/assets/{ProvidersList-BWbUb7-2.js → ProvidersList-BXeGOw0M.js} +1 -1
  13. package/ui-dist/assets/{RemoteAccessPage-NsawrZb0.js → RemoteAccessPage-vlBOKnMP.js} +1 -1
  14. package/ui-dist/assets/{RuntimeConfig-BJHBsVTd.js → RuntimeConfig-CEkrhzg7.js} +1 -1
  15. package/ui-dist/assets/{SearchConfig-BsaX_WYy.js → SearchConfig-BK0dn4Zp.js} +1 -1
  16. package/ui-dist/assets/{SecretsConfig-CgDZOd3w.js → SecretsConfig-Jduzy42Q.js} +1 -1
  17. package/ui-dist/assets/{SessionsConfig-Dd-KM7F7.js → SessionsConfig-CIwqHwvE.js} +1 -1
  18. package/ui-dist/assets/{index-BZaB1TqM.js → index-BuTtTFjM.js} +2 -2
  19. package/ui-dist/assets/{security-config-DRDxrApx.js → security-config-BrmOzvpp.js} +1 -1
  20. package/ui-dist/assets/{useConfirmDialog-DsxnXB1B.js → useConfirmDialog-RlLbo0NU.js} +1 -1
  21. package/ui-dist/index.html +1 -1
  22. package/ui-dist/assets/MarketplacePage-GGkEXowp.js +0 -1
@@ -1,4 +1,4 @@
1
- import{_ as e,a as t,d as n,f as r,g as i,h as a,i as o,m as s,n as c,p as l,u}from"./i18n-BK1w-oBy.js";import{a as d,c as f,n as p,o as m,r as h,s as g,u as _}from"./dist-DazA6Wd_.js";import{c as v,o as y,s as b}from"./chunk-JZWAC4HX-B5l0hr_u.js";import{n as x,t as S}from"./react-C3yu5yge.js";import{t as C}from"./useMutation-oTTWXgLG.js";import{D as w,O as T,_ as E,a as D,b as O,c as ee,d as k,f as te,g as A,h as j,i as ne,k as re,l as ie,m as M,n as ae,o as oe,p as se,r as ce,s as le,t as ue,u as de,v as fe,y as pe}from"./select-BHJPiJWt.js";import{t as N}from"./createLucideIcon-o1WWhwhd.js";import{n as me}from"./DocBrowser-DxdSujSc.js";import{t as he}from"./book-open-FnK2xCQd.js";import{t as ge}from"./external-link-BKje3SiD.js";import{i as _e,n as ve,o as ye,t as be}from"./provider-models-DJ29qHuA.js";import{n as xe,t as Se}from"./logos-CTLlde_T.js";import{t as Ce}from"./loader-circle-DdZPxBUz.js";import{a as we,c as Te,i as Ee,l as De,n as Oe,o as ke,r as Ae,s as je,t as Me,u as Ne}from"./MarketplacePage-CRNvxtvx.js";import{t as Pe}from"./plus-DP2PSCPO.js";import{t as Fe}from"./refresh-ccw-BAJf-h7w.js";import{a as Ie,c as Le,d as Re,i as ze,l as Be,n as Ve,o as He,r as Ue,s as We,t as Ge,u as Ke}from"./chat-session-display-BD_AN71I.js";import{t as qe}from"./search-pD6ZwQYF.js";import{t as Je}from"./trash-2-CrjYH5ok.js";import{t as Ye}from"./x-CTIQHUuD.js";import{d as Xe}from"./config-JKmXfZ3q.js";import{i as Ze}from"./DocBrowserContext-CQ-8jMha.js";import{F as Qe,G as $e,I as et,K as tt,L as nt,N as rt,P as it,R as at,S as ot,T as st,W as ct,_t as lt,a as ut,at as dt,b as ft,c as pt,ct as mt,et as ht,f as gt,ft as _t,gt as vt,ht as yt,i as bt,it as xt,l as St,lt as Ct,n as wt,nt as Tt,o as Et,ot as Dt,p as Ot,pt as kt,r as At,rt as jt,s as Mt,t as Nt,tt as Pt,ut as Ft,y as It}from"./index-BZaB1TqM.js";import{a as Lt,c as Rt,i as zt,n as Bt,o as Vt,r as Ht,s as Ut,t as Wt}from"./popover-5DWhNfd4.js";import{t as Gt}from"./LogoBadge-D-KQIN4U.js";import{t as Kt}from"./label-BzDWmdOe.js";import{n as qt,t as Jt}from"./page-layout-BagR3t59.js";import{t as Yt}from"./useConfirmDialog-DsxnXB1B.js";var Xt=N(`ArrowUpRight`,[[`path`,{d:`M7 7h10v10`,key:`1tivn9`}],[`path`,{d:`M7 17 17 7`,key:`1vkiza`}]]),Zt=N(`ArrowUp`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),Qt=N(`Brain`,[[`path`,{d:`M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z`,key:`l5xja`}],[`path`,{d:`M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z`,key:`ep3f8r`}],[`path`,{d:`M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4`,key:`1p4c4q`}],[`path`,{d:`M17.599 6.5a3 3 0 0 0 .399-1.375`,key:`tmeiqw`}],[`path`,{d:`M6.003 5.125A3 3 0 0 0 6.401 6.5`,key:`105sqy`}],[`path`,{d:`M3.477 10.896a4 4 0 0 1 .585-.396`,key:`ql3yin`}],[`path`,{d:`M19.938 10.5a4 4 0 0 1 .585.396`,key:`1qfode`}],[`path`,{d:`M6 18a4 4 0 0 1-1.967-.516`,key:`2e4loj`}],[`path`,{d:`M19.967 17.484A4 4 0 0 1 18 18`,key:`159ez6`}]]),$t=N(`ChevronRight`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),en=N(`CodeXml`,[[`path`,{d:`m18 16 4-4-4-4`,key:`1inbqp`}],[`path`,{d:`m6 8-4 4 4 4`,key:`15zrgr`}],[`path`,{d:`m14.5 4-5 16`,key:`e7oirm`}]]),tn=N(`Copy`,[[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`,key:`17jyea`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`,key:`zix9uf`}]]),nn=N(`Ellipsis`,[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`19`,cy:`12`,r:`1`,key:`1wjl8i`}],[`circle`,{cx:`5`,cy:`12`,r:`1`,key:`1pcz8c`}]]),rn=N(`FileText`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),an=N(`FolderOpen`,[[`path`,{d:`m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2`,key:`usdka0`}]]),on=N(`FolderUp`,[[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}],[`path`,{d:`M12 10v6`,key:`1bos4e`}],[`path`,{d:`m9 13 3-3 3 3`,key:`1pxg3c`}]]),sn=N(`FolderX`,[[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}],[`path`,{d:`m9.5 10.5 5 5`,key:`ra9qjz`}],[`path`,{d:`m14.5 10.5-5 5`,key:`l2rkpq`}]]),cn=N(`HeartPulse`,[[`path`,{d:`M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z`,key:`c3ymky`}],[`path`,{d:`M3.22 12H9.5l.5-1 2 4.5 2-7 1.5 3.5h5.27`,key:`1uw2ng`}]]),ln=N(`House`,[[`path`,{d:`M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8`,key:`5wwlr5`}],[`path`,{d:`M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z`,key:`1d0kgt`}]]),un=N(`MessageSquareText`,[[`path`,{d:`M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z`,key:`1lielz`}],[`path`,{d:`M13 8H7`,key:`14i4kc`}],[`path`,{d:`M17 12H7`,key:`16if0g`}]]),dn=N(`Minus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}]]),fn=N(`Paperclip`,[[`path`,{d:`m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48`,key:`1u3ebp`}]]),pn=N(`Pencil`,[[`path`,{d:`M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z`,key:`1a8usu`}],[`path`,{d:`m15 5 4 4`,key:`1mk7zo`}]]),mn=N(`Play`,[[`polygon`,{points:`6 3 20 12 6 21 6 3`,key:`1oa8hb`}]]),hn=N(`Power`,[[`path`,{d:`M12 2v10`,key:`mnfbl`}],[`path`,{d:`M18.4 6.6a9 9 0 1 1-12.77.04`,key:`obofu9`}]]),gn=N(`Puzzle`,[[`path`,{d:`M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z`,key:`w46dr5`}]]),_n=N(`ShieldCheck`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),vn=N(`Terminal`,[[`polyline`,{points:`4 17 10 11 4 5`,key:`akl6gq`}],[`line`,{x1:`12`,x2:`20`,y1:`19`,y2:`19`,key:`q2wloq`}]]),yn=N(`TriangleAlert`,[[`path`,{d:`m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3`,key:`wmoenq`}],[`path`,{d:`M12 9v4`,key:`juzpu7`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),P=e(s(),1),F=(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))(F||{}),bn=/\[\[\s*reply_to_current\s*\]\]/gi,xn=/\[\[\s*reply_to\s*:\s*([^\]]+?)\s*\]\]/i;function Sn(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Cn(e,t){let n=e,r;bn.test(n)&&(r=Sn(t),n=n.replace(bn,``).trim());let i=n.match(xn)?.[1];return i&&(r=Sn(i),n=n.replace(xn,``).trim()),r?{content:n,replyTo:r}:{content:n}}function wn(e,t=e.id){if(e.role!==`assistant`)return{...e,parts:[...e.parts],metadata:e.metadata?{...e.metadata}:void 0};let n=e.parts.findIndex(e=>e.type===`text`),r=e.metadata?{...e.metadata}:void 0,i=Sn(r?.reply_to);if(n<0)return{...e,parts:[...e.parts],metadata:r};let a=e.parts[n];if(!a||a.type!==`text`)return{...e,parts:[...e.parts],metadata:r};let{content:o,replyTo:s}=Cn(a.text,t),c=s??i,l=e.parts.flatMap((e,t)=>t!==n||e.type!==`text`?[e]:o.length===0?[]:[{...e,text:o}]);return c?{...e,parts:l,metadata:{...r,reply_to:c}}:{...e,parts:l,metadata:r}}function Tn(e){return{...e,parts:[...e.parts],metadata:e.metadata?{...e.metadata}:void 0}}function En(e){return Tn(wn(e))}function Dn(e){let t=e.error?.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 On(e,t){return t.trim()?e.id.startsWith(`tool-`)?!0:e.parts.some(e=>e.type===`tool-invocation`):!1}function kn(e,t,n){for(let[r,i]of e)i===t&&e.set(r,n)}function An(e,t,n){for(let[r,i]of e)i===n&&(e.delete(r),t.delete(r))}function jn(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r.type===`tool-invocation`&&r.toolCallId===t)return r}return null}function Mn(e,t){return jn(e,t)?.toolName??null}function Nn(e,t){let n=[...e];for(let e=n.length-1;e>=0;--e){let r=n[e];if(r.type===`tool-invocation`&&r.toolCallId===t.toolCallId)return n[e]={...r,...t},n}return n.push(t),n}var Pn=`assistant`,Fn=class{messages=[];streamingMessage=null;error=null;activeRun=null;listeners=new Set;toolCallMessageIdByCallId=new Map;toolCallArgsRawByCallId=new Map;lastSettledRunId=null;snapshotCache=null;snapshotVersion=-1;stateVersion=0;getSnapshot=()=>{if(this.snapshotCache&&this.snapshotVersion===this.stateVersion)return this.snapshotCache;let e={messages:this.messages,streamingMessage:this.streamingMessage,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=>(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.lastSettledRunId=null,this.stateVersion+=1,this.notifyListeners())};hydrate=e=>{this.messages=e.messages.map(e=>En(e)),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.lastSettledRunId=null,this.stateVersion+=1,this.notifyListeners()};dispatch=e=>this.dispatchBatch([e]);dispatchBatch=async e=>{if(!e.length)return;let t=this.stateVersion;e.forEach(this.applyEvent),this.stateVersion!==t&&this.notifyListeners()};applyEvent=e=>{switch(e.type){case F.MessageSent:this.handleMessageSent(e.payload);break;case F.MessageAbort:this.handleMessageAbort(e.payload);break;case F.MessageTextStart:this.handleMessageTextStart(e.payload);break;case F.MessageTextDelta:this.handleMessageTextDelta(e.payload);break;case F.MessageTextEnd:this.handleMessageTextEnd(e.payload);break;case F.MessageReasoningStart:this.handleMessageReasoningStart(e.payload);break;case F.MessageReasoningDelta:this.handleMessageReasoningDelta(e.payload);break;case F.MessageReasoningEnd:this.handleMessageReasoningEnd(e.payload);break;case F.MessageToolCallStart:this.handleMessageToolCallStart(e.payload);break;case F.MessageToolCallArgs:this.handleMessageToolCallArgs(e.payload);break;case F.MessageToolCallArgsDelta:this.handleMessageToolCallArgsDelta(e.payload);break;case F.MessageToolCallEnd:this.handleMessageToolCallEnd(e.payload);break;case F.MessageToolCallResult:this.handleMessageToolCallResult(e.payload);break;case F.RunStarted:this.handleRunStarted(e.payload);break;case F.RunFinished:this.handleRunFinished(e.payload);break;case F.RunError:this.handleRunError(e.payload);break;case F.RunMetadata:this.handleRunMetadata(e.payload);break;case F.EndpointError:this.handleEndpointError(e.payload);break;default:break}};handleMessageSent=e=>{this.upsertMessage(e.message),this.setError(null)};handleMessageAbort=e=>{let t=e.messageId?.trim();if(this.clearActiveRun(),this.setError(null),this.streamingMessage&&(!t||this.streamingMessage.id===t)){let e=this.streamingMessage.id;this.upsertMessage({...this.streamingMessage,status:`final`}),this.replaceStreamingMessage(null),t?An(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,t):An(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,e)}};handleMessageTextStart=e=>{this.ensureStreamingMessage(e.sessionId,e.messageId,`streaming`),this.setError(null)};handleMessageTextDelta=e=>{if(!e.delta)return;let t=this.ensureStreamingMessage(e.sessionId,e.messageId,`streaming`),n=[...t.parts],r=n[n.length-1];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=>{this.streamingMessage?.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;let t=this.ensureStreamingMessage(e.sessionId,e.messageId,`streaming`),n=[...t.parts],r=n[n.length-1];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=>{this.streamingMessage?.id,e.messageId};handleMessageToolCallStart=e=>{let t=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId,e.messageId);this.toolCallArgsRawByCallId.set(e.toolCallId,``);let n=Nn(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=>{let t=`${this.toolCallArgsRawByCallId.get(e.toolCallId)??``}${e.delta}`;this.toolCallArgsRawByCallId.set(e.toolCallId,t),this.applyToolCallArgs(e.sessionId,e.toolCallId,t,e.messageId)};handleMessageToolCallEnd=e=>{let t=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId),n=this.toolCallArgsRawByCallId.get(e.toolCallId)??``,r=Nn(t.parts,{type:`tool-invocation`,toolCallId:e.toolCallId,toolName:Mn(t.parts,e.toolCallId)??`unknown`,state:`call`,args:n});this.replaceStreamingMessage({...t,parts:r,status:`streaming`})};handleMessageToolCallResult=e=>{if(!this.updateMessageContainingToolCall(e.toolCallId,(t,n)=>{let r={type:`tool-invocation`,toolCallId:e.toolCallId,toolName:n.toolName,state:`result`,args:n.args,result:e.content};return Nn(t.parts,r)})){let t=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId),n=Nn(t.parts,{type:`tool-invocation`,toolCallId:e.toolCallId,toolName:`unknown`,state:`result`,result:e.content});this.replaceStreamingMessage({...t,parts:n,status:`streaming`})}};handleRunStarted=e=>{this.isSettledRunId(e.runId)||(this.setError(null),this.activeRun={runId:e.runId??null,sessionId:e.sessionId},this.stateVersion+=1)};handleRunFinished=e=>{this.markRunAsSettled(e.runId??this.activeRun?.runId??null),this.settleStreamingMessage(`final`),this.setError(null),this.clearActiveRun()};handleRunError=e=>{this.markRunAsSettled(e.runId??this.activeRun?.runId??null),this.settleStreamingMessage(`error`),this.setError(Dn(e)),this.clearActiveRun()};handleRunMetadata=e=>{let t=e.metadata;if(t?.kind===`ready`){let e=t;if(this.isSettledRunId(e.runId))return;this.activeRun={runId:e.runId??this.activeRun?.runId??null,sessionId:e.sessionId??this.activeRun?.sessionId,abortDisabledReason:e.supportsAbort===!1?e.abortDisabledReason??`Unsupported`:null},this.stateVersion+=1}else t?.kind===`final`&&(this.markRunAsSettled(e.runId??this.activeRun?.runId??null),this.clearActiveRun())};handleEndpointError=e=>{if(e.code===`abort-error`){this.handleMessageAbort({sessionId:this.activeRun?.sessionId??this.streamingMessage?.sessionId??``,...this.streamingMessage?.id?{messageId:this.streamingMessage.id}:{}});return}this.settleStreamingMessage(`error`),this.clearActiveRun(),this.setError(e)};applyToolCallArgs=(e,t,n,r)=>{let i=this.resolveToolCallTargetMessage(e,t,r),a=Mn(i.parts,t)??`unknown`,o=Nn(i.parts,{type:`tool-invocation`,toolCallId:t,toolName:a,state:`partial-call`,args:n});this.replaceStreamingMessage({...i,parts:o,status:`streaming`})};ensureStreamingMessage=(e,t,n)=>{if(this.streamingMessage?.id===t){if(this.streamingMessage.status===n)return this.streamingMessage;let e={...this.streamingMessage,status:n};return this.replaceStreamingMessage(e),e}let r=this.messages.findIndex(e=>e.id===t);if(r>=0){let t=Tn(this.messages[r]),i=[...this.messages];i.splice(r,1),this.messages=i,this.stateVersion+=1;let a={...t,sessionId:e,status:n};return this.replaceStreamingMessage(a),a}let i=this.streamingMessage;if(i&&i.id!==t&&i.sessionId===e&&On(i,t)){let r={...i,id:t,sessionId:e,status:n};return kn(this.toolCallMessageIdByCallId,i.id,t),this.replaceStreamingMessage(r),r}let a={id:t,sessionId:e,role:Pn,status:n,parts:[],timestamp:new Date().toISOString()};return this.replaceStreamingMessage(a),a};resolveToolCallTargetMessage=(e,t,n)=>{let r=n?.trim()||this.toolCallMessageIdByCallId.get(t)||this.streamingMessage?.id||`tool-${t}`;return this.toolCallMessageIdByCallId.set(t,r),this.ensureStreamingMessage(e,r,`streaming`)};updateMessageContainingToolCall=(e,t)=>{if(this.streamingMessage){let n=jn(this.streamingMessage.parts,e);if(n){let e=t(this.streamingMessage,n);return this.replaceStreamingMessage({...this.streamingMessage,parts:e}),!0}}for(let n=this.messages.length-1;n>=0;--n){let r=this.messages[n],i=jn(r.parts,e);if(!i)continue;let a=[...this.messages];return a[n]={...r,parts:t(r,i)},this.messages=a,this.stateVersion+=1,!0}return!1};upsertMessage=e=>{let t=En(e),n=this.messages.findIndex(e=>e.id===t.id);if(n<0){this.messages=[...this.messages,t],this.stateVersion+=1;return}let r=[...this.messages];r[n]=t,this.messages=r,this.stateVersion+=1};replaceStreamingMessage=e=>{!e&&!this.streamingMessage||(this.streamingMessage=e?En(e):null,this.stateVersion+=1)};setError=e=>{this.error?.code===e?.code&&this.error?.message===e?.message&&this.error?.details===e?.details&&this.error?.cause===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)};isSettledRunId=e=>!!e?.trim()&&e===this.lastSettledRunId;markRunAsSettled=e=>{this.lastSettledRunId=e?.trim()||null};settleStreamingMessage=e=>{if(!this.streamingMessage)return;let t={...this.streamingMessage,status:e};this.upsertMessage(t),this.replaceStreamingMessage(null),An(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,t.id)};notifyListeners=()=>{let e=this.getSnapshot();for(let t of this.listeners)t(e)}},In=16,Ln=class{constructor(e){this.dispatchBatch=e,this.queue=[],this.flushTimerId=null,this.isFlushing=!1,this.isDisposed=!1,this.enqueue=e=>{this.isDisposed||(this.queue.push(e),this.scheduleFlush())},this.dispose=()=>{this.isDisposed=!0,this.flushTimerId!==null&&(window.clearTimeout(this.flushTimerId),this.flushTimerId=null),this.queue.length=0},this.scheduleFlush=()=>{this.flushTimerId!==null||this.isFlushing||this.queue.length===0||(this.flushTimerId=window.setTimeout(()=>{this.flushTimerId=null,this.flush()},In))},this.flush=async()=>{if(!(this.isDisposed||this.isFlushing||this.queue.length===0)){this.isFlushing=!0;try{for(;this.queue.length>0;){let e=this.queue.splice(0);await this.dispatchBatch(e)}}finally{this.isFlushing=!1,this.scheduleFlush()}}}}};function Rn(e,t){let n=e.dispatchBatch;return typeof n==`function`?n.call(e,t):t.reduce((t,n)=>t.then(()=>e.dispatch(n)),Promise.resolve())}function zn(e,t){let n=`payload`in e?e.payload:null;return!n||typeof n!=`object`||!(`sessionId`in n)||typeof n.sessionId!=`string`?!0:n.sessionId===t}function Bn(e){return e.parts.some(e=>e.type===`text`||e.type===`rich-text`||e.type===`reasoning`?e.text.trim().length>0:!0)}function Vn(e,t){if(typeof e==`string`){let 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 Bn(e.message)?{...e,sessionId:e.sessionId,message:{...e.message,sessionId:e.message.sessionId||e.sessionId}}:null}function Hn(e){let t=(0,P.useRef)();return(!t.current||t.current.sessionId!==e)&&(t.current={sessionId:e,manager:new Fn}),t.current.manager}function Un({sessionId:e,client:t,manager:n}){let r=(0,P.useSyncExternalStore)(e=>n.subscribe(()=>e()),()=>n.getSnapshot(),()=>n.getSnapshot()),[i,a]=(0,P.useState)(!1);(0,P.useEffect)(()=>{a(!1)},[e]),(0,P.useEffect)(()=>{let r=new Ln(e=>Rn(n,e)),i=t.subscribe(t=>{zn(t,e)&&r.enqueue(t)});return()=>{i(),r.dispose(),t.stop()}},[t,n,e]);let o=r.streamingMessage?[...r.messages,r.streamingMessage]:r.messages,s=r.activeRun?.runId??null,c=!!r.activeRun;return{snapshot:r,visibleMessages:o,activeRunId:s,isRunning:c,isSending:i,send:async r=>{if(i||c)return;let o=Vn(r,e);if(o){a(!0),await n.dispatch({type:F.MessageSent,payload:{sessionId:e,message:o.message,metadata:o.metadata}});try{await t.send(o)}finally{a(!1)}}},abort:async()=>{r.activeRun&&await t.abort({sessionId:e})},streamRun:async()=>{await t.stop(),await t.stream({sessionId:e})}}}function Wn(e){return e instanceof Error?e:Error(String(e))}function Gn(e){return e.isHydrating||e.hydratedSessionId!==e.sessionId}function Kn({sessionId:e,client:t,loadSeed:n}){let r=Hn(e),i=Un({sessionId:e,client:t,manager:r}),[a,o]=(0,P.useState)(!0),[s,c]=(0,P.useState)(null),[l,u]=(0,P.useState)(null),d=(0,P.useRef)({requestId:0,controller:null}),f=(0,P.useCallback)(async()=>{d.current.controller?.abort();let i=new AbortController,a=d.current.requestId+1;d.current={requestId:a,controller:i},await t.stop(),r.reset(),c(null),o(!0);try{let s=await n(e,i.signal);if(i.signal.aborted||d.current.requestId!==a)return;r.hydrate({sessionId:e,messages:s.messages,activeRun:s.status===`running`?{runId:null,sessionId:e,abortDisabledReason:null}:null}),c(null),u(e),o(!1),t.stream({sessionId:e}).catch(e=>{d.current.requestId===a&&c(Wn(e))})}catch(t){if(i.signal.aborted||d.current.requestId!==a)return;c(Wn(t)),u(e),o(!1)}finally{d.current.controller===i&&(d.current.controller=null)}},[t,n,r,e]);return(0,P.useEffect)(()=>(f(),()=>{d.current.controller?.abort(),d.current.controller=null}),[f]),{...i,isHydrating:Gn({sessionId:e,hydratedSessionId:l,isHydrating:a}),hydrateError:s}}var qn=200*1024*1024,Jn=`application/octet-stream`;function Yn(e){let t=e.type.trim().toLowerCase();return t.length>0?t:Jn}function Xn(e,t){let n=t.acceptedMimeTypes&&t.acceptedMimeTypes.length>0?new Set(t.acceptedMimeTypes.map(e=>e.trim().toLowerCase())):null,r=t.maxBytes??209715200,i=Yn(e);return n&&!n.has(i)?{ok:!1,rejected:{fileName:e.name,mimeType:i,sizeBytes:e.size,reason:`unsupported-type`}}:e.size>r?{ok:!1,rejected:{fileName:e.name,mimeType:i,sizeBytes:e.size,reason:`too-large`}}:{ok:!0,mimeType:i}}function Zn(e){let t=e.parts&&e.parts.length>0?e.parts.map(e=>structuredClone(e)):[...e.text?.trim()??``?[{type:`text`,text:e.text.trim()}]:[],...(e.attachments??[]).map(e=>({type:`file`,name:e.name,mimeType:e.mimeType,...e.assetUri?.trim()?{assetUri:e.assetUri.trim()}:{},...e.url?.trim()?{url:e.url.trim()}:{},...e.contentBase64?.trim()?{contentBase64:e.contentBase64.trim()}:{},sizeBytes:e.sizeBytes}))];if(t.length===0)return null;let n=e.timestamp??new Date().toISOString(),r=e.messageId??`user-${Date.now().toString(36)}`;return{sessionId:e.sessionId,message:{id:r,sessionId:e.sessionId,role:`user`,status:`final`,parts:t,timestamp:n,...e.metadata?{metadata:e.metadata}:{}},...e.metadata?{metadata:e.metadata}:{}}}async function Qn(e,t){let n=[],r=[];for(let i of e){let e=Xn(i,t);if(!e.ok){r.push(e.rejected);continue}n.push(i)}if(n.length===0)return{attachments:[],rejected:r};try{return{attachments:await t.uploadBatch(n),rejected:r}}catch{return r.push(...n.map(e=>({fileName:e.name,mimeType:Yn(e),sizeBytes:e.size,reason:`read-failed`}))),{attachments:[],rejected:r}}}var I=l(),$n={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 er({status:e,className:t}){let n=$n[e],r=o(e===`connected`?`connected`:e===`disconnected`?`disconnected`:`connecting`);return(0,I.jsx)(Ee,{delayDuration:250,children:(0,I.jsxs)(Oe,{children:[(0,I.jsx)(we,{asChild:!0,children:(0,I.jsx)(`span`,{role:`status`,"aria-label":r,className:u(`inline-flex h-5 w-5 items-center justify-center`,t),children:e===`connecting`?(0,I.jsx)(Ce,{className:u(`h-3 w-3 animate-spin`,n.dotClass)}):(0,I.jsx)(`span`,{className:u(e===`connected`?`h-2 w-2 rounded-full`:``,n.dotClass)})})}),(0,I.jsx)(Ae,{side:`bottom`,className:`text-xs`,children:r})]})})}var tr=[[`bg-amber-100`,`text-amber-700`],[`bg-emerald-100`,`text-emerald-700`],[`bg-blue-100`,`text-blue-700`],[`bg-rose-100`,`text-rose-700`],[`bg-cyan-100`,`text-cyan-700`],[`bg-violet-100`,`text-violet-700`]];function nr(e){let t=0;for(let n=0;n<e.length;n+=1)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t)}function rr(e){let t=e.trim();return t?t.slice(0,1).toUpperCase():`A`}function ir({agentId:e,displayName:t,avatarUrl:n,className:r}){let i=t?.trim()||e,[a,o]=tr[nr(e)%tr.length]??tr[0];return n?.trim()?(0,I.jsx)(`img`,{src:n,alt:t?.trim()||e,className:u(`rounded-full object-cover`,r)}):(0,I.jsx)(`div`,{className:u(`rounded-full flex items-center justify-center font-semibold`,a,o,r),"aria-label":t?.trim()||e,children:rr(i)})}var ar={wx:`weixin`,lark:`feishu`},or={heartbeat:{icon:`heartbeat`},cron:{icon:`cron`}},sr={codex:`chatSessionTypeCodex`,claude:`chatSessionTypeClaude`};function cr(e){return e?.trim().toLowerCase()??``}function lr(e){return e.split(/[-_]+/g).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function ur(e,t){let n=cr(e);if(!n||n===`native`)return null;let r=t.find(e=>cr(e.value)===n);return r?.label.trim()?r.label.trim():lr(n)}function dr(e){let t=cr(e);if(!t)return null;let n=ar[t]??t;return Se(n)?n:null}function fr(e,t){let n=dr(e.channel??``);if(n)return{icon:{kind:`channel-logo`,channel:n},label:null};let r=or[cr(e.type)];if(r)return{icon:{kind:`symbol`,icon:r.icon},label:null};let i=sr[cr(e.sessionType)];return i?{icon:null,label:o(i)}:{icon:null,label:ur(e.sessionType,t)}}function pr({icon:e,className:t}){return e.kind===`channel-logo`?(0,I.jsx)(mr,{channel:e.channel,className:t}):e.icon===`heartbeat`?(0,I.jsx)(cn,{className:u(`h-3.5 w-3.5`,t)}):(0,I.jsx)(lt,{className:u(`h-3.5 w-3.5`,t)})}function mr({channel:e,className:t}){return(0,I.jsx)(Gt,{name:e,src:Se(e),className:u(`h-4 w-4 rounded-[4px] border border-gray-200/80 bg-white`,t),imgClassName:`h-3 w-3 object-contain`,fallback:(0,I.jsx)(vt,{className:`h-3 w-3 text-gray-500`})})}function hr(e){let{session:t,active:n,runStatus:r,context:i,title:a,agentId:s,agentLabel:l,agentAvatarUrl:d,isEditing:f,draftLabel:p,isSaving:h,onSelect:g,onStartEditing:_,onDraftLabelChange:v,onSave:y,onCancel:b}=e,x=n?`text-gray-700`:`text-gray-500`;return(0,I.jsx)(`div`,{className:u(`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:f?(0,I.jsxs)(`div`,{className:`space-y-2`,children:[(0,I.jsx)(ct,{value:p,onChange:e=>v(e.target.value),onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),y()):e.key===`Escape`&&(e.preventDefault(),b())},placeholder:o(`sessionsLabelPlaceholder`),className:`h-8 rounded-lg border-gray-300 bg-white text-xs`,autoFocus:!0,disabled:h}),(0,I.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,I.jsx)(`div`,{className:`min-w-0 text-[11px] text-gray-400 truncate`,children:t.key}),(0,I.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,I.jsx)(m,{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 y(),disabled:h,"aria-label":o(`save`),children:(0,I.jsx)(re,{className:`h-3.5 w-3.5`})}),(0,I.jsx)(m,{type:`button`,size:`icon`,variant:`ghost`,className:`h-7 w-7 rounded-lg text-gray-500 hover:bg-white hover:text-gray-900`,onClick:b,disabled:h,"aria-label":o(`cancel`),children:(0,I.jsx)(Ye,{className:`h-3.5 w-3.5`})})]})]})]}):(0,I.jsxs)(`div`,{className:`group/session relative`,children:[(0,I.jsxs)(`button`,{type:`button`,onClick:g,className:`w-full text-left`,children:[(0,I.jsxs)(`div`,{className:`grid grid-cols-[minmax(0,1fr)_0.875rem] items-center gap-1.5 pr-8`,children:[(0,I.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5`,children:[s?(0,I.jsx)(ir,{agentId:s,displayName:l,avatarUrl:d,className:`h-5 w-5 shrink-0`}):null,(0,I.jsx)(`span`,{className:`truncate font-medium`,children:a}),i.label?(0,I.jsx)(`span`,{className:u(`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:i.label}):null,i.icon?(0,I.jsx)(`span`,{className:`inline-flex h-[1.125rem] w-[1.125rem] shrink-0 items-center justify-center`,children:(0,I.jsx)(pr,{icon:i.icon,className:x})}):null]}),(0,I.jsx)(`span`,{className:`inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center`,children:r?(0,I.jsx)(Be,{status:r}):null})]}),(0,I.jsxs)(`div`,{className:`mt-0.5 text-[11px] text-gray-400 truncate`,children:[l?.trim()?`${l} · `:``,t.messageCount,` · `,c(t.updatedAt)]})]}),(0,I.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),_()},className:u(`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":o(`edit`),children:(0,I.jsx)(pn,{className:`h-3.5 w-3.5`})})]})})}function gr(){let e=_();return async t=>{try{nt(e,await Qe(t.sessionKey,t.patch)),p.success(t.successMessage??o(`configSavedApplied`))}catch(e){throw p.error(o(`configSaveFailed`)+`: `+(e instanceof Error?e.message:String(e))),e}}}function _r(){let e=gr();return async t=>{await e({sessionKey:t.sessionKey,patch:{label:t.label},successMessage:o(`configSavedApplied`)})}}var vr={selectedSessionKey:null,selectedAgentId:`main`,query:``},L=S(e=>({snapshot:vr,setSnapshot:t=>e(e=>({snapshot:{...e.snapshot,...t}}))}));function yr(e,t){return e.filter(e=>Ve(e,t))}function br(e){return e.isChildSession?e.isPromotedChildSession===!0:!0}function xr(e={}){let t=L(e=>e.snapshot.query),n=ft({limit:e.limit??200}),r=(0,P.useMemo)(()=>{let e=n.data?.sessions??[],r=yr(ze(e).filter(br),t),i=new Map(e.map(e=>[e.sessionId,e]));return r.map(e=>({session:e,runStatus:i.get(e.key)?.status===`running`?`running`:void 0}))},[t,n.data?.sessions]);return{isLoading:n.isLoading,items:r}}var Sr=(0,P.createContext)(null);function Cr({presenter:e,children:t}){return(0,I.jsx)(Sr.Provider,{value:e,children:t})}function wr(){let e=(0,P.useContext)(Sr);if(!e)throw Error(`usePresenter must be used inside ChatPresenterProvider`);return e}var Tr=e=>`[data-item-index="${e}"]`;function Er(e){let t=e.getItemSelector??Tr;(0,P.useEffect)(()=>{if(!e.isEnabled||e.itemCount===0)return;let n=e.containerRef.current;n&&n.querySelector(t(e.activeIndex))?.scrollIntoView({block:`nearest`,inline:`nearest`})},[t,e.activeIndex,e.containerRef,e.isEnabled,e.itemCount])}function Dr(){let e=(0,P.useRef)(null),[t,n]=(0,P.useState)(null);return(0,P.useEffect)(()=>{let t=e.current;if(!t||typeof ResizeObserver>`u`)return;let r=()=>{n(t.getBoundingClientRect().width)};r();let i=new ResizeObserver(()=>r());return i.observe(t),()=>i.disconnect()},[]),{elementRef:e,width:t}}function R(...e){return n(r(e))}var Or=P.forwardRef(({className:e,type:t,...n},r)=>(0,I.jsx)(`input`,{type:t,className:R(`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}));Or.displayName=`ChatInput`;var kr=Ut,Ar=Rt,jr=zt,Mr=P.forwardRef(({className:e,sideOffset:t=8,align:n=`start`,...r},i)=>(0,I.jsx)(Vt,{children:(0,I.jsx)(Lt,{ref:i,sideOffset:t,align:n,className:R(`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})}));Mr.displayName=Lt.displayName;var Nr=M,Pr=le,Fr=pe,Ir=P.forwardRef(({className:e,children:t,...n},r)=>(0,I.jsxs)(fe,{ref:r,className:R(`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,(0,I.jsx)(ee,{asChild:!0,children:(0,I.jsx)(T,{className:`h-4 w-4 opacity-50`})})]}));Ir.displayName=fe.displayName;var Lr=P.forwardRef(({className:e,...t},n)=>(0,I.jsx)(A,{ref:n,className:R(`flex cursor-default items-center justify-center py-1`,e),...t,children:(0,I.jsx)(w,{className:`h-4 w-4`})}));Lr.displayName=A.displayName;var Rr=P.forwardRef(({className:e,...t},n)=>(0,I.jsx)(j,{ref:n,className:R(`flex cursor-default items-center justify-center py-1`,e),...t,children:(0,I.jsx)(T,{className:`h-4 w-4`})}));Rr.displayName=j.displayName;var zr=P.forwardRef(({className:e,children:t,position:n=`popper`,...r},i)=>(0,I.jsx)(se,{children:(0,I.jsxs)(oe,{ref:i,className:R(`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:[(0,I.jsx)(Lr,{}),(0,I.jsx)(O,{className:R(`p-1`,n===`popper`&&`h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]`),children:t}),(0,I.jsx)(Rr,{})]})}));zr.displayName=oe.displayName;var Br=P.forwardRef(({className:e,...t},n)=>(0,I.jsx)(te,{ref:n,className:R(`px-2 py-1 text-[11px] font-semibold uppercase tracking-[0.08em] text-gray-500`,e),...t}));Br.displayName=te.displayName;var Vr=P.forwardRef(({className:e,children:t,...n},r)=>(0,I.jsxs)(ie,{ref:r,className:R(`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:[(0,I.jsx)(`span`,{className:`absolute right-2 flex h-3.5 w-3.5 items-center justify-center`,children:(0,I.jsx)(de,{children:(0,I.jsx)(re,{className:`h-4 w-4`})})}),(0,I.jsx)(k,{children:t})]}));Vr.displayName=ie.displayName;var Hr=P.forwardRef(({className:e,...t},n)=>(0,I.jsx)(E,{ref:n,className:R(`-mx-1 my-1 h-px bg-gray-100`,e),...t}));Hr.displayName=E.displayName;var Ur=Te,Wr=De,Gr=Ne,Kr=P.forwardRef(({className:e,sideOffset:t=4,...n},r)=>(0,I.jsx)(je,{children:(0,I.jsx)(ke,{ref:r,sideOffset:t,className:R(`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})}));Kr.displayName=ke.displayName;var qr={Popover:kr,PopoverAnchor:jr,PopoverContent:Mr,PopoverTrigger:Ar,Input:Or,Select:Nr,SelectContent:zr,SelectGroup:Pr,SelectItem:Vr,SelectLabel:Br,SelectSeparator:Hr,SelectTrigger:Ir,SelectValue:Fr,Tooltip:Wr,TooltipContent:Kr,TooltipProvider:Ur,TooltipTrigger:Gr},Jr=680,Yr=.82,Xr=560;function Zr(e){let{Popover:t,PopoverAnchor:n,PopoverContent:r}=qr,{elementRef:i,width:a}=Dr(),o=(0,P.useRef)(null),{isOpen:s,isLoading:c,items:l,activeIndex:u,activeItem:d,texts:f,onSelectItem:p,onOpenChange:m,onSetActiveIndex:h}=e,g=(0,P.useMemo)(()=>{if(a)return Math.min(a>Xr?a*Yr:a,Jr)},[a]);return Er({containerRef:o,activeIndex:u,itemCount:l.length,isEnabled:s&&!c,getItemSelector:e=>`[data-slash-index="${e}"]`}),(0,I.jsxs)(t,{open:s,onOpenChange:m,children:[(0,I.jsx)(n,{asChild:!0,children:(0,I.jsx)(`div`,{ref:i,className:`pointer-events-none absolute bottom-full left-3 right-3 h-0`})}),(0,I.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:e=>e.preventDefault(),style:g?{width:`${g}px`}:void 0,children:(0,I.jsxs)(`div`,{className:`grid min-h-[240px] grid-cols-[minmax(220px,300px)_minmax(0,1fr)]`,children:[(0,I.jsx)(`div`,{ref:o,role:`listbox`,"aria-label":f.slashSectionLabel,className:`custom-scrollbar max-h-[320px] overflow-y-auto border-r border-gray-200 p-2.5`,children:c?(0,I.jsx)(`div`,{className:`p-2 text-xs text-gray-500`,children:f.slashLoadingLabel}):(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(`div`,{className:`mb-2 px-2 text-[11px] font-semibold uppercase tracking-wide text-gray-500`,children:f.slashSectionLabel}),l.length===0?(0,I.jsx)(`div`,{className:`px-2 text-xs text-gray-400`,children:f.slashEmptyLabel}):(0,I.jsx)(`div`,{className:`space-y-1`,children:l.map((e,t)=>{let n=t===u;return(0,I.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":n,"data-slash-index":t,onMouseEnter:()=>h(t),onClick:()=>p(e),className:`flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left transition ${n?`bg-gray-100 text-gray-900`:`text-gray-700 hover:bg-gray-50`}`,children:[(0,I.jsx)(`span`,{className:`truncate text-xs font-semibold`,children:e.title}),(0,I.jsx)(`span`,{className:`truncate text-xs text-gray-500`,children:e.subtitle})]},e.key)})})]})}),(0,I.jsx)(`div`,{className:`min-w-0 p-2.5`,children:d?(0,I.jsxs)(`div`,{className:`space-y-3`,children:[(0,I.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,I.jsx)(`span`,{className:`inline-flex rounded-full bg-primary/10 px-2 py-0.5 text-[11px] font-semibold text-primary`,children:d.subtitle}),(0,I.jsx)(`span`,{className:`text-sm font-semibold text-gray-900`,children:d.title})]}),(0,I.jsx)(`p`,{className:`text-xs leading-5 text-gray-600`,children:d.description}),(0,I.jsx)(`div`,{className:`space-y-1`,children:d.detailLines.map(e=>(0,I.jsx)(`div`,{className:`min-w-0 break-all rounded-md bg-gray-50 px-2 py-1 text-[11px] leading-5 text-gray-600`,children:e},e))}),(0,I.jsx)(`div`,{className:`pt-1 text-[11px] text-gray-500`,children:f.slashSkillHintLabel})]}):(0,I.jsx)(`div`,{className:`text-xs text-gray-500`,children:f.slashHintLabel})})]})})]})}var Qr=g(`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`}}),$r=P.forwardRef(({className:e,variant:t,size:n,...r},i)=>(0,I.jsx)(`button`,{className:R(Qr({variant:t,size:n,className:e})),ref:i,...r}));$r.displayName=`ChatButton`;function ei(){return(0,I.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 ti(e){let{Tooltip:t,TooltipContent:n,TooltipProvider:r,TooltipTrigger:i}=qr;return(0,I.jsxs)(`div`,{className:`flex flex-col items-end gap-1`,children:[e.sendError?.trim()?(0,I.jsx)(`div`,{className:`max-w-[420px] text-right text-[11px] text-red-600`,children:e.sendError}):null,(0,I.jsx)(`div`,{className:`flex items-center gap-2`,children:e.isSending?e.canStopGeneration?(0,I.jsx)($r,{size:`icon`,variant:`outline`,className:`h-8 w-8 rounded-full`,"aria-label":e.stopButtonLabel,onClick:()=>void e.onStop(),disabled:e.stopDisabled,children:(0,I.jsx)(ei,{})}):(0,I.jsx)(r,{children:(0,I.jsxs)(t,{children:[(0,I.jsx)(i,{asChild:!0,children:(0,I.jsx)(`span`,{children:(0,I.jsx)($r,{size:`icon`,variant:`outline`,className:`h-8 w-8 rounded-full`,"aria-label":e.stopButtonLabel,disabled:!0,children:(0,I.jsx)(ei,{})})})}),(0,I.jsx)(n,{side:`top`,children:(0,I.jsx)(`p`,{className:`text-xs`,children:e.stopHint})})]})}):(0,I.jsx)($r,{size:`icon`,className:`h-8 w-8 rounded-full`,"aria-label":e.sendButtonLabel,onClick:()=>void e.onSend(),disabled:e.sendDisabled,children:(0,I.jsx)(Zt,{className:`h-5 w-5`})})})]})}function ni(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>[e.label,e.key,e.description].filter(e=>typeof e==`string`&&e.trim().length>0).join(` `).toLowerCase().includes(n)):e}function ri(e){let{Input:t,Popover:n,PopoverContent:r,PopoverTrigger:i}=qr,{picker:a}=e,o=(0,P.useRef)(null),s=(0,P.useId)(),[c,l]=(0,P.useState)(``),[u,d]=(0,P.useState)(0),f=(0,P.useMemo)(()=>new Set(a.selectedKeys),[a.selectedKeys]),p=a.selectedKeys.length,m=c.trim().length>0,h=(0,P.useMemo)(()=>{if(m)return null;let e=a.groups?.filter(e=>e.options.length>0)??[];return e.length>0?e:null},[m,a.groups]),g=(0,P.useMemo)(()=>h?h.flatMap(e=>e.options):ni(a.options,c),[h,a.options,c]);(0,P.useEffect)(()=>{d(0)},[c]),(0,P.useEffect)(()=>{d(e=>g.length===0?0:Math.min(e,g.length-1))},[g.length]),Er({containerRef:o,activeIndex:u,itemCount:g.length,isEnabled:g.length>0,getItemSelector:e=>`[data-skill-index="${e}"]`});let _=e=>{if(f.has(e)){a.onSelectedKeysChange(a.selectedKeys.filter(t=>t!==e));return}a.onSelectedKeysChange([...a.selectedKeys,e])},v=e=>{if(g.length!==0){if(e.key===`ArrowDown`){e.preventDefault(),d(e=>Math.min(e+1,g.length-1));return}if(e.key===`ArrowUp`){e.preventDefault(),d(e=>Math.max(e-1,0));return}if(e.key===`Enter`){e.preventDefault();let t=g[u];t&&_(t.key)}}};return(0,I.jsxs)(n,{children:[(0,I.jsx)(i,{asChild:!0,children:(0,I.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:[(0,I.jsx)(yt,{className:`h-4 w-4`}),(0,I.jsx)(`span`,{children:a.title}),p>0?(0,I.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:p}):null]})}),(0,I.jsxs)(r,{side:`top`,align:`start`,className:`w-[360px] p-0`,children:[(0,I.jsxs)(`div`,{className:`space-y-2 border-b border-gray-100 px-4 py-3`,children:[(0,I.jsx)(`div`,{className:`text-sm font-semibold text-gray-900`,children:a.title}),(0,I.jsxs)(`div`,{className:`relative`,children:[(0,I.jsx)(qe,{className:`pointer-events-none absolute left-3 top-2.5 h-3.5 w-3.5 text-gray-400`}),(0,I.jsx)(t,{value:c,onChange:e=>l(e.target.value),onKeyDown:v,placeholder:a.searchPlaceholder,role:`combobox`,"aria-controls":s,"aria-expanded":`true`,"aria-autocomplete":`list`,"aria-activedescendant":g[u]?`${s}-option-${u}`:void 0,className:`h-8 rounded-lg pl-8 text-xs`})]})]}),(0,I.jsx)(`div`,{ref:o,id:s,role:`listbox`,"aria-multiselectable":`true`,className:`custom-scrollbar max-h-[320px] overflow-y-auto`,children:a.isLoading?(0,I.jsx)(`div`,{className:`p-4 text-xs text-gray-500`,children:a.loadingLabel}):g.length===0?(0,I.jsx)(`div`,{className:`p-4 text-center text-xs text-gray-500`,children:a.emptyLabel}):(0,I.jsx)(`div`,{className:`py-1`,children:(()=>{let e=h??[{key:`all-skills`,options:g}],t=0;return e.map(e=>(0,I.jsxs)(`div`,{children:[e.label?(0,I.jsx)(`div`,{className:`px-4 pb-1 pt-2 text-[11px] font-semibold uppercase tracking-wide text-gray-500`,children:e.label}):null,e.options.map(e=>{let n=t;t+=1;let r=f.has(e.key),i=n===u;return(0,I.jsxs)(`button`,{type:`button`,id:`${s}-option-${n}`,role:`option`,"aria-selected":r,"data-skill-index":n,onClick:()=>_(e.key),onMouseEnter:()=>d(n),className:`flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors ${i?`bg-gray-50`:`hover:bg-gray-50`}`,children:[(0,I.jsx)(`div`,{className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-gray-100 text-gray-500`,children:(0,I.jsx)(gn,{className:`h-4 w-4`})}),(0,I.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,I.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,I.jsx)(`span`,{className:`truncate text-sm text-gray-900`,children:e.label}),e.badgeLabel?(0,I.jsx)(`span`,{className:`shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary`,children:e.badgeLabel}):null]}),(0,I.jsx)(`div`,{className:`mt-0.5 truncate text-xs text-gray-500`,children:e.description||e.key})]}),(0,I.jsx)(`div`,{className:`ml-3 shrink-0`,children:(0,I.jsx)(`span`,{className:r?`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:r?(0,I.jsx)(re,{className:`h-3 w-3`}):null})})]},e.key)})]},e.key))})()})}),a.manageHref&&a.manageLabel?(0,I.jsx)(`div`,{className:`border-t border-gray-100 px-4 py-2.5`,children:(0,I.jsxs)(`a`,{href:a.manageHref,className:`inline-flex items-center gap-1.5 text-xs font-medium text-primary transition-colors hover:text-primary/80`,children:[a.manageLabel,(0,I.jsx)(ge,{className:`h-3 w-3`})]})}):null]})]})}function ii({icon:e}){return e===`sparkles`?(0,I.jsx)(mt,{className:`h-3.5 w-3.5 shrink-0 text-primary`}):e===`brain`?(0,I.jsx)(Qt,{className:`h-3.5 w-3.5 shrink-0 text-gray-500`}):null}function ai({icon:e}){return e===`paperclip`?(0,I.jsx)(fn,{className:`h-4 w-4`}):(0,I.jsx)(ii,{icon:e})}function oi(e){return e===`model`?`min-w-[220px]`:e===`session-type`?`min-w-[140px]`:e===`thinking`?`min-w-[150px]`:``}function si(e){return e===`model`?`w-[320px]`:e===`session-type`?`w-[220px]`:e===`thinking`?`w-[180px]`:``}function ci({item:e}){let{Select:t,SelectContent:n,SelectGroup:r,SelectItem:i,SelectLabel:a,SelectSeparator:o,SelectTrigger:s,SelectValue:c}=qr,l=e.groups?.filter(e=>e.options.length>0)??(e.options.length>0?[{key:`${e.key}-default`,options:e.options}]:[]),u=l.some(e=>e.options.length>0);return(0,I.jsxs)(t,{value:e.value,onValueChange:e.onValueChange,disabled:e.disabled,children:[(0,I.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 ${oi(e.key)}`,children:e.selectedLabel?(0,I.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 text-left`,children:[(0,I.jsx)(ii,{icon:e.icon}),(0,I.jsx)(`span`,{className:`truncate text-xs font-semibold text-gray-700`,children:e.selectedLabel})]}):e.loading?(0,I.jsx)(`div`,{className:`h-3 w-24 animate-pulse rounded bg-gray-200`}):(0,I.jsx)(c,{placeholder:e.placeholder})}),(0,I.jsxs)(n,{className:si(e.key),children:[u?null:e.loading?(0,I.jsxs)(`div`,{className:`space-y-2 px-3 py-2`,children:[(0,I.jsx)(`div`,{className:`h-3 w-36 animate-pulse rounded bg-gray-200`}),(0,I.jsx)(`div`,{className:`h-3 w-28 animate-pulse rounded bg-gray-200`}),(0,I.jsx)(`div`,{className:`h-3 w-32 animate-pulse rounded bg-gray-200`})]}):e.emptyLabel?(0,I.jsx)(`div`,{className:`px-3 py-2 text-xs text-gray-500`,children:e.emptyLabel}):null,l.map((e,t)=>(0,I.jsxs)(`div`,{children:[t>0?(0,I.jsx)(o,{}):null,(0,I.jsxs)(r,{children:[e.label?(0,I.jsx)(a,{children:e.label}):null,e.options.map(e=>(0,I.jsx)(i,{value:e.value,className:`py-2`,children:e.description?(0,I.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-0.5`,children:[(0,I.jsx)(`span`,{className:`truncate text-xs font-semibold text-gray-800`,children:e.label}),(0,I.jsx)(`span`,{className:`truncate text-[11px] text-gray-500`,children:e.description})]}):(0,I.jsx)(`span`,{className:`truncate text-xs font-semibold text-gray-800`,children:e.label})},e.value))]})]},e.key))]})]})}function li(e){let{Tooltip:t,TooltipContent:n,TooltipProvider:r,TooltipTrigger:i}=qr;return(0,I.jsxs)(`div`,{className:`flex items-center justify-between px-3 pb-3`,children:[(0,I.jsxs)(`div`,{className:`flex items-center gap-1`,children:[e.skillPicker?(0,I.jsx)(ri,{picker:e.skillPicker}):null,e.selects.map(e=>(0,I.jsx)(ci,{item:e},e.key)),e.accessories?.map(e=>{let a=(0,I.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 ${e.iconOnly?`h-8 w-8 justify-center px-0`:`gap-1.5 px-3`}`,onClick:e.onClick,disabled:e.disabled,"aria-label":e.label,children:[(0,I.jsx)(ai,{icon:e.icon}),e.iconOnly?null:(0,I.jsx)(`span`,{children:e.label})]});return e.tooltip?(0,I.jsx)(r,{children:(0,I.jsxs)(t,{children:[(0,I.jsx)(i,{asChild:!0,children:e.disabled?(0,I.jsx)(`span`,{className:`inline-flex`,children:a}):a}),(0,I.jsx)(n,{side:`top`,children:(0,I.jsx)(`p`,{className:`text-xs`,children:e.tooltip})})]})},e.key):(0,I.jsx)(`div`,{children:a},e.key)})]}),(0,I.jsx)(ti,{...e.actions})]})}function ui(){return`composer-${Math.random().toString(36).slice(2,10)}`}function di(e=``){return{id:ui(),type:`text`,text:e}}function fi(e){return{id:ui(),type:`token`,tokenKind:e.tokenKind,tokenKey:e.tokenKey,label:e.label}}function pi(e){return e.type===`text`?e.text.length:1}function mi(){return[di(``)]}function hi(e){return[di(e)]}function gi(e){let t=[];for(let n of e){if(n.type===`text`){if(n.text.length===0)continue;let e=t[t.length-1];if(e?.type===`text`){t[t.length-1]={...e,text:e.text+n.text};continue}}t.push(n)}return t.length===0?mi():t}function _i(e){return e.map(e=>e.type===`text`?e.text:``).join(``)}function vi(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function yi(e,t){let n=[],r=new Set;for(let i of e)i.type!==`token`||i.tokenKind!==t||r.has(i.tokenKey)||(r.add(i.tokenKey),n.push(i.tokenKey));return n}function bi(e,t,n,r){let i=Math.max(0,n-t),a=Math.max(0,t+e.text.length-r),o=[];return i>0&&o.push({...e,text:e.text.slice(0,i)}),a>0&&o.push({...e,text:e.text.slice(e.text.length-a)}),o}function xi(e,t,n,r){return t<=n||e>=r}function Si(e,t,n,r,i){return!n&&r>=i?(e.push(...t),!0):n}function Ci(e,t,n,r,i,a,o){let s=bi(t,n,r,i);s[0]&&e.push(s[0]);let c=o;return c||=(e.push(...a),!0),s[1]&&e.push(s[1]),c}function wi(e,t,n,r,i,a){return!r&&i<=a?(e.push(...n),!0):(e.push(t),r)}function Ti(e,t,n,r){let i=Math.max(0,t),a=Math.max(i,n),o=[],s=0,c=!1;for(let t of e){let e=pi(t),n=s,l=s+e;if(xi(n,l,i,a)){c=Si(o,r,c,n,a),o.push(t),s=l;continue}c=t.type===`text`?Ci(o,t,n,i,a,r,c):wi(o,t,r,c,i,n),s=l}return c||o.push(...r),gi(o)}function Ei(e,t){return gi(e.filter(e=>e.type!==`token`||!t(e)))}function Di(e,t){if(!t||t.start!==t.end)return null;let n=_i(e),r=t.end,i=n.slice(0,r),a=/(?:^|\s)\/([^\s\uFFFC]*)$/.exec(i);if(!a)return null;let o=r-a[0].length+(a[0].startsWith(`/`)?0:1);return{query:(a[1]??``).trim().toLowerCase(),start:o,end:r}}function Oi(e,t,n){return e?e.start<n&&e.end>t:!1}function ki(e){let t=new Map,n=0;for(let r of e)t.set(r.id,n),n+=pi(r);return t}function Ai(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 ji(e,t,n){if(e instanceof HTMLElement){let t=e.dataset.composerNodeId;if(t)return n.find(e=>e.id===t)}return n[t]}function Mi(e,t,n){let r=0;for(let i=0;i<n;i+=1){let n=ji(e.childNodes[i],i,t);n&&(r+=pi(n))}return r}function Ni(e,t,n,r){let i=Ai(e,t),a=Mi(e,r,i),o=r[i];return o?.type===`text`?a+Math.min(n,o.text.length):a+Math.min(n,t.textContent?.length??0)}function Pi(e,t,n,r,i){return n.type===`text`?e.nodeType===Node.TEXT_NODE?r+Math.min(t,n.text.length):e===i?r+(t>0?n.text.length:0):r+n.text.length:e===i?r+(t>0?1:0):r+1}function Fi(e,t,n,r,i){if(t===e)return Mi(e,r,n);if(t.nodeType===Node.TEXT_NODE&&t.parentNode===e)return Ni(e,t,n,r);let a=t instanceof HTMLElement?t.closest(`[data-composer-node-id]`):t.parentElement?.closest(`[data-composer-node-id]`)??null;if(!(a instanceof HTMLElement))return Fi(e,e,Ai(e,t),r,i);let o=a.dataset.composerNodeId;if(!o)return 0;let s=r.find(e=>e.id===o),c=i.get(o)??0;return s?Pi(t,n,s,c,a):c}function Ii(e,t){let n=window.getSelection();if(!n||n.rangeCount===0)return null;let r=n.getRangeAt(0);if(!e.contains(r.startContainer)||!e.contains(r.endContainer))return null;let i=ki(t),a=Fi(e,r.startContainer,r.startOffset,t,i),o=Fi(e,r.endContainer,r.endOffset,t,i);return{start:Math.min(a,o),end:Math.max(a,o)}}function Li(e,t,n){if(!n)return;let r=window.getSelection();if(!r)return;let i=n=>{let r=0;for(let i=0;i<t.length;i+=1){let a=t[i],o=pi(a),s=r,c=r+o,l=e.childNodes[i];if(!l){r=c;continue}if(a.type===`text`){if(n<=c)return{container:l.firstChild??l,offset:Math.max(0,Math.min(n-s,a.text.length))}}else{if(n<=s)return{container:e,offset:i};if(n<=c)return{container:e,offset:i+1}}r=c}return{container:e,offset:e.childNodes.length}},a=i(n.start),o=i(n.end),s=document.createRange();s.setStart(a.container,a.offset),s.setEnd(o.container,o.offset),r.removeAllRanges(),r.addRange(s)}function Ri(e){let t=[];for(let n of Array.from(e.childNodes)){if(n.nodeType===Node.TEXT_NODE){t.push(di(n.textContent??``));continue}if(!(n instanceof HTMLElement))continue;if(n.dataset.composerNodeType===`token`){let e=n.dataset.composerTokenKind,r=n.dataset.composerTokenKey,i=n.dataset.composerLabel;e&&r&&i&&t.push({id:n.dataset.composerNodeId??fi({tokenKind:e,tokenKey:r,label:i}).id,type:`token`,tokenKind:e,tokenKey:r,label:i});continue}let e=n.textContent??``;t.push({id:n.dataset.composerNodeId??di(e).id,type:`text`,text:e})}return gi(t)}function zi(e){let t=Ri(e);return{nodes:t,selection:Ii(e,t)}}var Bi=class{constructor(){this.nodes=mi(),this.selection=null,this.sync=(e,t)=>(this.nodes=gi(e),this.selection=t,this.getSnapshot()),this.setSelection=e=>(this.selection=e,this.getSnapshot()),this.replaceDocument=(e,t)=>(this.nodes=gi(e),this.selection=t,this.getSnapshot()),this.insertText=e=>{let t=this.selection??{start:0,end:0};this.nodes=Ti(this.nodes,t.start,t.end,[di(e)]);let n=t.start+e.length;return this.selection={start:n,end:n},this.getSnapshot()},this.insertFileToken=(e,t)=>this.insertToken(`file`,e,t),this.insertSkillToken=(e,t)=>this.getSelectedSkillKeys().includes(e)?this.getSnapshot():this.insertToken(`skill`,e,t,this.getSlashTrigger()),this.syncSelectedSkills=(e,t)=>{let n=this.getSelectedSkillKeys(),r=new Map(t.map(e=>[e.key,e])),i=e.find(e=>!n.includes(e));if(i){let e=r.get(i);return this.insertSkillToken(i,e?.label??i)}let a=n.find(t=>!e.includes(t));return a&&(this.nodes=Ei(this.nodes,e=>e.tokenKind===`skill`&&e.tokenKey===a)),this.getSnapshot()},this.deleteContent=e=>{let t=this.getDocumentLength(),n=this.selection??{start:t,end:t},r=n.start,i=n.end;if(n.start===n.end)if(e===`backward`&&n.start>0)r=n.start-1;else if(e===`forward`)i=n.end+1;else return this.getSnapshot();return this.nodes=Ti(this.nodes,r,i,[]),this.selection={start:r,end:r},this.getSnapshot()},this.getSnapshot=()=>({nodes:this.nodes,selection:this.selection,nodeStartMap:ki(this.nodes),documentLength:this.getDocumentLength(),selectedSkillKeys:this.getSelectedSkillKeys(),slashTrigger:this.getSlashTrigger()}),this.getDocumentLength=()=>this.nodes.reduce((e,t)=>e+pi(t),0),this.getSelectedSkillKeys=()=>yi(this.nodes,`skill`),this.insertToken=(e,t,n,r=null)=>{let i=this.getDocumentLength(),a=r?.start??this.selection?.start??i,o=r?.end??this.selection?.end??a;return this.nodes=Ti(this.nodes,a,o,[fi({tokenKind:e,tokenKey:t,label:n})]),this.selection={start:a+1,end:a+1},this.getSnapshot()},this.getSlashTrigger=()=>Di(this.nodes,this.selection)}};function Vi(e){let{key:t,shiftKey:n,isComposing:r,isSlashMenuOpen:i,slashItemCount:a,activeSlashIndex:o,isSending:s,canStopGeneration:c}=e;if(t===`Enter`&&!n&&s)return{type:`consume`};if(i&&a>0){if(t===`ArrowDown`)return{type:`move-slash-index`,index:(o+1)%a};if(t===`ArrowUp`)return{type:`move-slash-index`,index:(o-1+a)%a};if(t===`Enter`&&!n||t===`Tab`)return{type:`insert-active-slash-item`}}return t===`Escape`?i?{type:`close-slash`}:s&&c?{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`}}var Hi=`http://www.w3.org/2000/svg`,Ui=class{constructor(){this.render=(e,t)=>{if(!e)return;let n=document.createDocumentFragment();for(let e of t.nodes){let r=e.type===`text`?this.createTextNodeElement(e):this.createTokenNodeElement(e,t.selectedRange,t.nodeStartMap);r&&n.appendChild(r)}e.replaceChildren(n)},this.createTextNodeElement=e=>{if(e.text.length===0)return null;let t=document.createElement(`span`);return t.dataset.composerNodeId=e.id,t.dataset.composerNodeType=`text`,t.textContent=e.text,t},this.createTokenNodeElement=(e,t,n)=>{let r=n.get(e.id)??0,i=Oi(t,r,r+1),a=document.createElement(`span`);a.contentEditable=`false`,a.dataset.composerNodeId=e.id,a.dataset.composerNodeType=`token`,a.dataset.composerTokenKind=e.tokenKind,a.dataset.composerTokenKey=e.tokenKey,a.dataset.composerLabel=e.label,a.title=e.label,a.className=this.buildTokenClassName(e.tokenKind,i),a.append(this.createTokenIcon(e.tokenKind));let o=document.createElement(`span`);return o.className=e.tokenKind===`file`?`min-w-0 flex-1 truncate text-[12px] font-medium text-slate-700`:`truncate`,o.textContent=e.label,a.append(o),a},this.buildTokenClassName=(e,t)=>e===`file`?[`mx-[2px]`,`inline-flex`,`h-7`,`max-w-[min(100%,17rem)]`,`items-center`,`gap-1.5`,`rounded-lg`,`border`,`px-2`,`align-baseline`,`transition-[border-color,background-color,box-shadow,color]`,`duration-150`,t?`border-slate-300 bg-slate-100 text-slate-800 shadow-[0_0_0_2px_rgba(148,163,184,0.14)]`:`border-slate-200/80 bg-slate-50 text-slate-700`].join(` `):[`mx-[2px]`,`inline-flex`,`h-7`,`max-w-full`,`items-center`,`gap-1.5`,`rounded-lg`,`border`,`px-2`,`align-baseline`,`text-[11px]`,`font-medium`,`transition`,t?`border-primary/30 bg-primary/18 text-primary`:`border-primary/12 bg-primary/8 text-primary`].join(` `),this.createTokenIcon=e=>{let t=document.createElement(`span`);return t.className=e===`file`?`inline-flex h-4.5 w-4.5 shrink-0 items-center justify-center rounded-md bg-white text-slate-500 ring-1 ring-black/5`:`inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center text-primary/70`,t.append(e===`file`?this.createFileIcon():this.createSkillIcon()),t},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:`M3.25 4.25A1.5 1.5 0 0 1 4.75 2.75h6.5a1.5 1.5 0 0 1 1.5 1.5v7.5a1.5 1.5 0 0 1-1.5 1.5h-6.5a1.5 1.5 0 0 1-1.5-1.5v-7.5Z`}},{tag:`path`,attrs:{d:`m4.75 10 2.25-2.5 1.75 1.75 1.25-1.25 2 2`}},{tag:`path`,attrs:{d:`M9.75 6.25h.01`}}]),this.createSvgIcon=e=>{let t=document.createElementNS(Hi,`svg`);t.setAttribute(`viewBox`,`0 0 16 16`),t.setAttribute(`fill`,`none`),t.setAttribute(`stroke`,`currentColor`),t.setAttribute(`stroke-width`,`1.25`),t.setAttribute(`stroke-linecap`,`round`),t.setAttribute(`stroke-linejoin`,`round`),t.setAttribute(`aria-hidden`,`true`),t.setAttribute(`class`,`h-3 w-3`);for(let n of e){let e=document.createElementNS(Hi,n.tag);for(let[t,r]of Object.entries(n.attrs))e.setAttribute(t,r);t.append(e)}return t}}},Wi=188,Gi=class{constructor(e){this.controller=e,this.surfaceRenderer=new Ui,this.sync=(e,t)=>this.controller.sync(e,t),this.syncSelectionFromRoot=e=>this.controller.setSelection(Ii(e,this.controller.getSnapshot().nodes)),this.restoreSelectionIfFocused=(e,t)=>{!e||document.activeElement!==e||Li(e,this.controller.getSnapshot().nodes,t)},this.syncViewport=e=>{e&&(e.style.maxHeight=`${Wi}px`,e.style.overflowY=e.scrollHeight>Wi?`auto`:`hidden`)},this.renderSurface=e=>{this.surfaceRenderer.render(e.root,{nodes:e.snapshot.nodes,selectedRange:e.selectedRange,nodeStartMap:e.snapshot.nodeStartMap})},this.insertSlashItem=(e,t)=>{e.value&&t(this.controller.insertSkillToken(e.value,e.title))},this.syncSelectedSkills=(e,t,n)=>{n(this.controller.syncSelectedSkills(e,t))},this.handleBeforeInput=e=>{let{event:t,disabled:n,isComposing:r,commitSnapshot:i}=e,a=t.nativeEvent;n||r||a.isComposing||!(a.inputType===`insertText`||a.inputType===`insertReplacementText`)||!a.data||(t.preventDefault(),i(this.controller.insertText(a.data)))},this.handleInput=e=>{let{event:t,isComposing:n,commitSnapshot:r}=e,i=t.nativeEvent;if(n||i.isComposing)return;let a=t.currentTarget,o=zi(a);r(this.controller.replaceDocument(o.nodes,o.selection))},this.handleCompositionEnd=e=>{let{event:t,commitSnapshot:n}=e,r=t.currentTarget,i=zi(r);n(this.controller.replaceDocument(i.nodes,i.selection))},this.handleKeyDown=e=>{let{event:t,slashItems:n,activeSlashIndex:r,activeSlashItem:i,actions:a,commitSnapshot:o,insertSkillToken:s,onSlashItemSelect:c,onSlashActiveIndexChange:l,onSlashQueryChange:u,onSlashOpenChange:d}=e,f=this.controller.getSnapshot(),p=Vi({key:t.key,shiftKey:t.shiftKey,isComposing:t.nativeEvent.isComposing,isSlashMenuOpen:f.slashTrigger!==null,slashItemCount:n.length,activeSlashIndex:r,isSending:a.isSending,canStopGeneration:a.canStopGeneration});p.type!==`noop`&&(t.preventDefault(),this.applyKeyboardAction({action:p,activeSlashItem:i,actions:a,commitSnapshot:o,insertSkillToken:s,onSlashItemSelect:c,onSlashActiveIndexChange:l,onSlashQueryChange:u,onSlashOpenChange:d}))},this.handlePaste=e=>{let{event:t,onFilesAdd:n,commitSnapshot:r}=e,i=Array.from(t.clipboardData.files??[]);if(i.length>0&&n){t.preventDefault(),n(i);return}let a=t.clipboardData.getData(`text/plain`);a&&(t.preventDefault(),r(this.controller.insertText(a)))},this.handleBlur=e=>{let{clearSelectedRange:t,onSlashQueryChange:n,onSlashOpenChange:r}=e;t(),n?.(null),r(!1)},this.applyKeyboardAction=e=>{let{action:t,activeSlashItem:n,actions:r,commitSnapshot:i,insertSkillToken:a,onSlashItemSelect:o,onSlashActiveIndexChange:s,onSlashQueryChange:c,onSlashOpenChange:l}=e;switch(t.type){case`move-slash-index`:s(t.index);return;case`insert-active-slash-item`:if(!n)return;o?.(n),a(n.value??n.key,n.title);return;case`close-slash`:c?.(null),l(!1);return;case`consume`:return;case`stop-generation`:r.onStop();return;case`insert-line-break`:i(this.controller.insertText(`
1
+ import{_ as e,a as t,d as n,f as r,g as i,h as a,i as o,m as s,n as c,p as l,u}from"./i18n-BK1w-oBy.js";import{a as d,c as f,n as p,o as m,r as h,s as g,u as _}from"./dist-DazA6Wd_.js";import{c as v,o as y,s as b}from"./chunk-JZWAC4HX-B5l0hr_u.js";import{n as x,t as S}from"./react-C3yu5yge.js";import{t as C}from"./useMutation-oTTWXgLG.js";import{D as w,O as T,_ as E,a as D,b as O,c as ee,d as k,f as te,g as A,h as j,i as ne,k as re,l as ie,m as M,n as ae,o as oe,p as se,r as ce,s as le,t as ue,u as de,v as fe,y as pe}from"./select-BHJPiJWt.js";import{t as N}from"./createLucideIcon-o1WWhwhd.js";import{n as me}from"./DocBrowser-DxdSujSc.js";import{t as he}from"./book-open-FnK2xCQd.js";import{t as ge}from"./external-link-BKje3SiD.js";import{i as _e,n as ve,o as ye,t as be}from"./provider-models-DJ29qHuA.js";import{n as xe,t as Se}from"./logos-CTLlde_T.js";import{t as Ce}from"./loader-circle-DdZPxBUz.js";import{a as we,c as Te,i as Ee,l as De,n as Oe,o as ke,r as Ae,s as je,t as Me,u as Ne}from"./MarketplacePage-CNeXwz7q.js";import{t as Pe}from"./plus-DP2PSCPO.js";import{t as Fe}from"./refresh-ccw-BAJf-h7w.js";import{a as Ie,c as Le,d as Re,i as ze,l as Be,n as Ve,o as He,r as Ue,s as We,t as Ge,u as Ke}from"./chat-session-display-BD_AN71I.js";import{t as qe}from"./search-pD6ZwQYF.js";import{t as Je}from"./trash-2-CrjYH5ok.js";import{t as Ye}from"./x-CTIQHUuD.js";import{d as Xe}from"./config-JKmXfZ3q.js";import{i as Ze}from"./DocBrowserContext-CQ-8jMha.js";import{F as Qe,G as $e,I as et,K as tt,L as nt,N as rt,P as it,R as at,S as ot,T as st,W as ct,_t as lt,a as ut,at as dt,b as ft,c as pt,ct as mt,et as ht,f as gt,ft as _t,gt as vt,ht as yt,i as bt,it as xt,l as St,lt as Ct,n as wt,nt as Tt,o as Et,ot as Dt,p as Ot,pt as kt,r as At,rt as jt,s as Mt,t as Nt,tt as Pt,ut as Ft,y as It}from"./index-BuTtTFjM.js";import{a as Lt,c as Rt,i as zt,n as Bt,o as Vt,r as Ht,s as Ut,t as Wt}from"./popover-5DWhNfd4.js";import{t as Gt}from"./LogoBadge-D-KQIN4U.js";import{t as Kt}from"./label-BzDWmdOe.js";import{n as qt,t as Jt}from"./page-layout-BagR3t59.js";import{t as Yt}from"./useConfirmDialog-RlLbo0NU.js";var Xt=N(`ArrowUpRight`,[[`path`,{d:`M7 7h10v10`,key:`1tivn9`}],[`path`,{d:`M7 17 17 7`,key:`1vkiza`}]]),Zt=N(`ArrowUp`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),Qt=N(`Brain`,[[`path`,{d:`M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z`,key:`l5xja`}],[`path`,{d:`M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z`,key:`ep3f8r`}],[`path`,{d:`M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4`,key:`1p4c4q`}],[`path`,{d:`M17.599 6.5a3 3 0 0 0 .399-1.375`,key:`tmeiqw`}],[`path`,{d:`M6.003 5.125A3 3 0 0 0 6.401 6.5`,key:`105sqy`}],[`path`,{d:`M3.477 10.896a4 4 0 0 1 .585-.396`,key:`ql3yin`}],[`path`,{d:`M19.938 10.5a4 4 0 0 1 .585.396`,key:`1qfode`}],[`path`,{d:`M6 18a4 4 0 0 1-1.967-.516`,key:`2e4loj`}],[`path`,{d:`M19.967 17.484A4 4 0 0 1 18 18`,key:`159ez6`}]]),$t=N(`ChevronRight`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),en=N(`CodeXml`,[[`path`,{d:`m18 16 4-4-4-4`,key:`1inbqp`}],[`path`,{d:`m6 8-4 4 4 4`,key:`15zrgr`}],[`path`,{d:`m14.5 4-5 16`,key:`e7oirm`}]]),tn=N(`Copy`,[[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`,key:`17jyea`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`,key:`zix9uf`}]]),nn=N(`Ellipsis`,[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`19`,cy:`12`,r:`1`,key:`1wjl8i`}],[`circle`,{cx:`5`,cy:`12`,r:`1`,key:`1pcz8c`}]]),rn=N(`FileText`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),an=N(`FolderOpen`,[[`path`,{d:`m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2`,key:`usdka0`}]]),on=N(`FolderUp`,[[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}],[`path`,{d:`M12 10v6`,key:`1bos4e`}],[`path`,{d:`m9 13 3-3 3 3`,key:`1pxg3c`}]]),sn=N(`FolderX`,[[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}],[`path`,{d:`m9.5 10.5 5 5`,key:`ra9qjz`}],[`path`,{d:`m14.5 10.5-5 5`,key:`l2rkpq`}]]),cn=N(`HeartPulse`,[[`path`,{d:`M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z`,key:`c3ymky`}],[`path`,{d:`M3.22 12H9.5l.5-1 2 4.5 2-7 1.5 3.5h5.27`,key:`1uw2ng`}]]),ln=N(`House`,[[`path`,{d:`M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8`,key:`5wwlr5`}],[`path`,{d:`M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z`,key:`1d0kgt`}]]),un=N(`MessageSquareText`,[[`path`,{d:`M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z`,key:`1lielz`}],[`path`,{d:`M13 8H7`,key:`14i4kc`}],[`path`,{d:`M17 12H7`,key:`16if0g`}]]),dn=N(`Minus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}]]),fn=N(`Paperclip`,[[`path`,{d:`m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48`,key:`1u3ebp`}]]),pn=N(`Pencil`,[[`path`,{d:`M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z`,key:`1a8usu`}],[`path`,{d:`m15 5 4 4`,key:`1mk7zo`}]]),mn=N(`Play`,[[`polygon`,{points:`6 3 20 12 6 21 6 3`,key:`1oa8hb`}]]),hn=N(`Power`,[[`path`,{d:`M12 2v10`,key:`mnfbl`}],[`path`,{d:`M18.4 6.6a9 9 0 1 1-12.77.04`,key:`obofu9`}]]),gn=N(`Puzzle`,[[`path`,{d:`M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z`,key:`w46dr5`}]]),_n=N(`ShieldCheck`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),vn=N(`Terminal`,[[`polyline`,{points:`4 17 10 11 4 5`,key:`akl6gq`}],[`line`,{x1:`12`,x2:`20`,y1:`19`,y2:`19`,key:`q2wloq`}]]),yn=N(`TriangleAlert`,[[`path`,{d:`m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3`,key:`wmoenq`}],[`path`,{d:`M12 9v4`,key:`juzpu7`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),P=e(s(),1),F=function(e){return 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}({}),bn=/\[\[\s*reply_to_current\s*\]\]/gi,xn=/\[\[\s*reply_to\s*:\s*([^\]]+?)\s*\]\]/i;function Sn(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Cn(e,t){let n=e,r;bn.test(n)&&(r=Sn(t),n=n.replace(bn,``).trim());let i=n.match(xn)?.[1];return i&&(r=Sn(i),n=n.replace(xn,``).trim()),r?{content:n,replyTo:r}:{content:n}}function wn(e,t=e.id){if(e.role!==`assistant`)return{...e,parts:[...e.parts],metadata:e.metadata?{...e.metadata}:void 0};let n=e.parts.findIndex(e=>e.type===`text`),r=e.metadata?{...e.metadata}:void 0,i=Sn(r?.reply_to);if(n<0)return{...e,parts:[...e.parts],metadata:r};let a=e.parts[n];if(!a||a.type!==`text`)return{...e,parts:[...e.parts],metadata:r};let{content:o,replyTo:s}=Cn(a.text,t),c=s??i,l=e.parts.flatMap((e,t)=>t!==n||e.type!==`text`?[e]:o.length===0?[]:[{...e,text:o}]);return c?{...e,parts:l,metadata:{...r,reply_to:c}}:{...e,parts:l,metadata:r}}function Tn(e){return{...e,parts:[...e.parts],metadata:e.metadata?{...e.metadata}:void 0}}function En(e){return Tn(wn(e))}function Dn(e){let t=e.error?.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 On(e,t){return t.trim()?e.id.startsWith(`tool-`)?!0:e.parts.some(e=>e.type===`tool-invocation`):!1}function kn(e,t,n){for(let[r,i]of e)i===t&&e.set(r,n)}function An(e,t,n){for(let[r,i]of e)i===n&&(e.delete(r),t.delete(r))}function jn(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r.type===`tool-invocation`&&r.toolCallId===t)return r}return null}function Mn(e,t){return jn(e,t)?.toolName??null}function Nn(e,t){let n=[...e];for(let e=n.length-1;e>=0;--e){let r=n[e];if(r.type===`tool-invocation`&&r.toolCallId===t.toolCallId)return n[e]={...r,...t},n}return n.push(t),n}var Pn=`assistant`,Fn=class{messages=[];streamingMessage=null;error=null;activeRun=null;listeners=new Set;toolCallMessageIdByCallId=new Map;toolCallArgsRawByCallId=new Map;lastSettledRunId=null;snapshotCache=null;snapshotVersion=-1;stateVersion=0;getSnapshot=()=>{if(this.snapshotCache&&this.snapshotVersion===this.stateVersion)return this.snapshotCache;let e={messages:this.messages,streamingMessage:this.streamingMessage,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=>(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.lastSettledRunId=null,this.stateVersion+=1,this.notifyListeners())};hydrate=e=>{this.messages=e.messages.map(e=>En(e)),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.lastSettledRunId=null,this.stateVersion+=1,this.notifyListeners()};dispatch=e=>this.dispatchBatch([e]);dispatchBatch=async e=>{if(!e.length)return;let t=this.stateVersion;e.forEach(this.applyEvent),this.stateVersion!==t&&this.notifyListeners()};applyEvent=e=>{switch(e.type){case F.MessageSent:this.handleMessageSent(e.payload);break;case F.MessageAbort:this.handleMessageAbort(e.payload);break;case F.MessageTextStart:this.handleMessageTextStart(e.payload);break;case F.MessageTextDelta:this.handleMessageTextDelta(e.payload);break;case F.MessageTextEnd:this.handleMessageTextEnd(e.payload);break;case F.MessageReasoningStart:this.handleMessageReasoningStart(e.payload);break;case F.MessageReasoningDelta:this.handleMessageReasoningDelta(e.payload);break;case F.MessageReasoningEnd:this.handleMessageReasoningEnd(e.payload);break;case F.MessageToolCallStart:this.handleMessageToolCallStart(e.payload);break;case F.MessageToolCallArgs:this.handleMessageToolCallArgs(e.payload);break;case F.MessageToolCallArgsDelta:this.handleMessageToolCallArgsDelta(e.payload);break;case F.MessageToolCallEnd:this.handleMessageToolCallEnd(e.payload);break;case F.MessageToolCallResult:this.handleMessageToolCallResult(e.payload);break;case F.RunStarted:this.handleRunStarted(e.payload);break;case F.RunFinished:this.handleRunFinished(e.payload);break;case F.RunError:this.handleRunError(e.payload);break;case F.RunMetadata:this.handleRunMetadata(e.payload);break;case F.EndpointError:this.handleEndpointError(e.payload);break;default:break}};handleMessageSent=e=>{this.upsertMessage(e.message),this.setError(null)};handleMessageAbort=e=>{let t=e.messageId?.trim();if(this.clearActiveRun(),this.setError(null),this.streamingMessage&&(!t||this.streamingMessage.id===t)){let e=this.streamingMessage.id;this.upsertMessage({...this.streamingMessage,status:`final`}),this.replaceStreamingMessage(null),t?An(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,t):An(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,e)}};handleMessageTextStart=e=>{this.ensureStreamingMessage(e.sessionId,e.messageId,`streaming`),this.setError(null)};handleMessageTextDelta=e=>{if(!e.delta)return;let t=this.ensureStreamingMessage(e.sessionId,e.messageId,`streaming`),n=[...t.parts],r=n[n.length-1];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=>{this.streamingMessage?.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;let t=this.ensureStreamingMessage(e.sessionId,e.messageId,`streaming`),n=[...t.parts],r=n[n.length-1];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=>{this.streamingMessage?.id,e.messageId};handleMessageToolCallStart=e=>{let t=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId,e.messageId);this.toolCallArgsRawByCallId.set(e.toolCallId,``);let n=Nn(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=>{let t=`${this.toolCallArgsRawByCallId.get(e.toolCallId)??``}${e.delta}`;this.toolCallArgsRawByCallId.set(e.toolCallId,t),this.applyToolCallArgs(e.sessionId,e.toolCallId,t,e.messageId)};handleMessageToolCallEnd=e=>{let t=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId),n=this.toolCallArgsRawByCallId.get(e.toolCallId)??``,r=Nn(t.parts,{type:`tool-invocation`,toolCallId:e.toolCallId,toolName:Mn(t.parts,e.toolCallId)??`unknown`,state:`call`,args:n});this.replaceStreamingMessage({...t,parts:r,status:`streaming`})};handleMessageToolCallResult=e=>{if(!this.updateMessageContainingToolCall(e.toolCallId,(t,n)=>{let r={type:`tool-invocation`,toolCallId:e.toolCallId,toolName:n.toolName,state:`result`,args:n.args,result:e.content};return Nn(t.parts,r)})){let t=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId),n=Nn(t.parts,{type:`tool-invocation`,toolCallId:e.toolCallId,toolName:`unknown`,state:`result`,result:e.content});this.replaceStreamingMessage({...t,parts:n,status:`streaming`})}};handleRunStarted=e=>{this.isSettledRunId(e.runId)||(this.setError(null),this.activeRun={runId:e.runId??null,sessionId:e.sessionId},this.stateVersion+=1)};handleRunFinished=e=>{this.markRunAsSettled(e.runId??this.activeRun?.runId??null),this.settleStreamingMessage(`final`),this.setError(null),this.clearActiveRun()};handleRunError=e=>{this.markRunAsSettled(e.runId??this.activeRun?.runId??null),this.settleStreamingMessage(`error`),this.setError(Dn(e)),this.clearActiveRun()};handleRunMetadata=e=>{let t=e.metadata;if(t?.kind===`ready`){let e=t;if(this.isSettledRunId(e.runId))return;this.activeRun={runId:e.runId??this.activeRun?.runId??null,sessionId:e.sessionId??this.activeRun?.sessionId,abortDisabledReason:e.supportsAbort===!1?e.abortDisabledReason??`Unsupported`:null},this.stateVersion+=1}else t?.kind===`final`&&(this.markRunAsSettled(e.runId??this.activeRun?.runId??null),this.clearActiveRun())};handleEndpointError=e=>{if(e.code===`abort-error`){this.handleMessageAbort({sessionId:this.activeRun?.sessionId??this.streamingMessage?.sessionId??``,...this.streamingMessage?.id?{messageId:this.streamingMessage.id}:{}});return}this.settleStreamingMessage(`error`),this.clearActiveRun(),this.setError(e)};applyToolCallArgs=(e,t,n,r)=>{let i=this.resolveToolCallTargetMessage(e,t,r),a=Mn(i.parts,t)??`unknown`,o=Nn(i.parts,{type:`tool-invocation`,toolCallId:t,toolName:a,state:`partial-call`,args:n});this.replaceStreamingMessage({...i,parts:o,status:`streaming`})};ensureStreamingMessage=(e,t,n)=>{if(this.streamingMessage?.id===t){if(this.streamingMessage.status===n)return this.streamingMessage;let e={...this.streamingMessage,status:n};return this.replaceStreamingMessage(e),e}let r=this.messages.findIndex(e=>e.id===t);if(r>=0){let t=Tn(this.messages[r]),i=[...this.messages];i.splice(r,1),this.messages=i,this.stateVersion+=1;let a={...t,sessionId:e,status:n};return this.replaceStreamingMessage(a),a}let i=this.streamingMessage;if(i&&i.id!==t&&i.sessionId===e&&On(i,t)){let r={...i,id:t,sessionId:e,status:n};return kn(this.toolCallMessageIdByCallId,i.id,t),this.replaceStreamingMessage(r),r}let a={id:t,sessionId:e,role:Pn,status:n,parts:[],timestamp:new Date().toISOString()};return this.replaceStreamingMessage(a),a};resolveToolCallTargetMessage=(e,t,n)=>{let r=n?.trim()||this.toolCallMessageIdByCallId.get(t)||this.streamingMessage?.id||`tool-${t}`;return this.toolCallMessageIdByCallId.set(t,r),this.ensureStreamingMessage(e,r,`streaming`)};updateMessageContainingToolCall=(e,t)=>{if(this.streamingMessage){let n=jn(this.streamingMessage.parts,e);if(n){let e=t(this.streamingMessage,n);return this.replaceStreamingMessage({...this.streamingMessage,parts:e}),!0}}for(let n=this.messages.length-1;n>=0;--n){let r=this.messages[n],i=jn(r.parts,e);if(!i)continue;let a=[...this.messages];return a[n]={...r,parts:t(r,i)},this.messages=a,this.stateVersion+=1,!0}return!1};upsertMessage=e=>{let t=En(e),n=this.messages.findIndex(e=>e.id===t.id);if(n<0){this.messages=[...this.messages,t],this.stateVersion+=1;return}let r=[...this.messages];r[n]=t,this.messages=r,this.stateVersion+=1};replaceStreamingMessage=e=>{!e&&!this.streamingMessage||(this.streamingMessage=e?En(e):null,this.stateVersion+=1)};setError=e=>{this.error?.code===e?.code&&this.error?.message===e?.message&&this.error?.details===e?.details&&this.error?.cause===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)};isSettledRunId=e=>!!e?.trim()&&e===this.lastSettledRunId;markRunAsSettled=e=>{this.lastSettledRunId=e?.trim()||null};settleStreamingMessage=e=>{if(!this.streamingMessage)return;let t={...this.streamingMessage,status:e};this.upsertMessage(t),this.replaceStreamingMessage(null),An(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,t.id)};notifyListeners=()=>{let e=this.getSnapshot();for(let t of this.listeners)t(e)}},In=16,Ln=class{constructor(e){this.dispatchBatch=e,this.queue=[],this.flushTimerId=null,this.isFlushing=!1,this.isDisposed=!1,this.enqueue=e=>{this.isDisposed||(this.queue.push(e),this.scheduleFlush())},this.dispose=()=>{this.isDisposed=!0,this.flushTimerId!==null&&(window.clearTimeout(this.flushTimerId),this.flushTimerId=null),this.queue.length=0},this.scheduleFlush=()=>{this.flushTimerId!==null||this.isFlushing||this.queue.length===0||(this.flushTimerId=window.setTimeout(()=>{this.flushTimerId=null,this.flush()},In))},this.flush=async()=>{if(!(this.isDisposed||this.isFlushing||this.queue.length===0)){this.isFlushing=!0;try{for(;this.queue.length>0;){let e=this.queue.splice(0);await this.dispatchBatch(e)}}finally{this.isFlushing=!1,this.scheduleFlush()}}}}};function Rn(e,t){let n=e.dispatchBatch;return typeof n==`function`?n.call(e,t):t.reduce((t,n)=>t.then(()=>e.dispatch(n)),Promise.resolve())}function zn(e,t){let n=`payload`in e?e.payload:null;return!n||typeof n!=`object`||!(`sessionId`in n)||typeof n.sessionId!=`string`?!0:n.sessionId===t}function Bn(e){return e.parts.some(e=>e.type===`text`||e.type===`rich-text`||e.type===`reasoning`?e.text.trim().length>0:!0)}function Vn(e,t){if(typeof e==`string`){let 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 Bn(e.message)?{...e,sessionId:e.sessionId,message:{...e.message,sessionId:e.message.sessionId||e.sessionId}}:null}function Hn(e){let t=(0,P.useRef)();return(!t.current||t.current.sessionId!==e)&&(t.current={sessionId:e,manager:new Fn}),t.current.manager}function Un({sessionId:e,client:t,manager:n}){let r=(0,P.useSyncExternalStore)(e=>n.subscribe(()=>e()),()=>n.getSnapshot(),()=>n.getSnapshot()),[i,a]=(0,P.useState)(!1);(0,P.useEffect)(()=>{a(!1)},[e]),(0,P.useEffect)(()=>{let r=new Ln(e=>Rn(n,e)),i=t.subscribe(t=>{zn(t,e)&&r.enqueue(t)});return()=>{i(),r.dispose(),t.stop()}},[t,n,e]);let o=r.streamingMessage?[...r.messages,r.streamingMessage]:r.messages,s=r.activeRun?.runId??null,c=!!r.activeRun;return{snapshot:r,visibleMessages:o,activeRunId:s,isRunning:c,isSending:i,send:async r=>{if(i||c)return;let o=Vn(r,e);if(o){a(!0),await n.dispatch({type:F.MessageSent,payload:{sessionId:e,message:o.message,metadata:o.metadata}});try{await t.send(o)}finally{a(!1)}}},abort:async()=>{r.activeRun&&await t.abort({sessionId:e})},streamRun:async()=>{await t.stop(),await t.stream({sessionId:e})}}}function Wn(e){return e instanceof Error?e:Error(String(e))}function Gn(e){return e.isHydrating||e.hydratedSessionId!==e.sessionId}function Kn({sessionId:e,client:t,loadSeed:n}){let r=Hn(e),i=Un({sessionId:e,client:t,manager:r}),[a,o]=(0,P.useState)(!0),[s,c]=(0,P.useState)(null),[l,u]=(0,P.useState)(null),d=(0,P.useRef)({requestId:0,controller:null}),f=(0,P.useCallback)(async()=>{d.current.controller?.abort();let i=new AbortController,a=d.current.requestId+1;d.current={requestId:a,controller:i},await t.stop(),r.reset(),c(null),o(!0);try{let s=await n(e,i.signal);if(i.signal.aborted||d.current.requestId!==a)return;r.hydrate({sessionId:e,messages:s.messages,activeRun:s.status===`running`?{runId:null,sessionId:e,abortDisabledReason:null}:null}),c(null),u(e),o(!1),t.stream({sessionId:e}).catch(e=>{d.current.requestId===a&&c(Wn(e))})}catch(t){if(i.signal.aborted||d.current.requestId!==a)return;c(Wn(t)),u(e),o(!1)}finally{d.current.controller===i&&(d.current.controller=null)}},[t,n,r,e]);return(0,P.useEffect)(()=>(f(),()=>{d.current.controller?.abort(),d.current.controller=null}),[f]),{...i,isHydrating:Gn({sessionId:e,hydratedSessionId:l,isHydrating:a}),hydrateError:s}}var qn=200*1024*1024,Jn=`application/octet-stream`;function Yn(e){let t=e.type.trim().toLowerCase();return t.length>0?t:Jn}function Xn(e,t){let n=t.acceptedMimeTypes&&t.acceptedMimeTypes.length>0?new Set(t.acceptedMimeTypes.map(e=>e.trim().toLowerCase())):null,r=t.maxBytes??209715200,i=Yn(e);return n&&!n.has(i)?{ok:!1,rejected:{fileName:e.name,mimeType:i,sizeBytes:e.size,reason:`unsupported-type`}}:e.size>r?{ok:!1,rejected:{fileName:e.name,mimeType:i,sizeBytes:e.size,reason:`too-large`}}:{ok:!0,mimeType:i}}function Zn(e){let t=e.parts&&e.parts.length>0?e.parts.map(e=>structuredClone(e)):[...e.text?.trim()??``?[{type:`text`,text:e.text.trim()}]:[],...(e.attachments??[]).map(e=>({type:`file`,name:e.name,mimeType:e.mimeType,...e.assetUri?.trim()?{assetUri:e.assetUri.trim()}:{},...e.url?.trim()?{url:e.url.trim()}:{},...e.contentBase64?.trim()?{contentBase64:e.contentBase64.trim()}:{},sizeBytes:e.sizeBytes}))];if(t.length===0)return null;let n=e.timestamp??new Date().toISOString(),r=e.messageId??`user-${Date.now().toString(36)}`;return{sessionId:e.sessionId,message:{id:r,sessionId:e.sessionId,role:`user`,status:`final`,parts:t,timestamp:n,...e.metadata?{metadata:e.metadata}:{}},...e.metadata?{metadata:e.metadata}:{}}}async function Qn(e,t){let n=[],r=[];for(let i of e){let e=Xn(i,t);if(!e.ok){r.push(e.rejected);continue}n.push(i)}if(n.length===0)return{attachments:[],rejected:r};try{return{attachments:await t.uploadBatch(n),rejected:r}}catch{return r.push(...n.map(e=>({fileName:e.name,mimeType:Yn(e),sizeBytes:e.size,reason:`read-failed`}))),{attachments:[],rejected:r}}}var I=l(),$n={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 er({status:e,className:t}){let n=$n[e],r=o(e===`connected`?`connected`:e===`disconnected`?`disconnected`:`connecting`);return(0,I.jsx)(Ee,{delayDuration:250,children:(0,I.jsxs)(Oe,{children:[(0,I.jsx)(we,{asChild:!0,children:(0,I.jsx)(`span`,{role:`status`,"aria-label":r,className:u(`inline-flex h-5 w-5 items-center justify-center`,t),children:e===`connecting`?(0,I.jsx)(Ce,{className:u(`h-3 w-3 animate-spin`,n.dotClass)}):(0,I.jsx)(`span`,{className:u(e===`connected`?`h-2 w-2 rounded-full`:``,n.dotClass)})})}),(0,I.jsx)(Ae,{side:`bottom`,className:`text-xs`,children:r})]})})}var tr=[[`bg-amber-100`,`text-amber-700`],[`bg-emerald-100`,`text-emerald-700`],[`bg-blue-100`,`text-blue-700`],[`bg-rose-100`,`text-rose-700`],[`bg-cyan-100`,`text-cyan-700`],[`bg-violet-100`,`text-violet-700`]];function nr(e){let t=0;for(let n=0;n<e.length;n+=1)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t)}function rr(e){let t=e.trim();return t?t.slice(0,1).toUpperCase():`A`}function ir({agentId:e,displayName:t,avatarUrl:n,className:r}){let i=t?.trim()||e,[a,o]=tr[nr(e)%tr.length]??tr[0];return n?.trim()?(0,I.jsx)(`img`,{src:n,alt:t?.trim()||e,className:u(`rounded-full object-cover`,r)}):(0,I.jsx)(`div`,{className:u(`rounded-full flex items-center justify-center font-semibold`,a,o,r),"aria-label":t?.trim()||e,children:rr(i)})}var ar={wx:`weixin`,lark:`feishu`},or={heartbeat:{icon:`heartbeat`},cron:{icon:`cron`}},sr={codex:`chatSessionTypeCodex`,claude:`chatSessionTypeClaude`};function cr(e){return e?.trim().toLowerCase()??``}function lr(e){return e.split(/[-_]+/g).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function ur(e,t){let n=cr(e);if(!n||n===`native`)return null;let r=t.find(e=>cr(e.value)===n);return r?.label.trim()?r.label.trim():lr(n)}function dr(e){let t=cr(e);if(!t)return null;let n=ar[t]??t;return Se(n)?n:null}function fr(e,t){let n=dr(e.channel??``);if(n)return{icon:{kind:`channel-logo`,channel:n},label:null};let r=or[cr(e.type)];if(r)return{icon:{kind:`symbol`,icon:r.icon},label:null};let i=sr[cr(e.sessionType)];return i?{icon:null,label:o(i)}:{icon:null,label:ur(e.sessionType,t)}}function pr({icon:e,className:t}){return e.kind===`channel-logo`?(0,I.jsx)(mr,{channel:e.channel,className:t}):e.icon===`heartbeat`?(0,I.jsx)(cn,{className:u(`h-3.5 w-3.5`,t)}):(0,I.jsx)(lt,{className:u(`h-3.5 w-3.5`,t)})}function mr({channel:e,className:t}){return(0,I.jsx)(Gt,{name:e,src:Se(e),className:u(`h-4 w-4 rounded-[4px] border border-gray-200/80 bg-white`,t),imgClassName:`h-3 w-3 object-contain`,fallback:(0,I.jsx)(vt,{className:`h-3 w-3 text-gray-500`})})}function hr(e){let{session:t,active:n,runStatus:r,context:i,title:a,agentId:s,agentLabel:l,agentAvatarUrl:d,isEditing:f,draftLabel:p,isSaving:h,onSelect:g,onStartEditing:_,onDraftLabelChange:v,onSave:y,onCancel:b}=e,x=n?`text-gray-700`:`text-gray-500`;return(0,I.jsx)(`div`,{className:u(`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:f?(0,I.jsxs)(`div`,{className:`space-y-2`,children:[(0,I.jsx)(ct,{value:p,onChange:e=>v(e.target.value),onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),y()):e.key===`Escape`&&(e.preventDefault(),b())},placeholder:o(`sessionsLabelPlaceholder`),className:`h-8 rounded-lg border-gray-300 bg-white text-xs`,autoFocus:!0,disabled:h}),(0,I.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,I.jsx)(`div`,{className:`min-w-0 text-[11px] text-gray-400 truncate`,children:t.key}),(0,I.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,I.jsx)(m,{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 y(),disabled:h,"aria-label":o(`save`),children:(0,I.jsx)(re,{className:`h-3.5 w-3.5`})}),(0,I.jsx)(m,{type:`button`,size:`icon`,variant:`ghost`,className:`h-7 w-7 rounded-lg text-gray-500 hover:bg-white hover:text-gray-900`,onClick:b,disabled:h,"aria-label":o(`cancel`),children:(0,I.jsx)(Ye,{className:`h-3.5 w-3.5`})})]})]})]}):(0,I.jsxs)(`div`,{className:`group/session relative`,children:[(0,I.jsxs)(`button`,{type:`button`,onClick:g,className:`w-full text-left`,children:[(0,I.jsxs)(`div`,{className:`grid grid-cols-[minmax(0,1fr)_0.875rem] items-center gap-1.5 pr-8`,children:[(0,I.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5`,children:[s?(0,I.jsx)(ir,{agentId:s,displayName:l,avatarUrl:d,className:`h-5 w-5 shrink-0`}):null,(0,I.jsx)(`span`,{className:`truncate font-medium`,children:a}),i.label?(0,I.jsx)(`span`,{className:u(`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:i.label}):null,i.icon?(0,I.jsx)(`span`,{className:`inline-flex h-[1.125rem] w-[1.125rem] shrink-0 items-center justify-center`,children:(0,I.jsx)(pr,{icon:i.icon,className:x})}):null]}),(0,I.jsx)(`span`,{className:`inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center`,children:r?(0,I.jsx)(Be,{status:r}):null})]}),(0,I.jsxs)(`div`,{className:`mt-0.5 text-[11px] text-gray-400 truncate`,children:[l?.trim()?`${l} · `:``,t.messageCount,` · `,c(t.updatedAt)]})]}),(0,I.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),_()},className:u(`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":o(`edit`),children:(0,I.jsx)(pn,{className:`h-3.5 w-3.5`})})]})})}function gr(){let e=_();return async t=>{try{nt(e,await Qe(t.sessionKey,t.patch)),p.success(t.successMessage??o(`configSavedApplied`))}catch(e){throw p.error(o(`configSaveFailed`)+`: `+(e instanceof Error?e.message:String(e))),e}}}function _r(){let e=gr();return async t=>{await e({sessionKey:t.sessionKey,patch:{label:t.label},successMessage:o(`configSavedApplied`)})}}var vr={selectedSessionKey:null,selectedAgentId:`main`,query:``},L=S(e=>({snapshot:vr,setSnapshot:t=>e(e=>({snapshot:{...e.snapshot,...t}}))}));function yr(e,t){return e.filter(e=>Ve(e,t))}function br(e){return e.isChildSession?e.isPromotedChildSession===!0:!0}function xr(e={}){let t=L(e=>e.snapshot.query),n=ft({limit:e.limit??200}),r=(0,P.useMemo)(()=>{let e=n.data?.sessions??[],r=yr(ze(e).filter(br),t),i=new Map(e.map(e=>[e.sessionId,e]));return r.map(e=>({session:e,runStatus:i.get(e.key)?.status===`running`?`running`:void 0}))},[t,n.data?.sessions]);return{isLoading:n.isLoading,items:r}}var Sr=(0,P.createContext)(null);function Cr({presenter:e,children:t}){return(0,I.jsx)(Sr.Provider,{value:e,children:t})}function wr(){let e=(0,P.useContext)(Sr);if(!e)throw Error(`usePresenter must be used inside ChatPresenterProvider`);return e}var Tr=e=>`[data-item-index="${e}"]`;function Er(e){let t=e.getItemSelector??Tr;(0,P.useEffect)(()=>{if(!e.isEnabled||e.itemCount===0)return;let n=e.containerRef.current;n&&n.querySelector(t(e.activeIndex))?.scrollIntoView({block:`nearest`,inline:`nearest`})},[t,e.activeIndex,e.containerRef,e.isEnabled,e.itemCount])}function Dr(){let e=(0,P.useRef)(null),[t,n]=(0,P.useState)(null);return(0,P.useEffect)(()=>{let t=e.current;if(!t||typeof ResizeObserver>`u`)return;let r=()=>{n(t.getBoundingClientRect().width)};r();let i=new ResizeObserver(()=>r());return i.observe(t),()=>i.disconnect()},[]),{elementRef:e,width:t}}function R(...e){return n(r(e))}var Or=P.forwardRef(({className:e,type:t,...n},r)=>(0,I.jsx)(`input`,{type:t,className:R(`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}));Or.displayName=`ChatInput`;var kr=Ut,Ar=Rt,jr=zt,Mr=P.forwardRef(({className:e,sideOffset:t=8,align:n=`start`,...r},i)=>(0,I.jsx)(Vt,{children:(0,I.jsx)(Lt,{ref:i,sideOffset:t,align:n,className:R(`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})}));Mr.displayName=Lt.displayName;var Nr=M,Pr=le,Fr=pe,Ir=P.forwardRef(({className:e,children:t,...n},r)=>(0,I.jsxs)(fe,{ref:r,className:R(`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,(0,I.jsx)(ee,{asChild:!0,children:(0,I.jsx)(T,{className:`h-4 w-4 opacity-50`})})]}));Ir.displayName=fe.displayName;var Lr=P.forwardRef(({className:e,...t},n)=>(0,I.jsx)(A,{ref:n,className:R(`flex cursor-default items-center justify-center py-1`,e),...t,children:(0,I.jsx)(w,{className:`h-4 w-4`})}));Lr.displayName=A.displayName;var Rr=P.forwardRef(({className:e,...t},n)=>(0,I.jsx)(j,{ref:n,className:R(`flex cursor-default items-center justify-center py-1`,e),...t,children:(0,I.jsx)(T,{className:`h-4 w-4`})}));Rr.displayName=j.displayName;var zr=P.forwardRef(({className:e,children:t,position:n=`popper`,...r},i)=>(0,I.jsx)(se,{children:(0,I.jsxs)(oe,{ref:i,className:R(`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:[(0,I.jsx)(Lr,{}),(0,I.jsx)(O,{className:R(`p-1`,n===`popper`&&`h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]`),children:t}),(0,I.jsx)(Rr,{})]})}));zr.displayName=oe.displayName;var Br=P.forwardRef(({className:e,...t},n)=>(0,I.jsx)(te,{ref:n,className:R(`px-2 py-1 text-[11px] font-semibold uppercase tracking-[0.08em] text-gray-500`,e),...t}));Br.displayName=te.displayName;var Vr=P.forwardRef(({className:e,children:t,...n},r)=>(0,I.jsxs)(ie,{ref:r,className:R(`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:[(0,I.jsx)(`span`,{className:`absolute right-2 flex h-3.5 w-3.5 items-center justify-center`,children:(0,I.jsx)(de,{children:(0,I.jsx)(re,{className:`h-4 w-4`})})}),(0,I.jsx)(k,{children:t})]}));Vr.displayName=ie.displayName;var Hr=P.forwardRef(({className:e,...t},n)=>(0,I.jsx)(E,{ref:n,className:R(`-mx-1 my-1 h-px bg-gray-100`,e),...t}));Hr.displayName=E.displayName;var Ur=Te,Wr=De,Gr=Ne,Kr=P.forwardRef(({className:e,sideOffset:t=4,...n},r)=>(0,I.jsx)(je,{children:(0,I.jsx)(ke,{ref:r,sideOffset:t,className:R(`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})}));Kr.displayName=ke.displayName;var qr={Popover:kr,PopoverAnchor:jr,PopoverContent:Mr,PopoverTrigger:Ar,Input:Or,Select:Nr,SelectContent:zr,SelectGroup:Pr,SelectItem:Vr,SelectLabel:Br,SelectSeparator:Hr,SelectTrigger:Ir,SelectValue:Fr,Tooltip:Wr,TooltipContent:Kr,TooltipProvider:Ur,TooltipTrigger:Gr},Jr=680,Yr=.82,Xr=560;function Zr(e){let{Popover:t,PopoverAnchor:n,PopoverContent:r}=qr,{elementRef:i,width:a}=Dr(),o=(0,P.useRef)(null),{isOpen:s,isLoading:c,items:l,activeIndex:u,activeItem:d,texts:f,onSelectItem:p,onOpenChange:m,onSetActiveIndex:h}=e,g=(0,P.useMemo)(()=>{if(a)return Math.min(a>Xr?a*Yr:a,Jr)},[a]);return Er({containerRef:o,activeIndex:u,itemCount:l.length,isEnabled:s&&!c,getItemSelector:e=>`[data-slash-index="${e}"]`}),(0,I.jsxs)(t,{open:s,onOpenChange:m,children:[(0,I.jsx)(n,{asChild:!0,children:(0,I.jsx)(`div`,{ref:i,className:`pointer-events-none absolute bottom-full left-3 right-3 h-0`})}),(0,I.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:e=>e.preventDefault(),style:g?{width:`${g}px`}:void 0,children:(0,I.jsxs)(`div`,{className:`grid min-h-[240px] grid-cols-[minmax(220px,300px)_minmax(0,1fr)]`,children:[(0,I.jsx)(`div`,{ref:o,role:`listbox`,"aria-label":f.slashSectionLabel,className:`custom-scrollbar max-h-[320px] overflow-y-auto border-r border-gray-200 p-2.5`,children:c?(0,I.jsx)(`div`,{className:`p-2 text-xs text-gray-500`,children:f.slashLoadingLabel}):(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(`div`,{className:`mb-2 px-2 text-[11px] font-semibold uppercase tracking-wide text-gray-500`,children:f.slashSectionLabel}),l.length===0?(0,I.jsx)(`div`,{className:`px-2 text-xs text-gray-400`,children:f.slashEmptyLabel}):(0,I.jsx)(`div`,{className:`space-y-1`,children:l.map((e,t)=>{let n=t===u;return(0,I.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":n,"data-slash-index":t,onMouseEnter:()=>h(t),onClick:()=>p(e),className:`flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left transition ${n?`bg-gray-100 text-gray-900`:`text-gray-700 hover:bg-gray-50`}`,children:[(0,I.jsx)(`span`,{className:`truncate text-xs font-semibold`,children:e.title}),(0,I.jsx)(`span`,{className:`truncate text-xs text-gray-500`,children:e.subtitle})]},e.key)})})]})}),(0,I.jsx)(`div`,{className:`min-w-0 p-2.5`,children:d?(0,I.jsxs)(`div`,{className:`space-y-3`,children:[(0,I.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,I.jsx)(`span`,{className:`inline-flex rounded-full bg-primary/10 px-2 py-0.5 text-[11px] font-semibold text-primary`,children:d.subtitle}),(0,I.jsx)(`span`,{className:`text-sm font-semibold text-gray-900`,children:d.title})]}),(0,I.jsx)(`p`,{className:`text-xs leading-5 text-gray-600`,children:d.description}),(0,I.jsx)(`div`,{className:`space-y-1`,children:d.detailLines.map(e=>(0,I.jsx)(`div`,{className:`min-w-0 break-all rounded-md bg-gray-50 px-2 py-1 text-[11px] leading-5 text-gray-600`,children:e},e))}),(0,I.jsx)(`div`,{className:`pt-1 text-[11px] text-gray-500`,children:f.slashSkillHintLabel})]}):(0,I.jsx)(`div`,{className:`text-xs text-gray-500`,children:f.slashHintLabel})})]})})]})}var Qr=g(`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`}}),$r=P.forwardRef(({className:e,variant:t,size:n,...r},i)=>(0,I.jsx)(`button`,{className:R(Qr({variant:t,size:n,className:e})),ref:i,...r}));$r.displayName=`ChatButton`;function ei(){return(0,I.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 ti(e){let{Tooltip:t,TooltipContent:n,TooltipProvider:r,TooltipTrigger:i}=qr;return(0,I.jsxs)(`div`,{className:`flex flex-col items-end gap-1`,children:[e.sendError?.trim()?(0,I.jsx)(`div`,{className:`max-w-[420px] text-right text-[11px] text-red-600`,children:e.sendError}):null,(0,I.jsx)(`div`,{className:`flex items-center gap-2`,children:e.isSending?e.canStopGeneration?(0,I.jsx)($r,{size:`icon`,variant:`outline`,className:`h-8 w-8 rounded-full`,"aria-label":e.stopButtonLabel,onClick:()=>void e.onStop(),disabled:e.stopDisabled,children:(0,I.jsx)(ei,{})}):(0,I.jsx)(r,{children:(0,I.jsxs)(t,{children:[(0,I.jsx)(i,{asChild:!0,children:(0,I.jsx)(`span`,{children:(0,I.jsx)($r,{size:`icon`,variant:`outline`,className:`h-8 w-8 rounded-full`,"aria-label":e.stopButtonLabel,disabled:!0,children:(0,I.jsx)(ei,{})})})}),(0,I.jsx)(n,{side:`top`,children:(0,I.jsx)(`p`,{className:`text-xs`,children:e.stopHint})})]})}):(0,I.jsx)($r,{size:`icon`,className:`h-8 w-8 rounded-full`,"aria-label":e.sendButtonLabel,onClick:()=>void e.onSend(),disabled:e.sendDisabled,children:(0,I.jsx)(Zt,{className:`h-5 w-5`})})})]})}function ni(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>[e.label,e.key,e.description].filter(e=>typeof e==`string`&&e.trim().length>0).join(` `).toLowerCase().includes(n)):e}function ri(e){let{Input:t,Popover:n,PopoverContent:r,PopoverTrigger:i}=qr,{picker:a}=e,o=(0,P.useRef)(null),s=(0,P.useId)(),[c,l]=(0,P.useState)(``),[u,d]=(0,P.useState)(0),f=(0,P.useMemo)(()=>new Set(a.selectedKeys),[a.selectedKeys]),p=a.selectedKeys.length,m=c.trim().length>0,h=(0,P.useMemo)(()=>{if(m)return null;let e=a.groups?.filter(e=>e.options.length>0)??[];return e.length>0?e:null},[m,a.groups]),g=(0,P.useMemo)(()=>h?h.flatMap(e=>e.options):ni(a.options,c),[h,a.options,c]);(0,P.useEffect)(()=>{d(0)},[c]),(0,P.useEffect)(()=>{d(e=>g.length===0?0:Math.min(e,g.length-1))},[g.length]),Er({containerRef:o,activeIndex:u,itemCount:g.length,isEnabled:g.length>0,getItemSelector:e=>`[data-skill-index="${e}"]`});let _=e=>{if(f.has(e)){a.onSelectedKeysChange(a.selectedKeys.filter(t=>t!==e));return}a.onSelectedKeysChange([...a.selectedKeys,e])},v=e=>{if(g.length!==0){if(e.key===`ArrowDown`){e.preventDefault(),d(e=>Math.min(e+1,g.length-1));return}if(e.key===`ArrowUp`){e.preventDefault(),d(e=>Math.max(e-1,0));return}if(e.key===`Enter`){e.preventDefault();let t=g[u];t&&_(t.key)}}};return(0,I.jsxs)(n,{children:[(0,I.jsx)(i,{asChild:!0,children:(0,I.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:[(0,I.jsx)(yt,{className:`h-4 w-4`}),(0,I.jsx)(`span`,{children:a.title}),p>0?(0,I.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:p}):null]})}),(0,I.jsxs)(r,{side:`top`,align:`start`,className:`w-[360px] p-0`,children:[(0,I.jsxs)(`div`,{className:`space-y-2 border-b border-gray-100 px-4 py-3`,children:[(0,I.jsx)(`div`,{className:`text-sm font-semibold text-gray-900`,children:a.title}),(0,I.jsxs)(`div`,{className:`relative`,children:[(0,I.jsx)(qe,{className:`pointer-events-none absolute left-3 top-2.5 h-3.5 w-3.5 text-gray-400`}),(0,I.jsx)(t,{value:c,onChange:e=>l(e.target.value),onKeyDown:v,placeholder:a.searchPlaceholder,role:`combobox`,"aria-controls":s,"aria-expanded":`true`,"aria-autocomplete":`list`,"aria-activedescendant":g[u]?`${s}-option-${u}`:void 0,className:`h-8 rounded-lg pl-8 text-xs`})]})]}),(0,I.jsx)(`div`,{ref:o,id:s,role:`listbox`,"aria-multiselectable":`true`,className:`custom-scrollbar max-h-[320px] overflow-y-auto`,children:a.isLoading?(0,I.jsx)(`div`,{className:`p-4 text-xs text-gray-500`,children:a.loadingLabel}):g.length===0?(0,I.jsx)(`div`,{className:`p-4 text-center text-xs text-gray-500`,children:a.emptyLabel}):(0,I.jsx)(`div`,{className:`py-1`,children:(()=>{let e=h??[{key:`all-skills`,options:g}],t=0;return e.map(e=>(0,I.jsxs)(`div`,{children:[e.label?(0,I.jsx)(`div`,{className:`px-4 pb-1 pt-2 text-[11px] font-semibold uppercase tracking-wide text-gray-500`,children:e.label}):null,e.options.map(e=>{let n=t;t+=1;let r=f.has(e.key),i=n===u;return(0,I.jsxs)(`button`,{type:`button`,id:`${s}-option-${n}`,role:`option`,"aria-selected":r,"data-skill-index":n,onClick:()=>_(e.key),onMouseEnter:()=>d(n),className:`flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors ${i?`bg-gray-50`:`hover:bg-gray-50`}`,children:[(0,I.jsx)(`div`,{className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-gray-100 text-gray-500`,children:(0,I.jsx)(gn,{className:`h-4 w-4`})}),(0,I.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,I.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,I.jsx)(`span`,{className:`truncate text-sm text-gray-900`,children:e.label}),e.badgeLabel?(0,I.jsx)(`span`,{className:`shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary`,children:e.badgeLabel}):null]}),(0,I.jsx)(`div`,{className:`mt-0.5 truncate text-xs text-gray-500`,children:e.description||e.key})]}),(0,I.jsx)(`div`,{className:`ml-3 shrink-0`,children:(0,I.jsx)(`span`,{className:r?`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:r?(0,I.jsx)(re,{className:`h-3 w-3`}):null})})]},e.key)})]},e.key))})()})}),a.manageHref&&a.manageLabel?(0,I.jsx)(`div`,{className:`border-t border-gray-100 px-4 py-2.5`,children:(0,I.jsxs)(`a`,{href:a.manageHref,className:`inline-flex items-center gap-1.5 text-xs font-medium text-primary transition-colors hover:text-primary/80`,children:[a.manageLabel,(0,I.jsx)(ge,{className:`h-3 w-3`})]})}):null]})]})}function ii({icon:e}){return e===`sparkles`?(0,I.jsx)(mt,{className:`h-3.5 w-3.5 shrink-0 text-primary`}):e===`brain`?(0,I.jsx)(Qt,{className:`h-3.5 w-3.5 shrink-0 text-gray-500`}):null}function ai({icon:e}){return e===`paperclip`?(0,I.jsx)(fn,{className:`h-4 w-4`}):(0,I.jsx)(ii,{icon:e})}function oi(e){return e===`model`?`min-w-[220px]`:e===`session-type`?`min-w-[140px]`:e===`thinking`?`min-w-[150px]`:``}function si(e){return e===`model`?`w-[320px]`:e===`session-type`?`w-[220px]`:e===`thinking`?`w-[180px]`:``}function ci({item:e}){let{Select:t,SelectContent:n,SelectGroup:r,SelectItem:i,SelectLabel:a,SelectSeparator:o,SelectTrigger:s,SelectValue:c}=qr,l=e.groups?.filter(e=>e.options.length>0)??(e.options.length>0?[{key:`${e.key}-default`,options:e.options}]:[]),u=l.some(e=>e.options.length>0);return(0,I.jsxs)(t,{value:e.value,onValueChange:e.onValueChange,disabled:e.disabled,children:[(0,I.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 ${oi(e.key)}`,children:e.selectedLabel?(0,I.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 text-left`,children:[(0,I.jsx)(ii,{icon:e.icon}),(0,I.jsx)(`span`,{className:`truncate text-xs font-semibold text-gray-700`,children:e.selectedLabel})]}):e.loading?(0,I.jsx)(`div`,{className:`h-3 w-24 animate-pulse rounded bg-gray-200`}):(0,I.jsx)(c,{placeholder:e.placeholder})}),(0,I.jsxs)(n,{className:si(e.key),children:[u?null:e.loading?(0,I.jsxs)(`div`,{className:`space-y-2 px-3 py-2`,children:[(0,I.jsx)(`div`,{className:`h-3 w-36 animate-pulse rounded bg-gray-200`}),(0,I.jsx)(`div`,{className:`h-3 w-28 animate-pulse rounded bg-gray-200`}),(0,I.jsx)(`div`,{className:`h-3 w-32 animate-pulse rounded bg-gray-200`})]}):e.emptyLabel?(0,I.jsx)(`div`,{className:`px-3 py-2 text-xs text-gray-500`,children:e.emptyLabel}):null,l.map((e,t)=>(0,I.jsxs)(`div`,{children:[t>0?(0,I.jsx)(o,{}):null,(0,I.jsxs)(r,{children:[e.label?(0,I.jsx)(a,{children:e.label}):null,e.options.map(e=>(0,I.jsx)(i,{value:e.value,className:`py-2`,children:e.description?(0,I.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-0.5`,children:[(0,I.jsx)(`span`,{className:`truncate text-xs font-semibold text-gray-800`,children:e.label}),(0,I.jsx)(`span`,{className:`truncate text-[11px] text-gray-500`,children:e.description})]}):(0,I.jsx)(`span`,{className:`truncate text-xs font-semibold text-gray-800`,children:e.label})},e.value))]})]},e.key))]})]})}function li(e){let{Tooltip:t,TooltipContent:n,TooltipProvider:r,TooltipTrigger:i}=qr;return(0,I.jsxs)(`div`,{className:`flex items-center justify-between px-3 pb-3`,children:[(0,I.jsxs)(`div`,{className:`flex items-center gap-1`,children:[e.skillPicker?(0,I.jsx)(ri,{picker:e.skillPicker}):null,e.selects.map(e=>(0,I.jsx)(ci,{item:e},e.key)),e.accessories?.map(e=>{let a=(0,I.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 ${e.iconOnly?`h-8 w-8 justify-center px-0`:`gap-1.5 px-3`}`,onClick:e.onClick,disabled:e.disabled,"aria-label":e.label,children:[(0,I.jsx)(ai,{icon:e.icon}),e.iconOnly?null:(0,I.jsx)(`span`,{children:e.label})]});return e.tooltip?(0,I.jsx)(r,{children:(0,I.jsxs)(t,{children:[(0,I.jsx)(i,{asChild:!0,children:e.disabled?(0,I.jsx)(`span`,{className:`inline-flex`,children:a}):a}),(0,I.jsx)(n,{side:`top`,children:(0,I.jsx)(`p`,{className:`text-xs`,children:e.tooltip})})]})},e.key):(0,I.jsx)(`div`,{children:a},e.key)})]}),(0,I.jsx)(ti,{...e.actions})]})}function ui(){return`composer-${Math.random().toString(36).slice(2,10)}`}function di(e=``){return{id:ui(),type:`text`,text:e}}function fi(e){return{id:ui(),type:`token`,tokenKind:e.tokenKind,tokenKey:e.tokenKey,label:e.label}}function pi(e){return e.type===`text`?e.text.length:1}function mi(){return[di(``)]}function hi(e){return[di(e)]}function gi(e){let t=[];for(let n of e){if(n.type===`text`){if(n.text.length===0)continue;let e=t[t.length-1];if(e?.type===`text`){t[t.length-1]={...e,text:e.text+n.text};continue}}t.push(n)}return t.length===0?mi():t}function _i(e){return e.map(e=>e.type===`text`?e.text:``).join(``)}function vi(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function yi(e,t){let n=[],r=new Set;for(let i of e)i.type!==`token`||i.tokenKind!==t||r.has(i.tokenKey)||(r.add(i.tokenKey),n.push(i.tokenKey));return n}function bi(e,t,n,r){let i=Math.max(0,n-t),a=Math.max(0,t+e.text.length-r),o=[];return i>0&&o.push({...e,text:e.text.slice(0,i)}),a>0&&o.push({...e,text:e.text.slice(e.text.length-a)}),o}function xi(e,t,n,r){return t<=n||e>=r}function Si(e,t,n,r,i){return!n&&r>=i?(e.push(...t),!0):n}function Ci(e,t,n,r,i,a,o){let s=bi(t,n,r,i);s[0]&&e.push(s[0]);let c=o;return c||=(e.push(...a),!0),s[1]&&e.push(s[1]),c}function wi(e,t,n,r,i,a){return!r&&i<=a?(e.push(...n),!0):(e.push(t),r)}function Ti(e,t,n,r){let i=Math.max(0,t),a=Math.max(i,n),o=[],s=0,c=!1;for(let t of e){let e=pi(t),n=s,l=s+e;if(xi(n,l,i,a)){c=Si(o,r,c,n,a),o.push(t),s=l;continue}c=t.type===`text`?Ci(o,t,n,i,a,r,c):wi(o,t,r,c,i,n),s=l}return c||o.push(...r),gi(o)}function Ei(e,t){return gi(e.filter(e=>e.type!==`token`||!t(e)))}function Di(e,t){if(!t||t.start!==t.end)return null;let n=_i(e),r=t.end,i=n.slice(0,r),a=/(?:^|\s)\/([^\s\uFFFC]*)$/.exec(i);if(!a)return null;let o=r-a[0].length+(a[0].startsWith(`/`)?0:1);return{query:(a[1]??``).trim().toLowerCase(),start:o,end:r}}function Oi(e,t,n){return e?e.start<n&&e.end>t:!1}function ki(e){let t=new Map,n=0;for(let r of e)t.set(r.id,n),n+=pi(r);return t}function Ai(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 ji(e,t,n){if(e instanceof HTMLElement){let t=e.dataset.composerNodeId;if(t)return n.find(e=>e.id===t)}return n[t]}function Mi(e,t,n){let r=0;for(let i=0;i<n;i+=1){let n=ji(e.childNodes[i],i,t);n&&(r+=pi(n))}return r}function Ni(e,t,n,r){let i=Ai(e,t),a=Mi(e,r,i),o=r[i];return o?.type===`text`?a+Math.min(n,o.text.length):a+Math.min(n,t.textContent?.length??0)}function Pi(e,t,n,r,i){return n.type===`text`?e.nodeType===Node.TEXT_NODE?r+Math.min(t,n.text.length):e===i?r+(t>0?n.text.length:0):r+n.text.length:e===i?r+(t>0?1:0):r+1}function Fi(e,t,n,r,i){if(t===e)return Mi(e,r,n);if(t.nodeType===Node.TEXT_NODE&&t.parentNode===e)return Ni(e,t,n,r);let a=t instanceof HTMLElement?t.closest(`[data-composer-node-id]`):t.parentElement?.closest(`[data-composer-node-id]`)??null;if(!(a instanceof HTMLElement))return Fi(e,e,Ai(e,t),r,i);let o=a.dataset.composerNodeId;if(!o)return 0;let s=r.find(e=>e.id===o),c=i.get(o)??0;return s?Pi(t,n,s,c,a):c}function Ii(e,t){let n=window.getSelection();if(!n||n.rangeCount===0)return null;let r=n.getRangeAt(0);if(!e.contains(r.startContainer)||!e.contains(r.endContainer))return null;let i=ki(t),a=Fi(e,r.startContainer,r.startOffset,t,i),o=Fi(e,r.endContainer,r.endOffset,t,i);return{start:Math.min(a,o),end:Math.max(a,o)}}function Li(e,t,n){if(!n)return;let r=window.getSelection();if(!r)return;let i=n=>{let r=0;for(let i=0;i<t.length;i+=1){let a=t[i],o=pi(a),s=r,c=r+o,l=e.childNodes[i];if(!l){r=c;continue}if(a.type===`text`){if(n<=c)return{container:l.firstChild??l,offset:Math.max(0,Math.min(n-s,a.text.length))}}else{if(n<=s)return{container:e,offset:i};if(n<=c)return{container:e,offset:i+1}}r=c}return{container:e,offset:e.childNodes.length}},a=i(n.start),o=i(n.end),s=document.createRange();s.setStart(a.container,a.offset),s.setEnd(o.container,o.offset),r.removeAllRanges(),r.addRange(s)}function Ri(e){let t=[];for(let n of Array.from(e.childNodes)){if(n.nodeType===Node.TEXT_NODE){t.push(di(n.textContent??``));continue}if(!(n instanceof HTMLElement))continue;if(n.dataset.composerNodeType===`token`){let e=n.dataset.composerTokenKind,r=n.dataset.composerTokenKey,i=n.dataset.composerLabel;e&&r&&i&&t.push({id:n.dataset.composerNodeId??fi({tokenKind:e,tokenKey:r,label:i}).id,type:`token`,tokenKind:e,tokenKey:r,label:i});continue}let e=n.textContent??``;t.push({id:n.dataset.composerNodeId??di(e).id,type:`text`,text:e})}return gi(t)}function zi(e){let t=Ri(e);return{nodes:t,selection:Ii(e,t)}}var Bi=class{constructor(){this.nodes=mi(),this.selection=null,this.sync=(e,t)=>(this.nodes=gi(e),this.selection=t,this.getSnapshot()),this.setSelection=e=>(this.selection=e,this.getSnapshot()),this.replaceDocument=(e,t)=>(this.nodes=gi(e),this.selection=t,this.getSnapshot()),this.insertText=e=>{let t=this.selection??{start:0,end:0};this.nodes=Ti(this.nodes,t.start,t.end,[di(e)]);let n=t.start+e.length;return this.selection={start:n,end:n},this.getSnapshot()},this.insertFileToken=(e,t)=>this.insertToken(`file`,e,t),this.insertSkillToken=(e,t)=>this.getSelectedSkillKeys().includes(e)?this.getSnapshot():this.insertToken(`skill`,e,t,this.getSlashTrigger()),this.syncSelectedSkills=(e,t)=>{let n=this.getSelectedSkillKeys(),r=new Map(t.map(e=>[e.key,e])),i=e.find(e=>!n.includes(e));if(i){let e=r.get(i);return this.insertSkillToken(i,e?.label??i)}let a=n.find(t=>!e.includes(t));return a&&(this.nodes=Ei(this.nodes,e=>e.tokenKind===`skill`&&e.tokenKey===a)),this.getSnapshot()},this.deleteContent=e=>{let t=this.getDocumentLength(),n=this.selection??{start:t,end:t},r=n.start,i=n.end;if(n.start===n.end)if(e===`backward`&&n.start>0)r=n.start-1;else if(e===`forward`)i=n.end+1;else return this.getSnapshot();return this.nodes=Ti(this.nodes,r,i,[]),this.selection={start:r,end:r},this.getSnapshot()},this.getSnapshot=()=>({nodes:this.nodes,selection:this.selection,nodeStartMap:ki(this.nodes),documentLength:this.getDocumentLength(),selectedSkillKeys:this.getSelectedSkillKeys(),slashTrigger:this.getSlashTrigger()}),this.getDocumentLength=()=>this.nodes.reduce((e,t)=>e+pi(t),0),this.getSelectedSkillKeys=()=>yi(this.nodes,`skill`),this.insertToken=(e,t,n,r=null)=>{let i=this.getDocumentLength(),a=r?.start??this.selection?.start??i,o=r?.end??this.selection?.end??a;return this.nodes=Ti(this.nodes,a,o,[fi({tokenKind:e,tokenKey:t,label:n})]),this.selection={start:a+1,end:a+1},this.getSnapshot()},this.getSlashTrigger=()=>Di(this.nodes,this.selection)}};function Vi(e){let{key:t,shiftKey:n,isComposing:r,isSlashMenuOpen:i,slashItemCount:a,activeSlashIndex:o,isSending:s,canStopGeneration:c}=e;if(t===`Enter`&&!n&&s)return{type:`consume`};if(i&&a>0){if(t===`ArrowDown`)return{type:`move-slash-index`,index:(o+1)%a};if(t===`ArrowUp`)return{type:`move-slash-index`,index:(o-1+a)%a};if(t===`Enter`&&!n||t===`Tab`)return{type:`insert-active-slash-item`}}return t===`Escape`?i?{type:`close-slash`}:s&&c?{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`}}var Hi=`http://www.w3.org/2000/svg`,Ui=class{constructor(){this.render=(e,t)=>{if(!e)return;let n=document.createDocumentFragment();for(let e of t.nodes){let r=e.type===`text`?this.createTextNodeElement(e):this.createTokenNodeElement(e,t.selectedRange,t.nodeStartMap);r&&n.appendChild(r)}e.replaceChildren(n)},this.createTextNodeElement=e=>{if(e.text.length===0)return null;let t=document.createElement(`span`);return t.dataset.composerNodeId=e.id,t.dataset.composerNodeType=`text`,t.textContent=e.text,t},this.createTokenNodeElement=(e,t,n)=>{let r=n.get(e.id)??0,i=Oi(t,r,r+1),a=document.createElement(`span`);a.contentEditable=`false`,a.dataset.composerNodeId=e.id,a.dataset.composerNodeType=`token`,a.dataset.composerTokenKind=e.tokenKind,a.dataset.composerTokenKey=e.tokenKey,a.dataset.composerLabel=e.label,a.title=e.label,a.className=this.buildTokenClassName(e.tokenKind,i),a.append(this.createTokenIcon(e.tokenKind));let o=document.createElement(`span`);return o.className=e.tokenKind===`file`?`min-w-0 flex-1 truncate text-[12px] font-medium text-slate-700`:`truncate`,o.textContent=e.label,a.append(o),a},this.buildTokenClassName=(e,t)=>e===`file`?[`mx-[2px]`,`inline-flex`,`h-7`,`max-w-[min(100%,17rem)]`,`items-center`,`gap-1.5`,`rounded-lg`,`border`,`px-2`,`align-baseline`,`transition-[border-color,background-color,box-shadow,color]`,`duration-150`,t?`border-slate-300 bg-slate-100 text-slate-800 shadow-[0_0_0_2px_rgba(148,163,184,0.14)]`:`border-slate-200/80 bg-slate-50 text-slate-700`].join(` `):[`mx-[2px]`,`inline-flex`,`h-7`,`max-w-full`,`items-center`,`gap-1.5`,`rounded-lg`,`border`,`px-2`,`align-baseline`,`text-[11px]`,`font-medium`,`transition`,t?`border-primary/30 bg-primary/18 text-primary`:`border-primary/12 bg-primary/8 text-primary`].join(` `),this.createTokenIcon=e=>{let t=document.createElement(`span`);return t.className=e===`file`?`inline-flex h-4.5 w-4.5 shrink-0 items-center justify-center rounded-md bg-white text-slate-500 ring-1 ring-black/5`:`inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center text-primary/70`,t.append(e===`file`?this.createFileIcon():this.createSkillIcon()),t},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:`M3.25 4.25A1.5 1.5 0 0 1 4.75 2.75h6.5a1.5 1.5 0 0 1 1.5 1.5v7.5a1.5 1.5 0 0 1-1.5 1.5h-6.5a1.5 1.5 0 0 1-1.5-1.5v-7.5Z`}},{tag:`path`,attrs:{d:`m4.75 10 2.25-2.5 1.75 1.75 1.25-1.25 2 2`}},{tag:`path`,attrs:{d:`M9.75 6.25h.01`}}]),this.createSvgIcon=e=>{let t=document.createElementNS(Hi,`svg`);t.setAttribute(`viewBox`,`0 0 16 16`),t.setAttribute(`fill`,`none`),t.setAttribute(`stroke`,`currentColor`),t.setAttribute(`stroke-width`,`1.25`),t.setAttribute(`stroke-linecap`,`round`),t.setAttribute(`stroke-linejoin`,`round`),t.setAttribute(`aria-hidden`,`true`),t.setAttribute(`class`,`h-3 w-3`);for(let n of e){let e=document.createElementNS(Hi,n.tag);for(let[t,r]of Object.entries(n.attrs))e.setAttribute(t,r);t.append(e)}return t}}},Wi=188,Gi=class{constructor(e){this.controller=e,this.surfaceRenderer=new Ui,this.sync=(e,t)=>this.controller.sync(e,t),this.syncSelectionFromRoot=e=>this.controller.setSelection(Ii(e,this.controller.getSnapshot().nodes)),this.restoreSelectionIfFocused=(e,t)=>{!e||document.activeElement!==e||Li(e,this.controller.getSnapshot().nodes,t)},this.syncViewport=e=>{e&&(e.style.maxHeight=`${Wi}px`,e.style.overflowY=e.scrollHeight>Wi?`auto`:`hidden`)},this.renderSurface=e=>{this.surfaceRenderer.render(e.root,{nodes:e.snapshot.nodes,selectedRange:e.selectedRange,nodeStartMap:e.snapshot.nodeStartMap})},this.insertSlashItem=(e,t)=>{e.value&&t(this.controller.insertSkillToken(e.value,e.title))},this.syncSelectedSkills=(e,t,n)=>{n(this.controller.syncSelectedSkills(e,t))},this.handleBeforeInput=e=>{let{event:t,disabled:n,isComposing:r,commitSnapshot:i}=e,a=t.nativeEvent;n||r||a.isComposing||!(a.inputType===`insertText`||a.inputType===`insertReplacementText`)||!a.data||(t.preventDefault(),i(this.controller.insertText(a.data)))},this.handleInput=e=>{let{event:t,isComposing:n,commitSnapshot:r}=e,i=t.nativeEvent;if(n||i.isComposing)return;let a=t.currentTarget,o=zi(a);r(this.controller.replaceDocument(o.nodes,o.selection))},this.handleCompositionEnd=e=>{let{event:t,commitSnapshot:n}=e,r=t.currentTarget,i=zi(r);n(this.controller.replaceDocument(i.nodes,i.selection))},this.handleKeyDown=e=>{let{event:t,slashItems:n,activeSlashIndex:r,activeSlashItem:i,actions:a,commitSnapshot:o,insertSkillToken:s,onSlashItemSelect:c,onSlashActiveIndexChange:l,onSlashQueryChange:u,onSlashOpenChange:d}=e,f=this.controller.getSnapshot(),p=Vi({key:t.key,shiftKey:t.shiftKey,isComposing:t.nativeEvent.isComposing,isSlashMenuOpen:f.slashTrigger!==null,slashItemCount:n.length,activeSlashIndex:r,isSending:a.isSending,canStopGeneration:a.canStopGeneration});p.type!==`noop`&&(t.preventDefault(),this.applyKeyboardAction({action:p,activeSlashItem:i,actions:a,commitSnapshot:o,insertSkillToken:s,onSlashItemSelect:c,onSlashActiveIndexChange:l,onSlashQueryChange:u,onSlashOpenChange:d}))},this.handlePaste=e=>{let{event:t,onFilesAdd:n,commitSnapshot:r}=e,i=Array.from(t.clipboardData.files??[]);if(i.length>0&&n){t.preventDefault(),n(i);return}let a=t.clipboardData.getData(`text/plain`);a&&(t.preventDefault(),r(this.controller.insertText(a)))},this.handleBlur=e=>{let{clearSelectedRange:t,onSlashQueryChange:n,onSlashOpenChange:r}=e;t(),n?.(null),r(!1)},this.applyKeyboardAction=e=>{let{action:t,activeSlashItem:n,actions:r,commitSnapshot:i,insertSkillToken:a,onSlashItemSelect:o,onSlashActiveIndexChange:s,onSlashQueryChange:c,onSlashOpenChange:l}=e;switch(t.type){case`move-slash-index`:s(t.index);return;case`insert-active-slash-item`:if(!n)return;o?.(n),a(n.value??n.key,n.title);return;case`close-slash`:c?.(null),l(!1);return;case`consume`:return;case`stop-generation`:r.onStop();return;case`insert-line-break`:i(this.controller.insertText(`
2
2
  `));return;case`send-message`:r.onSend();return;case`delete-content`:i(this.controller.deleteContent(t.direction));return;case`noop`:return}}}},Ki=class{constructor(){this.controller=new Bi,this.viewController=new Gi(this.controller),this.rootElement=null,this.selection=null,this.selectedRange=null,this.snapshot=this.controller.getSnapshot(),this.config=null,this.isComposing=!1,this.bindRootElement=e=>{this.rootElement=e},this.update=e=>(this.config=e,this.snapshot=this.viewController.sync(e.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:e=>{this.config?.onSlashItemSelect?.(e),this.viewController.insertSlashItem(e,this.commitSnapshot)},insertFileToken:(e,t)=>{this.commitSnapshot(this.controller.insertFileToken(e,t)),this.focusComposerSoon()},insertFileTokens:e=>{let t=null;for(let n of e)t=this.controller.insertFileToken(n.tokenKey,n.label);t&&(this.commitSnapshot(t),this.focusComposerSoon())},focusComposer:()=>{this.focusComposer()},syncSelectedSkills:(e,t)=>{this.viewController.syncSelectedSkills(e,t,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;let e=this.viewController.syncSelectionFromRoot(this.rootElement);this.selection=e.selection,this.selectedRange=e.selection,this.syncSlashState(e),this.requestRender()},this.handleBeforeInput=e=>{this.viewController.handleBeforeInput({event:e,disabled:this.requireConfig().disabled,isComposing:this.isComposing,commitSnapshot:this.commitSnapshot})},this.handleInput=e=>{this.viewController.handleInput({event:e,isComposing:this.isComposing,commitSnapshot:this.commitSnapshot})},this.handleCompositionStart=()=>{this.isComposing=!0},this.handleCompositionEnd=e=>{this.isComposing=!1,this.viewController.handleCompositionEnd({event:e,commitSnapshot:this.commitSnapshot})},this.handleKeyDown=e=>{let t=this.requireConfig();if(this.rootElement&&!this.isComposing){let e=this.viewController.syncSelectionFromRoot(this.rootElement);this.selection=e.selection,this.selectedRange=e.selection,this.snapshot=e}let n=t.slashItems[t.activeSlashIndex]??null;this.viewController.handleKeyDown({event:e,slashItems:t.slashItems,activeSlashIndex:t.activeSlashIndex,activeSlashItem:n,actions:t.actions,commitSnapshot:this.commitSnapshot,insertSkillToken:this.insertSkillToken,onSlashItemSelect:t.onSlashItemSelect,onSlashActiveIndexChange:t.onSlashActiveIndexChange,onSlashQueryChange:t.onSlashQueryChange,onSlashOpenChange:t.onSlashOpenChange})},this.handlePaste=e=>{this.viewController.handlePaste({event:e,onFilesAdd:this.requireConfig().onFilesAdd,commitSnapshot:this.commitSnapshot})},this.handleBlur=()=>{let e=this.requireConfig();this.isComposing=!1,this.viewController.handleBlur({clearSelectedRange:this.clearSelectedRange,onSlashQueryChange:e.onSlashQueryChange,onSlashOpenChange:e.onSlashOpenChange})},this.setSelectedRange=e=>{this.selectedRange=e,this.selection=e,this.requestRender()},this.clearSelectedRange=()=>{this.selectedRange=null,this.requestRender()},this.commitSnapshot=e=>{let t=this.requireConfig();this.selection=e.selection,this.selectedRange=e.selection,this.snapshot=e,t.onNodesChange(e.nodes),this.syncSlashState(e)},this.insertSkillToken=(e,t)=>{this.commitSnapshot(this.controller.insertSkillToken(e,t))},this.syncSlashState=e=>{let t=this.requireConfig();t.onSlashTriggerChange?.(e.slashTrigger),t.onSlashQueryChange?.(e.slashTrigger?.query??null),t.onSlashOpenChange(e.slashTrigger!==null)},this.requestRender=()=>{this.requireConfig().requestRender()},this.focusComposerSoon=()=>{if(typeof requestAnimationFrame==`function`){requestAnimationFrame(()=>this.focusComposer());return}this.focusComposer()},this.focusComposer=()=>{if(!this.rootElement)return;let e=this.selection;this.rootElement.focus();let t=()=>{this.rootElement&&(this.selection=e,this.selectedRange=e,this.viewController.restoreSelectionIfFocused(this.rootElement,e))};if(typeof requestAnimationFrame==`function`){requestAnimationFrame(t);return}t()},this.requireConfig=()=>{if(!this.config)throw Error(`ChatComposerRuntime is not configured.`);return this.config}}},qi=(0,P.forwardRef)(function(e,t){let{nodes:n,placeholder:r,disabled:i,slashItems:a,onSlashItemSelect:o,actions:s,onNodesChange:c,onFilesAdd:l,onSlashQueryChange:u,onSlashTriggerChange:d,onSlashOpenChange:f,onSlashActiveIndexChange:p,activeSlashIndex:m}=e,[h,g]=(0,P.useState)(0),[_]=(0,P.useState)(()=>new Ki),{snapshot:v,bindRootElement:y,handleBeforeInput:b,handleInput:x,handleCompositionStart:S,handleCompositionEnd:C,handleKeyDown:w,handlePaste:T,handleBlur:E,syncSelectionState:D,imperativeHandle:O}=_.update({nodes:n,disabled:i,slashItems:a,onSlashItemSelect:o,actions:s,onNodesChange:c,onFilesAdd:l,onSlashQueryChange:u,onSlashTriggerChange:d,onSlashOpenChange:f,onSlashActiveIndexChange:p,activeSlashIndex:m,requestRender:()=>g(e=>e+1)});return(0,P.useImperativeHandle)(t,()=>O,[O]),(0,P.useLayoutEffect)(()=>{_.renderSurface(),_.restoreDomAfterCommit(),_.syncViewport()},[_,v.nodes,v.nodeStartMap,h]),(0,I.jsx)(`div`,{className:`px-4 py-2.5`,children:(0,I.jsx)(`div`,{className:`min-h-[60px]`,children:(0,I.jsx)(`div`,{ref:y,contentEditable:!i,suppressContentEditableWarning:!0,role:`textbox`,"aria-multiline":`true`,"data-placeholder":r,onBeforeInput:b,onInput:x,onCompositionStart:S,onCompositionEnd:C,onKeyDown:w,onKeyUp:D,onMouseUp:D,onFocus:D,onBlur:E,onPaste:T,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 Ji({hint:e}){return e?e.loading?(0,I.jsx)(`div`,{className:`px-4 pb-2`,children:(0,I.jsxs)(`div`,{className:`inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-gray-50 px-3 py-2`,children:[(0,I.jsx)(`span`,{className:`h-3 w-28 animate-pulse rounded bg-gray-200`}),(0,I.jsx)(`span`,{className:`h-3 w-16 animate-pulse rounded bg-gray-200`})]})}):(0,I.jsx)(`div`,{className:`px-4 pb-2`,children:(0,I.jsxs)(`div`,{className:`inline-flex items-center gap-2 rounded-lg px-3 py-1.5 text-xs ${e.tone===`warning`?`border-amber-200 bg-amber-50 text-amber-800`:`border-gray-200 bg-gray-50 text-gray-700`}`,children:[e.text?(0,I.jsx)(`span`,{children:e.text}):null,e.actionLabel&&e.onAction?(0,I.jsx)(`button`,{type:`button`,onClick:e.onAction,className:`font-semibold underline-offset-2 hover:underline`,children:e.actionLabel}):null]})}):null}var Yi=(0,P.forwardRef)(function(e,t){let n=(0,P.useRef)(null),[r,i]=(0,P.useState)(null),[a,o]=(0,P.useState)(0),[s,c]=(0,P.useState)(null),[l,u]=(0,P.useState)(null),d=s!==null&&l!==s,f=e.slashMenu.items[a]??null;(0,P.useEffect)(()=>{o(t=>e.slashMenu.items.length===0?0:Math.min(t,e.slashMenu.items.length-1))},[e.slashMenu.items.length]),(0,P.useEffect)(()=>{r!==null&&o(0)},[r]),(0,P.useEffect)(()=>{s===null&&l!==null&&u(null)},[s,l]);let p=(0,P.useMemo)(()=>e.toolbar.skillPicker?{...e.toolbar,skillPicker:{...e.toolbar.skillPicker,onSelectedKeysChange:t=>{n.current?.syncSelectedSkills(t,e.toolbar.skillPicker?.options??[])}}}:e.toolbar,[e.toolbar]);return(0,P.useImperativeHandle)(t,()=>({insertFileToken:(e,t)=>n.current?.insertFileToken(e,t),insertFileTokens:e=>n.current?.insertFileTokens(e),focusComposer:()=>n.current?.focusComposer()}),[]),(0,I.jsx)(`div`,{className:`border-t border-gray-200/80 bg-white p-4`,children:(0,I.jsx)(`div`,{className:`mx-auto w-full max-w-[min(1120px,100%)]`,children:(0,I.jsxs)(`div`,{className:`overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-card`,children:[(0,I.jsxs)(`div`,{className:`relative`,children:[(0,I.jsx)(qi,{ref:n,nodes:e.composer.nodes,placeholder:e.composer.placeholder,disabled:e.composer.disabled,slashItems:e.slashMenu.items,onSlashItemSelect:e.slashMenu.onSelectItem,actions:e.toolbar.actions,activeSlashIndex:a,onNodesChange:e.composer.onNodesChange,onFilesAdd:e.composer.onFilesAdd,onSlashQueryChange:t=>{i(t),e.composer.onSlashQueryChange?.(t)},onSlashTriggerChange:e=>{c(e?.start??null)},onSlashOpenChange:e=>{!e&&s!==null&&u(s)},onSlashActiveIndexChange:o}),(0,I.jsx)(Zr,{isOpen:d,isLoading:e.slashMenu.isLoading,items:e.slashMenu.items,activeIndex:a,activeItem:f,texts:e.slashMenu.texts,onSelectItem:e=>{u(null),n.current?.insertSlashItem(e)},onOpenChange:e=>{!e&&s!==null&&u(s)},onSetActiveIndex:o})]}),(0,I.jsx)(Ji,{hint:e.hint}),(0,I.jsx)(li,{...p})]})})})});Yi.displayName=`ChatInputBar`;function Xi({role:e}){return e===`user`?(0,I.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:(0,I.jsx)(Ke,{className:`h-4 w-4`})}):e===`tool`?(0,I.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:(0,I.jsx)(Dt,{className:`h-4 w-4`})}):(0,I.jsx)(`div`,{"data-testid":`chat-message-avatar-assistant`,className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-gradient-to-b from-gray-700 to-gray-950 text-white shadow-md ring-1 ring-inset ring-white/20`,children:(0,I.jsx)(vt,{className:`h-[18px] w-[18px] text-white/95`,strokeWidth:2.5})})}function Zi(e,t){let n=t||{};return(e[e.length-1]===``?[...e,``]:e).join((n.padRight?` `:``)+`,`+(n.padLeft===!1?``:` `)).trim()}var Qi=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,$i=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,ea={};function ta(e,t){return((t||ea).jsx?$i:Qi).test(e)}var na=/[ \t\n\f\r]/g;function ra(e){return typeof e==`object`?e.type===`text`?ia(e.value):!1:ia(e)}function ia(e){return e.replace(na,``)===``}var aa=class{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}};aa.prototype.normal={},aa.prototype.property={},aa.prototype.space=void 0;function oa(e,t){let n={},r={};for(let t of e)Object.assign(n,t.property),Object.assign(r,t.normal);return new aa(n,r,t)}function sa(e){return e.toLowerCase()}var z=class{constructor(e,t){this.attribute=t,this.property=e}};z.prototype.attribute=``,z.prototype.booleanish=!1,z.prototype.boolean=!1,z.prototype.commaOrSpaceSeparated=!1,z.prototype.commaSeparated=!1,z.prototype.defined=!1,z.prototype.mustUseProperty=!1,z.prototype.number=!1,z.prototype.overloadedBoolean=!1,z.prototype.property=``,z.prototype.spaceSeparated=!1,z.prototype.space=void 0;var ca=i({boolean:()=>B,booleanish:()=>V,commaOrSpaceSeparated:()=>fa,commaSeparated:()=>da,number:()=>H,overloadedBoolean:()=>ua,spaceSeparated:()=>U}),la=0,B=pa(),V=pa(),ua=pa(),H=pa(),U=pa(),da=pa(),fa=pa();function pa(){return 2**++la}var ma=Object.keys(ca),ha=class extends z{constructor(e,t,n,r){let i=-1;if(super(e,t),ga(this,`space`,r),typeof n==`number`)for(;++i<ma.length;){let e=ma[i];ga(this,ma[i],(n&ca[e])===ca[e])}}};ha.prototype.defined=!0;function ga(e,t,n){n&&(e[t]=n)}function _a(e){let t={},n={};for(let[r,i]of Object.entries(e.properties)){let a=new ha(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(a.mustUseProperty=!0),t[r]=a,n[sa(r)]=r,n[sa(a.attribute)]=r}return new aa(t,n,e.space)}var va=_a({properties:{ariaActiveDescendant:null,ariaAtomic:V,ariaAutoComplete:null,ariaBusy:V,ariaChecked:V,ariaColCount:H,ariaColIndex:H,ariaColSpan:H,ariaControls:U,ariaCurrent:null,ariaDescribedBy:U,ariaDetails:null,ariaDisabled:V,ariaDropEffect:U,ariaErrorMessage:null,ariaExpanded:V,ariaFlowTo:U,ariaGrabbed:V,ariaHasPopup:null,ariaHidden:V,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:U,ariaLevel:H,ariaLive:null,ariaModal:V,ariaMultiLine:V,ariaMultiSelectable:V,ariaOrientation:null,ariaOwns:U,ariaPlaceholder:null,ariaPosInSet:H,ariaPressed:V,ariaReadOnly:V,ariaRelevant:null,ariaRequired:V,ariaRoleDescription:U,ariaRowCount:H,ariaRowIndex:H,ariaRowSpan:H,ariaSelected:V,ariaSetSize:H,ariaSort:null,ariaValueMax:H,ariaValueMin:H,ariaValueNow:H,ariaValueText:null,role:null},transform(e,t){return t===`role`?t:`aria-`+t.slice(4).toLowerCase()}});function ya(e,t){return t in e?e[t]:t}function ba(e,t){return ya(e,t.toLowerCase())}var xa=_a({attributes:{acceptcharset:`accept-charset`,classname:`class`,htmlfor:`for`,httpequiv:`http-equiv`},mustUseProperty:[`checked`,`multiple`,`muted`,`selected`],properties:{abbr:null,accept:da,acceptCharset:U,accessKey:U,action:null,allow:null,allowFullScreen:B,allowPaymentRequest:B,allowUserMedia:B,alt:null,as:null,async:B,autoCapitalize:null,autoComplete:U,autoFocus:B,autoPlay:B,blocking:U,capture:null,charSet:null,checked:B,cite:null,className:U,cols:H,colSpan:null,content:null,contentEditable:V,controls:B,controlsList:U,coords:H|da,crossOrigin:null,data:null,dateTime:null,decoding:null,default:B,defer:B,dir:null,dirName:null,disabled:B,download:ua,draggable:V,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:B,formTarget:null,headers:U,height:H,hidden:ua,high:H,href:null,hrefLang:null,htmlFor:U,httpEquiv:U,id:null,imageSizes:null,imageSrcSet:null,inert:B,inputMode:null,integrity:null,is:null,isMap:B,itemId:null,itemProp:U,itemRef:U,itemScope:B,itemType:U,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:B,low:H,manifest:null,max:null,maxLength:H,media:null,method:null,min:null,minLength:H,multiple:B,muted:B,name:null,nonce:null,noModule:B,noValidate:B,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:B,optimum:H,pattern:null,ping:U,placeholder:null,playsInline:B,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:B,referrerPolicy:null,rel:U,required:B,reversed:B,rows:H,rowSpan:H,sandbox:U,scope:null,scoped:B,seamless:B,selected:B,shadowRootClonable:B,shadowRootDelegatesFocus:B,shadowRootMode:null,shape:null,size:H,sizes:null,slot:null,span:H,spellCheck:V,src:null,srcDoc:null,srcLang:null,srcSet:null,start:H,step:null,style:null,tabIndex:H,target:null,title:null,translate:null,type:null,typeMustMatch:B,useMap:null,value:V,width:H,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:U,axis:null,background:null,bgColor:null,border:H,borderColor:null,bottomMargin:H,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:B,declare:B,event:null,face:null,frame:null,frameBorder:null,hSpace:H,leftMargin:H,link:null,longDesc:null,lowSrc:null,marginHeight:H,marginWidth:H,noResize:B,noHref:B,noShade:B,noWrap:B,object:null,profile:null,prompt:null,rev:null,rightMargin:H,rules:null,scheme:null,scrolling:V,standby:null,summary:null,text:null,topMargin:H,valueType:null,version:null,vAlign:null,vLink:null,vSpace:H,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:B,disableRemotePlayback:B,prefix:null,property:null,results:H,security:null,unselectable:null},space:`html`,transform:ba}),Sa=_a({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:fa,accentHeight:H,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:H,amplitude:H,arabicForm:null,ascent:H,attributeName:null,attributeType:null,azimuth:H,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:H,by:null,calcMode:null,capHeight:H,className:U,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:H,diffuseConstant:H,direction:null,display:null,dur:null,divisor:H,dominantBaseline:null,download:B,dx:null,dy:null,edgeMode:null,editable:null,elevation:H,enableBackground:null,end:null,event:null,exponent:H,externalResourcesRequired:null,fill:null,fillOpacity:H,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:da,g2:da,glyphName:da,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:H,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:H,horizOriginX:H,horizOriginY:H,id:null,ideographic:H,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:H,k:H,k1:H,k2:H,k3:H,k4:H,kernelMatrix:fa,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:H,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:H,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:H,overlineThickness:H,paintOrder:null,panose1:null,path:null,pathLength:H,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:U,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:H,pointsAtY:H,pointsAtZ:H,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:fa,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:fa,rev:fa,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:fa,requiredFeatures:fa,requiredFonts:fa,requiredFormats:fa,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:H,specularExponent:H,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:H,strikethroughThickness:H,string:null,stroke:null,strokeDashArray:fa,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:H,strokeOpacity:H,strokeWidth:null,style:null,surfaceScale:H,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:fa,tabIndex:H,tableValues:null,target:null,targetX:H,targetY:H,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:fa,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:H,underlineThickness:H,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:H,values:null,vAlphabetic:H,vMathematical:H,vectorEffect:null,vHanging:H,vIdeographic:H,version:null,vertAdvY:H,vertOriginX:H,vertOriginY:H,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:H,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:`svg`,transform:ya}),Ca=_a({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()}}),wa=_a({attributes:{xmlnsxlink:`xmlns:xlink`},properties:{xmlnsXLink:null,xmlns:null},space:`xmlns`,transform:ba}),Ta=_a({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:`xml`,transform(e,t){return`xml:`+t.slice(3).toLowerCase()}}),Ea={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`},Da=/[A-Z]/g,Oa=/-[a-z]/g,ka=/^data[-\w.:]+$/i;function Aa(e,t){let n=sa(t),r=t,i=z;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)===`data`&&ka.test(t)){if(t.charAt(4)===`-`){let e=t.slice(5).replace(Oa,Ma);r=`data`+e.charAt(0).toUpperCase()+e.slice(1)}else{let e=t.slice(4);if(!Oa.test(e)){let n=e.replace(Da,ja);n.charAt(0)!==`-`&&(n=`-`+n),t=`data`+n}}i=ha}return new i(r,t)}function ja(e){return`-`+e.toLowerCase()}function Ma(e){return e.charAt(1).toUpperCase()}var Na=oa([va,xa,Ca,wa,Ta],`html`),Pa=oa([va,Sa,Ca,wa,Ta],`svg`);function Fa(e){return e.join(` `).trim()}var Ia=a(((e,t)=>{var n=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,r=/\n/g,i=/^\s*/,a=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,o=/^:\s*/,s=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,l=/^\s+|\s+$/g,u=`
3
3
  `,d=`/`,f=`*`,p=``,m=`comment`,h=`declaration`;function g(e,t){if(typeof e!=`string`)throw TypeError(`First argument must be a string`);if(!e)return[];t||={};var l=1,g=1;function v(e){var t=e.match(r);t&&(l+=t.length);var n=e.lastIndexOf(u);g=~n?e.length-n:g+e.length}function y(){var e={line:l,column:g};return function(t){return t.position=new b(e),C(),t}}function b(e){this.start=e,this.end={line:l,column:g},this.source=t.source}b.prototype.content=e;function x(n){var r=Error(t.source+`:`+l+`:`+g+`: `+n);if(r.reason=n,r.filename=t.source,r.line=l,r.column=g,r.source=e,!t.silent)throw r}function S(t){var n=t.exec(e);if(n){var r=n[0];return v(r),e=e.slice(r.length),n}}function C(){S(i)}function w(e){var t;for(e||=[];t=T();)t!==!1&&e.push(t);return e}function T(){var t=y();if(!(d!=e.charAt(0)||f!=e.charAt(1))){for(var n=2;p!=e.charAt(n)&&(f!=e.charAt(n)||d!=e.charAt(n+1));)++n;if(n+=2,p===e.charAt(n-1))return x(`End of comment missing`);var r=e.slice(2,n-2);return g+=2,v(r),e=e.slice(n),g+=2,t({type:m,comment:r})}}function E(){var e=y(),t=S(a);if(t){if(T(),!S(o))return x(`property missing ':'`);var r=S(s),i=e({type:h,property:_(t[0].replace(n,p)),value:r?_(r[0].replace(n,p)):p});return S(c),i}}function D(){var e=[];w(e);for(var t;t=E();)t!==!1&&(e.push(t),w(e));return e}return C(),D()}function _(e){return e?e.replace(l,p):p}t.exports=g})),La=a((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,`__esModule`,{value:!0}),e.default=r;var n=t(Ia());function r(e,t){let r=null;if(!e||typeof e!=`string`)return r;let i=(0,n.default)(e),a=typeof t==`function`;return i.forEach(e=>{if(e.type!==`declaration`)return;let{property:n,value:i}=e;a?t(n,i,e):i&&(r||={},r[n]=i)}),r}})),Ra=a((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.camelCase=void 0;var t=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,r=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(e){return!e||r.test(e)||t.test(e)},s=function(e,t){return t.toUpperCase()},c=function(e,t){return`${t}-`};e.camelCase=function(e,t){return t===void 0&&(t={}),o(e)?e:(e=e.toLowerCase(),e=t.reactCompat?e.replace(a,c):e.replace(i,c),e.replace(n,s))}})),za=a(((e,t)=>{var n=(e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(La()),r=Ra();function i(e,t){var i={};return!e||typeof e!=`string`||(0,n.default)(e,function(e,n){e&&n&&(i[(0,r.camelCase)(e,t)]=n)}),i}i.default=i,t.exports=i})),Ba=Ha(`end`),Va=Ha(`start`);function Ha(e){return t;function t(t){let n=t&&t.position&&t.position[e]||{};if(typeof n.line==`number`&&n.line>0&&typeof n.column==`number`&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset==`number`&&n.offset>-1?n.offset:void 0}}}function Ua(e){let t=Va(e),n=Ba(e);if(t&&n)return{start:t,end:n}}function Wa(e){return!e||typeof e!=`object`?``:`position`in e||`type`in e?Ka(e.position):`start`in e||`end`in e?Ka(e):`line`in e||`column`in e?Ga(e):``}function Ga(e){return qa(e&&e.line)+`:`+qa(e&&e.column)}function Ka(e){return Ga(e&&e.start)+`-`+Ga(e&&e.end)}function qa(e){return e&&typeof e==`number`?e:1}var W=class extends Error{constructor(e,t,n){super(),typeof t==`string`&&(n=t,t=void 0);let r=``,i={},a=!1;if(t&&(i=`line`in t&&`column`in t||`start`in t&&`end`in t?{place:t}:`type`in t?{ancestors:[t],place:t.position}:{...t}),typeof e==`string`?r=e:!i.cause&&e&&(a=!0,r=e.message,i.cause=e),!i.ruleId&&!i.source&&typeof n==`string`){let e=n.indexOf(`:`);e===-1?i.ruleId=n:(i.source=n.slice(0,e),i.ruleId=n.slice(e+1))}if(!i.place&&i.ancestors&&i.ancestors){let e=i.ancestors[i.ancestors.length-1];e&&(i.place=e.position)}let o=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=o?o.column:void 0,this.fatal=void 0,this.file=``,this.message=r,this.line=o?o.line:void 0,this.name=Wa(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=a&&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}};W.prototype.file=``,W.prototype.name=``,W.prototype.reason=``,W.prototype.message=``,W.prototype.stack=``,W.prototype.column=void 0,W.prototype.line=void 0,W.prototype.ancestors=void 0,W.prototype.cause=void 0,W.prototype.fatal=void 0,W.prototype.place=void 0,W.prototype.ruleId=void 0,W.prototype.source=void 0;var Ja=e(za(),1),Ya={}.hasOwnProperty,Xa=new Map,Za=/[A-Z]/g,Qa=new Set([`table`,`tbody`,`thead`,`tfoot`,`tr`]),$a=new Set([`td`,`th`]),eo=`https://github.com/syntax-tree/hast-util-to-jsx-runtime`;function to(e,t){if(!t||t.Fragment===void 0)throw TypeError("Expected `Fragment` in options");let n=t.filePath||void 0,r;if(t.development){if(typeof t.jsxDEV!=`function`)throw TypeError("Expected `jsxDEV` in options when `development: true`");r=po(n,t.jsxDEV)}else{if(typeof t.jsx!=`function`)throw TypeError("Expected `jsx` in production options");if(typeof t.jsxs!=`function`)throw TypeError("Expected `jsxs` in production options");r=fo(n,t.jsx,t.jsxs)}let i={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`?Pa:Na,stylePropertyNameCase:t.stylePropertyNameCase||`dom`,tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},a=no(i,e,void 0);return a&&typeof a!=`string`?a:i.create(e,i.Fragment,{children:a||void 0},void 0)}function no(e,t,n){if(t.type===`element`)return ro(e,t,n);if(t.type===`mdxFlowExpression`||t.type===`mdxTextExpression`)return io(e,t);if(t.type===`mdxJsxFlowElement`||t.type===`mdxJsxTextElement`)return oo(e,t,n);if(t.type===`mdxjsEsm`)return ao(e,t);if(t.type===`root`)return so(e,t,n);if(t.type===`text`)return co(e,t)}function ro(e,t,n){let r=e.schema,i=r;t.tagName.toLowerCase()===`svg`&&r.space===`html`&&(i=Pa,e.schema=i),e.ancestors.push(t);let a=yo(e,t.tagName,!1),o=mo(e,t),s=go(e,t);return Qa.has(t.tagName)&&(s=s.filter(function(e){return typeof e==`string`?!ra(e):!0})),lo(e,o,a,t),uo(o,s),e.ancestors.pop(),e.schema=r,e.create(t,a,o,n)}function io(e,t){if(t.data&&t.data.estree&&e.evaluater){let n=t.data.estree.body[0];return n.type,e.evaluater.evaluateExpression(n.expression)}bo(e,t.position)}function ao(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);bo(e,t.position)}function oo(e,t,n){let r=e.schema,i=r;t.name===`svg`&&r.space===`html`&&(i=Pa,e.schema=i),e.ancestors.push(t);let a=t.name===null?e.Fragment:yo(e,t.name,!0),o=ho(e,t),s=go(e,t);return lo(e,o,a,t),uo(o,s),e.ancestors.pop(),e.schema=r,e.create(t,a,o,n)}function so(e,t,n){let r={};return uo(r,go(e,t)),e.create(t,e.Fragment,r,n)}function co(e,t){return t.value}function lo(e,t,n,r){typeof n!=`string`&&n!==e.Fragment&&e.passNode&&(t.node=r)}function uo(e,t){if(t.length>0){let n=t.length>1?t:t[0];n&&(e.children=n)}}function fo(e,t,n){return r;function r(e,r,i,a){let o=Array.isArray(i.children)?n:t;return a?o(r,i,a):o(r,i)}}function po(e,t){return n;function n(n,r,i,a){let o=Array.isArray(i.children),s=Va(n);return t(r,i,a,o,{columnNumber:s?s.column-1:void 0,fileName:e,lineNumber:s?s.line:void 0},void 0)}}function mo(e,t){let n={},r,i;for(i in t.properties)if(i!==`children`&&Ya.call(t.properties,i)){let a=_o(e,i,t.properties[i]);if(a){let[i,o]=a;e.tableCellAlignToStyle&&i===`align`&&typeof o==`string`&&$a.has(t.tagName)?r=o:n[i]=o}}if(r){let t=n.style||={};t[e.stylePropertyNameCase===`css`?`text-align`:`textAlign`]=r}return n}function ho(e,t){let n={};for(let r of t.attributes)if(r.type===`mdxJsxExpressionAttribute`)if(r.data&&r.data.estree&&e.evaluater){let t=r.data.estree.body[0];t.type;let i=t.expression;i.type;let a=i.properties[0];a.type,Object.assign(n,e.evaluater.evaluateExpression(a.argument))}else bo(e,t.position);else{let i=r.name,a;if(r.value&&typeof r.value==`object`)if(r.value.data&&r.value.data.estree&&e.evaluater){let t=r.value.data.estree.body[0];t.type,a=e.evaluater.evaluateExpression(t.expression)}else bo(e,t.position);else a=r.value===null?!0:r.value;n[i]=a}return n}function go(e,t){let n=[],r=-1,i=e.passKeys?new Map:Xa;for(;++r<t.children.length;){let a=t.children[r],o;if(e.passKeys){let e=a.type===`element`?a.tagName:a.type===`mdxJsxFlowElement`||a.type===`mdxJsxTextElement`?a.name:void 0;if(e){let t=i.get(e)||0;o=e+`-`+t,i.set(e,t+1)}}let s=no(e,a,o);s!==void 0&&n.push(s)}return n}function _o(e,t,n){let r=Aa(e.schema,t);if(!(n==null||typeof n==`number`&&Number.isNaN(n))){if(Array.isArray(n)&&(n=r.commaSeparated?Zi(n):Fa(n)),r.property===`style`){let t=typeof n==`object`?n:vo(e,String(n));return e.stylePropertyNameCase===`css`&&(t=xo(t)),[`style`,t]}return[e.elementAttributeNameCase===`react`&&r.space?Ea[r.property]||r.property:r.attribute,n]}}function vo(e,t){try{return(0,Ja.default)(t,{reactCompat:!0})}catch(t){if(e.ignoreInvalidStyle)return{};let n=t,r=new W("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:n,ruleId:`style`,source:`hast-util-to-jsx-runtime`});throw r.file=e.filePath||void 0,r.url=eo+`#cannot-parse-style-attribute`,r}}function yo(e,t,n){let r;if(!n)r={type:`Literal`,value:t};else if(t.includes(`.`)){let e=t.split(`.`),n=-1,i;for(;++n<e.length;){let t=ta(e[n])?{type:`Identifier`,name:e[n]}:{type:`Literal`,value:e[n]};i=i?{type:`MemberExpression`,object:i,property:t,computed:!!(n&&t.type===`Literal`),optional:!1}:t}r=i}else r=ta(t)&&!/^[a-z]/.test(t)?{type:`Identifier`,name:t}:{type:`Literal`,value:t};if(r.type===`Literal`){let t=r.value;return Ya.call(e.components,t)?e.components[t]:t}if(e.evaluater)return e.evaluater.evaluateExpression(r);bo(e)}function bo(e,t){let n=new W("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=eo+`#cannot-handle-mdx-estrees-without-createevaluater`,n}function xo(e){let t={},n;for(n in e)Ya.call(e,n)&&(t[So(n)]=e[n]);return t}function So(e){let t=e.replace(Za,Co);return t.slice(0,3)===`ms-`&&(t=`-`+t),t}function Co(e){return`-`+e.toLowerCase()}var wo={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`]},To={};function Eo(e,t){let n=t||To;return Do(e,typeof n.includeImageAlt==`boolean`?n.includeImageAlt:!0,typeof n.includeHtml==`boolean`?n.includeHtml:!0)}function Do(e,t,n){if(ko(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 Oo(e.children,t,n)}return Array.isArray(e)?Oo(e,t,n):``}function Oo(e,t,n){let r=[],i=-1;for(;++i<e.length;)r[i]=Do(e[i],t,n);return r.join(``)}function ko(e){return!!(e&&typeof e==`object`)}var Ao=document.createElement(`i`);function jo(e){let t=`&`+e+`;`;Ao.innerHTML=t;let n=Ao.textContent;return n.charCodeAt(n.length-1)===59&&e!==`semi`||n===t?!1:n}function Mo(e,t,n,r){let i=e.length,a=0,o;if(t=t<0?-t>i?0:i+t:t>i?i: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);a<r.length;)o=r.slice(a,a+1e4),o.unshift(t,0),e.splice(...o),a+=1e4,t+=1e4}function No(e,t){return e.length>0?(Mo(e,e.length,0,t),e):t}var Po={}.hasOwnProperty;function Fo(e){let t={},n=-1;for(;++n<e.length;)Io(t,e[n]);return t}function Io(e,t){let n;for(n in t){let r=(Po.call(e,n)?e[n]:void 0)||(e[n]={}),i=t[n],a;if(i)for(a in i){Po.call(r,a)||(r[a]=[]);let e=i[a];Lo(r[a],Array.isArray(e)?e:e?[e]:[])}}}function Lo(e,t){let n=-1,r=[];for(;++n<t.length;)(t[n].add===`after`?e:r).push(t[n]);Mo(e,0,0,r)}function Ro(e,t){let 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 zo(e){return e.replace(/[\t\n\r ]+/g,` `).replace(/^ | $/g,``).toLowerCase().toUpperCase()}var G=qo(/[A-Za-z]/),K=qo(/[\dA-Za-z]/),Bo=qo(/[#-'*+\--9=?A-Z^-~]/);function Vo(e){return e!==null&&(e<32||e===127)}var Ho=qo(/\d/),Uo=qo(/[\dA-Fa-f]/),Wo=qo(/[!-/:-@[-`{-~]/);function q(e){return e!==null&&e<-2}function J(e){return e!==null&&(e<0||e===32)}function Y(e){return e===-2||e===-1||e===32}var Go=qo(/\p{P}|\p{S}/u),Ko=qo(/\s/);function qo(e){return t;function t(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function Jo(e){let t=[],n=-1,r=0,i=0;for(;++n<e.length;){let a=e.charCodeAt(n),o=``;if(a===37&&K(e.charCodeAt(n+1))&&K(e.charCodeAt(n+2)))i=2;else if(a<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(a))||(o=String.fromCharCode(a));else if(a>55295&&a<57344){let t=e.charCodeAt(n+1);a<56320&&t>56319&&t<57344?(o=String.fromCharCode(a,t),i=1):o=`�`}else o=String.fromCharCode(a);o&&=(t.push(e.slice(r,n),encodeURIComponent(o)),r=n+i+1,``),i&&=(n+=i,0)}return t.join(``)+e.slice(r)}function X(e,t,n,r){let i=r?r-1:1/0,a=0;return o;function o(r){return Y(r)?(e.enter(n),s(r)):t(r)}function s(r){return Y(r)&&a++<i?(e.consume(r),s):(e.exit(n),t(r))}}var Yo={tokenize:Xo};function Xo(e){let t=e.attempt(this.parser.constructs.contentInitial,r,i),n;return t;function r(n){if(n===null){e.consume(n);return}return e.enter(`lineEnding`),e.consume(n),e.exit(`lineEnding`),X(e,t,`linePrefix`)}function i(t){return e.enter(`paragraph`),a(t)}function a(t){let r=e.enter(`chunkText`,{contentType:`text`,previous:n});return n&&(n.next=r),n=r,o(t)}function o(t){if(t===null){e.exit(`chunkText`),e.exit(`paragraph`),e.consume(t);return}return q(t)?(e.consume(t),e.exit(`chunkText`),a):(e.consume(t),o)}}var Zo={tokenize:$o},Qo={tokenize:es};function $o(e){let t=this,n=[],r=0,i,a,o;return s;function s(i){if(r<n.length){let a=n[r];return t.containerState=a[1],e.attempt(a[0].continuation,c,l)(i)}return l(i)}function c(e){if(r++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,i&&v();let n=t.events.length,a=n,o;for(;a--;)if(t.events[a][0]===`exit`&&t.events[a][1].type===`chunkFlow`){o=t.events[a][1].end;break}_(r);let s=n;for(;s<t.events.length;)t.events[s][1].end={...o},s++;return Mo(t.events,a+1,0,t.events.slice(n)),t.events.length=s,l(e)}return s(e)}function l(a){if(r===n.length){if(!i)return f(a);if(i.currentConstruct&&i.currentConstruct.concrete)return m(a);t.interrupt=!!(i.currentConstruct&&!i._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(Qo,u,d)(a)}function u(e){return i&&v(),_(r),f(e)}function d(e){return t.parser.lazy[t.now().line]=r!==n.length,o=t.now().offset,m(e)}function f(n){return t.containerState={},e.attempt(Qo,p,m)(n)}function p(e){return r++,n.push([t.currentConstruct,t.containerState]),f(e)}function m(n){if(n===null){i&&v(),_(0),e.consume(n);return}return i||=t.parser.flow(t.now()),e.enter(`chunkFlow`,{_tokenizer:i,contentType:`flow`,previous:a}),h(n)}function h(n){if(n===null){g(e.exit(`chunkFlow`),!0),_(0),e.consume(n);return}return q(n)?(e.consume(n),g(e.exit(`chunkFlow`)),r=0,t.interrupt=void 0,s):(e.consume(n),h)}function g(e,n){let s=t.sliceStream(e);if(n&&s.push(null),e.previous=a,a&&(a.next=e),a=e,i.defineSkip(e.start),i.write(s),t.parser.lazy[e.start.line]){let e=i.events.length;for(;e--;)if(i.events[e][1].start.offset<o&&(!i.events[e][1].end||i.events[e][1].end.offset>o))return;let n=t.events.length,a=n,s,c;for(;a--;)if(t.events[a][0]===`exit`&&t.events[a][1].type===`chunkFlow`){if(s){c=t.events[a][1].end;break}s=!0}for(_(r),e=n;e<t.events.length;)t.events[e][1].end={...c},e++;Mo(t.events,a+1,0,t.events.slice(n)),t.events.length=e}}function _(r){let i=n.length;for(;i-- >r;){let r=n[i];t.containerState=r[1],r[0].exit.call(t,e)}n.length=r}function v(){i.write([null]),a=void 0,i=void 0,t.containerState._closeFlow=void 0}}function es(e,t,n){return X(e,e.attempt(this.parser.constructs.document,t,n),`linePrefix`,this.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)}function ts(e){if(e===null||J(e)||Ko(e))return 1;if(Go(e))return 2}function ns(e,t,n){let r=[],i=-1;for(;++i<e.length;){let a=e[i].resolveAll;a&&!r.includes(a)&&(t=a(t,n),r.push(a))}return t}var rs={name:`attention`,resolveAll:is,tokenize:as};function is(e,t){let n=-1,r,i,a,o,s,c,l,u;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;c=e[r][1].end.offset-e[r][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;let d={...e[r][1].end},f={...e[n][1].start};os(d,-c),os(f,c),o={type:c>1?`strongSequence`:`emphasisSequence`,start:d,end:{...e[r][1].end}},s={type:c>1?`strongSequence`:`emphasisSequence`,start:{...e[n][1].start},end:f},a={type:c>1?`strongText`:`emphasisText`,start:{...e[r][1].end},end:{...e[n][1].start}},i={type:c>1?`strong`:`emphasis`,start:{...o.start},end:{...s.end}},e[r][1].end={...o.start},e[n][1].start={...s.end},l=[],e[r][1].end.offset-e[r][1].start.offset&&(l=No(l,[[`enter`,e[r][1],t],[`exit`,e[r][1],t]])),l=No(l,[[`enter`,i,t],[`enter`,o,t],[`exit`,o,t],[`enter`,a,t]]),l=No(l,ns(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),l=No(l,[[`exit`,a,t],[`enter`,s,t],[`exit`,s,t],[`exit`,i,t]]),e[n][1].end.offset-e[n][1].start.offset?(u=2,l=No(l,[[`enter`,e[n][1],t],[`exit`,e[n][1],t]])):u=0,Mo(e,r-1,n-r+3,l),n=r+l.length-u-2;break}}for(n=-1;++n<e.length;)e[n][1].type===`attentionSequence`&&(e[n][1].type=`data`);return e}function as(e,t){let n=this.parser.constructs.attentionMarkers.null,r=this.previous,i=ts(r),a;return o;function o(t){return a=t,e.enter(`attentionSequence`),s(t)}function s(o){if(o===a)return e.consume(o),s;let c=e.exit(`attentionSequence`),l=ts(o),u=!l||l===2&&i||n.includes(o),d=!i||i===2&&l||n.includes(r);return c._open=!!(a===42?u:u&&(i||!d)),c._close=!!(a===42?d:d&&(l||!u)),t(o)}}function os(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}var ss={name:`autolink`,tokenize:cs};function cs(e,t,n){let r=0;return i;function i(t){return e.enter(`autolink`),e.enter(`autolinkMarker`),e.consume(t),e.exit(`autolinkMarker`),e.enter(`autolinkProtocol`),a}function a(t){return G(t)?(e.consume(t),o):t===64?n(t):l(t)}function o(e){return e===43||e===45||e===46||K(e)?(r=1,s(e)):l(e)}function s(t){return t===58?(e.consume(t),r=0,c):(t===43||t===45||t===46||K(t))&&r++<32?(e.consume(t),s):(r=0,l(t))}function c(r){return r===62?(e.exit(`autolinkProtocol`),e.enter(`autolinkMarker`),e.consume(r),e.exit(`autolinkMarker`),e.exit(`autolink`),t):r===null||r===32||r===60||Vo(r)?n(r):(e.consume(r),c)}function l(t){return t===64?(e.consume(t),u):Bo(t)?(e.consume(t),l):n(t)}function u(e){return K(e)?d(e):n(e)}function d(n){return n===46?(e.consume(n),r=0,u):n===62?(e.exit(`autolinkProtocol`).type=`autolinkEmail`,e.enter(`autolinkMarker`),e.consume(n),e.exit(`autolinkMarker`),e.exit(`autolink`),t):f(n)}function f(t){if((t===45||K(t))&&r++<63){let n=t===45?f:d;return e.consume(t),n}return n(t)}}var ls={partial:!0,tokenize:us};function us(e,t,n){return r;function r(t){return Y(t)?X(e,i,`linePrefix`)(t):i(t)}function i(e){return e===null||q(e)?t(e):n(e)}}var ds={continuation:{tokenize:ps},exit:ms,name:`blockQuote`,tokenize:fs};function fs(e,t,n){let r=this;return i;function i(t){if(t===62){let n=r.containerState;return n.open||=(e.enter(`blockQuote`,{_container:!0}),!0),e.enter(`blockQuotePrefix`),e.enter(`blockQuoteMarker`),e.consume(t),e.exit(`blockQuoteMarker`),a}return n(t)}function a(n){return Y(n)?(e.enter(`blockQuotePrefixWhitespace`),e.consume(n),e.exit(`blockQuotePrefixWhitespace`),e.exit(`blockQuotePrefix`),t):(e.exit(`blockQuotePrefix`),t(n))}}function ps(e,t,n){let r=this;return i;function i(t){return Y(t)?X(e,a,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):a(t)}function a(r){return e.attempt(ds,t,n)(r)}}function ms(e){e.exit(`blockQuote`)}var hs={name:`characterEscape`,tokenize:gs};function gs(e,t,n){return r;function r(t){return e.enter(`characterEscape`),e.enter(`escapeMarker`),e.consume(t),e.exit(`escapeMarker`),i}function i(r){return Wo(r)?(e.enter(`characterEscapeValue`),e.consume(r),e.exit(`characterEscapeValue`),e.exit(`characterEscape`),t):n(r)}}var _s={name:`characterReference`,tokenize:vs};function vs(e,t,n){let r=this,i=0,a,o;return s;function s(t){return e.enter(`characterReference`),e.enter(`characterReferenceMarker`),e.consume(t),e.exit(`characterReferenceMarker`),c}function c(t){return t===35?(e.enter(`characterReferenceMarkerNumeric`),e.consume(t),e.exit(`characterReferenceMarkerNumeric`),l):(e.enter(`characterReferenceValue`),a=31,o=K,u(t))}function l(t){return t===88||t===120?(e.enter(`characterReferenceMarkerHexadecimal`),e.consume(t),e.exit(`characterReferenceMarkerHexadecimal`),e.enter(`characterReferenceValue`),a=6,o=Uo,u):(e.enter(`characterReferenceValue`),a=7,o=Ho,u(t))}function u(s){if(s===59&&i){let i=e.exit(`characterReferenceValue`);return o===K&&!jo(r.sliceSerialize(i))?n(s):(e.enter(`characterReferenceMarker`),e.consume(s),e.exit(`characterReferenceMarker`),e.exit(`characterReference`),t)}return o(s)&&i++<a?(e.consume(s),u):n(s)}}var ys={partial:!0,tokenize:Ss},bs={concrete:!0,name:`codeFenced`,tokenize:xs};function xs(e,t,n){let r=this,i={partial:!0,tokenize:x},a=0,o=0,s;return c;function c(e){return l(e)}function l(t){let n=r.events[r.events.length-1];return a=n&&n[1].type===`linePrefix`?n[2].sliceSerialize(n[1],!0).length:0,s=t,e.enter(`codeFenced`),e.enter(`codeFencedFence`),e.enter(`codeFencedFenceSequence`),u(t)}function u(t){return t===s?(o++,e.consume(t),u):o<3?n(t):(e.exit(`codeFencedFenceSequence`),Y(t)?X(e,d,`whitespace`)(t):d(t))}function d(n){return n===null||q(n)?(e.exit(`codeFencedFence`),r.interrupt?t(n):e.check(ys,h,b)(n)):(e.enter(`codeFencedFenceInfo`),e.enter(`chunkString`,{contentType:`string`}),f(n))}function f(t){return t===null||q(t)?(e.exit(`chunkString`),e.exit(`codeFencedFenceInfo`),d(t)):Y(t)?(e.exit(`chunkString`),e.exit(`codeFencedFenceInfo`),X(e,p,`whitespace`)(t)):t===96&&t===s?n(t):(e.consume(t),f)}function p(t){return t===null||q(t)?d(t):(e.enter(`codeFencedFenceMeta`),e.enter(`chunkString`,{contentType:`string`}),m(t))}function m(t){return t===null||q(t)?(e.exit(`chunkString`),e.exit(`codeFencedFenceMeta`),d(t)):t===96&&t===s?n(t):(e.consume(t),m)}function h(t){return e.attempt(i,b,g)(t)}function g(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),_}function _(t){return a>0&&Y(t)?X(e,v,`linePrefix`,a+1)(t):v(t)}function v(t){return t===null||q(t)?e.check(ys,h,b)(t):(e.enter(`codeFlowValue`),y(t))}function y(t){return t===null||q(t)?(e.exit(`codeFlowValue`),v(t)):(e.consume(t),y)}function b(n){return e.exit(`codeFenced`),t(n)}function x(e,t,n){let i=0;return a;function a(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),c}function c(t){return e.enter(`codeFencedFence`),Y(t)?X(e,l,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):l(t)}function l(t){return t===s?(e.enter(`codeFencedFenceSequence`),u(t)):n(t)}function u(t){return t===s?(i++,e.consume(t),u):i>=o?(e.exit(`codeFencedFenceSequence`),Y(t)?X(e,d,`whitespace`)(t):d(t)):n(t)}function d(r){return r===null||q(r)?(e.exit(`codeFencedFence`),t(r)):n(r)}}}function Ss(e,t,n){let r=this;return i;function i(t){return t===null?n(t):(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),a)}function a(e){return r.parser.lazy[r.now().line]?n(e):t(e)}}var Cs={name:`codeIndented`,tokenize:Ts},ws={partial:!0,tokenize:Es};function Ts(e,t,n){let r=this;return i;function i(t){return e.enter(`codeIndented`),X(e,a,`linePrefix`,5)(t)}function a(e){let t=r.events[r.events.length-1];return t&&t[1].type===`linePrefix`&&t[2].sliceSerialize(t[1],!0).length>=4?o(e):n(e)}function o(t){return t===null?c(t):q(t)?e.attempt(ws,o,c)(t):(e.enter(`codeFlowValue`),s(t))}function s(t){return t===null||q(t)?(e.exit(`codeFlowValue`),o(t)):(e.consume(t),s)}function c(n){return e.exit(`codeIndented`),t(n)}}function Es(e,t,n){let r=this;return i;function i(t){return r.parser.lazy[r.now().line]?n(t):q(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),i):X(e,a,`linePrefix`,5)(t)}function a(e){let a=r.events[r.events.length-1];return a&&a[1].type===`linePrefix`&&a[2].sliceSerialize(a[1],!0).length>=4?t(e):q(e)?i(e):n(e)}}var Ds={name:`codeText`,previous:ks,resolve:Os,tokenize:As};function Os(e){let t=e.length-4,n=3,r,i;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;)i===void 0?r!==t&&e[r][1].type!==`lineEnding`&&(i=r):(r===t||e[r][1].type===`lineEnding`)&&(e[i][1].type=`codeTextData`,r!==i+2&&(e[i][1].end=e[r-1][1].end,e.splice(i+2,r-i-2),t-=r-i-2,r=i+2),i=void 0);return e}function ks(e){return e!==96||this.events[this.events.length-1][1].type===`characterEscape`}function As(e,t,n){let r=0,i,a;return o;function o(t){return e.enter(`codeText`),e.enter(`codeTextSequence`),s(t)}function s(t){return t===96?(e.consume(t),r++,s):(e.exit(`codeTextSequence`),c(t))}function c(t){return t===null?n(t):t===32?(e.enter(`space`),e.consume(t),e.exit(`space`),c):t===96?(a=e.enter(`codeTextSequence`),i=0,u(t)):q(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),c):(e.enter(`codeTextData`),l(t))}function l(t){return t===null||t===32||t===96||q(t)?(e.exit(`codeTextData`),c(t)):(e.consume(t),l)}function u(n){return n===96?(e.consume(n),i++,u):i===r?(e.exit(`codeTextSequence`),e.exit(`codeText`),t(n)):(a.type=`codeTextData`,l(n))}}var js=class{constructor(e){this.left=e?[...e]:[],this.right=[]}get(e){if(e<0||e>=this.left.length+this.right.length)throw RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return e<this.left.length?this.left[e]:this.right[this.right.length-e+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(e,t){let n=t??1/0;return n<this.left.length?this.left.slice(e,n):e>this.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(e,t,n){let r=t||0;this.setCursor(Math.trunc(e));let i=this.right.splice(this.right.length-r,1/0);return n&&Ms(this.left,n),i.reverse()}pop(){return this.setCursor(1/0),this.left.pop()}push(e){this.setCursor(1/0),this.left.push(e)}pushMany(e){this.setCursor(1/0),Ms(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),Ms(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0))if(e<this.left.length){let t=this.left.splice(e,1/0);Ms(this.right,t.reverse())}else{let t=this.right.splice(this.left.length+this.right.length-e,1/0);Ms(this.left,t.reverse())}}};function Ms(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 Ns(e){let t={},n=-1,r,i,a,o,s,c,l,u=new js(e);for(;++n<u.length;){for(;n in t;)n=t[n];if(r=u.get(n),n&&r[1].type===`chunkFlow`&&u.get(n-1)[1].type===`listItemPrefix`&&(c=r[1]._tokenizer.events,a=0,a<c.length&&c[a][1].type===`lineEndingBlank`&&(a+=2),a<c.length&&c[a][1].type===`content`))for(;++a<c.length&&c[a][1].type!==`content`;)c[a][1].type===`chunkText`&&(c[a][1]._isInFirstContentOfListItem=!0,a++);if(r[0]===`enter`)r[1].contentType&&(Object.assign(t,Ps(u,n)),n=t[n],l=!0);else if(r[1]._container){for(a=n,i=void 0;a--;)if(o=u.get(a),o[1].type===`lineEnding`||o[1].type===`lineEndingBlank`)o[0]===`enter`&&(i&&(u.get(i)[1].type=`lineEndingBlank`),o[1].type=`lineEnding`,i=a);else if(!(o[1].type===`linePrefix`||o[1].type===`listItemIndent`))break;i&&(r[1].end={...u.get(i)[1].start},s=u.slice(i,n),s.unshift(r),u.splice(i,n-i+1,s))}}return Mo(e,0,1/0,u.slice(0)),!l}function Ps(e,t){let n=e.get(t)[1],r=e.get(t)[2],i=t-1,a=[],o=n._tokenizer;o||(o=r.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(o._contentTypeTextTrailing=!0));let s=o.events,c=[],l={},u,d,f=-1,p=n,m=0,h=0,g=[h];for(;p;){for(;e.get(++i)[1]!==p;);a.push(i),p._tokenizer||(u=r.sliceStream(p),p.next||u.push(null),d&&o.defineSkip(p.start),p._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(u),p._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),d=p,p=p.next}for(p=n;++f<s.length;)s[f][0]===`exit`&&s[f-1][0]===`enter`&&s[f][1].type===s[f-1][1].type&&s[f][1].start.line!==s[f][1].end.line&&(h=f+1,g.push(h),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(o.events=[],p?(p._tokenizer=void 0,p.previous=void 0):g.pop(),f=g.length;f--;){let t=s.slice(g[f],g[f+1]),n=a.pop();c.push([n,n+t.length-1]),e.splice(n,2,t)}for(c.reverse(),f=-1;++f<c.length;)l[m+c[f][0]]=m+c[f][1],m+=c[f][1]-c[f][0]-1;return l}var Fs={resolve:Ls,tokenize:Rs},Is={partial:!0,tokenize:zs};function Ls(e){return Ns(e),e}function Rs(e,t){let n;return r;function r(t){return e.enter(`content`),n=e.enter(`chunkContent`,{contentType:`content`}),i(t)}function i(t){return t===null?a(t):q(t)?e.check(Is,o,a)(t):(e.consume(t),i)}function a(n){return e.exit(`chunkContent`),e.exit(`content`),t(n)}function o(t){return e.consume(t),e.exit(`chunkContent`),n.next=e.enter(`chunkContent`,{contentType:`content`,previous:n}),n=n.next,i}}function zs(e,t,n){let r=this;return i;function i(t){return e.exit(`chunkContent`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),X(e,a,`linePrefix`)}function a(i){if(i===null||q(i))return n(i);let 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(i):e.interrupt(r.parser.constructs.flow,n,t)(i)}}function Bs(e,t,n,r,i,a,o,s,c){let l=c||1/0,u=0;return d;function d(t){return t===60?(e.enter(r),e.enter(i),e.enter(a),e.consume(t),e.exit(a),f):t===null||t===32||t===41||Vo(t)?n(t):(e.enter(r),e.enter(o),e.enter(s),e.enter(`chunkString`,{contentType:`string`}),h(t))}function f(n){return n===62?(e.enter(a),e.consume(n),e.exit(a),e.exit(i),e.exit(r),t):(e.enter(s),e.enter(`chunkString`,{contentType:`string`}),p(n))}function p(t){return t===62?(e.exit(`chunkString`),e.exit(s),f(t)):t===null||t===60||q(t)?n(t):(e.consume(t),t===92?m:p)}function m(t){return t===60||t===62||t===92?(e.consume(t),p):p(t)}function h(i){return!u&&(i===null||i===41||J(i))?(e.exit(`chunkString`),e.exit(s),e.exit(o),e.exit(r),t(i)):u<l&&i===40?(e.consume(i),u++,h):i===41?(e.consume(i),u--,h):i===null||i===32||i===40||Vo(i)?n(i):(e.consume(i),i===92?g:h)}function g(t){return t===40||t===41||t===92?(e.consume(t),h):h(t)}}function Vs(e,t,n,r,i,a){let o=this,s=0,c;return l;function l(t){return e.enter(r),e.enter(i),e.consume(t),e.exit(i),e.enter(a),u}function u(l){return s>999||l===null||l===91||l===93&&!c||l===94&&!s&&`_hiddenFootnoteSupport`in o.parser.constructs?n(l):l===93?(e.exit(a),e.enter(i),e.consume(l),e.exit(i),e.exit(r),t):q(l)?(e.enter(`lineEnding`),e.consume(l),e.exit(`lineEnding`),u):(e.enter(`chunkString`,{contentType:`string`}),d(l))}function d(t){return t===null||t===91||t===93||q(t)||s++>999?(e.exit(`chunkString`),u(t)):(e.consume(t),c||=!Y(t),t===92?f:d)}function f(t){return t===91||t===92||t===93?(e.consume(t),s++,d):d(t)}}function Hs(e,t,n,r,i,a){let o;return s;function s(t){return t===34||t===39||t===40?(e.enter(r),e.enter(i),e.consume(t),e.exit(i),o=t===40?41:t,c):n(t)}function c(n){return n===o?(e.enter(i),e.consume(n),e.exit(i),e.exit(r),t):(e.enter(a),l(n))}function l(t){return t===o?(e.exit(a),c(o)):t===null?n(t):q(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),X(e,l,`linePrefix`)):(e.enter(`chunkString`,{contentType:`string`}),u(t))}function u(t){return t===o||t===null||q(t)?(e.exit(`chunkString`),l(t)):(e.consume(t),t===92?d:u)}function d(t){return t===o||t===92?(e.consume(t),u):u(t)}}function Us(e,t){let n;return r;function r(i){return q(i)?(e.enter(`lineEnding`),e.consume(i),e.exit(`lineEnding`),n=!0,r):Y(i)?X(e,r,n?`linePrefix`:`lineSuffix`)(i):t(i)}}var Ws={name:`definition`,tokenize:Ks},Gs={partial:!0,tokenize:qs};function Ks(e,t,n){let r=this,i;return a;function a(t){return e.enter(`definition`),o(t)}function o(t){return Vs.call(r,e,s,n,`definitionLabel`,`definitionLabelMarker`,`definitionLabelString`)(t)}function s(t){return i=zo(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),t===58?(e.enter(`definitionMarker`),e.consume(t),e.exit(`definitionMarker`),c):n(t)}function c(t){return J(t)?Us(e,l)(t):l(t)}function l(t){return Bs(e,u,n,`definitionDestination`,`definitionDestinationLiteral`,`definitionDestinationLiteralMarker`,`definitionDestinationRaw`,`definitionDestinationString`)(t)}function u(t){return e.attempt(Gs,d,d)(t)}function d(t){return Y(t)?X(e,f,`whitespace`)(t):f(t)}function f(a){return a===null||q(a)?(e.exit(`definition`),r.parser.defined.push(i),t(a)):n(a)}}function qs(e,t,n){return r;function r(t){return J(t)?Us(e,i)(t):n(t)}function i(t){return Hs(e,a,n,`definitionTitle`,`definitionTitleMarker`,`definitionTitleString`)(t)}function a(t){return Y(t)?X(e,o,`whitespace`)(t):o(t)}function o(e){return e===null||q(e)?t(e):n(e)}}var Js={name:`hardBreakEscape`,tokenize:Ys};function Ys(e,t,n){return r;function r(t){return e.enter(`hardBreakEscape`),e.consume(t),i}function i(r){return q(r)?(e.exit(`hardBreakEscape`),t(r)):n(r)}}var Xs={name:`headingAtx`,resolve:Zs,tokenize:Qs};function Zs(e,t){let n=e.length-2,r=3,i,a;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&&(i={type:`atxHeadingText`,start:e[r][1].start,end:e[n][1].end},a={type:`chunkText`,start:e[r][1].start,end:e[n][1].end,contentType:`text`},Mo(e,r,n-r+1,[[`enter`,i,t],[`enter`,a,t],[`exit`,a,t],[`exit`,i,t]])),e}function Qs(e,t,n){let r=0;return i;function i(t){return e.enter(`atxHeading`),a(t)}function a(t){return e.enter(`atxHeadingSequence`),o(t)}function o(t){return t===35&&r++<6?(e.consume(t),o):t===null||J(t)?(e.exit(`atxHeadingSequence`),s(t)):n(t)}function s(n){return n===35?(e.enter(`atxHeadingSequence`),c(n)):n===null||q(n)?(e.exit(`atxHeading`),t(n)):Y(n)?X(e,s,`whitespace`)(n):(e.enter(`atxHeadingText`),l(n))}function c(t){return t===35?(e.consume(t),c):(e.exit(`atxHeadingSequence`),s(t))}function l(t){return t===null||t===35||J(t)?(e.exit(`atxHeadingText`),s(t)):(e.consume(t),l)}}var $s=`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`.split(`.`),ec=[`pre`,`script`,`style`,`textarea`],tc={concrete:!0,name:`htmlFlow`,resolveTo:ic,tokenize:ac},nc={partial:!0,tokenize:sc},rc={partial:!0,tokenize:oc};function ic(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 ac(e,t,n){let r=this,i,a,o,s,c;return l;function l(e){return u(e)}function u(t){return e.enter(`htmlFlow`),e.enter(`htmlFlowData`),e.consume(t),d}function d(s){return s===33?(e.consume(s),f):s===47?(e.consume(s),a=!0,h):s===63?(e.consume(s),i=3,r.interrupt?t:ie):G(s)?(e.consume(s),o=String.fromCharCode(s),g):n(s)}function f(a){return a===45?(e.consume(a),i=2,p):a===91?(e.consume(a),i=5,s=0,m):G(a)?(e.consume(a),i=4,r.interrupt?t:ie):n(a)}function p(i){return i===45?(e.consume(i),r.interrupt?t:ie):n(i)}function m(i){return i===`CDATA[`.charCodeAt(s++)?(e.consume(i),s===6?r.interrupt?t:O:m):n(i)}function h(t){return G(t)?(e.consume(t),o=String.fromCharCode(t),g):n(t)}function g(s){if(s===null||s===47||s===62||J(s)){let c=s===47,l=o.toLowerCase();return!c&&!a&&ec.includes(l)?(i=1,r.interrupt?t(s):O(s)):$s.includes(o.toLowerCase())?(i=6,c?(e.consume(s),_):r.interrupt?t(s):O(s)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(s):a?v(s):y(s))}return s===45||K(s)?(e.consume(s),o+=String.fromCharCode(s),g):n(s)}function _(i){return i===62?(e.consume(i),r.interrupt?t:O):n(i)}function v(t){return Y(t)?(e.consume(t),v):E(t)}function y(t){return t===47?(e.consume(t),E):t===58||t===95||G(t)?(e.consume(t),b):Y(t)?(e.consume(t),y):E(t)}function b(t){return t===45||t===46||t===58||t===95||K(t)?(e.consume(t),b):x(t)}function x(t){return t===61?(e.consume(t),S):Y(t)?(e.consume(t),x):y(t)}function S(t){return t===null||t===60||t===61||t===62||t===96?n(t):t===34||t===39?(e.consume(t),c=t,C):Y(t)?(e.consume(t),S):w(t)}function C(t){return t===c?(e.consume(t),c=null,T):t===null||q(t)?n(t):(e.consume(t),C)}function w(t){return t===null||t===34||t===39||t===47||t===60||t===61||t===62||t===96||J(t)?x(t):(e.consume(t),w)}function T(e){return e===47||e===62||Y(e)?y(e):n(e)}function E(t){return t===62?(e.consume(t),D):n(t)}function D(t){return t===null||q(t)?O(t):Y(t)?(e.consume(t),D):n(t)}function O(t){return t===45&&i===2?(e.consume(t),A):t===60&&i===1?(e.consume(t),j):t===62&&i===4?(e.consume(t),M):t===63&&i===3?(e.consume(t),ie):t===93&&i===5?(e.consume(t),re):q(t)&&(i===6||i===7)?(e.exit(`htmlFlowData`),e.check(nc,ae,ee)(t)):t===null||q(t)?(e.exit(`htmlFlowData`),ee(t)):(e.consume(t),O)}function ee(t){return e.check(rc,k,ae)(t)}function k(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),te}function te(t){return t===null||q(t)?ee(t):(e.enter(`htmlFlowData`),O(t))}function A(t){return t===45?(e.consume(t),ie):O(t)}function j(t){return t===47?(e.consume(t),o=``,ne):O(t)}function ne(t){if(t===62){let n=o.toLowerCase();return ec.includes(n)?(e.consume(t),M):O(t)}return G(t)&&o.length<8?(e.consume(t),o+=String.fromCharCode(t),ne):O(t)}function re(t){return t===93?(e.consume(t),ie):O(t)}function ie(t){return t===62?(e.consume(t),M):t===45&&i===2?(e.consume(t),ie):O(t)}function M(t){return t===null||q(t)?(e.exit(`htmlFlowData`),ae(t)):(e.consume(t),M)}function ae(n){return e.exit(`htmlFlow`),t(n)}}function oc(e,t,n){let r=this;return i;function i(t){return q(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),a):n(t)}function a(e){return r.parser.lazy[r.now().line]?n(e):t(e)}}function sc(e,t,n){return r;function r(r){return e.enter(`lineEnding`),e.consume(r),e.exit(`lineEnding`),e.attempt(ls,t,n)}}var cc={name:`htmlText`,tokenize:lc};function lc(e,t,n){let r=this,i,a,o;return s;function s(t){return e.enter(`htmlText`),e.enter(`htmlTextData`),e.consume(t),c}function c(t){return t===33?(e.consume(t),l):t===47?(e.consume(t),x):t===63?(e.consume(t),y):G(t)?(e.consume(t),w):n(t)}function l(t){return t===45?(e.consume(t),u):t===91?(e.consume(t),a=0,m):G(t)?(e.consume(t),v):n(t)}function u(t){return t===45?(e.consume(t),p):n(t)}function d(t){return t===null?n(t):t===45?(e.consume(t),f):q(t)?(o=d,j(t)):(e.consume(t),d)}function f(t){return t===45?(e.consume(t),p):d(t)}function p(e){return e===62?A(e):e===45?f(e):d(e)}function m(t){return t===`CDATA[`.charCodeAt(a++)?(e.consume(t),a===6?h:m):n(t)}function h(t){return t===null?n(t):t===93?(e.consume(t),g):q(t)?(o=h,j(t)):(e.consume(t),h)}function g(t){return t===93?(e.consume(t),_):h(t)}function _(t){return t===62?A(t):t===93?(e.consume(t),_):h(t)}function v(t){return t===null||t===62?A(t):q(t)?(o=v,j(t)):(e.consume(t),v)}function y(t){return t===null?n(t):t===63?(e.consume(t),b):q(t)?(o=y,j(t)):(e.consume(t),y)}function b(e){return e===62?A(e):y(e)}function x(t){return G(t)?(e.consume(t),S):n(t)}function S(t){return t===45||K(t)?(e.consume(t),S):C(t)}function C(t){return q(t)?(o=C,j(t)):Y(t)?(e.consume(t),C):A(t)}function w(t){return t===45||K(t)?(e.consume(t),w):t===47||t===62||J(t)?T(t):n(t)}function T(t){return t===47?(e.consume(t),A):t===58||t===95||G(t)?(e.consume(t),E):q(t)?(o=T,j(t)):Y(t)?(e.consume(t),T):A(t)}function E(t){return t===45||t===46||t===58||t===95||K(t)?(e.consume(t),E):D(t)}function D(t){return t===61?(e.consume(t),O):q(t)?(o=D,j(t)):Y(t)?(e.consume(t),D):T(t)}function O(t){return t===null||t===60||t===61||t===62||t===96?n(t):t===34||t===39?(e.consume(t),i=t,ee):q(t)?(o=O,j(t)):Y(t)?(e.consume(t),O):(e.consume(t),k)}function ee(t){return t===i?(e.consume(t),i=void 0,te):t===null?n(t):q(t)?(o=ee,j(t)):(e.consume(t),ee)}function k(t){return t===null||t===34||t===39||t===60||t===61||t===96?n(t):t===47||t===62||J(t)?T(t):(e.consume(t),k)}function te(e){return e===47||e===62||J(e)?T(e):n(e)}function A(r){return r===62?(e.consume(r),e.exit(`htmlTextData`),e.exit(`htmlText`),t):n(r)}function j(t){return e.exit(`htmlTextData`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),ne}function ne(t){return Y(t)?X(e,re,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):re(t)}function re(t){return e.enter(`htmlTextData`),o(t)}}var uc={name:`labelEnd`,resolveAll:mc,resolveTo:hc,tokenize:gc},dc={tokenize:_c},fc={tokenize:vc},pc={tokenize:yc};function mc(e){let t=-1,n=[];for(;++t<e.length;){let r=e[t][1];if(n.push(e[t]),r.type===`labelImage`||r.type===`labelLink`||r.type===`labelEnd`){let e=r.type===`labelImage`?4:2;r.type=`data`,t+=e}}return e.length!==n.length&&Mo(e,0,e.length,n),e}function hc(e,t){let n=e.length,r=0,i,a,o,s;for(;n--;)if(i=e[n][1],a){if(i.type===`link`||i.type===`labelLink`&&i._inactive)break;e[n][0]===`enter`&&i.type===`labelLink`&&(i._inactive=!0)}else if(o){if(e[n][0]===`enter`&&(i.type===`labelImage`||i.type===`labelLink`)&&!i._balanced&&(a=n,i.type!==`labelLink`)){r=2;break}}else i.type===`labelEnd`&&(o=n);let c={type:e[a][1].type===`labelLink`?`link`:`image`,start:{...e[a][1].start},end:{...e[e.length-1][1].end}},l={type:`label`,start:{...e[a][1].start},end:{...e[o][1].end}},u={type:`labelText`,start:{...e[a+r+2][1].end},end:{...e[o-2][1].start}};return s=[[`enter`,c,t],[`enter`,l,t]],s=No(s,e.slice(a+1,a+r+3)),s=No(s,[[`enter`,u,t]]),s=No(s,ns(t.parser.constructs.insideSpan.null,e.slice(a+r+4,o-3),t)),s=No(s,[[`exit`,u,t],e[o-2],e[o-1],[`exit`,l,t]]),s=No(s,e.slice(o+1)),s=No(s,[[`exit`,c,t]]),Mo(e,a,e.length,s),e}function gc(e,t,n){let r=this,i=r.events.length,a,o;for(;i--;)if((r.events[i][1].type===`labelImage`||r.events[i][1].type===`labelLink`)&&!r.events[i][1]._balanced){a=r.events[i][1];break}return s;function s(t){return a?a._inactive?d(t):(o=r.parser.defined.includes(zo(r.sliceSerialize({start:a.end,end:r.now()}))),e.enter(`labelEnd`),e.enter(`labelMarker`),e.consume(t),e.exit(`labelMarker`),e.exit(`labelEnd`),c):n(t)}function c(t){return t===40?e.attempt(dc,u,o?u:d)(t):t===91?e.attempt(fc,u,o?l:d)(t):o?u(t):d(t)}function l(t){return e.attempt(pc,u,d)(t)}function u(e){return t(e)}function d(e){return a._balanced=!0,n(e)}}function _c(e,t,n){return r;function r(t){return e.enter(`resource`),e.enter(`resourceMarker`),e.consume(t),e.exit(`resourceMarker`),i}function i(t){return J(t)?Us(e,a)(t):a(t)}function a(t){return t===41?u(t):Bs(e,o,s,`resourceDestination`,`resourceDestinationLiteral`,`resourceDestinationLiteralMarker`,`resourceDestinationRaw`,`resourceDestinationString`,32)(t)}function o(t){return J(t)?Us(e,c)(t):u(t)}function s(e){return n(e)}function c(t){return t===34||t===39||t===40?Hs(e,l,n,`resourceTitle`,`resourceTitleMarker`,`resourceTitleString`)(t):u(t)}function l(t){return J(t)?Us(e,u)(t):u(t)}function u(r){return r===41?(e.enter(`resourceMarker`),e.consume(r),e.exit(`resourceMarker`),e.exit(`resource`),t):n(r)}}function vc(e,t,n){let r=this;return i;function i(t){return Vs.call(r,e,a,o,`reference`,`referenceMarker`,`referenceString`)(t)}function a(e){return r.parser.defined.includes(zo(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(e):n(e)}function o(e){return n(e)}}function yc(e,t,n){return r;function r(t){return e.enter(`reference`),e.enter(`referenceMarker`),e.consume(t),e.exit(`referenceMarker`),i}function i(r){return r===93?(e.enter(`referenceMarker`),e.consume(r),e.exit(`referenceMarker`),e.exit(`reference`),t):n(r)}}var bc={name:`labelStartImage`,resolveAll:uc.resolveAll,tokenize:xc};function xc(e,t,n){let r=this;return i;function i(t){return e.enter(`labelImage`),e.enter(`labelImageMarker`),e.consume(t),e.exit(`labelImageMarker`),a}function a(t){return t===91?(e.enter(`labelMarker`),e.consume(t),e.exit(`labelMarker`),e.exit(`labelImage`),o):n(t)}function o(e){return e===94&&`_hiddenFootnoteSupport`in r.parser.constructs?n(e):t(e)}}var Sc={name:`labelStartLink`,resolveAll:uc.resolveAll,tokenize:Cc};function Cc(e,t,n){let r=this;return i;function i(t){return e.enter(`labelLink`),e.enter(`labelMarker`),e.consume(t),e.exit(`labelMarker`),e.exit(`labelLink`),a}function a(e){return e===94&&`_hiddenFootnoteSupport`in r.parser.constructs?n(e):t(e)}}var wc={name:`lineEnding`,tokenize:Tc};function Tc(e,t){return n;function n(n){return e.enter(`lineEnding`),e.consume(n),e.exit(`lineEnding`),X(e,t,`linePrefix`)}}var Ec={name:`thematicBreak`,tokenize:Dc};function Dc(e,t,n){let r=0,i;return a;function a(t){return e.enter(`thematicBreak`),o(t)}function o(e){return i=e,s(e)}function s(a){return a===i?(e.enter(`thematicBreakSequence`),c(a)):r>=3&&(a===null||q(a))?(e.exit(`thematicBreak`),t(a)):n(a)}function c(t){return t===i?(e.consume(t),r++,c):(e.exit(`thematicBreakSequence`),Y(t)?X(e,s,`whitespace`)(t):s(t))}}var Z={continuation:{tokenize:jc},exit:Nc,name:`list`,tokenize:Ac},Oc={partial:!0,tokenize:Pc},kc={partial:!0,tokenize:Mc};function Ac(e,t,n){let r=this,i=r.events[r.events.length-1],a=i&&i[1].type===`linePrefix`?i[2].sliceSerialize(i[1],!0).length:0,o=0;return s;function s(t){let i=r.containerState.type||(t===42||t===43||t===45?`listUnordered`:`listOrdered`);if(i===`listUnordered`?!r.containerState.marker||t===r.containerState.marker:Ho(t)){if(r.containerState.type||(r.containerState.type=i,e.enter(i,{_container:!0})),i===`listUnordered`)return e.enter(`listItemPrefix`),t===42||t===45?e.check(Ec,n,l)(t):l(t);if(!r.interrupt||t===49)return e.enter(`listItemPrefix`),e.enter(`listItemValue`),c(t)}return n(t)}function c(t){return Ho(t)&&++o<10?(e.consume(t),c):(!r.interrupt||o<2)&&(r.containerState.marker?t===r.containerState.marker:t===41||t===46)?(e.exit(`listItemValue`),l(t)):n(t)}function l(t){return e.enter(`listItemMarker`),e.consume(t),e.exit(`listItemMarker`),r.containerState.marker=r.containerState.marker||t,e.check(ls,r.interrupt?n:u,e.attempt(Oc,f,d))}function u(e){return r.containerState.initialBlankLine=!0,a++,f(e)}function d(t){return Y(t)?(e.enter(`listItemPrefixWhitespace`),e.consume(t),e.exit(`listItemPrefixWhitespace`),f):n(t)}function f(n){return r.containerState.size=a+r.sliceSerialize(e.exit(`listItemPrefix`),!0).length,t(n)}}function jc(e,t,n){let r=this;return r.containerState._closeFlow=void 0,e.check(ls,i,a);function i(n){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,X(e,t,`listItemIndent`,r.containerState.size+1)(n)}function a(n){return r.containerState.furtherBlankLines||!Y(n)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,o(n)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(kc,t,o)(n))}function o(i){return r.containerState._closeFlow=!0,r.interrupt=void 0,X(e,e.attempt(Z,t,n),`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(i)}}function Mc(e,t,n){let r=this;return X(e,i,`listItemIndent`,r.containerState.size+1);function i(e){let i=r.events[r.events.length-1];return i&&i[1].type===`listItemIndent`&&i[2].sliceSerialize(i[1],!0).length===r.containerState.size?t(e):n(e)}}function Nc(e){e.exit(this.containerState.type)}function Pc(e,t,n){let r=this;return X(e,i,`listItemPrefixWhitespace`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:5);function i(e){let i=r.events[r.events.length-1];return!Y(e)&&i&&i[1].type===`listItemPrefixWhitespace`?t(e):n(e)}}var Fc={name:`setextUnderline`,resolveTo:Ic,tokenize:Lc};function Ic(e,t){let n=e.length,r,i,a;for(;n--;)if(e[n][0]===`enter`){if(e[n][1].type===`content`){r=n;break}e[n][1].type===`paragraph`&&(i=n)}else e[n][1].type===`content`&&e.splice(n,1),!a&&e[n][1].type===`definition`&&(a=n);let o={type:`setextHeading`,start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[i][1].type=`setextHeadingText`,a?(e.splice(i,0,[`enter`,o,t]),e.splice(a+1,0,[`exit`,e[r][1],t]),e[r][1].end={...e[a][1].end}):e[r][1]=o,e.push([`exit`,o,t]),e}function Lc(e,t,n){let r=this,i;return a;function a(t){let a=r.events.length,s;for(;a--;)if(r.events[a][1].type!==`lineEnding`&&r.events[a][1].type!==`linePrefix`&&r.events[a][1].type!==`content`){s=r.events[a][1].type===`paragraph`;break}return!r.parser.lazy[r.now().line]&&(r.interrupt||s)?(e.enter(`setextHeadingLine`),i=t,o(t)):n(t)}function o(t){return e.enter(`setextHeadingLineSequence`),s(t)}function s(t){return t===i?(e.consume(t),s):(e.exit(`setextHeadingLineSequence`),Y(t)?X(e,c,`lineSuffix`)(t):c(t))}function c(r){return r===null||q(r)?(e.exit(`setextHeadingLine`),t(r)):n(r)}}var Rc={tokenize:zc};function zc(e){let t=this,n=e.attempt(ls,r,e.attempt(this.parser.constructs.flowInitial,i,X(e,e.attempt(this.parser.constructs.flow,i,e.attempt(Fs,i)),`linePrefix`)));return n;function r(r){if(r===null){e.consume(r);return}return e.enter(`lineEndingBlank`),e.consume(r),e.exit(`lineEndingBlank`),t.currentConstruct=void 0,n}function i(r){if(r===null){e.consume(r);return}return e.enter(`lineEnding`),e.consume(r),e.exit(`lineEnding`),t.currentConstruct=void 0,n}}var Bc={resolveAll:Wc()},Vc=Uc(`string`),Hc=Uc(`text`);function Uc(e){return{resolveAll:Wc(e===`text`?Gc:void 0),tokenize:t};function t(t){let n=this,r=this.parser.constructs[e],i=t.attempt(r,a,o);return a;function a(e){return c(e)?i(e):o(e)}function o(e){if(e===null){t.consume(e);return}return t.enter(`data`),t.consume(e),s}function s(e){return c(e)?(t.exit(`data`),i(e)):(t.consume(e),s)}function c(e){if(e===null)return!0;let t=r[e],i=-1;if(t)for(;++i<t.length;){let e=t[i];if(!e.previous||e.previous.call(n,n.previous))return!0}return!1}}}function Wc(e){return t;function t(t,n){let r=-1,i;for(;++r<=t.length;)i===void 0?t[r]&&t[r][1].type===`data`&&(i=r,r++):(!t[r]||t[r][1].type!==`data`)&&(r!==i+2&&(t[i][1].end=t[r-1][1].end,t.splice(i+2,r-i-2),r=i+2),i=void 0);return e?e(t,n):t}}function Gc(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type===`lineEnding`)&&e[n-1][1].type===`data`){let r=e[n-1][1],i=t.sliceStream(r),a=i.length,o=-1,s=0,c;for(;a--;){let e=i[a];if(typeof e==`string`){for(o=e.length;e.charCodeAt(o-1)===32;)s++,o--;if(o)break;o=-1}else if(e===-2)c=!0,s++;else if(e!==-1){a++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(s=0),s){let i={type:n===e.length||c||s<2?`lineSuffix`:`hardBreakTrailing`,start:{_bufferIndex:a?o:r.start._bufferIndex+o,_index:r.start._index+a,line:r.end.line,column:r.end.column-s,offset:r.end.offset-s},end:{...r.end}};r.end={...i.start},r.start.offset===r.end.offset?Object.assign(r,i):(e.splice(n,0,[`enter`,i,t],[`exit`,i,t]),n+=2)}n++}return e}var Kc=i({attentionMarkers:()=>el,contentInitial:()=>Jc,disable:()=>tl,document:()=>qc,flow:()=>Xc,flowInitial:()=>Yc,insideSpan:()=>$c,string:()=>Zc,text:()=>Qc}),qc={42:Z,43:Z,45:Z,48:Z,49:Z,50:Z,51:Z,52:Z,53:Z,54:Z,55:Z,56:Z,57:Z,62:ds},Jc={91:Ws},Yc={[-2]:Cs,[-1]:Cs,32:Cs},Xc={35:Xs,42:Ec,45:[Fc,Ec],60:tc,61:Fc,95:Ec,96:bs,126:bs},Zc={38:_s,92:hs},Qc={[-5]:wc,[-4]:wc,[-3]:wc,33:bc,38:_s,42:rs,60:[ss,cc],91:Sc,92:[Js,hs],93:uc,95:rs,96:Ds},$c={null:[rs,Bc]},el={null:[42,95]},tl={null:[]};function nl(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0},i={},a=[],o=[],s=[],c={attempt:C(x),check:C(S),consume:v,enter:y,exit:b,interrupt:C(S,{interrupt:!0})},l={code:null,containerState:{},defineSkip:h,events:[],now:m,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:d},u=t.tokenize.call(l,c);return t.resolveAll&&a.push(t),l;function d(e){return o=No(o,e),g(),o[o.length-1]===null?(w(t,0),l.events=ns(a,l.events,l),l.events):[]}function f(e,t){return il(p(e),t)}function p(e){return rl(o,e)}function m(){let{_bufferIndex:e,_index:t,line:n,column:i,offset:a}=r;return{_bufferIndex:e,_index:t,line:n,column:i,offset:a}}function h(e){i[e.line]=e.column,E()}function g(){let e;for(;r._index<o.length;){let t=o[r._index];if(typeof t==`string`)for(e=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===e&&r._bufferIndex<t.length;)_(t.charCodeAt(r._bufferIndex));else _(t)}}function _(e){u=u(e)}function v(e){q(e)?(r.line++,r.column=1,r.offset+=e===-3?2:1,E()):e!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===o[r._index].length&&(r._bufferIndex=-1,r._index++)),l.previous=e}function y(e,t){let n=t||{};return n.type=e,n.start=m(),l.events.push([`enter`,n,l]),s.push(n),n}function b(e){let t=s.pop();return t.end=m(),l.events.push([`exit`,t,l]),t}function x(e,t){w(e,t.from)}function S(e,t){t.restore()}function C(e,t){return n;function n(n,r,i){let a,o,s,u;return Array.isArray(n)?f(n):`tokenize`in n?f([n]):d(n);function d(e){return t;function t(t){let n=t!==null&&e[t],r=t!==null&&e.null;return f([...Array.isArray(n)?n:n?[n]:[],...Array.isArray(r)?r:r?[r]:[]])(t)}}function f(e){return a=e,o=0,e.length===0?i:p(e[o])}function p(e){return n;function n(n){return u=T(),s=e,e.partial||(l.currentConstruct=e),e.name&&l.parser.constructs.disable.null.includes(e.name)?h(n):e.tokenize.call(t?Object.assign(Object.create(l),t):l,c,m,h)(n)}}function m(t){return e(s,u),r}function h(e){return u.restore(),++o<a.length?p(a[o]):i}}}function w(e,t){e.resolveAll&&!a.includes(e)&&a.push(e),e.resolve&&Mo(l.events,t,l.events.length-t,e.resolve(l.events.slice(t),l)),e.resolveTo&&(l.events=e.resolveTo(l.events,l))}function T(){let e=m(),t=l.previous,n=l.currentConstruct,i=l.events.length,a=Array.from(s);return{from:i,restore:o};function o(){r=e,l.previous=t,l.currentConstruct=n,l.events.length=i,s=a,E()}}function E(){r.line in i&&r.column<2&&(r.column=i[r.line],r.offset+=i[r.line]-1)}}function rl(e,t){let n=t.start._index,r=t.start._bufferIndex,i=t.end._index,a=t.end._bufferIndex,o;if(n===i)o=[e[n].slice(r,a)];else{if(o=e.slice(n,i),r>-1){let e=o[0];typeof e==`string`?o[0]=e.slice(r):o.shift()}a>0&&o.push(e[i].slice(0,a))}return o}function il(e,t){let n=-1,r=[],i;for(;++n<e.length;){let a=e[n],o;if(typeof a==`string`)o=a;else switch(a){case-5:o=`\r`;break;case-4:o=`
4
4
  `;break;case-3:o=`\r
@@ -40,4 +40,4 @@ import{_ as e,a as t,d as n,f as r,g as i,h as a,i as o,m as s,n as c,p as l,u}f
40
40
  `;case`r`:return`\r`;case`t`:return` `;default:return e}}function iv(e,t){let n=`"${t}"`,r=e.indexOf(n);if(r<0)return null;let i=e.indexOf(`:`,r+n.length);if(i<0)return null;let a=i+1;for(;a<e.length&&/\s/.test(e[a]??``);)a+=1;return e[a]===`"`?a+1:null}function av(e,t,n=1/0){let r=``,i=!1;for(let a=t;a<e.length;a+=1){let t=e[a];if(t==null)break;if(i){r+=rv(t),i=!1;continue}if(t===`\\`){i=!0;continue}if(t===`"`)return{value:r,truncated:!1};if(r+=t,r.length>=n)return{value:r,truncated:!0}}return r.length>0?{value:r,truncated:!1}:null}function ov(e,t,n=1/0){for(let r of t){let t=iv(e,r);if(t!=null)return av(e,t,n)}return null}function sv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function cv(e){return typeof e==`string`&&e.trim()?e.trim():null}function lv(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:typeof e==`string`&&/^\d+$/.test(e.trim())?Number(e.trim()):null}function uv(e){if(sv(e))return e;if(typeof e!=`string`)return null;let t=e.trim();if(!t.startsWith(`{`))return null;try{let e=JSON.parse(t);return sv(e)?e:null}catch{return null}}function dv(e){if(sv(e))return e;if(typeof e!=`string`)return null;let t=e.trim();if(!t.startsWith(`{`))return null;let n=ov(t,[`path`,`filePath`,`file_path`,`targetPath`,`target_path`,`filename`,`name`])?.value??null,r=ov(t,[`content`,`text`,`afterText`,`after_text`])?.value??null,i=ov(t,[`oldText`,`beforeText`,`before_text`])?.value??null,a=ov(t,[`newText`,`afterText`,`after_text`])?.value??null,o=ov(t,[`patch`,`diff`,`unifiedDiff`,`unified_diff`])?.value??null,s={};return n&&(s.path=n),r&&(s.content=r),i&&(s.oldText=i),a&&(s.newText=a),o&&(s.patch=o),Object.keys(s).length>0?s:null}function fv(e){return cv(e.path)??cv(e.filePath)??cv(e.file_path)??cv(e.targetPath)??cv(e.target_path)??cv(e.filename)??cv(e.name)}function pv(e){return $(e.operation)??$(e.op)??$(e.action)??$(e.kind)??$(e.type)??$(e.status)}function mv(e,t){for(let n of t){let t=lv(e[n]);if(t!==null)return t}return null}function hv(e){return mv(e,[`oldStartLine`,`old_start_line`,`startOldLine`,`start_old_line`,`oldLineStart`,`old_line_start`,`oldLineNumber`,`old_line_number`,`lineStart`,`line_start`,`startLine`,`start_line`,`lineNumber`,`line_number`])}function gv(e){return mv(e,[`newStartLine`,`new_start_line`,`startNewLine`,`start_new_line`,`newLineStart`,`new_line_start`,`newLineNumber`,`new_line_number`,`lineStart`,`line_start`,`startLine`,`start_line`,`lineNumber`,`line_number`])}function _v(e){return $(e.patch)??$(e.diff)??$(e.unifiedDiff)??$(e.unified_diff)}function vv(e){return $(e.beforeText)??$(e.before_text)??$(e.oldText)??$(e.old_text)??$(e.oldContent)??$(e.old_content)??$(e.before)??$(e.previous)}function yv(e){return $(e.afterText)??$(e.after_text)??$(e.newText)??$(e.new_text)??$(e.newContent)??$(e.new_content)??$(e.content)??$(e.text)??$(e.after)??$(e.updated)}var bv=new Set([`file_change`,`read_file`,`write_file`,`edit_file`,`apply_patch`]);function xv(e){let t=e.map((e,t)=>({key:`${e.path}-${t+1}`,path:e.path,display:e.display,...e.caption?{caption:e.caption}:{},lines:e.lines,...e.rawText?{rawText:e.rawText}:{},...e.truncated?{truncated:!0}:{}})).filter(e=>e.lines.length>0||!!e.rawText);if(t.length===0)return null;let n=t.map(e=>e.path);return{summary:n.length===1?n[0]:`${n.length} files · ${n.slice(0,2).join(` · `)}${n.length>2?` …`:``}`,fileOperation:{blocks:t}}}function Sv(e,t){let n=fv(e)??t,r=pv(e),i=hv(e),a=gv(e),o=_v(e);if(o){let e=nv(o);if(e.length>0)return e[0]??null}let s=vv(e),c=yv(e);if(s!=null||c!=null)return X_({path:n,beforeText:s,afterText:c,operation:r,oldStartLine:i,newStartLine:a});let l=$(e.preview);return l?Y_({path:n,text:l,operation:r,oldStartLine:i,newStartLine:a}):null}function Cv(e){if(!Array.isArray(e))return[];let t=[];return e.forEach((e,n)=>{if(typeof e==`string`){let n=nv(e);n.length>0&&t.push(...n);return}if(!sv(e))return;let r=Sv(e,fv(e)??`file-${n+1}`);if(r){t.push(r);return}let i=Array.isArray(e.changes)?Cv(e.changes):[];i.length>0&&t.push(...i)}),t}function wv(e){let t=uv(e.result)??uv(e.parsedArgs)??uv(e.args);return t?xv(Cv(t.changes)):null}function Tv(e){let t=uv(e.parsedArgs)??uv(e.args)??dv(e.args),n=t&&fv(t),r=$(e.result);return!n||!r?null:xv([Y_({path:n,text:r,operation:`read`})].filter(e=>!!e))}function Ev(e){if(e.status===`partial-call`&&typeof e.args==`string`){let t=ov(e.args,[`path`,`filePath`,`file_path`,`targetPath`,`target_path`,`filename`,`name`]),n=ov(e.args,[`content`,`text`,`afterText`,`after_text`]);if(t?.value&&n?.value){let e=Y_({path:t.value,text:n.value,operation:`write`});if(e)return xv([e])}}let t=uv(e.parsedArgs)??uv(e.args)??dv(e.args);if(!t)return null;let n=fv(t),r=$(t.content);return!n||!r?null:xv([Y_({path:n,text:r,operation:`write`})].filter(e=>!!e))}function Dv(e){let t=uv(e.result),n=uv(e.parsedArgs)??uv(e.args)??dv(e.args);if(!t&&!n)return null;let r=(t?fv(t):null)??(n?fv(n):null),i=(t?vv(t):null)??(n?vv(n):null),a=(t?yv(t):null)??(n?yv(n):null),o=(t?hv(t):null)??(n?hv(n):null),s=(t?gv(t):null)??(n?gv(n):null);return!r||i==null&&a==null?null:xv([X_({path:r,beforeText:i,afterText:a,operation:`edit`,oldStartLine:o,newStartLine:s})].filter(e=>!!e))}function Ov(e){let t=uv(e.parsedArgs),n=uv(e.args)??dv(e.args),r=$(e.args)??(t?$(t.patch):null)??(n?$(n.patch):null);return r?xv(nv(r)):null}function kv(e){return bv.has(e.toolName)?e.toolName===`file_change`?wv(e):e.toolName===`read_file`?Tv(e):e.toolName===`write_file`?Ev(e):e.toolName===`edit_file`?Dv(e):e.toolName===`apply_patch`?Ov(e):null:null}function Av(e){return typeof e==`object`&&!!e}function jv(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function Mv(e){return!Av(e)||e.kind!==`nextclaw.session_request`?null:e}function Nv(e,t){return[jv(e.title)?`title: ${e.title?.trim()}`:null,jv(e.sessionId)?`session: ${e.sessionId?.trim()}`:null,jv(e.task)?`task: ${e.task?.trim()}`:null].filter(e=>!!e).join(` · `)||m_(t)}function Pv(e){let t=jv(e.requestId),n=jv(e.sessionId),r=jv(e.title),i=jv(e.task),a=e.message===void 0?``:f_(e.message).trim(),o=e.finalResponseText===void 0?``:f_(e.finalResponseText).trim(),s=e.error===void 0?``:f_(e.error).trim(),c=[t?`Request ID: ${t}`:null,n?`Session ID: ${n}`:null,typeof e.isChildSession==`boolean`?`Target: ${e.isChildSession?`child`:`session`}`:null,r?`Title: ${r}`:null,i?`Task:\n${i}`:null,o?`Final Response:\n${o}`:s?`Error:\n${s}`:a?`Status:\n${a}`:null].filter(e=>!!e);return c.length>0?c.join(`
41
41
 
42
42
  `):void 0}function Fv(e){let{invocation:t,texts:n}=e,{toolName:r,toolCallId:i,args:a,result:o}=t;if(r!==`spawn`&&r!==`sessions_request`)return null;let s=Mv(o);if(!s)return null;let c=jv(s.status)?.toLowerCase(),l=Nv(s,a),u=Pv(s),d=jv(s.sessionId),f=N_({args:a,result:s}),p=d?{kind:`open-session`,sessionId:d,sessionKind:s.isChildSession===!0?`child`:`session`,...f?{agentId:f}:{},...jv(s.title)?{label:s.title.trim()}:{},...jv(s.parentSessionId)?{parentSessionId:s.parentSessionId.trim()}:{}}:void 0;return c===`failed`?{kind:`result`,name:r,detail:l,text:u,callId:i||void 0,hasResult:!!u,statusTone:`error`,statusLabel:n.toolStatusFailedLabel,...f?{agentId:f}:{},...p?{action:p}:{}}:c===`completed`?{kind:`result`,name:r,detail:l,text:u,callId:i||void 0,hasResult:!!u,statusTone:`success`,statusLabel:n.toolStatusCompletedLabel,...f?{agentId:f}:{},...p?{action:p}:{}}:{kind:`result`,name:r,detail:l,text:u,callId:i||void 0,hasResult:!!u,statusTone:`running`,statusLabel:n.toolStatusRunningLabel,...f?{agentId:f}:{},...p?{action:p}:{}}}function Iv(e){return typeof e==`object`&&!!e}function Lv(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function Rv(e){if(typeof e==`number`&&Number.isFinite(e)&&e>=0)return e;if(typeof e!=`string`)return null;let t=e.trim();if(!t)return null;let n=Number(t);return Number.isFinite(n)&&n>=0?n:null}function zv(e){return Iv(e)?`command`in e||`workingDir`in e||`exitCode`in e||`stdout`in e||`stderr`in e||`aggregated_output`in e||`combinedOutput`in e:!1}function Bv(e,t){if(!Iv(e))return null;let n=Iv(e.asset)?e.asset:Array.isArray(e.assets)&&e.assets.length>0&&Iv(e.assets[0])?e.assets[0]:null;if(!n)return null;let r=Lv(n.url),i=Lv(n.mimeType)??`application/octet-stream`,a=Rv(n.sizeBytes);return r?{type:`file`,file:{label:Lv(n.name)??(i.startsWith(`image/`)?t.imageAttachmentLabel:t.fileAttachmentLabel),mimeType:i,dataUrl:r,...a==null?{}:{sizeBytes:a},isImage:i.startsWith(`image/`)}}:null}function Vv(e,t){return{kind:e.kind,toolName:e.name,...`agentId`in e&&e.agentId?{agentId:e.agentId}:{},summary:e.detail,inputLabel:t.toolInputLabel,input:`input`in e&&typeof e.input==`string`?e.input:void 0,output:e.text,outputData:e.outputData,hasResult:!!e.hasResult,statusTone:e.statusTone,statusLabel:e.statusLabel,titleLabel:e.kind===`call`?t.toolCallLabel:t.toolResultLabel,outputLabel:t.toolOutputLabel,emptyLabel:t.toolNoOutputLabel,...`action`in e&&e.action?{action:e.action}:{},...`fileOperation`in e&&e.fileOperation?{fileOperation:e.fileOperation}:{}}}function Hv(e){let t=typeof e.status==`string`?e.status.trim().toLowerCase():``,n=typeof e.error==`string`&&e.error.trim().length>0;return e.cancelled===!0||t===`cancelled`?{kind:`result`,hasResult:!0,statusTone:`cancelled`,statusLabel:e.texts.toolStatusCancelledLabel}:n||t===`error`?{kind:`result`,hasResult:!0,statusTone:`error`,statusLabel:e.texts.toolStatusFailedLabel}:t===`result`||e.result!=null?{kind:`result`,hasResult:!0,statusTone:`success`,statusLabel:e.texts.toolStatusCompletedLabel}:{kind:`call`,hasResult:!1,statusTone:`running`,statusLabel:e.texts.toolStatusRunningLabel}}function Uv(e){if(typeof e!=`string`)return e;let t=e.trim();if(!t.startsWith(`{`)&&!t.startsWith(`[`))return e;try{return JSON.parse(t)}catch{return e}}function Wv(e,t){return f_(t??Uv(e)).trim()||void 0}function Gv(e,t){let n=O_(e.reasoning);return n?{type:`reasoning`,text:n,label:t.reasoningLabel}:null}function Kv(e,t){let n=e.mimeType.startsWith(`image/`),r=Rv(e.sizeBytes);return{type:`file`,file:{label:typeof e.name==`string`&&e.name.trim()?e.name.trim():n?t.imageAttachmentLabel:t.fileAttachmentLabel,mimeType:e.mimeType,dataUrl:typeof e.url==`string`&&e.url.trim().length>0?e.url.trim():`data:${e.mimeType};base64,${e.data}`,...r==null?{}:{sizeBytes:r},isImage:n}}}function qv(e,t){let n=e.toolInvocation,r=Bv(n.result,t);if(r)return r;let i=Fv({invocation:n,texts:{toolStatusRunningLabel:t.toolStatusRunningLabel,toolStatusCompletedLabel:t.toolStatusCompletedLabel,toolStatusFailedLabel:t.toolStatusFailedLabel}});if(i)return{type:`tool-card`,card:Vv(i,t)};let a=Hv({status:n.status,error:n.error,cancelled:n.cancelled,result:n.result,texts:t}),o=kv({toolName:n.toolName,status:n.status,toolCallId:n.toolCallId,args:n.args,parsedArgs:n.parsedArgs,result:n.result}),s=o?.summary??m_(n.parsedArgs??n.args),c=o?void 0:Wv(n.args,n.parsedArgs),l=typeof n.error==`string`&&n.error.trim()?n.error.trim():n.result==null?``:f_(n.result).trim(),u=!n.error&&zv(n.result),d=(!o?.fileOperation||!!n.error)&&!u,f=N_(n);return{type:`tool-card`,card:Vv({kind:a.kind,name:n.toolName,...f?{agentId:f}:{},detail:s,...c?{input:c}:{},text:d&&l?l:void 0,outputData:n.result,callId:n.toolCallId||void 0,hasResult:a.hasResult,statusTone:a.statusTone,statusLabel:a.statusLabel,...o?.fileOperation?{fileOperation:o.fileOperation}:{}},t)}}function Jv(e,t){return{type:`unknown`,label:t.unknownPartLabel,rawType:typeof e.type==`string`?e.type:`unknown`,text:f_(e)}}function Yv(e){return e.type===`text`&&typeof e.text==`string`}function Xv(e){return e.type===`reasoning`&&typeof e.reasoning==`string`}function Zv(e){return e.type===`file`&&typeof e.mimeType==`string`&&typeof e.data==`string`}function Qv(e){return e.type!==`tool-invocation`||!Iv(e.toolInvocation)?!1:typeof e.toolInvocation.toolName==`string`}function $v(e){return Yv(e.part)?D_(e.part,e.inlineTokens):Xv(e.part)?Gv(e.part,e.texts):Zv(e.part)?Kv(e.part,e.texts):Qv(e.part)?qv(e.part,e.texts):Jv(e.part,e.texts)}function ey(e){let t=e.meta?.timestamp;return t&&Number.isFinite(Date.parse(t))?t:new Date().toISOString()}function ty(e,t){return e===`user`?t.user:e===`assistant`?t.assistant:e===`tool`?t.tool:e===`system`?t.system:t.fallback}function ny(e){return e===`user`||e===`assistant`||e===`tool`||e===`system`?e:`message`}function ry(e,t){return{id:e.id,role:ny(e.role),roleLabel:ty(e.role,t.texts.roleLabels),timestampLabel:t.formatTimestamp(ey(e)),status:e.meta?.status,parts:e.parts.map(n=>$v({part:n,inlineTokens:e.meta?.inlineTokens??[],texts:t.texts})).filter(e=>e!==null)}}var iy={isProviderStateResolved:!1,modelOptions:[],sessionTypeUnavailable:!1,sessionTypeUnavailableMessage:null,sessionTypeLabel:null,sessionKey:null,agentId:null,agentDisplayName:null,agentAvatarUrl:null,availableAgents:[],sessionDisplayName:void 0,sessionProjectRoot:null,sessionProjectName:null,canDeleteSession:!1,isDeletePending:!1,threadRef:null,isHistoryLoading:!1,messages:[],isSending:!1,isAwaitingAssistantOutput:!1,parentSessionKey:null,parentSessionLabel:null,childSessionTabs:[],activeChildSessionKey:null},ay=S(e=>({snapshot:iy,setSnapshot:t=>e(e=>({snapshot:{...e.snapshot,...t}}))}));function oy(e,t){return new Map([...t,...e].filter(e=>typeof e.id==`string`&&e.id.trim().length>0).map(e=>[e.id,e]))}function sy(e){let t=e?.trim()??``,n=ay(e=>e.snapshot.availableAgents??[]),r=jg(),i=(0,P.useMemo)(()=>oy(n,r.data?.agents??[]),[r.data?.agents,n]);return(0,P.useMemo)(()=>{if(!t)return null;let e=i.get(t)??null;return{agentId:t,profile:e,displayName:e?.displayName?.trim()||t,avatarUrl:e?.avatarUrl?.trim()||null}},[i,t])}function cy({agentId:e,className:t}){let n=sy(e);return n?(0,I.jsx)(ir,{agentId:n.agentId,displayName:n.displayName,avatarUrl:n.avatarUrl,className:t}):null}var ly=new WeakMap;function uy(e){return{roleLabels:{user:o(`chatRoleUser`),assistant:o(`chatRoleAssistant`),tool:o(`chatRoleTool`),system:o(`chatRoleSystem`),fallback:o(`chatRoleMessage`)},reasoningLabel:o(`chatReasoning`),toolCallLabel:o(`chatToolCall`),toolResultLabel:o(`chatToolResult`),toolInputLabel:o(`chatToolInput`),toolNoOutputLabel:o(`chatToolNoOutput`),toolOutputLabel:o(`chatToolOutput`),toolStatusPreparingLabel:o(`chatToolStatusPreparing`),toolStatusRunningLabel:o(`chatToolStatusRunning`),toolStatusCompletedLabel:o(`chatToolStatusCompleted`),toolStatusFailedLabel:o(`chatToolStatusFailed`),toolStatusCancelledLabel:o(`chatToolStatusCancelled`),imageAttachmentLabel:o(`chatImageAttachment`),fileAttachmentLabel:o(`chatFileAttachment`),unknownPartLabel:o(`chatUnknownPart`)}}function dy(e){return{copyCodeLabel:o(`chatCodeCopy`),copiedCodeLabel:o(`chatCodeCopied`),copyMessageLabel:o(`chatMessageCopy`),copiedMessageLabel:o(`chatMessageCopied`),typingLabel:o(`chatTyping`)}}function fy({messages:e,isSending:t,className:n,onToolAction:r}){let{language:i}=At(),a=(0,P.useMemo)(()=>uy(i),[i]),o=(0,P.useMemo)(()=>e.map(e=>{let t=ly.get(e);if(t&&t.language===i)return t.viewModel;let n=Ue(e),r=ry({id:n.id,role:n.role,meta:{timestamp:n.meta?.timestamp,status:n.meta?.status,inlineTokens:x_(e.metadata)},parts:n.parts},{formatTimestamp:e=>c(e,i),texts:a});return ly.set(e,{language:i,viewModel:r}),r}),[i,e,a]);return(0,I.jsx)(mg,{messages:o,isSending:t,hasAssistantDraft:(0,P.useMemo)(()=>o.some(e=>e.role===`assistant`&&(e.status===`streaming`||e.status===`pending`)),[o]),className:n,texts:(0,P.useMemo)(()=>dy(i),[i]),onToolAction:r,renderToolAgent:e=>(0,I.jsx)(cy,{agentId:e,className:`h-4 w-4 shrink-0`})})}function py(e,t){return e.label?.trim()?e.label.trim():t?Ge(t):e.sessionKey}function my(e){let t=ft({limit:200}),n=(0,P.useMemo)(()=>{let e=ze(t.data?.sessions??[]);return new Map(e.map(e=>[e.key,e]))},[t.data?.sessions]);return(0,P.useMemo)(()=>e.map(e=>{let t=n.get(e.sessionKey)??null,r=e.agentId?.trim()||t?.agentId||null;return{sessionKey:e.sessionKey,parentSessionKey:e.parentSessionKey,title:py(e,t),agentId:r}}),[n,e])}function hy(e){let t=e.split(/\r?\n/),n=`message`,r=[];for(let e of t){let t=e.trimEnd();if(!(!t||t.startsWith(`:`))){if(t.startsWith(`event:`)){n=t.slice(6).trim()||`message`;continue}t.startsWith(`data:`)&&r.push(t.slice(5).trimStart())}}return r.length===0?null:{event:n,data:r.join(`
43
- `)}}async function*gy(e){let t=e.getReader(),n=new TextDecoder,r=``;try{for(;;){let{value:e,done:i}=await t.read();if(i)break;r+=n.decode(e,{stream:!0});let{frames:a,rest:o}=_y(r);r=o;for(let e of a)yield e}r+=n.decode();let{frames:e}=_y(r,!0);for(let t of e)yield t}finally{t.releaseLock()}}function _y(e,t=!1){let n=e.split(/\r?\n\r?\n/),r=n.pop()??``,i=[];for(let e of n){let t=hy(e);t&&i.push(t)}if(t&&r.trim()){let e=hy(r);return e&&i.push(e),{frames:i,rest:``}}return{frames:i,rest:r}}var vy=`/ncp/agent`,yy=`ncp-http-agent-client`,by=class extends Error{ncpError;alreadyPublished;constructor(e,t=!1){super(e.message),this.name=`NcpHttpAgentClientError(${e.code})`,this.ncpError=e,this.alreadyPublished=t}};function xy(e){let t=e.trim();if(!t)throw Error(`NcpHttpAgentClient requires a non-empty baseUrl.`);return new URL(t)}function Sy(e){if(e)return e;if(typeof globalThis.fetch==`function`)return globalThis.fetch.bind(globalThis);throw Error(`No fetch implementation found. Pass options.fetchImpl explicitly.`)}function Cy(e){let t=(e??vy).trim();if(!t)return vy;let n=t.startsWith(`/`)?t:`/${t}`;return n.endsWith(`/`)?n.slice(0,-1):n}async function wy(e){try{return(await e.text()).trim()}catch{return``}}function Ty(e){if(ky(e))return e.ncpError;if(Dy(e))return e;let t=e instanceof Error?e.message:String(e??`Unknown error`);return{code:jy(void 0),message:t,...e instanceof Error&&e.stack?{details:{stack:e.stack}}:{}}}function Ey(e,t={}){return new by(e,t.alreadyPublished??!1)}function Dy(e){return Oy(e)&&typeof e.code==`string`&&typeof e.message==`string`}function Oy(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function ky(e){return e instanceof by}var Ay={"config-error":`config-error`,"auth-error":`auth-error`,"runtime-error":`runtime-error`,"timeout-error":`timeout-error`,"abort-error":`abort-error`};function jy(e){if(!e)return`runtime-error`;let t=Ay[e];if(t)return t;let 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 My(e){let t=Py(e);return!t||typeof t.type!=`string`||!t.type.trim()?null:t}function Ny(e){let t=Py(e);if(!t)return{code:`runtime-error`,message:e||`Unknown stream error.`};let n=typeof t.code==`string`?t.code:void 0,r=jy(n),i=Oy(t.details)?t.details:{};return n&&n!==r&&(i.originalCode=n),{code:r,message:typeof t.message==`string`&&t.message?t.message:`Unknown stream error.`,...Object.keys(i).length>0?{details:i}:{}}}function Py(e){try{let t=JSON.parse(e);return Oy(t)?t:null}catch{return null}}var Fy=[`text`,`file`,`source`,`step-start`,`reasoning`,`tool-invocation`,`card`,`rich-text`,`action`,`extension`],Iy=class{manifest;baseUrl;basePath;fetchImpl;defaultHeaders;subscribers=new Set;activeControllers=new Set;started=!1;constructor(e){this.baseUrl=xy(e.baseUrl),this.basePath=Cy(e.basePath),this.fetchImpl=Sy(e.fetchImpl),this.defaultHeaders=e.headers??{},this.manifest={endpointKind:`custom`,endpointId:e.endpointId?.trim()||yy,version:`0.1.0`,supportsStreaming:!0,supportsAbort:!0,supportsProactiveMessages:!1,supportsLiveSessionStream:!0,supportedPartTypes:Fy,expectedLatency:`seconds`,metadata:{transport:`http+sse`,scope:`agent`}}}async start(){this.started||(this.started=!0,this.publish({type:F.EndpointReady}))}async stop(){if(this.started){this.started=!1;for(let 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.jsonRequest({path:`/send`,method:`POST`,body:e})}async stream(e){await this.ensureStarted();let t=new URLSearchParams({sessionId:e.sessionId});await this.streamRequest({path:`/stream?${t.toString()}`,method:`GET`})}async abort(e){await this.ensureStarted();let t=new AbortController;this.activeControllers.add(t);try{let 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 Error(`Abort request failed with HTTP ${n.status}: ${await wy(n)}`)}catch(e){if(t.signal.aborted)return;let n=Ty(e);throw this.publish({type:F.EndpointError,payload:n}),Ey(n)}finally{this.activeControllers.delete(t)}}async ensureStarted(){this.started||await this.start()}publish(e){for(let t of this.subscribers)t(e)}resolveUrl(e){return new URL(`${this.basePath}${e}`,this.baseUrl)}async jsonRequest(e){let t=new AbortController;this.activeControllers.add(t);try{let n=await this.fetchImpl(this.resolveUrl(e.path),{method:e.method,headers:{...this.defaultHeaders,"content-type":`application/json`,accept:`application/json`},body:e.body===void 0?void 0:JSON.stringify(e.body),signal:t.signal});if(!n.ok)throw Error(`NCP request failed with HTTP ${n.status}: ${await wy(n)}`)}catch(e){if(t.signal.aborted)return;if(ky(e))throw e;let n=Ty(e);throw this.publish({type:F.EndpointError,payload:n}),Ey(n)}finally{this.activeControllers.delete(t)}}async streamRequest(e){let t=new AbortController;this.activeControllers.add(t);try{let 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 Error(`NCP stream request failed with HTTP ${n.status}: ${await wy(n)}`);if(!n.body)throw Error(`NCP stream response has no body.`);for await(let e of gy(n.body)){if(t.signal.aborted)return;this.handleSseFrame(e)}}catch(e){if(t.signal.aborted)return;if(ky(e))throw e;let n=Ty(e);throw this.publish({type:F.EndpointError,payload:n}),Ey(n)}finally{this.activeControllers.delete(t)}}handleSseFrame(e){if(e.event===`ncp-event`){let t=My(e.data);if(!t){this.publish({type:F.EndpointError,payload:{code:`runtime-error`,message:`Received malformed ncp-event frame.`}});return}this.publish(t);return}if(e.event===`error`){let t=Ny(e.data);throw this.publish({type:F.EndpointError,payload:t}),Ey(t,{alreadyPublished:!0})}}};function Ly(){return(e,t)=>fetch(e,{credentials:`include`,...t})}var Ry=300;function zy(e){return e instanceof Error?e.message.includes(`ncp session not found:`):!1}function By(){return new Iy({baseUrl:d,basePath:`/api/ncp/agent`,fetchImpl:Ly()})}async function Vy(e,t,n=Ry){t.throwIfAborted();try{let r=await it(e,n);return t.throwIfAborted(),{messages:r.messages,status:r.status??`idle`}}catch(e){if(t.throwIfAborted(),!zy(e))throw e;return{messages:[],status:`idle`}}}function Hy(e,t={}){let[n]=(0,P.useState)(()=>By()),r=t.messageLimit??Ry;return Kn({sessionId:e,client:n,loadSeed:(0,P.useCallback)((e,t)=>Vy(e,t,r),[r])})}var Uy=P.createContext(null);function Wy({defaultValue:e,value:t,onValueChange:n,children:r}){return(0,I.jsx)(Uy.Provider,{value:{value:t,onValueChange:n},children:r})}function Gy({children:e,className:t}){return(0,I.jsx)(`div`,{className:u(`inline-flex h-9 items-center justify-center rounded-xl bg-gray-100/80 p-1 text-gray-500`,t),children:e})}function Ky({value:e,children:t,className:n}){let r=P.useContext(Uy);if(!r)throw Error(`TabsTrigger must be used within Tabs`);let i=r.value===e;return(0,I.jsx)(`button`,{type:`button`,onClick:()=>r.onValueChange(e),"aria-pressed":i,"data-state":i?`active`:`inactive`,className:u(`inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-[13px] font-medium ring-offset-white transition-all duration-fast focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50`,i?`bg-white text-gray-900 shadow-sm`:`hover:bg-white/50 hover:text-gray-800 text-gray-600`,n),children:t})}function qy({sessionKey:e,onToolAction:t}){let n=Hy(e),r=n.visibleMessages;return n.isHydrating?(0,I.jsxs)(`div`,{className:`flex h-full items-center justify-center text-sm text-gray-500`,children:[(0,I.jsx)(Ce,{className:`mr-2 h-4 w-4 animate-spin`}),o(`chatChildSessionLoading`)]}):n.hydrateError?(0,I.jsx)(`div`,{className:`px-4 py-5 text-sm text-rose-600`,children:n.hydrateError.message}):r.length===0&&!n.isRunning?(0,I.jsx)(`div`,{className:`px-4 py-5 text-sm text-gray-500`,children:o(`chatChildSessionEmpty`)}):(0,I.jsx)(`div`,{className:`px-4 py-5`,children:(0,I.jsx)(fy,{messages:r,isSending:n.isRunning,onToolAction:t})})}function Jy({tabs:e,activeSessionKey:t,onSelectSession:n,onClose:r,onBackToParent:i,onToolAction:a}){let s=my(e),c=s.find(e=>e.sessionKey===t)??s[0]??null,l=s.some(e=>!!e.parentSessionKey),d=s.length>1;return c?(0,I.jsx)(`aside`,{className:`hidden md:flex md:w-[24rem] lg:w-[28rem] shrink-0 border-l border-gray-200/70 bg-white/90 backdrop-blur-sm`,children:(0,I.jsxs)(`div`,{className:`flex h-full min-h-0 w-full flex-col`,children:[(0,I.jsxs)(`div`,{className:`border-b border-gray-200/70 px-4 py-3`,children:[(0,I.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,I.jsxs)(`button`,{type:`button`,onClick:i,className:u(`inline-flex items-center gap-1 text-xs font-medium text-gray-600 transition-colors hover:text-gray-900`,!l&&`pointer-events-none opacity-0`),children:[(0,I.jsx)(me,{className:`h-3.5 w-3.5`}),(0,I.jsx)(`span`,{children:o(`chatBackToParent`)})]}),(0,I.jsx)(`button`,{type:`button`,onClick:r,className:`rounded-full border border-gray-200/80 p-1.5 text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-900`,"aria-label":o(`chatChildSessionClosePanel`),children:(0,I.jsx)(Ye,{className:`h-4 w-4`})})]}),d?null:(0,I.jsxs)(`div`,{className:`mt-3 flex min-w-0 items-center gap-2 text-sm font-semibold text-gray-900`,children:[c.agentId?(0,I.jsx)(cy,{agentId:c.agentId,className:`h-5 w-5 shrink-0`}):null,(0,I.jsx)(`span`,{className:`truncate`,title:c.sessionKey,children:c.title})]}),d?(0,I.jsx)(`div`,{className:`mt-3 overflow-x-auto custom-scrollbar`,children:(0,I.jsx)(Wy,{value:t,onValueChange:n,children:(0,I.jsx)(Gy,{className:`h-auto min-w-max justify-start gap-1.5 rounded-none bg-transparent p-0 text-gray-500`,children:s.map(e=>(0,I.jsxs)(Ky,{value:e.sessionKey,className:`gap-2 rounded-full border border-gray-200/80 bg-white/85 px-2.5 py-1.5 text-xs font-medium text-gray-600 shadow-none hover:border-primary/30 hover:text-primary data-[state=active]:border-primary/30 data-[state=active]:bg-primary-50/70 data-[state=active]:text-primary data-[state=active]:shadow-sm`,children:[e.agentId?(0,I.jsx)(cy,{agentId:e.agentId,className:`h-4 w-4 shrink-0`}):null,(0,I.jsx)(`span`,{className:`max-w-[132px] truncate`,children:e.title})]},e.sessionKey))})})}):null]}),(0,I.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto custom-scrollbar`,children:s.map(e=>(0,I.jsx)(`div`,{className:u(e.sessionKey===t?`block`:`hidden`),children:(0,I.jsx)(qy,{sessionKey:e.sessionKey,onToolAction:a})},e.sessionKey))})]})}):null}var Yy=[{icon:_t,titleKey:`chatWelcomeCapability1Title`,descKey:`chatWelcomeCapability1Desc`},{icon:yt,titleKey:`chatWelcomeCapability2Title`,descKey:`chatWelcomeCapability2Desc`},{icon:lt,titleKey:`chatWelcomeCapability3Title`,descKey:`chatWelcomeCapability3Desc`}];function Xy({onCreateSession:e,agents:t,selectedAgentId:n,onSelectAgent:r}){let i=t.find(e=>e.id===n)??null;return(0,I.jsx)(`div`,{className:`h-full flex items-center justify-center p-8`,children:(0,I.jsxs)(`div`,{className:`max-w-lg w-full text-center`,children:[(0,I.jsx)(`div`,{className:`mx-auto mb-6 h-16 w-16 rounded-2xl bg-primary/10 flex items-center justify-center`,children:(0,I.jsx)(vt,{className:`h-8 w-8 text-primary`})}),(0,I.jsx)(`h2`,{className:`text-xl font-semibold text-gray-900 mb-2`,children:o(`chatWelcomeTitle`)}),(0,I.jsx)(`p`,{className:`text-sm text-gray-500 mb-8`,children:o(`chatWelcomeSubtitle`)}),(0,I.jsxs)(`div`,{className:`mb-8 rounded-2xl border border-gray-200 bg-white/90 p-4 text-left shadow-card`,children:[(0,I.jsx)(`div`,{className:`text-sm font-semibold text-gray-900`,children:o(`chatDraftAgentTitle`)}),(0,I.jsx)(`p`,{className:`mt-1 text-xs text-gray-500`,children:o(`chatDraftAgentDescription`)}),(0,I.jsx)(`div`,{className:`mt-4 flex flex-wrap gap-2`,children:t.map(e=>(0,I.jsxs)(`button`,{type:`button`,onClick:()=>r(e.id),className:[`inline-flex items-center gap-2 rounded-full border px-3 py-2 text-left transition-colors`,e.id===n?`border-gray-900 bg-gray-900 text-white`:`border-gray-200 bg-white text-gray-700 hover:bg-gray-50`].join(` `),children:[(0,I.jsx)(ir,{agentId:e.id,displayName:e.displayName,avatarUrl:e.avatarUrl,className:`h-6 w-6`}),(0,I.jsx)(`span`,{className:`text-xs font-medium`,children:e.displayName?.trim()||e.id})]},e.id))}),i?(0,I.jsxs)(`div`,{className:`mt-4 flex items-center gap-2 text-xs text-gray-500`,children:[(0,I.jsxs)(`span`,{children:[o(`chatDraftAgentCurrent`),`:`]}),(0,I.jsx)(`span`,{className:`font-medium text-gray-700`,children:i.displayName?.trim()||i.id})]}):null]}),(0,I.jsx)(`div`,{className:`grid grid-cols-3 gap-3`,children:Yy.map(t=>{let n=t.icon;return(0,I.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:[(0,I.jsx)(`div`,{className:`h-9 w-9 rounded-xl bg-primary/8 flex items-center justify-center mb-3`,children:(0,I.jsx)(n,{className:`h-4.5 w-4.5 text-primary`})}),(0,I.jsx)(`div`,{className:`text-sm font-semibold text-gray-900 mb-1`,children:o(t.titleKey)}),(0,I.jsx)(`div`,{className:`text-[11px] text-gray-500 leading-relaxed`,children:o(t.descKey)})]},t.titleKey)})})]})})}function Zy(){let e=gr();return async t=>{let n=t.projectRoot?o(`chatSessionProjectUpdated`):o(`chatSessionProjectCleared`);if(!t.persistToServer){Q.getState().setSnapshot({pendingProjectRoot:t.projectRoot,pendingProjectRootSessionKey:t.sessionKey}),p.success(n);return}await e({sessionKey:t.sessionKey,patch:{projectRoot:t.projectRoot},successMessage:n}),Q.getState().setSnapshot({pendingProjectRoot:t.projectRoot,pendingProjectRootSessionKey:t.sessionKey})}}function Qy({icon:e,label:t,onClick:n,disabled:r=!1,destructive:i=!1}){return(0,I.jsxs)(`button`,{type:`button`,className:u(`flex w-full items-center gap-2 rounded-xl px-3 py-2 text-left text-sm transition-colors disabled:cursor-not-allowed disabled:opacity-50`,i?`text-destructive hover:bg-destructive/10`:`text-gray-700 hover:bg-gray-100`),onClick:n,disabled:r,children:[(0,I.jsx)(e,{className:`h-4 w-4 shrink-0`}),(0,I.jsx)(`span`,{children:t})]})}async function $y(e){let t=new URLSearchParams;typeof e?.path==`string`&&e.path.trim().length>0&&t.set(`path`,e.path.trim()),e?.includeFiles&&t.set(`includeFiles`,`1`);let n=t.toString(),r=await h.get(n?`/api/server-paths/browse?${n}`:`/api/server-paths/browse`);if(!r.ok)throw Error(r.error.message);return r.data}function eb(e){return f({queryKey:[`server-path-browse`,e.path??null,e.includeFiles??!1],queryFn:()=>$y({path:e.path,includeFiles:e.includeFiles}),enabled:e.enabled??!0,staleTime:0})}var tb=P.forwardRef(({className:e,children:t,...n},r)=>(0,I.jsx)(`div`,{ref:r,className:u(`overflow-auto`,e),...n,children:t}));tb.displayName=`ScrollArea`;function nb({open:e,currentPath:t,isSaving:n,onOpenChange:r,onConfirm:i,title:a,description:s,pathLabel:c,pathPlaceholder:l,confirmLabel:u,hint:d}){let[f,p]=(0,P.useState)(``),[h,g]=(0,P.useState)(null),[_,v]=(0,P.useState)(``);(0,P.useEffect)(()=>{if(!e)return;let n=t?.trim()||null;p(n??``),g(n),v(``)},[t,e]);let y=eb({path:h,enabled:e});(0,P.useEffect)(()=>{!e||!y.data||f.trim().length===0&&p(y.data.currentPath)},[y.data,f,e]);let b=f.trim(),x=b.length===0||n,S=(0,P.useMemo)(()=>y.error?y.error instanceof Error?y.error.message:String(y.error):null,[y.error]),C=_.trim().toLowerCase(),w=(0,P.useMemo)(()=>{let e=y.data?.entries??[];return C.length===0?e:e.filter(e=>{let t=e.name.toLowerCase(),n=e.path.toLowerCase();return t.includes(C)||n.includes(C)})},[y.data?.entries,C]),T=e=>{g(e),v(``),e&&p(e)};return(0,I.jsx)(ht,{open:e,onOpenChange:e=>{n||r(e)},children:(0,I.jsxs)(Pt,{className:`max-h-[85vh] overflow-hidden sm:h-[42rem] sm:max-w-2xl sm:grid-rows-[auto_minmax(0,1fr)]`,children:[(0,I.jsxs)(xt,{children:[(0,I.jsx)(dt,{children:a}),s?(0,I.jsx)(Tt,{children:s}):null]}),(0,I.jsxs)(`form`,{className:`flex min-h-0 flex-col gap-4`,onSubmit:e=>{e.preventDefault(),!x&&i(b)},children:[(0,I.jsxs)(`div`,{className:`space-y-2`,children:[(0,I.jsx)(Kt,{htmlFor:`server-path-picker-input`,children:c}),(0,I.jsxs)(`div`,{className:`flex gap-2`,children:[(0,I.jsx)(ct,{id:`server-path-picker-input`,value:f,onChange:e=>p(e.target.value),placeholder:l,autoFocus:!0,disabled:n}),(0,I.jsx)(m,{type:`button`,variant:`outline`,onClick:()=>T(b||null),disabled:n,children:o(`openPath`)})]})]}),(0,I.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden rounded-2xl border border-gray-200 bg-gray-50/70`,children:[(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 border-b border-gray-200 px-3 py-2`,children:[(0,I.jsxs)(m,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>T(y.data?.homePath??null),disabled:n||y.isLoading,children:[(0,I.jsx)(ln,{className:`mr-1 h-4 w-4`}),o(`homeDirectory`)]}),(0,I.jsxs)(m,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>T(y.data?.parentPath??null),disabled:!y.data?.parentPath||n||y.isLoading,children:[(0,I.jsx)(on,{className:`mr-1 h-4 w-4`}),o(`parentDirectory`)]}),(0,I.jsxs)(m,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>{y.refetch()},disabled:n||y.isLoading,children:[(0,I.jsx)(Fe,{className:`mr-1 h-4 w-4`}),o(`chatRefresh`)]})]}),(0,I.jsxs)(`div`,{className:`border-b border-gray-200 px-3 py-2`,children:[(0,I.jsx)(`div`,{className:`mb-2 text-xs font-medium text-gray-500`,children:o(`currentDirectory`)}),(0,I.jsx)(`div`,{className:`flex flex-wrap items-center gap-1 text-xs text-gray-600`,children:y.data?.breadcrumbs.map((e,t)=>(0,I.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,I.jsx)(`button`,{type:`button`,className:`rounded px-1.5 py-0.5 hover:bg-gray-200`,onClick:()=>T(e.path),disabled:n,children:e.label}),t<y.data.breadcrumbs.length-1?(0,I.jsx)($t,{className:`h-3 w-3 text-gray-400`}):null]},e.path))})]}),(0,I.jsx)(`div`,{className:`border-b border-gray-200 px-3 py-2`,children:(0,I.jsxs)(`div`,{className:`relative`,children:[(0,I.jsx)(qe,{className:`pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400`}),(0,I.jsx)(ct,{value:_,onChange:e=>v(e.target.value),placeholder:o(`pathPickerSearchPlaceholder`),disabled:n||y.isLoading,className:`pl-9`})]})}),(0,I.jsx)(tb,{className:`min-h-0 flex-1 px-2 py-2`,children:y.isLoading?(0,I.jsx)(`div`,{className:`px-2 py-6 text-sm text-gray-500`,children:o(`loading`)}):S?(0,I.jsxs)(`div`,{className:`px-2 py-4 text-sm text-destructive`,children:[o(`pathBrowseFailed`),`: `,S]}):y.data&&w.length>0?(0,I.jsx)(`div`,{className:`space-y-1`,children:w.map(e=>(0,I.jsxs)(`button`,{type:`button`,className:`flex w-full items-center gap-2 rounded-xl px-3 py-2 text-left text-sm text-gray-700 transition-colors hover:bg-white`,onClick:()=>T(e.path),disabled:n,children:[(0,I.jsx)(ye,{className:`h-4 w-4 shrink-0 text-emerald-600`}),(0,I.jsx)(`span`,{className:`truncate`,children:e.name})]},e.path))}):y.data&&y.data.entries.length>0?(0,I.jsx)(`div`,{className:`px-2 py-6 text-sm text-gray-500`,children:o(`pathPickerSearchEmpty`)}):(0,I.jsx)(`div`,{className:`px-2 py-6 text-sm text-gray-500`,children:o(`emptyDirectory`)})})]}),d?(0,I.jsx)(`p`,{className:`text-xs leading-relaxed text-gray-500`,children:d}):null,(0,I.jsxs)(jt,{children:[(0,I.jsx)(m,{type:`button`,variant:`outline`,onClick:()=>r(!1),disabled:n,children:o(`cancel`)}),(0,I.jsx)(m,{type:`submit`,disabled:x,children:n?o(`saving`):u})]})]})]})})}function rb({open:e,currentProjectRoot:t,isSaving:n,onOpenChange:r,onSave:i}){return(0,I.jsx)(nb,{open:e,currentPath:t,isSaving:n,onOpenChange:r,onConfirm:i,title:o(`chatSessionProjectDialogTitle`),description:o(`chatSessionProjectDialogDescription`),pathLabel:o(`chatSessionProjectPathLabel`),pathPlaceholder:o(`chatSessionProjectPathPlaceholder`),confirmLabel:o(`chatSessionSetProject`),hint:o(`chatSessionProjectUpdateHint`)})}function ib({sessionKey:e,canDeleteSession:t,isDeletePending:n,projectRoot:r,onDeleteSession:i}){let a=Zy(),[s,c]=(0,P.useState)(!1),[l,u]=(0,P.useState)(!1),[d,f]=(0,P.useState)(!1),p=n||d,h=async n=>{let r=t;f(!0);try{await a({sessionKey:e,projectRoot:n,persistToServer:r}),u(!1),c(!1)}finally{f(!1)}};return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)(Wt,{open:s,onOpenChange:c,children:[(0,I.jsx)(Ht,{asChild:!0,children:(0,I.jsx)(m,{variant:`ghost`,size:`icon`,className:`rounded-lg shrink-0 text-gray-400 hover:text-gray-700`,"aria-label":o(`chatSessionMoreActions`),disabled:p,children:(0,I.jsx)(nn,{className:`h-4 w-4`})})}),(0,I.jsx)(Bt,{align:`end`,className:`w-56 p-2`,children:(0,I.jsxs)(`div`,{className:`space-y-1`,children:[(0,I.jsx)(Qy,{icon:an,label:o(`chatSessionSetProject`),onClick:()=>{c(!1),u(!0)},disabled:p}),(0,I.jsx)(Qy,{icon:Je,label:o(`chatDeleteSession`),onClick:()=>{c(!1),i()},disabled:!t||p,destructive:!0})]})})]}),(0,I.jsx)(rb,{open:l,currentProjectRoot:r,isSaving:d,onOpenChange:u,onSave:h})]})}function ab({sessionKey:e,projectName:t,projectRoot:n,persistToServer:r}){let i=Zy(),[a,s]=(0,P.useState)(!1),[c,l]=(0,P.useState)(!1),[u,d]=(0,P.useState)(!1),f=async t=>{d(!0);try{await i({sessionKey:e,projectRoot:t,persistToServer:r}),l(!1),s(!1)}finally{d(!1)}};return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)(Wt,{open:a,onOpenChange:s,children:[(0,I.jsx)(Ht,{asChild:!0,children:(0,I.jsx)(`button`,{type:`button`,title:n??void 0,className:`min-w-0 max-w-[320px] shrink rounded-full border border-emerald-200 bg-emerald-50 px-2 py-0.5 text-[11px] font-medium text-emerald-700 transition-colors hover:border-emerald-300 hover:bg-emerald-100 disabled:cursor-not-allowed disabled:opacity-60`,"aria-label":o(`chatSessionSetProject`),disabled:u,children:(0,I.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,I.jsx)(an,{className:`h-3.5 w-3.5 shrink-0`}),(0,I.jsx)(`span`,{className:`truncate`,children:t}),(0,I.jsx)(T,{className:`h-3 w-3 shrink-0 opacity-70`})]})})}),(0,I.jsxs)(Bt,{align:`start`,className:`w-72 p-2`,children:[(0,I.jsxs)(`div`,{className:`px-3 pb-2 pt-1`,children:[(0,I.jsx)(`div`,{className:`text-[11px] font-medium uppercase tracking-wider text-emerald-700/80`,children:t}),n?(0,I.jsx)(`div`,{className:`mt-1 break-all text-xs text-gray-500`,children:n}):null]}),(0,I.jsxs)(`div`,{className:`space-y-1`,children:[(0,I.jsx)(Qy,{icon:pn,label:o(`chatSessionSetProject`),onClick:()=>{s(!1),l(!0)},disabled:u}),(0,I.jsx)(Qy,{icon:sn,label:o(`chatSessionClearProject`),onClick:()=>{f(null)},disabled:u})]})]})]}),(0,I.jsx)(rb,{open:c,currentProjectRoot:n,isSaving:u,onOpenChange:l,onSave:f})]})}function ob(){return(0,I.jsxs)(`section`,{className:`flex-1 min-h-0 flex flex-col overflow-hidden bg-gradient-to-b from-gray-50/60 to-white`,children:[(0,I.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto custom-scrollbar`,children:(0,I.jsx)(`div`,{className:`mx-auto w-full max-w-[min(1120px,100%)] px-6 py-5`,children:(0,I.jsxs)(`div`,{className:`space-y-4`,children:[(0,I.jsx)(`div`,{className:`h-6 w-48 animate-pulse rounded bg-gray-200`}),(0,I.jsx)(`div`,{className:`h-24 w-[78%] animate-pulse rounded-2xl bg-gray-200/80`}),(0,I.jsx)(`div`,{className:`h-20 w-[62%] animate-pulse rounded-2xl bg-gray-200/80`}),(0,I.jsx)(`div`,{className:`h-28 w-[84%] animate-pulse rounded-2xl bg-gray-200/80`})]})})}),(0,I.jsx)(`div`,{className:`border-t border-gray-200/80 bg-white p-4`,children:(0,I.jsx)(`div`,{className:`mx-auto w-full max-w-[min(1120px,100%)]`,children:(0,I.jsxs)(`div`,{className:`rounded-2xl border border-gray-200 bg-white shadow-card p-4`,children:[(0,I.jsx)(`div`,{className:`h-16 w-full animate-pulse rounded-xl bg-gray-200/80`}),(0,I.jsxs)(`div`,{className:`mt-3 flex items-center justify-between`,children:[(0,I.jsx)(`div`,{className:`h-8 w-36 animate-pulse rounded-lg bg-gray-200/80`}),(0,I.jsx)(`div`,{className:`h-8 w-20 animate-pulse rounded-lg bg-gray-200/80`})]})]})})})]})}function sb(){let e=wr(),t=ay(e=>e.snapshot),n=(0,P.useRef)(null),r=t.threadRef??n,i=t.childSessionTabs.filter(e=>e.parentSessionKey===t.sessionKey),a=i.some(e=>e.sessionKey===t.activeChildSessionKey)?t.activeChildSessionKey:i[i.length-1]?.sessionKey??null,s=!!(t.sessionKey||t.sessionTypeLabel),c=t.sessionDisplayName||(t.canDeleteSession&&t.sessionKey?t.sessionKey:null)||o(`chatSidebarNewTask`),l=!t.canDeleteSession&&t.messages.length===0&&!t.isSending,d=t.modelOptions.length>0,f=t.isProviderStateResolved&&!d,p=t.isHistoryLoading&&t.messages.length===0&&!t.isSending&&!t.isAwaitingAssistantOutput,{onScroll:m}=xh({scrollRef:r,resetKey:t.sessionKey,isLoading:t.isHistoryLoading,hasContent:t.messages.length>0,contentVersion:t.messages[t.messages.length-1]??null});return t.isProviderStateResolved?(0,I.jsxs)(`section`,{className:`flex-1 min-h-0 flex overflow-hidden bg-gradient-to-b from-gray-50/60 to-white`,children:[(0,I.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden`,children:[t.parentSessionKey?(0,I.jsx)(`div`,{className:`border-b border-gray-200/60 bg-white/75 px-5 py-2 backdrop-blur-sm`,children:(0,I.jsxs)(`button`,{type:`button`,onClick:e.chatThreadManager.goToParentSession,className:`inline-flex items-center gap-2 text-xs font-medium text-gray-600 transition-colors hover:text-gray-900`,children:[(0,I.jsx)(me,{className:`h-3.5 w-3.5`}),(0,I.jsxs)(`span`,{children:[o(`chatBackToParent`),t.parentSessionLabel?.trim()?` · ${t.parentSessionLabel.trim()}`:``]})]})}):null,(0,I.jsxs)(`div`,{className:u(`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:[(0,I.jsxs)(`div`,{className:`min-w-0 flex-1 flex items-center gap-2`,children:[t.agentId?(0,I.jsxs)(`div`,{className:`inline-flex items-center gap-2 shrink-0 rounded-full border border-gray-200 bg-white/80 px-2 py-1`,children:[(0,I.jsx)(ir,{agentId:t.agentId,displayName:t.agentDisplayName,avatarUrl:t.agentAvatarUrl,className:`h-5 w-5`}),(0,I.jsx)(`span`,{className:`max-w-[120px] truncate text-xs font-medium text-gray-700`,children:t.agentDisplayName?.trim()||t.agentId})]}):null,(0,I.jsx)(`span`,{className:`text-sm font-medium text-gray-700 truncate`,children:c}),t.sessionTypeLabel?(0,I.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.sessionProjectName?(0,I.jsx)(ab,{sessionKey:t.sessionKey??`draft`,projectName:t.sessionProjectName,projectRoot:t.sessionProjectRoot,persistToServer:t.canDeleteSession}):null]}),t.sessionKey?(0,I.jsx)(ib,{sessionKey:t.sessionKey,canDeleteSession:t.canDeleteSession,isDeletePending:t.isDeletePending,projectRoot:t.sessionProjectRoot,onDeleteSession:e.chatThreadManager.deleteSession}):null]}),f&&(0,I.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:[(0,I.jsx)(`span`,{className:`text-xs text-amber-800`,children:o(`chatModelNoOptions`)}),(0,I.jsx)(`button`,{type:`button`,onClick:e.chatThreadManager.goToProviders,className:`text-xs font-semibold text-amber-900 underline-offset-2 hover:underline`,children:o(`chatGoConfigureProvider`)})]}),t.sessionTypeUnavailable&&t.sessionTypeUnavailableMessage?.trim()&&(0,I.jsx)(`div`,{className:`px-5 py-2.5 border-b border-amber-200/70 bg-amber-50/70 shrink-0`,children:(0,I.jsx)(`span`,{className:`text-xs text-amber-800`,children:t.sessionTypeUnavailableMessage})}),(0,I.jsx)(`div`,{ref:r,onScroll:m,className:`flex-1 min-h-0 overflow-y-auto custom-scrollbar`,children:l?(0,I.jsx)(Xy,{onCreateSession:e.chatThreadManager.createSession,agents:t.availableAgents??[],selectedAgentId:t.agentId??`main`,onSelectAgent:e.chatSessionListManager.setSelectedAgentId}):p?(0,I.jsx)(`div`,{className:`h-full`}):t.messages.length===0?(0,I.jsx)(`div`,{className:`px-5 py-5 text-sm text-gray-500`,children:o(`chatNoMessages`)}):(0,I.jsx)(`div`,{className:`mx-auto w-full max-w-[min(1120px,100%)] px-6 py-5`,children:(0,I.jsx)(fy,{messages:t.messages,isSending:t.isSending&&t.isAwaitingAssistantOutput,onToolAction:e.chatThreadManager.openSessionFromToolAction},t.sessionKey??`draft`)})}),(0,I.jsx)(c_,{})]}),a?(0,I.jsx)(Jy,{tabs:i,activeSessionKey:a,onSelectSession:e.chatThreadManager.selectChildSessionDetail,onClose:e.chatThreadManager.closeChildSessionDetail,onBackToParent:e.chatThreadManager.goToParentSession,onToolAction:e.chatThreadManager.openSessionFromToolAction}):null]}):(0,I.jsx)(ob,{})}var cb={id:``,displayName:``,description:``,avatar:``,home:``},lb=[{strip:`bg-[#efc37a]`,chip:`border-[#f2d7a7] bg-[#fff8eb] text-[#8d5a18]`},{strip:`bg-[#8fd4c0]`,chip:`border-[#bde6da] bg-[#effbf7] text-[#156653]`},{strip:`bg-[#b7c9fb]`,chip:`border-[#d7e2ff] bg-[#f4f7ff] text-[#2d4d8f]`}];function ub(e,t){return t?{strip:`bg-[#e6b765]`,chip:`border-[#f2d19c] bg-[#fff8ec] text-[#90550d]`}:lb[e%lb.length]}function db(){let e=b(),t=jg(),n=Mg(),r=Ng(),[i,a]=(0,P.useState)(!1),[s,c]=(0,P.useState)(cb),l=L(e=>e.setSnapshot),d=(0,P.useMemo)(()=>t.data?.agents??[],[t.data?.agents]),f=(0,P.useMemo)(()=>[...d].sort((e,t)=>Number(!!t.builtIn)-Number(!!e.builtIn)||e.id.localeCompare(t.id)),[d]),p=async()=>{await n.mutateAsync({data:{id:s.id,...s.displayName.trim()?{displayName:s.displayName.trim()}:{},...s.description.trim()?{description:s.description.trim()}:{},...s.avatar.trim()?{avatar:s.avatar.trim()}:{},...s.home.trim()?{home:s.home.trim()}:{}}}),c(cb),a(!1)},h=t=>{l({selectedAgentId:t,selectedSessionKey:null}),e(`/chat`)};return(0,I.jsxs)(qt,{className:`space-y-5`,children:[(0,I.jsxs)(`section`,{className:`relative overflow-hidden rounded-[28px] border border-[#f0d6aa] bg-[linear-gradient(135deg,#fff7ea_0%,#fff9f1_32%,#f2fbff_100%)] px-5 py-5 sm:px-6`,children:[(0,I.jsx)(`div`,{className:`absolute inset-y-0 right-0 w-[46%] bg-[radial-gradient(circle_at_top_right,rgba(255,215,163,0.52),transparent_54%)]`}),(0,I.jsx)(`div`,{className:`absolute -bottom-10 left-8 h-32 w-32 rounded-full bg-[#ffe6c0]/55 blur-3xl`}),(0,I.jsxs)(`div`,{className:`relative grid gap-5 xl:grid-cols-[minmax(0,1fr)_320px] xl:items-center`,children:[(0,I.jsxs)(`div`,{className:`max-w-3xl space-y-3`,children:[(0,I.jsxs)(`div`,{className:`inline-flex items-center gap-2 rounded-full border border-white/70 bg-white/80 px-3 py-1 text-[11px] font-semibold tracking-[0.16em] text-[#9b6118]`,children:[(0,I.jsx)(mt,{className:`h-3.5 w-3.5`}),o(`agentsHeroEyebrow`)]}),(0,I.jsxs)(`div`,{className:`space-y-2`,children:[(0,I.jsx)(`h1`,{className:`max-w-2xl text-[30px] font-semibold leading-tight tracking-[-0.05em] text-[#2f2212] sm:text-[38px]`,children:o(`agentsHeroTitle`)}),(0,I.jsx)(`p`,{className:`max-w-2xl text-sm leading-6 text-[#6d5841] sm:text-[15px] sm:leading-7`,children:o(`agentsHeroDescription`)})]}),(0,I.jsx)(`div`,{className:`pt-1`,children:(0,I.jsxs)(`div`,{className:`inline-flex items-center gap-3 rounded-2xl border border-[#f2d5a4] bg-white/82 px-3 py-2 text-[#7a4d12] shadow-[0_14px_30px_rgba(167,117,47,0.07)]`,children:[(0,I.jsx)(`span`,{className:`text-[11px] font-semibold tracking-[0.14em]`,children:o(`agentsOverviewTotal`)}),(0,I.jsx)(`span`,{className:`text-xl font-semibold tracking-[-0.04em] text-[#1f2937]`,children:d.length})]})})]}),(0,I.jsxs)(`div`,{className:`flex shrink-0 flex-col gap-3`,children:[(0,I.jsxs)(m,{type:`button`,className:`h-10 rounded-2xl bg-[#1f5c4d] px-5 text-sm font-semibold text-white hover:bg-[#184d40]`,onClick:()=>a(!0),children:[(0,I.jsx)(Pe,{className:`mr-2 h-4 w-4`}),o(`agentsCreateButton`)]}),(0,I.jsx)(`div`,{className:`rounded-2xl border border-white/70 bg-white/72 px-4 py-3 text-xs leading-6 text-[#6d5841] shadow-[0_18px_40px_rgba(167,117,47,0.08)]`,children:o(`agentsCreateDialogHint`)})]})]})]}),(0,I.jsx)(`div`,{className:`grid gap-4 md:grid-cols-2 xl:grid-cols-3`,children:t.isLoading?(0,I.jsx)($e,{className:`md:col-span-2 xl:col-span-3 border-dashed border-[#d9dce3] bg-white/70`,children:(0,I.jsx)(tt,{className:`py-14 text-center text-sm text-gray-500`,children:o(`agentsLoading`)})}):f.length===0?(0,I.jsx)($e,{className:`md:col-span-2 xl:col-span-3 overflow-hidden border-dashed border-[#d9dce3] bg-[linear-gradient(135deg,#fff7ea_0%,#f4fbff_100%)]`,children:(0,I.jsxs)(tt,{className:`flex min-h-[240px] flex-col items-center justify-center px-6 py-14 text-center`,children:[(0,I.jsx)(`div`,{className:`mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-white/80 shadow-[0_18px_44px_rgba(0,0,0,0.08)]`,children:(0,I.jsx)(vt,{className:`h-8 w-8 text-[#d39a3b]`})}),(0,I.jsx)(`div`,{className:`text-lg font-semibold text-[#2f2212]`,children:o(`agentsEmpty`)}),(0,I.jsx)(`p`,{className:`mt-2 max-w-md text-sm leading-6 text-[#78644d]`,children:o(`agentsEmptyDescription`)}),(0,I.jsxs)(m,{type:`button`,className:`mt-5 rounded-2xl bg-[#1f5c4d] px-5 text-white hover:bg-[#184d40]`,onClick:()=>a(!0),children:[(0,I.jsx)(Pe,{className:`mr-2 h-4 w-4`}),o(`agentsCreateButton`)]})]})}):f.map((e,t)=>{let n=ub(t,!!e.builtIn);return(0,I.jsxs)($e,{className:`overflow-hidden border border-gray-200 bg-white shadow-sm transition-shadow duration-200 hover:shadow-md`,children:[(0,I.jsx)(`div`,{className:u(`h-1.5 w-full`,n.strip)}),(0,I.jsxs)(tt,{className:`flex h-full flex-col gap-4 px-4 py-4`,children:[(0,I.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,I.jsx)(ir,{agentId:e.id,displayName:e.displayName,avatarUrl:e.avatarUrl,className:`h-11 w-11 shrink-0`}),(0,I.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1 pt-0.5`,children:[(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,I.jsx)(`div`,{className:`truncate text-lg font-semibold tracking-[-0.03em] text-[#1f2937]`,children:e.displayName?.trim()||e.id}),e.builtIn?(0,I.jsxs)(`span`,{className:u(`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-medium`,n.chip),children:[(0,I.jsx)(_n,{className:`h-3 w-3`}),o(`agentsCardBuiltInTag`)]}):null]}),(0,I.jsxs)(`div`,{className:`text-[11px] font-medium uppercase tracking-[0.18em] text-[#94a3b8]`,children:[`@`,e.id]})]})]}),(0,I.jsx)(`p`,{className:`text-sm leading-6 text-[#64748b]`,children:e.description?.trim()||(e.builtIn?o(`agentsCardBuiltInSummary`):o(`agentsCardCustomSummary`))}),(0,I.jsxs)(`div`,{className:`mt-auto flex flex-col gap-4`,children:[(0,I.jsxs)(`div`,{className:`border-t border-gray-100 pt-3`,children:[(0,I.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-[#94a3b8]`,children:[(0,I.jsx)(ln,{className:`h-3.5 w-3.5`}),o(`agentsCardHomeLabel`)]}),(0,I.jsx)(`div`,{className:`mt-1.5 break-all text-sm leading-6 text-[#475569]`,children:e.workspace??`-`})]}),(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,I.jsxs)(m,{type:`button`,className:`h-9 rounded-xl bg-[#1f5c4d] px-4 text-white hover:bg-[#184d40]`,onClick:()=>h(e.id),children:[(0,I.jsx)(_t,{className:`mr-2 h-4 w-4`}),o(`agentsCardStartChat`)]}),e.builtIn?null:(0,I.jsxs)(m,{type:`button`,variant:`ghost`,className:`h-8 rounded-xl px-3 text-xs text-[#7b8794] hover:bg-[#f3f4f6] hover:text-[#475569]`,onClick:()=>r.mutate({agentId:e.id}),disabled:r.isPending,children:[(0,I.jsx)(Je,{className:`mr-1.5 h-3.5 w-3.5`}),o(`agentsRemoveAction`)]})]})]})]})]},e.id)})}),(0,I.jsx)(ht,{open:i,onOpenChange:e=>{a(e),!e&&!n.isPending&&c(cb)},children:(0,I.jsxs)(Pt,{className:`overflow-hidden border-none bg-[linear-gradient(180deg,#fff9f1_0%,#ffffff_24%)] p-0 sm:max-w-xl`,children:[(0,I.jsx)(`div`,{className:`border-b border-[#f0e2c8] px-6 py-6`,children:(0,I.jsxs)(xt,{className:`text-left`,children:[(0,I.jsx)(dt,{children:o(`agentsCreateDialogTitle`)}),(0,I.jsx)(Tt,{children:o(`agentsCreateDialogDescription`)})]})}),(0,I.jsxs)(`div`,{className:`space-y-4 px-6 py-6`,children:[(0,I.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,I.jsx)(ct,{value:s.id,onChange:e=>c(t=>({...t,id:e.target.value})),placeholder:o(`agentsFormIdPlaceholder`)}),(0,I.jsx)(ct,{value:s.displayName,onChange:e=>c(t=>({...t,displayName:e.target.value})),placeholder:o(`agentsFormNamePlaceholder`)}),(0,I.jsx)(ct,{value:s.description,onChange:e=>c(t=>({...t,description:e.target.value})),placeholder:o(`agentsFormDescriptionPlaceholder`)}),(0,I.jsx)(ct,{value:s.avatar,onChange:e=>c(t=>({...t,avatar:e.target.value})),placeholder:o(`agentsFormAvatarPlaceholder`)}),(0,I.jsx)(ct,{value:s.home,onChange:e=>c(t=>({...t,home:e.target.value})),placeholder:o(`agentsFormHomePlaceholder`)})]}),(0,I.jsx)(`div`,{className:`rounded-2xl border border-[#efe3ca] bg-[#fff9ef] px-4 py-3 text-xs leading-6 text-[#7a6246]`,children:o(`agentsCreateDialogHint`)})]}),(0,I.jsxs)(jt,{className:`border-t border-[#f1e7d4] px-6 py-5`,children:[(0,I.jsx)(m,{type:`button`,variant:`ghost`,onClick:()=>a(!1),disabled:n.isPending,children:o(`cancel`)}),(0,I.jsxs)(m,{type:`button`,className:`rounded-2xl bg-[#1f5c4d] px-5 text-white hover:bg-[#184d40]`,onClick:()=>void p(),disabled:n.isPending||s.id.trim().length===0,children:[(0,I.jsx)(Pe,{className:`mr-2 h-4 w-4`}),o(`agentsCreateAction`)]})]})]})})]})}function fb(e){return c(e??void 0)}function pb(e){return typeof e!=`number`||!Number.isFinite(e)?`-`:c(new Date(e))}function mb(e){if(typeof e!=`number`||!Number.isFinite(e))return`-`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.round(t/60);if(n<60)return`${n}m`;let r=Math.round(n/60);return r<24?`${r}h`:`${Math.round(r/24)}d`}function hb(e){let t=e.schedule;return t.kind===`cron`?t.expr?`cron ${t.expr}`:`cron`:t.kind===`every`?`every ${mb(t.everyMs)}`:t.kind===`at`?`at ${pb(t.atMs)}`:`-`}function gb(e){return e.payload.deliver?`${e.payload.channel??`-`}:${e.payload.to??`-`}`:`-`}function _b(e,t){let 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 vb(e,t){return t===`all`?!0:t===`enabled`?e.enabled:!e.enabled}function yb(){let[e,t]=(0,P.useState)(``),[n,r]=(0,P.useState)(`all`),i=gt({all:!0}),a=Ot(),s=st(),c=ot(),{confirm:l,ConfirmDialog:d}=Yt(),f=(0,P.useMemo)(()=>(i.data?.jobs??[]).filter(t=>_b(t,e)).filter(e=>vb(e,n)),[i.data,e,n]),p=async e=>{await l({title:`${o(`cronDeleteConfirm`)}?`,description:e.name?`${e.name} (${e.id})`:e.id,variant:`destructive`,confirmLabel:o(`delete`)})&&a.mutate({id:e.id})},h=async e=>{let t=!e.enabled;await l({title:t?`${o(`cronEnableConfirm`)}?`:`${o(`cronDisableConfirm`)}?`,description:e.name?`${e.name} (${e.id})`:e.id,variant:t?`default`:`destructive`,confirmLabel:o(t?`cronEnable`:`cronDisable`)})&&s.mutate({id:e.id,enabled:t})},g=async e=>{let t=!e.enabled;await l({title:t?`${o(`cronRunForceConfirm`)}?`:`${o(`cronRunConfirm`)}?`,description:e.name?`${e.name} (${e.id})`:e.id,confirmLabel:o(`cronRunNow`)})&&c.mutate({id:e.id,force:t})};return(0,I.jsxs)(qt,{fullHeight:!0,children:[(0,I.jsx)(Jt,{title:o(`cronPageTitle`),description:o(`cronPageDescription`),actions:(0,I.jsx)(m,{variant:`ghost`,size:`icon`,className:`h-9 w-9 rounded-lg text-gray-400 hover:text-gray-700 hover:bg-gray-100`,onClick:()=>i.refetch(),children:(0,I.jsx)(Re,{className:u(`h-4 w-4`,i.isFetching&&`animate-spin`)})})}),(0,I.jsx)(`div`,{className:`mb-6`,children:(0,I.jsxs)(`div`,{className:`flex flex-wrap gap-3 items-center`,children:[(0,I.jsxs)(`div`,{className:`relative flex-1 min-w-[240px]`,children:[(0,I.jsx)(ct,{value:e,onChange:e=>t(e.target.value),placeholder:o(`cronSearchPlaceholder`),className:`pl-9`}),(0,I.jsx)(lt,{className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400`})]}),(0,I.jsx)(`div`,{className:`min-w-[180px]`,children:(0,I.jsxs)(ue,{value:n,onValueChange:e=>r(e),children:[(0,I.jsx)(ne,{className:`w-full`,children:(0,I.jsx)(D,{placeholder:o(`cronStatusLabel`)})}),(0,I.jsxs)(ae,{children:[(0,I.jsx)(ce,{value:`all`,children:o(`cronStatusAll`)}),(0,I.jsx)(ce,{value:`enabled`,children:o(`cronStatusEnabled`)}),(0,I.jsx)(ce,{value:`disabled`,children:o(`cronStatusDisabled`)})]})]})}),(0,I.jsxs)(`div`,{className:`text-xs text-gray-500 ml-auto`,children:[o(`cronTotalLabel`),`: `,i.data?.total??0,` / `,f.length]})]})}),(0,I.jsx)(`div`,{className:`flex-1 overflow-auto custom-scrollbar`,children:i.isLoading?(0,I.jsx)(`div`,{className:`text-sm text-gray-400 p-4 text-center`,children:o(`cronLoading`)}):f.length===0?(0,I.jsx)(`div`,{className:`text-sm text-gray-400 p-4 text-center`,children:o(`cronEmpty`)}):(0,I.jsx)(`div`,{className:`space-y-4`,children:f.map(e=>(0,I.jsx)($e,{className:`border border-gray-200`,children:(0,I.jsx)(tt,{className:`pt-5 pb-5`,children:(0,I.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-4`,children:[(0,I.jsxs)(`div`,{className:`min-w-[220px] flex-1`,children:[(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,I.jsx)(`span`,{className:`text-sm font-semibold text-gray-900`,children:e.name||e.id}),(0,I.jsx)(`span`,{className:`text-[10px] font-semibold px-2 py-0.5 rounded-full bg-gray-100 text-gray-500`,children:e.id}),(0,I.jsx)(`span`,{className:u(`text-[10px] font-semibold px-2 py-0.5 rounded-full`,e.enabled?`bg-emerald-50 text-emerald-700`:`bg-gray-100 text-gray-500`),children:e.enabled?o(`enabled`):o(`disabled`)}),e.deleteAfterRun&&(0,I.jsx)(`span`,{className:`text-[10px] font-semibold px-2 py-0.5 rounded-full bg-amber-50 text-amber-700`,children:o(`cronOneShot`)})]}),(0,I.jsxs)(`div`,{className:`mt-2 text-xs text-gray-500`,children:[o(`cronScheduleLabel`),`: `,hb(e)]}),(0,I.jsx)(`div`,{className:`mt-2 text-sm text-gray-700 whitespace-pre-wrap break-words`,children:e.payload.message}),(0,I.jsxs)(`div`,{className:`mt-2 text-xs text-gray-500`,children:[o(`cronDeliverTo`),`: `,gb(e)]})]}),(0,I.jsxs)(`div`,{className:`min-w-[220px] text-xs text-gray-500 space-y-2`,children:[(0,I.jsxs)(`div`,{children:[(0,I.jsxs)(`span`,{className:`font-medium text-gray-700`,children:[o(`cronNextRun`),`:`]}),` `,fb(e.state.nextRunAt)]}),(0,I.jsxs)(`div`,{children:[(0,I.jsxs)(`span`,{className:`font-medium text-gray-700`,children:[o(`cronLastRun`),`:`]}),` `,fb(e.state.lastRunAt)]}),(0,I.jsxs)(`div`,{children:[(0,I.jsxs)(`span`,{className:`font-medium text-gray-700`,children:[o(`cronLastStatus`),`:`]}),` `,e.state.lastStatus??`-`]}),e.state.lastError&&(0,I.jsx)(`div`,{className:`text-[11px] text-red-500 break-words`,children:e.state.lastError})]}),(0,I.jsxs)(`div`,{className:`flex items-start gap-2 flex-wrap justify-end`,children:[(0,I.jsxs)(m,{variant:`subtle`,size:`sm`,onClick:()=>g(e),className:`gap-1`,children:[(0,I.jsx)(mn,{className:`h-3.5 w-3.5`}),o(`cronRunNow`)]}),(0,I.jsxs)(m,{variant:e.enabled?`outline`:`primary`,size:`sm`,onClick:()=>h(e),className:`gap-1`,children:[(0,I.jsx)(hn,{className:`h-3.5 w-3.5`}),e.enabled?o(`cronDisable`):o(`cronEnable`)]}),(0,I.jsxs)(m,{variant:`destructive`,size:`sm`,onClick:()=>p(e),className:`gap-1`,children:[(0,I.jsx)(Je,{className:`h-3.5 w-3.5`}),o(`delete`)]})]})]})})},e.id))})}),(0,I.jsx)(d,{})]})}function bb(e){let{view:t,routeSessionKey:n,selectedSessionKey:r,setSelectedSessionKey:i,selectedSessionKeyRef:a,resetStreamState:o}=e;(0,P.useEffect)(()=>{if(t===`chat`){if(n){r!==n&&i(n);return}r!==null&&(i(null),o())}},[o,n,r,i,t]),(0,P.useEffect)(()=>{a.current=r},[r,a])}function xb({view:e,confirmDialog:t}){return(0,I.jsxs)(`div`,{className:`h-full flex`,children:[(0,I.jsx)(Rg,{}),e===`chat`?(0,I.jsx)(sb,{}):(0,I.jsx)(`section`,{className:`flex-1 min-h-0 overflow-hidden bg-gradient-to-b from-gray-50/60 to-white`,children:e===`cron`?(0,I.jsx)(`div`,{className:`h-full overflow-auto custom-scrollbar`,children:(0,I.jsx)(`div`,{className:`mx-auto w-full max-w-[min(1120px,100%)] px-6 py-5`,children:(0,I.jsx)(yb,{})})}):e===`agents`?(0,I.jsx)(`div`,{className:`h-full overflow-auto custom-scrollbar`,children:(0,I.jsx)(`div`,{className:`mx-auto w-full max-w-[min(1180px,100%)] px-6 py-5`,children:(0,I.jsx)(db,{})})}):(0,I.jsx)(`div`,{className:`h-full overflow-hidden`,children:(0,I.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:(0,I.jsx)(Me,{forcedType:`skills`})})})}),t]})}var Sb=`sid_`;function Cb(e){let t=new TextEncoder().encode(e),n=``;for(let e of t)n+=String.fromCharCode(e);return`${Sb}${btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}`}function wb(e){if(!e.startsWith(Sb))return null;let t=e.slice(4).replace(/-/g,`+`).replace(/_/g,`/`),n=t.length%4==0?``:`=`.repeat(4-t.length%4);try{let e=atob(t+n),r=Uint8Array.from(e,e=>e.charCodeAt(0));return new TextDecoder().decode(r)}catch{return null}}function Tb(e){if(!e)return null;let t=wb(e);if(t)return t;try{return decodeURIComponent(e)}catch{return e}}function Eb(e){return`/chat/${Cb(e)}`}var Db=`native`;function Ob(e){return typeof e==`string`?e.trim().toLowerCase()||`native`:Db}function kb(e,t){return e===`native`?o(`chatSessionTypeNative`):t?.trim()||e.trim().split(/[-_]+/g).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)||e}function Ab(e){let t=new Map;for(let n of e){let e=Ob(n.value);t.set(e,{value:e,label:n.label?.trim()||kb(e),ready:n.ready??!0,reason:n.reason??null,reasonMessage:n.reasonMessage??null,supportedModels:n.supportedModels,recommendedModel:n.recommendedModel??null,cta:n.cta??null})}return t.has(`native`)||t.set(Db,{value:Db,label:kb(Db),ready:!0,reason:null,reasonMessage:null,supportedModels:void 0,recommendedModel:null,cta:null}),Array.from(t.values()).sort((e,t)=>e.value===`native`?-1:t.value===`native`?1:e.value.localeCompare(t.value))}function jb(e){let{selectedSession:t,selectedSessionKey:n,pendingSessionType:r,setPendingSessionType:i,sessionTypesData:a}=e,s=(0,P.useMemo)(()=>Ab(a?.options??[]),[a?.options]),c=(0,P.useMemo)(()=>{let e=[...s],n=Ob(t?.sessionType);return e.some(e=>e.value===n)||e.push({value:n,label:kb(n),ready:!0,reason:null,reasonMessage:null,supportedModels:void 0,recommendedModel:null,cta:null}),e.sort((e,t)=>e.value===`native`?-1:t.value===`native`?1:e.value.localeCompare(t.value))},[s,t?.sessionType]),l=(0,P.useMemo)(()=>Ob(a?.defaultType??`native`),[a?.defaultType]),u=(0,P.useRef)(null),d=(0,P.useMemo)(()=>Ob(t?.sessionType??r??l),[l,r,t?.sessionType]),f=(0,P.useMemo)(()=>c.find(e=>e.value===d)??null,[d,c]);(0,P.useEffect)(()=>{if(n)return;let e=typeof r==`string`?r.trim():``,t=Ob(r);(e.length===0||u.current===t||u.current===null&&t===`native`)&&(u.current=l,t!==l&&i(l))},[l,r,n,i]);let p=!n||!!t?.sessionTypeMutable,m=(0,P.useMemo)(()=>new Set(s.map(e=>e.value)),[s]);return{sessionTypeOptions:c,selectedSessionTypeOption:f,defaultSessionType:l,selectedSessionType:d,canEditSessionType:p,sessionTypeUnavailable:(0,P.useMemo)(()=>t&&!m.has(Ob(t.sessionType))?!0:f?.ready===!1,[m,t,f?.ready]),sessionTypeUnavailableMessage:(0,P.useMemo)(()=>t&&!m.has(Ob(t.sessionType))?`${kb(d)} ${o(`chatSessionTypeUnavailableSuffix`)}`:f?.ready===!1?f.reasonMessage?.trim()||`${f.label} setup required`:null,[m,t,d,f])}}function Mb(e){return e?.trim().toLowerCase()||`native`}function Nb(e,t){if(typeof t!=`string`)return!1;let n=t.trim();return n?e.some(e=>e.value===n):!1}function Pb(e,t){return typeof t==`string`&&e.includes(t)}function Fb(e){return e.length===0?null:e.includes(`off`)?`off`:e[0]??null}function Ib(e){let{currentValue:t,selectedSessionPreferredValue:n,fallbackPreferredValue:r,defaultValue:i,isValueSupported:a,firstAvailableValue:o,preferSessionPreferredValue:s=!1,preserveCurrentValueOnSessionChange:c=!1}=e;return a(t)&&(!s||c)?t:a(n)?n:a(r)?r:a(i)?i:o}function Lb(e){let{modelOptions:t}=e;return t.length===0?``:Ib({currentValue:e.currentSelectedModel,selectedSessionPreferredValue:e.selectedSessionPreferredModel,fallbackPreferredValue:e.fallbackPreferredModel,defaultValue:e.defaultModel,isValueSupported:e=>Nb(t,e),firstAvailableValue:t[0]?.value??``,preferSessionPreferredValue:e.preferSessionPreferredModel,preserveCurrentValueOnSessionChange:e.preserveCurrentSelectedModelOnSessionChange})}function Rb(e){let{supportedThinkingLevels:t}=e;return t.length===0?null:Ib({currentValue:e.currentSelectedThinkingLevel,selectedSessionPreferredValue:e.selectedSessionPreferredThinking,fallbackPreferredValue:e.fallbackPreferredThinking,defaultValue:e.defaultThinkingLevel,isValueSupported:e=>Pb(t,e),firstAvailableValue:Fb(t)??`off`,preferSessionPreferredValue:e.preferSessionPreferredThinking,preserveCurrentValueOnSessionChange:e.preserveCurrentSelectedThinkingOnSessionChange})}function zb(e){let t=Mb(e.sessionType),n,r=-1/0;for(let i of e.sessions){if(i.key===e.selectedSessionKey||Mb(i.sessionType)!==t)continue;let a=e.readPreference(i);if(a==null)continue;let o=Date.parse(i.updatedAt),s=Number.isFinite(o)?o:-1/0;(n===void 0||s>r)&&(n=a,r=s)}return n}function Bb(e){return zb({sessions:e.sessions,selectedSessionKey:e.selectedSessionKey,sessionType:e.sessionType,readPreference:e=>e.preferredModel?.trim()||void 0})}function Vb(e){return zb({sessions:e.sessions,selectedSessionKey:e.selectedSessionKey,sessionType:e.sessionType,readPreference:e=>e.preferredThinking??void 0})}function Hb(e){let{isPreferenceAvailable:t,emptyValue:n,selectedSessionKey:r,selectedSessionExists:i=!1,setValue:a,resolveValue:o}=e,s=(0,P.useRef)(void 0),c=(0,P.useRef)(o);(0,P.useEffect)(()=>{c.current=o},[o]),(0,P.useEffect)(()=>{let e=s.current!==r;if(!t){a(n),s.current=r;return}a(t=>c.current({currentValue:t,sessionChanged:e,preserveCurrentValueOnSessionChange:e&&!!r&&!i})),s.current=r},[n,t,i,r,a])}function Ub(e){let{modelOptions:t,selectedSessionKey:n,selectedSessionExists:r=!1,selectedSessionPreferredModel:i,fallbackPreferredModel:a,defaultModel:o,setSelectedModel:s}=e;Hb({isPreferenceAvailable:t.length>0,emptyValue:``,selectedSessionKey:n,selectedSessionExists:r,setValue:s,resolveValue:({currentValue:e,sessionChanged:n,preserveCurrentValueOnSessionChange:r})=>Lb({currentSelectedModel:e,modelOptions:t,selectedSessionPreferredModel:i,fallbackPreferredModel:a,defaultModel:o,preferSessionPreferredModel:n,preserveCurrentSelectedModelOnSessionChange:r})})}function Wb(e){let{supportedThinkingLevels:t,selectedSessionKey:n,selectedSessionExists:r=!1,selectedSessionPreferredThinking:i,fallbackPreferredThinking:a,defaultThinkingLevel:o,setSelectedThinkingLevel:s}=e;Hb({isPreferenceAvailable:t.length>0,emptyValue:null,selectedSessionKey:n,selectedSessionExists:r,setValue:s,resolveValue:({currentValue:e,sessionChanged:n,preserveCurrentValueOnSessionChange:r})=>Rb({currentSelectedThinkingLevel:e,supportedThinkingLevels:t,selectedSessionPreferredThinking:i,fallbackPreferredThinking:a,defaultThinkingLevel:o,preferSessionPreferredThinking:n,preserveCurrentSelectedThinkingOnSessionChange:r})})}function Gb(){return f({queryKey:[`ncp-session-types`],queryFn:Xe,staleTime:1e4,retry:!1})}function Kb(e,t){return e.filter(e=>Ve(e,t))}function qb(e){if(!e.supportedModels||e.supportedModels.length===0)return e.modelOptions;let t=new Set(e.supportedModels),n=e.modelOptions.filter(e=>t.has(e.value));return n.length>0?n:e.modelOptions}function Jb(e){let t=pt(),n=St(),r=ft({limit:200}),i=Gb(),a=It({sessionId:e.sessionKey,...Object.prototype.hasOwnProperty.call(e,`projectRootOverride`)?{projectRoot:e.projectRootOverride??null}:{}}),o=(t.isFetched||t.isSuccess)&&(n.isFetched||n.isSuccess),s=(0,P.useMemo)(()=>{let e=be({meta:n.data,config:t.data,onlyConfigured:!0}),r=new Set,i=[];for(let t of e)for(let e of t.models){let n=ve(t.prefix,e);!n||r.has(n)||(r.add(n),i.push({value:n,modelLabel:e,providerLabel:t.displayName,thinkingCapability:_e(t.modelThinking,e,t.aliases)}))}return i.sort((e,t)=>{let n=e.providerLabel.localeCompare(t.providerLabel);return n===0?e.modelLabel.localeCompare(t.modelLabel):n})},[n.data,t.data]),c=(0,P.useMemo)(()=>r.data?.sessions??[],[r.data?.sessions]),l=(0,P.useMemo)(()=>ze(c),[c]),u=(0,P.useMemo)(()=>Kb(l,e.query),[l,e.query]),d=(0,P.useMemo)(()=>l.find(t=>t.key===e.sessionKey)??null,[l,e.sessionKey]),f=(0,P.useMemo)(()=>a.data?.records??[],[a.data?.records]),p=jb({selectedSession:d,selectedSessionKey:e.sessionKey,pendingSessionType:e.pendingSessionType,setPendingSessionType:e.setPendingSessionType,sessionTypesData:i.data}),m=(0,P.useMemo)(()=>qb({modelOptions:s,supportedModels:p.selectedSessionTypeOption?.supportedModels}),[s,p.selectedSessionTypeOption?.supportedModels]),h=(0,P.useMemo)(()=>Bb({sessions:l,selectedSessionKey:e.sessionKey,sessionType:p.selectedSessionType}),[l,e.sessionKey,p.selectedSessionType]),g=(0,P.useMemo)(()=>m.find(t=>t.value===e.currentSelectedModel),[m,e.currentSelectedModel]),_=(0,P.useMemo)(()=>g?.thinkingCapability?.supported??[],[g?.thinkingCapability?.supported]),v=(0,P.useMemo)(()=>g?.thinkingCapability?.default??null,[g?.thinkingCapability?.default]),y=(0,P.useMemo)(()=>Vb({sessions:l,selectedSessionKey:e.sessionKey,sessionType:p.selectedSessionType}),[l,e.sessionKey,p.selectedSessionType]);return Ub({modelOptions:m,selectedSessionKey:e.sessionKey,selectedSessionExists:!!d,selectedSessionPreferredModel:d?.preferredModel,fallbackPreferredModel:p.selectedSessionTypeOption?.recommendedModel??h,defaultModel:p.selectedSessionTypeOption?.recommendedModel??t.data?.agents.defaults.model,setSelectedModel:e.setSelectedModel}),Wb({supportedThinkingLevels:_,selectedSessionKey:e.sessionKey,selectedSessionExists:!!d,selectedSessionPreferredThinking:d?.preferredThinking??null,fallbackPreferredThinking:y??null,defaultThinkingLevel:v,setSelectedThinkingLevel:e.setSelectedThinkingLevel}),{configQuery:t,configMetaQuery:n,sessionsQuery:r,sessionTypesQuery:i,sessionSkillsQuery:a,isProviderStateResolved:o,modelOptions:m,sessionSummaries:c,sessions:u,skillRecords:f,selectedSession:d,...p}}var Yb=class{constructor(e,t){this.uiManager=e,this.streamActionsManager=t,this.resolveUpdateValue=(e,t)=>typeof t==`function`?t(e):t,this.setSelectedAgentId=e=>{let t=L.getState().snapshot.selectedAgentId,n=this.resolveUpdateValue(t,e);n!==t&&L.getState().setSnapshot({selectedAgentId:n})},this.setSelectedSessionKey=e=>{let t=L.getState().snapshot.selectedSessionKey,n=this.resolveUpdateValue(t,e);n!==t&&L.getState().setSnapshot({selectedSessionKey:n})},this.createSession=e=>{let{snapshot:t}=Q.getState(),{defaultSessionType:n}=t,r=n||`native`,i=typeof e==`string`&&e.trim().length>0?e.trim():r;this.streamActionsManager.resetStreamState(),Q.getState().setSnapshot({pendingSessionType:i,pendingProjectRoot:null,pendingProjectRootSessionKey:null}),this.uiManager.goToChatRoot()},this.selectSession=e=>{this.uiManager.goToSession(e)},this.setQuery=e=>{let t=L.getState().snapshot.query,n=this.resolveUpdateValue(t,e);n!==t&&L.getState().setSnapshot({query:n})}}},Xb=async()=>{},Zb=()=>{},Qb=class{constructor(){this.actions={sendMessage:Xb,stopCurrentRun:Xb,resumeRun:Xb,resetStreamState:Zb,applyHistoryMessages:Zb},this.bind=e=>{this.actions={...this.actions,...e}},this.sendMessage=e=>this.actions.sendMessage(e),this.stopCurrentRun=()=>this.actions.stopCurrentRun(),this.resumeRun=e=>this.actions.resumeRun(e),this.resetStreamState=()=>this.actions.resetStreamState(),this.applyHistoryMessages=(e,t)=>this.actions.applyHistoryMessages(e,t)}},$b=async e=>!1,ex=class{constructor(){this.state={pathname:``},this.actions={navigate:null,confirm:$b},this.syncState=e=>{this.state={...this.state,...e}},this.bindActions=e=>{this.actions={...this.actions,...e}},this.confirm=async e=>this.actions.confirm(e),this.navigateTo=(e,t)=>{this.actions.navigate&&(this.state.pathname===e&&!t?.replace||(this.actions.navigate(e,t),this.state.pathname=e))},this.goToProviders=()=>{this.navigateTo(`/providers`)},this.goToChatRoot=e=>{this.navigateTo(`/chat`,e)},this.goToSession=(e,t)=>{this.navigateTo(Eb(e),t)}}};function tx(e){let t=e.trim();return t.length>0?t:null}function nx(e){return e??null}var rx=class{constructor(e){this.updateSession=e,this.inFlight=null,this.queued=null,this.syncSelectedSessionPreferences=()=>{let e=Q.getState().snapshot,t=L.getState().snapshot.selectedSessionKey;t&&this.enqueue({sessionKey:t,patch:{preferredModel:tx(e.selectedModel),preferredThinking:nx(e.selectedThinkingLevel)}})}}enqueue(e){this.queued=e,!this.inFlight&&this.startFlush()}startFlush(){this.inFlight=this.flush().catch(e=>{console.error(`Failed to sync chat session preferences: ${String(e)}`)}).finally(()=>{this.inFlight=null,this.queued&&this.startFlush()})}async flush(){for(;this.queued;){let e=this.queued;this.queued=null,await this.updateSession(e.sessionKey,e.patch)}}},ix=class{constructor(e,t,n){this.uiManager=e,this.streamActionsManager=t,this.getDraftSessionId=n,this.sessionPreferenceSync=new rx(Qe),this.buildAttachmentSignature=e=>[e.assetUri??``,e.url??``,e.name,e.mimeType,String(e.sizeBytes),e.contentBase64??``].join(`:`),this.hasSnapshotChanges=e=>{let t=Q.getState().snapshot;for(let[n,r]of Object.entries(e))if(!Object.is(t[n],r))return!0;return!1},this.resolveUpdateValue=(e,t)=>typeof t==`function`?t(e):t,this.isSameStringArray=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),this.syncComposerSnapshot=e=>{let t=Q.getState().snapshot.attachments,n=Tg(e,t);Q.getState().setSnapshot({composerNodes:e,attachments:n,draft:bg(e),selectedSkills:xg(e)})},this.syncComposerSnapshotWithAttachments=(e,t)=>{Q.getState().setSnapshot({composerNodes:e,attachments:t,draft:bg(e),selectedSkills:xg(e)})},this.dedupeAttachments=e=>{let t=new Set,n=[];for(let r of e){let e=this.buildAttachmentSignature(r);t.has(e)||(t.add(e),n.push(r))}return n},this.syncSnapshot=e=>{if(this.hasSnapshotChanges(e)&&(Q.getState().setSnapshot(e),Object.prototype.hasOwnProperty.call(e,`modelOptions`)||Object.prototype.hasOwnProperty.call(e,`selectedModel`)||Object.prototype.hasOwnProperty.call(e,`selectedThinkingLevel`))){let{selectedModel:e}=Q.getState().snapshot;this.reconcileThinkingForModel(e)}},this.setDraft=e=>{let t=Q.getState().snapshot.draft,n=this.resolveUpdateValue(t,e);n!==t&&this.syncComposerSnapshot(yg(n))},this.setComposerNodes=e=>{let t=Q.getState().snapshot.composerNodes,n=this.resolveUpdateValue(t,e);Object.is(n,t)||this.syncComposerSnapshot(n)},this.addAttachments=e=>{if(e.length===0)return[];let t=Q.getState().snapshot,n=new Set(t.attachments.map(this.buildAttachmentSignature)),r=this.dedupeAttachments([...t.attachments,...e]),i=r.filter(e=>!n.has(this.buildAttachmentSignature(e)));if(i.length===0)return[];let a=wg(t.composerNodes,r);return this.syncComposerSnapshotWithAttachments(a,r),i},this.restoreComposerState=(e,t)=>{let n=this.dedupeAttachments(t),r=wg(e,n);this.syncComposerSnapshotWithAttachments(r,n)},this.setPendingSessionType=e=>{let t=Q.getState().snapshot.pendingSessionType,n=this.resolveUpdateValue(t,e);n!==t&&Q.getState().setSnapshot({pendingSessionType:n})},this.send=async()=>{let e=Q.getState().snapshot,t=L.getState().snapshot,n=e.draft.trim(),r=e.attachments,i=Eg(e.composerNodes,r);if(!i.some(e=>e.type!==`text`||e.text.trim().length>0))return;let{selectedSkills:a,composerNodes:o}=e,s=t.selectedSessionKey??this.getDraftSessionId();t.selectedSessionKey||this.uiManager.goToSession(s,{replace:!0}),this.setComposerNodes(vg()),await this.streamActionsManager.sendMessage({message:n,sessionKey:s,agentId:t.selectedAgentId,sessionType:e.selectedSessionType,model:e.selectedModel||void 0,thinkingLevel:e.selectedThinkingLevel??void 0,stopSupported:!0,requestedSkills:a,attachments:r,parts:i,restoreDraftOnError:!0,composerNodes:o})},this.stop=async()=>{await this.streamActionsManager.stopCurrentRun()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.setSelectedModel=e=>{let t=Q.getState().snapshot.selectedModel,n=this.resolveUpdateValue(t,e);n!==t&&(Q.getState().setSnapshot({selectedModel:n}),this.reconcileThinkingForModel(n))},this.setSelectedThinkingLevel=e=>{let t=Q.getState().snapshot.selectedThinkingLevel,n=this.resolveUpdateValue(t,e);n!==t&&Q.getState().setSnapshot({selectedThinkingLevel:n})},this.selectSessionType=e=>{let t=Ob(e);Q.getState().setSnapshot({selectedSessionType:t,pendingSessionType:t})},this.setSelectedSkills=e=>{let t=Q.getState().snapshot,{selectedSkills:n}=t,r=this.resolveUpdateValue(n,e);this.isSameStringArray(r,n)||this.syncComposerSnapshot(Cg(t.composerNodes,r,t.skillRecords))},this.selectModel=e=>{this.setSelectedModel(e),r_.remember(e),this.sessionPreferenceSync.syncSelectedSessionPreferences()},this.selectThinkingLevel=e=>{this.setSelectedThinkingLevel(e),this.sessionPreferenceSync.syncSelectedSessionPreferences()},this.rememberSkillSelection=e=>{i_.remember(e)},this.selectSkills=e=>{let t=Q.getState().snapshot.selectedSkills;for(let n of e)t.includes(n)||this.rememberSkillSelection(n);this.setSelectedSkills(e)},this.resolveThinkingForModel=(e,t)=>{let n=e?.thinkingCapability;return!n||n.supported.length===0?null:t===`off`?`off`:t&&n.supported.includes(t)?t:n.default&&n.supported.includes(n.default)?n.default:`off`},this.reconcileThinkingForModel=e=>{let t=Q.getState().snapshot,n=t.modelOptions.find(t=>t.value===e),{selectedThinkingLevel:r}=t,i=this.resolveThinkingForModel(n,r);i!==r&&Q.getState().setSnapshot({selectedThinkingLevel:i})}}},ax=class{constructor(e,t,n){this.uiManager=e,this.sessionListManager=t,this.streamActionsManager=n,this.hasSnapshotChanges=e=>{let t=ay.getState().snapshot;for(let[n,r]of Object.entries(e))if(!Object.is(t[n],r))return!0;return!1},this.syncSnapshot=e=>{this.hasSnapshotChanges(e)&&ay.getState().setSnapshot(e)},this.deleteSession=()=>{this.deleteCurrentSession()},this.createSession=()=>{this.sessionListManager.createSession()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.upsertChildSessionTab=e=>{let{snapshot:t}=ay.getState(),n=t.childSessionTabs.findIndex(t=>t.sessionKey===e.sessionKey),r=n>=0?t.childSessionTabs.map((t,r)=>r===n?{...t,...e}:t):[...t.childSessionTabs,e];ay.getState().setSnapshot({childSessionTabs:r,activeChildSessionKey:e.sessionKey})},this.openSessionFromToolAction=e=>{if(e.kind===`open-session`){if(e.sessionKind===`child`&&!this.isCompactViewport()){let t=e.parentSessionId?.trim()||L.getState().snapshot.selectedSessionKey||null;this.upsertChildSessionTab({sessionKey:e.sessionId,parentSessionKey:t,label:e.label?.trim()||null,agentId:e.agentId?.trim()||null});return}this.uiManager.goToSession(e.sessionId)}},this.selectChildSessionDetail=e=>{let t=e.trim();if(!t)return;let{childSessionTabs:n}=ay.getState().snapshot;n.some(e=>e.sessionKey===t)&&ay.getState().setSnapshot({activeChildSessionKey:t})},this.closeChildSessionDetail=()=>{let{sessionKey:e,childSessionTabs:t,activeChildSessionKey:n}=ay.getState().snapshot;if(!e){ay.getState().setSnapshot({childSessionTabs:[],activeChildSessionKey:null});return}let r=t.filter(t=>t.parentSessionKey!==e),i=r.some(e=>e.sessionKey===n)?n:null;ay.getState().setSnapshot({childSessionTabs:r,activeChildSessionKey:i})},this.goToParentSession=()=>{let{parentSessionKey:e,childSessionTabs:t,activeChildSessionKey:n}=ay.getState().snapshot,r=t.find(e=>e.sessionKey===n)?.parentSessionKey??null,i=e??r;i&&(this.closeChildSessionDetail(),this.uiManager.goToSession(i))},this.isCompactViewport=()=>typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(`(max-width: 767px)`).matches,this.deleteCurrentSession=async()=>{let{snapshot:{selectedSessionKey:e}}=L.getState();if(e&&await this.uiManager.confirm({title:o(`chatDeleteSessionConfirm`),variant:`destructive`,confirmLabel:o(`delete`)})){ay.getState().setSnapshot({isDeletePending:!0});try{await rt(e),et(x,e),x.removeQueries({queryKey:[`ncp-session-messages`,e]}),this.streamActionsManager.resetStreamState(),this.uiManager.goToChatRoot({replace:!0})}finally{ay.getState().setSnapshot({isDeletePending:!1})}}}}},ox=class{constructor(){this.chatUiManager=new ex,this.chatStreamActionsManager=new Qb,this.chatSessionListManager=new Yb(this.chatUiManager,this.chatStreamActionsManager),this.chatInputManager=new ix(this.chatUiManager,this.chatStreamActionsManager,()=>this.getDraftSessionId()),this.chatThreadManager=new ax(this.chatUiManager,this.chatSessionListManager,this.chatStreamActionsManager),this.draftSessionId=``,this.setDraftSessionId=e=>{this.draftSessionId=e}}getDraftSessionId(){return this.draftSessionId}};function sx(e){let t=e.selectedSession?Ge(e.selectedSession):void 0,n=e.selectedSession?.agentId??e.selectedAgentId;return{currentSessionDisplayName:t,currentAgentId:n,currentAgent:e.availableAgents.find(e=>e.id===n)??null,parentSession:(0,P.useMemo)(()=>{if(!e.parentSessionId)return null;let t=e.sessionSummaries.find(t=>t.sessionId===e.parentSessionId)??null;return t?Ie(t):null},[e.parentSessionId,e.sessionSummaries]),currentSessionTypeLabel:e.sessionTypeOptions.find(t=>t.value===e.selectedSessionType)?.label??kb(e.selectedSessionType)}}function cx(e){(0,P.useEffect)(()=>{e.presenter.chatInputManager.syncSnapshot({isProviderStateResolved:e.isProviderStateResolved,defaultSessionType:e.defaultSessionType,canStopGeneration:e.canStopCurrentRun,stopDisabledReason:e.stopDisabledReason,stopSupported:!0,stopReason:void 0,sendError:e.lastSendError,isSending:e.isSending,modelOptions:e.modelOptions,sessionTypeOptions:e.sessionTypeOptions,selectedSessionType:e.selectedSessionType,canEditSessionType:e.canEditSessionType,sessionTypeUnavailable:e.sessionTypeUnavailable,skillRecords:e.skillRecords,isSkillsLoading:e.isSkillsLoading}),e.presenter.chatThreadManager.syncSnapshot({isProviderStateResolved:e.isProviderStateResolved,modelOptions:e.modelOptions,sessionTypeUnavailable:e.sessionTypeUnavailable,sessionTypeUnavailableMessage:e.sessionTypeUnavailableMessage,sessionTypeLabel:e.currentSessionTypeLabel,sessionKey:e.sessionKey,agentId:e.currentAgentId,agentDisplayName:e.currentAgent?.displayName??null,agentAvatarUrl:e.currentAgent?.avatarUrl??null,availableAgents:e.availableAgents,sessionDisplayName:e.currentSessionDisplayName,sessionProjectRoot:e.effectiveSessionProjectRoot,sessionProjectName:e.effectiveSessionProjectName,canDeleteSession:!!e.selectedSession,threadRef:e.threadRef,isHistoryLoading:e.agent.isHydrating,messages:e.agent.visibleMessages,isSending:e.isSending,isAwaitingAssistantOutput:e.isAwaitingAssistantOutput,parentSessionKey:e.parentSession?.key??null,parentSessionLabel:e.parentSession?Ge(e.parentSession):null})},[e])}function lx(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){let e=n.trim();e&&t.add(e)}return[...t]}function ux(e){let t={};e.model?.trim()&&(t.model=e.model.trim(),t.preferred_model=e.model.trim()),e.thinkingLevel?.trim()&&(t.thinking=e.thinkingLevel.trim(),t.preferred_thinking=e.thinkingLevel.trim()),e.sessionType?.trim()&&(t.session_type=e.sessionType.trim()),e.agentId?.trim()&&(t.agent_id=e.agentId.trim());let n=Le(e.projectRoot);n&&(t.project_root=n);let r=lx(e.requestedSkills);r.length>0&&(t.requested_skill_refs=r);let i=e.composerNodes?b_(e.composerNodes):[];return i.length>0&&(t[h_]=i),t}function dx({view:e}){let[t]=(0,P.useState)(()=>new ox),[n,r]=(0,P.useState)(()=>He()),i=L(e=>e.snapshot.query),a=L(e=>e.snapshot.selectedSessionKey),o=L(e=>e.snapshot.selectedAgentId),s=Q(e=>e.snapshot.pendingSessionType),c=Q(e=>e.snapshot.pendingProjectRoot),l=Q(e=>e.snapshot.pendingProjectRootSessionKey),u=jg(),d=Q(e=>e.snapshot.selectedModel),{confirm:f,ConfirmDialog:p}=Yt(),m=y(),h=b(),{sessionId:g}=v(),_=(0,P.useRef)(null),x=(0,P.useRef)(a),S=(0,P.useMemo)(()=>Tb(g),[g]),C=a??n,w=l===C,{sessionSkillsQuery:T,isProviderStateResolved:E,modelOptions:D,sessionSummaries:O,skillRecords:ee,selectedSession:k,sessionTypeOptions:te,defaultSessionType:A,selectedSessionType:j,canEditSessionType:ne,sessionTypeUnavailable:re,sessionTypeUnavailableMessage:ie}=Jb({query:i,sessionKey:C,projectRootOverride:w?c:void 0,currentSelectedModel:d,pendingSessionType:s,setPendingSessionType:t.chatInputManager.setPendingSessionType,setSelectedModel:t.chatInputManager.setSelectedModel,setSelectedThinkingLevel:t.chatInputManager.setSelectedThinkingLevel}),M=Hy(C);(0,P.useEffect)(()=>{t.setDraftSessionId(n)},[n,t]),(0,P.useEffect)(()=>{if(a===null){let e=He();r(e),t.setDraftSessionId(e)}},[t,a]);let ae=w?c:k?.projectRoot??null,oe=w?We(ae):k?.projectName??We(ae),se=k?.parentSessionId??null,ce=M.isSending||M.isRunning,le=M.isRunning,ue=M.isRunning,de=M.isRunning?null:`__preparing__`,fe=M.hydrateError?.message??M.snapshot.error?.message??null;(0,P.useEffect)(()=>{t.chatStreamActionsManager.bind({sendMessage:async e=>{if(e.sessionKey!==C)return;let n=ux({agentId:e.agentId,model:e.model,thinkingLevel:e.thinkingLevel,sessionType:e.sessionType,projectRoot:e.sessionKey===l?c:k?.projectRoot??null,requestedSkills:e.requestedSkills,composerNodes:e.composerNodes}),r=Zn({sessionId:e.sessionKey,text:e.message,attachments:e.attachments,parts:e.parts,metadata:n});if(r)try{await M.send(r)}catch(n){throw e.restoreDraftOnError&&(e.composerNodes&&e.composerNodes.length>0?t.chatInputManager.restoreComposerState?.(e.composerNodes,e.attachments??[]):t.chatInputManager.setDraft(t=>t.trim().length===0?e.message:t)),n}},stopCurrentRun:async()=>{await M.abort()},resumeRun:async e=>{e.sessionKey===C&&await M.streamRun()},resetStreamState:()=>{x.current=null},applyHistoryMessages:()=>{}})},[M,c,l,t,k?.projectRoot,C]),(0,P.useEffect)(()=>{!k||l!==k.key||(k.projectRoot??null)!==c||Q.getState().setSnapshot({pendingProjectRoot:null,pendingProjectRootSessionKey:null})},[c,l,k]),bb({view:e,routeSessionKey:S,selectedSessionKey:a,setSelectedSessionKey:t.chatSessionListManager.setSelectedSessionKey,selectedSessionKeyRef:x,resetStreamState:t.chatStreamActionsManager.resetStreamState}),(0,P.useEffect)(()=>{t.chatUiManager.syncState({pathname:m.pathname}),t.chatUiManager.bindActions({navigate:h,confirm:f})},[f,m.pathname,h,t]);let pe=(u.data?.agents?.length??0)>0?u.data?.agents??[]:[{id:k?.agentId??o}],{currentSessionDisplayName:N,currentAgentId:me,currentAgent:he,parentSession:ge,currentSessionTypeLabel:_e}=sx({selectedSession:k,selectedAgentId:o,availableAgents:pe,parentSessionId:se,sessionSummaries:O,selectedSessionType:j,sessionTypeOptions:te});return(0,P.useEffect)(()=>{!k?.agentId||o===k.agentId||t.chatSessionListManager.setSelectedAgentId(k.agentId)},[t,o,k?.agentId]),cx({presenter:t,isProviderStateResolved:E,defaultSessionType:A,canStopCurrentRun:ue,stopDisabledReason:de,lastSendError:fe,isSending:ce,modelOptions:D,sessionTypeOptions:te,selectedSessionType:j,canEditSessionType:ne,sessionTypeUnavailable:re,skillRecords:ee,isSkillsLoading:T.isLoading,sessionTypeUnavailableMessage:ie,currentSessionTypeLabel:_e,sessionKey:C,currentAgentId:me,currentAgent:he,availableAgents:pe,currentSessionDisplayName:N,effectiveSessionProjectRoot:ae,effectiveSessionProjectName:oe,selectedSession:k,threadRef:_,agent:M,isAwaitingAssistantOutput:le,parentSession:ge}),(0,I.jsx)(Cr,{presenter:t,children:(0,I.jsx)(xb,{view:e,confirmDialog:(0,I.jsx)(p,{})})})}function fx({view:e}){return(0,I.jsx)(dx,{view:e})}export{fx as ChatPage};
43
+ `)}}async function*gy(e){let t=e.getReader(),n=new TextDecoder,r=``;try{for(;;){let{value:e,done:i}=await t.read();if(i)break;r+=n.decode(e,{stream:!0});let{frames:a,rest:o}=_y(r);r=o;for(let e of a)yield e}r+=n.decode();let{frames:e}=_y(r,!0);for(let t of e)yield t}finally{t.releaseLock()}}function _y(e,t=!1){let n=e.split(/\r?\n\r?\n/),r=n.pop()??``,i=[];for(let e of n){let t=hy(e);t&&i.push(t)}if(t&&r.trim()){let e=hy(r);return e&&i.push(e),{frames:i,rest:``}}return{frames:i,rest:r}}var vy=`/ncp/agent`,yy=class extends Error{ncpError;alreadyPublished;constructor(e,t=!1){super(e.message),this.name=`NcpHttpAgentClientError(${e.code})`,this.ncpError=e,this.alreadyPublished=t}};function by(e){let t=e.trim();if(!t)throw Error(`NcpHttpAgentClient requires a non-empty baseUrl.`);return new URL(t)}function xy(e){if(e)return e;if(typeof globalThis.fetch==`function`)return globalThis.fetch.bind(globalThis);throw Error(`No fetch implementation found. Pass options.fetchImpl explicitly.`)}function Sy(e){let t=(e??`/ncp/agent`).trim();if(!t)return vy;let n=t.startsWith(`/`)?t:`/${t}`;return n.endsWith(`/`)?n.slice(0,-1):n}async function Cy(e){try{return(await e.text()).trim()}catch{return``}}function wy(e){if(Oy(e))return e.ncpError;if(Ey(e))return e;let t=e instanceof Error?e.message:String(e??`Unknown error`);return{code:Ay(void 0),message:t,...e instanceof Error&&e.stack?{details:{stack:e.stack}}:{}}}function Ty(e,t={}){return new yy(e,t.alreadyPublished??!1)}function Ey(e){return Dy(e)&&typeof e.code==`string`&&typeof e.message==`string`}function Dy(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Oy(e){return e instanceof yy}var ky={"config-error":`config-error`,"auth-error":`auth-error`,"runtime-error":`runtime-error`,"timeout-error":`timeout-error`,"abort-error":`abort-error`};function Ay(e){if(!e)return`runtime-error`;let t=ky[e];if(t)return t;let 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 jy(e){let t=Ny(e);return!t||typeof t.type!=`string`||!t.type.trim()?null:t}function My(e){let t=Ny(e);if(!t)return{code:`runtime-error`,message:e||`Unknown stream error.`};let n=typeof t.code==`string`?t.code:void 0,r=Ay(n),i=Dy(t.details)?t.details:{};return n&&n!==r&&(i.originalCode=n),{code:r,message:typeof t.message==`string`&&t.message?t.message:`Unknown stream error.`,...Object.keys(i).length>0?{details:i}:{}}}function Ny(e){try{let t=JSON.parse(e);return Dy(t)?t:null}catch{return null}}var Py=[`text`,`file`,`source`,`step-start`,`reasoning`,`tool-invocation`,`card`,`rich-text`,`action`,`extension`],Fy=class{manifest;baseUrl;basePath;fetchImpl;defaultHeaders;subscribers=new Set;activeControllers=new Set;started=!1;constructor(e){this.baseUrl=by(e.baseUrl),this.basePath=Sy(e.basePath),this.fetchImpl=xy(e.fetchImpl),this.defaultHeaders=e.headers??{},this.manifest={endpointKind:`custom`,endpointId:e.endpointId?.trim()||`ncp-http-agent-client`,version:`0.1.0`,supportsStreaming:!0,supportsAbort:!0,supportsProactiveMessages:!1,supportsLiveSessionStream:!0,supportedPartTypes:Py,expectedLatency:`seconds`,metadata:{transport:`http+sse`,scope:`agent`}}}async start(){this.started||(this.started=!0,this.publish({type:F.EndpointReady}))}async stop(){if(this.started){this.started=!1;for(let 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.jsonRequest({path:`/send`,method:`POST`,body:e})}async stream(e){await this.ensureStarted();let t=new URLSearchParams({sessionId:e.sessionId});await this.streamRequest({path:`/stream?${t.toString()}`,method:`GET`})}async abort(e){await this.ensureStarted();let t=new AbortController;this.activeControllers.add(t);try{let 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 Error(`Abort request failed with HTTP ${n.status}: ${await Cy(n)}`)}catch(e){if(t.signal.aborted)return;let n=wy(e);throw this.publish({type:F.EndpointError,payload:n}),Ty(n)}finally{this.activeControllers.delete(t)}}async ensureStarted(){this.started||await this.start()}publish(e){for(let t of this.subscribers)t(e)}resolveUrl(e){return new URL(`${this.basePath}${e}`,this.baseUrl)}async jsonRequest(e){let t=new AbortController;this.activeControllers.add(t);try{let n=await this.fetchImpl(this.resolveUrl(e.path),{method:e.method,headers:{...this.defaultHeaders,"content-type":`application/json`,accept:`application/json`},body:e.body===void 0?void 0:JSON.stringify(e.body),signal:t.signal});if(!n.ok)throw Error(`NCP request failed with HTTP ${n.status}: ${await Cy(n)}`)}catch(e){if(t.signal.aborted)return;if(Oy(e))throw e;let n=wy(e);throw this.publish({type:F.EndpointError,payload:n}),Ty(n)}finally{this.activeControllers.delete(t)}}async streamRequest(e){let t=new AbortController;this.activeControllers.add(t);try{let 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 Error(`NCP stream request failed with HTTP ${n.status}: ${await Cy(n)}`);if(!n.body)throw Error(`NCP stream response has no body.`);for await(let e of gy(n.body)){if(t.signal.aborted)return;this.handleSseFrame(e)}}catch(e){if(t.signal.aborted)return;if(Oy(e))throw e;let n=wy(e);throw this.publish({type:F.EndpointError,payload:n}),Ty(n)}finally{this.activeControllers.delete(t)}}handleSseFrame(e){if(e.event===`ncp-event`){let t=jy(e.data);if(!t){this.publish({type:F.EndpointError,payload:{code:`runtime-error`,message:`Received malformed ncp-event frame.`}});return}this.publish(t);return}if(e.event===`error`){let t=My(e.data);throw this.publish({type:F.EndpointError,payload:t}),Ty(t,{alreadyPublished:!0})}}};function Iy(){return(e,t)=>fetch(e,{credentials:`include`,...t})}var Ly=300;function Ry(e){return e instanceof Error?e.message.includes(`ncp session not found:`):!1}function zy(){return new Fy({baseUrl:d,basePath:`/api/ncp/agent`,fetchImpl:Iy()})}async function By(e,t,n=Ly){t.throwIfAborted();try{let r=await it(e,n);return t.throwIfAborted(),{messages:r.messages,status:r.status??`idle`}}catch(e){if(t.throwIfAborted(),!Ry(e))throw e;return{messages:[],status:`idle`}}}function Vy(e,t={}){let[n]=(0,P.useState)(()=>zy()),r=t.messageLimit??Ly;return Kn({sessionId:e,client:n,loadSeed:(0,P.useCallback)((e,t)=>By(e,t,r),[r])})}var Hy=P.createContext(null);function Uy({defaultValue:e,value:t,onValueChange:n,children:r}){return(0,I.jsx)(Hy.Provider,{value:{value:t,onValueChange:n},children:r})}function Wy({children:e,className:t}){return(0,I.jsx)(`div`,{className:u(`inline-flex h-9 items-center justify-center rounded-xl bg-gray-100/80 p-1 text-gray-500`,t),children:e})}function Gy({value:e,children:t,className:n}){let r=P.useContext(Hy);if(!r)throw Error(`TabsTrigger must be used within Tabs`);let i=r.value===e;return(0,I.jsx)(`button`,{type:`button`,onClick:()=>r.onValueChange(e),"aria-pressed":i,"data-state":i?`active`:`inactive`,className:u(`inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-[13px] font-medium ring-offset-white transition-all duration-fast focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50`,i?`bg-white text-gray-900 shadow-sm`:`hover:bg-white/50 hover:text-gray-800 text-gray-600`,n),children:t})}function Ky({sessionKey:e,onToolAction:t}){let n=Vy(e),r=n.visibleMessages;return n.isHydrating?(0,I.jsxs)(`div`,{className:`flex h-full items-center justify-center text-sm text-gray-500`,children:[(0,I.jsx)(Ce,{className:`mr-2 h-4 w-4 animate-spin`}),o(`chatChildSessionLoading`)]}):n.hydrateError?(0,I.jsx)(`div`,{className:`px-4 py-5 text-sm text-rose-600`,children:n.hydrateError.message}):r.length===0&&!n.isRunning?(0,I.jsx)(`div`,{className:`px-4 py-5 text-sm text-gray-500`,children:o(`chatChildSessionEmpty`)}):(0,I.jsx)(`div`,{className:`px-4 py-5`,children:(0,I.jsx)(fy,{messages:r,isSending:n.isRunning,onToolAction:t})})}function qy({tabs:e,activeSessionKey:t,onSelectSession:n,onClose:r,onBackToParent:i,onToolAction:a}){let s=my(e),c=s.find(e=>e.sessionKey===t)??s[0]??null,l=s.some(e=>!!e.parentSessionKey),d=s.length>1;return c?(0,I.jsx)(`aside`,{className:`hidden md:flex md:w-[24rem] lg:w-[28rem] shrink-0 border-l border-gray-200/70 bg-white/90 backdrop-blur-sm`,children:(0,I.jsxs)(`div`,{className:`flex h-full min-h-0 w-full flex-col`,children:[(0,I.jsxs)(`div`,{className:`border-b border-gray-200/70 px-4 py-3`,children:[(0,I.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,I.jsxs)(`button`,{type:`button`,onClick:i,className:u(`inline-flex items-center gap-1 text-xs font-medium text-gray-600 transition-colors hover:text-gray-900`,!l&&`pointer-events-none opacity-0`),children:[(0,I.jsx)(me,{className:`h-3.5 w-3.5`}),(0,I.jsx)(`span`,{children:o(`chatBackToParent`)})]}),(0,I.jsx)(`button`,{type:`button`,onClick:r,className:`rounded-full border border-gray-200/80 p-1.5 text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-900`,"aria-label":o(`chatChildSessionClosePanel`),children:(0,I.jsx)(Ye,{className:`h-4 w-4`})})]}),d?null:(0,I.jsxs)(`div`,{className:`mt-3 flex min-w-0 items-center gap-2 text-sm font-semibold text-gray-900`,children:[c.agentId?(0,I.jsx)(cy,{agentId:c.agentId,className:`h-5 w-5 shrink-0`}):null,(0,I.jsx)(`span`,{className:`truncate`,title:c.sessionKey,children:c.title})]}),d?(0,I.jsx)(`div`,{className:`mt-3 overflow-x-auto custom-scrollbar`,children:(0,I.jsx)(Uy,{value:t,onValueChange:n,children:(0,I.jsx)(Wy,{className:`h-auto min-w-max justify-start gap-1.5 rounded-none bg-transparent p-0 text-gray-500`,children:s.map(e=>(0,I.jsxs)(Gy,{value:e.sessionKey,className:`gap-2 rounded-full border border-gray-200/80 bg-white/85 px-2.5 py-1.5 text-xs font-medium text-gray-600 shadow-none hover:border-primary/30 hover:text-primary data-[state=active]:border-primary/30 data-[state=active]:bg-primary-50/70 data-[state=active]:text-primary data-[state=active]:shadow-sm`,children:[e.agentId?(0,I.jsx)(cy,{agentId:e.agentId,className:`h-4 w-4 shrink-0`}):null,(0,I.jsx)(`span`,{className:`max-w-[132px] truncate`,children:e.title})]},e.sessionKey))})})}):null]}),(0,I.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto custom-scrollbar`,children:s.map(e=>(0,I.jsx)(`div`,{className:u(e.sessionKey===t?`block`:`hidden`),children:(0,I.jsx)(Ky,{sessionKey:e.sessionKey,onToolAction:a})},e.sessionKey))})]})}):null}var Jy=[{icon:_t,titleKey:`chatWelcomeCapability1Title`,descKey:`chatWelcomeCapability1Desc`},{icon:yt,titleKey:`chatWelcomeCapability2Title`,descKey:`chatWelcomeCapability2Desc`},{icon:lt,titleKey:`chatWelcomeCapability3Title`,descKey:`chatWelcomeCapability3Desc`}];function Yy({onCreateSession:e,agents:t,selectedAgentId:n,onSelectAgent:r}){let i=t.find(e=>e.id===n)??null;return(0,I.jsx)(`div`,{className:`h-full flex items-center justify-center p-8`,children:(0,I.jsxs)(`div`,{className:`max-w-lg w-full text-center`,children:[(0,I.jsx)(`div`,{className:`mx-auto mb-6 h-16 w-16 rounded-2xl bg-primary/10 flex items-center justify-center`,children:(0,I.jsx)(vt,{className:`h-8 w-8 text-primary`})}),(0,I.jsx)(`h2`,{className:`text-xl font-semibold text-gray-900 mb-2`,children:o(`chatWelcomeTitle`)}),(0,I.jsx)(`p`,{className:`text-sm text-gray-500 mb-8`,children:o(`chatWelcomeSubtitle`)}),(0,I.jsxs)(`div`,{className:`mb-8 rounded-2xl border border-gray-200 bg-white/90 p-4 text-left shadow-card`,children:[(0,I.jsx)(`div`,{className:`text-sm font-semibold text-gray-900`,children:o(`chatDraftAgentTitle`)}),(0,I.jsx)(`p`,{className:`mt-1 text-xs text-gray-500`,children:o(`chatDraftAgentDescription`)}),(0,I.jsx)(`div`,{className:`mt-4 flex flex-wrap gap-2`,children:t.map(e=>(0,I.jsxs)(`button`,{type:`button`,onClick:()=>r(e.id),className:[`inline-flex items-center gap-2 rounded-full border px-3 py-2 text-left transition-colors`,e.id===n?`border-gray-900 bg-gray-900 text-white`:`border-gray-200 bg-white text-gray-700 hover:bg-gray-50`].join(` `),children:[(0,I.jsx)(ir,{agentId:e.id,displayName:e.displayName,avatarUrl:e.avatarUrl,className:`h-6 w-6`}),(0,I.jsx)(`span`,{className:`text-xs font-medium`,children:e.displayName?.trim()||e.id})]},e.id))}),i?(0,I.jsxs)(`div`,{className:`mt-4 flex items-center gap-2 text-xs text-gray-500`,children:[(0,I.jsxs)(`span`,{children:[o(`chatDraftAgentCurrent`),`:`]}),(0,I.jsx)(`span`,{className:`font-medium text-gray-700`,children:i.displayName?.trim()||i.id})]}):null]}),(0,I.jsx)(`div`,{className:`grid grid-cols-3 gap-3`,children:Jy.map(t=>{let n=t.icon;return(0,I.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:[(0,I.jsx)(`div`,{className:`h-9 w-9 rounded-xl bg-primary/8 flex items-center justify-center mb-3`,children:(0,I.jsx)(n,{className:`h-4.5 w-4.5 text-primary`})}),(0,I.jsx)(`div`,{className:`text-sm font-semibold text-gray-900 mb-1`,children:o(t.titleKey)}),(0,I.jsx)(`div`,{className:`text-[11px] text-gray-500 leading-relaxed`,children:o(t.descKey)})]},t.titleKey)})})]})})}function Xy(){let e=gr();return async t=>{let n=t.projectRoot?o(`chatSessionProjectUpdated`):o(`chatSessionProjectCleared`);if(!t.persistToServer){Q.getState().setSnapshot({pendingProjectRoot:t.projectRoot,pendingProjectRootSessionKey:t.sessionKey}),p.success(n);return}await e({sessionKey:t.sessionKey,patch:{projectRoot:t.projectRoot},successMessage:n}),Q.getState().setSnapshot({pendingProjectRoot:t.projectRoot,pendingProjectRootSessionKey:t.sessionKey})}}function Zy({icon:e,label:t,onClick:n,disabled:r=!1,destructive:i=!1}){return(0,I.jsxs)(`button`,{type:`button`,className:u(`flex w-full items-center gap-2 rounded-xl px-3 py-2 text-left text-sm transition-colors disabled:cursor-not-allowed disabled:opacity-50`,i?`text-destructive hover:bg-destructive/10`:`text-gray-700 hover:bg-gray-100`),onClick:n,disabled:r,children:[(0,I.jsx)(e,{className:`h-4 w-4 shrink-0`}),(0,I.jsx)(`span`,{children:t})]})}async function Qy(e){let t=new URLSearchParams;typeof e?.path==`string`&&e.path.trim().length>0&&t.set(`path`,e.path.trim()),e?.includeFiles&&t.set(`includeFiles`,`1`);let n=t.toString(),r=await h.get(n?`/api/server-paths/browse?${n}`:`/api/server-paths/browse`);if(!r.ok)throw Error(r.error.message);return r.data}function $y(e){return f({queryKey:[`server-path-browse`,e.path??null,e.includeFiles??!1],queryFn:()=>Qy({path:e.path,includeFiles:e.includeFiles}),enabled:e.enabled??!0,staleTime:0})}var eb=P.forwardRef(({className:e,children:t,...n},r)=>(0,I.jsx)(`div`,{ref:r,className:u(`overflow-auto`,e),...n,children:t}));eb.displayName=`ScrollArea`;function tb({open:e,currentPath:t,isSaving:n,onOpenChange:r,onConfirm:i,title:a,description:s,pathLabel:c,pathPlaceholder:l,confirmLabel:u,hint:d}){let[f,p]=(0,P.useState)(``),[h,g]=(0,P.useState)(null),[_,v]=(0,P.useState)(``);(0,P.useEffect)(()=>{if(!e)return;let n=t?.trim()||null;p(n??``),g(n),v(``)},[t,e]);let y=$y({path:h,enabled:e});(0,P.useEffect)(()=>{!e||!y.data||f.trim().length===0&&p(y.data.currentPath)},[y.data,f,e]);let b=f.trim(),x=b.length===0||n,S=(0,P.useMemo)(()=>y.error?y.error instanceof Error?y.error.message:String(y.error):null,[y.error]),C=_.trim().toLowerCase(),w=(0,P.useMemo)(()=>{let e=y.data?.entries??[];return C.length===0?e:e.filter(e=>{let t=e.name.toLowerCase(),n=e.path.toLowerCase();return t.includes(C)||n.includes(C)})},[y.data?.entries,C]),T=e=>{g(e),v(``),e&&p(e)};return(0,I.jsx)(ht,{open:e,onOpenChange:e=>{n||r(e)},children:(0,I.jsxs)(Pt,{className:`max-h-[85vh] overflow-hidden sm:h-[42rem] sm:max-w-2xl sm:grid-rows-[auto_minmax(0,1fr)]`,children:[(0,I.jsxs)(xt,{children:[(0,I.jsx)(dt,{children:a}),s?(0,I.jsx)(Tt,{children:s}):null]}),(0,I.jsxs)(`form`,{className:`flex min-h-0 flex-col gap-4`,onSubmit:e=>{e.preventDefault(),!x&&i(b)},children:[(0,I.jsxs)(`div`,{className:`space-y-2`,children:[(0,I.jsx)(Kt,{htmlFor:`server-path-picker-input`,children:c}),(0,I.jsxs)(`div`,{className:`flex gap-2`,children:[(0,I.jsx)(ct,{id:`server-path-picker-input`,value:f,onChange:e=>p(e.target.value),placeholder:l,autoFocus:!0,disabled:n}),(0,I.jsx)(m,{type:`button`,variant:`outline`,onClick:()=>T(b||null),disabled:n,children:o(`openPath`)})]})]}),(0,I.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden rounded-2xl border border-gray-200 bg-gray-50/70`,children:[(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 border-b border-gray-200 px-3 py-2`,children:[(0,I.jsxs)(m,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>T(y.data?.homePath??null),disabled:n||y.isLoading,children:[(0,I.jsx)(ln,{className:`mr-1 h-4 w-4`}),o(`homeDirectory`)]}),(0,I.jsxs)(m,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>T(y.data?.parentPath??null),disabled:!y.data?.parentPath||n||y.isLoading,children:[(0,I.jsx)(on,{className:`mr-1 h-4 w-4`}),o(`parentDirectory`)]}),(0,I.jsxs)(m,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>{y.refetch()},disabled:n||y.isLoading,children:[(0,I.jsx)(Fe,{className:`mr-1 h-4 w-4`}),o(`chatRefresh`)]})]}),(0,I.jsxs)(`div`,{className:`border-b border-gray-200 px-3 py-2`,children:[(0,I.jsx)(`div`,{className:`mb-2 text-xs font-medium text-gray-500`,children:o(`currentDirectory`)}),(0,I.jsx)(`div`,{className:`flex flex-wrap items-center gap-1 text-xs text-gray-600`,children:y.data?.breadcrumbs.map((e,t)=>(0,I.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,I.jsx)(`button`,{type:`button`,className:`rounded px-1.5 py-0.5 hover:bg-gray-200`,onClick:()=>T(e.path),disabled:n,children:e.label}),t<y.data.breadcrumbs.length-1?(0,I.jsx)($t,{className:`h-3 w-3 text-gray-400`}):null]},e.path))})]}),(0,I.jsx)(`div`,{className:`border-b border-gray-200 px-3 py-2`,children:(0,I.jsxs)(`div`,{className:`relative`,children:[(0,I.jsx)(qe,{className:`pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400`}),(0,I.jsx)(ct,{value:_,onChange:e=>v(e.target.value),placeholder:o(`pathPickerSearchPlaceholder`),disabled:n||y.isLoading,className:`pl-9`})]})}),(0,I.jsx)(eb,{className:`min-h-0 flex-1 px-2 py-2`,children:y.isLoading?(0,I.jsx)(`div`,{className:`px-2 py-6 text-sm text-gray-500`,children:o(`loading`)}):S?(0,I.jsxs)(`div`,{className:`px-2 py-4 text-sm text-destructive`,children:[o(`pathBrowseFailed`),`: `,S]}):y.data&&w.length>0?(0,I.jsx)(`div`,{className:`space-y-1`,children:w.map(e=>(0,I.jsxs)(`button`,{type:`button`,className:`flex w-full items-center gap-2 rounded-xl px-3 py-2 text-left text-sm text-gray-700 transition-colors hover:bg-white`,onClick:()=>T(e.path),disabled:n,children:[(0,I.jsx)(ye,{className:`h-4 w-4 shrink-0 text-emerald-600`}),(0,I.jsx)(`span`,{className:`truncate`,children:e.name})]},e.path))}):y.data&&y.data.entries.length>0?(0,I.jsx)(`div`,{className:`px-2 py-6 text-sm text-gray-500`,children:o(`pathPickerSearchEmpty`)}):(0,I.jsx)(`div`,{className:`px-2 py-6 text-sm text-gray-500`,children:o(`emptyDirectory`)})})]}),d?(0,I.jsx)(`p`,{className:`text-xs leading-relaxed text-gray-500`,children:d}):null,(0,I.jsxs)(jt,{children:[(0,I.jsx)(m,{type:`button`,variant:`outline`,onClick:()=>r(!1),disabled:n,children:o(`cancel`)}),(0,I.jsx)(m,{type:`submit`,disabled:x,children:n?o(`saving`):u})]})]})]})})}function nb({open:e,currentProjectRoot:t,isSaving:n,onOpenChange:r,onSave:i}){return(0,I.jsx)(tb,{open:e,currentPath:t,isSaving:n,onOpenChange:r,onConfirm:i,title:o(`chatSessionProjectDialogTitle`),description:o(`chatSessionProjectDialogDescription`),pathLabel:o(`chatSessionProjectPathLabel`),pathPlaceholder:o(`chatSessionProjectPathPlaceholder`),confirmLabel:o(`chatSessionSetProject`),hint:o(`chatSessionProjectUpdateHint`)})}function rb({sessionKey:e,canDeleteSession:t,isDeletePending:n,projectRoot:r,onDeleteSession:i}){let a=Xy(),[s,c]=(0,P.useState)(!1),[l,u]=(0,P.useState)(!1),[d,f]=(0,P.useState)(!1),p=n||d,h=async n=>{let r=t;f(!0);try{await a({sessionKey:e,projectRoot:n,persistToServer:r}),u(!1),c(!1)}finally{f(!1)}};return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)(Wt,{open:s,onOpenChange:c,children:[(0,I.jsx)(Ht,{asChild:!0,children:(0,I.jsx)(m,{variant:`ghost`,size:`icon`,className:`rounded-lg shrink-0 text-gray-400 hover:text-gray-700`,"aria-label":o(`chatSessionMoreActions`),disabled:p,children:(0,I.jsx)(nn,{className:`h-4 w-4`})})}),(0,I.jsx)(Bt,{align:`end`,className:`w-56 p-2`,children:(0,I.jsxs)(`div`,{className:`space-y-1`,children:[(0,I.jsx)(Zy,{icon:an,label:o(`chatSessionSetProject`),onClick:()=>{c(!1),u(!0)},disabled:p}),(0,I.jsx)(Zy,{icon:Je,label:o(`chatDeleteSession`),onClick:()=>{c(!1),i()},disabled:!t||p,destructive:!0})]})})]}),(0,I.jsx)(nb,{open:l,currentProjectRoot:r,isSaving:d,onOpenChange:u,onSave:h})]})}function ib({sessionKey:e,projectName:t,projectRoot:n,persistToServer:r}){let i=Xy(),[a,s]=(0,P.useState)(!1),[c,l]=(0,P.useState)(!1),[u,d]=(0,P.useState)(!1),f=async t=>{d(!0);try{await i({sessionKey:e,projectRoot:t,persistToServer:r}),l(!1),s(!1)}finally{d(!1)}};return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)(Wt,{open:a,onOpenChange:s,children:[(0,I.jsx)(Ht,{asChild:!0,children:(0,I.jsx)(`button`,{type:`button`,title:n??void 0,className:`min-w-0 max-w-[320px] shrink rounded-full border border-emerald-200 bg-emerald-50 px-2 py-0.5 text-[11px] font-medium text-emerald-700 transition-colors hover:border-emerald-300 hover:bg-emerald-100 disabled:cursor-not-allowed disabled:opacity-60`,"aria-label":o(`chatSessionSetProject`),disabled:u,children:(0,I.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,I.jsx)(an,{className:`h-3.5 w-3.5 shrink-0`}),(0,I.jsx)(`span`,{className:`truncate`,children:t}),(0,I.jsx)(T,{className:`h-3 w-3 shrink-0 opacity-70`})]})})}),(0,I.jsxs)(Bt,{align:`start`,className:`w-72 p-2`,children:[(0,I.jsxs)(`div`,{className:`px-3 pb-2 pt-1`,children:[(0,I.jsx)(`div`,{className:`text-[11px] font-medium uppercase tracking-wider text-emerald-700/80`,children:t}),n?(0,I.jsx)(`div`,{className:`mt-1 break-all text-xs text-gray-500`,children:n}):null]}),(0,I.jsxs)(`div`,{className:`space-y-1`,children:[(0,I.jsx)(Zy,{icon:pn,label:o(`chatSessionSetProject`),onClick:()=>{s(!1),l(!0)},disabled:u}),(0,I.jsx)(Zy,{icon:sn,label:o(`chatSessionClearProject`),onClick:()=>{f(null)},disabled:u})]})]})]}),(0,I.jsx)(nb,{open:c,currentProjectRoot:n,isSaving:u,onOpenChange:l,onSave:f})]})}function ab(){return(0,I.jsxs)(`section`,{className:`flex-1 min-h-0 flex flex-col overflow-hidden bg-gradient-to-b from-gray-50/60 to-white`,children:[(0,I.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto custom-scrollbar`,children:(0,I.jsx)(`div`,{className:`mx-auto w-full max-w-[min(1120px,100%)] px-6 py-5`,children:(0,I.jsxs)(`div`,{className:`space-y-4`,children:[(0,I.jsx)(`div`,{className:`h-6 w-48 animate-pulse rounded bg-gray-200`}),(0,I.jsx)(`div`,{className:`h-24 w-[78%] animate-pulse rounded-2xl bg-gray-200/80`}),(0,I.jsx)(`div`,{className:`h-20 w-[62%] animate-pulse rounded-2xl bg-gray-200/80`}),(0,I.jsx)(`div`,{className:`h-28 w-[84%] animate-pulse rounded-2xl bg-gray-200/80`})]})})}),(0,I.jsx)(`div`,{className:`border-t border-gray-200/80 bg-white p-4`,children:(0,I.jsx)(`div`,{className:`mx-auto w-full max-w-[min(1120px,100%)]`,children:(0,I.jsxs)(`div`,{className:`rounded-2xl border border-gray-200 bg-white shadow-card p-4`,children:[(0,I.jsx)(`div`,{className:`h-16 w-full animate-pulse rounded-xl bg-gray-200/80`}),(0,I.jsxs)(`div`,{className:`mt-3 flex items-center justify-between`,children:[(0,I.jsx)(`div`,{className:`h-8 w-36 animate-pulse rounded-lg bg-gray-200/80`}),(0,I.jsx)(`div`,{className:`h-8 w-20 animate-pulse rounded-lg bg-gray-200/80`})]})]})})})]})}function ob(){let e=wr(),t=ay(e=>e.snapshot),n=(0,P.useRef)(null),r=t.threadRef??n,i=t.childSessionTabs.filter(e=>e.parentSessionKey===t.sessionKey),a=i.some(e=>e.sessionKey===t.activeChildSessionKey)?t.activeChildSessionKey:i[i.length-1]?.sessionKey??null,s=!!(t.sessionKey||t.sessionTypeLabel),c=t.sessionDisplayName||(t.canDeleteSession&&t.sessionKey?t.sessionKey:null)||o(`chatSidebarNewTask`),l=!t.canDeleteSession&&t.messages.length===0&&!t.isSending,d=t.modelOptions.length>0,f=t.isProviderStateResolved&&!d,p=t.isHistoryLoading&&t.messages.length===0&&!t.isSending&&!t.isAwaitingAssistantOutput,{onScroll:m}=xh({scrollRef:r,resetKey:t.sessionKey,isLoading:t.isHistoryLoading,hasContent:t.messages.length>0,contentVersion:t.messages[t.messages.length-1]??null});return t.isProviderStateResolved?(0,I.jsxs)(`section`,{className:`flex-1 min-h-0 flex overflow-hidden bg-gradient-to-b from-gray-50/60 to-white`,children:[(0,I.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden`,children:[t.parentSessionKey?(0,I.jsx)(`div`,{className:`border-b border-gray-200/60 bg-white/75 px-5 py-2 backdrop-blur-sm`,children:(0,I.jsxs)(`button`,{type:`button`,onClick:e.chatThreadManager.goToParentSession,className:`inline-flex items-center gap-2 text-xs font-medium text-gray-600 transition-colors hover:text-gray-900`,children:[(0,I.jsx)(me,{className:`h-3.5 w-3.5`}),(0,I.jsxs)(`span`,{children:[o(`chatBackToParent`),t.parentSessionLabel?.trim()?` · ${t.parentSessionLabel.trim()}`:``]})]})}):null,(0,I.jsxs)(`div`,{className:u(`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:[(0,I.jsxs)(`div`,{className:`min-w-0 flex-1 flex items-center gap-2`,children:[t.agentId?(0,I.jsxs)(`div`,{className:`inline-flex items-center gap-2 shrink-0 rounded-full border border-gray-200 bg-white/80 px-2 py-1`,children:[(0,I.jsx)(ir,{agentId:t.agentId,displayName:t.agentDisplayName,avatarUrl:t.agentAvatarUrl,className:`h-5 w-5`}),(0,I.jsx)(`span`,{className:`max-w-[120px] truncate text-xs font-medium text-gray-700`,children:t.agentDisplayName?.trim()||t.agentId})]}):null,(0,I.jsx)(`span`,{className:`text-sm font-medium text-gray-700 truncate`,children:c}),t.sessionTypeLabel?(0,I.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.sessionProjectName?(0,I.jsx)(ib,{sessionKey:t.sessionKey??`draft`,projectName:t.sessionProjectName,projectRoot:t.sessionProjectRoot,persistToServer:t.canDeleteSession}):null]}),t.sessionKey?(0,I.jsx)(rb,{sessionKey:t.sessionKey,canDeleteSession:t.canDeleteSession,isDeletePending:t.isDeletePending,projectRoot:t.sessionProjectRoot,onDeleteSession:e.chatThreadManager.deleteSession}):null]}),f&&(0,I.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:[(0,I.jsx)(`span`,{className:`text-xs text-amber-800`,children:o(`chatModelNoOptions`)}),(0,I.jsx)(`button`,{type:`button`,onClick:e.chatThreadManager.goToProviders,className:`text-xs font-semibold text-amber-900 underline-offset-2 hover:underline`,children:o(`chatGoConfigureProvider`)})]}),t.sessionTypeUnavailable&&t.sessionTypeUnavailableMessage?.trim()&&(0,I.jsx)(`div`,{className:`px-5 py-2.5 border-b border-amber-200/70 bg-amber-50/70 shrink-0`,children:(0,I.jsx)(`span`,{className:`text-xs text-amber-800`,children:t.sessionTypeUnavailableMessage})}),(0,I.jsx)(`div`,{ref:r,onScroll:m,className:`flex-1 min-h-0 overflow-y-auto custom-scrollbar`,children:l?(0,I.jsx)(Yy,{onCreateSession:e.chatThreadManager.createSession,agents:t.availableAgents??[],selectedAgentId:t.agentId??`main`,onSelectAgent:e.chatSessionListManager.setSelectedAgentId}):p?(0,I.jsx)(`div`,{className:`h-full`}):t.messages.length===0?(0,I.jsx)(`div`,{className:`px-5 py-5 text-sm text-gray-500`,children:o(`chatNoMessages`)}):(0,I.jsx)(`div`,{className:`mx-auto w-full max-w-[min(1120px,100%)] px-6 py-5`,children:(0,I.jsx)(fy,{messages:t.messages,isSending:t.isSending&&t.isAwaitingAssistantOutput,onToolAction:e.chatThreadManager.openSessionFromToolAction},t.sessionKey??`draft`)})}),(0,I.jsx)(c_,{})]}),a?(0,I.jsx)(qy,{tabs:i,activeSessionKey:a,onSelectSession:e.chatThreadManager.selectChildSessionDetail,onClose:e.chatThreadManager.closeChildSessionDetail,onBackToParent:e.chatThreadManager.goToParentSession,onToolAction:e.chatThreadManager.openSessionFromToolAction}):null]}):(0,I.jsx)(ab,{})}var sb={id:``,displayName:``,description:``,avatar:``,home:``},cb=[{strip:`bg-[#efc37a]`,chip:`border-[#f2d7a7] bg-[#fff8eb] text-[#8d5a18]`},{strip:`bg-[#8fd4c0]`,chip:`border-[#bde6da] bg-[#effbf7] text-[#156653]`},{strip:`bg-[#b7c9fb]`,chip:`border-[#d7e2ff] bg-[#f4f7ff] text-[#2d4d8f]`}];function lb(e,t){return t?{strip:`bg-[#e6b765]`,chip:`border-[#f2d19c] bg-[#fff8ec] text-[#90550d]`}:cb[e%cb.length]}function ub(){let e=b(),t=jg(),n=Mg(),r=Ng(),[i,a]=(0,P.useState)(!1),[s,c]=(0,P.useState)(sb),l=L(e=>e.setSnapshot),d=(0,P.useMemo)(()=>t.data?.agents??[],[t.data?.agents]),f=(0,P.useMemo)(()=>[...d].sort((e,t)=>Number(!!t.builtIn)-Number(!!e.builtIn)||e.id.localeCompare(t.id)),[d]),p=async()=>{await n.mutateAsync({data:{id:s.id,...s.displayName.trim()?{displayName:s.displayName.trim()}:{},...s.description.trim()?{description:s.description.trim()}:{},...s.avatar.trim()?{avatar:s.avatar.trim()}:{},...s.home.trim()?{home:s.home.trim()}:{}}}),c(sb),a(!1)},h=t=>{l({selectedAgentId:t,selectedSessionKey:null}),e(`/chat`)};return(0,I.jsxs)(qt,{className:`space-y-5`,children:[(0,I.jsxs)(`section`,{className:`relative overflow-hidden rounded-[28px] border border-[#f0d6aa] bg-[linear-gradient(135deg,#fff7ea_0%,#fff9f1_32%,#f2fbff_100%)] px-5 py-5 sm:px-6`,children:[(0,I.jsx)(`div`,{className:`absolute inset-y-0 right-0 w-[46%] bg-[radial-gradient(circle_at_top_right,rgba(255,215,163,0.52),transparent_54%)]`}),(0,I.jsx)(`div`,{className:`absolute -bottom-10 left-8 h-32 w-32 rounded-full bg-[#ffe6c0]/55 blur-3xl`}),(0,I.jsxs)(`div`,{className:`relative grid gap-5 xl:grid-cols-[minmax(0,1fr)_320px] xl:items-center`,children:[(0,I.jsxs)(`div`,{className:`max-w-3xl space-y-3`,children:[(0,I.jsxs)(`div`,{className:`inline-flex items-center gap-2 rounded-full border border-white/70 bg-white/80 px-3 py-1 text-[11px] font-semibold tracking-[0.16em] text-[#9b6118]`,children:[(0,I.jsx)(mt,{className:`h-3.5 w-3.5`}),o(`agentsHeroEyebrow`)]}),(0,I.jsxs)(`div`,{className:`space-y-2`,children:[(0,I.jsx)(`h1`,{className:`max-w-2xl text-[30px] font-semibold leading-tight tracking-[-0.05em] text-[#2f2212] sm:text-[38px]`,children:o(`agentsHeroTitle`)}),(0,I.jsx)(`p`,{className:`max-w-2xl text-sm leading-6 text-[#6d5841] sm:text-[15px] sm:leading-7`,children:o(`agentsHeroDescription`)})]}),(0,I.jsx)(`div`,{className:`pt-1`,children:(0,I.jsxs)(`div`,{className:`inline-flex items-center gap-3 rounded-2xl border border-[#f2d5a4] bg-white/82 px-3 py-2 text-[#7a4d12] shadow-[0_14px_30px_rgba(167,117,47,0.07)]`,children:[(0,I.jsx)(`span`,{className:`text-[11px] font-semibold tracking-[0.14em]`,children:o(`agentsOverviewTotal`)}),(0,I.jsx)(`span`,{className:`text-xl font-semibold tracking-[-0.04em] text-[#1f2937]`,children:d.length})]})})]}),(0,I.jsxs)(`div`,{className:`flex shrink-0 flex-col gap-3`,children:[(0,I.jsxs)(m,{type:`button`,className:`h-10 rounded-2xl bg-[#1f5c4d] px-5 text-sm font-semibold text-white hover:bg-[#184d40]`,onClick:()=>a(!0),children:[(0,I.jsx)(Pe,{className:`mr-2 h-4 w-4`}),o(`agentsCreateButton`)]}),(0,I.jsx)(`div`,{className:`rounded-2xl border border-white/70 bg-white/72 px-4 py-3 text-xs leading-6 text-[#6d5841] shadow-[0_18px_40px_rgba(167,117,47,0.08)]`,children:o(`agentsCreateDialogHint`)})]})]})]}),(0,I.jsx)(`div`,{className:`grid gap-4 md:grid-cols-2 xl:grid-cols-3`,children:t.isLoading?(0,I.jsx)($e,{className:`md:col-span-2 xl:col-span-3 border-dashed border-[#d9dce3] bg-white/70`,children:(0,I.jsx)(tt,{className:`py-14 text-center text-sm text-gray-500`,children:o(`agentsLoading`)})}):f.length===0?(0,I.jsx)($e,{className:`md:col-span-2 xl:col-span-3 overflow-hidden border-dashed border-[#d9dce3] bg-[linear-gradient(135deg,#fff7ea_0%,#f4fbff_100%)]`,children:(0,I.jsxs)(tt,{className:`flex min-h-[240px] flex-col items-center justify-center px-6 py-14 text-center`,children:[(0,I.jsx)(`div`,{className:`mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-white/80 shadow-[0_18px_44px_rgba(0,0,0,0.08)]`,children:(0,I.jsx)(vt,{className:`h-8 w-8 text-[#d39a3b]`})}),(0,I.jsx)(`div`,{className:`text-lg font-semibold text-[#2f2212]`,children:o(`agentsEmpty`)}),(0,I.jsx)(`p`,{className:`mt-2 max-w-md text-sm leading-6 text-[#78644d]`,children:o(`agentsEmptyDescription`)}),(0,I.jsxs)(m,{type:`button`,className:`mt-5 rounded-2xl bg-[#1f5c4d] px-5 text-white hover:bg-[#184d40]`,onClick:()=>a(!0),children:[(0,I.jsx)(Pe,{className:`mr-2 h-4 w-4`}),o(`agentsCreateButton`)]})]})}):f.map((e,t)=>{let n=lb(t,!!e.builtIn);return(0,I.jsxs)($e,{className:`overflow-hidden border border-gray-200 bg-white shadow-sm transition-shadow duration-200 hover:shadow-md`,children:[(0,I.jsx)(`div`,{className:u(`h-1.5 w-full`,n.strip)}),(0,I.jsxs)(tt,{className:`flex h-full flex-col gap-4 px-4 py-4`,children:[(0,I.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,I.jsx)(ir,{agentId:e.id,displayName:e.displayName,avatarUrl:e.avatarUrl,className:`h-11 w-11 shrink-0`}),(0,I.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1 pt-0.5`,children:[(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,I.jsx)(`div`,{className:`truncate text-lg font-semibold tracking-[-0.03em] text-[#1f2937]`,children:e.displayName?.trim()||e.id}),e.builtIn?(0,I.jsxs)(`span`,{className:u(`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-medium`,n.chip),children:[(0,I.jsx)(_n,{className:`h-3 w-3`}),o(`agentsCardBuiltInTag`)]}):null]}),(0,I.jsxs)(`div`,{className:`text-[11px] font-medium uppercase tracking-[0.18em] text-[#94a3b8]`,children:[`@`,e.id]})]})]}),(0,I.jsx)(`p`,{className:`text-sm leading-6 text-[#64748b]`,children:e.description?.trim()||(e.builtIn?o(`agentsCardBuiltInSummary`):o(`agentsCardCustomSummary`))}),(0,I.jsxs)(`div`,{className:`mt-auto flex flex-col gap-4`,children:[(0,I.jsxs)(`div`,{className:`border-t border-gray-100 pt-3`,children:[(0,I.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-[#94a3b8]`,children:[(0,I.jsx)(ln,{className:`h-3.5 w-3.5`}),o(`agentsCardHomeLabel`)]}),(0,I.jsx)(`div`,{className:`mt-1.5 break-all text-sm leading-6 text-[#475569]`,children:e.workspace??`-`})]}),(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,I.jsxs)(m,{type:`button`,className:`h-9 rounded-xl bg-[#1f5c4d] px-4 text-white hover:bg-[#184d40]`,onClick:()=>h(e.id),children:[(0,I.jsx)(_t,{className:`mr-2 h-4 w-4`}),o(`agentsCardStartChat`)]}),e.builtIn?null:(0,I.jsxs)(m,{type:`button`,variant:`ghost`,className:`h-8 rounded-xl px-3 text-xs text-[#7b8794] hover:bg-[#f3f4f6] hover:text-[#475569]`,onClick:()=>r.mutate({agentId:e.id}),disabled:r.isPending,children:[(0,I.jsx)(Je,{className:`mr-1.5 h-3.5 w-3.5`}),o(`agentsRemoveAction`)]})]})]})]})]},e.id)})}),(0,I.jsx)(ht,{open:i,onOpenChange:e=>{a(e),!e&&!n.isPending&&c(sb)},children:(0,I.jsxs)(Pt,{className:`overflow-hidden border-none bg-[linear-gradient(180deg,#fff9f1_0%,#ffffff_24%)] p-0 sm:max-w-xl`,children:[(0,I.jsx)(`div`,{className:`border-b border-[#f0e2c8] px-6 py-6`,children:(0,I.jsxs)(xt,{className:`text-left`,children:[(0,I.jsx)(dt,{children:o(`agentsCreateDialogTitle`)}),(0,I.jsx)(Tt,{children:o(`agentsCreateDialogDescription`)})]})}),(0,I.jsxs)(`div`,{className:`space-y-4 px-6 py-6`,children:[(0,I.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,I.jsx)(ct,{value:s.id,onChange:e=>c(t=>({...t,id:e.target.value})),placeholder:o(`agentsFormIdPlaceholder`)}),(0,I.jsx)(ct,{value:s.displayName,onChange:e=>c(t=>({...t,displayName:e.target.value})),placeholder:o(`agentsFormNamePlaceholder`)}),(0,I.jsx)(ct,{value:s.description,onChange:e=>c(t=>({...t,description:e.target.value})),placeholder:o(`agentsFormDescriptionPlaceholder`)}),(0,I.jsx)(ct,{value:s.avatar,onChange:e=>c(t=>({...t,avatar:e.target.value})),placeholder:o(`agentsFormAvatarPlaceholder`)}),(0,I.jsx)(ct,{value:s.home,onChange:e=>c(t=>({...t,home:e.target.value})),placeholder:o(`agentsFormHomePlaceholder`)})]}),(0,I.jsx)(`div`,{className:`rounded-2xl border border-[#efe3ca] bg-[#fff9ef] px-4 py-3 text-xs leading-6 text-[#7a6246]`,children:o(`agentsCreateDialogHint`)})]}),(0,I.jsxs)(jt,{className:`border-t border-[#f1e7d4] px-6 py-5`,children:[(0,I.jsx)(m,{type:`button`,variant:`ghost`,onClick:()=>a(!1),disabled:n.isPending,children:o(`cancel`)}),(0,I.jsxs)(m,{type:`button`,className:`rounded-2xl bg-[#1f5c4d] px-5 text-white hover:bg-[#184d40]`,onClick:()=>void p(),disabled:n.isPending||s.id.trim().length===0,children:[(0,I.jsx)(Pe,{className:`mr-2 h-4 w-4`}),o(`agentsCreateAction`)]})]})]})})]})}function db(e){return c(e??void 0)}function fb(e){return typeof e!=`number`||!Number.isFinite(e)?`-`:c(new Date(e))}function pb(e){if(typeof e!=`number`||!Number.isFinite(e))return`-`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.round(t/60);if(n<60)return`${n}m`;let r=Math.round(n/60);return r<24?`${r}h`:`${Math.round(r/24)}d`}function mb(e){let t=e.schedule;return t.kind===`cron`?t.expr?`cron ${t.expr}`:`cron`:t.kind===`every`?`every ${pb(t.everyMs)}`:t.kind===`at`?`at ${fb(t.atMs)}`:`-`}function hb(e){return e.payload.deliver?`${e.payload.channel??`-`}:${e.payload.to??`-`}`:`-`}function gb(e,t){let 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 _b(e,t){return t===`all`?!0:t===`enabled`?e.enabled:!e.enabled}function vb(){let[e,t]=(0,P.useState)(``),[n,r]=(0,P.useState)(`all`),i=gt({all:!0}),a=Ot(),s=st(),c=ot(),{confirm:l,ConfirmDialog:d}=Yt(),f=(0,P.useMemo)(()=>(i.data?.jobs??[]).filter(t=>gb(t,e)).filter(e=>_b(e,n)),[i.data,e,n]),p=async e=>{await l({title:`${o(`cronDeleteConfirm`)}?`,description:e.name?`${e.name} (${e.id})`:e.id,variant:`destructive`,confirmLabel:o(`delete`)})&&a.mutate({id:e.id})},h=async e=>{let t=!e.enabled;await l({title:t?`${o(`cronEnableConfirm`)}?`:`${o(`cronDisableConfirm`)}?`,description:e.name?`${e.name} (${e.id})`:e.id,variant:t?`default`:`destructive`,confirmLabel:o(t?`cronEnable`:`cronDisable`)})&&s.mutate({id:e.id,enabled:t})},g=async e=>{let t=!e.enabled;await l({title:t?`${o(`cronRunForceConfirm`)}?`:`${o(`cronRunConfirm`)}?`,description:e.name?`${e.name} (${e.id})`:e.id,confirmLabel:o(`cronRunNow`)})&&c.mutate({id:e.id,force:t})};return(0,I.jsxs)(qt,{fullHeight:!0,children:[(0,I.jsx)(Jt,{title:o(`cronPageTitle`),description:o(`cronPageDescription`),actions:(0,I.jsx)(m,{variant:`ghost`,size:`icon`,className:`h-9 w-9 rounded-lg text-gray-400 hover:text-gray-700 hover:bg-gray-100`,onClick:()=>i.refetch(),children:(0,I.jsx)(Re,{className:u(`h-4 w-4`,i.isFetching&&`animate-spin`)})})}),(0,I.jsx)(`div`,{className:`mb-6`,children:(0,I.jsxs)(`div`,{className:`flex flex-wrap gap-3 items-center`,children:[(0,I.jsxs)(`div`,{className:`relative flex-1 min-w-[240px]`,children:[(0,I.jsx)(ct,{value:e,onChange:e=>t(e.target.value),placeholder:o(`cronSearchPlaceholder`),className:`pl-9`}),(0,I.jsx)(lt,{className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400`})]}),(0,I.jsx)(`div`,{className:`min-w-[180px]`,children:(0,I.jsxs)(ue,{value:n,onValueChange:e=>r(e),children:[(0,I.jsx)(ne,{className:`w-full`,children:(0,I.jsx)(D,{placeholder:o(`cronStatusLabel`)})}),(0,I.jsxs)(ae,{children:[(0,I.jsx)(ce,{value:`all`,children:o(`cronStatusAll`)}),(0,I.jsx)(ce,{value:`enabled`,children:o(`cronStatusEnabled`)}),(0,I.jsx)(ce,{value:`disabled`,children:o(`cronStatusDisabled`)})]})]})}),(0,I.jsxs)(`div`,{className:`text-xs text-gray-500 ml-auto`,children:[o(`cronTotalLabel`),`: `,i.data?.total??0,` / `,f.length]})]})}),(0,I.jsx)(`div`,{className:`flex-1 overflow-auto custom-scrollbar`,children:i.isLoading?(0,I.jsx)(`div`,{className:`text-sm text-gray-400 p-4 text-center`,children:o(`cronLoading`)}):f.length===0?(0,I.jsx)(`div`,{className:`text-sm text-gray-400 p-4 text-center`,children:o(`cronEmpty`)}):(0,I.jsx)(`div`,{className:`space-y-4`,children:f.map(e=>(0,I.jsx)($e,{className:`border border-gray-200`,children:(0,I.jsx)(tt,{className:`pt-5 pb-5`,children:(0,I.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-4`,children:[(0,I.jsxs)(`div`,{className:`min-w-[220px] flex-1`,children:[(0,I.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,I.jsx)(`span`,{className:`text-sm font-semibold text-gray-900`,children:e.name||e.id}),(0,I.jsx)(`span`,{className:`text-[10px] font-semibold px-2 py-0.5 rounded-full bg-gray-100 text-gray-500`,children:e.id}),(0,I.jsx)(`span`,{className:u(`text-[10px] font-semibold px-2 py-0.5 rounded-full`,e.enabled?`bg-emerald-50 text-emerald-700`:`bg-gray-100 text-gray-500`),children:e.enabled?o(`enabled`):o(`disabled`)}),e.deleteAfterRun&&(0,I.jsx)(`span`,{className:`text-[10px] font-semibold px-2 py-0.5 rounded-full bg-amber-50 text-amber-700`,children:o(`cronOneShot`)})]}),(0,I.jsxs)(`div`,{className:`mt-2 text-xs text-gray-500`,children:[o(`cronScheduleLabel`),`: `,mb(e)]}),(0,I.jsx)(`div`,{className:`mt-2 text-sm text-gray-700 whitespace-pre-wrap break-words`,children:e.payload.message}),(0,I.jsxs)(`div`,{className:`mt-2 text-xs text-gray-500`,children:[o(`cronDeliverTo`),`: `,hb(e)]})]}),(0,I.jsxs)(`div`,{className:`min-w-[220px] text-xs text-gray-500 space-y-2`,children:[(0,I.jsxs)(`div`,{children:[(0,I.jsxs)(`span`,{className:`font-medium text-gray-700`,children:[o(`cronNextRun`),`:`]}),` `,db(e.state.nextRunAt)]}),(0,I.jsxs)(`div`,{children:[(0,I.jsxs)(`span`,{className:`font-medium text-gray-700`,children:[o(`cronLastRun`),`:`]}),` `,db(e.state.lastRunAt)]}),(0,I.jsxs)(`div`,{children:[(0,I.jsxs)(`span`,{className:`font-medium text-gray-700`,children:[o(`cronLastStatus`),`:`]}),` `,e.state.lastStatus??`-`]}),e.state.lastError&&(0,I.jsx)(`div`,{className:`text-[11px] text-red-500 break-words`,children:e.state.lastError})]}),(0,I.jsxs)(`div`,{className:`flex items-start gap-2 flex-wrap justify-end`,children:[(0,I.jsxs)(m,{variant:`subtle`,size:`sm`,onClick:()=>g(e),className:`gap-1`,children:[(0,I.jsx)(mn,{className:`h-3.5 w-3.5`}),o(`cronRunNow`)]}),(0,I.jsxs)(m,{variant:e.enabled?`outline`:`primary`,size:`sm`,onClick:()=>h(e),className:`gap-1`,children:[(0,I.jsx)(hn,{className:`h-3.5 w-3.5`}),e.enabled?o(`cronDisable`):o(`cronEnable`)]}),(0,I.jsxs)(m,{variant:`destructive`,size:`sm`,onClick:()=>p(e),className:`gap-1`,children:[(0,I.jsx)(Je,{className:`h-3.5 w-3.5`}),o(`delete`)]})]})]})})},e.id))})}),(0,I.jsx)(d,{})]})}function yb(e){let{view:t,routeSessionKey:n,selectedSessionKey:r,setSelectedSessionKey:i,selectedSessionKeyRef:a,resetStreamState:o}=e;(0,P.useEffect)(()=>{if(t===`chat`){if(n){r!==n&&i(n);return}r!==null&&(i(null),o())}},[o,n,r,i,t]),(0,P.useEffect)(()=>{a.current=r},[r,a])}function bb({view:e,confirmDialog:t}){return(0,I.jsxs)(`div`,{className:`h-full flex`,children:[(0,I.jsx)(Rg,{}),e===`chat`?(0,I.jsx)(ob,{}):(0,I.jsx)(`section`,{className:`flex-1 min-h-0 overflow-hidden bg-gradient-to-b from-gray-50/60 to-white`,children:e===`cron`?(0,I.jsx)(`div`,{className:`h-full overflow-auto custom-scrollbar`,children:(0,I.jsx)(`div`,{className:`mx-auto w-full max-w-[min(1120px,100%)] px-6 py-5`,children:(0,I.jsx)(vb,{})})}):e===`agents`?(0,I.jsx)(`div`,{className:`h-full overflow-auto custom-scrollbar`,children:(0,I.jsx)(`div`,{className:`mx-auto w-full max-w-[min(1180px,100%)] px-6 py-5`,children:(0,I.jsx)(ub,{})})}):(0,I.jsx)(`div`,{className:`h-full overflow-hidden`,children:(0,I.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:(0,I.jsx)(Me,{forcedType:`skills`})})})}),t]})}var xb=`sid_`;function Sb(e){let t=new TextEncoder().encode(e),n=``;for(let e of t)n+=String.fromCharCode(e);return`${xb}${btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}`}function Cb(e){if(!e.startsWith(xb))return null;let t=e.slice(4).replace(/-/g,`+`).replace(/_/g,`/`),n=t.length%4==0?``:`=`.repeat(4-t.length%4);try{let e=atob(t+n),r=Uint8Array.from(e,e=>e.charCodeAt(0));return new TextDecoder().decode(r)}catch{return null}}function wb(e){if(!e)return null;let t=Cb(e);if(t)return t;try{return decodeURIComponent(e)}catch{return e}}function Tb(e){return`/chat/${Sb(e)}`}var Eb=`native`;function Db(e){return typeof e==`string`?e.trim().toLowerCase()||`native`:Eb}function Ob(e,t){return e===`native`?o(`chatSessionTypeNative`):t?.trim()||e.trim().split(/[-_]+/g).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)||e}function kb(e){let t=new Map;for(let n of e){let e=Db(n.value);t.set(e,{value:e,label:n.label?.trim()||Ob(e),ready:n.ready??!0,reason:n.reason??null,reasonMessage:n.reasonMessage??null,supportedModels:n.supportedModels,recommendedModel:n.recommendedModel??null,cta:n.cta??null})}return t.has(`native`)||t.set(Eb,{value:Eb,label:Ob(Eb),ready:!0,reason:null,reasonMessage:null,supportedModels:void 0,recommendedModel:null,cta:null}),Array.from(t.values()).sort((e,t)=>e.value===`native`?-1:t.value===`native`?1:e.value.localeCompare(t.value))}function Ab(e){let{selectedSession:t,selectedSessionKey:n,pendingSessionType:r,setPendingSessionType:i,sessionTypesData:a}=e,s=(0,P.useMemo)(()=>kb(a?.options??[]),[a?.options]),c=(0,P.useMemo)(()=>{let e=[...s],n=Db(t?.sessionType);return e.some(e=>e.value===n)||e.push({value:n,label:Ob(n),ready:!0,reason:null,reasonMessage:null,supportedModels:void 0,recommendedModel:null,cta:null}),e.sort((e,t)=>e.value===`native`?-1:t.value===`native`?1:e.value.localeCompare(t.value))},[s,t?.sessionType]),l=(0,P.useMemo)(()=>Db(a?.defaultType??`native`),[a?.defaultType]),u=(0,P.useRef)(null),d=(0,P.useMemo)(()=>Db(t?.sessionType??r??l),[l,r,t?.sessionType]),f=(0,P.useMemo)(()=>c.find(e=>e.value===d)??null,[d,c]);(0,P.useEffect)(()=>{if(n)return;let e=typeof r==`string`?r.trim():``,t=Db(r);(e.length===0||u.current===t||u.current===null&&t===`native`)&&(u.current=l,t!==l&&i(l))},[l,r,n,i]);let p=!n||!!t?.sessionTypeMutable,m=(0,P.useMemo)(()=>new Set(s.map(e=>e.value)),[s]);return{sessionTypeOptions:c,selectedSessionTypeOption:f,defaultSessionType:l,selectedSessionType:d,canEditSessionType:p,sessionTypeUnavailable:(0,P.useMemo)(()=>t&&!m.has(Db(t.sessionType))?!0:f?.ready===!1,[m,t,f?.ready]),sessionTypeUnavailableMessage:(0,P.useMemo)(()=>t&&!m.has(Db(t.sessionType))?`${Ob(d)} ${o(`chatSessionTypeUnavailableSuffix`)}`:f?.ready===!1?f.reasonMessage?.trim()||`${f.label} setup required`:null,[m,t,d,f])}}function jb(e){return e?.trim().toLowerCase()||`native`}function Mb(e,t){if(typeof t!=`string`)return!1;let n=t.trim();return n?e.some(e=>e.value===n):!1}function Nb(e,t){return typeof t==`string`&&e.includes(t)}function Pb(e){return e.length===0?null:e.includes(`off`)?`off`:e[0]??null}function Fb(e){let{currentValue:t,selectedSessionPreferredValue:n,fallbackPreferredValue:r,defaultValue:i,isValueSupported:a,firstAvailableValue:o,preferSessionPreferredValue:s=!1,preserveCurrentValueOnSessionChange:c=!1}=e;return a(t)&&(!s||c)?t:a(n)?n:a(r)?r:a(i)?i:o}function Ib(e){let{modelOptions:t}=e;return t.length===0?``:Fb({currentValue:e.currentSelectedModel,selectedSessionPreferredValue:e.selectedSessionPreferredModel,fallbackPreferredValue:e.fallbackPreferredModel,defaultValue:e.defaultModel,isValueSupported:e=>Mb(t,e),firstAvailableValue:t[0]?.value??``,preferSessionPreferredValue:e.preferSessionPreferredModel,preserveCurrentValueOnSessionChange:e.preserveCurrentSelectedModelOnSessionChange})}function Lb(e){let{supportedThinkingLevels:t}=e;return t.length===0?null:Fb({currentValue:e.currentSelectedThinkingLevel,selectedSessionPreferredValue:e.selectedSessionPreferredThinking,fallbackPreferredValue:e.fallbackPreferredThinking,defaultValue:e.defaultThinkingLevel,isValueSupported:e=>Nb(t,e),firstAvailableValue:Pb(t)??`off`,preferSessionPreferredValue:e.preferSessionPreferredThinking,preserveCurrentValueOnSessionChange:e.preserveCurrentSelectedThinkingOnSessionChange})}function Rb(e){let t=jb(e.sessionType),n,r=-1/0;for(let i of e.sessions){if(i.key===e.selectedSessionKey||jb(i.sessionType)!==t)continue;let a=e.readPreference(i);if(a==null)continue;let o=Date.parse(i.updatedAt),s=Number.isFinite(o)?o:-1/0;(n===void 0||s>r)&&(n=a,r=s)}return n}function zb(e){return Rb({sessions:e.sessions,selectedSessionKey:e.selectedSessionKey,sessionType:e.sessionType,readPreference:e=>e.preferredModel?.trim()||void 0})}function Bb(e){return Rb({sessions:e.sessions,selectedSessionKey:e.selectedSessionKey,sessionType:e.sessionType,readPreference:e=>e.preferredThinking??void 0})}function Vb(e){let{isPreferenceAvailable:t,emptyValue:n,selectedSessionKey:r,selectedSessionExists:i=!1,setValue:a,resolveValue:o}=e,s=(0,P.useRef)(void 0),c=(0,P.useRef)(o);(0,P.useEffect)(()=>{c.current=o},[o]),(0,P.useEffect)(()=>{let e=s.current!==r;if(!t){a(n),s.current=r;return}a(t=>c.current({currentValue:t,sessionChanged:e,preserveCurrentValueOnSessionChange:e&&!!r&&!i})),s.current=r},[n,t,i,r,a])}function Hb(e){let{modelOptions:t,selectedSessionKey:n,selectedSessionExists:r=!1,selectedSessionPreferredModel:i,fallbackPreferredModel:a,defaultModel:o,setSelectedModel:s}=e;Vb({isPreferenceAvailable:t.length>0,emptyValue:``,selectedSessionKey:n,selectedSessionExists:r,setValue:s,resolveValue:({currentValue:e,sessionChanged:n,preserveCurrentValueOnSessionChange:r})=>Ib({currentSelectedModel:e,modelOptions:t,selectedSessionPreferredModel:i,fallbackPreferredModel:a,defaultModel:o,preferSessionPreferredModel:n,preserveCurrentSelectedModelOnSessionChange:r})})}function Ub(e){let{supportedThinkingLevels:t,selectedSessionKey:n,selectedSessionExists:r=!1,selectedSessionPreferredThinking:i,fallbackPreferredThinking:a,defaultThinkingLevel:o,setSelectedThinkingLevel:s}=e;Vb({isPreferenceAvailable:t.length>0,emptyValue:null,selectedSessionKey:n,selectedSessionExists:r,setValue:s,resolveValue:({currentValue:e,sessionChanged:n,preserveCurrentValueOnSessionChange:r})=>Lb({currentSelectedThinkingLevel:e,supportedThinkingLevels:t,selectedSessionPreferredThinking:i,fallbackPreferredThinking:a,defaultThinkingLevel:o,preferSessionPreferredThinking:n,preserveCurrentSelectedThinkingOnSessionChange:r})})}function Wb(){return f({queryKey:[`ncp-session-types`],queryFn:Xe,staleTime:1e4,retry:!1})}function Gb(e,t){return e.filter(e=>Ve(e,t))}function Kb(e){if(!e.supportedModels||e.supportedModels.length===0)return e.modelOptions;let t=new Set(e.supportedModels),n=e.modelOptions.filter(e=>t.has(e.value));return n.length>0?n:e.modelOptions}function qb(e){let t=pt(),n=St(),r=ft({limit:200}),i=Wb(),a=It({sessionId:e.sessionKey,...Object.prototype.hasOwnProperty.call(e,`projectRootOverride`)?{projectRoot:e.projectRootOverride??null}:{}}),o=(t.isFetched||t.isSuccess)&&(n.isFetched||n.isSuccess),s=(0,P.useMemo)(()=>{let e=be({meta:n.data,config:t.data,onlyConfigured:!0}),r=new Set,i=[];for(let t of e)for(let e of t.models){let n=ve(t.prefix,e);!n||r.has(n)||(r.add(n),i.push({value:n,modelLabel:e,providerLabel:t.displayName,thinkingCapability:_e(t.modelThinking,e,t.aliases)}))}return i.sort((e,t)=>{let n=e.providerLabel.localeCompare(t.providerLabel);return n===0?e.modelLabel.localeCompare(t.modelLabel):n})},[n.data,t.data]),c=(0,P.useMemo)(()=>r.data?.sessions??[],[r.data?.sessions]),l=(0,P.useMemo)(()=>ze(c),[c]),u=(0,P.useMemo)(()=>Gb(l,e.query),[l,e.query]),d=(0,P.useMemo)(()=>l.find(t=>t.key===e.sessionKey)??null,[l,e.sessionKey]),f=(0,P.useMemo)(()=>a.data?.records??[],[a.data?.records]),p=Ab({selectedSession:d,selectedSessionKey:e.sessionKey,pendingSessionType:e.pendingSessionType,setPendingSessionType:e.setPendingSessionType,sessionTypesData:i.data}),m=(0,P.useMemo)(()=>Kb({modelOptions:s,supportedModels:p.selectedSessionTypeOption?.supportedModels}),[s,p.selectedSessionTypeOption?.supportedModels]),h=(0,P.useMemo)(()=>zb({sessions:l,selectedSessionKey:e.sessionKey,sessionType:p.selectedSessionType}),[l,e.sessionKey,p.selectedSessionType]),g=(0,P.useMemo)(()=>m.find(t=>t.value===e.currentSelectedModel),[m,e.currentSelectedModel]),_=(0,P.useMemo)(()=>g?.thinkingCapability?.supported??[],[g?.thinkingCapability?.supported]),v=(0,P.useMemo)(()=>g?.thinkingCapability?.default??null,[g?.thinkingCapability?.default]),y=(0,P.useMemo)(()=>Bb({sessions:l,selectedSessionKey:e.sessionKey,sessionType:p.selectedSessionType}),[l,e.sessionKey,p.selectedSessionType]);return Hb({modelOptions:m,selectedSessionKey:e.sessionKey,selectedSessionExists:!!d,selectedSessionPreferredModel:d?.preferredModel,fallbackPreferredModel:p.selectedSessionTypeOption?.recommendedModel??h,defaultModel:p.selectedSessionTypeOption?.recommendedModel??t.data?.agents.defaults.model,setSelectedModel:e.setSelectedModel}),Ub({supportedThinkingLevels:_,selectedSessionKey:e.sessionKey,selectedSessionExists:!!d,selectedSessionPreferredThinking:d?.preferredThinking??null,fallbackPreferredThinking:y??null,defaultThinkingLevel:v,setSelectedThinkingLevel:e.setSelectedThinkingLevel}),{configQuery:t,configMetaQuery:n,sessionsQuery:r,sessionTypesQuery:i,sessionSkillsQuery:a,isProviderStateResolved:o,modelOptions:m,sessionSummaries:c,sessions:u,skillRecords:f,selectedSession:d,...p}}var Jb=class{constructor(e,t){this.uiManager=e,this.streamActionsManager=t,this.resolveUpdateValue=(e,t)=>typeof t==`function`?t(e):t,this.setSelectedAgentId=e=>{let t=L.getState().snapshot.selectedAgentId,n=this.resolveUpdateValue(t,e);n!==t&&L.getState().setSnapshot({selectedAgentId:n})},this.setSelectedSessionKey=e=>{let t=L.getState().snapshot.selectedSessionKey,n=this.resolveUpdateValue(t,e);n!==t&&L.getState().setSnapshot({selectedSessionKey:n})},this.createSession=e=>{let{snapshot:t}=Q.getState(),{defaultSessionType:n}=t,r=n||`native`,i=typeof e==`string`&&e.trim().length>0?e.trim():r;this.streamActionsManager.resetStreamState(),Q.getState().setSnapshot({pendingSessionType:i,pendingProjectRoot:null,pendingProjectRootSessionKey:null}),this.uiManager.goToChatRoot()},this.selectSession=e=>{this.uiManager.goToSession(e)},this.setQuery=e=>{let t=L.getState().snapshot.query,n=this.resolveUpdateValue(t,e);n!==t&&L.getState().setSnapshot({query:n})}}},Yb=async()=>{},Xb=()=>{},Zb=class{constructor(){this.actions={sendMessage:Yb,stopCurrentRun:Yb,resumeRun:Yb,resetStreamState:Xb,applyHistoryMessages:Xb},this.bind=e=>{this.actions={...this.actions,...e}},this.sendMessage=e=>this.actions.sendMessage(e),this.stopCurrentRun=()=>this.actions.stopCurrentRun(),this.resumeRun=e=>this.actions.resumeRun(e),this.resetStreamState=()=>this.actions.resetStreamState(),this.applyHistoryMessages=(e,t)=>this.actions.applyHistoryMessages(e,t)}},Qb=async e=>!1,$b=class{constructor(){this.state={pathname:``},this.actions={navigate:null,confirm:Qb},this.syncState=e=>{this.state={...this.state,...e}},this.bindActions=e=>{this.actions={...this.actions,...e}},this.confirm=async e=>this.actions.confirm(e),this.navigateTo=(e,t)=>{this.actions.navigate&&(this.state.pathname===e&&!t?.replace||(this.actions.navigate(e,t),this.state.pathname=e))},this.goToProviders=()=>{this.navigateTo(`/providers`)},this.goToChatRoot=e=>{this.navigateTo(`/chat`,e)},this.goToSession=(e,t)=>{this.navigateTo(Tb(e),t)}}};function ex(e){let t=e.trim();return t.length>0?t:null}function tx(e){return e??null}var nx=class{constructor(e){this.updateSession=e,this.inFlight=null,this.queued=null,this.syncSelectedSessionPreferences=()=>{let e=Q.getState().snapshot,t=L.getState().snapshot.selectedSessionKey;t&&this.enqueue({sessionKey:t,patch:{preferredModel:ex(e.selectedModel),preferredThinking:tx(e.selectedThinkingLevel)}})}}enqueue(e){this.queued=e,!this.inFlight&&this.startFlush()}startFlush(){this.inFlight=this.flush().catch(e=>{console.error(`Failed to sync chat session preferences: ${String(e)}`)}).finally(()=>{this.inFlight=null,this.queued&&this.startFlush()})}async flush(){for(;this.queued;){let e=this.queued;this.queued=null,await this.updateSession(e.sessionKey,e.patch)}}},rx=class{constructor(e,t,n){this.uiManager=e,this.streamActionsManager=t,this.getDraftSessionId=n,this.sessionPreferenceSync=new nx(Qe),this.buildAttachmentSignature=e=>[e.assetUri??``,e.url??``,e.name,e.mimeType,String(e.sizeBytes),e.contentBase64??``].join(`:`),this.hasSnapshotChanges=e=>{let t=Q.getState().snapshot;for(let[n,r]of Object.entries(e))if(!Object.is(t[n],r))return!0;return!1},this.resolveUpdateValue=(e,t)=>typeof t==`function`?t(e):t,this.isSameStringArray=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),this.syncComposerSnapshot=e=>{let t=Q.getState().snapshot.attachments,n=Tg(e,t);Q.getState().setSnapshot({composerNodes:e,attachments:n,draft:bg(e),selectedSkills:xg(e)})},this.syncComposerSnapshotWithAttachments=(e,t)=>{Q.getState().setSnapshot({composerNodes:e,attachments:t,draft:bg(e),selectedSkills:xg(e)})},this.dedupeAttachments=e=>{let t=new Set,n=[];for(let r of e){let e=this.buildAttachmentSignature(r);t.has(e)||(t.add(e),n.push(r))}return n},this.syncSnapshot=e=>{if(this.hasSnapshotChanges(e)&&(Q.getState().setSnapshot(e),Object.prototype.hasOwnProperty.call(e,`modelOptions`)||Object.prototype.hasOwnProperty.call(e,`selectedModel`)||Object.prototype.hasOwnProperty.call(e,`selectedThinkingLevel`))){let{selectedModel:e}=Q.getState().snapshot;this.reconcileThinkingForModel(e)}},this.setDraft=e=>{let t=Q.getState().snapshot.draft,n=this.resolveUpdateValue(t,e);n!==t&&this.syncComposerSnapshot(yg(n))},this.setComposerNodes=e=>{let t=Q.getState().snapshot.composerNodes,n=this.resolveUpdateValue(t,e);Object.is(n,t)||this.syncComposerSnapshot(n)},this.addAttachments=e=>{if(e.length===0)return[];let t=Q.getState().snapshot,n=new Set(t.attachments.map(this.buildAttachmentSignature)),r=this.dedupeAttachments([...t.attachments,...e]),i=r.filter(e=>!n.has(this.buildAttachmentSignature(e)));if(i.length===0)return[];let a=wg(t.composerNodes,r);return this.syncComposerSnapshotWithAttachments(a,r),i},this.restoreComposerState=(e,t)=>{let n=this.dedupeAttachments(t),r=wg(e,n);this.syncComposerSnapshotWithAttachments(r,n)},this.setPendingSessionType=e=>{let t=Q.getState().snapshot.pendingSessionType,n=this.resolveUpdateValue(t,e);n!==t&&Q.getState().setSnapshot({pendingSessionType:n})},this.send=async()=>{let e=Q.getState().snapshot,t=L.getState().snapshot,n=e.draft.trim(),r=e.attachments,i=Eg(e.composerNodes,r);if(!i.some(e=>e.type!==`text`||e.text.trim().length>0))return;let{selectedSkills:a,composerNodes:o}=e,s=t.selectedSessionKey??this.getDraftSessionId();t.selectedSessionKey||this.uiManager.goToSession(s,{replace:!0}),this.setComposerNodes(vg()),await this.streamActionsManager.sendMessage({message:n,sessionKey:s,agentId:t.selectedAgentId,sessionType:e.selectedSessionType,model:e.selectedModel||void 0,thinkingLevel:e.selectedThinkingLevel??void 0,stopSupported:!0,requestedSkills:a,attachments:r,parts:i,restoreDraftOnError:!0,composerNodes:o})},this.stop=async()=>{await this.streamActionsManager.stopCurrentRun()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.setSelectedModel=e=>{let t=Q.getState().snapshot.selectedModel,n=this.resolveUpdateValue(t,e);n!==t&&(Q.getState().setSnapshot({selectedModel:n}),this.reconcileThinkingForModel(n))},this.setSelectedThinkingLevel=e=>{let t=Q.getState().snapshot.selectedThinkingLevel,n=this.resolveUpdateValue(t,e);n!==t&&Q.getState().setSnapshot({selectedThinkingLevel:n})},this.selectSessionType=e=>{let t=Db(e);Q.getState().setSnapshot({selectedSessionType:t,pendingSessionType:t})},this.setSelectedSkills=e=>{let t=Q.getState().snapshot,{selectedSkills:n}=t,r=this.resolveUpdateValue(n,e);this.isSameStringArray(r,n)||this.syncComposerSnapshot(Cg(t.composerNodes,r,t.skillRecords))},this.selectModel=e=>{this.setSelectedModel(e),r_.remember(e),this.sessionPreferenceSync.syncSelectedSessionPreferences()},this.selectThinkingLevel=e=>{this.setSelectedThinkingLevel(e),this.sessionPreferenceSync.syncSelectedSessionPreferences()},this.rememberSkillSelection=e=>{i_.remember(e)},this.selectSkills=e=>{let t=Q.getState().snapshot.selectedSkills;for(let n of e)t.includes(n)||this.rememberSkillSelection(n);this.setSelectedSkills(e)},this.resolveThinkingForModel=(e,t)=>{let n=e?.thinkingCapability;return!n||n.supported.length===0?null:t===`off`?`off`:t&&n.supported.includes(t)?t:n.default&&n.supported.includes(n.default)?n.default:`off`},this.reconcileThinkingForModel=e=>{let t=Q.getState().snapshot,n=t.modelOptions.find(t=>t.value===e),{selectedThinkingLevel:r}=t,i=this.resolveThinkingForModel(n,r);i!==r&&Q.getState().setSnapshot({selectedThinkingLevel:i})}}},ix=class{constructor(e,t,n){this.uiManager=e,this.sessionListManager=t,this.streamActionsManager=n,this.hasSnapshotChanges=e=>{let t=ay.getState().snapshot;for(let[n,r]of Object.entries(e))if(!Object.is(t[n],r))return!0;return!1},this.syncSnapshot=e=>{this.hasSnapshotChanges(e)&&ay.getState().setSnapshot(e)},this.deleteSession=()=>{this.deleteCurrentSession()},this.createSession=()=>{this.sessionListManager.createSession()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.upsertChildSessionTab=e=>{let{snapshot:t}=ay.getState(),n=t.childSessionTabs.findIndex(t=>t.sessionKey===e.sessionKey),r=n>=0?t.childSessionTabs.map((t,r)=>r===n?{...t,...e}:t):[...t.childSessionTabs,e];ay.getState().setSnapshot({childSessionTabs:r,activeChildSessionKey:e.sessionKey})},this.openSessionFromToolAction=e=>{if(e.kind===`open-session`){if(e.sessionKind===`child`&&!this.isCompactViewport()){let t=e.parentSessionId?.trim()||L.getState().snapshot.selectedSessionKey||null;this.upsertChildSessionTab({sessionKey:e.sessionId,parentSessionKey:t,label:e.label?.trim()||null,agentId:e.agentId?.trim()||null});return}this.uiManager.goToSession(e.sessionId)}},this.selectChildSessionDetail=e=>{let t=e.trim();if(!t)return;let{childSessionTabs:n}=ay.getState().snapshot;n.some(e=>e.sessionKey===t)&&ay.getState().setSnapshot({activeChildSessionKey:t})},this.closeChildSessionDetail=()=>{let{sessionKey:e,childSessionTabs:t,activeChildSessionKey:n}=ay.getState().snapshot;if(!e){ay.getState().setSnapshot({childSessionTabs:[],activeChildSessionKey:null});return}let r=t.filter(t=>t.parentSessionKey!==e),i=r.some(e=>e.sessionKey===n)?n:null;ay.getState().setSnapshot({childSessionTabs:r,activeChildSessionKey:i})},this.goToParentSession=()=>{let{parentSessionKey:e,childSessionTabs:t,activeChildSessionKey:n}=ay.getState().snapshot,r=t.find(e=>e.sessionKey===n)?.parentSessionKey??null,i=e??r;i&&(this.closeChildSessionDetail(),this.uiManager.goToSession(i))},this.isCompactViewport=()=>typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(`(max-width: 767px)`).matches,this.deleteCurrentSession=async()=>{let{snapshot:{selectedSessionKey:e}}=L.getState();if(e&&await this.uiManager.confirm({title:o(`chatDeleteSessionConfirm`),variant:`destructive`,confirmLabel:o(`delete`)})){ay.getState().setSnapshot({isDeletePending:!0});try{await rt(e),et(x,e),x.removeQueries({queryKey:[`ncp-session-messages`,e]}),this.streamActionsManager.resetStreamState(),this.uiManager.goToChatRoot({replace:!0})}finally{ay.getState().setSnapshot({isDeletePending:!1})}}}}},ax=class{constructor(){this.chatUiManager=new $b,this.chatStreamActionsManager=new Zb,this.chatSessionListManager=new Jb(this.chatUiManager,this.chatStreamActionsManager),this.chatInputManager=new rx(this.chatUiManager,this.chatStreamActionsManager,()=>this.getDraftSessionId()),this.chatThreadManager=new ix(this.chatUiManager,this.chatSessionListManager,this.chatStreamActionsManager),this.draftSessionId=``,this.setDraftSessionId=e=>{this.draftSessionId=e}}getDraftSessionId(){return this.draftSessionId}};function ox(e){let t=e.selectedSession?Ge(e.selectedSession):void 0,n=e.selectedSession?.agentId??e.selectedAgentId;return{currentSessionDisplayName:t,currentAgentId:n,currentAgent:e.availableAgents.find(e=>e.id===n)??null,parentSession:(0,P.useMemo)(()=>{if(!e.parentSessionId)return null;let t=e.sessionSummaries.find(t=>t.sessionId===e.parentSessionId)??null;return t?Ie(t):null},[e.parentSessionId,e.sessionSummaries]),currentSessionTypeLabel:e.sessionTypeOptions.find(t=>t.value===e.selectedSessionType)?.label??Ob(e.selectedSessionType)}}function sx(e){(0,P.useEffect)(()=>{e.presenter.chatInputManager.syncSnapshot({isProviderStateResolved:e.isProviderStateResolved,defaultSessionType:e.defaultSessionType,canStopGeneration:e.canStopCurrentRun,stopDisabledReason:e.stopDisabledReason,stopSupported:!0,stopReason:void 0,sendError:e.lastSendError,isSending:e.isSending,modelOptions:e.modelOptions,sessionTypeOptions:e.sessionTypeOptions,selectedSessionType:e.selectedSessionType,canEditSessionType:e.canEditSessionType,sessionTypeUnavailable:e.sessionTypeUnavailable,skillRecords:e.skillRecords,isSkillsLoading:e.isSkillsLoading}),e.presenter.chatThreadManager.syncSnapshot({isProviderStateResolved:e.isProviderStateResolved,modelOptions:e.modelOptions,sessionTypeUnavailable:e.sessionTypeUnavailable,sessionTypeUnavailableMessage:e.sessionTypeUnavailableMessage,sessionTypeLabel:e.currentSessionTypeLabel,sessionKey:e.sessionKey,agentId:e.currentAgentId,agentDisplayName:e.currentAgent?.displayName??null,agentAvatarUrl:e.currentAgent?.avatarUrl??null,availableAgents:e.availableAgents,sessionDisplayName:e.currentSessionDisplayName,sessionProjectRoot:e.effectiveSessionProjectRoot,sessionProjectName:e.effectiveSessionProjectName,canDeleteSession:!!e.selectedSession,threadRef:e.threadRef,isHistoryLoading:e.agent.isHydrating,messages:e.agent.visibleMessages,isSending:e.isSending,isAwaitingAssistantOutput:e.isAwaitingAssistantOutput,parentSessionKey:e.parentSession?.key??null,parentSessionLabel:e.parentSession?Ge(e.parentSession):null})},[e])}function cx(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){let e=n.trim();e&&t.add(e)}return[...t]}function lx(e){let t={};e.model?.trim()&&(t.model=e.model.trim(),t.preferred_model=e.model.trim()),e.thinkingLevel?.trim()&&(t.thinking=e.thinkingLevel.trim(),t.preferred_thinking=e.thinkingLevel.trim()),e.sessionType?.trim()&&(t.session_type=e.sessionType.trim()),e.agentId?.trim()&&(t.agent_id=e.agentId.trim());let n=Le(e.projectRoot);n&&(t.project_root=n);let r=cx(e.requestedSkills);r.length>0&&(t.requested_skill_refs=r);let i=e.composerNodes?b_(e.composerNodes):[];return i.length>0&&(t[h_]=i),t}function ux({view:e}){let[t]=(0,P.useState)(()=>new ax),[n,r]=(0,P.useState)(()=>He()),i=L(e=>e.snapshot.query),a=L(e=>e.snapshot.selectedSessionKey),o=L(e=>e.snapshot.selectedAgentId),s=Q(e=>e.snapshot.pendingSessionType),c=Q(e=>e.snapshot.pendingProjectRoot),l=Q(e=>e.snapshot.pendingProjectRootSessionKey),u=jg(),d=Q(e=>e.snapshot.selectedModel),{confirm:f,ConfirmDialog:p}=Yt(),m=y(),h=b(),{sessionId:g}=v(),_=(0,P.useRef)(null),x=(0,P.useRef)(a),S=(0,P.useMemo)(()=>wb(g),[g]),C=a??n,w=l===C,{sessionSkillsQuery:T,isProviderStateResolved:E,modelOptions:D,sessionSummaries:O,skillRecords:ee,selectedSession:k,sessionTypeOptions:te,defaultSessionType:A,selectedSessionType:j,canEditSessionType:ne,sessionTypeUnavailable:re,sessionTypeUnavailableMessage:ie}=qb({query:i,sessionKey:C,projectRootOverride:w?c:void 0,currentSelectedModel:d,pendingSessionType:s,setPendingSessionType:t.chatInputManager.setPendingSessionType,setSelectedModel:t.chatInputManager.setSelectedModel,setSelectedThinkingLevel:t.chatInputManager.setSelectedThinkingLevel}),M=Vy(C);(0,P.useEffect)(()=>{t.setDraftSessionId(n)},[n,t]),(0,P.useEffect)(()=>{if(a===null){let e=He();r(e),t.setDraftSessionId(e)}},[t,a]);let ae=w?c:k?.projectRoot??null,oe=w?We(ae):k?.projectName??We(ae),se=k?.parentSessionId??null,ce=M.isSending||M.isRunning,le=M.isRunning,ue=M.isRunning,de=M.isRunning?null:`__preparing__`,fe=M.hydrateError?.message??M.snapshot.error?.message??null;(0,P.useEffect)(()=>{t.chatStreamActionsManager.bind({sendMessage:async e=>{if(e.sessionKey!==C)return;let n=lx({agentId:e.agentId,model:e.model,thinkingLevel:e.thinkingLevel,sessionType:e.sessionType,projectRoot:e.sessionKey===l?c:k?.projectRoot??null,requestedSkills:e.requestedSkills,composerNodes:e.composerNodes}),r=Zn({sessionId:e.sessionKey,text:e.message,attachments:e.attachments,parts:e.parts,metadata:n});if(r)try{await M.send(r)}catch(n){throw e.restoreDraftOnError&&(e.composerNodes&&e.composerNodes.length>0?t.chatInputManager.restoreComposerState?.(e.composerNodes,e.attachments??[]):t.chatInputManager.setDraft(t=>t.trim().length===0?e.message:t)),n}},stopCurrentRun:async()=>{await M.abort()},resumeRun:async e=>{e.sessionKey===C&&await M.streamRun()},resetStreamState:()=>{x.current=null},applyHistoryMessages:()=>{}})},[M,c,l,t,k?.projectRoot,C]),(0,P.useEffect)(()=>{!k||l!==k.key||(k.projectRoot??null)!==c||Q.getState().setSnapshot({pendingProjectRoot:null,pendingProjectRootSessionKey:null})},[c,l,k]),yb({view:e,routeSessionKey:S,selectedSessionKey:a,setSelectedSessionKey:t.chatSessionListManager.setSelectedSessionKey,selectedSessionKeyRef:x,resetStreamState:t.chatStreamActionsManager.resetStreamState}),(0,P.useEffect)(()=>{t.chatUiManager.syncState({pathname:m.pathname}),t.chatUiManager.bindActions({navigate:h,confirm:f})},[f,m.pathname,h,t]);let pe=(u.data?.agents?.length??0)>0?u.data?.agents??[]:[{id:k?.agentId??o}],{currentSessionDisplayName:N,currentAgentId:me,currentAgent:he,parentSession:ge,currentSessionTypeLabel:_e}=ox({selectedSession:k,selectedAgentId:o,availableAgents:pe,parentSessionId:se,sessionSummaries:O,selectedSessionType:j,sessionTypeOptions:te});return(0,P.useEffect)(()=>{!k?.agentId||o===k.agentId||t.chatSessionListManager.setSelectedAgentId(k.agentId)},[t,o,k?.agentId]),sx({presenter:t,isProviderStateResolved:E,defaultSessionType:A,canStopCurrentRun:ue,stopDisabledReason:de,lastSendError:fe,isSending:ce,modelOptions:D,sessionTypeOptions:te,selectedSessionType:j,canEditSessionType:ne,sessionTypeUnavailable:re,skillRecords:ee,isSkillsLoading:T.isLoading,sessionTypeUnavailableMessage:ie,currentSessionTypeLabel:_e,sessionKey:C,currentAgentId:me,currentAgent:he,availableAgents:pe,currentSessionDisplayName:N,effectiveSessionProjectRoot:ae,effectiveSessionProjectName:oe,selectedSession:k,threadRef:_,agent:M,isAwaitingAssistantOutput:le,parentSession:ge}),(0,I.jsx)(Cr,{presenter:t,children:(0,I.jsx)(bb,{view:e,confirmDialog:(0,I.jsx)(p,{})})})}function dx({view:e}){return(0,I.jsx)(ux,{view:e})}export{dx as ChatPage};